From f20e42948f1f2c81cd3c3ee43b5879a62c8636ad Mon Sep 17 00:00:00 2001 From: bc-alfreid Date: Thu, 14 May 2026 14:30:31 +1000 Subject: [PATCH 1/3] feat(payment): PAYMENTS-11577 Allow payment details to be passed for purchase order in createOrder endpoint --- dist/esm/checkout-sdk.js | 2 +- dist/esm/checkout-sdk.js.map | 2 +- dist/esm/extension.js | 2 +- dist/esm/extension.js.map | 2 +- dist/esm/integrations/offline.js | 2 +- dist/esm/integrations/offline.js.map | 2 +- .../src/offline-payment-strategy.ts | 12 +++++++++++- 7 files changed, 17 insertions(+), 7 deletions(-) diff --git a/dist/esm/checkout-sdk.js b/dist/esm/checkout-sdk.js index 5919b2cf8b..dcf3ea29cf 100644 --- a/dist/esm/checkout-sdk.js +++ b/dist/esm/checkout-sdk.js @@ -1,2 +1,2 @@ -import*as e from"iframe-resizer";import*as t from"iframe-resizer/js/iframeResizer.contentWindow";import{createRequestSender as n,createTimeout as i}from"@bigcommerce/request-sender";import{ScriptLoader as r,createScriptLoader as o,getScriptLoader as a,getStylesheetLoader as s}from"@bigcommerce/script-loader";import{combineReducers as d,composeReducers as c,createAction as l,createDataStore as u,createErrorAction as h,deepFreeze as p}from"@bigcommerce/data-store";import{Observable as m,Subject as y,concat as g,defer as v,empty as f,from as S,fromEvent as _,merge as w,noop as I,of as C,throwError as b}from"rxjs";import{catchError as P,delay as O,distinctUntilChanged as E,filter as A,map as T,retryWhen as k,shareReplay as D,switchMap as M,take as z}from"rxjs/operators";import{cond as N,constant as x,difference as R,each as F,filter as L,find as B,findIndex as j,flatMap as U,flatten as q,get as V,identity as G,includes as H,isArray as W,isEmpty as $,isEqual as Y,isMatch as K,isNil as J,isObject as Z,isPlainObject as Q,isString as X,isUndefined as ee,kebabCase as te,keyBy as ne,keys as ie,last as re,map as oe,max as ae,memoize as se,merge as de,noop as ce,omit as le,omitBy as ue,overSome as he,pick as pe,pickBy as me,reduce as ye,round as ge,some as ve,stubTrue as fe,transform as Se,union as _e,uniq as we,uniqueId as Ie,values as Ce,without as be}from"lodash";import{memoize as Pe,memoizeOne as Oe}from"@bigcommerce/memoize";import{createFormPoster as Ee}from"@bigcommerce/form-poster";import{supportsPopups as Ae}from"@braintree/browser-detection";import{default as Te}from"local-storage-fallback";import{createClient as ke}from"@bigcommerce/bigpay-client";import{creditCardType as De,number as Me}from"card-validator";import{exclude as ze,parseUrl as Ne,stringifyUrl as xe}from"query-string";import{createSelector as Re,createSelectorCreator as Fe,defaultMemoize as Le}from"reselect";import{default as Be}from"shallowequal";import{IntlMessageFormat as je}from"intl-messageformat";var Ue={785(t,n,i){var r,o;t.exports=(r={iframeResizer:()=>e.iframeResizer},o={},i.d(o,r),o)},939(e){e.exports=t}},qe={};function Ve(e){var t=qe[e];if(void 0!==t)return t.exports;var n=qe[e]={exports:{}};return Ue[e](n,n.exports,Ve),n.exports}Ve.d=(e,t)=>{for(var n in t)Ve.o(t,n)&&!Ve.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},Ve.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ve.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var Ge={};Ve.r(Ge),Ve.d(Ge,{createAmazonPayV2CustomerStrategy:()=>Ii,createApplePayCustomerStrategy:()=>Xi,createBigCommercePaymentsCustomerStrategy:()=>br,createBigCommercePaymentsFastlaneCustomerStrategy:()=>Hr,createBigCommercePaymentsPayLaterCustomerStrategy:()=>Yr,createBigCommercePaymentsVenmoCustomerStrategy:()=>Zr,createBoltCustomerStrategy:()=>so,createBraintreeFastlaneCustomerStrategy:()=>zo,createBraintreePaypalCreditCustomerStrategy:()=>Oo,createBraintreePaypalCustomerStrategy:()=>Co,createBraintreeVisaCheckoutCustomerStrategy:()=>Ro,createGooglePayAdyenV2CustomerStrategy:()=>ca,createGooglePayAdyenV3CustomerStrategy:()=>la,createGooglePayAuthorizeDotNetCustomerStrategy:()=>ha,createGooglePayBigCommercePaymentsCustomerStrategy:()=>as,createGooglePayBnzCustomerStrategy:()=>_a,createGooglePayBraintreeCustomerStrategy:()=>Ya,createGooglePayCheckoutComCustomerStrategy:()=>va,createGooglePayCybersourceCustomerStrategy:()=>Sa,createGooglePayOrbitalCustomerStrategy:()=>Ia,createGooglePayPayPalCommerceCustomerStrategy:()=>is,createGooglePayStripeCustomerStrategy:()=>qa,createGooglePayStripeUpeCustomerStrategy:()=>Va,createGooglePayTdOnlineMartCustomerStrategy:()=>ls,createGooglePayWorldpayAccessCustomerStrategy:()=>Ha,createPayPalCommerceCreditCustomerStrategy:()=>Js,createPayPalCommerceCustomerStrategy:()=>zs,createPayPalCommerceFastlaneCustomerStrategy:()=>sd,createPayPalCommerceVenmoCustomerStrategy:()=>Xs,createStripeLinkV2CustomerStrategy:()=>Id,createStripeUPECustomerStrategy:()=>ud});var He={};Ve.r(He),Ve.d(He,{createAdyenV2PaymentStrategy:()=>Ld,createAdyenV3PaymentStrategy:()=>Vd,createAffirmPaymentStrategy:()=>Yd,createAfterpayPaymentStrategy:()=>tc,createAmazonPayV2PaymentStrategy:()=>rc,createApplePayPaymentStrategy:()=>dc,createBigCommercePaymentsAlternativeMethodsPaymentStrategy:()=>xc,createBigCommercePaymentsCreditCardsPaymentStrategy:()=>Mc,createBigCommercePaymentsFastlanePaymentStrategy:()=>fc,createBigCommercePaymentsPayLaterPaymentStrategy:()=>wc,createBigCommercePaymentsPaymentStrategy:()=>mc,createBigCommercePaymentsRatePayPayPaymentStrategy:()=>Pc,createBigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy:()=>Fc,createBigCommercePaymentsVenmoPaymentStrategy:()=>jc,createBlueSnapDirectAPMPaymentStrategy:()=>al,createBlueSnapDirectCreditCardPaymentStrategy:()=>rl,createBlueSnapV2PaymentStrategy:()=>ul,createBoltPaymentStrategy:()=>fl,createBraintreeAchPaymentStrategy:()=>Il,createBraintreeCreditCardPaymentStrategy:()=>Ql,createBraintreeFastlanePaymentStrategy:()=>Ll,createBraintreeLocalMethodsPaymentStrategy:()=>Nl,createBraintreePaypalPaymentStrategy:()=>kl,createBraintreeVenmoPaymentStrategy:()=>Gl,createBraintreeVisaCheckoutPaymentStrategy:()=>Ul,createCBAMPGSPaymentStrategy:()=>ou,createCheckoutComAPMPaymentStrategy:()=>wu,createCheckoutComCreditCardPaymentStrategy:()=>mu,createCheckoutComFawryPaymentStrategy:()=>cu,createCheckoutComIdealPaymentStrategy:()=>fu,createCheckoutComSepaPaymentStrategy:()=>gu,createClearpayPaymentStrategy:()=>Pu,createCreditCardPaymentStrategy:()=>Ou,createCyberSourcePaymentStrategy:()=>Uu,createCyberSourceV2PaymentStrategy:()=>Wu,createGooglePayAdyenV2PaymentStrategy:()=>Qu,createGooglePayAdyenV3PaymentStrategy:()=>th,createGooglePayAuthorizeNetPaymentStrategy:()=>nh,createGooglePayBigCommercePaymentsPaymentStrategy:()=>fh,createGooglePayBraintreePaymentStrategy:()=>dh,createGooglePayCheckoutComPaymentStrategy:()=>ih,createGooglePayCybersourcePaymentStrategy:()=>rh,createGooglePayOrbitalPaymentStrategy:()=>oh,createGooglePayPPCPPaymentStrategy:()=>ph,createGooglePayStripePaymentStrategy:()=>ah,createGooglePayTdOnlineMartPaymentStrategy:()=>Sh,createGooglePayWorldpayAccessPaymentStrategy:()=>sh,createHummPaymentStrategy:()=>Ih,createKlarnaPaymentStrategy:()=>Ah,createKlarnaV2PaymentStrategy:()=>zh,createLegacyPaymentStrategy:()=>xh,createMolliePaymentStrategy:()=>Uh,createMonerisPaymentStrategy:()=>Hh,createNoPaymentStrategy:()=>Pd,createOfflinePaymentStrategy:()=>$h,createOffsitePaymentStrategy:()=>Jh,createPayPalCommerceAlternativeMethodsPaymentStrategy:()=>lp,createPayPalCommerceCreditCardsPaymentStrategy:()=>pp,createPayPalCommerceCreditPaymentStrategy:()=>ip,createPayPalCommerceFastlanePaymentStrategy:()=>_p,createPayPalCommercePaymentStrategy:()=>ep,createPayPalCommerceRatePayPaymentStrategy:()=>gp,createPayPalCommerceVenmoPaymentStrategy:()=>ap,createPayPalProPaymentStrategy:()=>zp,createPaypalExpressPaymentStrategy:()=>kp,createSagePayPaymentStrategy:()=>xp,createSezzlePaymentStrategy:()=>Lp,createSquareV2PaymentStrategy:()=>Wp,createStripeCSPaymentStrategy:()=>ym,createStripeOCSPaymentStrategy:()=>hm,createStripeUPEPaymentStrategy:()=>dm,createStripeV3PaymentStrategy:()=>im,createTDOnlineMartPaymentStrategy:()=>_m,createWorldpayAccessOpenBankingPaymentStrategy:()=>Em,createWorldpayAccessPaymentStrategy:()=>Pm,createZipPaymentStrategy:()=>km});var We={};Ve.r(We),Ve.d(We,{createAmazonPayV2ButtonStrategy:()=>w_,createApplePayButtonStrategy:()=>O_,createBigCommercePaymentsButtonStrategy:()=>T_,createBigCommercePaymentsPayLaterButtonStrategy:()=>M_,createBigCommercePaymentsVenmoButtonStrategy:()=>x_,createBoltButtonStrategy:()=>F_,createBraintreePaypalButtonStrategy:()=>q_,createBraintreePaypalCreditButtonStrategy:()=>H_,createBraintreeVenmoButtonStrategy:()=>ew,createBraintreeVisaCheckoutButtonStrategy:()=>Y_,createGooglePayAdyenV2ButtonStrategy:()=>aw,createGooglePayAdyenV3ButtonStrategy:()=>sw,createGooglePayAuthorizeDotNetButtonStrategy:()=>dw,createGooglePayBigCommercePaymentsButtonStrategy:()=>ow,createGooglePayBraintreeButtonStrategy:()=>iw,createGooglePayCheckoutComButtonStrategy:()=>cw,createGooglePayCybersourceButtonStrategy:()=>lw,createGooglePayOrbitalButtonStrategy:()=>uw,createGooglePayPayPalCommerceButtonStrategy:()=>rw,createGooglePayStripeButtonStrategy:()=>hw,createGooglePayTdOnlineMartButtonStrategy:()=>mw,createGooglePayWorldpayAccessButtonStrategy:()=>pw,createLinkV2ButtonStrategy:()=>Aw,createPayPalCommerceButtonStrategy:()=>gw,createPayPalCommerceCreditButtonStrategy:()=>Sw,createPayPalCommerceVenmoButtonStrategy:()=>Iw,createPaypalExpressButtonStrategy:()=>Pw});const $e="b2bExtraField_";function Ye(e){return e.name.startsWith($e)}function Ke(e){var t;const{fieldType:n,type:i}=function(e){switch(e){case"multiline_text":return{fieldType:"multiline",type:"string"};case"number":return{fieldType:"text",type:"integer"};case"dropdown":return{fieldType:"dropdown",type:"array"};default:return{fieldType:"text",type:"string"}}}(e.type);let r;return e.config.numberOfRows&&(r={rows:e.config.numberOfRows}),(null===(t=e.config.options)||void 0===t?void 0:t.length)&&(r=Object.assign(Object.assign({},r),{items:e.config.options.map(e=>({value:e,label:e}))})),{id:`${$e}${e.id}`,name:`${$e}${e.id}`,custom:!1,label:e.name,hidden:!e.visibleToStorefront,required:e.isRequired,default:null!=e.config.defaultValue?String(e.config.defaultValue):void 0,fieldType:n,type:i,maxLength:e.config.maxLength,max:e.config.maxValue,options:r}}function Je(e,t,n){return(i=t)&&i.type&&i.error?g(C(t),b(h(e,t.payload,n))):b(h(e,t,n));var i}var Ze;!function(e){e.LoadB2BTokenRequested="LOAD_B2B_TOKEN_REQUESTED",e.LoadB2BTokenSucceeded="LOAD_B2B_TOKEN_SUCCEEDED",e.LoadB2BTokenFailed="LOAD_B2B_TOKEN_FAILED"}(Ze||(Ze={}));class Qe{constructor(e){this._requestSender=e}loadB2BToken(e){return t=>{var n;const i=t.getState(),r=i.config.getStoreConfigOrThrow(),{storeHash:o}=r.storeProfile,{baseUrl:a="",clientId:s=""}=null!==(n=r.b2bApiSettings)&&void 0!==n?n:{},{id:d}=i.customer.getCustomerOrThrow(),{channelId:c}=i.checkout.getCheckoutOrThrow();return g(C(l(Ze.LoadB2BTokenRequested)),v(()=>{return t=this,n=void 0,r=function*(){const{body:t}=yield this._requestSender.getB2BToken(s,d,o,c,a,e);return l(Ze.LoadB2BTokenSucceeded,{token:t.data.token})},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r})).pipe(P(e=>Je(Ze.LoadB2BTokenFailed,e)))}}}const Xe={"X-Checkout-SDK-Version":"1.909.5"};var et,tt;class nt{constructor(e){this._requestSender=e}getB2BToken(e,t,n,i,r,o){return a=this,s=void 0,c=function*(){const{body:a}=yield this._requestSender.get("/customer/current.jwt",{timeout:null==o?void 0:o.timeout,params:{app_client_id:e},headers:Xe});return this._requestSender.post(`${r}/api/v2/login`,{timeout:null==o?void 0:o.timeout,credentials:!1,headers:{"Content-Type":"application/json"},body:{bcToken:a.token,customerId:t,storeHash:n,channelId:i}})},new((d=void 0)||(d=Promise))(function(e,t){function n(e){try{r(c.next(e))}catch(e){t(e)}}function i(e){try{r(c.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof d?r:new d(function(e){e(r)})).then(n,i)}r((c=c.apply(a,s||[])).next())});var a,s,d,c}}class it extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}!function(e){e[e.MissingBillingAddress=0]="MissingBillingAddress",e[e.MissingCart=1]="MissingCart",e[e.MissingCheckout=2]="MissingCheckout",e[e.MissingConsignments=3]="MissingConsignments",e[e.MissingCustomer=4]="MissingCustomer",e[e.MissingCheckoutConfig=5]="MissingCheckoutConfig",e[e.MissingOrder=6]="MissingOrder",e[e.MissingOrderConfig=7]="MissingOrderConfig",e[e.MissingOrderId=8]="MissingOrderId",e[e.MissingPayment=9]="MissingPayment",e[e.MissingPaymentId=10]="MissingPaymentId",e[e.MissingPaymentInstrument=11]="MissingPaymentInstrument",e[e.MissingPaymentMethod=12]="MissingPaymentMethod",e[e.MissingPaymentProviderCustomer=13]="MissingPaymentProviderCustomer",e[e.MissingPaymentRedirectUrl=14]="MissingPaymentRedirectUrl",e[e.MissingPaymentStatus=15]="MissingPaymentStatus",e[e.MissingPaymentToken=16]="MissingPaymentToken",e[e.MissingShippingAddress=17]="MissingShippingAddress"}(et||(et={}));class rt extends it{constructor(e){super(function(e){switch(e){case et.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case et.MissingCart:return"Unable to proceed because cart data is unavailable.";case et.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case et.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case et.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case et.MissingCheckoutConfig:case et.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case et.MissingOrder:return"Unable to proceed because order data is unavailable.";case et.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case et.MissingPayment:return"Unable to proceed because payment data is unavailable.";case et.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case et.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case et.MissingPaymentProviderCustomer:return"Unable to proceed because payment provider customer is unavailable.";case et.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e)),this.subtype=e,this.name="MissingDataError",this.type="missing_data"}}!function(e){e.UpdateBillingAddressRequested="UPDATE_BILLING_ADDRESS_REQUESTED",e.UpdateBillingAddressSucceeded="UPDATE_BILLING_ADDRESS_SUCCEEDED",e.UpdateBillingAddressFailed="UPDATE_BILLING_ADDRESS_FAILED",e.ContinueAsGuestRequested="CONTINUE_AS_GUEST_REQUESTED",e.ContinueAsGuestSucceeded="CONTINUE_AS_GUEST_SUCCEEDED",e.ContinueAsGuestFailed="CONTINUE_AS_GUEST_FAILED"}(tt||(tt={}));class ot extends it{constructor(e){super(e||"Unable to continue as a guest because the customer is already signed in."),this.name="UnableToContinueAsGuestError",this.type="unable_to_continue_as_guest"}}var at;class st{constructor(e,t){this._requestSender=e,this._subscriptionActionCreator=t}continueAsGuest(e,t){return n=>{const i=n.getState(),r=i.checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);const o=i.customer.getCustomer();if(o&&!o.isGuest)throw new ot;const a=i.billingAddress.getBillingAddress();let s;if(a){const{country:t}=a,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{return e=this,n=void 0,o=function*(){const{body:e}=yield this._createOrUpdateBillingAddress(r.id,s,d,t);return l(tt.ContinueAsGuestSucceeded,e)},new((i=void 0)||(i=Promise))(function(t,r){function a(e){try{d(o.next(e))}catch(e){r(e)}}function s(e){try{d(o.throw(e))}catch(e){r(e)}}function d(e){var n;e.done?t(e.value):(n=e.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((o=o.apply(e,n||[])).next())});var e,n,i,o})).pipe(P(e=>Je(tt.ContinueAsGuestFailed,e))),this._updateCustomerConsent(e,t))}}updateAddress(e,t){return n=>m.create(i=>{const r=n.getState(),o=r.checkout.getCheckout();if(!o)throw new rt(et.MissingCheckout);i.next(l(tt.UpdateBillingAddressRequested));const a=r.billingAddress.getBillingAddress(),s=!$(a),d=Object.assign(Object.assign({},e),{email:void 0===e.email&&a?a.email:e.email});a&&a.id&&(d.id=a.id),this._createOrUpdateBillingAddress(o.id,d,s,t).then(({body:e})=>{i.next(l(tt.UpdateBillingAddressSucceeded,e)),i.complete()}).catch(e=>{i.error(h(tt.UpdateBillingAddressFailed,e))})})}_updateCustomerConsent({email:e,acceptsAbandonedCartEmails:t,acceptsMarketingNewsletter:n},i){return null==t&&null==n?f():this._subscriptionActionCreator.updateSubscriptions({email:e,acceptsMarketingNewsletter:n||!1,acceptsAbandonedCartEmails:t||!1},i)}_createOrUpdateBillingAddress(e,t,n,i){return n?this._requestSender.updateAddress(e,t,i):this._requestSender.createAddress(e,t,i)}}class dt extends it{constructor(e){super(e||"Your checkout could not be processed because your cart is empty. Please add items to your cart and try again."),this.name="EmptyCartError",this.type="empty_cart"}}!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(at||(at={}));const ct=at;const lt={include:["cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","promotions.banners"].join(",")};class ut{constructor(e){this._requestSender=e}createAddress(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/billing-address`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{body:t,params:lt,headers:r,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}updateAddress(e,t,{timeout:n}={}){const{id:i}=t,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if("empty_cart"===e.body.type)throw new dt;throw e})}}var ht,pt;function mt(e,t){const n=u((e,t)=>t.type===ht.Synchronize?t.payload:e,e.getState(),{stateTransformer:t});return e.subscribe(e=>{n.dispatch(l(ht.Synchronize,e))},{initial:!1}),n}!function(e){e.Synchronize="SYNCHRONIZE"}(ht||(ht={})),function(e){e.ClearError="CLEAR_ERROR"}(pt||(pt={}));class yt{clearError(e){return{type:pt.ClearError,payload:e}}}class gt{constructor(e,t){this._requestSender=e,this._config=t}sendRequest(e,t){return this._requestSender.sendRequest(e,t)}get(e,t){return this._requestSender.get(e,t)}post(e,t){return this._requestSender.post(this._prefixed(e),t)}put(e,t){return this._requestSender.put(this._prefixed(e),t)}patch(e,t){return this._requestSender.patch(this._prefixed(e),t)}delete(e,t){return this._requestSender.delete(this._prefixed(e),t)}_prefixed(e){const t=this._config.getBasePath();return!this._config.getFeatures()["CHECKOUT-9950.update_sf_checkout_url_for_subfolder"]||!t||t.endsWith("/checkout")||/^https?:\/\//.test(e)?e:`${t}${e}`}}function vt(){try{return"production"}catch(e){return"development"}}class ft{constructor(e){this._console=e}log(...e){this._logToConsole("log",...e)}info(...e){this._logToConsole("info",...e)}warn(...e){this._logToConsole("warn",...e)}error(...e){this._logToConsole("error",...e)}debug(...e){this._logToConsole("debug",...e)}_logToConsole(e,...t){this._console&&this._console[e]&&this._console[e].call(this._console,...t)}}class St{log(){}info(){}warn(){}error(){}debug(){}}const _t=function(e=!0){return e?new ft(console):new St}("test"!==vt());function wt(){return _t}function It(e,t,n){const i=new WeakMap;function r(e){return(...n)=>{const r=n[n.length-1],{useCache:o}=(a=r)&&"boolean"==typeof a.useCache?r:{useCache:!1};var a;if(!o)return e.call(this,...n);const s=i.get(this)||{};var d;return i.get(this)||i.set(this,s),s[t]||(s[t]=(d=e,Pe(function(...e){const t=d.call(this,...e);return t instanceof m?S(t).pipe(D()):"function"==typeof t?Pe(e=>S(t(e)).pipe(D()),{isEqual:Y}):t},{isEqual:Y}))),s[t].call(this,...n)}}return{get(){if("function"!=typeof n.value)throw new Error("Decorator should be used in functions");const e=r.call(this,n.value);return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e}}}var Ct;!function(e){e.LoadConfigRequested="LOAD_CONFIG_REQUESTED",e.LoadConfigSucceeded="LOAD_CONFIG_SUCCEEDED",e.LoadConfigFailed="LOAD_CONFIG_FAILED"}(Ct||(Ct={}));class bt{constructor(e){this._configRequestSender=e}loadConfig(e){return m.create(t=>{t.next(l(Ct.LoadConfigRequested)),this._configRequestSender.loadConfig(e).then(e=>{t.next(l(Ct.LoadConfigSucceeded,e.body)),t.complete()}).catch(e=>{t.error(h(Ct.LoadConfigFailed,e))})})}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([It],bt.prototype,"loadConfig",null);const Pt={body:{},headers:{},status:0};class Ot extends it{constructor(e,{message:t,errors:n}={}){const{body:i,headers:r,status:o}=e||Pt;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=i,this.headers=r,this.status=o,this.errors=n||[]}}class Et extends Ot{constructor(e){super(e,{message:e.body.title}),this.name="CheckoutNotAvailableError",this.type="checkout_not_available"}}const At="This API endpoint is for internal use only and may change in the future";class Tt{constructor(e){this._requestSender=e}loadConfig({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/checkout-settings",{timeout:e,headers:Object.assign({Accept:ct.JsonV1,"X-API-INTERNAL":At},Xe),params:t}).catch(e=>{if(e.status>=400&&e.status<500)throw new Et(e);throw e})}}var kt;!function(e){e.ApplyCouponRequested="APPLY_COUPON_REQUESTED",e.ApplyCouponSucceeded="APPLY_COUPON_SUCCEEDED",e.ApplyCouponFailed="APPLY_COUPON_FAILED",e.RemoveCouponRequested="REMOVE_COUPON_REQUESTED",e.RemoveCouponSucceeded="REMOVE_COUPON_SUCCEEDED",e.RemoveCouponFailed="REMOVE_COUPON_FAILED"}(kt||(kt={}));class Dt{constructor(e){this._couponRequestSender=e}applyCoupon(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l(kt.ApplyCouponRequested)),this._couponRequestSender.applyCoupon(r.id,e,t).then(({body:e})=>{i.next(l(kt.ApplyCouponSucceeded,e)),i.complete()}).catch(e=>{i.error(h(kt.ApplyCouponFailed,e))})})}removeCoupon(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l(kt.RemoveCouponRequested)),this._couponRequestSender.removeCoupon(r.id,e,t).then(({body:e})=>{i.next(l(kt.RemoveCouponSucceeded,e)),i.complete()}).catch(e=>{i.error(h(kt.RemoveCouponFailed,e))})})}}const Mt=["cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","customer.customerGroup","payments","promotions.banners"];var zt,Nt,xt,Rt;function Ft(e){return we(e).join(",")}!function(e){e.AvailableShippingOptions="consignments.availableShippingOptions",e.PhysicalItemsCategoryNames="cart.lineItems.physicalItems.categoryNames",e.DigitalItemsCategoryNames="cart.lineItems.digitalItems.categoryNames"}(zt||(zt={}));class Lt{constructor(e){this._requestSender=e}applyCoupon(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/coupons`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{headers:r,timeout:n,params:{include:Ft([...Mt,zt.AvailableShippingOptions])},body:{couponCode:t}}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}removeCoupon(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/coupons/${t}`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.delete(i,{headers:r,timeout:n,params:{include:Ft([...Mt,zt.AvailableShippingOptions])}}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}!function(e){e.ApplyGiftCertificateRequested="APPLY_GIFT_CERTIFICATE_REQUESTED",e.ApplyGiftCertificateSucceeded="APPLY_GIFT_CERTIFICATE_SUCCEEDED",e.ApplyGiftCertificateFailed="APPLY_GIFT_CERTIFICATE_FAILED",e.RemoveGiftCertificateRequested="REMOVE_GIFT_CERTIFICATE_REQUESTED",e.RemoveGiftCertificateSucceeded="REMOVE_GIFT_CERTIFICATE_SUCCEEDED",e.RemoveGiftCertificateFailed="REMOVE_GIFT_CERTIFICATE_FAILED"}(Nt||(Nt={}));class Bt{constructor(e){this._giftCertificateRequestSender=e}applyGiftCertificate(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l(Nt.ApplyGiftCertificateRequested)),this._giftCertificateRequestSender.applyGiftCertificate(r.id,e,t).then(({body:e})=>{i.next(l(Nt.ApplyGiftCertificateSucceeded,e)),i.complete()}).catch(e=>{i.error(h(Nt.ApplyGiftCertificateFailed,e))})})}removeGiftCertificate(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l(Nt.RemoveGiftCertificateRequested)),this._giftCertificateRequestSender.removeGiftCertificate(r.id,e,t).then(({body:e})=>{i.next(l(Nt.RemoveGiftCertificateSucceeded,e)),i.complete()}).catch(e=>{i.error(h(Nt.RemoveGiftCertificateFailed,e))})})}}class jt{constructor(e){this._requestSender=e}applyGiftCertificate(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/gift-certificates`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{headers:r,timeout:n,params:{include:Ft(Mt)},body:{giftCertificateCode:t}}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}removeGiftCertificate(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/gift-certificates/${t}`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.delete(i,{headers:r,timeout:n,params:{include:Ft(Mt)}}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}function Ut(e){return e&&"resolveIds"in e}class qt extends it{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class Vt{constructor(e){var t,n,i;this._factories={},this._instances={},this._defaultToken=null!==(t=null==e?void 0:e.defaultToken)&&void 0!==t?t:"default",this._useFallback=null===(n=null==e?void 0:e.useFallback)||void 0===n||n,this._tokenResolver=null!==(i=null==e?void 0:e.tokenResolver)&&void 0!==i?i:e=>e}get(e,t){try{return this._getInstance(e||this._defaultToken,t||e||this._defaultToken)}catch(e){if(!this._useFallback)throw e;return this._getInstance(this._defaultToken,t||this._defaultToken)}}getFactory(e,t){const n=this._tokenResolver(e,Object.keys(this._factories),t);return n?this._factories[n]:void 0}register(e,t){if(this._hasFactory(e))throw new qt(`'${e}' is already registered.`);this._factories[e]=t}_hasFactory(e){return!!this._factories[e]}_hasInstance(e){return!!this._instances[e]}_getInstance(e,t){if(!this._hasInstance(t)){const n=this.getFactory(e);if(!n)throw new qt(`'${e}' is not registered.`);this._instances[t]=n()}return this._instances[t]}}class Gt{constructor(e=!1){this._useFallback=e,this._registry=new Vt({tokenResolver:this._resolveToken.bind(this),defaultToken:this._encodeToken({default:!0}),useFallback:this._useFallback})}get(e){return this._registry.get(this._encodeToken(e))}getFactory(e,t){try{return this._registry.getFactory(this._encodeToken(e),t)}catch(e){return}}getUseFallback(){return this._useFallback}register(e,t){this._registry.register(this._encodeToken(e),t)}_encodeToken(e){return btoa(JSON.stringify(e))}_decodeToken(e){return JSON.parse(atob(e))}_resolveToken(e,t,n){var i;const r=this._decodeToken(e),o=[];t.forEach(e=>{const t=this._decodeToken(e),n={token:e,matches:0,default:!1,totalKeys:Object.keys(t).length};for(const[e,i]of Object.entries(t)){if(e in r&&r[e]!==i){n.matches=0;break}e in r&&r[e]===i&&n.matches++,"default"===e&&!0===i&&(n.default=!0)}o.push(n)});const a=o.sort((e,t)=>t.matches-e.matches).filter(e=>e.matches>0);a.length>1&&a[0].matches===a[1].matches&&"development"===vt()&&wt().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.");const s=Object.keys(r).length;if(n){const e=a.find(e=>e.matches===s&&e.matches===e.totalKeys);if(!e)throw new Error(`Unable to resolve to a registered token with the provided token for ${JSON.stringify(r)} with exact match.`);return e.token}const d=a[0];if(d&&d.token)return d.token;if(this._useFallback){const e=null===(i=o.find(e=>e.default))||void 0===i?void 0:i.token;if(e)return e}throw new Error(`Unable to resolve to a registered token with the provided token for ${JSON.stringify(r)}.`)}}function Ht(e){const t=e;return"object"==typeof t&&"object"==typeof t.payload&&"string"==typeof t.payload.token}!function(e){e.BuyNow="BUY_NOW"}(xt||(xt={})),function(e){e.SignInCustomerRequested="SIGN_IN_CUSTOMER_REQUESTED",e.SignInCustomerSucceeded="SIGN_IN_CUSTOMER_SUCCEEDED",e.SignInCustomerFailed="SIGN_IN_CUSTOMER_FAILED",e.SignOutCustomerRequested="SIGN_OUT_CUSTOMER_REQUESTED",e.SignOutCustomerSucceeded="SIGN_OUT_CUSTOMER_SUCCEEDED",e.SignOutCustomerFailed="SIGN_OUT_CUSTOMER_FAILED",e.CreateCustomerRequested="CREATE_CUSTOMER_REQUESTED",e.CreateCustomerSucceeded="CREATE_CUSTOMER_SUCCEEDED",e.CreateCustomerFailed="CREATE_CUSTOMER_FAILED",e.CreateCustomerAddressRequested="CREATE_CUSTOMER_ADDRESS_REQUESTED",e.CreateCustomerAddressSucceeded="CREATE_CUSTOMER_ADDRESS_SUCCEEDED",e.CreateCustomerAddressFailed="CREATE_CUSTOMER_ADDRESS_FAILED",e.StripeLinkAuthenticated="STRIPE_LINK_AUTHENTICATED"}(Rt||(Rt={}));var Wt,$t,Yt;class Kt{constructor(e,t,n){this._customerRequestSender=e,this._checkoutActionCreator=t,this._spamProtectionActionCreator=n}createCustomer(e,t){return n=>{const i=n.getState().config.getStoreConfigOrThrow(),{isStorefrontSpamProtectionEnabled:r}=i.checkoutSettings,o=i=>S(this._customerRequestSender.createAccount(Object.assign(Object.assign({},e),{token:i}),t)).pipe(M(()=>g(this._checkoutActionCreator.loadCurrentCheckout(t)(n),C(l(Rt.CreateCustomerSucceeded)))));return g(C(l(Rt.CreateCustomerRequested)),r?S(this._spamProtectionActionCreator.execute()(n)).pipe(M(e=>{var t;return Ht(e)?g(C(e),o(null===(t=e.payload)||void 0===t?void 0:t.token)):C(e)})):o()).pipe(P(e=>Je(Rt.CreateCustomerFailed,e)))}}createAddress(e,t){return g(C(l(Rt.CreateCustomerAddressRequested)),v(()=>{return n=this,i=void 0,o=function*(){const{body:n}=yield this._customerRequestSender.createAddress(e,t);return l(Rt.CreateCustomerAddressSucceeded,n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Je(Rt.CreateCustomerAddressFailed,e)))}signInCustomer(e,t){return n=>{const i=n.getState().checkout.getCheckoutOrThrow(),r=i.cart.source===xt.BuyNow?i.id:void 0;return g(C(l(Rt.SignInCustomerRequested)),S(this._customerRequestSender.signInCustomer(Object.assign(Object.assign({},e),{cartId:r}),t)).pipe(M(({body:e})=>e.data.persistentCartRetrievalInformation?g(this._checkoutActionCreator.loadCheckout(e.data.persistentCartRetrievalInformation.id,t)(n),C(l(Rt.SignInCustomerSucceeded,e.data))):g(this._checkoutActionCreator.loadCurrentCheckout(t)(n),C(l(Rt.SignInCustomerSucceeded,e.data)))))).pipe(P(e=>Je(Rt.SignInCustomerFailed,e)))}}signOutCustomer(e){return t=>{const n=t.getState().checkout.getCheckoutOrThrow(),i=n.cart.source===xt.BuyNow?n.id:void 0;return g(C(l(Rt.SignOutCustomerRequested)),S(this._customerRequestSender.signOutCustomer(e,i)).pipe(M(({body:n})=>g(this._checkoutActionCreator.loadCurrentCheckout(e)(t),C(l(Rt.SignOutCustomerSucceeded,n.data)))))).pipe(P(e=>Je(Rt.SignOutCustomerFailed,e)))}}}class Jt{constructor(e){this._requestSender=e}createAccount(e,{timeout:t}={}){return this._requestSender.post("/api/storefront/customer",{timeout:t,headers:Xe,body:e})}createAddress(e,{timeout:t}={}){return this._requestSender.post("/api/storefront/customer-address",{timeout:t,headers:Xe,body:e})}signInCustomer(e,{timeout:t}={}){return this._requestSender.post("/internalapi/v1/checkout/customer",{timeout:t,headers:Xe,body:e})}signOutCustomer({timeout:e}={},t){return this._requestSender.delete("/internalapi/v1/checkout/customer",Object.assign({timeout:e,headers:Xe},t&&{body:{cartId:t}}))}}function Zt(e,t,n){t.forEach(t=>{Ut(t)&&t.resolveIds.forEach(i=>{e.getFactory(i,!0)||e.register(i,()=>t(n))})})}!function(e){e.SignInFailed="CUSTOMER_STRATEGY_SIGN_IN_FAILED",e.SignInRequested="CUSTOMER_STRATEGY_SIGN_IN_REQUESTED",e.SignInSucceeded="CUSTOMER_STRATEGY_SIGN_IN_SUCCEEDED",e.SignOutFailed="CUSTOMER_STRATEGY_SIGN_OUT_FAILED",e.SignOutRequested="CUSTOMER_STRATEGY_SIGN_OUT_REQUESTED",e.SignOutSucceeded="CUSTOMER_STRATEGY_SIGN_OUT_SUCCEEDED",e.ExecutePaymentMethodCheckoutFailed="CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_FAILED",e.ExecutePaymentMethodCheckoutRequested="CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_REQUESTED",e.ExecutePaymentMethodCheckoutSucceeded="CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_SUCCEEDED",e.InitializeFailed="CUSTOMER_STRATEGY_INITIALIZE_FAILED",e.InitializeRequested="CUSTOMER_STRATEGY_INITIALIZE_REQUESTED",e.InitializeSucceeded="CUSTOMER_STRATEGY_INITIALIZE_SUCCEEDED",e.DeinitializeFailed="CUSTOMER_STRATEGY_DEINITIALIZE_FAILED",e.DeinitializeRequested="CUSTOMER_STRATEGY_DEINITIALIZE_REQUESTED",e.DeinitializeSucceeded="CUSTOMER_STRATEGY_DEINITIALIZE_SUCCEEDED",e.WidgetInteractionStarted="CUSTOMER_STRATEGY_WIDGET_INTERACTION_STARTED",e.WidgetInteractionFinished="CUSTOMER_STRATEGY_WIDGET_INTERACTION_FINISHED",e.WidgetInteractionFailed="CUSTOMER_STRATEGY_WIDGET_INTERACTION_FAILED"}(Wt||(Wt={}));class Qt{constructor(e,t,n){this._strategyRegistry=e,this._strategyRegistryV2=t,this._paymentIntegrationService=n}signIn(e,t){return m.create(n=>{const i=t&&t.methodId,r={methodId:i};n.next(l(Wt.SignInRequested,void 0,r)),this._getStrategy(i).signIn(e,t).then(()=>{n.next(l(Wt.SignInSucceeded,void 0,r)),n.complete()}).catch(e=>{n.error(h(Wt.SignInFailed,e,r))})})}signOut(e){return m.create(t=>{const n=e&&e.methodId,i={methodId:n};t.next(l(Wt.SignOutRequested,void 0,i)),this._getStrategy(n).signOut(e).then(()=>{t.next(l(Wt.SignOutSucceeded,void 0,i)),t.complete()}).catch(e=>{t.error(h(Wt.SignOutFailed,e,i))})})}executePaymentMethodCheckout(e){return m.create(t=>{const n=e&&e.methodId,i={methodId:n};t.next(l(Wt.ExecutePaymentMethodCheckoutRequested,void 0,i)),this._getStrategy(n).executePaymentMethodCheckout(e).then(()=>{t.next(l(Wt.ExecutePaymentMethodCheckoutSucceeded,void 0,i)),t.complete()}).catch(e=>{t.error(h(Wt.ExecutePaymentMethodCheckoutFailed,e,i))})})}initialize(e){return t=>m.create(n=>{var i;const r=t.getState(),o=e&&e.methodId,a={methodId:o};if(Zt(this._strategyRegistryV2,null!==(i=null==e?void 0:e.integrations)&&void 0!==i?i:[],this._paymentIntegrationService),o&&r.customerStrategies.isInitialized(o))return n.complete();n.next(l(Wt.InitializeRequested,void 0,a)),this._getStrategy(o).initialize(e).then(()=>{n.next(l(Wt.InitializeSucceeded,void 0,a)),n.complete()}).catch(e=>{n.error(h(Wt.InitializeFailed,e,a))})})}deinitialize(e){return t=>m.create(n=>{const i=t.getState(),r=e&&e.methodId,o={methodId:r};if(r&&!i.customerStrategies.isInitialized(r))return n.complete();n.next(l(Wt.DeinitializeRequested,void 0,o)),this._getStrategy(r).deinitialize(e).then(()=>{n.next(l(Wt.DeinitializeSucceeded,void 0,o)),n.complete()}).catch(e=>{n.error(h(Wt.DeinitializeFailed,e,o))})})}widgetInteraction(e,t){return m.create(n=>{const i={methodId:t&&t.methodId};n.next(l(Wt.WidgetInteractionStarted,void 0,i)),e().then(()=>{n.next(l(Wt.WidgetInteractionFinished,void 0,i)),n.complete()}).catch(e=>{n.error(h(Wt.WidgetInteractionFailed,e,i))})})}_getStrategy(e){let t;try{t=this._strategyRegistryV2.get({id:e||""})}catch(n){t=this._strategyRegistry.get(e)}return t}}function Xt(e,t=[]){return Array.isArray(t)?Ft([...e,...t]):function(e,t){const n=ie(me(t,e=>!e)),i=ie(L(t));return Ft([...R(e,n),...i])}(e,t)}class en{constructor(e){this._requestSender=e}loadCheckout(e,{params:{include:t}={},timeout:n}={}){const i=`/api/storefront/checkout/${e}`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.get(i,{params:{include:Xt(Mt,t)},headers:r,timeout:n}).catch(e=>{if(e.status>=400&&e.status<500)throw new Et(e);throw e})}updateCheckout(e,t,{params:{include:n}={},timeout:i}={}){const r=`/api/storefront/checkout/${e}`,o=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.put(r,{params:{include:Xt(Mt,n)},body:t,headers:o,timeout:i}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}!function(e){e.LoadCheckoutRequested="LOAD_CHECKOUT_REQUESTED",e.LoadCheckoutSucceeded="LOAD_CHECKOUT_SUCCEEDED",e.LoadCheckoutFailed="LOAD_CHECKOUT_FAILED",e.UpdateCheckoutRequested="UPDATE_CHECKOUT_REQUESTED",e.UpdateCheckoutSucceeded="UPDATE_CHECKOUT_SUCCEEDED",e.UpdateCheckoutFailed="UPDATE_CHECKOUT_FAILED"}($t||($t={})),function(e){e.HydrateInitialState="HYDRATE_INITIAL_STATE"}(Yt||(Yt={}));var tn;class nn{constructor(e,t,n){this._checkoutRequestSender=e,this._configActionCreator=t,this._formFieldsActionCreator=n}loadCheckout(e,t){return()=>g(C(l($t.LoadCheckoutRequested)),w(this._configActionCreator.loadConfig({useCache:!0,timeout:null==t?void 0:t.timeout,params:{checkoutId:e}}),this._formFieldsActionCreator.loadFormFields({useCache:!0,timeout:null==t?void 0:t.timeout})),v(()=>this._checkoutRequestSender.loadCheckout(e,t).then(({body:e})=>l($t.LoadCheckoutSucceeded,this._transformCustomerAddresses(e))))).pipe(P(e=>Je($t.LoadCheckoutFailed,e)))}loadDefaultCheckout(e){return t=>g(C(l($t.LoadCheckoutRequested)),w(this._configActionCreator.loadConfig({useCache:!0,timeout:null==e?void 0:e.timeout}),this._formFieldsActionCreator.loadFormFields({useCache:!0,timeout:null==e?void 0:e.timeout})),v(()=>{return n=this,i=void 0,o=function*(){const n=t.getState().config.getContextConfig();if(!n||!n.checkoutId)throw new rt(et.MissingCheckoutConfig);const{body:i}=yield this._checkoutRequestSender.loadCheckout(n.checkoutId,e);return l($t.LoadCheckoutSucceeded,this._transformCustomerAddresses(i))},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Je($t.LoadCheckoutFailed,e)))}updateCheckout(e,t){return n=>new m(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l($t.UpdateCheckoutRequested)),this._checkoutRequestSender.updateCheckout(r.id,e,t).then(({body:e})=>{i.next(l($t.UpdateCheckoutSucceeded,e)),i.complete()}).catch(e=>{i.error(h($t.UpdateCheckoutFailed,e))})})}loadCurrentCheckout(e){return t=>{const n=t.getState().checkout.getCheckout();if(!n)throw new rt(et.MissingCheckout);return this.loadCheckout(n.id,e)(t)}}hydrateInitialState(e){return{type:Yt.HydrateInitialState,payload:e}}_transformCustomerAddresses(e){return Object.assign(Object.assign({},e),{customer:Object.assign(Object.assign({},e.customer),{addresses:e.customer.addresses.map(e=>Object.assign(Object.assign({},e),{shouldSaveAddress:!1}))})})}}!function(e){e.LoadFormFieldsRequested="LOAD_FORM_FIELDS_REQUESTED",e.LoadFormFieldsSucceeded="LOAD_FORM_FIELDS_SUCCEEDED",e.LoadFormFieldsFailed="LOAD_FORM_FIELDS_FAILED"}(tn||(tn={}));var rn;class on{constructor(e){this._formFieldsRequestSender=e}loadFormFields(e){return g(C(l(tn.LoadFormFieldsRequested)),v(()=>{return t=this,n=void 0,r=function*(){const{body:t}=yield this._formFieldsRequestSender.loadFields(e);return l(tn.LoadFormFieldsSucceeded,t)},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r})).pipe(P(e=>Je(tn.LoadFormFieldsFailed,e)))}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([It],on.prototype,"loadFormFields",null);class an{constructor(e){this._requestSender=e}loadFields({timeout:e}={}){return this._requestSender.get("/api/storefront/form-fields",{timeout:e,headers:Object.assign({Accept:ct.JsonV1,"X-API-INTERNAL":At},Xe)})}}class sn extends it{constructor(){super("You haven't complete our spam protection challenge. Please try again."),this.name="SpamProtectionChallengeNotCompletedError",this.type="spam_protection_challenge_not_completed"}}class dn extends it{constructor(){super("We were not able to complete your spam protection verification. Please try again."),this.name="SpamProtectionFailedError",this.type="spam_protection_failed"}}!function(e){e.InitializeFailed="SPAM_PROTECTION_INITIALIZE_FAILED",e.InitializeSucceeded="SPAM_PROTECTION_INITIALIZE_SUCCEEDED",e.InitializeRequested="SPAM_PROTECTION_INITIALIZE_REQUESTED",e.VerifyCheckoutRequested="SPAM_PROTECTION_CHECKOUT_VERIFY_REQUESTED",e.VerifyCheckoutSucceeded="SPAM_PROTECTION_CHECKOUT_VERIFY_SUCCEEDED",e.VerifyCheckoutFailed="SPAM_PROTECTION_CHECKOUT_VERIFY_FAILED",e.ExecuteRequested="SPAM_PROTECTION_EXECUTE_REQUESTED",e.ExecuteSucceeded="SPAM_PROTECTION_EXECUTE_SUCCEEDED",e.ExecuteFailed="SPAM_PROTECTION_EXECUTE_FAILED"}(rn||(rn={}));var cn,ln,un,hn=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pn{constructor(e,t){this._googleRecaptcha=e,this._requestSender=t}initialize(e){return t=>g(C(l(rn.InitializeRequested,void 0)),v(()=>hn(this,void 0,void 0,function*(){const n=e?e.containerId:"spamProtectionContainer";if(document.getElementById(n)&&this._googleRecaptcha.reset(n),!e&&!document.getElementById(n)){const e=document.createElement("div");e.setAttribute("id",n),document.body.appendChild(e)}const i=t.getState().config.getStoreConfigOrThrow().checkoutSettings.googleRecaptchaSitekey;return yield this._googleRecaptcha.load(n,i),l(rn.InitializeSucceeded)}))).pipe(P(e=>Je(rn.InitializeFailed,e)))}verifyCheckoutSpamProtection(){return e=>v(()=>{const t=e.getState().checkout.getCheckout();if(!t)throw new rt(et.MissingCheckout);return g(C(l(rn.VerifyCheckoutRequested)),S(this.execute()(e)).pipe(M(e=>Ht(e)&&e.payload?S(this._requestSender.validate(t.id,e.payload.token)).pipe(M(({body:t})=>g(C(e),C(l(rn.VerifyCheckoutSucceeded,t))))):C(e)))).pipe(P(e=>Je(rn.VerifyCheckoutFailed,e)))})}execute(){return e=>g(C(l(rn.ExecuteRequested)),this.initialize()(e),this._googleRecaptcha.execute().pipe(z(1)).pipe(M(({error:e,token:t})=>hn(this,void 0,void 0,function*(){if(e instanceof sn)throw e;if(e||!t)throw new dn;return l(rn.ExecuteSucceeded,{token:t})})))).pipe(P(e=>Je(rn.ExecuteFailed,e)))}}class mn{constructor(e=window){this._window=e}create(e){return new this._window.MutationObserver(e)}}!function(e){e[e.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",e[e.CustomerNotInitialized=1]="CustomerNotInitialized",e[e.PaymentNotInitialized=2]="PaymentNotInitialized",e[e.ShippingNotInitialized=3]="ShippingNotInitialized",e[e.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(cn||(cn={}));class yn extends it{constructor(e){super(function(e){switch(e){case cn.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case cn.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case cn.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case cn.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.subtype=e,this.name="NotInitializedError",this.type="not_initialized"}}class gn extends it{constructor(){super("Spam protection is not loaded. Please try again."),this.name="SpamProtectionNotLoadedError",this.type="spam_protection_failed"}}class vn{constructor(e,t){this.googleRecaptchaScriptLoader=e,this.mutationObserverFactory=t,this._memoized=Pe((e,t,n)=>{const i=new y;if(!n)throw new Error;return this._widgetId=e.render(n.id,{sitekey:t,size:"invisible",callback:()=>{i.next({token:e.getResponse(this._widgetId)}),e.reset(this._widgetId)},"error-callback":()=>{i.next({error:new dn})}}),i},{isEqual:(e,t)=>e===t})}load(e,t){return this.googleRecaptchaScriptLoader.load().then(n=>{n&&(this._event$=this._memoized(n,t,document.getElementById(e)),this._recaptcha=n)}).catch(e=>{throw e})}reset(e){var t;const n=document.getElementById(e);null==n||n.remove(),null===(t=this._recaptcha)||void 0===t||t.reset(this._widgetId)}execute(){return v(()=>{const e=this._event$,t=this._recaptcha;if(!e||!t)throw new yn(cn.SpamProtectionNotInitialized);return v(()=>{const e=document.querySelector('iframe[src*="bframe"]');return e?C(e):b(new gn)}).pipe(k(e=>e.pipe(O(250),M((e,t)=>t<28?C(e):b(e)))),M(n=>(this._watchRecaptchaChallengeWindow(e,n),t.execute(this._widgetId),e)),P(e=>C({error:e})))})}_watchRecaptchaChallengeWindow(e,t){const n=t.parentElement;if(!n)throw new gn;const i=n.parentElement;if(!i)throw new gn;this.mutationObserverFactory.create(()=>{"hidden"===i.style.visibility&&e.next({error:new sn})}).observe(i,{attributes:!0,attributeFilter:["style"]})}}class fn{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(){return this._loadPromise||(this._loadPromise=this._loadScript()),this._loadPromise}_loadScript(){const e="initRecaptcha",t=[`onload=${e}`,"render=explicit"].join("&");return new Promise((n,i)=>{this._window[e]=()=>n(this._window.grecaptcha),this._scriptLoader.loadScript(`//www.google.com/recaptcha/api.js?${t}`).catch(e=>{this._loadPromise=void 0,i(e)})})}}function Sn(e){return new vn(new fn(e),new mn)}class _n{constructor(e){this._requestSender=e}validate(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/spam-protection`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{body:{token:t},headers:r,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}class wn{constructor(e,t){this._store=e,this._customerActionCreator=t}signIn(e,t){return this._store.dispatch(this._customerActionCreator.signInCustomer(e,t))}signOut(e){return this._store.dispatch(this._customerActionCreator.signOutCustomer(e))}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())}initialize(){return Promise.resolve(this._store.getState())}deinitialize(){return Promise.resolve(this._store.getState())}}function In(e){if(!/^(https?:)?\/\//.test(e))throw new qt("The provided URL must be absolute.");const t=document.createElement("a");t.href=e;const n=t.port&&-1!==e.indexOf(`${t.hostname}:${t.port}`)?t.port:"";return{hash:t.hash,hostname:t.hostname,href:t.href,origin:`${t.protocol}//${t.hostname}${n?`:${n}`:""}`,pathname:t.pathname,port:n,protocol:t.protocol,search:t.search}}class Cn extends it{constructor(e){super(e||"Unable to proceed due to no extension configured for this region."),this.name="ExtensionNotFoundError",this.type="extension_not_found"}}function bn(e,t){return e.type===t}!function(e){e.LoadExtensionsRequested="LOAD_EXTENSIONS_REQUESTED",e.LoadExtensionsSucceeded="LOAD_EXTENSIONS_SUCCEEDED",e.LoadExtensionsFailed="LOAD_EXTENSIONS_FAILED",e.RenderExtensionRequested="RENDER_EXTENSION_REQUESTED",e.RenderExtensionSucceeded="RENDER_EXTENSION_SUCCEEDED",e.RenderExtensionFailed="RENDER_EXTENSION_FAILED"}(ln||(ln={}));class Pn{constructor(e,t,n){this._targetWindow=t,this._context=n,this._targetOrigin="*"===e?"*":In(e).origin}post(e,t){const n=this._targetWindow;if(window===n)return;if(!n)throw new Error("Unable to post message because target window is not set.");const i=t&&_(window,"message").pipe(A(e=>e.origin===this._targetOrigin&&bn(e.data,e.data.type)&&-1!==[t.successType,t.errorType].indexOf(e.data.type)),T(e=>{if(t.errorType===e.data.type)throw e.data;return e.data}),z(1)).toPromise();return n.postMessage(Object.assign(Object.assign({},e),{context:this._context}),this._targetOrigin),i}setTarget(e){this._targetWindow=e}setContext(e){this._context=e}}function On(e){var t;const n=null===(t=document.querySelector(`[data-extension-id="${e.id}"]`))||void 0===t?void 0:t.querySelector("iframe");if(!(null==n?void 0:n.contentWindow))throw new Cn(`Unable to post due to no extension rendered for ID: ${e.id}.`);return new Pn(e.url,n.contentWindow)}!function(e){e.ExtensionReady="EXTENSION:READY",e.ExtensionFailed="EXTENSION:FAILED"}(un||(un={}));class En{constructor(e){const t=new Promise((e,t)=>{this.cancel=t});this.promise=Promise.race([e,t])}}class An extends it{constructor(e){super(e||"Unable to proceed because the required element is unexpectedly detached from the page."),this.name="UnexpectedDetachmentError",this.type="unexpected_detachment"}}var Tn;class kn{constructor(e){this._mutationObserver=e}ensurePresence(e,t){return n=this,i=void 0,o=function*(){const n=new En(t),i=this._mutationObserver.create(t=>{t.forEach(t=>{0!==Array.from(t.removedNodes).filter(t=>e.some(e=>t===e||t.contains(e))).length&&n.cancel(new An)})});i.observe(document.body,{childList:!0,subtree:!0});try{const e=yield n.promise;return i.disconnect(),e}catch(e){throw i.disconnect(),e}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}function Dn(e,t){const{iframeResizer:n}=Ve(785);return n(e,t)}class Mn extends it{constructor(e){super(e||"Unable to load an extension"),this.name="ExtensionNotLoadedError",this.type="extension_not_loaded"}}!function(e){e.Subscribe="EXTENSION_INTERNAL:SUBSCRIBE",e.Unsubscribe="EXTENSION_INTERNAL:UNSUBSCRIBE",e.ResizeIframe="EXTENSION_INTERNAL:RESIZE_IFRAME"}(Tn||(Tn={}));class zn{constructor(e){this._options=e}createFrame(e,t,n,i){const r=document.getElementById(t),{timeout:o=6e4}=this._options||{};if(!r)throw new Mn("Unable to embed the iframe because the container element could not be found.");const a=document.createElement("iframe");return a.src=e,a.style.border="none",a.style.display="none",a.style.width="100%",r.appendChild(a),this._toResizableFrame(a,o,n,i).catch(e=>{throw r.removeChild(a),e})}_toResizableFrame(e,t,n,i){return r=this,o=void 0,s=function*(){const r=new kn(new mn),o=new Promise((r,o)=>{const a=window.setTimeout(()=>{try{i()}catch(e){e instanceof Error&&console.error(`Extension rendering timed out after ${t}ms, and the callback function could not be executed. Error: ${e.message}`)}o(new Mn("Unable to load the extension because the content could not be loaded."))},t),s=t=>{if(t.origin===In(e.src).origin&&bn(t.data,Tn.ResizeIframe)){e.style.display="";const t=Dn({autoResize:!1,scrolling:!1,sizeWidth:!1,heightCalculationMethod:"bodyOffset",initCallback:n},e);d(),r(t[t.length-1])}},d=()=>{window.removeEventListener("message",s),window.clearTimeout(a)};window.addEventListener("message",s)});return r.ensurePresence([e],o)},new((a=void 0)||(a=Promise))(function(e,t){function n(e){try{d(s.next(e))}catch(e){t(e)}}function i(e){try{d(s.throw(e))}catch(e){t(e)}}function d(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a(function(e){e(r)})).then(n,i)}d((s=s.apply(r,o||[])).next())});var r,o,a,s}}class Nn{constructor(e,t,n){this._containerId=e,this._extension=t,this._config=n;const{cartId:i,parentOrigin:r}=this._config;this._url=new URL(this._extension.url),this._url.searchParams.set("extensionId",this._extension.id),this._url.searchParams.set("cartId",i),this._url.searchParams.set("parentOrigin",r)}attach(){var e,t,n,i,r;return t=this,n=void 0,r=function*(){if(null===(e=document.querySelector(`[data-extension-id="${this._extension.id}"]`))||void 0===e?void 0:e.querySelector("iframe"))return;const t=new zn,n=e=>{On(this._extension).post({type:e})};this._iframe=yield t.createFrame(this._url.toString(),this._containerId,()=>{n(un.ExtensionReady)},()=>{n(un.ExtensionFailed)});const i=document.getElementById(this._containerId);null==i||i.setAttribute("data-extension-id",this._extension.id)},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())})}detach(){this._iframe&&this._iframe.parentElement&&this._iframe.parentElement.removeChild(this._iframe)}}class xn{constructor(e){this._requestSender=e}loadExtensions(e){return()=>m.create(t=>{t.next(l(ln.LoadExtensionsRequested)),this._requestSender.loadExtensions(e).then(e=>{const n=e.body;t.next(l(ln.LoadExtensionsSucceeded,n)),t.complete()}).catch(e=>{t.error(h(ln.LoadExtensionsFailed,e))})})}renderExtension(e,t,n){return i=>m.create(r=>{return o=this,a=void 0,d=function*(){const o=i.getState(),{id:a}=o.cart.getCartOrThrow(),{links:{checkoutLink:s}}=o.config.getStoreConfigOrThrow(),d=o.extensions.getExtensionByRegion(t);try{if(!d)throw new Cn(`Unable to proceed due to no extension configured for the region: ${t}.`);if(r.next(l(ln.RenderExtensionRequested)),"worker"===d.type){const e=function(e){if(!window.Worker)throw new Error("Unable to load the extension's web worker: your browser does not support Web Workers.");try{const t=URL.createObjectURL(new Blob([`importScripts=((i)=>(...a)=>i(...a.map((u)=>''+new URL(u,"${e}"))))(importScripts);importScripts("${e}")`],{type:"text/javascript"}));return new Worker(t)}catch(e){throw new Error("Unable to load the extension's web worker")}}(d.url);n.add(d.id,e)}else{const t=new Nn(e,d,{cartId:a,parentOrigin:In(s).origin});yield t.attach()}r.next(l(ln.RenderExtensionSucceeded)),r.complete()}catch(e){r.error(h(ln.RenderExtensionFailed,e))}},new((s=void 0)||(s=Promise))(function(e,t){function n(e){try{r(d.next(e))}catch(e){t(e)}}function i(e){try{r(d.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof s?r:new s(function(e){e(r)})).then(n,i)}r((d=d.apply(o,a||[])).next())});var o,a,s,d})}}class Rn{constructor(e){this._requestSender=e}loadExtensions({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/checkout-extensions",{timeout:e,headers:Object.assign({Accept:ct.JsonV1},Xe),params:t})}}const Fn=function(e,t,n){return t&&n?Ln(0,t,n):function(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(n=>{const i=Object.getOwnPropertyDescriptor(e.prototype,n);i&&"constructor"!==n&&Object.defineProperty(t.prototype,n,Ln(e.prototype,n,i))}),t}(e)};function Ln(e,t,n){if("function"!=typeof n.value)return n;let i=n.value;return{get(){const e=i.bind(this);return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e},set(e){i=e}}}var Bn,jn;class Un{constructor(e){this._worker=e,this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,this._worker.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,this._worker.removeEventListener("message",this._handleMessage))}addListener(e,t){let n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)}removeListener(e,t){const n=this._listeners[e];if(!n)return;const i=n.indexOf(t);i>=0&&n.splice(i,1)}trigger(e,t){const n=this._listeners[e.type];n&&n.forEach(n=>t?n(e,t):n(e))}_handleMessage(e){const t=e.data,{context:n}=t,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([Fn],Un.prototype,"_handleMessage",null);class qn{constructor(e,t){this._worker=e,this._context=t}post(e){if(!this._worker)throw new Error("WorkerPoster: Worker is not initialized or creation failed. Cannot post message.");this._worker.postMessage(Object.assign(Object.assign({},e),{context:this._context}))}}class Vn extends it{constructor(e){super(e||"Unable to proceed due to unsupported extension command."),this.name="UnsupportedExtensionCommandError",this.type="unsupported_extension_command_error"}}class Gn extends it{constructor(e){super(e||"Unable to proceed due to unsupported extension query."),this.name="UnsupportedExtensionQueryError",this.type="unsupported_extension_query_error"}}!function(e){e.ReloadCheckout="EXTENSION:RELOAD_CHECKOUT",e.ShowLoadingIndicator="EXTENSION:SHOW_LOADING_INDICATOR",e.SetIframeStyle="EXTENSION:SET_IFRAME_STYLE",e.ReRenderShippingForm="EXTENSION:RE_RENDER_SHIPPING_FORM",e.ReRenderShippingStep="EXTENSION:RE_RENDER_SHIPPING_STEP"}(Bn||(Bn={})),function(e){e.GetConsignments="EXTENSION:GET_CONSIGNMENTS"}(jn||(jn={}));class Hn{constructor(e={},t={},n={}){this._workers=e,this._commandListeners=t,this._queryListeners=n}add(e,t){this._workers[e]=t}listenForCommand(e,t,n){const i=this._getWorkerById(e);this._commandListeners[e]||(this._commandListeners[e]=new Un(i));const r=this._commandListeners[e];r.listen();const o=this._validateCommand(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}listenForQuery(e,t,n){const i=this._getWorkerById(e);this._queryListeners[e]||(this._queryListeners[e]=new Un(i));const r=this._queryListeners[e];r.listen();const o=this._validateQuery(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}stopListen(e){this._commandListeners[e]&&this._commandListeners[e].stopListen(),this._queryListeners[e]&&this._queryListeners[e].stopListen()}post(e,t){if(!this._workers[e])throw new Error(`Worker with extensionId ${e} not found`);new qn(this._workers[e],e).post(t)}clearCacheById(e){delete this._workers[e]}_getWorkerById(e){const t=this._workers[e];if(!t)throw new Cn(`Worker with extensionId ${e} not found`);return t}_validateCommand(e){if(Object.values(Bn).includes(e))return e;throw new Vn}_validateQuery(e){if(Object.values(jn).includes(e))return e;throw new Gn}}function Wn(e){return In(0===e.hostname.indexOf("www")?e.href:e.href.replace(e.hostname,`www.${e.hostname}`))}var $n;class Yn{constructor(e){this._sourceOrigins=[In(e).origin,Wn(In(e)).origin],this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))}addListener(e,t){let n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)}removeListener(e,t){const n=this._listeners[e];if(!n)return;const i=n.indexOf(t);i>=0&&n.splice(i,1)}trigger(e,t){const n=this._listeners[e.type];n&&n.forEach(n=>t?n(e,t):n(e))}_handleMessage(e){if(-1===this._sourceOrigins.indexOf(e.origin)||!bn(e.data,e.data.type))return;const t=e.data,{context:n}=t,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([Fn],Yn.prototype,"_handleMessage",null);class Kn{constructor(e,t,n={},i={},r={}){this._store=e,this._workerExtensionMessenger=t,this._commandListeners=n,this._queryListeners=i,this._posters=r}clearCacheByRegion(e){const t=this._getExtensionByRegion(e);"worker"!==t.type?this.clearCacheById(t.id):this._workerExtensionMessenger.clearCacheById(t.id)}clearCacheById(e){const t=this._getExtensionById(e);"worker"!==t.type?(this._commandListeners[e]&&delete this._commandListeners[e],this._queryListeners[e]&&delete this._queryListeners[e],this._posters[e]&&delete this._posters[e]):this._workerExtensionMessenger.clearCacheById(t.id)}listenForCommand(e,t,n){const i=this._getExtensionById(e);if("worker"===i.type)return this._workerExtensionMessenger.listenForCommand(e,t,n);this._commandListeners[e]||(this._commandListeners[e]=new Yn(i.url));const r=this._commandListeners[e];r.listen();const o=this._validateCommand(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}listenForQuery(e,t,n){const i=this._getExtensionById(e);if("worker"===i.type)return this._workerExtensionMessenger.listenForQuery(e,t,n);this._queryListeners[e]||(this._queryListeners[e]=new Yn(i.url));const r=this._queryListeners[e];r.listen();const o=this._validateQuery(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}stopListen(e){"worker"!==this._getExtensionById(e).type?(this._commandListeners[e]&&this._commandListeners[e].stopListen(),this._queryListeners[e]&&this._queryListeners[e].stopListen()):this._workerExtensionMessenger.stopListen(e)}post(e,t){try{const n=this._getExtensionById(e);if("worker"===n.type)return void this._workerExtensionMessenger.post(e,t);this._posters[e]||(this._posters[e]=On(n)),this._posters[e].post(t)}catch(n){this.clearCacheById(e),console.log(`Unable to post event to extension(${e}) because extension iframe is not mounted.\nThe event that could not be delivered:`,t)}}_getExtensionById(e){var t;this._getExtensions();const n=null===(t=this._extensions)||void 0===t?void 0:t.find(t=>t.id===e);if(!n)throw new Cn(`Unable to proceed due to no extension found for ID: ${e}.`);return n}_getExtensionByRegion(e){var t;this._getExtensions();const n=null===(t=this._extensions)||void 0===t?void 0:t.find(t=>t.region===e);if(!n)throw new Cn(`Unable to proceed due to no extension found for region: ${e}.`);return n}_getExtensions(){if(this._extensions)return;const{extensions:{getExtensions:e}}=this._store.getState();if(this._extensions=e(),!this._extensions)throw new Cn("Extension configurations not found.")}_validateCommand(e){if(Object.values(Bn).includes(e))return e;throw new Vn}_validateQuery(e){if(Object.values(jn).includes(e))return e;throw new Gn}}class Jn{constructor(e,t,n){this._store=e,this._extensionMessenger=t,this._subscribers=n,this._subscribed={},this._unsubscribers={},this._listeners={}}listen(){var e;const{data:{getExtensions:t}}=this._store.getState();null===(e=t())||void 0===e||e.forEach(e=>{if(this._listeners[e.id])return;const t=new Yn(e.url);t.addListener(Tn.Subscribe,this._handleSubscribe.bind(this)),t.addListener(Tn.Unsubscribe,this._handleUnsubscribe.bind(this)),t.listen(),this._listeners[e.id]=t})}broadcast(e){var t;const{data:{getExtensions:n}}=this._store.getState();null===(t=n())||void 0===t||t.forEach(t=>{this._subscribed[t.id]&&this._extensionMessenger.post(t.id,e)})}_handleSubscribe({payload:{eventType:e,extensionId:t}}){this._subscribed[t]=!0,this._unsubscribers[e]||(this._unsubscribers[e]=this._subscribers[e](this._store,this))}_handleUnsubscribe({payload:{eventType:e,extensionId:t}}){var n,i;delete this._subscribed[t],Object.keys(this._subscribed).length||(null===(i=(n=this._unsubscribers)[e])||void 0===i||i.call(n),delete this._unsubscribers[e])}}!function(e){e.ConsignmentsChanged="EXTENSION:CONSIGNMENTS_CHANGED"}($n||($n={}));const Zn=(e,t)=>{var n;const{data:{getConsignments:i}}=e.getState();let r=null!==(n=i())&&void 0!==n?n:[];return e.subscribe(({data:{getConsignments:e}})=>{var n;const i=null!==(n=e())&&void 0!==n?n:[];i!==r&&(t.broadcast({type:$n.ConsignmentsChanged,payload:{consignments:i,previousConsignments:r}}),r=i)},({data:{getConsignments:e}})=>e())};class Qn extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}var Xn,ei;!function(e){e[e.MissingBillingAddress=0]="MissingBillingAddress",e[e.MissingCart=1]="MissingCart",e[e.MissingCheckout=2]="MissingCheckout",e[e.MissingConsignments=3]="MissingConsignments",e[e.MissingCustomer=4]="MissingCustomer",e[e.MissingCheckoutConfig=5]="MissingCheckoutConfig",e[e.MissingOrder=6]="MissingOrder",e[e.MissingOrderConfig=7]="MissingOrderConfig",e[e.MissingOrderId=8]="MissingOrderId",e[e.MissingPayment=9]="MissingPayment",e[e.MissingPaymentId=10]="MissingPaymentId",e[e.MissingPaymentInstrument=11]="MissingPaymentInstrument",e[e.MissingPaymentMethod=12]="MissingPaymentMethod",e[e.MissingPaymentRedirectUrl=13]="MissingPaymentRedirectUrl",e[e.MissingPaymentStatus=14]="MissingPaymentStatus",e[e.MissingPaymentToken=15]="MissingPaymentToken",e[e.MissingShippingAddress=16]="MissingShippingAddress"}(Xn||(Xn={}));class ti extends Qn{constructor(e){super(function(e){switch(e){case Xn.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case Xn.MissingCart:return"Unable to proceed because cart data is unavailable.";case Xn.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case Xn.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case Xn.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case Xn.MissingCheckoutConfig:case Xn.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case Xn.MissingOrder:return"Unable to proceed because order data is unavailable.";case Xn.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case Xn.MissingPayment:return"Unable to proceed because payment data is unavailable.";case Xn.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case Xn.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case Xn.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e)),this.subtype=e,this.name="MissingDataError",this.type="missing_data"}}function ni(e){return t=e.lineItems.physicalItems.filter(e=>!e.addedByPromotion),ye(t,(e,t)=>e+t.quantity,0);var t}function ii(e,t){if(null==e)throw t?t():new Error("An unexpected error has occurred.");return e}!function(e){e[e.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",e[e.CustomerNotInitialized=1]="CustomerNotInitialized",e[e.PaymentNotInitialized=2]="PaymentNotInitialized",e[e.ShippingNotInitialized=3]="ShippingNotInitialized",e[e.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(ei||(ei={}));class ri extends Qn{constructor(e){super(function(e){switch(e){case ei.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case ei.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case ei.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case ei.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.subtype=e,this.name="NotInitializedError",this.type="not_initialized"}}const oi={de:"eu",jp:"fe",uk:"eu",us:"na"};var ai,si,di,ci,li,ui;!function(e){e.en_US="en_US",e.en_GB="en_GB",e.de_DE="de_DE",e.fr_FR="fr_FR",e.it_IT="it_IT",e.es_ES="es_ES",e.ja_JP="ja_JP"}(ai||(ai={})),function(e){e.Home="Home",e.Product="Product",e.Cart="Cart",e.Checkout="Checkout",e.Other="Other"}(si||(si={})),function(e){e.USD="USD",e.EUR="EUR",e.GBP="GBP",e.JPY="JPY"}(di||(di={})),function(e){e.PayAndShip="PayAndShip",e.PayOnly="PayOnly"}(ci||(ci={})),function(e){e.Gold="Gold",e.LightGray="LightGray",e.DarkGray="DarkGray"}(li||(li={})),function(e){e.C0001="C0001"}(ui||(ui={}));var hi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pi{constructor(e){this.amazonPayV2ScriptLoader=e}initialize(e){return hi(this,void 0,void 0,function*(){this.amazonPayV2SDK=yield this.amazonPayV2ScriptLoader.load(e),this.buttonParentContainer=this.buttonParentContainer||this.createAmazonPayButtonParentContainer()})}deinitialize(){var e;return this.amazonPayV2Button=void 0,null===(e=this.buttonParentContainer)||void 0===e||e.remove(),this.buttonParentContainer=void 0,this.amazonPayV2SDK=void 0,Promise.resolve()}bindButton(e,t,n){this.getAmazonPayV2SDK().Pay.bindChangeAction(`#${e}`,{amazonCheckoutSessionId:t,changeAction:n})}createButton(e,t){this.amazonPayV2Button=this.getAmazonPayV2SDK().Pay.renderButton(`#${e}`,t)}prepareCheckout(e){const t=this.prepareRequestConfig(e);this.getAmazonPayV2Button().onClick(()=>{this.getAmazonPayV2Button().initCheckout(t)})}prepareCheckoutWithCreationRequestConfig(e){this.getAmazonPayV2Button().onClick(()=>hi(this,void 0,void 0,function*(){const t=yield e();if(t){const e=this.prepareRequestConfig(t.createCheckoutSessionConfig,t.estimatedOrderAmount,t.productType);this.getAmazonPayV2Button().initCheckout(e)}}))}signout(){return hi(this,void 0,void 0,function*(){return this.amazonPayV2SDK&&this.amazonPayV2SDK.Pay.signout(),Promise.resolve()})}renderAmazonPayButton({buttonColor:e,checkoutState:t,containerId:n,decoupleCheckoutInitiation:i=!1,methodId:r,options:o,placement:a,isButtonMicroTextDisabled:s=!1}){const d=document.querySelector(`#${n}`);if(!d)return;const{id:c}=d.appendChild(this.getButtonParentContainer());o&&s&&(o.design=ui.C0001);const l=null!=o?o:this.getAmazonPayV2ButtonOptions(t,r,a,i,e);return this.createButton(c,l),this.getButtonParentContainer()}updateBuyNowFlowFlag(e){this.isBuyNowFlow=Boolean(e)}isPh4Enabled(e,t){const n=!!e["PROJECT-3483.amazon_pay_ph4"],i=!!e["INT-6885.amazon_pay_ph4_us_only"];return n&&i?"US"===t:n}prepareRequestConfig(e,t,n){const{publicKeyId:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew ri(ei.PaymentNotInitialized))}getCheckoutState(e){return"object"==typeof(t=e)&&null!==t&&"cart"in t&&"checkout"in t&&"config"in t&&"paymentMethods"in t?{getCart:e.cart.getCart,getCheckout:e.checkout.getCheckout,getStoreConfigOrThrow:e.config.getStoreConfigOrThrow,getPaymentMethodOrThrow:t=>e.paymentMethods.getPaymentMethodOrThrow(t)}:e;var t}}class mi extends Qn{constructor(e){super(e||"Unable to proceed because the client library of a payment method is not loaded or ready to be used."),this.name="PaymentMethodClientUnavailableError",this.type="payment_method_client_unavailable"}}class yi{constructor(e,t=window){this.scriptLoader=e,this.windowWithAmazonPay=t}load(e){return t=this,n=void 0,r=function*(){const{initializationData:t}=e,n=(null==t?void 0:t.region)||"us",i=oi[n];if(yield this.scriptLoader.loadScript(`https://static-${i}.payments-amazon.com/checkout.js`),!this.windowWithAmazonPay.amazon)throw new mi;return this.windowWithAmazonPay.amazon},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}function gi(){return new pi(new yi(a()))}function vi(e,t){return Object.assign(e,{resolveIds:t})}class fi extends Qn{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class Si extends Qn{constructor(e){super(e||"Not implemented."),this.name="NotImplementedError",this.type="not_implemented"}}var _i=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class wi{constructor(e,t){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t}initialize(e){return _i(this,void 0,void 0,function*(){const{methodId:t,amazonpay:n}=e;if(!t||!(null==n?void 0:n.container))throw new fi('Unable to proceed because "methodId" or "containerId" argument is not provided.');let i;try{i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)}catch(e){yield this.paymentIntegrationService.loadPaymentMethod(t),i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)}yield this.amazonPayV2PaymentProcessor.initialize(i),this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:this.paymentIntegrationService.getState(),containerId:n.container,methodId:t,placement:si.Checkout})})}deinitialize(){return _i(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize()})}signIn(){throw new Si('In order to sign in via Amazon, the shopper must click on "Amazon Pay" button.')}signOut(e){return _i(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getPaymentId();t&&(yield this.amazonPayV2PaymentProcessor.signout(),yield this.paymentIntegrationService.remoteCheckoutSignOut(t.providerId,e))})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}}const Ii=vi(e=>new wi(e,gi()),[{id:"amazonpay"}]);function Ci(e,t,n=!0){var i;return null!==(i=e[t])&&void 0!==i?i:n}const bi="3.128.0",Pi="3.123.2",Oi="3.106.0";class Ei{constructor(e){this.paymentIntegrationService=e,this.braintreeWindow=window}getSDKVersion(){const e=this.paymentIntegrationService.getState().getStoreConfig(),t=(null==e?void 0:e.checkoutSettings.features)||{};return this.getPreloadedSDKVersion()||(Ci(t,"PAYPAL-5809.braintree_hosted_fields_fix_version")?bi:Ci(t,"PAYPAL-5636.update_braintree_sdk_version")?Pi:Oi)}getPreloadedSDKVersion(){const e=this.braintreeWindow.braintree;if(e){const t=B(Object.values(e),e=>!!e.VERSION);return null==t?void 0:t.VERSION}}}class Ai extends Qn{constructor(e){super(e||"Unsupported browser error"),this.name="UnsupportedBrowserError",this.type="unsupported_browser"}}var Ti,ki,Di,Mi,zi,Ni,xi;function Ri(e){return Boolean("object"==typeof e&&null!==e&&("type"in e||"message"in e||"code"in e))}!function(e){e.ESTIMATED="ESTIMATED",e.FINAL="FINAL",e.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(Ti||(Ti={})),function(e){e.Completed="COMPLETED",e.Pending="PENDING",e.Failed="FAILED"}(ki||(ki={})),function(e){e.TRUSTLY="trustly"}(Di||(Di={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="cancelled",e.UNRECOGNIZED="unrecognized"}(Mi||(Mi={})),function(e){e.Customer="CUSTOMER",e.Merchant="MERCHANT",e.Network="NETWORK",e.Internal="INTERNAL",e.Unknown="UNKNOWN"}(zi||(zi={})),function(e){e.KountNotEnabled="DATA_COLLECTOR_KOUNT_NOT_ENABLED"}(Ni||(Ni={})),function(e){e.Visa="visa",e.Mastercard="mastercard",e.AmericanExpress="american-express",e.DinersClub="diners-club",e.Discover="discover",e.Jcb="jcb",e.UnionPay="union-pay",e.Maestro="maestro",e.Elo="elo",e.Mir="mir",e.Hiper="hiper",e.Hipercard="hipercard"}(xi||(xi={}));var Fi,Li,Bi,ji=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ui{constructor(e){this.braintreeScriptLoader=e}initialize(e){this.setClientToken(e)}deinitialize(){return ji(this,void 0,void 0,function*(){yield this.teardownModule(this.dataCollector),this.dataCollector=void 0})}getClient(){return ji(this,void 0,void 0,function*(){if(!this.client){const e=this.getClientTokenOrThrow(),t=yield this.braintreeScriptLoader.loadClient();this.client=yield t.create({authorization:e})}return this.client})}getDataCollectorOrThrow(e){return ji(this,void 0,void 0,function*(){const t={deviceData:void 0,teardown:()=>Promise.resolve()};if(!this.dataCollector)try{const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadDataCollector(),i=Object.assign({client:t,kount:!0},e);this.dataCollector=yield n.create(i)}catch(e){if(Ri(e)&&e.code===Ni.KountNotEnabled)return t;throw e}return this.dataCollector})}getBraintreeGooglePayment(){return ji(this,void 0,void 0,function*(){if(!this.googlePayment){const[e,t]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.loadGooglePayment()]);this.googlePayment=yield t.create({client:e})}return this.googlePayment})}getBraintreeThreeDS(){return ji(this,void 0,void 0,function*(){if(!this.threeDS){const[e,t]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.load3DS()]);this.threeDS=yield t.create({client:e,version:2})}return this.threeDS})}getBraintreeLocalPayment(e){return ji(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment){const[t,n]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.loadLocalPayment()]);this.braintreeLocalPayment=yield new Promise((i,r)=>{n.create({client:t,merchantAccountId:e},(e,t)=>{e&&r(e),i(t)})})}return this.braintreeLocalPayment})}getUsBankAccount(){return ji(this,void 0,void 0,function*(){if(!this.usBankAccount){const e=yield this.getClient(),t=yield this.braintreeScriptLoader.loadUsBankAccount();this.usBankAccount=yield t.create({client:e})}return this.usBankAccount})}getBraintreeVisaCheckout(){return this.visaCheckout||(this.visaCheckout=Promise.all([this.getClient(),this.braintreeScriptLoader.loadVisaCheckout()]).then(([e,t])=>t.create({client:e}))),this.visaCheckout}getVisaCheckoutSdk(e){return ji(this,void 0,void 0,function*(){return this.visaCheckoutSDK||(this.visaCheckoutSDK=yield this.braintreeScriptLoader.loadVisaCheckoutSdk(e)),this.visaCheckoutSDK})}getVenmoCheckoutOrThrow(){return ji(this,void 0,void 0,function*(){if(!this.braintreeVenmo){const e=yield this.getClient(),t=yield this.braintreeScriptLoader.loadVenmoCheckout(),n={client:e,allowDesktop:!0,paymentMethodUsage:"multi_use"},i=yield t.create(n);if(!i.isBrowserSupported())throw new Ai;this.braintreeVenmo=i}return this.braintreeVenmo})}setClientToken(e){this.clientToken=e}getClientTokenOrThrow(){if(!this.clientToken)throw new ri(ei.PaymentNotInitialized);return this.clientToken}teardownModule(e){return e?e.teardown():Promise.resolve()}}!function(e){e.Sandbox="sandbox",e.Production="production"}(Fi||(Fi={})),function(e){e.Client="client",e.DataCollector="dataCollector",e.Fastlane="fastlane",e.GooglePayment="googlePayment",e.HostedFields="hostedFields",e.LocalPayment="localPayment",e.Paypal="paypal",e.PaypalCheckout="paypalCheckout",e.ThreeDSecure="threeDSecure",e.UsBankAccount="usBankAccount",e.Venmo="venmo",e.VisaCheckout="visaCheckout"}(Li||(Li={})),function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification"}(Bi||(Bi={}));const qi={[Oi]:{[Li.Client]:"sha384-26BXDNnJI23JYRyFBj4xe4sVNrUSSiSSu11kxVXNM/vEPONm4LuL00w6ZaTgQewt",[Li.PaypalCheckout]:"sha384-B+vzbZwnQtzWBthpkT4TXKUibO65tyeK7eCxSvpblgprTep2+IAXB2Cxxjrn710O",[Li.Paypal]:"sha384-uyAGL1/3+XJAHnGoNy4eCoXdzJ4f7Ilzp+6w9PNnEjs6DCCz9WMyJjMN1gzc78U+",[Li.LocalPayment]:"sha384-LIvOEMkIVEwVuYBdVOQc1AC5YbGGlwyfUheS0ACK218D2STuVYQlZ4FyEPowAEfT",[Li.DataCollector]:"sha384-1bo9JDz+Kscthc085cCKWur8CLwUoBpoNyxsDi7932mCl0zFq3A5mv+FQLw9GHpV",[Li.UsBankAccount]:"sha384-xmHBVaU+w74V+OebD3AaPONFxHUGMf+QRs8G/JxVPXNNP7MDa2jL0ICWHIe2tTfJ",[Li.GooglePayment]:"sha384-WKDJl8mqoP82qZpMGH6AbZxnvXnSW8ILV4M64CyMLiugGMwu7LyP89wjCkHqsiBe",[Li.ThreeDSecure]:"sha384-VQUlpGHzsGvs5XeiGFip7EXRsvoHWEXDVmgCacfbyieZI9mdBOqq3NSoyo28OCOB",[Li.VisaCheckout]:"sha384-yx7mADfzTN0T43Q6rlH49LIg1EJ0iUZgBp/EczX9LXsUGkySgxrD+nWHQRBkyfoT",[Li.Venmo]:"sha384-QX4rPjoj1ZDhuG0aSyKs56lEKDqTMTcjYxUHY1SzO5VZDsqIE2NTkqot7KNSCyov",[Li.HostedFields]:"sha384-VvYBACfSu0Cr/J32uKmxG7AXcNOJE1AzIIL3kbikyS7YKp5fz5Is+NzNP/lyauNy",[Li.Fastlane]:"sha384-9oGsZMRZwpGtDEDYa/dFt76dECqj1xAni9gIKgc3KfMIiRnR73nEeeUDLiBzxhFa"},[Pi]:{[Li.Client]:"sha384-o+nbQGcwNNxIBeXeu3+XmbSq+Cg8R3EN3N0l5hXCgMMU2RGY0t1z0LroSEIAbfAO",[Li.PaypalCheckout]:"sha384-WrfbWPBS4mH86GAoycPSgiH8hQ8KH7A67C93Hjhunv/xhNk2YpBn3wbFA4Fhg9U/",[Li.Paypal]:"sha384-VF389nvvrRUgDsTXMxTYORDtVegB9IQa3Cxr//DyJnLYnz8/X8VCzEvck2c+Megt",[Li.LocalPayment]:"sha384-tZKx2rEQbfmZpoPSY5VPmJEhaq4X75dLvwHMs3VE9U+C8lPyw+hWTIL1+GPvWCIH",[Li.DataCollector]:"sha384-E6k3wOpP7syCDDwaRDLF06942Y00NkbwJvWi2OQXwwKzGwG5fd3E7RFUvCCecfvO",[Li.UsBankAccount]:"sha384-258FON8LZGG0W9Qaz4Jij83pZHu30YnKjJA7gNulLBh6CclkucgF+tHDQuYFRYfW",[Li.GooglePayment]:"sha384-taJ2p/0+n0VH328POAoBiuEbL3tnHUTE9S42hK1V+Txs3X+QYjZOyKW35JgHRFfO",[Li.ThreeDSecure]:"sha384-+NSZH4Zj3sO5bdWvPKhU5N16QDxeueTVTnUVeleeESkhLSaz4Ob1hh/5myecc9Ym",[Li.VisaCheckout]:"sha384-66DiBjghxk1OmBj8aksN8gbQ+CwoQcx1vPfiXUN08g1iQVM+BwewF0p7toM3i7SS",[Li.Venmo]:"sha384-B5UwY42kE4RoLoWbQ7YpqosUlUad2/DlGWiw0HhoZbSPk30CQAaSA10ohyLDTkDU",[Li.HostedFields]:"sha384-Aw9EesSaUeWxe36PqEHiOyOyOq8M6CIb1gw7/yHNVPRzGtFXXcd2OQ8qXrIlOj2P",[Li.Fastlane]:"sha384-rhBL1hpZ71JqG+2TsT0Dih47mbjx8cjJCpeZjk9tw3df1gFMKfCTmMyZunhr7H4Y"},[bi]:{[Li.Client]:"sha384-0WNxksIpRP+fYZiIdr12g6DBUQfLDzYCQJZtR/C8KkcwSGhPHfcFp3tTaGcMyFTq",[Li.PaypalCheckout]:"sha384-lWM1jk4BOxoDNV6Kop7tVNvQgINlmEVz0c/OwM+HNHK3QC8xqwd54Ovrt2QRDTjh",[Li.Paypal]:"sha384-fXUmVxC2EMZBDXZ7eTHSTL/LFBrHej/MSXT/vTBXvra4lzgLNGvREAp+x0GYObuH",[Li.LocalPayment]:"sha384-pha1xGuGSkmZH5x9aqHvRaO4xLea7rmQ/79PFj9zxNzxuFcOWZg7gOP7FibygOEC",[Li.DataCollector]:"sha384-Q6PI2F9eekWbAxhroybl+aEcvqhdowN/EQlGwBUyJOzPFn9982u9xl6SU6XfGKzc",[Li.UsBankAccount]:"sha384-W3RLQSKJL1tQ3+Y7mP6tmkamtZ8bV4Yw/XxL9Jj5JtXHraD8loMF8hAIG5m2zK7F",[Li.GooglePayment]:"sha384-TITQMsFWA3elDNGP2mWz2oKBo4qjt+TlqzovcaPoeBiAh/wPBi6nae50ADdgU1/i",[Li.ThreeDSecure]:"sha384-YiycYN89ZlL/Evcaq4y1ajW1mhd7JYfZBDuOwHtIn4/Jnm20GL+/XCM+zYAwWD8D",[Li.VisaCheckout]:"sha384-/OdaTv9qrkKzjObtUe6yzfDhHozFW/+uXlrSl736sOZRJpjGQETvpYXqMFFg69xv",[Li.Venmo]:"sha384-dA+ojdW9vbJS4JavcXyOs9d5uZHJg5dNtYupoPSH2zsXIiYDVS5amLb/u8qmQ6oz",[Li.HostedFields]:"sha384-31ZkS58+iaWsW06ftW52zzVZFp43WPd7pNYRiddYynSNg6Oh7WGbSFGorAUH6T1z",[Li.Fastlane]:"sha384-jlbrwNvL3HvLAUCtLSmrnQ2GH1udCUrRS/bVmReAS5fuIVvcW8Pko/Gkg82tlgtr"}};var Vi,Gi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Hi{constructor(e,t,n){this.scriptLoader=e,this.braintreeHostWindow=t,this.braintreeSDKVersionManager=n}loadClient(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.Client,"client.min.js")})}loadFastlane(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.Fastlane,"fastlane.min.js")})}loadPaypalCheckout(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.PaypalCheckout,"paypal-checkout.min.js")})}loadPaypal(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.Paypal,"paypal.min.js")})}loadLocalPayment(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.LocalPayment,"local-payment.min.js")})}loadDataCollector(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.DataCollector,"data-collector.min.js")})}loadUsBankAccount(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.UsBankAccount,"us-bank-account.min.js")})}loadGooglePayment(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.GooglePayment,"google-payment.min.js")})}load3DS(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.ThreeDSecure,"three-d-secure.min.js")})}loadVisaCheckout(){return this.loadBraintreeModuleOrThrow(Li.VisaCheckout,"visa-checkout.min.js")}loadVenmoCheckout(){return this.loadBraintreeModuleOrThrow(Li.Venmo,"venmo.min.js")}loadHostedFields(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.HostedFields,"hosted-fields.min.js")})}loadVisaCheckoutSdk(e){return Gi(this,void 0,void 0,function*(){if(this.braintreeHostWindow.V)return this.braintreeHostWindow.V;const t=e?"sha384-0eu1s1GtqzXlL9DtLgmwzC5WWlEH/ADRM0n38cVQkvtT+W/gey96rcb1LwuUOPDm":"sha384-1f1csvP3ZFxg4dILH1GaY4LHlZ0oX7Rk83rxmLlwbnIi4TM0NYzXoev1VoEiVDS6";return this.scriptLoader.loadScript(`//${e?"sandbox-":""}assets.secure.checkout.visa.com/checkout-widget/resources/js/integration/v1/sdk.js`,{async:!0,attributes:{integrity:t,crossorigin:"anonymous"}}).then(()=>{if(!this.braintreeHostWindow.V)throw new mi;return this.braintreeHostWindow.V})})}loadBraintreeModuleOrThrow(e,t){return Gi(this,void 0,void 0,function*(){let n=this.getBraintreeModule(e);if(n)return n;const i=this.braintreeSDKVersionManager.getSDKVersion(),r=`//js.braintreegateway.com/web/${i}/js/${t}`,o=i in qi?this.getIntegrityValuesByModuleName(e,i):void 0;if(yield this.scriptLoader.loadScript(r,o?{async:!0,attributes:{integrity:o,crossorigin:"anonymous"}}:void 0),n=this.getBraintreeModule(e),!n)throw new mi;return n})}getBraintreeModule(e){var t;return null===(t=this.braintreeHostWindow.braintree)||void 0===t?void 0:t[e]}getIntegrityValuesByModuleName(e,t){const n=qi[t][e];if(!n)throw new Error("Unexpected fileName value");return n}}class Wi extends Qn{constructor(e){super(e||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}!function(e){e.BRAINTREE="braintree",e.BRAINTREE_FASTLANE="braintreeacceleratedcheckout"}(Vi||(Vi={}));var $i,Yi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}($i||($i={}));class Ki{constructor(e,t,n,i,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._braintreeSdk=i,this._applePayScriptLoader=r,this._onAuthorizeCallback=ce,this._onError=ce,this._onClick=ce,this._subTotalLabel=$i.Subtotal,this._shippingLabel=$i.Shipping,this._hasApplePaySession=!1}initialize(e){var t;return Yi(this,void 0,void 0,function*(){const{methodId:n,applepay:i}=e;if(!n||!i)throw new ti(Xn.MissingPaymentMethod);const{container:r,shippingLabel:o,subtotalLabel:a,onError:s=ce,onClick:d=ce,onPaymentAuthorize:c}=i;this._shippingLabel=o||$i.Shipping,this._subTotalLabel=a||$i.Subtotal,this._onAuthorizeCallback=c,this._onError=s,this._onClick=d;let l=this._paymentIntegrationService.getState();yield this._applePayScriptLoader.loadSdk();try{this._paymentMethod=l.getPaymentMethodOrThrow(n)}catch(e){l=yield this._paymentIntegrationService.loadPaymentMethod(n),this._paymentMethod=l.getPaymentMethodOrThrow(n)}yield this._paymentIntegrationService.verifyCheckoutSpamProtection(),this._applePayButton=this._createButton(r),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),(null===(t=this._paymentMethod.initializationData)||void 0===t?void 0:t.gateway)===Vi.BRAINTREE&&this._paymentMethod.clientToken&&this._braintreeSdk.initialize(this._paymentMethod.clientToken)})}deinitialize(){return Promise.resolve()}signIn(){throw new Si('In order to sign in via Apple, the shopper must click on "Apple Pay" button.')}signOut(){throw new Si("Need to do signout via apple.")}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}_createButton(e){const t=document.getElementById(e);if(!t)throw new fi("Unable to create sign-in button without valid container ID.");const n=this._createApplePayButtonElement();return t.appendChild(n),n}_createApplePayButtonElement(){const e=document.createElement("apple-pay-button");return e.setAttribute("buttonstyle","black"),e.setAttribute("type","plain"),e.setAttribute("style","--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;"),e}_handleWalletButtonClick(e){if(e.preventDefault(),this._hasApplePaySession)return;this._onClick();const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getStoreConfigOrThrow(),r=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new ti(Xn.MissingPaymentMethod);const o=this._getBaseRequest(n,r,i,this._paymentMethod),a=this._sessionFactory.create(o);this._handleApplePayEvents(a,this._paymentMethod,i),a.begin(),this._hasApplePaySession=!0}_getBaseRequest(e,t,n,i){var r;const{storeProfile:{storeCountryCode:o,storeName:a}}=n,{currency:{code:s,decimalPlaces:d}}=e,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=i,u=e.lineItems.physicalItems.length>0,h={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:o,currencyCode:s,merchantCapabilities:c,supportedNetworks:l,lineItems:[],total:u?{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"pending"}:{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"final"}};if(u)null===(r=h.requiredShippingContactFields)||void 0===r||r.push("postalAddress");else{const e=[{label:this._subTotalLabel,amount:`${t.subtotal.toFixed(d)}`}];t.taxes.forEach(t=>e.push({label:t.name,amount:`${t.amount.toFixed(d)}`})),h.lineItems=e}return h}_handleApplePayEvents(e,t,n){e.onvalidatemerchant=n=>Yi(this,void 0,void 0,function*(){try{const{body:i}=yield this._onValidateMerchant(t,n);e.completeMerchantValidation(i)}catch(e){this._onError(e)}}),e.onshippingcontactselected=t=>Yi(this,void 0,void 0,function*(){return this._handleShippingContactSelected(e,n,t)}),e.onshippingmethodselected=t=>Yi(this,void 0,void 0,function*(){return this._handleShippingMethodSelected(e,n,t)}),e.oncancel=()=>Yi(this,void 0,void 0,function*(){this._hasApplePaySession=!1;try{const e=`/remote-checkout/${t.id}/signout`;return yield this._requestSender.get(e),yield this._paymentIntegrationService.loadCheckout()}catch(e){return this._onError(new Wi)}}),e.onpaymentauthorized=n=>Yi(this,void 0,void 0,function*(){return this._onPaymentAuthorized(n,e,t)})}_handleShippingContactSelected(e,t,n){var i;return Yi(this,void 0,void 0,function*(){const r=this._transformContactToAddress(n.shippingContact);try{yield this._paymentIntegrationService.updateShippingAddress(r)}catch(t){return e.abort(),this._hasApplePaySession=!1,this._onError(t)}const{storeProfile:{storeName:o}}=t;let a=this._paymentIntegrationService.getState();const{currency:{decimalPlaces:s}}=a.getCartOrThrow();let d=a.getCheckoutOrThrow();const c=null===(i=d.consignments[0].selectedShippingOption)||void 0===i?void 0:i.id,l=d.consignments[0].availableShippingOptions,u=null==l?void 0:l.find(({id:e})=>e===c),h=null==l?void 0:l.filter(e=>e.id!==c),p=u?[{label:u.description,amount:`${u.cost.toFixed(s)}`,detail:u.additionalDescription,identifier:u.id}]:[];if(h&&[...h.filter(e=>e.isRecommended),...h.filter(e=>!e.isRecommended)].forEach(e=>p.push({label:e.description,amount:`${e.cost.toFixed(s)}`,detail:e.additionalDescription,identifier:e.id})),!(l instanceof Array))throw new Error("Shipping options not available.");if(0===l.length)return void e.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:o,amount:`${d.grandTotal.toFixed(s)}`},[]);const m=l.find(e=>e.isRecommended),y=m?m.id:l[0].id,g=u?u.id:y;try{yield this._updateShippingOption(g)}catch(e){return this._onError(e)}a=this._paymentIntegrationService.getState(),d=a.getCheckoutOrThrow(),e.completeShippingContactSelection({newShippingMethods:p,newTotal:{type:"final",label:o,amount:`${d.grandTotal.toFixed(s)}`},newLineItems:this._getUpdatedLineItems(d,s)})})}_handleShippingMethodSelected(e,t,n){return Yi(this,void 0,void 0,function*(){const{storeProfile:{storeName:i}}=t,{shippingMethod:{identifier:r}}=n;try{yield this._updateShippingOption(r)}catch(t){return e.abort(),this._hasApplePaySession=!1,this._onError(t)}const o=this._paymentIntegrationService.getState(),{currency:{decimalPlaces:a}}=o.getCartOrThrow(),s=o.getCheckoutOrThrow();e.completeShippingMethodSelection({newTotal:{type:"final",label:i,amount:`${s.grandTotal.toFixed(a)}`},newLineItems:this._getUpdatedLineItems(s,a)})})}_getUpdatedLineItems(e,t){const n=[{label:this._subTotalLabel,amount:`${e.subtotal.toFixed(t)}`}];return e.taxes.forEach(e=>n.push({label:e.name,amount:`${e.amount.toFixed(t)}`})),n.push({label:this._shippingLabel,amount:`${e.shippingCostTotal.toFixed(t)}`}),n}_updateShippingOption(e){return Yi(this,void 0,void 0,function*(){return this._paymentIntegrationService.selectShippingOption(e)})}_onValidateMerchant(e,t){return Yi(this,void 0,void 0,function*(){const n=[`validationUrl=${t.validationURL}`,`merchantIdentifier=${e.initializationData.merchantId}`,`displayName=${e.initializationData.storeName}`,`domainName=${window.location.hostname}`].join("&");return this._requestSender.post(`${e.initializationData.paymentsUrl}/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})})}_onPaymentAuthorized(e,t,n){var i;return Yi(this,void 0,void 0,function*(){const{token:r,billingContact:o,shippingContact:a}=e.payment,s=this._paymentIntegrationService.getState().getCartOrThrow().lineItems.physicalItems.length>0;let d;(null===(i=n.initializationData)||void 0===i?void 0:i.gateway)===Vi.BRAINTREE&&(d=yield this._getBraintreeDeviceData());const c={methodId:n.id,paymentData:{deviceSessionId:d,formattedPayload:{apple_pay_token:{payment_data:r.paymentData,payment_method:r.paymentMethod,transaction_id:r.transactionIdentifier}}}},l=this._transformContactToAddress(o),u=this._transformContactToAddress(a),h=null==a?void 0:a.emailAddress,p=(null==a?void 0:a.phoneNumber)||"";try{return yield this._paymentIntegrationService.updateBillingAddress(Object.assign(Object.assign({},l),{email:h,phone:p})),s&&(yield this._paymentIntegrationService.updateShippingAddress(u)),yield this._paymentIntegrationService.submitOrder({useStoreCredit:!1}),yield this._paymentIntegrationService.submitPayment(c),t.completePayment(ApplePaySession.STATUS_SUCCESS),this._onAuthorizeCallback()}catch(e){return t.completePayment(ApplePaySession.STATUS_FAILURE),this._onError(e)}})}_transformContactToAddress(e){return{firstName:(null==e?void 0:e.givenName)||"",lastName:(null==e?void 0:e.familyName)||"",city:(null==e?void 0:e.locality)||"",company:"",address1:(null==e?void 0:e.addressLines)&&e.addressLines[0]||"",address2:(null==e?void 0:e.addressLines)&&e.addressLines[1]||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||"",phone:(null==e?void 0:e.phoneNumber)||"",stateOrProvince:(null==e?void 0:e.administrativeArea)||"",stateOrProvinceCode:(null==e?void 0:e.administrativeArea)||"",customFields:[]}}_getBraintreeDeviceData(){return Yi(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}function Ji(e){if(!function(e){return"ApplePaySession"in e}(e))throw new Error("Apple pay is not supported")}class Zi{create(e){return Ji(window),new ApplePaySession(1,e)}}class Qi{constructor(e){this.scriptLoader=e,this.sdkVersion="1.latest"}loadSdk(){return e=this,t=void 0,i=function*(){(function(e){return"ApplePaySDK"in e})(window)||(yield this.scriptLoader.loadScript(`https://applepay.cdn-apple.com/jsapi/${this.sdkVersion}/apple-pay-sdk.js`),Ji(window))},new((n=void 0)||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())});var e,t,n,i}}const Xi=vi(e=>{const{getHost:t}=e.getState(),i=new Ei(e);return new Ki(n({host:t()}),e,new Zi,new Ui(new Hi(a(),window,i)),new Qi(new r))},[{id:"applepay"}]);class er extends Qn{constructor(e){super(e||"An unexpected error has occurred during buy now cart creation process. Please try again later."),this.name="BuyNowCartCreationError",this.type="buy_now_cart_creation_error"}}const tr={body:{},headers:{},status:0};class nr extends Qn{constructor(e,{message:t,errors:n}={}){const{body:i,headers:r,status:o}=e||tr;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=i,this.headers=r,this.status=o,this.errors=n||[]}}var ir,rr,or,ar,sr,dr,cr;!function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(ir||(ir={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(rr||(rr={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(or||(or={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(ar||(ar={})),function(e){e.pill="pill",e.rect="rect"}(sr||(sr={})),function(e){e.OXXO="oxxo"}(dr||(dr={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(cr||(cr={}));var lr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ur{constructor(e,t,n,i){this.formPoster=e,this.paymentIntegrationService=t,this.bigCommercePaymentsRequestSender=n,this.bigCommercePaymentsScriptLoader=i}loadPayPalSdk(e,t,n,i){return lr(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e);return this.paypalSdk=yield this.bigCommercePaymentsScriptLoader.getPayPalSDK(a,o,n,i),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new mi;return this.paypalSdk}createBuyNowCartOrThrow(e){return lr(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}})}createOrder(e,t){return lr(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:n},t));return i})}createOrderCardFields(e,t){return lr(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i,setupToken:r}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:n},t));return Object.assign({orderId:i},r?{setupToken:r}:{})})}updateOrder(){return lr(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getConsignmentsOrThrow()[0];try{yield this.bigCommercePaymentsRequestSender.updateOrder({availableShippingOptions:n.availableShippingOptions,cartId:t.id,selectedShippingOption:n.selectedShippingOption})}catch(e){throw new nr}})}getOrderStatus(e,t){return lr(this,void 0,void 0,function*(){try{const{status:n}=yield this.bigCommercePaymentsRequestSender.getOrderStatus(e,t);return n}catch(e){throw new nr}})}tokenizePayment(e,t){const n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new ti(Xn.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===xt.BuyNow&&{cart_id:n.id}))}submitPayment(e,t,n){return lr(this,void 0,void 0,function*(){const i={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}};yield this.paymentIntegrationService.submitPayment(Object.assign({methodId:e,paymentData:i},n?{gatewayId:n}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],i=n.find(e=>e.isRecommended),r=(e?n.find(t=>t.id===e):n.find(e=>{var n;return e.id===(null===(n=t.selectedShippingOption)||void 0===n?void 0:n.id)}))||i||n[0];if(!r)throw new Error("Your order can't be shipped to this address");return r}getAddress(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:(null==e?void 0:e.phone)||"",company:"",address1:(null==e?void 0:e.address1)||"",address2:(null==e?void 0:e.address2)||"",city:(null==e?void 0:e.city)||"",countryCode:(null==e?void 0:e.countryCode)||"",postalCode:(null==e?void 0:e.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==e?void 0:e.stateOrProvinceCode)||"",customFields:[]}}getBillingAddressFromOrderDetails({payer:e}){var t,n;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,address2:e.address.address_line_2,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1,phone:null===(n=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===n?void 0:n.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:n}=e,{address:i,name:{full_name:r}}=n[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:i.address_line_1,address2:i.address_line_2,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})}getValidButtonStyle(e){const{color:t,height:n,label:i,shape:r}=e||{},o={color:t&&ar[t]?t:void 0,height:this.getValidHeight(n),label:i&&or[i]?i:void 0,shape:r&&sr[r]?r:void 0};return ue(o,J)}getValidHeight(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40}removeElement(e){const t=e&&document.getElementById(e);t&&(t.style.display="none")}}const hr="This API endpoint is for internal use only and may change in the future";var pr;!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(pr||(pr={}));const mr=pr,yr={"X-Checkout-SDK-Version":"1.909.5"};var gr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vr{constructor(e){this.requestSender=e}createOrder(e,t){return gr(this,void 0,void 0,function*(){const n=`/api/storefront/payment/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.post(n,{headers:r,body:i})).body})}updateOrder(e){return gr(this,void 0,void 0,function*(){const t=e,n=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.put("/api/storefront/initialization/bigcommerce_payments",{headers:n,body:t})).body})}getOrderStatus(e="bigcommerce_payments",t){return gr(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body})}}var fr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Sr{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,n,i){return fr(this,void 0,void 0,function*(){const r=this.getPayPalSdkScriptConfigOrThrow(e,t,n);return this.loadPayPalSDK(r,i)})}loadPayPalSDK(e,t=!1){return fr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsPayPalSDK||t){const t=this.transformConfig(e.options),n=this.transformConfig(e.attributes),i=`https://www.paypal.com/sdk/js?${new URLSearchParams(t).toString()}`;yield this.scriptLoader.loadScript(i,{async:!0,attributes:n})}if(!this.window.bigCommercePaymentsPayPalSDK)throw new mi;return this.window.bigCommercePaymentsPayPalSDK})}getPayPalSdkScriptConfigOrThrow(e,t,n=!0){const{id:i,clientToken:r,initializationData:o}=e;if(!(null==o?void 0:o.clientId))throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:c,attributionId:l,isVenmoEnabled:u,isHostedCheckoutEnabled:h,isPayPalCreditAvailable:p,isDeveloperModeApplicable:m,availableAlternativePaymentMethods:y=[],enabledAlternativePaymentMethods:g=[],isGooglePayEnabled:v}=o,f=h||n,S="bigcommerce_payments_creditcards"===i,_=S?["card"]:[],w=S?[]:["card"],I=p?["credit","paylater"]:[],C=p?[]:["credit","paylater"],b=u?["venmo"]:[],P=u?[]:["venmo"],O=y.filter(e=>!g.includes(e)),E=v?["googlepay"]:[],A=n?["card-fields"]:[],T=this.filterFundingOptions([...w,...C,...P,...O]),k=this.filterFundingOptions([..._,...I,...b,...g]);return{options:Object.assign({"client-id":s,"merchant-id":d,"enable-funding":k.length>0?k:void 0,"disable-funding":T.length>0?T:void 0,commit:f,components:["buttons","hosted-fields","payment-fields","legal",...E,...A],currency:t,intent:a},m&&{"buyer-country":c}),attributes:{"data-partner-attribution-id":l,"data-client-token":r,"data-namespace":"bigCommercePaymentsPayPalSDK"}}}filterFundingOptions(e){const t=["klarna","afterpay"];return e?e.filter(e=>!t.includes(e)):[]}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}const _r=e=>{const{getHost:t}=e.getState();return new ur(Ee(),e,new vr(n({host:t()})),new Sr(a()))},wr=40;var Ir=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Cr{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=ce}initialize(e){return Ir(this,void 0,void 0,function*(){const{bigcommerce_payments:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.bigcommerce_payments.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.bigcommerce_payments.onClick" argument is not a function.');this.onError=t.onError||ce,this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Ir(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return Ir(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){var n,i;const{container:r,onClick:o,onComplete:a}=t,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:c,paymentButtonStyles:l,isAppSwitchEnabled:u=!1}=d.initializationData||{},{checkoutTopButtonStyles:h}=l||{},p=Object.assign(Object.assign(Object.assign({},u&&{appSwitchWhenAvailable:!0}),{createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)}),o&&{onClick:()=>o()}),m=Object.assign(Object.assign({},!u&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(t,n)=>this.onHostedCheckoutApprove(t,n,e,a)}),y=Object.assign(Object.assign({fundingSource:s.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},h),{height:wr}))},p),c&&m),g=s.Buttons(y);g.isEligible()?(null===(n=g.hasReturned)||void 0===n?void 0:n.call(g))&&u?null===(i=g.resume)||void 0===i||i.call(g):g.render(`#${r}`):this.bigCommercePaymentsIntegrationService.removeElement(r)}onHostedCheckoutApprove(e,t,n,i){return Ir(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Ir(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}onShippingOptionsChange(e){return Ir(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const br=vi(e=>new Cr(e,_r(e)),[{id:"bigcommerce_payments"}]);var Pr,Or,Er,Ar,Tr,kr,Dr,Mr,zr,Nr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class xr{constructor(e){this.scriptLoader=e,this.window=window}getPayPalFastlaneSdk(e,t,n){return Nr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsFastlaneSdk){const i=this.getPayPalFastlaneSdkConfiguration(e,t,n);if(yield this.loadPayPalSdk(i),!this.window.bigCommercePaymentsFastlaneSdk)throw new mi}return this.window.bigCommercePaymentsFastlaneSdk})}getPayPalGooglePaySdk(e,t,n,i){return Nr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsGooglePay||i){const i=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n);yield this.loadPayPalSdk(i)}if(!this.window.bigCommercePaymentsGooglePay)throw new mi;return this.window.bigCommercePaymentsGooglePay})}getPayPalApmsSdk(e,t){return Nr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsApms){const n=this.getPayPalApmSdkConfiguration(e,t);if(yield this.loadPayPalSdk(n),!this.window.bigCommercePaymentsApms)throw new mi}return this.window.bigCommercePaymentsApms})}getPayPalMessages(e,t){return Nr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsMessages){const n=this.getPayPalSdkMessagesConfiguration(e,t);yield this.loadPayPalSdk(n)}if(!this.window.bigCommercePaymentsMessages)throw new mi;return this.window.bigCommercePaymentsMessages})}loadPayPalSdk({options:e,attributes:t}){return Nr(this,void 0,void 0,function*(){const n=this.transformConfig(e),i=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(n).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:i})})}getPayPalFastlaneSdkConfiguration(e,t,n){const{clientToken:i,initializationData:r}=e;if(!r||!r.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,attributionId:d}=r;return{options:{"client-id":a,"merchant-id":s,commit:!0,components:["fastlane","three-domain-secure"],currency:t,intent:o},attributes:{"data-client-metadata-id":n.replace(/-/g,""),"data-namespace":"bigCommercePaymentsFastlaneSdk","data-partner-attribution-id":d,"data-sdk-client-token":i}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n=!0){const{clientToken:i,initializationData:r}=e;if(!r||!r.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,buyerCountry:d,attributionId:c,isHostedCheckoutEnabled:l,isDeveloperModeApplicable:u}=r,h=l||n;return{options:Object.assign({"client-id":a,"merchant-id":s,commit:h,components:["googlepay"],currency:t,intent:o},u&&{"buyer-country":d}),attributes:{"data-partner-attribution-id":c,"data-client-token":i,"data-namespace":"bigCommercePaymentsGooglePay"}}}getPayPalApmSdkConfiguration(e,t){const{initializationData:n}=e;if(!n||!n.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:i,clientId:r,merchantId:o,buyerCountry:a,attributionId:s,isDeveloperModeApplicable:d,availableAlternativePaymentMethods:c=[],enabledAlternativePaymentMethods:l=[]}=n,u=this.filterFundingOptions(l),h=this.filterFundingOptions(c.filter(e=>!l.includes(e)));return{options:Object.assign({"client-id":r,"merchant-id":o,"enable-funding":u.length>0?u:void 0,"disable-funding":h.length>0?h:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:i},d&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":s,"data-namespace":"bigCommercePaymentsApms"}}}getPayPalSdkMessagesConfiguration(e,t){const{initializationData:n}=e;if(!n||!n.clientId)throw new ti(Xn.MissingPaymentMethod);const{clientId:i,merchantId:r,attributionId:o,isDeveloperModeApplicable:a,buyerCountry:s}=n;return{options:Object.assign({"client-id":i,"merchant-id":r,components:["messages"],currency:t},a&&{"buyer-country":s}),attributes:{"data-namespace":"bigCommercePaymentsMessages","data-partner-attribution-id":o}}}filterFundingOptions(e){const t=["klarna","afterpay"];return e?e.filter(e=>!t.includes(e)):[]}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}function Rr(){return new xr(o())}!function(e){e.CVV="cvv",e.PAN="pan"}(Pr||(Pr={}));class Fr{static get(e){const t=`${encodeURIComponent(`${e}`)}=`,n=document.cookie;let i=null;const r=n.indexOf(t);if(r>-1){let e=n.indexOf(";",r);-1===e&&(e=n.length),i=decodeURIComponent(n.substring(r+t.length,e))}return i}static set(e,t,n={secure:!0}){let i=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;const{expires:r,path:o,domain:a,secure:s}=n;if(r)i+=`; expires=${r.toUTCString()}`;else{const e=new Date,t=60;e.setTime(e.getTime()+60*t*1e3),i+=`; expires=${e.toUTCString()}`}o&&(i+=`; path=${o}`),a&&(i+=`; domain=${a}`),s&&(i+="; secure"),document.cookie=i}static remove(e,t){Fr.set(e,"",Object.assign({expires:new Date(0)},t))}}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Or||(Or={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(Er||(Er={})),function(e){e.Always="SCA_ALWAYS"}(Ar||(Ar={})),function(e){e.Succeeded="succeeded",e.Cancelled="cancelled",e.Errored="errored"}(Tr||(Tr={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(kr||(kr={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(Dr||(Dr={})),function(e){e.pill="pill",e.rect="rect"}(Mr||(Mr={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="canceled",e.UNRECOGNIZED="unrecognized"}(zr||(zr={}));var Lr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Br{constructor(){this.window=window}initializePayPalFastlane(e,t,n){return Lr(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("fastlaneEnv","sandbox"),window.localStorage.setItem("axoEnv","sandbox")),!this.window.bigCommercePaymentsFastlane){const t={root:{backgroundColorPrimary:"transparent"}};this.window.bigCommercePaymentsFastlane=yield e.Fastlane({styles:n||t})}return this.window.bigCommercePaymentsFastlane})}getPayPalFastlaneOrThrow(){if(!this.window.bigCommercePaymentsFastlane)throw new mi;return this.window.bigCommercePaymentsFastlane}lookupCustomerOrThrow(e){return Lr(this,void 0,void 0,function*(){return this.getPayPalFastlaneOrThrow().identity.lookupCustomerByEmail(e)})}triggerAuthenticationFlowOrThrow(e){return Lr(this,void 0,void 0,function*(){return e?this.getPayPalFastlaneOrThrow().identity.triggerAuthenticationFlow(e):{}})}updateStorageSessionId(e){const t=new Date;t.setDate(t.getDate()+14);const n={expires:t,secure:!0};Fr.set("bc-fastlane-sessionId",e,n)}removeStorageSessionId(){Fr.remove("bc-fastlane-sessionId")}getStorageSessionId(){return Fr.get("bc-fastlane-sessionId")||""}mapPayPalFastlaneProfileToBcCustomerData(e,t){var n,i,r;const{authenticationState:o,profileData:a}=t,s=null===(r=null===(i=null===(n=null==a?void 0:a.card)||void 0===n?void 0:n.paymentSource)||void 0===i?void 0:i.card)||void 0===r?void 0:r.billingAddress,d=null==a?void 0:a.shippingAddress,c=null==a?void 0:a.name,l=null==a?void 0:a.card,u=d?this.mapPayPalToBcAddress(d.address,d.name,d.phoneNumber):void 0,h=s&&c?this.mapPayPalToBcAddress(s,c,null==d?void 0:d.phoneNumber):void 0,p=l?this.mapPayPalToBcInstrument(e,l):[],m=this.filterAddresses([u,h]);return{authenticationState:o||zr.UNRECOGNIZED,addresses:m,billingAddress:h,shippingAddress:u,instruments:p}}mapPayPalToBcInstrument(e,t){const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a}=i.card,[s,d]=o.split("-");return[{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:Pr.PAN,type:"card"}]}mapBcToPayPalAddress(e){return{company:(null==e?void 0:e.company)||"",addressLine1:(null==e?void 0:e.address1)||"",addressLine2:(null==e?void 0:e.address2)||"",adminArea1:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",adminArea2:(null==e?void 0:e.city)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||""}}mapPayPalToBcAddress(e,t,n,i){const[r,o]=t.fullName.split(" "),a=(null==n?void 0:n.nationalNumber)||"",s=(null==n?void 0:n.countryCode)||"";return{id:Date.now(),type:"paypal-address",firstName:t.firstName||r||"",lastName:t.lastName||o||"",company:e.company||"",address1:e.addressLine1,address2:e.addressLine2||"",city:e.adminArea2,stateOrProvince:e.adminArea1,stateOrProvinceCode:e.adminArea1,country:e.countryCode||"",countryCode:e.countryCode||"",postalCode:e.postalCode,phone:s+a,customFields:i||[]}}filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this.isEqualAddresses(e,t))?e:[...e,t]:e,[])}isEqualAddresses(e,t){return Y(this.normalizeAddress(e),this.normalizeAddress(t))}normalizeAddress(e){return le(e,["id","phone"])}}function jr(){return new Br}function Ur(e){return"string"!=typeof e}function qr(e,t){if(t||e)return function(e){var t,n;const i={},r=ue(e.root,Ur),o=ue(e.input,Ur),a=ue(e.toggle,Ur),s=ue(null===(t=e.text)||void 0===t?void 0:t.body,Ur),d=ue(null===(n=e.text)||void 0===n?void 0:n.caption,Ur),c=e.branding;return Object.keys(r).length&&(i.root=r),Object.keys(o).length&&(i.input=o),Object.keys(a).length&&(i.toggle=a),Object.keys(s).length&&(i.text={},i.text.body=s),Object.keys(d).length&&(i.text=Object.assign({},i.text),i.text.caption=d),c&&(i.branding=c),i}(function(e,t){var n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,_,w,I,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(c=null==t?void 0:t.input)||void 0===c?void 0:c.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.focusBorderColor),backgroundColor:(null==e?void 0:e.fastlaneInputSettingsBackgroundColor)||(null===(u=null==t?void 0:t.input)||void 0===u?void 0:u.backgroundColor),borderWidth:(null==e?void 0:e.fastlaneInputSettingsBorderWidth)||(null===(h=null==t?void 0:t.input)||void 0===h?void 0:h.borderWidth),textColorBase:(null==e?void 0:e.fastlaneInputSettingsTextColorBase)||(null===(p=null==t?void 0:t.input)||void 0===p?void 0:p.textColorBase)},toggle:{colorPrimary:(null==e?void 0:e.fastlaneToggleSettingsColorPrimary)||(null===(m=null==t?void 0:t.toggle)||void 0===m?void 0:m.colorPrimary),colorSecondary:(null==e?void 0:e.fastlaneToggleSettingsColorSecondary)||(null===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(S=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===S?void 0:S.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(w=null===(_=null==t?void 0:t.text)||void 0===_?void 0:_.caption)||void 0===w?void 0:w.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(I=null==t?void 0:t.text)||void 0===I?void 0:I.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var Vr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Gr{constructor(e,t,n){this.paymentIntegrationService=e,this.bigCommercePaymentsSdk=t,this.bigCommercePaymentsFastlaneUtils=n}initialize(e){var t;return Vr(this,void 0,void 0,function*(){const{methodId:n,bigcommerce_payments_fastlane:i}=e;if(!n)throw new fi('Unable to proceed because "methodId" argument is not provided.');try{yield this.paymentIntegrationService.loadPaymentMethod(n);const e=this.paymentIntegrationService.getState(),r=e.getCartOrThrow(),o=e.getPaymentMethodOrThrow(n),a=!!(null===(t=o.initializationData)||void 0===t?void 0:t.isDeveloperModeApplicable),s=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(o,r.currency.code,r.id);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(s,a,this.getFastlaneStyles(n,i))}catch(e){}return Promise.resolve()})}deinitialize(){return Vr(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return Vr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:void 0,addresses:void 0,instruments:void 0}),this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId()})}signOut(e){return Vr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return Vr(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:n,methodId:i}=e||{};if(!i)throw new fi('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof n)throw new fi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(this.paymentIntegrationService.getState().getCustomerOrThrow().isGuest){t&&"function"==typeof t&&t();try{yield this.runPayPalAuthenticationFlowOrThrow(i)}catch(e){}}n()})}runPayPalAuthenticationFlowOrThrow(e){return Vr(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow().id,i=t.getCustomer(),r=t.getBillingAddress(),o=(null==i?void 0:i.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(a),d=s.authenticationState===zr.CANCELED;yield this.updateCustomerDataState(e,s),d?this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId():this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(n)})}updateCustomerDataState(e,t){var n;return Vr(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow(),{authenticationState:r,addresses:o,billingAddress:a,shippingAddress:s,instruments:d}=this.bigCommercePaymentsFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,t);if(yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:r,addresses:o,instruments:d}),a&&(yield this.paymentIntegrationService.updateBillingAddress(a)),s&&i.lineItems.physicalItems.length>0){const t=yield this.paymentIntegrationService.updateShippingAddress(s),i=t.getPaymentMethodOrThrow(e),{isFastlaneShippingOptionAutoSelectEnabled:r}=i.initializationData||{},o=t.getConsignments()||[],a=(null===(n=o[0])||void 0===n?void 0:n.availableShippingOptions)||[],d=a[0],c=a.find(e=>e.isRecommended);if((c||d)&&r){const e=(null==c?void 0:c.id)||d.id;yield this.paymentIntegrationService.selectShippingOption(e)}}})}getFastlaneStyles(e,t){const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{fastlaneStyles:i,isFastlaneStylingEnabled:r}=n.initializationData||{};return qr(r?i:{},null==t?void 0:t.styles)}}const Hr=vi(e=>new Gr(e,Rr(),jr()),[{id:"bigcommerce_payments_fastlane"},{id:"bigcommerce_payments_creditcards"}]);var Wr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class $r{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=ce}initialize(e){return Wr(this,void 0,void 0,function*(){const{bigcommerce_payments_paylater:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater.onClick" argument is not a function.');this.onError=t.onError||ce,this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC BigCommercePayments PayLater]: button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Wr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Wr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){const{container:n,onComplete:i,onClick:r}=t,o=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:s,paymentButtonStyles:d}=a.initializationData||{},{checkoutTopButtonStyles:c}=d||{},l=Object.assign({createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},r&&{onClick:()=>r()}),u={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(t,n)=>this.onHostedCheckoutApprove(t,n,e,i)},h=[o.FUNDING.PAYLATER,o.FUNDING.CREDIT];let p=!1;h.forEach(e=>{if(!p){const t=Object.assign(Object.assign({fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},c),{height:wr}))},l),s&&u),i=o.Buttons(t);i.isEligible()&&(i.render(`#${n}`),p=!0)}}),p||this.bigCommercePaymentsIntegrationService.removeElement(n)}onHostedCheckoutApprove(e,t,n,i){return Wr(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Wr(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}onShippingOptionsChange(e){return Wr(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const Yr=vi(e=>new $r(e,_r(e)),[{id:"bigcommerce_payments_paylater"}]);var Kr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Jr{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return Kr(this,void 0,void 0,function*(){const{bigcommerce_payments_venmo:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC Payments Venmo]: Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Kr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Kr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){const{container:n,onClick:i}=t,r=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:a}=o.initializationData||{},{checkoutTopButtonStyles:s}=a||{},d=Object.assign({fundingSource:r.FUNDING.VENMO,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},s),{height:wr})),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},i&&{onClick:()=>i()}),c=r.Buttons(d);c.isEligible()?c.render(`#${n}`):this.bigCommercePaymentsIntegrationService.removeElement(n)}}const Zr=vi(e=>new Jr(e,_r(e)),[{id:"bigcommerce_payments_venmo"}]);class Qr extends Qn{constructor(e){super(e||"Unable to proceed because the client library of a payment method has thrown an unexpected error."),this.name="PaymentMethodFailedError",this.type="payment_method_client_invalid"}}class Xr extends nr{constructor(e){super(e,{message:"There is a problem processing your payment. Please try again later."}),this.name="PaymentMethodInvalidError",this.type="payment_method_invalid"}}var eo,to,no,io=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ro{constructor(e,t){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=window}initialize(e){var t;return io(this,void 0,void 0,function*(){const{methodId:n,bolt:i}=e,{onInit:r}=i||{};if(!n)throw new fi('Unable to proceed because "methodId" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n);if(!(null===(t=o.initializationData)||void 0===t?void 0:t.publishableKey))throw new ti(Xn.MissingPaymentMethod);const{developerConfig:a,publishableKey:s}=o.initializationData;if(yield this.boltScriptLoader.loadBoltClient(s,o.config.testMode,a),r&&"function"==typeof r){const e=this.getCustomerEmail();r(yield this.hasBoltAccount(e),e)}})}deinitialize(){return Promise.resolve()}signIn(e,t){return io(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return io(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){return io(this,void 0,void 0,function*(){const{continueWithCheckoutCallback:t=I,checkoutPaymentMethodExecuted:n,methodId:i}=e||{},r=this.getCustomerEmail();if(!i)throw new fi('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof t)throw new fi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(r)return this.openBoltCheckoutModalOrThrow(r,i,t,n);t()})}openBoltCheckoutModalOrThrow(e,t,n,i){var r;return io(this,void 0,void 0,function*(){const o=this.getBoltClientOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethod(t);try{if(null===(r=null==a?void 0:a.initializationData)||void 0===r?void 0:r.embeddedOneClickEnabled){const t=yield this.hasBoltAccount(e);if(t){const t={close:()=>{n()}};yield o.openCheckout(e,t)}else n();"function"==typeof i&&i({hasBoltAccount:t})}else n()}catch(e){if(function(e){return"string"==typeof e.message&&"string"==typeof e.type&&("string"==typeof e.subtype||!e.subtype)&&e instanceof Error}(e)&&"MissingDataError"!==e.name&&"NotInitializedError"!==e.name)throw new Qr(e.message);throw e}})}getBoltClientOrThrow(){const e=this.boltHostWindow.BoltCheckout;if(!e)throw new ri(ei.PaymentNotInitialized);return e}hasBoltAccount(e){return io(this,void 0,void 0,function*(){const t=this.getBoltClientOrThrow();try{return yield t.hasBoltAccount(e)}catch(e){throw new Xr}})}getCustomerEmail(){const e=this.paymentIntegrationService.getState(),t=e.getCustomer(),n=e.getBillingAddress();return(null==t?void 0:t.email)||(null==n?void 0:n.email)||""}}!function(e){e.SandboxMode="bolt_sandbox",e.StagingMode="bolt_staging",e.DevelopmentMode="bolt_development"}(eo||(eo={})),function(e){e.Small="small",e.Medium="medium",e.Large="large"}(to||(to={})),function(e){e.Pill="pill",e.Rect="rect"}(no||(no={}));var oo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ao{constructor(e,t=window){this.scriptLoader=e,this.boltHostWindow=t}loadBoltClient(e,t,n,i,r){return oo(this,void 0,void 0,function*(){if(this.boltHostWindow.BoltCheckout)return this.boltHostWindow.BoltCheckout;if(!e)throw new fi('Unable to initialize payment because "publishableKey" argument is not provided.');if(yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,n)}/connect-bigcommerce.js`,this.getScriptOptions("bolt-connect",e,i,r)),yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,n)}/track.js`,this.getScriptOptions("bolt-track",e)),!this.boltHostWindow.BoltCheckout)throw new mi;return this.boltHostWindow.BoltCheckout})}loadBoltEmbedded(e,t,n){return oo(this,void 0,void 0,function*(){if(yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,n)}/embed.js`,{async:!0,attributes:{id:"bolt-embedded"}}),!this.boltHostWindow.Bolt)throw new mi;return this.boltHostWindow.Bolt(e)})}getDomainURL(e,t){if(!e)return"connect.bolt.com";if(t)switch(t.developerMode){case eo.StagingMode:return"connect-staging.bolt.com";case eo.DevelopmentMode:return`connect.${t.developerDomain}`}return"connect-sandbox.bolt.com"}getScriptOptions(e,t,n,i){return{async:!0,attributes:Object.assign(Object.assign({id:e,"data-publishable-key":t},n&&{"data-shopping-cart-id":n}),i&&{"data-storefront-api-token":i})}}}const so=vi(e=>new ro(e,new ao(a())),[{id:"bolt"}]);class co extends fi{constructor(e){let t="Unable to submit payment for the order because the payload is invalid.";e&&(t=`${t} Make sure the following fields are provided correctly: ${e.join(", ")}.`),super(t),this.name="PaymentArgumentInvalidError"}}class lo extends Qn{constructor(e,t){super(t||"Unable to proceed because the payment form contains invalid data."),this.details=e,this.name="PaymentInvalidFormError",this.type="payment_invalid_form"}}let uo=null;const ho=["buttons","messages"];var po,mo,yo,go,vo,fo;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(po||(po={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(mo||(mo={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black",e.WHITE="white"}(yo||(yo={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(go||(go={})),function(e){e.PILL="pill",e.RECT="rect"}(vo||(vo={})),function(e){e.CART="cart",e.HOME="homepage",e.PAYMENT="payment",e.PRODUCT="product"}(fo||(fo={}));var So=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class _o{constructor(e,t,n){this.braintreeScriptLoader=e,this.braintreeHostWindow=t,this.overlay=n,this.dataCollectors={}}initialize(e,t){this.clientToken=e,this.threeDSecureOptions=t}getBraintreeFastlane(e,t,n){return So(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("axoEnv","sandbox"),window.localStorage.setItem("fastlaneEnv","sandbox")),!this.braintreeHostWindow.braintreeFastlane){const t=this.getClientTokenOrThrow(),i=yield this.getClient(),r=yield this.getSessionId(e),o=yield this.braintreeScriptLoader.loadFastlane(),a={root:{backgroundColorPrimary:"transparent"}};this.braintreeHostWindow.braintreeFastlane=yield o.create({authorization:t,client:i,deviceData:r,styles:n||a})}return this.braintreeHostWindow.braintreeFastlane})}getClient(){return So(this,void 0,void 0,function*(){if(!this.client){const e=this.getClientTokenOrThrow(),t=yield this.braintreeScriptLoader.loadClient();this.client=t.create({authorization:e})}return this.client})}getPaypal(){return this.braintreePaypal||(this.braintreePaypal=Promise.all([this.getClient(),this.braintreeScriptLoader.loadPaypal()]).then(([e,t])=>t.create({client:e}))),this.braintreePaypal}paypal(e){var{shouldSaveInstrument:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{var r;return i&&(null===(r=this.overlay)||void 0===r||r.show({onClick:()=>e.focusWindow()})),e.tokenize(Object.assign({enableShippingAddress:!0,flow:t?"vault":"checkout",useraction:"commit"},n))}).then(e=>{var t;return null===(t=this.overlay)||void 0===t||t.remove(),e}).catch(e=>{var t;throw null===(t=this.overlay)||void 0===t||t.remove(),e})}getPaypalCheckout(e,t,n){return So(this,void 0,void 0,function*(){const i=yield this.getClient(),r=yield this.braintreeScriptLoader.loadPaypalCheckout(),o={client:i};return this.paypalCheckout=yield r.create(o,(i,r)=>{var o;if(i)return n(i);const a=Object.assign(Object.assign({currency:e.currency},e.isCreditEnabled&&{"enable-funding":"paylater"}),{components:ho.toString(),intent:e.intent,commit:null===(o=e.commit)||void 0===o||o});this.braintreeHostWindow.paypal?t(r):function(e,t){return uo||(uo=new Promise((n,i)=>{e.loadPayPalSDK(t,t=>{t?(uo=null,i(t)):n(e)})})),uo}(r,a).then(()=>t(r))}),this.paypalCheckout})}getDataCollector(e){return So(this,void 0,void 0,function*(){const t=(null==e?void 0:e.paypal)?"paypal":"default";let n=this.dataCollectors[t];if(!n){try{const t=yield this.getClient(),i=yield this.braintreeScriptLoader.loadDataCollector(),r=Object.assign({client:t,kount:!0},e);n=yield i.create(r)}catch(e){if(!Ri(e)||"DATA_COLLECTOR_KOUNT_NOT_ENABLED"!==e.code)throw e;n={deviceData:void 0,teardown:()=>Promise.resolve()}}this.dataCollectors[t]=n}return n})}getBraintreeEnv(e=!1){return e?Fi.Sandbox:Fi.Production}mapToBraintreeShippingAddressOverride(e){return{recipientName:`${e.firstName} ${e.lastName}`,line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,postalCode:e.postalCode,countryCode:e.countryCode,phone:e.phone}}mapToLegacyShippingAddress(e){const{email:t,phone:n,shippingAddress:i}=e,r=(null==i?void 0:i.recipientName)||"",[o,a]=r.split(" ");return{email:t,first_name:o||"",last_name:a||"",phone_number:n,address_line_1:null==i?void 0:i.line1,address_line_2:null==i?void 0:i.line2,city:null==i?void 0:i.city,state:null==i?void 0:i.state,country_code:null==i?void 0:i.countryCode,postal_code:null==i?void 0:i.postalCode}}mapToLegacyBillingAddress(e){const{billingAddress:t,email:n,firstName:i,lastName:r,phone:o,shippingAddress:a}=e,s=t||a;return{email:n,first_name:i,last_name:r,phone_number:o,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}}removeElement(e){const t=e&&document.getElementById(e);t&&t.remove()}getSessionId(e){return So(this,void 0,void 0,function*(){const{deviceData:t}=yield this.getDataCollector({riskCorrelationId:e});return t})}teardown(){return So(this,void 0,void 0,function*(){yield this.teardownModule(this.dataCollectors.default),yield this.teardownModule(this.dataCollectors.paypal),this.dataCollectors={},yield this.teardownModule(this.paypalCheckout),this.paypalCheckout=void 0})}get3DS(){return So(this,void 0,void 0,function*(){return this.threeDS||(this.threeDS=Promise.all([this.getClient(),this.braintreeScriptLoader.load3DS()]).then(([e,t])=>t.create({client:e,version:2}))),this.threeDS})}getVenmoCheckout(e){return So(this,void 0,void 0,function*(){if(!this.venmoCheckout){const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadVenmoCheckout(),i=Object.assign({client:t,allowDesktop:!0,paymentMethodUsage:"multi_use"},e||{});this.venmoCheckout=yield new Promise((e,t)=>{n.create(i,(n,i)=>n?t(n):i.isBrowserSupported()?void e(i):t(new Ai))})}return this.venmoCheckout})}verifyCard(e,t,n){return So(this,void 0,void 0,function*(){const i=yield this.tokenizeCard(e,t);return this.challenge3DSVerification(i,n)})}tokenizeCard(e,t){return So(this,void 0,void 0,function*(){const{paymentData:n}=e;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"object"==typeof t.ccExpiry&&null!==t.ccExpiry&&"string"==typeof t.ccNumber&&"string"==typeof t.ccName}(n))throw new co(["payment.paymentData"]);const i=this.getErrorsRequiredFields(n);if(!$(i))throw new lo(i);const r=this.mapToCreditCard(n,t),o=yield this.getClient(),{creditCards:a}=yield o.request(r);return{nonce:a[0].nonce,bin:a[0].details.bin}})}challenge3DSVerification(e,t){return So(this,void 0,void 0,function*(){const n=yield this.get3DS();return this.present3DSChallenge(n,t,e)})}teardownModule(e){return e?e.teardown():Promise.resolve()}getClientTokenOrThrow(){if(!this.clientToken)throw new ri(ei.PaymentNotInitialized);return this.clientToken}getErrorsRequiredFields(e){const{ccNumber:t,ccExpiry:n}=e,i={};return t||(i.ccNumber=[{message:"Credit card number is required",type:"required"}]),n||(i.ccExpiry=[{message:"Expiration date is required",type:"required"}]),i}mapToCreditCard(e,t){return{data:{creditCard:{cardholderName:e.ccName,number:e.ccNumber,cvv:e.ccCvv,expirationDate:`${e.ccExpiry.month}/${e.ccExpiry.year}`,options:{validate:!1},billingAddress:t&&{countryCodeAlpha2:t.countryCode,locality:t.city,countryName:t.country,postalCode:t.postalCode,streetAddress:t.address2?`${t.address1} ${t.address2}`:t.address1}}},endpoint:"payment_methods/credit_cards",method:"post"}}present3DSChallenge(e,t,n){const{nonce:i,bin:r}=n;if(!this.threeDSecureOptions||!i)throw new ri(ei.PaymentNotInitialized);const{addFrame:o,removeFrame:a,challengeRequested:s=!0,additionalInformation:d}=this.threeDSecureOptions,c=()=>So(this,void 0,void 0,function*(){const t=yield e.cancelVerifyCard();return u.cancel(new Wi),t}),l=t.toFixed(2),u=new En(e.verifyCard({addFrame:(e,t)=>{o&&o(e,t,c)},amount:Number(l),bin:r,challengeRequested:s,nonce:i,removeFrame:a,onLookupComplete:(e,t)=>{t()},collectDeviceData:!0,additionalInformation:d}));return u.promise}}var wo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Io{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return wo(this,void 0,void 0,function*(){const{braintreepaypal:t,methodId:n}=e,{container:i,onError:r}=t||{};if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.braintreepaypal.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(n),!o.clientToken)throw new ti(Xn.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(n),o=a.getPaymentMethodOrThrow(n)}const{clientToken:s,config:d,initializationData:c}=o,{paymentButtonStyles:l}=c||{},{checkoutTopButtonStyles:u}=l||{};if(!s||!c)throw new ti(Xn.MissingPaymentMethod);const h={currency:a.getCartOrThrow().currency.code,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{this.renderPayPalButton(e,t,n,Boolean(d.testMode),u)},e=>this.handleError(e,i,r))})}deinitialize(){return wo(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}signIn(e,t){return wo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return wo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderPayPalButton(e,t,n,i,r){const{container:o,onClick:a=ce}=t,{paypal:s}=this.braintreeHostWindow,d=null==s?void 0:s.FUNDING.PAYPAL;if(s&&d){const c=s.Buttons({env:this.braintreeIntegrationService.getBraintreeEnv(i),fundingSource:d,style:Object.assign(Object.assign({},r),{height:wr}),createOrder:()=>this.setupPayment(e,t,n),onApprove:i=>this.tokenizePayment(i,e,n,t),onClick:a});c.isEligible()&&c.render(`#${o}`)}else this.braintreeIntegrationService.removeElement(o)}setupPayment(e,t,n){var i;return wo(this,void 0,void 0,function*(){try{yield this.paymentIntegrationService.loadDefaultCheckout();const t=this.paymentIntegrationService.getState(),r=t.getCheckoutOrThrow().outstandingBalance,o=t.getCartOrThrow().currency.code,a=t.getCustomer(),s=t.getPaymentMethodOrThrow(n),d=null==a?void 0:a.addresses[0],c=d?this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(d):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:c,amount:r,currency:o,offerCredit:!1,intent:null===(i=s.initializationData)||void 0===i?void 0:i.intent})}catch(e){const{container:n,onError:i}=t;this.handleError(e,n,i)}})}tokenizePayment(e,t,n,i){return wo(this,void 0,void 0,function*(){try{const{deviceData:i}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),r=yield t.tokenizePayment(e),{details:o,nonce:a}=r,s=this.braintreeIntegrationService.mapToLegacyBillingAddress(o),d=this.braintreeIntegrationService.mapToLegacyShippingAddress(o);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:n,action:"set_external_checkout",nonce:a,device_data:i,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:n}=i;this.handleError(e,t,n)}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const Co=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t);return new Io(e,Ee(),i,t)},[{id:"braintreepaypal"}]);var bo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Po{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return bo(this,void 0,void 0,function*(){const{braintreepaypalcredit:t,methodId:n}=e,{container:i,onError:r}=t||{};if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(n),!o.clientToken)throw new ti(Xn.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(n),o=a.getPaymentMethodOrThrow(n)}const{clientToken:s,config:d,initializationData:c}=o,{paymentButtonStyles:l}=c||{},{checkoutTopButtonStyles:u}=l||{};if(!s||!c)throw new ti(Xn.MissingPaymentMethod);const h={currency:a.getCartOrThrow().currency.code,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{this.renderPayPalButton(e,t,n,Boolean(d.testMode),Object.assign(Object.assign({},u),{height:wr}))},e=>this.handleError(e,i,r))})}deinitialize(){return bo(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}signIn(e,t){return bo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return bo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderPayPalButton(e,t,n,i,r){const{container:o,onClick:a=ce}=t,{paypal:s}=this.braintreeHostWindow;let d=!1;s&&[s.FUNDING.PAYLATER,s.FUNDING.CREDIT].forEach(c=>{if(!d){const l=s.Buttons({env:i?"sandbox":"production",fundingSource:c,style:r,createOrder:()=>this.setupPayment(e,t,n),onApprove:i=>this.tokenizePayment(i,e,n,t),onClick:a});l.isEligible()&&(l.render(`#${o}`),d=!0)}}),s&&d||this.braintreeIntegrationService.removeElement(o)}setupPayment(e,t,n){var i;return bo(this,void 0,void 0,function*(){try{yield this.paymentIntegrationService.loadDefaultCheckout();const t=this.paymentIntegrationService.getState(),r=t.getCheckoutOrThrow().outstandingBalance,o=t.getCartOrThrow().currency.code,a=t.getCustomer(),s=t.getPaymentMethodOrThrow(n),d=null==a?void 0:a.addresses[0],c=d?this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(d):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:c,amount:r,currency:o,offerCredit:!0,intent:null===(i=s.initializationData)||void 0===i?void 0:i.intent})}catch(e){const{container:n,onError:i}=t;this.handleError(e,n,i)}})}tokenizePayment(e,t,n,i){return bo(this,void 0,void 0,function*(){try{const{deviceData:i}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),r=yield t.tokenizePayment(e),{details:o,nonce:a}=r,s=this.braintreeIntegrationService.mapToLegacyBillingAddress(o),d=this.braintreeIntegrationService.mapToLegacyShippingAddress(o);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:n,action:"set_external_checkout",nonce:a,device_data:i,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:n}=i;this.handleError(e,t,n)}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const Oo=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t);return new Po(e,Ee(),i,t)},[{id:"braintreepaypalcredit"}]);function Eo(e){return"string"!=typeof e}function Ao(e,t){if(t||e)return function(e){var t,n;const i={},r=ue(e.root,Eo),o=ue(e.input,Eo),a=ue(e.toggle,Eo),s=ue(null===(t=e.text)||void 0===t?void 0:t.body,Eo),d=ue(null===(n=e.text)||void 0===n?void 0:n.caption,Eo),c=e.branding;return Object.keys(r).length&&(i.root=r),Object.keys(o).length&&(i.input=o),Object.keys(a).length&&(i.toggle=a),Object.keys(s).length&&(i.text={},i.text.body=s),Object.keys(d).length&&(i.text=Object.assign({},i.text),i.text.caption=d),c&&(i.branding=c),i}(function(e,t){var n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,_,w,I,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(c=null==t?void 0:t.input)||void 0===c?void 0:c.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.focusBorderColor),backgroundColor:(null==e?void 0:e.fastlaneInputSettingsBackgroundColor)||(null===(u=null==t?void 0:t.input)||void 0===u?void 0:u.backgroundColor),borderWidth:(null==e?void 0:e.fastlaneInputSettingsBorderWidth)||(null===(h=null==t?void 0:t.input)||void 0===h?void 0:h.borderWidth),textColorBase:(null==e?void 0:e.fastlaneInputSettingsTextColorBase)||(null===(p=null==t?void 0:t.input)||void 0===p?void 0:p.textColorBase)},toggle:{colorPrimary:(null==e?void 0:e.fastlaneToggleSettingsColorPrimary)||(null===(m=null==t?void 0:t.toggle)||void 0===m?void 0:m.colorPrimary),colorSecondary:(null==e?void 0:e.fastlaneToggleSettingsColorSecondary)||(null===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(S=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===S?void 0:S.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(w=null===(_=null==t?void 0:t.text)||void 0===_?void 0:_.caption)||void 0===w?void 0:w.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(I=null==t?void 0:t.text)||void 0===I?void 0:I.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var To=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ko{constructor(e,t){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.isAcceleratedCheckoutEnabled=!1}initialize({methodId:e,braintreefastlane:t}){var n;return To(this,void 0,void 0,function*(){if(!e)throw new fi('Unable to proceed because "methodId" argument is not provided.');const i=yield this.getValidPaymentMethodOrThrow(e),{isAcceleratedCheckoutEnabled:r,isFastlaneStylingEnabled:o}=i.initializationData||{},a=o?null===(n=i.initializationData)||void 0===n?void 0:n.fastlaneStyles:void 0;this.isAcceleratedCheckoutEnabled=!!r;try{if(this.isAcceleratedCheckoutEnabled){const e=Ao(a,null==t?void 0:t.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(i.id,e)}}catch(e){}return Promise.resolve()})}deinitialize(){return To(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return To(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return To(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return To(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:n}=e||{};if("function"!=typeof n)throw new fi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');const i=this.paymentIntegrationService.getState().getCustomerOrThrow();if(this.isAcceleratedCheckoutEnabled&&i.isGuest){const e=yield this.shouldRunAuthenticationFlow();t&&"function"==typeof t&&t(),e&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow(void 0,!0))}n()})}shouldRunAuthenticationFlow(){var e;return To(this,void 0,void 0,function*(){const t="braintreeacceleratedcheckout";try{yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t);return(null===(e=n.initializationData)||void 0===e?void 0:e.shouldRunAcceleratedCheckout)||!1}catch(e){return!1}})}getValidPaymentMethodOrThrow(e){return To(this,void 0,void 0,function*(){let t=e;try{yield this.paymentIntegrationService.loadPaymentMethod(t)}catch(n){t="braintree"===e?"braintreeacceleratedcheckout":"braintree",yield this.paymentIntegrationService.loadPaymentMethod(t)}return this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)})}}var Do=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Mo{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}getDeviceSessionId(){return Do(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getCart();return this.braintreeIntegrationService.getSessionId(null==e?void 0:e.id)})}initializeBraintreeFastlaneOrThrow(e,t){return Do(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getCart(),{clientToken:r,config:o}=n.getPaymentMethodOrThrow(e);if(!r)throw new ti(Xn.MissingPaymentMethod);this.methodId=e,this.braintreeIntegrationService.initialize(r),this.braintreeFastlane=yield this.braintreeIntegrationService.getBraintreeFastlane(null==i?void 0:i.id,o.testMode,t)})}getBraintreeFastlaneOrThrow(){if(!this.braintreeFastlane)throw new mi;return this.braintreeFastlane}getBraintreeFastlaneComponentOrThrow(){return this.getBraintreeFastlaneOrThrow().FastlaneCardComponent}runPayPalAuthenticationFlowOrThrow(e,t){var n;return Do(this,void 0,void 0,function*(){try{const i=this.getMethodIdOrThrow(),r=this.getBraintreeFastlaneOrThrow(),{lookupCustomerByEmail:o,triggerAuthenticationFlow:a}=r.identity,s=this.paymentIntegrationService.getState(),d=s.getCartOrThrow(),c=s.getCustomer(),l=s.getBillingAddress(),{isFastlaneShippingOptionAutoSelectEnabled:u}=s.getPaymentMethodOrThrow(i).initializationData||{},h=e||(null==c?void 0:c.email)||(null==l?void 0:l.email)||"",{customerContextId:p}=yield o(h);if(!p)return yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:Mi.UNRECOGNIZED,addresses:[],instruments:[]}),void this.saveSessionIdToCookies(d.id);const{authenticationState:m,profileData:y}=yield a(p),g=(null===(n=null==y?void 0:y.shippingAddress)||void 0===n?void 0:n.phoneNumber)||"";if(m===Mi.CANCELED)return yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:[],instruments:[]}),void this.removeSessionIdFromCookies();const v=this.mapPayPalToBcAddress([y.shippingAddress],[g])||[],f=this.getPayPalBillingAddresses(y),S=f?this.mapPayPalToBcAddress([f],[g]):[],_=y.card?this.mapPayPalToBcInstrument(i,[y.card]):[],w=this.mergeShippingAndBillingAddresses(v,S);if(this.saveSessionIdToCookies(d.id),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:w,instruments:_}),S.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateBillingAddress(S[0])),S.length>0&&d.lineItems.digitalItems.length>0&&0===d.lineItems.physicalItems.length){const{firstName:e,lastName:t}=w[0],n=Object.assign(Object.assign({},S[0]),{firstName:e,lastName:t});yield this.paymentIntegrationService.updateBillingAddress(n)}v.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateShippingAddress(v[0]),t&&u&&(yield this.setShippingOption()))}catch(e){}})}getSessionIdFromCookies(){return Fr.get("bc-fastlane-sessionId")||""}saveSessionIdToCookies(e){const t=new Date;t.setDate(t.getDate()+14),Fr.set("bc-fastlane-sessionId",e,{expires:t,secure:!0})}removeSessionIdFromCookies(){Fr.remove("bc-fastlane-sessionId")}mapPayPalToBcInstrument(e,t){if(t)return t.map(t=>{const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a,binDetails:s}=i.card,[d,c]=o.split("-");return{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:c,expiryYear:d,iin:(null==s?void 0:s.bin)||"",last4:a,method:e,provider:e,trustedShippingAddress:!1,type:"card",untrustedShippingCardVerificationMode:Pr.PAN}})}mapPayPalToBcAddress(e,t){if(!e)return[];const n=this.paymentIntegrationService.getState().getCountries()||[],i=e=>{const t=n.find(t=>t.code===e);return(null==t?void 0:t.name)||""};return e.map(e=>({id:Date.now(),type:"paypal-address",firstName:e.firstName||"",lastName:e.lastName||"",company:e.company||"",address1:e.streetAddress,address2:e.extendedAddress||"",city:e.locality,stateOrProvince:e.region,stateOrProvinceCode:e.region,country:i(e.countryCodeAlpha2),countryCode:e.countryCodeAlpha2,postalCode:e.postalCode,phone:t&&t[0]||"",customFields:[]}))}getPayPalBillingAddresses(e){const{card:t,name:n}=e||{};if(!t)return;const{firstName:i,lastName:r}=t.paymentSource.card.billingAddress,{firstName:o,lastName:a}=n||{},{shippingAddress:s}=e||{},d=Object.assign(Object.assign({},t.paymentSource.card.billingAddress),{firstName:i||o,lastName:r||a});return s&&Y(this.normalizeAddress(d),this.normalizeAddress(s))?s:d}normalizeAddress(e){return le(e,["id"])}mergeShippingAndBillingAddresses(e,t){const n=t.filter(t=>!e.some(e=>Y(this.normalizeAddress(e),this.normalizeAddress(t))));return[...e,...n]}getMethodIdOrThrow(){if(!this.methodId)throw new fi('Unable to proceed because "methodId" argument is not provided.');return this.methodId}setShippingOption(){var e;return Do(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getConsignments()||[],n=(null===(e=t[0])||void 0===e?void 0:e.availableShippingOptions)||[],i=n.find(e=>e.isRecommended);if(i||n.length){const e=i||n[0];yield this.paymentIntegrationService.selectShippingOption(e.id)}})}}const zo=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t),r=new Mo(e,i);return new ko(e,r)},[{id:"braintreeacceleratedcheckout"},{id:"braintree"}]);var No=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class xo{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n,this.buttonClassName="visa-checkout-wrapper",this.onError=ce}initialize(e){return No(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:n}=e;if(!n)throw new fi('Unable to proceed because "methodId" argument is not provided.');if(!t)throw new fi('Unable to proceed because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState(),r=i.getCheckoutOrThrow(),{clientToken:o,config:a}=i.getPaymentMethodOrThrow(n),s=i.getStoreConfigOrThrow();if(!o)throw new ti(Xn.MissingPaymentMethod);this.braintreeSdk.initialize(o);const d=yield this.braintreeSdk.getBraintreeVisaCheckout(),c=yield this.braintreeSdk.getVisaCheckoutSdk(a.testMode),{container:l,onError:u}=t;this.onError=u||ce;const h=d.createInitOptions({paymentRequest:{currencyCode:s.currency.code,subtotal:String(r.subtotal)},settings:{locale:s.storeProfile.storeLanguage,shipping:{collectShipping:!0}}}),p=this.createSignInButton(l,this.buttonClassName);yield c.init(h),c.on("payment.success",e=>this.tokenizePayment(d,e).then(()=>this.paymentIntegrationService.loadCheckout()).catch(e=>this.handleError(e))),c.on("payment.error",(e,t)=>this.handleError(t)),p.style.visibility="visible"})}deinitialize(){return No(this,void 0,void 0,function*(){yield this.braintreeSdk.deinitialize()})}signIn(){throw new Si('In order to sign in via VisaCheckout, the shopper must click on "Visa Checkout" button.')}signOut(e){return No(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}tokenizePayment(e,t){return No(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const n=this.paymentIntegrationService.getState(),i=n.getShippingAddress(),r=n.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(i),billingAddress:a=this.mapToVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}postForm(e,t){const{userData:n,billingAddress:i,shippingAddress:r,details:o}=e,{userEmail:a}=n,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,i)),shipping_address:JSON.stringify(this.getAddress(a,r))})}mapToVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}createSignInButton(e,t){const n=document.querySelector(`#${e}`);if(!n)throw new Error("Unable to proceed because the provided container ID is not valid.");return this.insertVisaCheckoutButton(n,t)}insertVisaCheckoutButton(e,t){const n=document.createElement("div");return n.style.display="flex",n.style.flexDirection="column",n.style.visibility="hidden",n.style.width="max-content",n.className=t,n.innerHTML='\n \n Tell Me More',e.appendChild(n),n}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const Ro=vi(e=>{const t=window,n=new Ei(e),i=new Ui(new Hi(a(),t,n));return new xo(e,Ee(),i)},[{id:"braintreevisacheckout"}]);class Fo{constructor(e){if(!e)throw new Error("Currency settings missing");const{decimalPlaces:t,symbolLocation:n,symbol:i,thousandsSeparator:r,decimalSeparator:o}=e;if("string"!=typeof n||"string"!=typeof i||"string"!=typeof r||"string"!=typeof o||"string"!=typeof t)throw new fi("Invalid currency settings provided");this._decimalPlaces=parseInt(t,10),this._symbolLocation=n,this._symbol=i,this._thousandsSeparator=r,this._decimalSeparator=o}format(e){if("number"!=typeof e)throw new fi("Invalid amount provided");const t=this._formatNumber(e),n=this._formatCurrency(t);return e<0?`-${n}`:n}_formatNumber(e){const t=Math.abs(e),[n,i=""]=this._toFixed(t,this._decimalPlaces).split("."),r=n.replace(/\B(?=(\d{3})+(?!\d))/g,this._thousandsSeparator);return this._decimalPlaces<1?r:[r,i].join(this._decimalSeparator)}_formatCurrency(e){return"left"===this._symbolLocation.toLowerCase()?`${this._symbol}${e}`:`${e}${this._symbol}`}_toFixed(e,t){return(+`${Math.round(+`${e}e${t}`)}e${-t}`).toFixed(t)}}let Lo=class{constructor(e){this._storeConfig=e,this._customerFormatter=new Fo(this._storeConfig.shopperCurrency),this._storeFormatter=new Fo(this._storeConfig.currency)}toCustomerCurrency(e){const t=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(e*t)}toStoreCurrency(e){return this._storeFormatter.format(e)}};Lo=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],Lo);const Bo=Lo,jo=(e,t)=>!!e&&(!!e.lineItems.physicalItems.some(e=>e.isShippingRequired)||!(!t||!e.lineItems.customItems)&&e.lineItems.customItems.length>0);function Uo(){if("undefined"==typeof window)return!1;if(function(e){return"ReactNativeWebView"in e}(window))return!0;const e=navigator.userAgent||navigator.vendor||(function(e){return"opera"in e}(window)?window.opera:""),t=/android.+; wv/i.test(e),n=/iPhone|iPod|iPad/i.test(e)&&/AppleWebKit/i.test(e)&&!/Safari/i.test(e);return t||n}var qo,Vo,Go,Ho,Wo,$o,Yo,Ko,Jo;function Zo(e){return e in $o}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(qo||(qo={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Vo||(Vo={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(Go||(Go={})),function(e){e.pill="pill",e.rect="rect"}(Ho||(Ho={})),function(e){e.ESTIMATED="ESTIMATED",e.FINAL="FINAL",e.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(Wo||(Wo={})),function(e){e.AMEX="AMEX",e.DISCOVER="DISCOVER",e.INTERAC="INTERAC",e.JCB="JCB",e.MC="MASTERCARD",e.VISA="VISA"}($o||($o={})),function(e){e.OFFER="OFFER",e.PAYMENT_AUTHORIZATION="PAYMENT_AUTHORIZATION",e.SHIPPING_ADDRESS="SHIPPING_ADDRESS",e.SHIPPING_OPTION="SHIPPING_OPTION"}(Yo||(Yo={})),function(e){e.OFFER_INVALID="OFFER_INVALID",e.PAYMENT_DATA_INVALID="PAYMENT_DATA_INVALID",e.SHIPPING_ADDRESS_INVALID="SHIPPING_ADDRESS_INVALID",e.SHIPPING_ADDRESS_UNSERVICEABLE="SHIPPING_ADDRESS_UNSERVICEABLE",e.SHIPPING_OPTION_INVALID="SHIPPING_OPTION_INVALID",e.OTHER_ERROR="OTHER_ERROR"}(Ko||(Ko={})),function(e){e.INITIALIZE="INITIALIZE",e.SHIPPING_OPTION="SHIPPING_OPTION",e.SHIPPING_ADDRESS="SHIPPING_ADDRESS",e.OFFER="OFFER"}(Jo||(Jo={}));var Qo,Xo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ea{constructor(e,t){this._gatewayIdentifier=e,this._paymentIntegrationService=t,this._isBuyNowFlow=!1,this._shouldRequestShipping=!0,this._isWebViewExperimentOn=null}mapToShippingAddressRequestBody({shippingAddress:e}){if(!e)return;const{company:t="",phone:n=""}=this._paymentIntegrationService.getState().getShippingAddress()||{};return this._mapToAddressRequestBody(e,t,n)}mapToBillingAddressRequestBody(e){const{billingAddress:t}=e.paymentMethodData.info;if(!t)return;const{company:n="",phone:i="",email:r,customFields:o=[]}=this._paymentIntegrationService.getState().getBillingAddress()||{};return Object.assign(Object.assign({},this._mapToAddressRequestBody(t,n,i,o)),{email:r||e.email})}mapToExternalCheckoutData(e){var t;const{paymentMethodData:{tokenizationData:{token:n},info:{cardNetwork:i,cardDetails:r}}}=e;if(!n)throw new ti(Xn.MissingPaymentToken);return Promise.resolve(Object.assign({nonce:n,card_information:{type:i,number:r}},this._isBuyNowFlow&&{cart_id:null===(t=this._paymentIntegrationService.getState().getCart())||void 0===t?void 0:t.id}))}getRequiredData(){var e;return Xo(this,void 0,void 0,function*(){const t={emailRequired:!0};if(!this._isShippingAddressRequired())return t;const n=yield this._paymentIntegrationService.loadShippingCountries(),i=null===(e=n.getShippingCountries())||void 0===e?void 0:e.map(e=>e.code);return Object.assign(Object.assign({},t),{shippingAddressRequired:!0,shippingAddressParameters:Object.assign({phoneNumberRequired:!0},i&&{allowedCountryCodes:i}),shippingOptionRequired:!0})})}getCallbackIntents(){return this._isShippingAddressRequired()?[Yo.OFFER,Yo.SHIPPING_ADDRESS,Yo.SHIPPING_OPTION]:[Yo.OFFER]}getCallbackTriggers(){return{availableTriggers:[Jo.INITIALIZE,Jo.SHIPPING_ADDRESS,Jo.SHIPPING_OPTION,Jo.OFFER],initializationTrigger:[Jo.INITIALIZE],addressChangeTriggers:[Jo.INITIALIZE,Jo.SHIPPING_ADDRESS],shippingOptionsChangeTriggers:[Jo.SHIPPING_OPTION],offerChangeTriggers:[Jo.OFFER]}}getNonce(e){var t;const n=null===(t=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.nonce;if(!n)throw new ti(Xn.MissingPaymentToken);return Promise.resolve(n)}extraPaymentData(){return Promise.resolve(void 0)}getMerchantInfo(){const{googleMerchantName:e,googleMerchantId:t,platformToken:n}=this.getGooglePayInitializationData();return{merchantName:e,merchantId:t,authJwt:n}}getTransactionInfo(){let e;const{getCartOrThrow:t}=this._paymentIntegrationService.getState();e=this._isBuyNowFlow?this._getCurrencyCodeOrThrow():t().currency.code;const n=this.getGooglePayInitializationData().storeCountry;if(this.isWebViewWithRestrictions()){const t=this.getTotalPrice();return Object.assign(Object.assign({},n&&{countryCode:n}),{currencyCode:e,totalPrice:t,totalPriceStatus:Wo.ESTIMATED})}return Object.assign(Object.assign({},n&&{countryCode:n}),{currencyCode:e,totalPriceStatus:Wo.ESTIMATED,totalPrice:"0"})}isWebViewWithRestrictions(){return null!==this._isWebViewExperimentOn?this._isWebViewExperimentOn&&Uo():Uo()}setIsWebViewExperimentOn(e){this._isWebViewExperimentOn=e}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData().gatewayMerchantId;if(!e)throw new fi("Unable to proceed, gatewayMerchantId is missing.");return{gateway:this._gatewayIdentifier,gatewayMerchantId:e}}getCardParameters(){return{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:this.getPaymentMethod().supportedCards.filter(Zo).map(e=>$o[e]),billingAddressRequired:!0,billingAddressParameters:{format:"FULL",phoneNumberRequired:!0}}}initialize(e,t,n){return this._getPaymentMethodFn=e,this._isBuyNowFlow=Boolean(t),this._currencyCode=n,this._isBuyNowFlow&&this._getCurrencyCodeOrThrow(),Promise.resolve()}handleShippingAddressChange(e){var t,n,i,r;return Xo(this,void 0,void 0,function*(){e&&(e.name=e.name||"",e.address1=e.address1||"");const o=this.mapToShippingAddressRequestBody({shippingAddress:e});o&&(yield this._paymentIntegrationService.updateShippingAddress(o));const a=this._paymentIntegrationService.getState(),s=a.getConsignments();if(!(null==s?void 0:s[0]))return;const d=s[0],c=a.getStoreConfigOrThrow();this._currencyService||(this._currencyService=new Bo(c));const l=(d.availableShippingOptions||[]).map(this._getGooglePayShippingOption.bind(this)),u=null===(t=d.availableShippingOptions)||void 0===t?void 0:t.find(e=>e.isRecommended);if(l.length){const e=(null===(n=d.selectedShippingOption)||void 0===n?void 0:n.id)||(null==u?void 0:u.id)||(null===(i=l[0])||void 0===i?void 0:i.id);return!(null===(r=d.selectedShippingOption)||void 0===r?void 0:r.id)&&l[0]&&(yield this.handleShippingOptionChange((null==u?void 0:u.id)||l[0].id)),{defaultSelectedOptionId:e,shippingOptions:l}}})}handleShippingOptionChange(e){return Xo(this,void 0,void 0,function*(){if("shipping_option_unselected"!==e)return this._paymentIntegrationService.selectShippingOption(e)})}getTotalPrice(){const{getCheckoutOrThrow:e,getCartOrThrow:t,getStoreConfigOrThrow:n}=this._paymentIntegrationService.getState(),{decimalPlaces:i}=t().currency,r=Ci(n().checkoutSettings.features,"PI-5075.google_pay_round_total_price_to_max_2_decimal_places")?Math.min(i,2):i;return ge(e().outstandingBalance,r).toFixed(r)}handleCoupons(e){return Xo(this,void 0,void 0,function*(){const{redemptionCodes:t=[]}=e,{offers:n}=this.getAppliedCoupons()||{};let i;return yield t.reduce((e,t)=>Xo(this,void 0,void 0,function*(){if(yield e,(n||[]).some(({redemptionCode:e})=>e===t))return;const r=yield this.applyCoupon(t);r&&(i=r)}),Promise.resolve()),yield(n||[]).reduce((e,n)=>Xo(this,void 0,void 0,function*(){yield e,t.includes(n.redemptionCode)||(yield this._paymentIntegrationService.removeCoupon(n.redemptionCode))}),Promise.resolve()),{newOfferInfo:this.getAppliedCoupons(),error:i}})}getAppliedCoupons(){const e=this._paymentIntegrationService.getState(),{coupons:t}=e.getCheckout()||{};return{offers:(t||[]).map(e=>{const{displayName:t,code:n}=e;return{redemptionCode:n,description:t}})}}applyCoupon(e){return Xo(this,void 0,void 0,function*(){let t;try{yield this._paymentIntegrationService.applyCoupon(e)}catch(e){return e instanceof Error&&(t={reason:Ko.OFFER_INVALID,message:e.message,intent:Jo.OFFER}),t}})}setShouldRequestShipping(e){this._shouldRequestShipping=e}getGooglePayInitializationData(){return ii(this.getPaymentMethod().initializationData,()=>new fi("Missing initialization data."))}getPaymentMethod(){return ii(this._getPaymentMethodFn,()=>new ri(ei.PaymentNotInitialized))()}getGatewayIdentifier(){return this._gatewayIdentifier}setGatewayIdentifier(e){this._gatewayIdentifier=e||this.getGatewayIdentifier()}_isShippingAddressRequired(){const{getCartOrThrow:e,getStoreConfigOrThrow:t,getShippingAddress:n}=this._paymentIntegrationService.getState(),i=t();let r;return r=Ci(i.checkoutSettings.features,"PI-4290.google_pay_require_shipping_address")?this._shouldRequestShipping:void 0===n(),r&&jo(e(),i)}_mapToAddressRequestBody(e,t,n,i){const{name:r,address1:o,address2:a,address3:s,locality:d,administrativeArea:c,countryCode:l,postalCode:u,phoneNumber:h}=e,[p,m]=this._getFirstAndLastName(r);return{firstName:p,lastName:m,company:t,address1:o,address2:`${a} ${s}`.trim(),city:d||c,stateOrProvince:c,stateOrProvinceCode:c,countryCode:l,postalCode:u,phone:h||n,customFields:i||[]}}_getFirstAndLastName(e){const t=e.split(" ");return 1===t.length?[e,""]:[t.slice(0,-1).join(" "),t[t.length-1]]}_getCurrencyCodeOrThrow(){return ii(this._currencyCode,()=>new fi('Unable to initialize payment because "options.currencyCode" argument is not provided.'))}_getGooglePayShippingOption({id:e,cost:t,description:n,additionalDescription:i}){var r;return{id:e,label:`${(null===(r=this._currencyService)||void 0===r?void 0:r.toCustomerCurrency(t))||t} ${n}`,description:i}}}function ta(e){return"object"==typeof e&&null!==e&&"statusCode"in e}function na(e){return Object.values(Qo).includes(e)}!function(e){e.ADYEN_V2="googlepayadyenv2",e.ADYEN_V3="googlepayadyenv3",e.AUTHORIZE_NET="googlepayauthorizenet",e.BNZ="googlepaybnz",e.BRAINTREE="googlepaybraintree",e.PAYPAL_COMMERCE="googlepaypaypalcommerce",e.BIGCOMMERCE_PAYMENTS="googlepay_bigcommerce_payments",e.CHECKOUT_COM="googlepaycheckoutcom",e.CYBERSOURCE_V2="googlepaycybersourcev2",e.ORBITAL="googlepayorbital",e.STRIPE="googlepaystripe",e.STRIPE_UPE="googlepaystripeupe",e.STRIPE_OCS="googlepaystripeocs",e.WORLDPAY_ACCESS="googlepayworldpayaccess",e.TD_ONLINE_MART="googlepaytdonlinemart"}(Qo||(Qo={}));var ia=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ra{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t}initialize(e){var t,n;return ia(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId)||!na(e.methodId))throw new fi('Unable to proceed because "methodId" is not a valid key.');this._methodId=e.methodId;const i=e[this._getMethodId()];if(!i)throw new fi("Unable to proceed without valid options.");let r,o=this._paymentIntegrationService.getState();try{r=o.getPaymentMethodOrThrow(this._getMethodId())}catch(e){o=yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodId()),r=o.getPaymentMethodOrThrow(this._getMethodId())}try{this._googlePayPaymentProcessor.setIsWebViewExperimentOn(!!(null===(t=r.initializationData)||void 0===t?void 0:t.isWebViewExperimentOn)),yield this._googlePayPaymentProcessor.initialize(()=>r,this._getGooglePayClientOptions(null===(n=r.initializationData)||void 0===n?void 0:n.storeCountry))}catch(e){return}this._addPaymentButton(i)})}signIn(){return Promise.reject(new Si('In order to sign in via Google Pay, the shopper must click on "Google Pay" button.'))}signOut(){var e;return ia(this,void 0,void 0,function*(){const t=null===(e=this._paymentIntegrationService.getState().getPaymentId())||void 0===e?void 0:e.providerId;t&&(yield this._googlePayPaymentProcessor.signOut(t))})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}deinitialize(){var e;return null===(e=this._paymentButton)||void 0===e||e.remove(),this._paymentButton=void 0,this._methodId=void 0,Promise.resolve()}_getGooglePayClientOptions(e){return this._googlePayPaymentProcessor.isWebViewWithRestrictions()?{}:{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:t,shippingAddress:n,shippingOptionData:i,offerData:r})=>ia(this,void 0,void 0,function*(){const{availableTriggers:o,addressChangeTriggers:a,shippingOptionsChangeTriggers:s,offerChangeTriggers:d}=this._googlePayPaymentProcessor.getCallbackTriggers();if(!o.includes(t))return;const c=a.includes(t)?yield this._googlePayPaymentProcessor.handleShippingAddressChange(n):void 0;s.includes(t)&&(yield this._googlePayPaymentProcessor.handleShippingOptionChange(i.id));const{newOfferInfo:l,error:u}=d.includes(t)?yield this._googlePayPaymentProcessor.handleCoupons(r):{},h=u;yield this._paymentIntegrationService.loadCheckout();const p=this._googlePayPaymentProcessor.getTotalPrice(),{code:m}=this._paymentIntegrationService.getState().getCartOrThrow().currency;return Object.assign(Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},e&&{countryCode:e}),{currencyCode:m,totalPriceStatus:Wo.FINAL,totalPrice:p})},c&&{newShippingOptionParameters:c}),l&&{newOfferInfo:l}),h&&{error:h})})}}}_addPaymentButton({container:e,buttonColor:t,buttonType:n,onClick:i,onError:r}){var o;this._paymentButton=null!==(o=this._paymentButton)&&void 0!==o?o:this._googlePayPaymentProcessor.addPaymentButton(e,{buttonColor:null!=t?t:"default",buttonType:null!=n?n:"plain",onClick:this._handleClick(r,i)})}_handleClick(e,t){return n=>ia(this,void 0,void 0,function*(){n.preventDefault(),t&&"function"==typeof t&&t();try{yield this._googlePayPaymentProcessor.initializeWidget(),yield this._interactWithPaymentSheet()}catch(t){let n=t;if(ta(t)){if("CANCELED"===t.statusCode)throw new Wi;n=new Qr(JSON.stringify(t))}throw null==e||e(new Qr("An error occurred while requesting your Google Pay payment details.")),n}})}_interactWithPaymentSheet(){return ia(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet(),t=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e),n=this._googlePayPaymentProcessor.mapToShippingAddressRequestBody(e),i="/embedded-checkout"===window.location.pathname?this._paymentIntegrationService.getState().getStoreConfigOrThrow().links.siteLink:void 0;t&&(yield this._paymentIntegrationService.updateBillingAddress(t)),n&&(yield this._paymentIntegrationService.updateShippingAddress(n)),yield this._googlePayPaymentProcessor.setExternalCheckoutForm(this._getMethodId(),e,i)})}_getMethodId(){return ii(this._methodId,()=>new ri(ei.PaymentNotInitialized))}}var oa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class aa{constructor(e,t,n,i){this._scriptLoader=e,this._gateway=t,this._requestSender=n,this._formPoster=i,this._baseRequest={apiVersion:2,apiVersionMinor:0}}initialize(e,t,n,i){return oa(this,void 0,void 0,function*(){this._paymentsClient=yield this._scriptLoader.getGooglePaymentsClient(e().config.testMode,t),yield this._gateway.initialize(e,n,i),this._buildButtonPayloads()})}initializeWidget(){return oa(this,void 0,void 0,function*(){yield this._buildWidgetPayloads(),yield this._determineReadinessToPay(),this._prefetchGooglePaymentData()})}getNonce(e){return this._gateway.getNonce(e)}extraPaymentData(){return oa(this,void 0,void 0,function*(){return this._gateway.extraPaymentData()})}addPaymentButton(e,t){const n=document.querySelector(`#${e}`);if(!n)return;const i=this._getPaymentsClient().createButton(Object.assign(Object.assign({},t),{allowedPaymentMethods:[this._getBaseCardPaymentMethod()]}));return n.appendChild(i)}showPaymentSheet(){return oa(this,void 0,void 0,function*(){const e=this._getPaymentDataRequest();return this._getPaymentsClient().loadPaymentData(e)})}setExternalCheckoutXhr(e,t){return oa(this,void 0,void 0,function*(){return this._setExternalCheckout(e,t)})}setExternalCheckoutForm(e,t,n){return oa(this,void 0,void 0,function*(){return this._setExternalCheckout(e,t,!0,n)})}mapToBillingAddressRequestBody(e){return this._gateway.mapToBillingAddressRequestBody(e)}mapToShippingAddressRequestBody(e){return this._gateway.mapToShippingAddressRequestBody(e)}processAdditionalAction(e,t){return"processAdditionalAction"in this._gateway?this._gateway.processAdditionalAction(e,t):Promise.reject(e)}signOut(e){return oa(this,void 0,void 0,function*(){yield this._requestSender.get(`/remote-checkout/${e}/signout`)})}getCallbackTriggers(){return this._gateway.getCallbackTriggers()}setShouldRequestShipping(e){return this._gateway.setShouldRequestShipping(e)}handleShippingAddressChange(e){return oa(this,void 0,void 0,function*(){return this._gateway.handleShippingAddressChange(e)})}handleShippingOptionChange(e){return oa(this,void 0,void 0,function*(){yield this._gateway.handleShippingOptionChange(e)})}handleCoupons(e){return oa(this,void 0,void 0,function*(){return this._gateway.handleCoupons(e)})}getTotalPrice(){return this._gateway.getTotalPrice()}_setExternalCheckout(e,t,n=!1,i){return oa(this,void 0,void 0,function*(){const r="/checkout.php",o=Object.assign({action:"set_external_checkout",provider:e},yield this._gateway.mapToExternalCheckoutData(t));if(n)return new Promise(e=>{this._formPoster.postForm(i?`${i}/checkout`:r,Object.assign(Object.assign({},o),{card_information:JSON.stringify(o.card_information)}),e)});yield this._requestSender.post(r,{headers:Object.assign({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded"},yr),body:o})})}isWebViewWithRestrictions(){return this._gateway.isWebViewWithRestrictions()}setIsWebViewExperimentOn(e){return this._gateway.setIsWebViewExperimentOn(e)}_prefetchGooglePaymentData(){const e=this._getPaymentDataRequest();e.transactionInfo=this._gateway.getTransactionInfo(),this._getPaymentsClient().prefetchPaymentData(e)}_determineReadinessToPay(){return oa(this,void 0,void 0,function*(){try{const{result:e}=yield this._getPaymentsClient().isReadyToPay(this._getIsReadyToPayRequest());if(!1===e)throw new Qr("Google Pay is not supported by the current device and browser, please try another payment method.")}catch(e){if(e instanceof Qr)throw e;throw new Qr}})}_buildButtonPayloads(){this._baseCardPaymentMethod={type:"CARD",parameters:this._gateway.getCardParameters()}}_buildWidgetPayloads(){return oa(this,void 0,void 0,function*(){const e=this._getBaseCardPaymentMethod();this._cardPaymentMethod=Object.assign(Object.assign({},e),{tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:yield this._gateway.getPaymentGatewayParameters()}});const t=this._gateway.isWebViewWithRestrictions()?{shippingOptionRequired:!1}:{callbackIntents:this._gateway.getCallbackIntents(),offerInfo:this._gateway.getAppliedCoupons()};this._paymentDataRequest=Object.assign(Object.assign(Object.assign(Object.assign({},this._baseRequest),{allowedPaymentMethods:[this._cardPaymentMethod],transactionInfo:this._gateway.getTransactionInfo(),merchantInfo:this._gateway.getMerchantInfo()}),yield this._gateway.getRequiredData()),t),this._isReadyToPayRequest=Object.assign(Object.assign({},this._baseRequest),{allowedPaymentMethods:[e]})})}_getBaseCardPaymentMethod(){return this._getOrThrow(this._baseCardPaymentMethod)}_getPaymentDataRequest(){return this._getOrThrow(this._paymentDataRequest)}_getIsReadyToPayRequest(){return this._getOrThrow(this._isReadyToPayRequest)}_getPaymentsClient(){return this._getOrThrow(this._paymentsClient)}_getOrThrow(e){return ii(e,()=>new ri(ei.PaymentNotInitialized))}}class sa{constructor(e){this._scriptLoader=e,this._window=window}getGooglePaymentsClient(e=!1,t){return n=this,i=void 0,o=function*(){if(yield this._scriptLoader.loadScript("https://pay.google.com/gp/p/js/pay.js"),!this._window.google)throw new mi;return void 0===this._paymentsClient&&(this._paymentsClient=new this._window.google.payments.api.PaymentsClient(Object.assign({environment:e?"TEST":"PRODUCTION"},null!=t?t:{}))),this._paymentsClient},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}function da(){return new sa(a())}const ca=vi(e=>{const t=n();return new ra(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv2"}]),la=vi(e=>{const t=n();return new ra(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv3"}]);class ua extends ea{constructor(e){super("authorizenet",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();return function(e){if(!function(e){return"paymentGatewayId"in e}(e))throw new ti(Xn.MissingPaymentMethod)}(e),{gateway:this.getGatewayIdentifier(),gatewayMerchantId:e.paymentGatewayId}}}const ha=vi(e=>new ra(e,new aa(da(),new ua(e),n(),Ee())),[{id:"googlepayauthorizenet"}]),pa=e=>"object"==typeof e&&null!==e&&"body"in e;function ma(e){if(!function(e){return"checkoutcomkey"in e}(e))throw new ti(Xn.MissingPaymentMethod)}var ya=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ga extends ea{constructor(e,t){super("checkoutltd",e),this._requestSender=t}processAdditionalAction(e){return new Promise((t,n)=>{if(pa(e)&&function(e){var t;if("object"!=typeof e||null===e)return!1;const n=e;return"string"==typeof(null===(t=n.three_ds_result)||void 0===t?void 0:t.acs_url)&&"string"==typeof n.three_ds_result.code}(e.body)&&"three_d_secure_required"===e.body.three_ds_result.code)return window.location.assign(e.body.three_ds_result.acs_url);n(e)})}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ya(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);let i;try{i=JSON.parse(n.nonce)}catch(e){throw new fi("Unable to parse response from Google Pay.")}return function(e){if(!function(e){return"object"==typeof e&&null!==e&&"protocolVersion"in e&&"signature"in e&&"signedMessage"in e}(e))throw new ti(Xn.MissingPaymentToken)}(i),n.nonce=yield this._tokenize(i),n})}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();return ma(e),{gateway:this.getGatewayIdentifier(),gatewayMerchantId:e.checkoutcomkey}}_tokenize(e){return ya(this,void 0,void 0,function*(){const t=this.getPaymentMethod().config.testMode?"https://api.sandbox.checkout.com/tokens":"https://api.checkout.com/tokens",n=this.getGooglePayInitializationData();ma(n);const{body:i}=yield this._requestSender.post(t,{credentials:!1,body:{type:"googlepay",token_data:e},headers:{Authorization:n.checkoutcomkey,"Content-Type":mr.Json,"X-XSRF-TOKEN":null}});return i.token})}}const va=vi(e=>{const t=n();return new ra(e,new aa(da(),new ga(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]);class fa extends ea{constructor(e){super("cybersource",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const Sa=vi(e=>new ra(e,new aa(da(),new fa(e),n(),Ee())),[{id:"googlepaycybersourcev2"}]),_a=vi(e=>new ra(e,new aa(da(),new fa(e),n(),Ee())),[{id:"googlepaybnz"}]);class wa extends ea{constructor(e){super("chase",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const Ia=vi(e=>new ra(e,new aa(da(),new wa(e),n(),Ee())),[{id:"googlepayorbital"}]);var Ca,ba,Pa,Oa,Ea,Aa,Ta,ka,Da,Ma,za,Na;!function(e){e.SHIPPING="shipping",e.BILLING="billing"}(Ca||(Ca={})),function(e){e.SPLIT="split",e.FULL="full",e.ORGANIZATION="organization"}(ba||(ba={})),function(e){e.Open="open",e.Expired="expired",e.Complete="complete"}(Pa||(Pa={})),function(e){e.Paid="paid",e.UnPaid="unpaid",e.NoPaymentRequired="no_payment_required"}(Oa||(Oa={})),function(e){e.SUCCESS="success",e.ERROR="error"}(Ea||(Ea={})),function(e){e.CreditCard="card",e.ACH="us_bank_account",e.Link="link",e.EPS="eps",e.GRABPAY="grabpay",e.BANCONTACT="bancontact",e.IDEAL="ideal",e.ALIPAY="alipay",e.KLARNA="klarna",e.OCS="optimized_checkout",e.CHECKOUT_SESSION="checkout_session"}(Aa||(Aa={})),function(e){e.NEVER="never",e.AUTO="auto",e.ALWAYS="always",e.PAYMENT="payment",e.IF_REQUIRED="if_required"}(Ta||(Ta={})),function(e){e.V3="v3",e.ACACIA="acacia",e.BASIL="basil",e.CLOVER="clover"}(ka||(ka={})),function(e){e.PAYMENT="payment",e.AUTHENTICATION="linkAuthentication",e.SHIPPING="address",e.EXPRESS_CHECKOUT="expressCheckout"}(Da||(Da={})),function(e){e.REQUIRES_PAYMENT_METHOD="requires_payment_method",e.REQUIRES_CONFIRMATION="requires_confirmation",e.REQUIRES_ACTION="requires_action",e.PROCESSING="processing",e.SUCCEEDED="succeeded",e.CANCELED="canceled"}(Ma||(Ma={})),function(e){e.CLICK="click",e.CHANGE="change",e.READY="ready",e.SHIPPING_ADDRESS_CHANGE="shippingaddresschange",e.SHIPPING_RATE_CHANGE="shippingratechange",e.CONFIRM="confirm",e.CANCEL="cancel",e.LOADER_START="loaderstart"}(za||(za={})),function(e){e.ON_SESSION="on_session",e.OFF_SESSION="off_session"}(Na||(Na={}));var xa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ra{constructor(e,t=window){this.scriptLoader=e,this.stripeWindow=t}getStripeClient(e,t,n,i,r){return xa(this,void 0,void 0,function*(){if(this.stripeWindow.bcStripeClient)return this.stripeWindow.bcStripeClient;const o=yield this.load(n),{stripePublishableKey:a,stripeConnectedAccount:s}=e,d=o(a,Object.assign(Object.assign(Object.assign(Object.assign({},s?{stripeAccount:s}:{}),t?{locale:t}:{}),i?{betas:i}:{}),r?{apiVersion:r}:{}));return Object.assign(this.stripeWindow,{bcStripeClient:d}),d})}getElements(e,t){return xa(this,void 0,void 0,function*(){let n=this.stripeWindow.bcStripeElements;return n?yield this.updateStripeElements(t):(n=e.elements(t),Object.assign(this.stripeWindow,{bcStripeElements:n})),n})}updateStripeElements(e){return xa(this,void 0,void 0,function*(){const t=this.stripeWindow.bcStripeElements;t&&(t.update(e),yield t.fetchUpdates())})}getStripeCheckout(e,t){return xa(this,void 0,void 0,function*(){let n=yield this.getStoredStripeCheckout(t);return n||(n=yield e.initCheckout(t),Object.assign(this.stripeWindow,{bcStripeCheckout:n})),n})}load(e){return xa(this,void 0,void 0,function*(){if(!this.stripeWindow.Stripe&&(yield this.scriptLoader.loadScript(this.getScriptUrl(e)),!this.stripeWindow.Stripe))throw new mi;return this.stripeWindow.Stripe})}getScriptUrl(e){return e&&e!==ka.V3?`https://js.stripe.com/${e}/stripe.js`:"https://js.stripe.com/v3/"}getStoredStripeCheckout(e){return xa(this,void 0,void 0,function*(){const t=this.stripeWindow.bcStripeCheckout;if(t)try{const{actions:n,error:i}=yield t.loadActions();if(i||!n)return void this.logErrorToConsole(i);const r=yield n.getSession(),o=e.clientSecret.split("_secret_")[0];if(r.id===o)return t}catch(e){return void this.logErrorToConsole(e)}})}logErrorToConsole(e){e?console.error(e):console.error("No stripe checkout actions available on loadActions().")}}const Fa=["payment_element_beta_2","alipay_pm_beta_1","link_default_integration_beta_1","shipping_address_element_beta_1","address_element_beta_1"],La="2020-03-02;alipay_beta=v1;link_beta=v1";function Ba(e){if(!function(e){return"stripeConnectedAccount"in e&&"stripePublishableKey"in e&&"stripeVersion"in e}(e))throw new ti(Xn.MissingPaymentMethod)}var ja=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ua extends ea{constructor(e,t){super("stripe",e),this.paymentIntegrationService=e,this.scriptLoader=t}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ja(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);let i;try{i=JSON.parse(n.nonce)}catch(e){throw new fi("Unable to parse response from Google Pay.")}return function(e){if(!function(e){return"object"==typeof e&&null!==e&&"id"in e}(e))throw new ti(Xn.MissingPaymentToken)}(i),n.nonce=i.id,n})}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();Ba(e);const{stripeVersion:t,stripePublishableKey:n,stripeConnectedAccount:i}=e;return{gateway:this.getGatewayIdentifier(),"stripe:version":t,"stripe:publishableKey":`${n}/${i}`}}processAdditionalAction(e,t){var n;return ja(this,void 0,void 0,function*(){if(!t)throw new co(["payment"]);if(!pa(e)||("object"!=typeof(i=e.body)||null===i||!("three_ds_result"in i)||!("errors"in i)))throw e;var i;if(ve(e.body.errors,{code:"three_d_secure_required"})){const i=this.getGooglePayInitializationData();Ba(i),this.stripeUPEClient=yield this.loadStripeJs(i,t);const r=e.body.three_ds_result.token;let o,a=!1;try{o=yield this.stripeUPEClient.confirmCardPayment(r)}catch(e){try{o=yield this.stripeUPEClient.retrievePaymentIntent(r)}catch(e){a=!0}}if(null==o?void 0:o.error){if(this._throwDisplayableStripeError(o.error),this._isCancellationError(o.error))throw new Wi;throw new Qr}if(!(null==o?void 0:o.paymentIntent)&&!a)throw new nr;return this.paymentIntegrationService.submitPayment({methodId:t,paymentData:{nonce:(null===(n=null==o?void 0:o.paymentIntent)||void 0===n?void 0:n.id)||r}})}throw e})}loadStripeJs(e,t){return ja(this,void 0,void 0,function*(){if(this.stripeUPEClient)return this.stripeUPEClient;const n=this.paymentIntegrationService.getState().getCartLocale();return"googlepaystripeocs"===t&&e.useNewStripeJsVersion?this.scriptLoader.getStripeClient(e,n,ka.CLOVER):this.scriptLoader.getStripeClient(e,n,ka.V3,Fa,La)})}_isCancellationError(e){var t,n;return e&&-1!==(null===(n=null===(t=e.payment_intent.last_payment_error)||void 0===t?void 0:t.message)||void 0===n?void 0:n.indexOf("canceled"))}_throwDisplayableStripeError(e){if(H(["card_error","invalid_request_error","validation_error"],e.type))throw new Error(e.message)}}const qa=vi(e=>new ra(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeocs"}]),Va=vi(e=>new ra(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripeupe"}]);class Ga extends ea{constructor(e){super("worldpay",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const Ha=vi(e=>new ra(e,new aa(da(),new Ga(e),n(),Ee())),[{id:"googlepayworldpayaccess"}]);var Wa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class $a extends ea{constructor(e,t){super("braintree",e),this._braintreeSdk=t,this._methodId=Qo.BRAINTREE,this._service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Wa(this,void 0,void 0,function*(){yield i.initialize.call(this,e,t,n);let r=i.getPaymentMethod.call(this);if(r.clientToken||(r=(yield this._service.loadPaymentMethod(this._methodId)).getPaymentMethodOrThrow(this._methodId)),!r.clientToken||!r.initializationData)throw new ti(Xn.MissingPaymentMethod);return this._braintreeSdk.initialize(r.clientToken),this._braintreeGooglePayment=yield this._braintreeSdk.getBraintreeGooglePayment(),Promise.resolve()})}getNonce(e){const t=Object.create(null,{getNonce:{get:()=>super.getNonce},getPaymentMethod:{get:()=>super.getPaymentMethod}});var n;return Wa(this,void 0,void 0,function*(){const i=yield t.getNonce.call(this,e),{clientToken:r,initializationData:o}=t.getPaymentMethod.call(this);if(!r||!o||!(null===(n=o.card_information)||void 0===n?void 0:n.bin))throw new ti(Xn.MissingPaymentMethod);const{isThreeDSecureEnabled:a,card_information:{bin:s,isNetworkTokenized:d}}=o;if(a&&!d){const e=yield this._braintreeSdk.getBraintreeThreeDS(),{orderAmount:t}=this._service.getState().getOrderOrThrow();return(yield this._braintreePresent3DSChallenge(e,t,i,s)).nonce}return i})}extraPaymentData(){return Wa(this,void 0,void 0,function*(){return{deviceSessionId:yield this._getBraintreeDeviceData()}})}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return Wa(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);let i;try{i=JSON.parse(n.nonce)}catch(e){throw new fi("Unable to parse response from Google Pay.")}return function(e){if(!function(e){return"object"==typeof e&&null!==e&&"androidPayCards"in e}(e))throw new ti(Xn.MissingPaymentToken)}(i),n.nonce=i.androidPayCards[0].nonce,n.card_information.bin=i.androidPayCards[0].details.bin,n.card_information.isNetworkTokenized=i.androidPayCards[0].details.isNetworkTokenized,n})}getCardParameters(){return super.getCardParameters()}getPaymentGatewayParameters(){const e=Object.create(null,{getMerchantInfo:{get:()=>super.getMerchantInfo},getTransactionInfo:{get:()=>super.getTransactionInfo},getRequiredData:{get:()=>super.getRequiredData}});return Wa(this,void 0,void 0,function*(){return this.getBraintreeGooglePayment().createPaymentDataRequest(Object.assign({merchantInfo:e.getMerchantInfo.call(this),transactionInfo:e.getTransactionInfo.call(this),cardRequirements:{billingAddressRequired:!0,billingAddressFormat:"FULL"}},yield e.getRequiredData.call(this))).paymentMethodTokenizationParameters.parameters})}getBraintreeGooglePayment(){if(!this._braintreeGooglePayment)throw new ti(Xn.MissingPaymentMethod);return this._braintreeGooglePayment}_getBraintreeDeviceData(){return Wa(this,void 0,void 0,function*(){const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e})}_braintreePresent3DSChallenge(e,t,n,i){return new En(e.verifyCard({amount:t,bin:i,nonce:n,onLookupComplete:(e,t)=>{t()}})).promise}}const Ya=vi(e=>{const t=n(),i=window,r=new Ei(e),o=new Ui(new Hi(a(),i,r));return new ra(e,new aa(da(),new $a(e,o),t,Ee()))},[{id:"googlepaybraintree"}]),Ka={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},Ja=["ar_BH","ar_DZ","ar_EG","ar_JO","ar_KW","ar_MA","ar_OM","ar_QA","ar_SA","ar_TN","ar_YE","ar_AE","bg_BG","cs_CZ","da_DK","da_FO","da_GL","de_AT","de_CH","de_DE","de_LU","el_GR","en_AD","en_AE","en_AG","en_AI","en_AL","en_AM","en_AN","en_AO","en_AT","en_AU","en_AW","en_AZ","en_BB","en_BE","en_BH","en_BJ","en_BM","en_BN","en_BS","en_BT","en_BW","en_BY","en_BZ","en_C2","en_CA","en_CD","en_CG","en_CH","en_CI","en_CK","en_CL","en_CM","en_CN","en_CO","en_CR","en_CV","en_CY","en_CZ","en_DE","en_DJ","en_DK","en_DM","en_DO","en_DZ","en_EC","en_EE","en_EG","en_ER","en_ES","en_ET","en_FI","en_FJ","en_FK","en_FM","en_FO","en_FR","en_GA","en_GB","en_GD","en_GE","en_GF","en_GI","en_GL","en_GM","en_GN","en_GP","en_GR","en_GT","en_GW","en_GY","en_HK","en_HN","en_HR","en_HU","en_ID","en_IE","en_IL","en_IN","en_IS","en_IT","en_JM","en_JO","en_JP","en_KE","en_KG","en_KH","en_KI","en_KM","en_KN","en_KR","en_KW","en_KY","en_KZ","en_LA","en_LC","en_LI","en_LK","en_LS","en_LT","en_LU","en_LV","en_MA","en_MC","en_MD","en_ME","en_MG","en_MH","en_MK","en_ML","en_MN","en_MQ","en_MR","en_MS","en_MT","en_MU","en_MV","en_MW","en_MY","en_MZ","en_NA","en_NC","en_NE","en_NF","en_NG","en_NI","en_NL","en_NO","en_NP","en_NR","en_NU","en_NZ","en_OM","en_PA","en_PE","en_PF","en_PG","en_PH","en_PL","en_PM","en_PN","en_PT","en_PW","en_PY","en_QA","en_RE","en_RO","en_RS","en_RU","en_RW","en_SA","en_SB","en_SC","en_SE","en_SG","en_SH","en_SI","en_SJ","en_SK","en_SL","en_SM","en_SN","en_SO","en_SR","en_ST","en_SV","en_SZ","en_TC","en_TD","en_TG","en_TH","en_TJ","en_TM","en_TN","en_TO","en_TR","en_TT","en_TV","en_TW","en_TZ","en_UA","en_UG","en_US","en_UY","en_VA","en_VC","en_VE","en_VG","en_VN","en_VU","en_WF","en_WS","en_YE","en_YT","en_ZA","en_ZM","en_ZW","es_AD","es_AI","es_AO","es_AR","es_AW","es_BB","es_BJ","es_BM","es_BO","es_BS","es_BZ","es_CD","es_CG","es_CK","es_CL","es_CO","es_CR","es_CV","es_DJ","es_DM","es_DO","es_DZ","es_EC","es_EG","es_ER","es_ES","es_ET","es_FJ","es_FK","es_FO","es_GA","es_GD","es_GE","es_GI","es_GL","es_GM","es_GN","es_GT","es_GW","es_GY","es_HN","es_IE","es_JM","es_JO","es_KE","es_KG","es_KI","es_KM","es_KN","es_KW","es_KY","es_KZ","es_LC","es_LI","es_LS","es_LU","es_MA","es_MG","es_MH","es_ML","es_MR","es_MS","es_MU","es_MW","es_MX","es_MZ","es_NA","es_NC","es_NE","es_NF","es_NI","es_NR","es_NU","es_NZ","es_OM","es_PA","es_PE","es_PF","es_PG","es_PM","es_PN","es_PW","es_PY","es_QA","es_RS","es_RW","es_SA","es_SB","es_SC","es_SH","es_SJ","es_SL","es_SM","es_SN","es_SO","es_SR","es_ST","es_SV","es_SZ","es_TC","es_TD","es_TG","es_TJ","es_TM","es_TN","es_TT","es_TV","es_UA","es_UG","es_US","es_UY","es_VA","es_VC","es_VE","es_VG","es_VU","es_WF","es_YE","es_ZM","et_EE","fi_FI","fr_AD","fr_AE","fr_AI","fr_AM","fr_AO","fr_AW","fr_AZ","fr_BB","fr_BE","fr_BF","fr_BI","fr_BJ","fr_BM","fr_BS","fr_BZ","fr_CA","fr_CD","fr_CG","fr_CH","fr_CI","fr_CK","fr_CM","fr_CV","fr_DJ","fr_DM","fr_DO","fr_DZ","fr_EC","fr_ER","fr_ET","fr_FJ","fr_FK","fr_FO","fr_FR","fr_GA","fr_GD","fr_GE","fr_GF","fr_GI","fr_GL","fr_GM","fr_GN","fr_GP","fr_GT","fr_GW","fr_GY","fr_HN","fr_IE","fr_JM","fr_JO","fr_KE","fr_KG","fr_KI","fr_KM","fr_KN","fr_KW","fr_KY","fr_KZ","fr_LC","fr_LI","fr_LS","fr_LU","fr_MA","fr_MC","fr_MG","fr_MH","fr_ML","fr_MQ","fr_MR","fr_MS","fr_MU","fr_MW","fr_MZ","fr_NA","fr_NC","fr_NE","fr_NF","fr_NI","fr_NR","fr_NU","fr_NZ","fr_OM","fr_PA","fr_PE","fr_PF","fr_PG","fr_PM","fr_PN","fr_PW","fr_QA","fr_RE","fr_RS","fr_RW","fr_SA","fr_SB","fr_SC","fr_SH","fr_SJ","fr_SL","fr_SM","fr_SN","fr_SO","fr_SR","fr_ST","fr_SV","fr_SZ","fr_TC","fr_TD","fr_TG","fr_TJ","fr_TM","fr_TN","fr_TT","fr_TV","fr_UA","fr_UG","fr_US","fr_UY","fr_VA","fr_VC","fr_VE","fr_VG","fr_VU","fr_WF","fr_YE","fr_YT","fr_ZA","fr_ZM","he_IL","hu_HU","id_ID","it_IT","ja_JP","ko_KR","lv_LV","lt_LT","ms_BN","ms_MY","nl_BE","nl_NL","pl_PL","pt_BR","pt_PT","ro_RO","ru_EE","ru_LT","ru_LV","ru_RU","ru_UA","si_LK","sk_SK","sl_SI","sq_AL","sv_SE","tl_PH","th_TH","tr_TR","vi_VN","zh_C2","zh_CN","zh_HK","zh_TW","zh_AD","zh_AE","zh_AI","zh_AO","zh_AW","zh_BB","zh_BH","zh_BJ","zh_BM","zh_BS","zh_BZ","zh_CD","zh_CG","zh_CK","zh_CL","zh_CO","zh_CV","zh_DJ","zh_DM","zh_DO","zh_DZ","zh_EC","zh_EG","zh_ER","zh_ET","zh_FJ","zh_FK","zh_FO","zh_GA","zh_GD","zh_GE","zh_GI","zh_GL","zh_GM","zh_GN","zh_GT","zh_GW","zh_GY","zh_HN","zh_IE","zh_JM","zh_JO","zh_KE","zh_KG","zh_KI","zh_KM","zh_KN","zh_KW","zh_KY","zh_KZ","zh_LC","zh_LI","zh_LS","zh_LT","zh_LU","zh_MA","zh_MG","zh_MH","zh_ML","zh_MR","zh_MS","zh_MU","zh_MW","zh_MZ","zh_NA","zh_NC","zh_NE","zh_NF","zh_NI","zh_NR","zh_NU","zh_NZ","zh_OM","zh_PA","zh_PE","zh_PF","zh_PG","zh_PM","zh_PN","zh_PW","zh_QA","zh_RS","zh_RW","zh_SA","zh_SB","zh_SC","zh_SH","zh_SJ","zh_SL","zh_SM","zh_SN","zh_SO","zh_SR","zh_ST","zh_SV","zh_SZ","zh_TC","zh_TD","zh_TG","zh_TJ","zh_TM","zh_TN","zh_TT","zh_TV","zh_UA","zh_UG","zh_US","zh_UY","zh_VA","zh_VC","zh_VE","zh_VG","zh_VU","zh_WF","zh_YE","zh_ZA","zh_ZM"];function Za(e){if(!e)return;let t;if(e.includes("-")){const[n,i]=e.split("-");t=`${n}_${i.toUpperCase()}`}else t=`${e}_${e.toUpperCase()}`;return Ja.includes(t)?t:void 0}var Qa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Xa{constructor(e){this.scriptLoader=e,this.window=window}getPayPalFastlaneSdk(e,t,n,i){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const r=this.getPayPalFastlaneSdkConfiguration(e,t,n,i);if(yield this.loadPayPalSdk(r),!this.window.paypalFastlaneSdk)throw new mi}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,n,i,r){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||r){const r=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i);yield this.loadPayPalSdk(r)}if(!this.window.paypalGooglePay)throw new mi;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t,n){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t,n);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new mi}return this.window.paypalApms})}getPayPalMessages(e,t,n){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t,n);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new mi;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return Qa(this,void 0,void 0,function*(){const n=this.transformConfig(e),i=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(n).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:i})})}getPayPalFastlaneSdkConfiguration(e,t,n,i){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,attributionId:c}=o,l=Za(i);return{options:Object.assign({"client-id":s,"merchant-id":d,commit:!0,components:["fastlane","buttons","payment-fields","hosted-fields","three-domain-secure"],currency:t,intent:a},l&&{locale:l}),attributes:{"data-client-metadata-id":n.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":c,"data-sdk-client-token":r}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i=!0){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:c,attributionId:l,isHostedCheckoutEnabled:u,isDeveloperModeApplicable:h}=o,p=u||i,m=Za(n);return{options:Object.assign(Object.assign({"client-id":s,"merchant-id":d,commit:p,components:["googlepay"],currency:t,intent:a},h&&{"buyer-country":c}),m&&{locale:m}),attributes:{"data-partner-attribution-id":l,"data-client-token":r,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:r,clientId:o,merchantId:a,buyerCountry:s,attributionId:d,isDeveloperModeApplicable:c,availableAlternativePaymentMethods:l=[],enabledAlternativePaymentMethods:u=[]}=i,h=u,p=l.filter(e=>!u.includes(e)),m=Za(n);return{options:Object.assign(Object.assign({"client-id":o,"merchant-id":a,"enable-funding":h.length>0?h:void 0,"disable-funding":p.length>0?p:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:r},c&&{"buyer-country":s}),m&&{locale:m}),attributes:{"data-partner-attribution-id":d,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ti(Xn.MissingPaymentMethod);const{clientId:r,merchantId:o,attributionId:a,isDeveloperModeApplicable:s,buyerCountry:d}=i,c=Za(n);return{options:Object.assign(Object.assign({"client-id":r,"merchant-id":o,components:["messages"],currency:t},s&&{"buyer-country":d}),c&&{locale:c}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":a}}}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}function es(e){if(!function(e){return!!e.initializationData&&"attributionId"in e.initializationData&&"isVenmoEnabled"in e.initializationData&&"isGooglePayEnabled"in e.initializationData&&"isPayPalCreditAvailable"in e.initializationData}(e))throw new ti(Xn.MissingPaymentMethod)}var ts=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ns extends ea{constructor(e,t){super("paypalsb",e),this.payPalCommerceSdk=t,this.service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});var r,o,a,s,d;return ts(this,void 0,void 0,function*(){const c=this.service.getState(),l=null!==(o=null===(r=c.getStoreConfig())||void 0===r?void 0:r.currency.code)&&void 0!==o?o:n;if(!l)throw new ti(Xn.MissingPaymentMethod);yield i.initialize.call(this,e,t,l);const u=i.getPaymentMethod.call(this);if(!u.initializationData)throw new ti(Xn.MissingPaymentMethod);es(u);const h=yield this.payPalCommerceSdk.getPayPalGooglePaySdk(u,l,c.getLocale());this.googlepayConfig=yield h.Googlepay().config();const{allowedPaymentMethods:p}=this.googlepayConfig;this.setGatewayIdentifier(null===(d=null===(s=null===(a=p[0])||void 0===a?void 0:a.tokenizationSpecification)||void 0===s?void 0:s.parameters)||void 0===d?void 0:d.gateway)})}getPaymentGatewayParameters(){if(this.googlepayConfig){const{allowedPaymentMethods:e}=this.googlepayConfig,{gatewayMerchantId:t}=e[0].tokenizationSpecification.parameters;return{gateway:this.getGatewayIdentifier(),gatewayMerchantId:t}}return{gateway:this.getGatewayIdentifier()}}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ts(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n})}}const is=vi(e=>new ra(e,new aa(da(),new ns(e,new Xa(a())),n(),Ee())),[{id:"googlepaypaypalcommerce"}]);var rs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class os extends ea{constructor(e,t){super("googlepay_bigcommerce_payments",e),this.payPalSdkHelper=t,this.service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});var r,o,a,s,d;return rs(this,void 0,void 0,function*(){const c=null!==(o=null===(r=this.service.getState().getStoreConfig())||void 0===r?void 0:r.currency.code)&&void 0!==o?o:n;if(!c)throw new ti(Xn.MissingPaymentMethod);yield i.initialize.call(this,e,t,c);const l=i.getPaymentMethod.call(this);if(!l.initializationData)throw new ti(Xn.MissingPaymentMethod);es(l);const u=yield this.payPalSdkHelper.getPayPalGooglePaySdk(l,c);this.googlepayConfig=yield u.Googlepay().config();const{allowedPaymentMethods:h}=this.googlepayConfig;this.setGatewayIdentifier(null===(d=null===(s=null===(a=h[0])||void 0===a?void 0:a.tokenizationSpecification)||void 0===s?void 0:s.parameters)||void 0===d?void 0:d.gateway)})}getPaymentGatewayParameters(){if(this.googlepayConfig){const{allowedPaymentMethods:e}=this.googlepayConfig,{gatewayMerchantId:t}=e[0].tokenizationSpecification.parameters;return{gateway:this.getGatewayIdentifier(),gatewayMerchantId:t}}return{gateway:this.getGatewayIdentifier()}}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return rs(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n})}}const as=vi(e=>new ra(e,new aa(da(),new os(e,new xr(a())),n(),Ee())),[{id:"googlepay_bigcommerce_payments"}]);function ss(){const{navigator:e}=window;let t;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 ds=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class cs extends ea{constructor(e,t){super("worldlinena",e),this.formPoster=t}extraPaymentData(){return ds(this,void 0,void 0,function*(){return Promise.resolve({browser_info:ss()})})}processAdditionalAction(e){return ds(this,void 0,void 0,function*(){if(!function(e){return pa(e)&&(t=e.body,Z(t)&&"object"==typeof t&&"errors"in t&&"three_ds_result"in t&&W(t.errors)&&ve(t.errors,{code:"three_d_secure_required"}));var t}(e))throw e;const{three_ds_result:t}=e.body,{acs_url:n,payer_auth_request:i,merchant_data:r}=t||{};if(!n||!i||!r)throw new co(["formUrl","threeDSSessionData","creq"]);return new Promise(e=>{this.formPoster.postForm(n,{threeDSSessionData:i,creq:r},e,"_top")})})}}const ls=vi(e=>new ra(e,new aa(da(),new cs(e,Ee()),n(),Ee())),[{id:"googlepaytdonlinemart"}]);var us,hs,ps,ms,ys,gs,vs,fs,Ss,_s,ws=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Is{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,n,i,r){return ws(this,void 0,void 0,function*(){if(!this.window.paypal||r){const r=this.getPayPalSdkScriptConfigOrThrow(e,t,n,i);if(yield this.loadPayPalSdk(r),!this.window.paypal)throw new mi}return this.window.paypal})}getPayPalFastlaneSdk(e,t,n,i){return ws(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const r=this.getPayPalFastlaneSdkConfiguration(e,t,n,i);if(yield this.loadPayPalSdk(r),!this.window.paypalFastlaneSdk)throw new mi}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,n,i,r){return ws(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||r){const r=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i);yield this.loadPayPalSdk(r)}if(!this.window.paypalGooglePay)throw new mi;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t,n){return ws(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t,n);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new mi}return this.window.paypalApms})}getPayPalMessages(e,t,n){return ws(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t,n);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new mi;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return ws(this,void 0,void 0,function*(){const n=this.transformConfig(e),i=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(n).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:i})})}getPayPalSdkScriptConfigOrThrow(e,t,n,i=!0){const{id:r,clientToken:o,initializationData:a}=e;if(!a||!a.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:s,clientId:d,merchantId:c,buyerCountry:l,attributionId:u,isVenmoEnabled:h,isHostedCheckoutEnabled:p,isPayPalCreditAvailable:m,isDeveloperModeApplicable:y,availableAlternativePaymentMethods:g=[],enabledAlternativePaymentMethods:v=[],isGooglePayEnabled:f}=a,S=p||i,_="paypalcommercecreditcards"===r||"bigcommerce_payments_creditcards"===r,w=_?["card"]:[],I=m?["credit","paylater"]:[],C=h?["venmo"]:[],b=f?["googlepay"]:[],P=i?["card-fields"]:[],O=[..._?[]:["card"],...m?[]:["credit","paylater"],...h?[]:["venmo"],...g.filter(e=>!v.includes(e))],E=[...w,...I,...C,...v],A=Za(n);return{options:Object.assign(Object.assign({"client-id":d,"merchant-id":c,"enable-funding":E.length>0?E:void 0,"disable-funding":O.length>0?O:void 0,commit:S,components:["buttons","hosted-fields","payment-fields","legal",...b,...P],currency:t,intent:s},y&&{"buyer-country":l}),A&&{locale:A}),attributes:{"data-partner-attribution-id":u,"data-client-token":o}}}getPayPalFastlaneSdkConfiguration(e,t,n,i){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,attributionId:c}=o,l=Za(i);return{options:Object.assign(Object.assign({"client-id":s,"merchant-id":d,commit:!0,components:["fastlane","buttons","payment-fields","hosted-fields","three-domain-secure"],currency:t},l&&{locale:l}),{intent:a}),attributes:{"data-client-metadata-id":n.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":c,"data-sdk-client-token":r}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i=!0){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:c,attributionId:l,isHostedCheckoutEnabled:u,isDeveloperModeApplicable:h}=o,p=u||i,m=Za(n);return{options:Object.assign(Object.assign({"client-id":s,"merchant-id":d,commit:p,components:["googlepay"],currency:t,intent:a},h&&{"buyer-country":c}),m&&{locale:m}),attributes:{"data-partner-attribution-id":l,"data-client-token":r,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:r,clientId:o,merchantId:a,buyerCountry:s,attributionId:d,isDeveloperModeApplicable:c,availableAlternativePaymentMethods:l=[],enabledAlternativePaymentMethods:u=[]}=i,h=u,p=l.filter(e=>!u.includes(e)),m=Za(n);return{options:Object.assign(Object.assign({"client-id":o,"merchant-id":a,"enable-funding":h.length>0?h:void 0,"disable-funding":p.length>0?p:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:r},c&&{"buyer-country":s}),m&&{locale:m}),attributes:{"data-partner-attribution-id":d,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ti(Xn.MissingPaymentMethod);const{clientId:r,merchantId:o,attributionId:a,isDeveloperModeApplicable:s,buyerCountry:d}=i,c=Za(n);return{options:Object.assign(Object.assign({"client-id":r,"merchant-id":o,components:["messages"],currency:t},s&&{"buyer-country":d}),c&&{locale:c}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":a}}}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}function Cs(){return new Is(a())}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(us||(us={})),(hs||(hs={})).Always="SCA_ALWAYS",function(e){e.Succeeded="succeeded",e.Cancelled="cancelled",e.Errored="errored"}(ps||(ps={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(ms||(ms={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(ys||(ys={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(gs||(gs={})),function(e){e.pill="pill",e.rect="rect"}(vs||(vs={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="canceled",e.UNRECOGNIZED="unrecognized"}(fs||(fs={})),(Ss||(Ss={})).OXXO="oxxo",function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(_s||(_s={}));var bs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ps{constructor(e,t,n,i){this.formPoster=e,this.paymentIntegrationService=t,this.paypalRequestSender=n,this.paypalSdkLoader=i}loadPayPalSdk(e,t,n,i){return bs(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e),s=r.getLocale();return this.paypalSdk=yield this.paypalSdkLoader.getPayPalSDK(a,o,s,n,i),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new mi;return this.paypalSdk}createBuyNowCartOrThrow(e){return bs(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}})}createOrder(e,t){return bs(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i}=yield this.paypalRequestSender.createOrder(e,Object.assign({cartId:n},t));return i})}createOrderCardFields(e,t){return bs(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i,setupToken:r}=yield this.paypalRequestSender.createOrder(e,Object.assign({cartId:n},t));return Object.assign({orderId:i},r?{setupToken:r}:{})})}updateOrder(e,t,n){return bs(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),r=i.getCartOrThrow(),o=i.getConsignmentsOrThrow()[0];try{yield this.paypalRequestSender.updateOrder(e,Object.assign(Object.assign({availableShippingOptions:o.availableShippingOptions,cartId:r.id,selectedShippingOption:o.selectedShippingOption},t?{methodId:t}:{}),n?{orderId:n}:{}))}catch(e){throw new nr}})}getOrderStatus(e,t){return bs(this,void 0,void 0,function*(){try{const{status:n}=yield this.paypalRequestSender.getOrderStatus(e,t);return n}catch(e){throw new nr}})}tokenizePayment(e,t){const n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new ti(Xn.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===xt.BuyNow&&{cart_id:n.id}))}submitPayment(e,t,n){return bs(this,void 0,void 0,function*(){const i={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}};yield this.paymentIntegrationService.submitPayment(Object.assign({methodId:e,paymentData:i},n?{gatewayId:n}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],i=n.find(e=>e.isRecommended),r=(e?n.find(t=>t.id===e):n.find(e=>{if(t.selectedShippingOption){const n=t.selectedShippingOption.id;return e.id===n}return!1}))||i||n[0];if(!r)throw new Error("Your order can't be shipped to this address");return r}getAddress(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:(null==e?void 0:e.phone)||"",company:"",address1:(null==e?void 0:e.address1)||"",address2:(null==e?void 0:e.address2)||"",city:(null==e?void 0:e.city)||"",countryCode:(null==e?void 0:e.countryCode)||"",postalCode:(null==e?void 0:e.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==e?void 0:e.stateOrProvinceCode)||"",customFields:[]}}getBillingAddressFromOrderDetails({payer:e}){var t,n;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,address2:e.address.address_line_2,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1,phone:null===(n=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===n?void 0:n.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:n}=e,{address:i,name:{full_name:r}}=n[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:i.address_line_1,address2:i.address_line_2,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})}getValidButtonStyle(e={}){const{color:t,height:n,label:i,shape:r}=e,o={color:t&&gs[t]?t:void 0,height:this.getValidHeight(n),label:i&&ys[i]?i:void 0,shape:r&&vs[r]?r:void 0};return ue(o,J)}getValidHeight(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40}removeElement(e){const t=e&&document.getElementById(e);t&&(t.style.display="none")}}var Os=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Es{constructor(e){this.requestSender=e}createOrder(e,t){return Os(this,void 0,void 0,function*(){const n=`/api/storefront/payment/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.post(n,{headers:r,body:i})).body})}updateOrder(e,t){return Os(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.put(n,{headers:r,body:i})).body})}getOrderStatus(e,t){return Os(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body})}}const As=e=>{const{getHost:t}=e.getState();return new Ps(Ee(),e,new Es(n({host:t()})),Cs())};var Ts=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const ks=class{constructor(e,t){this.paymentIntegrationService=e,this.paypalIntegrationService=t}createPayPalButton(e,t,n,i){const{style:r,fundingSource:o,isAppSwitchEnabled:a,isHostedCheckoutEnabled:s,onClick:d,onCancel:c,onPaymentComplete:l,onError:u}=n;this.onError=u;const h=this.paypalIntegrationService.getPayPalSdkOrThrow();if(!Object.values(h.FUNDING).includes(o))throw new fi('Unable to initialize PayPal button because "fundingSource" argument is not valid funding source.');const p=Object.assign(Object.assign({},!a&&{onShippingAddressChange:t=>this.onShippingAddressChange(t,e),onShippingOptionsChange:t=>this.onShippingOptionsChange(t,e)}),{onApprove:(n,i)=>this.onHostedCheckoutApprove(n,i,t,e,l)});return h.Buttons(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({fundingSource:o,style:this.paypalIntegrationService.getValidButtonStyle(r)},a&&{appSwitchWhenAvailable:!0}),{createOrder:()=>Ts(this,void 0,void 0,function*(){if(i){const e=yield this.paypalIntegrationService.createBuyNowCartOrThrow(i);yield this.paymentIntegrationService.loadCheckout(e.id)}return this.paypalIntegrationService.createOrder(e)}),onApprove:({orderID:e})=>this.paypalIntegrationService.tokenizePayment(t,e)}),d?{onClick:d}:{}),c?{onCancel:c}:{}),s&&p))}onHostedCheckoutApprove(e,t,n,i,r){return Ts(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const o=this.paymentIntegrationService.getState().getCartOrThrow(),a=yield t.order.get();try{const t=this.paypalIntegrationService.getBillingAddressFromOrderDetails(a);if(yield this.paymentIntegrationService.updateBillingAddress(t),o.lineItems.physicalItems.length>0){const e=this.paypalIntegrationService.getShippingAddressFromOrderDetails(a);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.paypalIntegrationService.updateOrder(i)}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.paypalIntegrationService.submitPayment(n,e.orderID),r&&"function"==typeof r&&r()}catch(e){this.handleError(e)}})}onShippingAddressChange(e,t){return Ts(this,void 0,void 0,function*(){const n=this.paypalIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(n),yield this.paymentIntegrationService.updateShippingAddress(n);const e=this.paypalIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.paypalIntegrationService.updateOrder(t)}catch(e){this.handleError(e)}})}onShippingOptionsChange(e,t){return Ts(this,void 0,void 0,function*(){const n=this.paypalIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(n.id),yield this.paypalIntegrationService.updateOrder(t)}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}};var Ds=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ms{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.paypalButtonCreationService=n}initialize(e){return Ds(this,void 0,void 0,function*(){const{paypalcommerce:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.paypalcommerce.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.paypalcommerce.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.paypalIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Ds(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return Ds(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){var n,i;const{container:r,onClick:o,onComplete:a,onError:s}=t,d=this.paypalIntegrationService.getPayPalSdkOrThrow(),c=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:l,paymentButtonStyles:u,isAppSwitchEnabled:h}=c.initializationData||{},{checkoutTopButtonStyles:p}=u||{},m=Object.assign(Object.assign(Object.assign({fundingSource:d.FUNDING.PAYPAL,isAppSwitchEnabled:h,isHostedCheckoutEnabled:l,style:Object.assign(Object.assign({},p),{height:wr})},o&&{onClick:()=>o()}),l&&a&&{onPaymentComplete:()=>a()}),{onError:s}),y=this.paypalButtonCreationService.createPayPalButton("paypalcommerce",e,m);y.isEligible()?(null===(n=y.hasReturned)||void 0===n?void 0:n.call(y))&&h?null===(i=y.resume)||void 0===i||i.call(y):y.render(`#${r}`):this.paypalIntegrationService.removeElement(r)}}const zs=vi(e=>{const t=As(e),n=new ks(e,t);return new Ms(e,t,n)},[{id:"paypalcommerce"}]);var Ns,xs,Rs,Fs,Ls,Bs,js;!function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(Ns||(Ns={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(xs||(xs={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Rs||(Rs={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(Fs||(Fs={})),function(e){e.pill="pill",e.rect="rect"}(Ls||(Ls={})),function(e){e.OXXO="oxxo",e.IDEAL="ideal"}(Bs||(Bs={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(js||(js={}));var Us=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class qs{constructor(e,t,n,i){this.formPoster=e,this.paymentIntegrationService=t,this.paypalCommerceRequestSender=n,this.paypalCommerceScriptLoader=i}loadPayPalSdk(e,t,n,i){return Us(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e);return this.paypalSdk=yield this.paypalCommerceScriptLoader.getPayPalSDK(a,o,r.getLocale(),n,i),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new mi;return this.paypalSdk}createBuyNowCartOrThrow(e){return Us(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}})}createOrder(e,t){return Us(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i}=yield this.paypalCommerceRequestSender.createOrder(e,Object.assign({cartId:n},t));return i})}createOrderCardFields(e,t){return Us(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i,setupToken:r}=yield this.paypalCommerceRequestSender.createOrder(e,Object.assign({cartId:n},t));return Object.assign({orderId:i},r?{setupToken:r}:{})})}updateOrder(){return Us(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getConsignmentsOrThrow()[0];try{yield this.paypalCommerceRequestSender.updateOrder({availableShippingOptions:n.availableShippingOptions,cartId:t.id,selectedShippingOption:n.selectedShippingOption})}catch(e){throw new nr}})}getOrderStatus(e,t){return Us(this,void 0,void 0,function*(){try{const{status:n}=yield this.paypalCommerceRequestSender.getOrderStatus(e,t);return n}catch(e){throw new nr}})}tokenizePayment(e,t){const n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new ti(Xn.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===xt.BuyNow&&{cart_id:n.id}))}submitPayment(e,t,n){return Us(this,void 0,void 0,function*(){const i={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}};yield this.paymentIntegrationService.submitPayment(Object.assign({methodId:e,paymentData:i},n?{gatewayId:n}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],i=n.find(e=>e.isRecommended),r=(e?n.find(t=>t.id===e):n.find(e=>{var n;return e.id===(null===(n=t.selectedShippingOption)||void 0===n?void 0:n.id)}))||i||n[0];if(!r)throw new Error("Your order can't be shipped to this address");return r}getAddress(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:(null==e?void 0:e.phone)||"",company:"",address1:(null==e?void 0:e.address1)||"",address2:(null==e?void 0:e.address2)||"",city:(null==e?void 0:e.city)||"",countryCode:(null==e?void 0:e.countryCode)||"",postalCode:(null==e?void 0:e.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==e?void 0:e.stateOrProvinceCode)||"",customFields:[]}}getBillingAddressFromOrderDetails({payer:e}){var t,n;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,address2:e.address.address_line_2,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1,phone:null===(n=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===n?void 0:n.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:n}=e,{address:i,name:{full_name:r}}=n[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:i.address_line_1,address2:i.address_line_2,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})}getValidButtonStyle(e){const{color:t,height:n,label:i,shape:r}=e||{},o={color:t&&Fs[t]?t:void 0,height:this.getValidHeight(n),label:i&&Rs[i]?i:void 0,shape:r&&Ls[r]?r:void 0};return ue(o,J)}getValidHeight(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40}removeElement(e){const t=e&&document.getElementById(e);t&&(t.style.display="none")}}var Vs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Gs{constructor(e){this.requestSender=e}createOrder(e,t){return Vs(this,void 0,void 0,function*(){const n=`/api/storefront/payment/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.post(n,{headers:r,body:i})).body})}updateOrder(e){return Vs(this,void 0,void 0,function*(){const t=e,n=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.put("/api/storefront/initialization/paypalcommerce",{headers:n,body:t})).body})}getOrderStatus(e="paypalcommerce",t){return Vs(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body})}}var Hs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ws{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,n,i,r){return Hs(this,void 0,void 0,function*(){const o=this.getPayPalSdkScriptConfigOrThrow(e,t,n,i);return this.loadPayPalSDK(o,r)})}loadPayPalSDK(e,t=!1){return Hs(this,void 0,void 0,function*(){if(!this.window.paypal||t){const t=this.transformConfig(e.options),n=this.transformConfig(e.attributes),i=`https://www.paypal.com/sdk/js?${new URLSearchParams(t).toString()}`;yield this.scriptLoader.loadScript(i,{async:!0,attributes:n})}if(!this.window.paypal)throw new mi;return this.window.paypal})}getPayPalSdkScriptConfigOrThrow(e,t,n,i=!0){const{id:r,clientToken:o,initializationData:a}=e;if(!(null==a?void 0:a.clientId))throw new ti(Xn.MissingPaymentMethod);const{intent:s,clientId:d,merchantId:c,buyerCountry:l,attributionId:u,isVenmoEnabled:h,isHostedCheckoutEnabled:p,isPayPalCreditAvailable:m,isDeveloperModeApplicable:y,availableAlternativePaymentMethods:g=[],enabledAlternativePaymentMethods:v=[],isGooglePayEnabled:f}=a,S=p||i,_="paypalcommercecreditcards"===r,w=_?["card"]:[],I=m?["credit","paylater"]:[],C=h?["venmo"]:[],b=f?["googlepay"]:[],P=i?["card-fields"]:[],O=[..._?[]:["card"],...m?[]:["credit","paylater"],...h?[]:["venmo"],...g.filter(e=>!v.includes(e))],E=[...w,...I,...C,...v],A=Za(n);return{options:Object.assign(Object.assign({"client-id":d,"merchant-id":c,"enable-funding":E.length>0?E:void 0,"disable-funding":O.length>0?O:void 0,commit:S,components:["buttons","hosted-fields","payment-fields","legal",...b,...P],currency:t,intent:s},y&&{"buyer-country":l}),A&&{locale:A}),attributes:{"data-partner-attribution-id":u,"data-client-token":o}}}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}const $s=e=>{const{getHost:t}=e.getState();return new qs(Ee(),e,new Gs(n({host:t()})),new Ws(a()))};var Ys=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ks{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.onError=ce}initialize(e){return Ys(this,void 0,void 0,function*(){const{paypalcommercecredit:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.paypalcommercecredit.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.paypalcommercecredit.onClick" argument is not a function.');this.onError=t.onError||ce,this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.paypalCommerceIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Ys(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Ys(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){const{container:n,onComplete:i,onClick:r}=t,o=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:s,paymentButtonStyles:d,isAppSwitchEnabled:c}=a.initializationData||{},{checkoutTopButtonStyles:l}=d||{},u=Object.assign({createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercecredit"),onApprove:({orderID:t})=>this.paypalCommerceIntegrationService.tokenizePayment(e,t)},r&&{onClick:()=>r()}),h=Object.assign(Object.assign({},!c&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(t,n)=>this.onHostedCheckoutApprove(t,n,e,i)}),p=[o.FUNDING.PAYLATER,o.FUNDING.CREDIT];let m=!1;p.forEach(e=>{if(!m){const t=Object.assign(Object.assign({fundingSource:e,style:this.paypalCommerceIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},l),{height:wr}))},u),s&&h),i=o.Buttons(t);i.isEligible()&&(i.render(`#${n}`),m=!0)}}),m||this.paypalCommerceIntegrationService.removeElement(n)}onHostedCheckoutApprove(e,t,n,i){return Ys(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.paypalCommerceIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.paypalCommerceIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Ys(this,void 0,void 0,function*(){const t=this.paypalCommerceIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.paypalCommerceIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}onShippingOptionsChange(e){return Ys(this,void 0,void 0,function*(){const t=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.paypalCommerceIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const Js=vi(e=>new Ks(e,$s(e)),[{id:"paypalcommercecredit"}]);var Zs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Qs{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}initialize(e){return Zs(this,void 0,void 0,function*(){const{paypalcommercevenmo:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.paypalCommerceIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Zs(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Zs(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){const{container:n,onClick:i}=t,r=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:a}=o.initializationData||{},{checkoutTopButtonStyles:s}=a||{},d=Object.assign({fundingSource:r.FUNDING.VENMO,style:this.paypalCommerceIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},s),{height:wr})),createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo"),onApprove:({orderID:t})=>this.paypalCommerceIntegrationService.tokenizePayment(e,t)},i&&{onClick:()=>i()}),c=r.Buttons(d);c.isEligible()?c.render(`#${n}`):this.paypalCommerceIntegrationService.removeElement(n)}}const Xs=vi(e=>new Qs(e,$s(e)),[{id:"paypalcommercevenmo"}]);var ed=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class td{constructor(){this.window=window}initializePayPalFastlane(e,t,n){return ed(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("fastlaneEnv","sandbox"),window.localStorage.setItem("axoEnv","sandbox")),!this.window.paypalFastlane){const t={root:{backgroundColorPrimary:"transparent"}};this.window.paypalFastlane=yield e.Fastlane({styles:n||t})}return this.window.paypalFastlane})}getPayPalFastlaneOrThrow(){if(!this.window.paypalFastlane)throw new mi;return this.window.paypalFastlane}lookupCustomerOrThrow(e){return ed(this,void 0,void 0,function*(){return this.getPayPalFastlaneOrThrow().identity.lookupCustomerByEmail(e)})}triggerAuthenticationFlowOrThrow(e){return ed(this,void 0,void 0,function*(){return e?this.getPayPalFastlaneOrThrow().identity.triggerAuthenticationFlow(e):{}})}updateStorageSessionId(e){const t=new Date;t.setDate(t.getDate()+14);const n={expires:t,secure:!0};Fr.set("bc-fastlane-sessionId",e,n)}removeStorageSessionId(){Fr.remove("bc-fastlane-sessionId")}getStorageSessionId(){return Fr.get("bc-fastlane-sessionId")||""}mapPayPalFastlaneProfileToBcCustomerData(e,t){var n,i,r;const{authenticationState:o,profileData:a}=t,s=null===(r=null===(i=null===(n=null==a?void 0:a.card)||void 0===n?void 0:n.paymentSource)||void 0===i?void 0:i.card)||void 0===r?void 0:r.billingAddress,d=null==a?void 0:a.shippingAddress,c=null==a?void 0:a.name,l=null==a?void 0:a.card,u=d?this.mapPayPalToBcAddress(d.address,d.name,d.phoneNumber):void 0,h=s&&c?this.mapPayPalToBcAddress(s,c,null==d?void 0:d.phoneNumber):void 0,p=l?this.mapPayPalToBcInstrument(e,l):[],m=this.filterAddresses([u,h]);return{authenticationState:o||fs.UNRECOGNIZED,addresses:m,billingAddress:h,shippingAddress:u,instruments:p}}mapPayPalToBcInstrument(e,t){const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a}=i.card,[s,d]=o.split("-");return[{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:Pr.PAN,type:"card"}]}mapBcToPayPalAddress(e){return{company:(null==e?void 0:e.company)||"",addressLine1:(null==e?void 0:e.address1)||"",addressLine2:(null==e?void 0:e.address2)||"",adminArea1:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",adminArea2:(null==e?void 0:e.city)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||""}}mapPayPalToBcAddress(e,t,n,i){const[r,o]=t.fullName.split(" "),a=(null==n?void 0:n.nationalNumber)||"",s=(null==n?void 0:n.countryCode)||"";return{id:Date.now(),type:"paypal-address",firstName:t.firstName||r||"",lastName:t.lastName||o||"",company:e.company||"",address1:e.addressLine1,address2:e.addressLine2||"",city:e.adminArea2,stateOrProvince:e.adminArea1,stateOrProvinceCode:e.adminArea1,country:e.countryCode||"",countryCode:e.countryCode||"",postalCode:e.postalCode,phone:s+a,customFields:i||[]}}filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this.isEqualAddresses(e,t))?e:[...e,t]:e,[])}isEqualAddresses(e,t){return Y(this.normalizeAddress(e),this.normalizeAddress(t))}normalizeAddress(e){return le(e,["id","phone"])}}function nd(){return new td}function id(e){return"string"!=typeof e}function rd(e,t){if(t||e)return function(e){var t,n;const i={},r=ue(e.root,id),o=ue(e.input,id),a=ue(e.toggle,id),s=ue(null===(t=e.text)||void 0===t?void 0:t.body,id),d=ue(null===(n=e.text)||void 0===n?void 0:n.caption,id),c=e.branding;return Object.keys(r).length&&(i.root=r),Object.keys(o).length&&(i.input=o),Object.keys(a).length&&(i.toggle=a),Object.keys(s).length&&(i.text={},i.text.body=s),Object.keys(d).length&&(i.text=Object.assign({},i.text),i.text.caption=d),c&&(i.branding=c),i}(function(e,t){var n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,_,w,I,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(c=null==t?void 0:t.input)||void 0===c?void 0:c.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.focusBorderColor),backgroundColor:(null==e?void 0:e.fastlaneInputSettingsBackgroundColor)||(null===(u=null==t?void 0:t.input)||void 0===u?void 0:u.backgroundColor),borderWidth:(null==e?void 0:e.fastlaneInputSettingsBorderWidth)||(null===(h=null==t?void 0:t.input)||void 0===h?void 0:h.borderWidth),textColorBase:(null==e?void 0:e.fastlaneInputSettingsTextColorBase)||(null===(p=null==t?void 0:t.input)||void 0===p?void 0:p.textColorBase)},toggle:{colorPrimary:(null==e?void 0:e.fastlaneToggleSettingsColorPrimary)||(null===(m=null==t?void 0:t.toggle)||void 0===m?void 0:m.colorPrimary),colorSecondary:(null==e?void 0:e.fastlaneToggleSettingsColorSecondary)||(null===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(S=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===S?void 0:S.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(w=null===(_=null==t?void 0:t.text)||void 0===_?void 0:_.caption)||void 0===w?void 0:w.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(I=null==t?void 0:t.text)||void 0===I?void 0:I.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var od=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ad{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalSdkScriptLoader=t,this.paypalFastlaneUtils=n}initialize(e){var t;return od(this,void 0,void 0,function*(){const{methodId:n,paypalcommercefastlane:i}=e;if(!n)throw new fi('Unable to proceed because "methodId" argument is not provided.');try{yield this.paymentIntegrationService.loadPaymentMethod(n);const e=this.paymentIntegrationService.getState(),r=e.getCartOrThrow(),o=e.getPaymentMethodOrThrow(n),a=!!(null===(t=o.initializationData)||void 0===t?void 0:t.isDeveloperModeApplicable),s=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(o,r.currency.code,r.id,e.getLocale());yield this.paypalFastlaneUtils.initializePayPalFastlane(s,a,this.getFastlaneStyles(n,i))}catch(e){}return Promise.resolve()})}deinitialize(){return od(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return od(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:void 0,addresses:void 0,instruments:void 0}),this.paypalFastlaneUtils.removeStorageSessionId()})}signOut(e){return od(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return od(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:n,methodId:i}=e||{};if(!i)throw new fi('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof n)throw new fi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(this.paymentIntegrationService.getState().getCustomerOrThrow().isGuest){t&&"function"==typeof t&&t();try{yield this.runPayPalAuthenticationFlowOrThrow(i)}catch(e){}}n()})}runPayPalAuthenticationFlowOrThrow(e){return od(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow().id,i=t.getCustomer(),r=t.getBillingAddress(),o=(null==i?void 0:i.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.paypalFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.paypalFastlaneUtils.triggerAuthenticationFlowOrThrow(a),d=s.authenticationState===fs.CANCELED;yield this.updateCustomerDataState(e,s),d?this.paypalFastlaneUtils.removeStorageSessionId():this.paypalFastlaneUtils.updateStorageSessionId(n)})}updateCustomerDataState(e,t){var n;return od(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow(),{authenticationState:r,addresses:o,billingAddress:a,shippingAddress:s,instruments:d}=this.paypalFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,t);if(yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:r,addresses:o,instruments:d}),a&&(yield this.paymentIntegrationService.updateBillingAddress(a)),s&&i.lineItems.physicalItems.length>0){const t=yield this.paymentIntegrationService.updateShippingAddress(s),i=t.getPaymentMethodOrThrow(e),{isFastlaneShippingOptionAutoSelectEnabled:r}=i.initializationData||{},o=t.getConsignments()||[],a=(null===(n=o[0])||void 0===n?void 0:n.availableShippingOptions)||[],d=a[0],c=a.find(e=>e.isRecommended);if((c||d)&&r){const e=(null==c?void 0:c.id)||d.id;yield this.paymentIntegrationService.selectShippingOption(e)}}})}getFastlaneStyles(e,t){const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{fastlaneStyles:i,isFastlaneStylingEnabled:r}=n.initializationData||{};return rd(r?i:{},null==t?void 0:t.styles)}}const sd=vi(e=>new ad(e,Cs(),nd()),[{id:"paypalcommerceacceleratedcheckout"},{id:"paypalcommercecreditcards"}]);function dd(e){return"object"==typeof e&&null!==e&&"initializationData"in e&&void 0!==e.initializationData&&null!==e.initializationData&&"object"==typeof e.initializationData&&"stripePublishableKey"in e.initializationData&&"stripeConnectedAccount"in e.initializationData&&"shopperLanguage"in e.initializationData&&void 0!==e.initializationData.stripePublishableKey&&void 0!==e.initializationData.stripeConnectedAccount&&void 0!==e.initializationData.shopperLanguage}function cd(e){return"stripeLinkAuthenticationState"in e}class ld{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){var t,n,i,r,o;return n=this,i=void 0,o=function*(){let n;if(!e.stripeupe)throw new fi('Unable to proceed because "options" argument is not provided.');const{container:i,gatewayId:r,methodId:o,onEmailChange:a,getStyles:s,isLoading:d}=e.stripeupe;Object.entries(e.stripeupe).forEach(([e,t])=>{if(!t)throw new fi(`Unable to proceed because "${e}" argument is not provided.`)}),yield this.paymentIntegrationService.loadPaymentMethod(r,{params:{method:o}});const c=this.paymentIntegrationService.getState(),l=c.getPaymentMethodOrThrow(o,r),{clientToken:u}=l;if(!dd(l)||!u)throw new ti(Xn.MissingPaymentToken);const{email:h}=c.getCustomerOrThrow(),p=c.getPaymentProviderCustomerOrThrow(),m=(cd(p)?p:{}).stripeLinkAuthenticationState;if(!h){let e;const r="function"==typeof s&&s();e=r?{variables:{colorPrimary:r.fieldInnerShadow,colorBackground:r.fieldBackground,colorText:r.labelText,colorDanger:r.fieldErrorText,colorTextSecondary:r.labelText,colorTextPlaceholder:r.fieldPlaceholderText},rules:{".Input":{borderColor:r.fieldBorder,color:r.fieldText,boxShadow:r.fieldInnerShadow}}}:{},n=yield this.scriptLoader.getStripeClient(l.initializationData,c.getCartLocale(),ka.V3,Fa,La),this._stripeElements=yield this.scriptLoader.getElements(n,{clientSecret:u,appearance:e});const{getBillingAddress:o,getConsignments:h}=this.paymentIntegrationService.getState(),p=h(),y=null===(t=null==p?void 0:p[0])||void 0===t?void 0:t.id,{email:g}=o()||{},v=g?{defaultValues:{mode:Ca.SHIPPING,email:g}}:{},f=this._stripeElements.getElement(Da.AUTHENTICATION)||this._stripeElements.create(Da.AUTHENTICATION,v);f.on(za.CHANGE,e=>{if(!("authenticated"in e))throw new ti(Xn.MissingCustomer);this.paymentIntegrationService.updatePaymentProviderCustomer({stripeLinkAuthenticationState:e.authenticated}),e.complete?a(e.authenticated,e.value.email):a(!1,""),d&&d(!1),void 0===m&&e.authenticated&&y&&this.paymentIntegrationService.deleteConsignment(y)}),f.mount(`#${i}`)}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}deinitialize(){var e,t;return null===(t=null===(e=this._stripeElements)||void 0===e?void 0:e.getElement(Da.AUTHENTICATION))||void 0===t||t.unmount(),Promise.resolve()}signIn(e,t){return this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()}signOut(e){return this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}}const ud=vi(e=>new ld(e,new Ra(a())),[{id:"stripeupe"}]);var hd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pd{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t,this.isMounted=!1}deinitialize(){var e;null===(e=this.checkoutEventsUnsubscribe)||void 0===e||e.call(this),this.isMounted=!1}initCheckoutEventsSubscription(e,t,n,i){this.checkoutEventsUnsubscribe=this.paymentIntegrationService.subscribe(()=>hd(this,void 0,void 0,function*(){var r;const o=null==i?void 0:i.getElement(Da.PAYMENT);if(o){try{yield this.updateStripePaymentIntent(e,t)}catch(e){return this.isMounted&&(o.unmount(),this.isMounted=!1),void(e instanceof Error&&(null===(r=n.onError)||void 0===r||r.call(n,e)))}this.isMounted||(yield null==i?void 0:i.fetchUpdates(),this.mountElement(o,n.containerId))}}),e=>{var t;return null===(t=e.getCheckout())||void 0===t?void 0:t.outstandingBalance},e=>{var t;return null===(t=e.getCheckout())||void 0===t?void 0:t.coupons})}mountElement(e,t){document.getElementById(t)&&(e.mount(`#${t}`),this.isMounted=!0)}mapAppearanceVariables(e){return{colorPrimary:e.fieldInnerShadow,colorBackground:e.fieldBackground,colorText:e.labelText,colorDanger:e.fieldErrorText,colorTextSecondary:e.labelText,colorTextPlaceholder:e.fieldPlaceholderText,colorIcon:e.fieldPlaceholderText}}mapInputAppearanceRules(e){return{borderColor:e.fieldBorder,color:e.fieldText,boxShadow:e.fieldInnerShadow}}throwStripeError(e){if("object"==typeof(t=e)&&null!==t&&"type"in t&&(this.throwDisplayableStripeError(e),this.isCancellationError(e)))throw new Wi;var t;throw new Qr}throwDisplayableStripeError(e){if(H(["card_error","invalid_request_error","validation_error"],e.type))throw new Error(e.message)}isCancellationError(e){var t;const n=null===(t=null==e?void 0:e.payment_intent.last_payment_error)||void 0===t?void 0:t.message;return!!n&&-1!==n.indexOf("canceled")}throwPaymentConfirmationProceedMessage(){throw new Qr("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.")}isPaymentCompleted(e,t){return hd(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getPaymentMethodOrThrow(e),{features:r}=n.getStoreConfigOrThrow().checkoutSettings;if(!i.clientToken||!t||!r["PI-626.Block_unnecessary_payment_confirmation_for_StripeUPE"])return!1;const{paymentIntent:o}=yield t.retrievePaymentIntent(i.clientToken);return(null==o?void 0:o.status)===Ma.SUCCEEDED})}mapStripePaymentData(e,t,n=!1){const i=this.paymentIntegrationService.getState().getBillingAddress(),{firstName:r="",lastName:o="",email:a=""}=i||{},s=this.mapStripeAddress(i);if(!e)throw new ri(ei.PaymentNotInitialized);if(!(a&&s&&s.city&&s.country&&r&&o))throw new ti(Xn.MissingBillingAddress);return{elements:e,redirect:Ta.IF_REQUIRED,confirmParams:Object.assign({payment_method_data:Object.assign(Object.assign({},n?{allow_redisplay:"always"}:{}),{billing_details:{email:a,address:s,name:this.getShopperFullName(i)}})},t&&{return_url:t})}}isAdditionalActionError(e){return ve(e,{code:"additional_action_required"})}isRedirectAction(e){const{type:t,data:{redirect_url:n}}=e;return"redirect_to_url"===t&&!!n}isOnPageAdditionalAction(e){const{type:t,data:{token:n}}=e;return"additional_action_requires_payment_method"===t&&!!n}updateStripePaymentIntent(e,t){return hd(this,void 0,void 0,function*(){const n=yield this.paymentIntegrationService.loadPaymentMethod(e,{params:{method:t}}),{clientToken:i}=n.getPaymentMethodOrThrow(t);i&&this.scriptLoader.updateStripeElements({clientSecret:i})})}getStripeJsVersion(e){return e.useNewStripeJsVersion?ka.CLOVER:ka.V3}mapStripeAddress(e){if(e){const{city:t,address1:n,address2:i,countryCode:r,postalCode:o,stateOrProvinceCode:a}=e;return Object.assign({city:t,country:r,postal_code:o,line1:n,line2:i},a?{state:a}:{})}throw new ti(Xn.MissingBillingAddress)}getShopperFullName(e){const{firstName:t="",lastName:n=""}=e||{};return`${t} ${n}`.trim()}}const md={size:70,color:"#d9d9d9",backgroundColor:"#ffffff"},yd={position:"fixed","background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},gd="embedded-checkout-loading-indicator-rotation";class vd{constructor(e){this.styles=Object.assign(Object.assign({},md),e&&e.styles),this.containerStyles=Object.assign({},e&&e.containerStyles),this.defineAnimation(),this.container=this.buildContainer(),this.indicator=this.buildIndicator(),this.container.appendChild(this.indicator)}show(e){if(e){const t=document.getElementById(e);if(!t)throw new Error("Unable to attach the loading indicator because the parent ID is not valid.");t.appendChild(this.container)}this.container.style.visibility="visible",this.container.style.opacity="1"}hide(){const e=()=>{this.container.style.visibility="hidden",this.container.removeEventListener("transitionend",e)};this.container.addEventListener("transitionend",e),this.container.style.opacity="0"}buildContainer(){const e=document.createElement("div");return e.style.display="block",e.style.bottom="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.position="absolute",e.style.right="0",e.style.top="0",e.style.transition="all 250ms ease-out",e.style.opacity="0",this.setStyleAttribute(e,this.containerStyles),e}buildIndicator(){const e=document.createElement("div");return e.style.display="block",e.style.width=`${this.styles.size}px`,e.style.height=`${this.styles.size}px`,e.style.borderRadius=`${this.styles.size}px`,e.style.border="solid 1px",e.style.borderColor=`${this.styles.backgroundColor} ${this.styles.backgroundColor} ${this.styles.color} ${this.styles.color}`,e.style.margin="0 auto",e.style.position="absolute",e.style.left="0",e.style.right="0",e.style.top="50%",e.style.transform="translateY(-50%) rotate(0deg)",e.style.transformStyle="preserve-3d",e.style.animation=`${gd} 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)`,e}setStyleAttribute(e,t){Object.keys(t).forEach(n=>{e.style.setProperty(n,t[n])})}defineAnimation(){var e;if(document.getElementById(gd))return;const t=document.createElement("style");t.id=gd,null===(e=document.head)||void 0===e||e.appendChild(t),t.sheet instanceof CSSStyleSheet&&t.sheet.insertRule(`\n @keyframes ${gd} {\n 0% { transform: translateY(-50%) rotate(0deg); }\n 100% { transform: translateY(-50%) rotate(360deg); }\n }\n `,0)}}class fd{constructor(e){this._decimalPlaces=e}toInteger(e){return Math.round(e*Math.pow(10,this._decimalPlaces))}}const Sd=["AC","AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CV","CW","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MK","ML","MM","MN","MO","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SZ","TA","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","US","UY","UZ","VA","VC","VE","VG","VN","VU","WF","WS","XK","YE","YT","ZA","ZM","ZW","ZZ"];var _d=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class wd{constructor(e,t,n,i){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n,this.loadingIndicator=i}initialize(e){return _d(this,void 0,void 0,function*(){const{stripeocs:t}=e||{};if(!t)throw new fi('Unable to proceed because "options" argument is not provided.');const{gatewayId:n,container:i}=t;if(!i||!n)throw new ri(ei.PaymentNotInitialized);const r=this._getMethodId(n),o=yield this.paymentIntegrationService.loadPaymentMethod(n,{params:{method:r}}),a=o.getPaymentMethodOrThrow(r,n),{loadingContainerId:s,buttonHeight:d,onComplete:c}=t;if(this._loadingIndicatorContainer=s,this._onComplete=c,!dd(a))throw new ti(Xn.MissingPaymentMethod);const{initializationData:l}=a,{captureMethod:u}=l,h=this.stripeIntegrationService.getStripeJsVersion(l);this._captureMethod=u,this._stripeClient=yield this.scriptLoader.getStripeClient(l,o.getCartLocale(),h),yield this._mountExpressCheckoutElement(i,this._stripeClient,d),this._initializeEvents(r)})}signIn(){return Promise.resolve()}signOut(){return Promise.resolve()}executePaymentMethodCheckout(){return Promise.resolve()}deinitialize(){return Promise.resolve()}_mountExpressCheckoutElement(e,t,n=40){return _d(this,void 0,void 0,function*(){const i=this._shouldRequireShippingAddress(),r=Object.assign(Object.assign(Object.assign({shippingAddressRequired:i},i?{allowedShippingCountries:yield this._getAvailableCountries()}:{}),i?{shippingRates:[{id:"_",amount:0,displayName:"Pending rates"}]}:{}),{billingAddressRequired:!0,emailRequired:!0,phoneNumberRequired:!0,paymentMethods:{link:Ta.AUTO,applePay:Ta.NEVER,googlePay:Ta.NEVER,amazonPay:Ta.NEVER,paypal:Ta.NEVER,klarna:Ta.NEVER},buttonHeight:n}),{cartAmount:o}=this.paymentIntegrationService.getState().getCartOrThrow(),a=Object.assign({mode:"payment",amount:this._toCents(o),currency:this._getCurrency()},this._captureMethod?{captureMethod:this._captureMethod}:{});return this._stripeElements=t.elements(a),this._linkV2Element=this._stripeElements.create(Da.EXPRESS_CHECKOUT,r),this._linkV2Element.mount(`#${e}`),this._linkV2Element})}_initializeEvents(e){this._linkV2Element&&(this._shouldRequireShippingAddress()&&(this._linkV2Element.on(za.SHIPPING_ADDRESS_CHANGE,e=>_d(this,void 0,void 0,function*(){return this._onShippingAddressChange(e)})),this._linkV2Element.on(za.SHIPPING_RATE_CHANGE,e=>_d(this,void 0,void 0,function*(){return this._onShippingRateChange(e)}))),this._linkV2Element.on(za.CONFIRM,t=>_d(this,void 0,void 0,function*(){return this._onConfirm(t,e)})),this._linkV2Element.on(za.CANCEL,this._onCancel))}_onShippingAddressChange(e){return _d(this,void 0,void 0,function*(){if(!("address"in e))return;const t=e.address,n={firstName:"",lastName:"",phone:"",company:"",address1:"",address2:"",city:(null==t?void 0:t.city)||"",countryCode:(null==t?void 0:t.country)||"",postalCode:(null==t?void 0:t.postal_code)||"",stateOrProvince:(null==t?void 0:t.state)||"",stateOrProvinceCode:(null==t?void 0:t.state)||"",customFields:[]};yield this.paymentIntegrationService.updateShippingAddress(n);const i=yield this._getAvailableShippingOptions();yield this._updateDisplayedPrice(),(null==i?void 0:i.length)?e.resolve({shippingRates:i}):e.reject()})}_onCancel(){throw new Wi}_onShippingRateChange(e){return _d(this,void 0,void 0,function*(){if("shippingRate"in e){const{shippingRate:t}=e;yield this._handleShippingOptionChange(null==t?void 0:t.id),yield this._updateDisplayedPrice(),e.resolve({})}})}_onConfirm(e,t){return _d(this,void 0,void 0,function*(){if("billingDetails"in e&&"shippingAddress"in e&&this._stripeClient&&this._stripeElements){yield this._updateShippingAndBillingAddress(e),yield this.paymentIntegrationService.submitOrder();const n=this._getPaymentPayload(t);try{yield this.paymentIntegrationService.submitPayment(n)}catch(e){yield this._processAdditionalAction(e,t)}}return Promise.resolve()})}_updateShippingAndBillingAddress(e){var t,n,i,r,o,a,s,d;return _d(this,void 0,void 0,function*(){const c=this._shouldRequireShippingAddress(),l=(null===(n=null===(t=e.shippingAddress)||void 0===t?void 0:t.name)||void 0===n?void 0:n.split(" ")[0])||(null===(r=null===(i=e.billingDetails)||void 0===i?void 0:i.name)||void 0===r?void 0:r.split(" ")[0])||"",u=(null===(a=null===(o=e.shippingAddress)||void 0===o?void 0:o.name)||void 0===a?void 0:a.split(" ")[1])||(null===(d=null===(s=e.billingDetails)||void 0===s?void 0:s.name)||void 0===d?void 0:d.split(" ")[1])||"";if(c){const t=this._mapShippingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateShippingAddress(t)}const h=this._mapBillingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateBillingAddress(h)})}_mapShippingAddress(e,t,n,i){var r,o,a,s,d,c,l;return{firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==e?void 0:e.address)||void 0===r?void 0:r.line1)||"",address2:(null===(o=null==e?void 0:e.address)||void 0===o?void 0:o.line2)||"",city:(null===(a=null==e?void 0:e.address)||void 0===a?void 0:a.city)||"",countryCode:(null===(s=null==e?void 0:e.address)||void 0===s?void 0:s.country)||"",postalCode:(null===(d=null==e?void 0:e.address)||void 0===d?void 0:d.postal_code)||"",stateOrProvince:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",stateOrProvinceCode:(null===(l=null==e?void 0:e.address)||void 0===l?void 0:l.state)||"",customFields:[]}}_mapBillingAddress(e,t,n,i){var r,o,a,s,d,c;return{email:(null==t?void 0:t.email)||"",firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==t?void 0:t.address)||void 0===r?void 0:r.line1)||"",address2:"",city:(null===(o=null==t?void 0:t.address)||void 0===o?void 0:o.city)||"",countryCode:(null===(a=null==t?void 0:t.address)||void 0===a?void 0:a.country)||"",postalCode:(null===(s=null==t?void 0:t.address)||void 0===s?void 0:s.postal_code)||"",stateOrProvince:(null===(d=null==t?void 0:t.address)||void 0===d?void 0:d.state)||"",stateOrProvinceCode:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",customFields:[]}}_processAdditionalAction(e,t){return _d(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeClient||!this._stripeElements)throw new ri(ei.PaymentNotInitialized);const{data:n}=e.body.additional_action_required,{token:i}=n,{paymentIntent:r}=yield this._confirmStripePaymentOrThrow(n,t),o=this._getPaymentPayload(t,(null==r?void 0:r.id)||i);try{this._toggleLoadingIndicator(!0),yield this.paymentIntegrationService.submitPayment(o),yield this._completeCheckoutFlow()}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}finally{this._toggleLoadingIndicator(!1)}})}_confirmStripePaymentOrThrow(e,t){var n,i,r;return _d(this,void 0,void 0,function*(){const{token:o,redirect_url:a}=e,s=this.stripeIntegrationService.mapStripePaymentData(this._stripeElements,a);let d;try{const e=(yield this.stripeIntegrationService.isPaymentCompleted(t,this._stripeClient))?yield null===(r=this._stripeClient)||void 0===r?void 0:r.retrievePaymentIntent(o||""):yield null===(n=this._stripeClient)||void 0===n?void 0:n.confirmPayment({elements:s.elements,clientSecret:o,redirect:Ta.IF_REQUIRED,confirmParams:{return_url:null===(i=s.confirmParams)||void 0===i?void 0:i.return_url}});if(d=null==e?void 0:e.error,d||!(null==e?void 0:e.paymentIntent))throw new Qr;return e}catch(e){return this.stripeIntegrationService.throwStripeError(d)}})}_completeCheckoutFlow(){return _d(this,void 0,void 0,function*(){return"function"==typeof this._onComplete?this._onComplete():(window.location.replace("/order-confirmation"),Promise.resolve())})}_getPaymentPayload(e,t){var n;const i=(null===(n=this.paymentIntegrationService.getState().getCart())||void 0===n?void 0:n.id)||"";return{methodId:e,paymentData:{formattedPayload:Object.assign(Object.assign({cart_id:i},t?{credit_card_token:{token:t}}:{}),{confirm:!1,method:Aa.Link})}}}_shouldRequireShippingAddress(){const{getCartOrThrow:e}=this.paymentIntegrationService.getState(),{lineItems:t}=e();return!!t.physicalItems.length}_updateDisplayedPrice(){return _d(this,void 0,void 0,function*(){this._stripeElements&&this._stripeElements.update({currency:this._getCurrency(),mode:"payment",amount:yield this._getTotalPrice()})})}_getCurrency(){if(!this._currencyCode){const{code:e}=this.paymentIntegrationService.getState().getCartOrThrow().currency;this._currencyCode=e.toLowerCase()}return this._currencyCode}_getTotalPrice(){return _d(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const{getCheckoutOrThrow:e,getCartOrThrow:t}=this.paymentIntegrationService.getState(),{decimalPlaces:n}=t().currency,i=ge(e().outstandingBalance,n).toFixed(n);return this._toCents(+i)})}_getAvailableCountries(){var e;return _d(this,void 0,void 0,function*(){const t=yield this.paymentIntegrationService.loadShippingCountries();return((null===(e=t.getShippingCountries())||void 0===e?void 0:e.map(e=>e.code))||[]).filter(e=>Sd.includes(e))})}_getAvailableShippingOptions(){var e,t,n;return _d(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getConsignments();if(!(null==i?void 0:i[0]))return;const r=i[0],o=(r.availableShippingOptions||[]).map(this._getStripeShippingOption.bind(this)),a=null===(e=r.availableShippingOptions)||void 0===e?void 0:e.find(e=>e.isRecommended),s=null===(t=r.selectedShippingOption)||void 0===t?void 0:t.id,d=null==a?void 0:a.id;return s?o.sort(e=>e.id===s?-1:0):d?(o.sort(e=>e.id===d?-1:0),yield this._handleShippingOptionChange(d)):yield this._handleShippingOptionChange(null===(n=o[0])||void 0===n?void 0:n.id),o.slice(0,9)})}_getStripeShippingOption({id:e,cost:t,description:n}){return{id:e,displayName:n,amount:this._toCents(t)}}_handleShippingOptionChange(e){return _d(this,void 0,void 0,function*(){if(e&&"shipping_option_unselected"!==e)return this.paymentIntegrationService.selectShippingOption(e)})}_getAmountTransformer(){if(this._amountTransformer)return this._amountTransformer;const{getCart:e}=this.paymentIntegrationService.getState(),{currency:t}=e()||{};return t?new fd(t.decimalPlaces):void 0}_toCents(e){const t=Math.round(100*e),n=this._getAmountTransformer();return n?n.toInteger(e):t}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this.loadingIndicator.show(this._loadingIndicatorContainer):this.loadingIndicator.hide()}_getMethodId(e){const{initializationData:{checkoutSessionEnabled:t}={}}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e);return t?Aa.CHECKOUT_SESSION:Aa.OCS}}const Id=vi(e=>{const t=new Ra(a()),n=new vd({containerStyles:yd});return new wd(e,t,new pd(e,t),n)},[{id:"stripeocs"}]);class Cd extends Qn{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}class bd{constructor(e){this._paymentIntegrationService=e}execute(e,t){return n=this,i=void 0,o=function*(){yield this._paymentIntegrationService.submitOrder(le(e,"payment"),t)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const Pd=vi(e=>new bd(e),[{id:"nopaymentdatarequired"}]);var Od,Ed,Ad,Td,kd,Dd,Md;class zd{constructor(e,t,n=window){this._scriptLoader=e,this._stylesheetLoader=t,this._window=n}load(e){var t,n,i,r,o,a;return i=this,r=void 0,a=function*(){if(yield Promise.all([this._stylesheetLoader.loadStylesheet(`https://checkoutshopper-${null!==(t=e.environment)&&void 0!==t?t:""}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.css`,{prepend:!1,attributes:{integrity:"sha384-8ofgICZZ/k5cC5N7xegqFZOA73H9RQ7H13439JfAZW8Gj3qjuKL2isaTD3GMIhDE",crossorigin:"anonymous"}}),this._scriptLoader.loadScript(`https://checkoutshopper-${null!==(n=e.environment)&&void 0!==n?n:""}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.js`,{async:!0,attributes:{integrity:"sha384-wG2z9zSQo61EIvyXmiFCo+zB3y0ZB4hsrXVcANmpP8HLthjoQJQPBh7tZKJSV8jA",crossorigin:"anonymous"}})]),!this._window.AdyenCheckout)throw new mi;return new this._window.AdyenCheckout(e)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}}function Nd(e){return"object"==typeof e&&"string"==typeof e.data.paymentMethod.encryptedSecurityCode||"string"==typeof e.data.paymentMethod.encryptedExpiryMonth}function xd(e){return Boolean(e.instrumentId)}!function(e){e.ThreeDS2Fingerprint="threeDS2Fingerprint",e.ThreeDS2="threeDS2",e.Redirect="redirect",e.QRCode="qrCode",e.Voucher="voucher",e.Sdk="sdk"}(Od||(Od={})),function(e){e.ThreeDS2Fingerprint="threeDS2Fingerprint",e.ThreeDS2Challenge="threeDS2Challenge",e.Redirect="redirect",e.QRCode="qrCode",e.Voucher="voucher"}(Ed||(Ed={})),function(e){e.SecuredFields="securedfields"}(Ad||(Ad={})),function(e){e.ACH="ach",e.AliPay="alipay",e.Bancontact="bcmc",e.CreditCard="scheme",e.Klarna="klarna",e.KlarnaPayNow="klarna_paynow",e.KlarnaAccount="klarna_account",e.IDEAL="ideal",e.GiroPay="giropay",e.GooglePay="paywithgoogle",e.SEPA="sepadirectdebit",e.Sofort="directEbanking",e.Vipps="vipps",e.WeChatPayQR="wechatpayQR"}(Td||(Td={})),function(e){e.POST="POST"}(kd||(kd={})),function(e){e.ChallengeShopper="ChallengeShopper",e.Error="Error",e.IdentifyShopper="IdentifyShopper"}(Dd||(Dd={})),function(e){e.CardNumber="encryptedCardNumber",e.SecurityCode="encryptedSecurityCode",e.ExpiryDate="encryptedExpiryDate"}(Md||(Md={}));var Rd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Fd{constructor(e,t){this._paymentIntegrationService=e,this._scriptLoader=t}initialize(e){return Rd(this,void 0,void 0,function*(){const{adyenv2:t}=e;if(!t)throw new fi('Unable to initialize payment because "options.adyenv2" argument is not provided.');this._paymentInitializeOptions=t;const n=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{originKey:i,clientKey:r,environment:o,paymentMethodsResponse:a}=n.initializationData||{},s={key:"",value:""};return i?(s.key="originKey",s.value=i):(s.key="clientKey",s.value=r||""),this._adyenClient=yield this._scriptLoader.load({environment:o,locale:this._paymentIntegrationService.getState().getLocale(),[s.key]:s.value,paymentMethodsResponse:a,translations:{es:{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-AR":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-ES":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-MX":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CL":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CO":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-PE":{"creditCard.expiryDateField.title":"Fecha de caducidad"}}}),this._paymentComponent=yield this._mountPaymentComponent(n),n.method!==Td.CreditCard&&n.method!==Td.Bancontact||(this._cardVerificationComponent=yield this._mountCardVerificationComponent()),Promise.resolve()})}execute(e,t){return Rd(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const{threeDS2ContainerId:i,additionalActionOptions:r}=this._getPaymentInitializeOptions(),{onBeforeLoad:o,containerId:a,onLoad:s,onComplete:d}=r,c=JSON.parse(e.action),l=this._getAdyenClient().createFromAction(c,{onAdditionalDetails:e=>{const n={methodId:c.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};d&&d(),t(n)},size:this._getThreeDS2ChallengeWidgetSize(),onError:e=>n(e)});o&&o(c.type===Ed.ThreeDS2Challenge||c.type===Ed.QRCode),l.mount(`#${a||i}`),s&&s(()=>{n(new Wi),l.unmount()})})}_mapAdyenPlaceholderData(e,t){if(!e)return{};const{firstName:n,lastName:i,address1:r,address2:o,postalCode:a,city:s,stateOrProvinceCode:d,countryCode:c}=e;return{holderName:t?`${n} ${i}`:"",billingAddress:{street:r,houseNumberOrName:o,postalCode:a,city:s,stateOrProvince:d,country:c}}}_mountCardVerificationComponent(){const e=this._getPaymentInitializeOptions(),t=this._getAdyenClient();let n;return new Promise((i,r)=>{var o,a,s;if(e.cardVerificationContainerId){n=t.create(Ad.SecuredFields,Object.assign(Object.assign({},e.options),{styles:Object.assign(Object.assign({},null===(o=e.options)||void 0===o?void 0:o.styles),{placeholder:Object.assign({color:"transparent",caretColor:"#000"},null===(s=null===(a=e.options)||void 0===a?void 0:a.styles)||void 0===s?void 0:s.placeholder)}),onChange:e=>this._updateComponentState(e),onError:t=>e.validateCardFields(t),onFieldValid:t=>e.validateCardFields(t)}));try{n.mount(`#${e.cardVerificationContainerId}`)}catch(e){r(new ri(ei.PaymentNotInitialized))}}i(n)})}_mountPaymentComponent(e){let t;const n=this._getPaymentInitializeOptions(),i=this._getAdyenClient();return new Promise((r,o)=>{switch(e.method){case Td.CreditCard:case Td.ACH:case Td.Bancontact:{const r=this._paymentIntegrationService.getState().getBillingAddress(),{prefillCardHolderName:a}=e.initializationData;t=i.create(e.method,Object.assign(Object.assign({},n.options),{onChange:e=>this._updateComponentState(e),data:this._mapAdyenPlaceholderData(r,a)}));try{t.mount(`#${n.containerId}`)}catch(e){o(new ri(ei.PaymentNotInitialized))}break}case Td.IDEAL:case Td.SEPA:if(n.hasVaultedInstruments)this._updateComponentState({data:{paymentMethod:{type:e.method}}});else{t=i.create(e.method,Object.assign(Object.assign({},n.options),{onChange:e=>this._updateComponentState(e)}));try{t.mount(`#${n.containerId}`)}catch(e){o(new ri(ei.PaymentNotInitialized))}}break;case Td.AliPay:case Td.GiroPay:case Td.Sofort:case Td.Klarna:case Td.KlarnaPayNow:case Td.KlarnaAccount:case Td.Vipps:case Td.WeChatPayQR:this._updateComponentState({data:{paymentMethod:{type:e.method}}})}r(t)})}_processAdditionalAction(e,t,n){return Rd(this,void 0,void 0,function*(){if(!pa(e)||!ve(e.body.errors,{code:"additional_action_required"}))throw e;const i=yield this._handleAction(e.body.provider_data);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:Object.assign(Object.assign({},i.paymentData),{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n})}))}catch(e){return this._processAdditionalAction(e,t,n)}})}_updateComponentState(e){this._componentState=e}_validateCardData(){var e,t;const n=this._getPaymentInitializeOptions().hasVaultedInstruments?this._cardVerificationComponent:this._paymentComponent;if((null===(e=null==n?void 0:n.componentRef)||void 0===e?void 0:e.showValidation)&&n.state&&(n.componentRef.showValidation(),0===Object.keys(n.state).length||!n.state.isValid&&!n.state.issuer||"sepadirectdebit"===(null===(t=n.props)||void 0===t?void 0:t.type)&&n.state.data&&Object.values(n.state.data).some(e=>0===e.toString().trim().length)))throw new lo(this._mapCardErrors(n.state.errors))}_mapCardErrors(e={}){const t={};return Object.keys(e).forEach(n=>{t[n]=[{message:e[n],type:n}]}),t}}const Ld=vi(e=>new Fd(e,new zd(a(),s())),[{gateway:"adyenv2"}]);class Bd{constructor(e,t,n=window){this._scriptLoader=e,this._stylesheetLoader=t,this._window=n}load(e){var t,n,i,r,o,a;return i=this,r=void 0,a=function*(){if(yield Promise.all([this._stylesheetLoader.loadStylesheet(`https://checkoutshopper-${null!==(t=e.environment)&&void 0!==t?t:""}.adyen.com/checkoutshopper/sdk/5.71.1/adyen.css`,{prepend:!1,attributes:{integrity:"sha384-5MvB4RnzvviA3VBT4KYABZ4HXNZG5LRqREEgd41xt/pf/QvKmsj2O9GuNuywRXx9",crossorigin:"anonymous"}}),this._scriptLoader.loadScript(`https://checkoutshopper-${null!==(n=e.environment)&&void 0!==n?n:""}.adyen.com/checkoutshopper/sdk/5.71.1/adyen.js`,{async:!0,attributes:{integrity:"sha384-yvY2yFNR4WqIjPqP9MzjI+gJimmaJnAvj4rLHKvgJbgFD5fMuf8zIJrFJOW8Lhhf",crossorigin:"anonymous"}})]),!this._window.AdyenCheckout)throw new mi;return yield this._window.AdyenCheckout(e)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}}function jd(e){return!("object"!=typeof e||null===e||void 0!==e.shouldSaveInstrument&&"boolean"!=typeof e.shouldSaveInstrument||void 0!==e.shouldSetAsDefaultInstrument&&"boolean"!=typeof e.shouldSetAsDefaultInstrument)}var Ud=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class qd{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){return Ud(this,void 0,void 0,function*(){const{adyenv3:t}=e;if(!t)throw new fi('Unable to initialize payment because "options.adyenv3" argument is not provided.');this.paymentInitializeOptions=t;const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{environment:i,clientKey:r,paymentMethodsResponse:o,installmentOptions:a}=n.initializationData||{};return this.adyenClient=yield this.scriptLoader.load({paymentMethodsConfiguration:Object.assign({klarna:{useKlarnaWidget:!0},klarna_account:{useKlarnaWidget:!0},klarna_paynow:{useKlarnaWidget:!0}},a?{card:{installmentOptions:Object.assign({showInstallmentAmounts:!0},a)}}:{}),environment:i,locale:this._getLocale(),clientKey:r,paymentMethodsResponse:o,showPayButton:!1,translations:{es:{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-AR":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-ES":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-MX":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CL":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CO":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-PE":{"creditCard.expiryDateField.title":"Fecha de caducidad"}}}),this.paymentComponent=yield this._mountPaymentComponent(n),n.method!==Td.CreditCard&&n.method!==Td.Bancontact||(this.cardVerificationComponent=yield this._mountCardVerificationComponent()),Promise.resolve()})}execute(e,t){var n;return Ud(this,void 0,void 0,function*(){const{payment:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const{additionalActionOptions:i}=this._getPaymentInitializeOptions(),{onBeforeLoad:r,containerId:o,onLoad:a,onComplete:s,widgetSize:d,onActionHandled:c}=i,l=JSON.parse(e.action),u=this._getAdyenClient().createFromAction(l,{onActionHandled:e=>{c&&"function"==typeof c&&"3DS2Fingerprint"!==e.componentType&&c()},onAdditionalDetails:e=>{const n={methodId:l.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};s&&"function"==typeof s&&s(),t(n)},challengeWindowSize:d||"05",onError:e=>n(e)});r&&"function"==typeof r&&r(l.type===Od.ThreeDS2||l.type===Od.QRCode||l.type===Od.Sdk),this._mountElement(u,o).then(()=>{a&&"function"==typeof a&&a(()=>{n(new Wi),u.unmount()})}).catch(n)})}_mapAdyenPlaceholderData(e,t){if(!e)return{};const{firstName:n,lastName:i,address1:r,address2:o,postalCode:a,city:s,stateOrProvinceCode:d,countryCode:c}=e;return{holderName:t?`${n} ${i}`:"",firstName:t?n:"",lastName:t?i:"",billingAddress:{street:r,houseNumberOrName:o,postalCode:a,city:s,stateOrProvince:d,country:c}}}_mountCardVerificationComponent(){var e,t,n;return Ud(this,void 0,void 0,function*(){const i=this._getPaymentInitializeOptions(),r=this._getAdyenClient();if(!i.cardVerificationContainerId)return;const o=r.create(Ad.SecuredFields,Object.assign(Object.assign({},i.options),{styles:Object.assign(Object.assign({},null===(e=i.options)||void 0===e?void 0:e.styles),{placeholder:Object.assign({color:"transparent",caretColor:"#000"},null===(n=null===(t=i.options)||void 0===t?void 0:t.styles)||void 0===n?void 0:n.placeholder)}),onChange:e=>this._updateComponentState(e),onError:e=>i.validateCardFields(e),onFieldValid:e=>i.validateCardFields(e)}));try{yield this._mountElement(o,i.cardVerificationContainerId)}catch(e){throw new ri(ei.PaymentNotInitialized)}return o})}_mountPaymentComponent(e){return Ud(this,void 0,void 0,function*(){const t=this._getPaymentInitializeOptions(),n=this._getAdyenClient(),i=this.paymentIntegrationService.getState().getBillingAddress(),{prefillCardHolderName:r}=e.initializationData,o=n.create(e.method,Object.assign(Object.assign(Object.assign(Object.assign({},this._isOneyPaymentMethod(e.method)?{visibility:{personalDetails:"hidden",billingAddress:"hidden",deliveryAddress:"hidden"}}:{}),t.options),{showBrandsUnderCardNumber:!1,billingAddressRequired:!1,showEmailAddress:!1,onChange:e=>this._updateComponentState(e),onSubmit:e=>this._updateComponentState(e)}),i?{data:this._mapAdyenPlaceholderData(i,r)}:{}));try{yield this._mountElement(o,t.containerId)}catch(e){throw new ri(ei.PaymentNotInitialized)}return o})}_isOneyPaymentMethod(e){return e.startsWith("facilypay")}_processAdditionalAction(e,t,n,i,r){return Ud(this,void 0,void 0,function*(){if(!pa(e)||!ve(e.body.errors,{code:"additional_action_required"}))throw e;const o=yield this._handleAction(e.body.provider_data);try{const e=Object.assign(Object.assign({},o.paymentData),{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n}),a=n&&!t?{instrumentId:i,formattedPayload:{bigpay_token:Object.assign(Object.assign({},r),{token:i})}}:{};yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},o),{paymentData:Object.assign(Object.assign({},e),a)}))}catch(e){return this._processAdditionalAction(e,t,n,i,r)}})}_validateCardData(){var e;const t=this._getPaymentInitializeOptions().hasVaultedInstruments?this.cardVerificationComponent:this.paymentComponent;if((null===(e=null==t?void 0:t.componentRef)||void 0===e?void 0:e.showValidation)&&t.state&&(t.componentRef.showValidation(),0===Object.keys(t.state).length||!t.state.isValid))throw new lo(this._mapCardErrors(t.state.errors))}_mapCardErrors(e={}){const t={};return Object.keys(e).forEach(n=>{t[n]=[{message:e[n],type:n}]}),t}_mountElement(e,t){return Ud(this,void 0,void 0,function*(){yield this._waitForMountContainer(t);try{e.mount(`#${t}`)}catch(e){throw new ri(ei.PaymentNotInitialized)}})}_waitForMountContainer(e){return Ud(this,void 0,void 0,function*(){const t=Math.ceil(qd.mountContainerMaxWaitMs/qd.mountContainerPollIntervalMs),n=qd.mountContainerPollIntervalMs;let i=0;const r=()=>Ud(this,void 0,void 0,function*(){if(i===t)throw new ri(ei.PaymentNotInitialized);document.getElementById(e)||(yield new Promise(e=>{setTimeout(e,n)}),i+=1,yield r())});yield r()})}}qd.mountContainerMaxWaitMs=5e3,qd.mountContainerPollIntervalMs=50;const Vd=vi(e=>new qd(e,new Bd(a(),s())),[{gateway:"adyenv3"}]);var Gd,Hd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Wd{constructor(e,t){this.paymentIntegrationService=e,this.affirmScriptLoader=t}initialize(e){return Hd(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadPaymentMethod(e.methodId);const t=this.paymentIntegrationService.getState(),{clientToken:n,config:{testMode:i}}=t.getPaymentMethodOrThrow(e.methodId);if(!n)throw new ti(Xn.MissingPaymentMethod);this.affirm=yield this.affirmScriptLoader.load(n,i)})}execute(e,t){var n;return Hd(this,void 0,void 0,function*(){const i=null===(n=e.payment)||void 0===n?void 0:n.methodId,{useStoreCredit:r}=e;if(!this.affirm)throw new ri(ei.PaymentNotInitialized);if(!i)throw new co(["payment.methodId"]);yield this.paymentIntegrationService.submitOrder({useStoreCredit:r},t);const o={methodId:i,paymentData:{nonce:(yield this.initializeAffirmCheckout()).checkout_token}};yield this.paymentIntegrationService.submitPayment(o)})}deinitialize(){return this.affirm&&(this.affirm=void 0),Promise.resolve()}finalize(){return Promise.reject(new Cd)}initializeAffirmCheckout(){var e;return null===(e=this.affirm)||void 0===e||e.checkout(this.getCheckoutInformation()),new Promise((e,t)=>{var n,i;null===(n=this.affirm)||void 0===n||n.checkout.open({onFail:e=>{"canceled"===e.reason?t(new Wi):t(new Xr)},onSuccess:t=>{e(t)}}),null===(i=this.affirm)||void 0===i||i.ui.error.on("close",()=>{t(new Wi)})})}getCheckoutInformation(){const e=this.paymentIntegrationService.getState(),t=e.getStoreConfig(),n=e.getConsignments(),i=e.getOrder(),r=e.getCart();if(!t)throw new ti(Xn.MissingCheckoutConfig);if(!i)throw new ti(Xn.MissingCheckout);const o=new fd(i.currency.decimalPlaces),a=this.getBillingAddress(),s=this.getShippingAddress(),d=jo(r,t)&&s?s:a;return{merchant:{user_confirmation_url:t.links.checkoutLink,user_cancel_url:t.links.checkoutLink,user_confirmation_url_action:"POST"},shipping:d,billing:a,items:this.getItems(o,i),metadata:{shipping_type:this.getShippingType(n),mode:"modal",platform_type:"BigCommerce",platform_version:"",platform_affirm:""},discounts:this.getDiscounts(o,i),order_id:i.orderId?i.orderId.toString():"",shipping_amount:o.toInteger(i.shippingCostTotal),tax_amount:o.toInteger(i.taxTotal),total:o.toInteger(i.orderAmount)}}getShippingType(e){if(!e)return"";const t=e[0];return(null==t?void 0:t.selectedShippingOption)?t.selectedShippingOption.type:""}getBillingAddress(){const e=this.paymentIntegrationService.getState().getBillingAddress();if(!e)throw new ti(Xn.MissingBillingAddress);return{name:{first:e.firstName,last:e.lastName,full:`${e.firstName} ${e.lastName}`},address:{line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,zipcode:e.postalCode,country:e.countryCode},phone_number:e.phone,email:e.email}}getShippingAddress(){const e=this.paymentIntegrationService.getState().getShippingAddress();if(e)return{name:{first:e.firstName,last:e.lastName,full:`${e.firstName} ${e.lastName}`},address:{line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,zipcode:e.postalCode,country:e.countryCode},phone_number:e.phone}}getItems(e,t){const n=[];return t.lineItems.physicalItems.forEach(t=>{n.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.salePrice),qty:t.quantity,item_image_url:t.imageUrl,item_url:t.url,categories:this.getCategories(t.categories)})}),t.lineItems.digitalItems.forEach(t=>{n.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.salePrice),qty:t.quantity,item_image_url:t.imageUrl,item_url:t.url,categories:this.getCategories(t.categories)})}),t.lineItems.giftCertificates.forEach(t=>{n.push({display_name:t.name,sku:"",unit_price:e.toInteger(t.amount),qty:1,item_image_url:"",item_url:""})}),t.lineItems.customItems&&t.lineItems.customItems.forEach(t=>{n.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.listPrice),qty:t.quantity,item_image_url:"",item_url:""})}),n}getDiscounts(e,t){const n={};return t.coupons.forEach(t=>{t.discountedAmount>0&&(n[t.code]={discount_amount:e.toInteger(t.discountedAmount),discount_display_name:t.displayName})}),t.discountAmount>0&&(n.DISCOUNTED_AMOUNT={discount_amount:e.toInteger(t.discountAmount),discount_display_name:"discount"}),n}getCategories(e){return e?e.map(e=>e.map(e=>e.name)):[[]]}}!function(e){e.PROD="//cdn1.affirm.com/js/v2/affirm.js",e.SANDBOX="//cdn1-sandbox.affirm.com/js/v2/affirm.js"}(Gd||(Gd={}));class $d{constructor(e=window){this.affirmWindow=e}load(e="",t){const n=t?Gd.SANDBOX:Gd.PROD;if(function(e,t,n,i,r,o,a){const s=e[n]||{},d=document.createElement(o),c=document.getElementsByTagName(o)[0],l=function(e,t,n){return function(){e[t]._.push([n,arguments])}};s[i]=l(s,i,"set");const u=s[i];s[r]={},s[r]._=[],u._=[],s._=[],s[r][a]=l(s,r,a),s.jsReady=function(){s._.push([a,arguments])};let h=0;for(const e="set add save post open empty reset on off trigger ready setProduct".split(" ");hnew Wd(e,new $d),[{id:"affirm"}]);class Kd extends Qn{constructor(e){super(e||"The current order could not be finalized successfully"),this.name="OrderFinalizationNotCompletedError",this.type="order_finalization_not_completed"}}var Jd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Zd{constructor(e,t){this._paymentIntegrationService=e,this._afterpayScriptLoader=t}initialize(e){var t;return Jd(this,void 0,void 0,function*(){const n=this._paymentIntegrationService.getState(),i=n.getPaymentMethod(e.methodId,e.gatewayId),r=(null===(t=n.getCart())||void 0===t?void 0:t.currency.code)||"",o=this._mapCurrencyToISO2(r),a=Ci(n.getStoreConfigOrThrow().checkoutSettings.features,"PI-4789.afterpay_script_use_https",!1);if(!i)throw new ti(Xn.MissingPaymentMethod);this._afterpaySdk=yield this._afterpayScriptLoader.load(i,o,a)})}deinitialize(){return this._afterpaySdk&&(this._afterpaySdk=void 0),Promise.resolve()}execute(e,t){var n;return Jd(this,void 0,void 0,function*(){if(!e.payment)throw new co(["payment.gatewayId","payment.methodId"]);const{gatewayId:i,methodId:r}=e.payment;if(!i||!r)throw new co(["payment.gatewayId","payment.methodId"]);const{useStoreCredit:o}=e;void 0!==o&&(yield this._paymentIntegrationService.applyStoreCredit(o)),yield this._loadPaymentMethod(i,r,t);const a=this._paymentIntegrationService.getState();yield this._paymentIntegrationService.validateCheckout(a.getCheckout(),t);const s=(null===(n=a.getCart())||void 0===n?void 0:n.currency.code)||"",d=this._mapCurrencyToISO2(s);return this._redirectToAfterpay(d,a.getPaymentMethod(r,i)),new Promise(()=>{})})}finalize(e){var t,n,i;return Jd(this,void 0,void 0,function*(){const r=this._paymentIntegrationService.getState(),o=r.getPaymentId(),a=r.getContextConfig();if(!o)throw new ti(Xn.MissingCheckout);if(!(null==a?void 0:a.payment.token))throw new ti(Xn.MissingCheckoutConfig);const s={methodId:o.providerId,paymentData:{nonce:a.payment.token}};yield this._paymentIntegrationService.submitOrder({},e);try{yield this._paymentIntegrationService.submitPayment(s)}catch(e){if(yield this._paymentIntegrationService.forgetCheckout(o.providerId),yield this._paymentIntegrationService.loadPaymentMethods(),pa(e))throw new Kd(null===(i=null===(n=null===(t=e.body)||void 0===t?void 0:t.errors)||void 0===n?void 0:n[0])||void 0===i?void 0:i.message)}})}_redirectToAfterpay(e,t){if(!this._afterpaySdk||!(null==t?void 0:t.clientToken))throw new ri(ei.PaymentNotInitialized);this._afterpaySdk.initialize({countryCode:e}),this._afterpaySdk.redirect({token:t.clientToken})}_mapCurrencyToISO2(e){return{AUD:"AU",NZD:"NZ",CAD:"CA",USD:"US"}[e]||"AU"}_loadPaymentMethod(e,t,n){var i;return Jd(this,void 0,void 0,function*(){try{return yield this._paymentIntegrationService.loadPaymentMethod(e,Object.assign(Object.assign({},n),{params:Object.assign(Object.assign({},null==n?void 0:n.params),{method:t})}))}catch(e){if(e instanceof nr&&422===(null===(i=e.body)||void 0===i?void 0:i.status))throw new fi("Afterpay can't process your payment for this order, please try another payment method");throw e}})}}var Qd,Xd;!function(e){e.PROD="//portal.afterpay.com/afterpay-async.js",e.SANDBOX="//portal.sandbox.afterpay.com/afterpay.js",e.HTTPS_PROD="https://portal.afterpay.com/afterpay-async.js",e.HTTPS_SANDBOX="https://portal.sandbox.afterpay.com/afterpay.js"}(Qd||(Qd={})),function(e){e.PROD="//portal.afterpay.com/afterpay-async.js",e.SANDBOX="//portal.sandbox.afterpay.com/afterpay.js",e.HTTPS_PROD="https://portal.afterpay.com/afterpay-async.js",e.HTTPS_SANDBOX="https://portal.sandbox.afterpay.com/afterpay.js"}(Xd||(Xd={}));class ec{constructor(e){this._scriptLoader=e}load(e,t,n=!1){return i=this,r=void 0,a=function*(){const i=e.config.testMode||!1,r=this._getScriptURI(t,i,n);return this._scriptLoader.loadScript(r).then(()=>{if(!function(e){return"AfterPay"in e}(window))throw new mi;return window.AfterPay})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a}_getScriptURI(e,t,n=!1){return"US"===e?n?t?Xd.HTTPS_SANDBOX:Xd.HTTPS_PROD:t?Xd.SANDBOX:Xd.PROD:n?t?Qd.HTTPS_SANDBOX:Qd.HTTPS_PROD:t?Qd.SANDBOX:Qd.PROD}}const tc=vi(e=>new Zd(e,new ec(o())),[{gateway:"afterpay"},{id:"afterpay"}]);var nc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ic{constructor(e,t){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t}initialize(e){return nc(this,void 0,void 0,function*(){const{methodId:t,amazonpay:n}=e;if(!t)throw new fi('Unable to proceed because "methodId" argument is not provided.');const i=this.paymentIntegrationService.getState(),{features:r}=i.getStoreConfigOrThrow().checkoutSettings,o=i.getPaymentMethodOrThrow(t),a=o.initializationData||{},{paymentToken:s="",region:d="",isButtonMicroTextDisabled:c}=a;if(yield this.amazonPayV2PaymentProcessor.initialize(o),this._isReadyToPay(s))(null==n?void 0:n.editButtonId)&&this._bindEditButton(n.editButtonId,s,"changePayment",this._isModalFlow(d));else{const{id:e}=this._createContainer();if(this._amazonPayButton=this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:i,containerId:e,decoupleCheckoutInitiation:this._isOneTimeTransaction(r,d.toUpperCase()),methodId:t,placement:si.Checkout,isButtonMicroTextDisabled:c}),!this._amazonPayButton)throw new fi("Unable to render the Amazon Pay button to an invalid HTML container element.")}})}execute(e,t){return nc(this,void 0,void 0,function*(){const{payment:n}=e;if(!n)throw new co(["payment"]);const{methodId:i}=n,r=this.paymentIntegrationService.getState(),{features:o}=r.getStoreConfigOrThrow().checkoutSettings,a=r.getPaymentMethodOrThrow(i).initializationData||{},{paymentToken:s="",region:d=""}=a;if(this._isReadyToPay(s)||this._isOneTimeTransaction(o,d.toUpperCase())){const n={methodId:i,paymentData:{nonce:s||"apb"}};yield this.paymentIntegrationService.submitOrder(e,t);try{return void(yield this.paymentIntegrationService.submitPayment(n))}catch(e){if(!(pa(e)&&(c=e.body,"object"==typeof c&&null!==c&&"status"in c&&"additional_action_required"in c&&"additional_action_required"===c.status&&"data"in c.additional_action_required&&"redirect_url"in c.additional_action_required.data&&"string"==typeof c.additional_action_required.data.redirect_url)))throw e;const{additional_action_required:t}=e.body,{redirect_url:n}=t.data;if(s)return new Promise(()=>window.location.assign(n));this.amazonPayV2PaymentProcessor.prepareCheckout(JSON.parse(n))}}var c;return this._getAmazonPayButton().click(),this._isModalFlow(d)?new Promise((e,t)=>{const n=()=>{window.removeEventListener("focus",n),t(new Wi("Shopper needs to login to Amazonpay to continue"))};window.addEventListener("focus",n)}):new Promise(ce)})}finalize(){return Promise.reject(new Cd)}deinitialize(){return nc(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize(),this._amazonPayButton=void 0})}_bindEditButton(e,t,n,i){const r=document.getElementById(e);if(r&&r.parentNode){if(!i){const e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener("click",()=>{this._showLoadingSpinner()})}this.amazonPayV2PaymentProcessor.bindButton(e,t,n)}}_isModalFlow(e){return"us"===e}_showLoadingSpinner(){return nc(this,void 0,void 0,function*(){yield this.paymentIntegrationService.widgetInteraction(()=>new Promise(ce))})}_createContainer(){let e=document.getElementById("AmazonPayButton");return e||(e=document.createElement("div"),e.id="AmazonPayButton",e.style.display="none",document.body.appendChild(e))}_getAmazonPayButton(){return ii(this._amazonPayButton,()=>new ri(ei.PaymentNotInitialized))}_isOneTimeTransaction(e,t){return this.amazonPayV2PaymentProcessor.isPh4Enabled(e,t)&&e["INT-6399.amazon_pay_apb"]}_isReadyToPay(e){return!!e}}const rc=vi(e=>new ic(e,gi()),[{id:"amazonpay"}]);var oc,ac=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.Shipping="Shipping",e.Subtotal="Subtotal",e.StoreCredit="Store Credit"}(oc||(oc={}));class sc{constructor(e,t,n,i,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._braintreeSdk=i,this._applePayScriptLoader=r,this._shippingLabel=oc.Shipping,this._subTotalLabel=oc.Subtotal,this._storeCreditLabel=oc.StoreCredit}initialize(e){var t,n,i,r;return ac(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new fi('Unable to submit payment because "options.methodId" argument is not provided.');const{methodId:o}=e;yield this._applePayScriptLoader.loadSdk(),this._shippingLabel=(null===(t=e.applepay)||void 0===t?void 0:t.shippingLabel)||oc.Shipping,this._subTotalLabel=(null===(n=e.applepay)||void 0===n?void 0:n.subtotalLabel)||oc.Subtotal,this._storeCreditLabel=(null===(i=e.applepay)||void 0===i?void 0:i.storeCreditLabel)||oc.StoreCredit;const a=(yield this._paymentIntegrationService.loadPaymentMethod(o)).getPaymentMethodOrThrow(o);(null===(r=a.initializationData)||void 0===r?void 0:r.gateway)===Vi.BRAINTREE&&a.clientToken&&this._braintreeSdk.initialize(a.clientToken)})}execute(e,t){return ac(this,void 0,void 0,function*(){const{payment:n}=e,i=this._paymentIntegrationService.getState();if(!n)throw new co(["payment"]);const{methodId:r}=n,o=i.getPaymentMethodOrThrow(r),a=this._getBaseRequest(i,o),s=this._sessionFactory.create(a);return yield this._paymentIntegrationService.submitOrder({useStoreCredit:e.useStoreCredit},t),s.begin(),new Promise((e,t)=>{this._handleApplePayEvents(s,o,{resolve:e,reject:t})})})}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_getBaseRequest(e,t){const n=e.getCheckoutOrThrow(),i=e.getCartOrThrow(),r=e.getStoreConfigOrThrow(),{storeProfile:{storeCountryCode:o,storeName:a}}=r,{currency:{code:s,decimalPlaces:d}}=i,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=t,{grandTotal:u,isStoreCreditApplied:h,outstandingBalance:p}=n,m=[{label:this._subTotalLabel,amount:`${n.subtotal.toFixed(d)}`}];if(n.taxes.forEach(e=>m.push({label:e.name,amount:`${e.amount.toFixed(d)}`})),m.push({label:this._shippingLabel,amount:`${n.shippingCostTotal.toFixed(d)}`}),h){const{storeCredit:t}=e.getCustomerOrThrow();m.push({label:this._storeCreditLabel,amount:`-${Math.min(u,t).toFixed(d)}`})}return{countryCode:o,currencyCode:s,merchantCapabilities:c,supportedNetworks:l,lineItems:m,total:{label:a,amount:`${p.toFixed(d)}`,type:"final"}}}_handleApplePayEvents(e,t,n){e.onvalidatemerchant=n=>ac(this,void 0,void 0,function*(){try{const{body:i}=yield this._onValidateMerchant(t,n);e.completeMerchantValidation(i)}catch(e){throw new Error("Merchant validation failed")}}),e.oncancel=()=>ac(this,void 0,void 0,function*(){return n.reject(new Wi("Continue with applepay"))}),e.onpaymentauthorized=i=>this._onPaymentAuthorized(i,e,t,n)}_onValidateMerchant(e,t){return ac(this,void 0,void 0,function*(){const n=[`validationUrl=${t.validationURL}`,`merchantIdentifier=${e.initializationData.merchantId}`,`displayName=${e.initializationData.storeName}`,`domainName=${window.location.hostname}`].join("&");return this._requestSender.post(`${e.initializationData.paymentsUrl}/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})})}_onPaymentAuthorized(e,t,n,i){var r;return ac(this,void 0,void 0,function*(){const{token:o}=e.payment;let a;(null===(r=n.initializationData)||void 0===r?void 0:r.gateway)===Vi.BRAINTREE&&(a=yield this._getBraintreeDeviceData());const s={methodId:n.id,paymentData:{deviceSessionId:a,formattedPayload:{apple_pay_token:{payment_data:o.paymentData,payment_method:o.paymentMethod,transaction_id:o.transactionIdentifier}}}};try{return yield this._paymentIntegrationService.submitPayment(s),t.completePayment(ApplePaySession.STATUS_SUCCESS),i.resolve()}catch(e){return t.completePayment(ApplePaySession.STATUS_FAILURE),i.reject(new ri(ei.PaymentNotInitialized))}})}_getBraintreeDeviceData(){return ac(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}const dc=vi(e=>{const{getHost:t}=e.getState(),i=new Ei(e);return new sc(n({host:t()}),e,new Zi,new Ui(new Hi(a(),window,i)),new Qi(new r))},[{id:"applepay"}]),cc={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},lc=function({styles:e}){const t={};return e.color&&(t.color=e.color),e.layout&&(t.layout=e.layout),(e["logo-type"]||e["logo-position"])&&(t.logo={},e["logo-type"]&&(t.logo.type=e["logo-type"]),e["logo-position"]&&(t.logo.position=e["logo-position"])),e.ratio&&(t.ratio=e.ratio),(e["text-color"]||e["text-size"])&&(t.text={},e["text-color"]&&(t.text.color=e["text-color"]),e["text-size"]&&(t.text.size=+e["text-size"])),t};function uc(e){return"object"==typeof e&&null!==e&&"bigpayToken"in e&&"defaultInstrument"in e&&"provider"in e&&"trustedShippingAddress"in e&&"method"in e&&"type"in e}var hc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.paypalSdkHelper=n,this.loadingIndicator=i}initialize(e){return hc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments:n}=e||{};if(this.bigcommerce_payments=n,!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(t),{container:o,bannerContainerId:a}=n,{orderId:s,paypalBNPLConfiguration:d=[],isPayPalCreditAvailable:c}=r.initializationData||{};if(void 0!==a){if(!document.getElementById(a))return void console.error("Unable to create banner without valid banner container ID.");const e=null==d?void 0:d.find(({id:e})=>"checkout"===e);if(c||!(null==e?void 0:e.status))return;const t=yield this.paypalSdkHelper.getPayPalMessages(r,i.getCartOrThrow().currency.code);return t&&"function"==typeof(null==t?void 0:t.Messages)?this.renderMessages(t,a,e):void console.error("[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK")}s?this.orderId=s:(this.loadingIndicatorContainer=null==o?void 0:o.split("#")[1],yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t),n.onInit&&"function"==typeof n.onInit&&n.onInit(()=>this.renderButton(t,n)),(void 0===n.shouldRenderPayPalButtonOnInitialization||n.shouldRenderPayPalButtonOnInitialization)&&this.renderButton(t,n))})}execute(e,t){return hc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{var i;this.bigcommerce_payments&&(null===(i=this.paypalButton)||void 0===i||i.close(),this.renderButton(n.methodId,this.bigcommerce_payments),this.handleError(new Error("INSTRUMENT_DECLINED"),r)),t()})),this.handleError(e,r),Promise.reject()}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}prepareVaultedInstrumentPaymentPayload(e,t,n){const{instrumentId:i,shouldSetAsDefaultInstrument:r}=n,o=!this.isTrustedVaultingFlow(n);return o?{methodId:e,paymentData:{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}:{methodId:e,paymentData:{instrumentId:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t},bigpay_token:{token:i}}}}}preparePaymentPayload(e,t,n){const{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:r=!1}=jd(n)?n:{};return{methodId:e,paymentData:{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}}renderButton(e,t){var n,i,r,o;const a=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:d}=s.initializationData||{},{checkoutPaymentButtonStyles:c}=d||{},{container:l,onError:u,onRenderButton:h,onValidate:p,submitForm:m}=t;if(!l)throw new fi('Unable to initialize payment because "container" argument is not provided.');const y=Object.assign(Object.assign({},this.isAppSwitchEnabled(e)&&{appSwitchWhenAvailable:!0}),{fundingSource:a.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(c),createOrder:()=>this.createOrder(),onClick:(e,t)=>this.handleClick(t,p),onApprove:e=>this.handleApprove(e,m),onError:e=>this.handleError(e,u),onCancel:()=>this.toggleLoadingIndicator(!1)});this.paypalButton=a.Buttons(y),this.paypalButton.isEligible()&&(h&&"function"==typeof h&&h(),(null===(i=(n=this.paypalButton).hasReturned)||void 0===i?void 0:i.call(n))&&this.isAppSwitchEnabled(e)?null===(o=(r=this.paypalButton).resume)||void 0===o||o.call(r):this.paypalButton.render(l))}handleClick(e,t){return hc(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;yield null==t?void 0:t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,null==t||t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createOrder(){return hc(this,void 0,void 0,function*(){const e=this.getFieldsValues();return this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_paymentscheckout",{shouldSaveInstrument:(null==e?void 0:e.shouldSaveInstrument)||!1})})}getFieldsValues(){const{getFieldsValues:e}=this.bigcommerce_payments||{};return"function"==typeof e?e():void 0}isTrustedVaultingFlow(e){if(e&&xd(e)){const t=this.paymentIntegrationService.getState().getInstruments(),n=null==t?void 0:t.find(t=>uc(t)&&t.bigpayToken===e.instrumentId);return!(uc(n)&&!n.trustedShippingAddress)}return!1}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isPayPalVaultedInstrumentPaymentData(e){return!!e&&xd(e)&&jd(e)}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:lc(n)};e.Messages(i).render(`#${t}`)}isProviderError(e){var t,n,i;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"INSTRUMENT_DECLINED"===(null===(i=null===(n=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===n?void 0:n.provider_error)||void 0===i?void 0:i.code)}isAppSwitchEnabled(e){var t,n;return null!==(n=null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)&&void 0!==n&&n}}const mc=vi(e=>new pc(e,_r(e),Rr(),new vd({containerStyles:cc})),[{id:"bigcommerce_payments"}]);function yc(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var gc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsRequestSender=t,this.bigCommercePaymentsSdk=n,this.bigCommercePaymentsFastlaneUtils=i}initialize(e){var t,n;return gc(this,void 0,void 0,function*(){const{methodId:i,bigcommerce_payments_fastlane:r}=e;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(this.methodId=i,!r)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_fastlane" argument is not provided.');if(this.bigcommerce_payments_fastlane=r,!r.onInit||"function"!=typeof r.onInit)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_fastlane.onInit" argument is not provided or it is not a function.');if(!r.onChange||"function"!=typeof r.onChange)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_fastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState(),a=o.getCartOrThrow(),s=o.getPaymentMethodOrThrow(i),{isDeveloperModeApplicable:d,isFastlaneStylingEnabled:c}=s.initializationData||{};this.threeDSVerificationMethod=null===(t=s.initializationData)||void 0===t?void 0:t.threeDSVerificationMethod,this.paypalFastlaneSdk=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(s,a.currency.code,a.id);const l=qr(c?null===(n=null==s?void 0:s.initializationData)||void 0===n?void 0:n.fastlaneStyles:{},null==r?void 0:r.styles);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(this.paypalFastlaneSdk,!!d,l),this.shouldRunAuthenticationFlow()&&(yield this.runPayPalAuthenticationFlowOrThrow(i)),yield this.initializePayPalPaymentComponent(),r.onInit(e=>this.renderPayPalPaymentComponent(e)),r.onChange(()=>this.handlePayPalStoredInstrumentChange(i))})}execute(e,t){return gc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const{getHost:t}=e.getState();return new vc(e,new vr(n({host:t()})),Rr(),jr())},[{id:"bigcommerce_payments_fastlane"}]);var Sc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class _c{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=n,this.paypalSdkHelper=i}initialize(e){return Sc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_paylater:n}=e||{};if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(t),{paypalBNPLConfiguration:o=[],orderId:a}=r.initializationData||{},{bannerContainerId:s,container:d}=n;if(void 0!==s){if(!document.getElementById(s))return void console.error("Unable to create banner without valid banner container ID.");const e=o&&o.find(({id:e})=>"checkout"===e);if(!(null==e?void 0:e.status))return;const t=yield this.paypalSdkHelper.getPayPalMessages(r,i.getCartOrThrow().currency.code);return this.renderMessages(t,s,e)}a?this.orderId=a:(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t),this.loadingIndicatorContainer=null==d?void 0:d.split("#")[1],this.renderButton(t,n))})}execute(e,t){return Sc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(h)return;const t={fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.bigCommercePaymentsButtons=n.Buttons(t),this.bigCommercePaymentsButtons.isEligible()||e!==n.FUNDING.PAYLATER){if(!this.bigCommercePaymentsButtons.isEligible()&&e===n.FUNDING.CREDIT)throw new Si(`BigCommercePayments ${e} is not available for your region. Please use BigCommercePayments Checkout instead.`);d&&"function"==typeof d&&d(),this.bigCommercePaymentsButtons.render(a),h=!0}})}handleClick(e,t){return Sc(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;t&&"function"==typeof t&&(yield t(()=>(this.toggleLoadingIndicator(!0),n()),i))})}handleApprove({orderID:e},t){this.orderId=e,t&&"function"==typeof t&&t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:lc(n)};e.Messages(i).render(`#${t}`)}}const wc=vi(e=>new _c(e,_r(e),new vd({containerStyles:cc}),Rr()),[{id:"bigcommerce_payments_paylater"}]);class Ic extends nr{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}var Cc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class bc{constructor(e,t,n,i=3e3,r=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=n,this.pollingInterval=i,this.maxPollingIntervalTime=r,this.pollingTimer=0,this.stopPolling=ce}initialize(e){return Cc(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,bigcommerce_payments_ratepay:i}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_ratepay" argument is not provided.');const{legalTextContainer:r,container:o,loadingContainerId:a}=i;if(!o)throw new fi('Unable to initialize payment because "options.container" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.legalTextContainer" argument is not provided.');if(!a)throw new fi('Unable to initialize payment because "options.loadingContainerId" argument is not provided.');this.loadingIndicatorContainer=a;const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t),{merchantId:d}=s.initializationData||{};if(!d)throw new fi("Unable to initialize payment because merchantId argument is not provided.");this.bigcommerce_payments_ratepay=i,yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n),this.createFraudNetScript(d,n,t),this.loadFraudnetConfig(),this.renderLegalText(r,o)})}execute(e,t){return Cc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.initializePollingMechanism(n.methodId,e,t,n.gatewayId)})}catch(e){return this.handleError(e),new Promise((e,t)=>t())}})}finalize(){return Promise.reject(new Cd)}deinitialize(){const{legalTextContainer:e}=this.bigcommerce_payments_ratepay||{},t=document.querySelectorAll('[data-id="fraudnetScript"]')[0],n=document.querySelectorAll('[data-id="fraudnetConfig"]')[0];if(this.deinitializePollingMechanism(),t.remove(),n.remove(),e){const t=document.getElementById(e);null==t||t.remove()}return Promise.resolve()}normalizeDate(e){const t=this.formatDate(e.getDate()),n=this.formatDate(e.getMonth()+1);return`${e.getFullYear()}-${n}-${t}`}formatDate(e){return`${e<10?0:""}${e}`}renderLegalText(e,t){const n=e,i=t.split("#")[1],r=document.getElementById(i),o=null==r?void 0:r.parentNode,a=document.createElement("div");a.style.marginBottom="20px",a.setAttribute("id",n),null==o||o.prepend(a);const s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=s.Legal({fundingSource:s.Legal.FUNDING.PAY_UPON_INVOICE});if(!document.getElementById(n))throw new fi('Unable to initialize payment because "legalTextContainerElement" argument is not found.');d.render(`#${n}`)}handleError(e){const{onError:t}=this.bigcommerce_payments_ratepay||{};this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createFraudNetScript(e,t,n){const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{testMode:r}=i.config,o=document.createElement("script");o.setAttribute("type","application/json"),o.setAttribute("fncls","fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99"),o.setAttribute("data-id","fraudnetScript"),this.guid=this.generateGUID();const a={f:this.guid,s:`${e}_checkout-page`,sandbox:r};o.innerHTML=JSON.stringify(a),document.body.appendChild(o)}generateGUID(){let e="";for(let t=0;t<32;t+=1)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(62*Math.random())];return e}loadFraudnetConfig(){const e=document.createElement("script");e.setAttribute("data-id","fraudnetConfig"),e.src="https://c.paypal.com/da/r/fb.js",document.body.appendChild(e)}reinitializeStrategy(e){return Cc(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}initializePollingMechanism(e,t,n,i){return Cc(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.bigCommercePaymentsIntegrationService.getOrderStatus("bigcommerce_payments_apms",{params:{useMetadata:!0}}),o=r===cr.PollingStop,a=r===cr.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimernew bc(e,_r(e),new vd({containerStyles:Object.assign(Object.assign({},cc),{position:"fixed"})})),[{gateway:"bigcommerce_payments_apms",id:"ratepay"}]);var Oc;!function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification",e.CardExpiryVerification="cardExpiryVerification"}(Oc||(Oc={}));const Ec=Oc;function Ac(e){return Ec.CardNumber in e&&Ec.CardName in e&&Ec.CardExpiry in e}function Tc(e){return Ec.CardNumberVerification in e&&Ec.CardCodeVerification in e&&Ec.CardExpiryVerification in e}var kc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Dc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdk=n,this.bigCommercePaymentsFastlaneUtils=i}initialize(e){return kc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_creditcards:n}=e,i=n,{form:r,onCreditCardFieldsRenderingError:o,onLoadComplete:a}=i||{};if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new fi('Unable to proceed because "options.bigcommerce_payments_creditcards.form" argument is not provided.');this.hostedFormOptions=r,this.isCreditCardForm=Ac(r.fields),this.isCreditCardVaultedForm=Tc(r.fields)&&!this.hasUndefinedValues(),yield this.paymentIntegrationService.loadPaymentMethod(t),yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t,void 0,!0,!0),(this.isCreditCardForm||this.isCreditCardVaultedForm)&&(yield this.initializeFields(r,o)),null==a||a(),this.shouldInitializePayPalFastlane(t)&&(yield this.initializePayPalFastlaneOrThrow(t))})}execute(e,t){return kc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(n===ir.No||n===ir.Unknown)throw new Error;return this.handleApprove({orderID:e,vaultSetupToken:t})},onError:()=>{throw new Qr},inputEvents:{onChange:t=>this.onChangeHandler(e,t),onFocus:t=>this.onFocusHandler(e,t),onBlur:t=>this.onBlurHandler(e,t),onInputSubmitRequest:t=>this.onInputSubmitRequest(e,t)}},o);if(this.cardFields=yield r.CardFields(a),!this.cardFields.isEligible())throw new ri(ei.PaymentNotInitialized);try{this.stylizeInputContainers(n),Ac(n)&&(yield this.renderFields(n)),Tc(n)&&(yield this.renderVaultedFields(n))}catch(e){"function"==typeof t&&t(e)}})}getExecuteCallback(e){return Tc(e)?this.createVaultSetupTokenCallback():this.createOrderCallback()}createVaultSetupTokenCallback(){return{createVaultSetupToken:()=>kc(this,void 0,void 0,function*(){const{setupToken:e}=(yield this.bigCommercePaymentsIntegrationService.createOrderCardFields("bigcommerce_payments_creditcardscheckout",Object.assign(Object.assign({},this.getInstrumentParams()),{setupToken:!0})))||{};return e})}}createOrderCallback(){return{createOrder:()=>kc(this,void 0,void 0,function*(){const{orderId:e}=(yield this.bigCommercePaymentsIntegrationService.createOrderCardFields("bigcommerce_payments_creditcardscheckout",this.getInstrumentParams()))||{};return e})}}handleApprove({orderID:e,vaultSetupToken:t}){e&&(this.returnedOrderId=e),t&&(this.returnedVaultedToken=t)}renderFields(e){var t,n,i,r;return kc(this,void 0,void 0,function*(){const o=this.getCardFieldsOrThrow();(null===(t=e.cardCode)||void 0===t?void 0:t.containerId)&&(this.cvvField=o.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCode.containerId}`)),(null===(n=e.cardExpiry)||void 0===n?void 0:n.containerId)&&(this.expiryField=o.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiry.containerId}`)),(null===(i=e.cardName)||void 0===i?void 0:i.containerId)&&(this.nameField=o.NameField({placeholder:""}),yield this.nameField.render(`#${e.cardName.containerId}`)),(null===(r=e.cardNumber)||void 0===r?void 0:r.containerId)&&(this.numberField=o.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumber.containerId}`))})}renderVaultedFields(e){var t,n,i;return kc(this,void 0,void 0,function*(){const r=this.getCardFieldsOrThrow();(null===(t=e.cardCodeVerification)||void 0===t?void 0:t.containerId)&&(this.cvvField=r.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCodeVerification.containerId}`)),(null===(n=e.cardExpiryVerification)||void 0===n?void 0:n.containerId)&&(this.expiryField=r.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiryVerification.containerId}`)),(null===(i=e.cardNumberVerification)||void 0===i?void 0:i.containerId)&&(this.numberField=r.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumberVerification.containerId}`))})}getInstrumentParams(){if(!this.executionPaymentData)return{};if(jd(this.executionPaymentData)){const{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}=this.executionPaymentData;return{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}}if(xd(this.executionPaymentData)){const{instrumentId:e}=this.executionPaymentData;return{instrumentId:e}}return{}}getFieldTypeByEmittedField({emittedBy:e}){return{fieldType:this.mapFieldType(e)}}submitHostedForm(){return kc(this,void 0,void 0,function*(){const e=this.getCardFieldsOrThrow(),t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),n={billingAddress:{company:t.company,addressLine1:t.address1,addressLine2:t.address2,adminArea1:t.stateOrProvinceCode,adminArea2:t.city,postalCode:t.postalCode,countryCode:t.countryCode}};try{this.isCreditCardVaultedForm?yield e.submit():yield e.submit(n)}catch(e){throw new Qr("Failed authentication. Please try to authorize again.")}})}validateHostedFormOrThrow(){var e,t;return kc(this,void 0,void 0,function*(){const n=this.getCardFieldsOrThrow(),i=yield n.getState().then(e=>e),r=this.getValidityData(i);if(!r.isValid)throw null===(t=null===(e=this.hostedFormOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,r),new lo(this.mapValidationErrors(r.errors))})}getValidityData({fields:e}){const t=Object.assign({},e);delete t.cardNameField;const n=Object.keys(t);return{isValid:n.every(e=>{var n;return null===(n=t[e])||void 0===n?void 0:n.isValid}),errors:n.reduce((e,n)=>{var i;const r=this.mapFieldType(n);return Object.assign(Object.assign({},e),{[r]:(null===(i=t[n])||void 0===i?void 0:i.isValid)?void 0:[this.getInvalidErrorByFieldType(r)]})},{})}}getInvalidErrorByFieldType(e){switch(e){case Ec.CardCode:case Ec.CardCodeVerification:return{fieldType:e,message:"Invalid card code",type:"invalid_card_code"};case Ec.CardNumber:case Ec.CardNumberVerification:return{fieldType:e,message:"Invalid card number",type:"invalid_card_number"};case Ec.CardExpiry:case Ec.CardExpiryVerification:return{fieldType:e,message:"Invalid card expiry",type:"invalid_card_expiry"};default:return{fieldType:e,message:"Invalid field",type:"invalid"}}}mapValidationErrors(e={}){const t={};return Object.keys(e).forEach(n=>{var i,r;t[n]=[{message:(null===(r=null===(i=e[n])||void 0===i?void 0:i[0])||void 0===r?void 0:r.message)||"",type:n}]}),t}mapFieldType(e){switch(e){case"name":return Ec.CardName;case"cardNumberField":case"number":return this.isCreditCardForm?Ec.CardNumber:Ec.CardNumberVerification;case"cardExpiryField":case"expiry":return this.isCreditCardForm?Ec.CardExpiry:Ec.CardExpiryVerification;case"cardCvvField":case"cvv":return this.isCreditCardForm?Ec.CardCode:Ec.CardCodeVerification;default:throw new Error("Unexpected field type")}}getCardFieldsOrThrow(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);return this.cardFields}getInputStyles(e){var t,n,i;const r={"font-size":(null===(t=null==e?void 0:e.default)||void 0===t?void 0:t.fontSize)||"1rem","font-family":(null===(n=null==e?void 0:e.default)||void 0===n?void 0:n.fontFamily)||"Montserrat, Arial, Helvetica, sans-serif","font-weight":(null===(i=null==e?void 0:e.default)||void 0===i?void 0:i.fontWeight)||"400",outline:"none",padding:"9px 13px"},o=Object.assign(Object.assign({},r),{color:"#333333"});return{input:o,".invalid":Object.assign(Object.assign({},r),{color:"red"}),".valid":o,":focus":o}}stylizeInputContainers(e){Object.values(e||{}).forEach(e=>{const t=document.getElementById(`${(null==e?void 0:e.containerId)||""}`);t&&(t.style.padding="0px",t.style.boxShadow="none",t.style.border="none",t.style.background="transparent",t.style.marginBottom="10px",t.style.marginLeft="-5px")})}hasUndefinedValues(){return!this.hostedFormOptions||Object.values(this.hostedFormOptions.fields).some(e=>void 0===e)}onChangeHandler(e,t){var n;null===(n=null==e?void 0:e.onValidate)||void 0===n||n.call(e,this.getValidityData(t))}onFocusHandler(e,t){var n;null===(n=null==e?void 0:e.onFocus)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onBlurHandler(e,t){var n;null===(n=null==e?void 0:e.onBlur)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onInputSubmitRequest(e,t){var n;null===(n=null==e?void 0:e.onEnter)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}shouldInitializePayPalFastlane(e){var t,n;const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(e),o=i.getPaymentProviderCustomer(),a=(s=o)&&("authenticationState"in s||"addresses"in s||"instruments"in s)?o:{};var s;return(null===(t=null==r?void 0:r.initializationData)||void 0===t?void 0:t.isAcceleratedCheckoutEnabled)&&(null===(n=null==r?void 0:r.initializationData)||void 0===n?void 0:n.isBigCommercePaymentsAnalyticsV2Enabled)&&!(null==a?void 0:a.authenticationState)}initializePayPalFastlaneOrThrow(e){return kc(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getPaymentMethodOrThrow(e),{initializationData:r}=i;if(!(null==r?void 0:r.connectClientToken))return;const o=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(i,n.currency.code,n.id);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(o,!!(null==r?void 0:r.isDeveloperModeApplicable))}catch(e){}})}}const Mc=vi(e=>new Dc(e,_r(e),Rr(),jr()),[{id:"bigcommerce_payments_creditcards"}]);var zc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Nc{constructor(e,t,n,i,r=3e3,o=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdkHelper=n,this.loadingIndicator=i,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.pollingTimer=0,this.stopPolling=ce,this.isPollingEnabled=!1}initialize(e){return zc(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,bigcommerce_payments_apms:i}=e;if(this.bigCommercePaymentsAlternativeMethods=i,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_apms" argument is not provided.');const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(n,t),{orderId:a,shouldRenderFields:s}=o.initializationData||{},d=r.getStoreConfigOrThrow().checkoutSettings.features;this.isPollingEnabled=Ci(d,"PAYPAL-5624.bcp_ideal_polling"),a?this.orderId=a:(this.paypalApms=yield this.bigCommercePaymentsSdkHelper.getPayPalApmsSdk(o,r.getCartOrThrow().currency.code),this.loadingIndicatorContainer=i.container.split("#")[1],this.renderButton(n,t,i),s&&this.renderFields(n,i))})}execute(e,t){return zc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.initializePollingMechanism(r,e,t,o)})),this.isNonInstantPaymentMethod(r)||(yield this.paymentIntegrationService.submitOrder(i,t)),yield this.bigCommercePaymentsIntegrationService.submitPayment(r,this.orderId,o)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,this.isPollingEnabled&&this.resetPollingMechanism(),null===(e=this.bigCommercePaymentsButton)||void 0===e||e.close(),Promise.resolve()}initializePollingMechanism(e,t,n,i){return zc(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.bigCommercePaymentsIntegrationService.getOrderStatus(i),o=r===cr.Approved,a=r===cr.PollingError;if(o)return this.deInitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimern.onInitButton(t),createOrder:()=>this.onCreateOrder(e,t,n),onApprove:e=>this.handleApprove(e,c),onCancel:()=>{this.toggleLoadingIndicator(!1),this.deInitializePollingMechanism()},onError:e=>{this.deInitializePollingMechanism(),this.handleFailure(e,s)},onClick:(e,t)=>zc(this,void 0,void 0,function*(){return n.onValidate(t.resolve,t.reject)})};this.bigCommercePaymentsButton=i.Buttons(l),this.bigCommercePaymentsButton.isEligible()&&(d&&"function"==typeof d&&d(),this.bigCommercePaymentsButton.render(a))}onCreateOrder(e,t,n){return zc(this,void 0,void 0,function*(){const{onValidate:i}=n;yield i(()=>(this.toggleLoadingIndicator(!0),()=>Promise.resolve()),ce);const r=yield this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apms");if(this.isNonInstantPaymentMethod(e)){const n={useStoreCredit:!1},i={params:{methodId:e,gatewayId:t}};yield this.paymentIntegrationService.submitOrder(n,i),yield this.bigCommercePaymentsIntegrationService.submitPayment(e,r,t)}return r})}handleApprove({orderID:e},t){this.orderId=e,t()}handleFailure(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderFields(e,t){const n=this.getPaypalAmpsSdkOrThrow(),i=this.paymentIntegrationService.getState(),{firstName:r,lastName:o,email:a}=i.getBillingAddressOrThrow(),{apmFieldsContainer:s,apmFieldsStyles:d}=t;if(!s)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_apms" argument should contain "apmFieldsContainer".');const c=document.querySelector(s);c&&(c.innerHTML="");const l={fundingSource:e,style:d||{},fields:{name:{value:`${r} ${o}`},email:{value:a}}};n.PaymentFields(l).render(s)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isNonInstantPaymentMethod(e){return e.toUpperCase()in dr}getPaypalAmpsSdkOrThrow(){if(!this.paypalApms)throw new mi;return this.paypalApms}}const xc=vi(e=>new Nc(e,_r(e),Rr(),new vd({containerStyles:cc})),[{gateway:"bigcommerce_payments_apms"}]);class Rc{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){const{gatewayId:t,methodId:n,bigcommerce_payments_apms:i}=e;if(this.bigCommercePaymentsAlternativeMethods=i,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');return Promise.resolve()}execute(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{window.location.replace(t),n()})}return this.handleError(e),Promise.reject(e)}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}handleError(e){const{onError:t}=this.bigCommercePaymentsAlternativeMethods||{};t&&"function"==typeof t&&t(e)}}const Fc=vi(e=>new Rc(e,_r(e)),[{gateway:"bigcommerce_payments_apms",id:"klarna"},{gateway:"bigcommerce_payments_apms",id:"afterpay"}]);var Lc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Bc{constructor(e,t,n){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=n}initialize(e){var t,n;return Lc(this,void 0,void 0,function*(){const{methodId:i,bigcommerce_payments_venmo:r}=e||{};if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i);(null===(t=o.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(n=o.initializationData)||void 0===n?void 0:n.orderId:(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i),this.loadingIndicatorContainer=r.container.split("#")[1],this.renderButton(i,r))})}execute(e,t){return Lc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rthis.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmocheckout"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=n.Buttons(u),!this.paypalButton.isEligible())throw new Si("Venmo is not available for your region. Please another payment method instead.");d&&"function"==typeof d&&d(),this.paypalButton.render(a)}handleClick(e,t){return Lc(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;yield t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,t(),this.toggleLoadingIndicator(!1)}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const jc=vi(e=>new Bc(e,_r(e),new vd({styles:{backgroundColor:"black"}})),[{id:"bigcommerce_payments_venmo"}]);class Uc{initialize(e){this._blueSnapSdk=e}initialize3ds(e,t){return n=this,i=void 0,o=function*(){const n=this._getBlueSnapSdk();return new Promise((i,r)=>{n.threeDsPaymentsSetup(e,e=>"1"===e.code?i(e.threeDSecure.threeDSecureReferenceId):r(new Qr)),n.threeDsPaymentsSubmitData(t)})},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_getBlueSnapSdk(){return ii(this._blueSnapSdk,()=>new ri(ei.PaymentNotInitialized))}}function qc(e){return Ec.CardNumber in e}function Vc(e){return Ec.CardCodeVerification in e||Ec.CardNumberVerification in e}var Gc,Hc,Wc,$c,Yc,Kc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Jc{constructor(e,t,n,i){this._scriptLoader=e,this._paymentIntegrationService=t,this._blueSnapDirectHostedForm=n,this._blueSnapDirect3ds=i}initialize(e){return Kc(this,void 0,void 0,function*(){const{methodId:t,gatewayId:n,creditCard:i}=e;if(!n||!i)throw new fi;const r=yield this._paymentIntegrationService.loadPaymentMethod(n,{params:{method:t,bigpayToken:i.bigpayToken}}),{config:{testMode:o,is3dsEnabled:a},clientToken:s}=r.getPaymentMethodOrThrow(t,n);if(this._blueSnapSdk=yield this._scriptLoader.load(o),this._paymentFieldsToken=s,this._shouldUseHostedFields=qc(i.form.fields)||Vc(i.form.fields)&&!!i.form.fields.cardNumberVerification,this._shouldUseHostedFields){this._blueSnapDirectHostedForm.initialize(this._blueSnapSdk,i.form.fields);try{yield this._blueSnapDirectHostedForm.attach(this._getPaymentFieldsToken(),i,a)}catch(e){if(e instanceof fi)return;throw e}}})}execute(e){return Kc(this,void 0,void 0,function*(){if(!e.payment)throw new co(["payment"]);if(!this._blueSnapSdk)throw new co(["payment"]);const{paymentData:t}=e.payment,{shouldSaveInstrument:n,shouldSetAsDefaultInstrument:i}=jd(t)?t:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},r=this._getPaymentFieldsToken();let o;const{is3dsEnabled:a}=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.payment.methodId,e.payment.gatewayId).config,s=this._shouldUseHostedFields?yield this._blueSnapDirectHostedForm.validate().submit(a?this._getBlueSnapDirectThreeDSecureData():void 0,!(jd(t)&&xd(t))):void 0;if(yield this._paymentIntegrationService.submitOrder(),jd(t)&&xd(t)&&this._paymentFieldsToken&&t.instrumentId){if(a){this._blueSnapDirect3ds.initialize(this._blueSnapSdk);const{last4:e,brand:n}=this._paymentIntegrationService.getState().getCardInstrumentOrThrow(t.instrumentId),i=Object.assign({last4Digits:e,ccType:n.toUpperCase()},this._getBlueSnapDirectThreeDSecureData());o=yield this._blueSnapDirect3ds.initialize3ds(this._paymentFieldsToken,i)}yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e.payment),{paymentData:Object.assign(Object.assign(Object.assign({instrumentId:t.instrumentId},this._shouldUseHostedFields?{nonce:r}:{}),o?{deviceSessionId:o}:{}),{shouldSetAsDefaultInstrument:!!i})}))}else yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e.payment),{paymentData:{formattedPayload:{credit_card_token:{token:JSON.stringify({pfToken:r,cardHolderName:s&&s.cardHolderName})},vault_payment_instrument:n,set_as_default_stored_instrument:i}}}))})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this._shouldUseHostedFields&&this._blueSnapDirectHostedForm.detach(),Promise.resolve()}_getBlueSnapDirectThreeDSecureData(){var e;const{getBillingAddress:t,getShippingAddress:n,getCustomer:i,getCheckoutOrThrow:r,getCartOrThrow:o}=this._paymentIntegrationService.getState(),a=t(),s=n(),d=(null===(e=i())||void 0===e?void 0:e.email)||(null==a?void 0:a.email),c=(null==a?void 0:a.phone)||(null==s?void 0:s.phone);return Object.assign(Object.assign(Object.assign(Object.assign({amount:r().outstandingBalance,currency:o().currency.code},d&&{email:d}),c&&{phone:c}),a&&{billingFirstName:a.firstName,billingLastName:a.lastName,billingCountry:a.countryCode,billingCity:a.city,billingAddress:`${a.address1} ${a.address2}`.trim(),billingZip:a.postalCode}),s&&{shippingFirstName:s.firstName,shippingLastName:s.lastName,shippingCountry:s.countryCode,shippingCity:s.city,shippingAddress:`${s.address1} ${s.address2}`.trim(),shippingZip:s.postalCode})}_getPaymentFieldsToken(){return ii(this._paymentFieldsToken,()=>new ti(Xn.MissingPaymentToken))}}!function(e){e.AMEX="american-express",e.CHINA_UNION_PAY="unionpay",e.DINERS="diners-club",e.DISCOVER="discover",e.JCB="jcb",e.MASTERCARD="mastercard",e.UNKNOWN="unknown",e.VISA="visa"}(Gc||(Gc={})),function(e){e.ON_BLUR="onBlur",e.ON_SUBMIT="onSubmit"}(Hc||(Hc={})),function(e){e.EMPTY="empty",e.INVALID="invalid",e.THREE_DS_NOT_ENABLED="3D Secure is not enabled"}(Wc||(Wc={})),function(e){e.CC_NOT_SUPORTED="22013",e.ERROR_403="403",e.ERROR_404="404",e.ERROR_500="500",e.INVALID_OR_EMPTY="10",e.SESSION_EXPIRED="400",e.THREE_DS_AUTH_FAILED="14101",e.THREE_DS_CLIENT_ERROR="14103",e.THREE_DS_MISSING_FIELDS="14102",e.THREE_DS_NOT_ENABLED="14100",e.TOKEN_EXPIRED="14040",e.TOKEN_NOT_ASSOCIATED="14042",e.TOKEN_NOT_FOUND="14041"}($c||($c={})),function(e){e.CardCode="cvv",e.CardExpiry="exp",e.CardName="noc",e.CardNumber="ccn"}(Yc||(Yc={}));const Zc={[Yc.CardNumber]:Ec.CardNumber,[Yc.CardExpiry]:Ec.CardExpiry,[Yc.CardName]:Ec.CardName,[Yc.CardCode]:Ec.CardCode},Qc={empty:{[Ec.CardNumber]:{fieldType:"cardNumber",message:"Credit card number is required",type:"required"},[Ec.CardNumberVerification]:{fieldType:"cardNumber",message:"Credit card number is required",type:"required"},[Ec.CardExpiry]:{fieldType:"cardExpiry",message:"Expiration date is required",type:"required"},[Ec.CardCode]:{fieldType:"cardCode",message:"CVV is required",type:"required"},[Ec.CardName]:{fieldType:"cardName",message:"Full name is required",type:"required"}},invalid:{[Ec.CardNumber]:{fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},[Ec.CardNumberVerification]:{fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},[Ec.CardExpiry]:{fieldType:"cardExpiry",message:"Expiration date must be a valid future date in MM / YY format",type:"invalid_card_expiry"},[Ec.CardCode]:{fieldType:"cardCode",message:"CVV must be valid",type:"invalid_card_code"},[Ec.CardName]:{fieldType:"cardName",message:"Full name is required",type:"required"}}};class Xc{constructor(e,t){this._nameOnCardInput=e,this._hostedInputValidator=t}initialize(e,t){this._blueSnapSdk=e,t&&(qc(t)?this._hostedInputValidator.initialize():Vc(t)&&t.cardNumberVerification&&this._hostedInputValidator.initializeValidationFields())}attach(e,t,n){var i,r,o,a,s=t.form,{fields:d}=s,c=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const r=this._getHostedPaymentFieldsOptions(e,d,c,i,n);t.hostedPaymentFieldsCreate(r),qc(d)&&this._nameOnCardInput.attach(r,d.cardName.accessibilityLabel,d.cardName.placeholder)})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}validate(){var e;const t=this._hostedInputValidator.validate();if(null===(e=this._onValidate)||void 0===e||e.call(this,t),!t.isValid){const e=Object.entries(t.errors).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n.map(({message:e,type:t})=>({message:e,type:t}))}),{});throw new lo(e)}return this}submit(e,t=!1){return new Promise((n,i)=>this._getBlueSnapSdk().hostedPaymentFieldsSubmitData(e=>this._isBlueSnapDirectCallbackError(e)?i(new Qr(e.statusCode===$c.THREE_DS_AUTH_FAILED?e.error[0].errorDescription:`Submission failed with status: ${e.statusCode} and errors: ${JSON.stringify(e.error)}`)):n(Object.assign(Object.assign({},e.cardData),t?{cardHolderName:this._nameOnCardInput.getValue()}:{})),e))}detach(){this._nameOnCardInput.detach()}_isBlueSnapDirectCallbackError(e){return"error"in e}_getHostedPaymentFieldsOptions(e,t,{onFocus:n,onBlur:i,onValidate:r,onCardTypeChange:o,onEnter:a,styles:s},d,c){var l;return Object.assign(Object.assign(Object.assign({token:e,onFieldEventHandler:{setupComplete:()=>d(),onFocus:this._usetUiEventCallback(n),onBlur:this._usetUiEventCallback(i),onError:this._handleError(r),onType:(e,t)=>null==o?void 0:o({cardType:Gc[t]}),onEnter:this._usetUiEventCallback(a),onValid:e=>null==r?void 0:r(this._hostedInputValidator.validate({tagId:e}))}},qc(t)&&{ccnPlaceHolder:t.cardNumber.placeholder||"",cvvPlaceHolder:(null===(l=t.cardCode)||void 0===l?void 0:l.placeholder)||"",expPlaceHolder:t.cardExpiry.placeholder||"MM / YY"}),s&&{style:this._mapStyles(s)}),{"3DS":c})}_mapStyles({default:e,error:t,focus:n}){return Object.entries(Object.assign(Object.assign(Object.assign({},e&&{input:e}),t&&{".invalid":t}),n&&{":focus":n})).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:Object.entries(n).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[te(t)]:n}),{})}),{})}_handleError(e){return(t,n,i,r)=>{if(n===$c.INVALID_OR_EMPTY&&t&&function(e){return void 0!==e&&[Wc.EMPTY,Wc.INVALID].includes(e)}(i))return null==e?void 0:e(this._hostedInputValidator.validate({tagId:t,errorDescription:i}));throw new Qr(`An unexpected error has occurred: ${JSON.stringify({tagId:t,errorCode:n,errorDescription:i,eventOrigin:r})}`)}}_usetUiEventCallback(e){return t=>{e&&e({fieldType:Zc[t]})}}_getBlueSnapSdk(){return ii(this._blueSnapSdk,()=>new ri(ei.PaymentNotInitialized))}_setCustomBlueSnapAttributes(e){const{cardNumber:t,cardExpiry:n,cardCode:i,cardName:r}=e,o=document.getElementById(t.containerId),a=document.getElementById(n.containerId),s=i&&document.getElementById(i.containerId),d=document.getElementById(r.containerId);if(!(o&&a&&s&&d))throw new fi("Unable to create hosted payment fields to invalid HTML container elements.");o.dataset.bluesnap=Yc.CardNumber,a.dataset.bluesnap=Yc.CardExpiry,s.dataset.bluesnap=Yc.CardCode,d.dataset.bluesnap=Yc.CardName}_setCustomStoredCardsBlueSnapAttributes(e){const{cardNumberVerification:t,cardCodeVerification:n}=e,i=t&&document.getElementById(t.containerId),r=n&&document.getElementById(n.containerId);(i||r)&&(i&&(i.dataset.bluesnap=Yc.CardNumber),r&&(r.dataset.bluesnap=Yc.CardCode))}}class el{constructor(){this._errors={}}initialize(){this._errors={cardNumber:[Qc.empty.cardNumber],cardExpiry:[Qc.empty.cardExpiry],cardCode:[Qc.empty.cardCode],cardName:[Qc.empty.cardName]}}initializeValidationFields(){this._errors={cardNumberVerification:[Qc.empty.cardNumber]}}validate(e){return e&&this._updateErrors(e.tagId,e.errorDescription),{isValid:Object.values(this._errors).every(e=>0===e.length),errors:this._errors}}_updateErrors(e,t){const n=this._errors.cardNumberVerification?Ec.CardNumberVerification:Zc[e];this._errors[n]=t?[Qc[t][n]]:[]}}class tl{attach({style:e,onFieldEventHandler:{onFocus:t,onBlur:n,onValid:i,onError:r,onEnter:o}={}},a,s){var d;this._style=e,this._create(),this._getInput().addEventListener("focus",this._handleFocus(t)),this._getInput().addEventListener("blur",this._handleBlur(n,i,r)),this._getInput().addEventListener("enter",this._handleEnter(o)),a&&this._getInput().setAttribute("aria-label",a),s&&(this._getInput().placeholder=s),null===(d=document.querySelector('[data-bluesnap="noc"]'))||void 0===d||d.appendChild(this._getInput())}getValue(){return this._getInput().value}detach(){this._input&&(this._input.remove(),this._input=void 0)}_handleFocus(e){return()=>{var t;this._applyStyles(null===(t=this._style)||void 0===t?void 0:t[":focus"]),null==e||e(Yc.CardName)}}_handleBlur(e,t,n){return({target:i})=>{var r,o;null==e||e(Yc.CardName),i instanceof HTMLInputElement&&(/\w{1,200}/.test(i.value)?(this._applyStyles(null===(r=this._style)||void 0===r?void 0:r.input),null==t||t(Yc.CardName)):(this._applyStyles(null===(o=this._style)||void 0===o?void 0:o[".invalid"]),null==n||n(Yc.CardName,$c.INVALID_OR_EMPTY,Wc.EMPTY,Hc.ON_BLUR)))}}_handleEnter(e){return()=>null==e?void 0:e(Yc.CardName)}_applyStyles(e={}){const t={color:e.color,fontFamily:e["font-family"],fontSize:e["font-size"],fontWeight:e["font-weight"]},n=Object.keys(t);n.every(e=>["color","fontFamily","fontSize","fontWeight"].includes(e))&&n.forEach(e=>{t[e]&&(this._getInput().style[e]=t[e]||"")})}_configureInput(){this._getInput().autocomplete="cc-name",this._getInput().id=Yc.CardName,this._getInput().inputMode="text",this._getInput().maxLength=200,this._getInput().style.backgroundColor="transparent",this._getInput().style.border="0",this._getInput().style.height="100%",this._getInput().style.margin="0",this._getInput().style.outline="none",this._getInput().style.padding="0",this._getInput().style.width="100%",this._getInput().type="text"}_getInput(){return ii(this._input,()=>new ri(ei.PaymentNotInitialized))}_create(){var e;this._input=document.createElement("input"),this._configureInput(),this._applyStyles(null===(e=this._style)||void 0===e?void 0:e.input)}}var nl;!function(e){e.PRODUCTION="https://pay.bluesnap.com/web-sdk/5/bluesnap.js",e.SANDBOX="https://sandpay.bluesnap.com/web-sdk/5/bluesnap.js"}(nl||(nl={}));class il{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e=!1){return t=this,n=void 0,r=function*(){if(this._window.bluesnap)return this._window.bluesnap;if(yield this._scriptLoader.loadScript(e?nl.SANDBOX:nl.PRODUCTION),!this._window.bluesnap)throw new mi;return this._window.bluesnap},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const rl=vi(e=>new Jc(new il(a()),e,new Xc(new tl,new el),new Uc),[{id:"credit_card",gateway:"bluesnapdirect"}]);class ol{constructor(e){this._paymentIntegrationService=e}execute(e){return t=this,n=void 0,r=function*(){const t=this._formatePaymentPayload(e);yield this._paymentIntegrationService.submitOrder();try{yield this._paymentIntegrationService.submitPayment(t)}catch(e){if(this._isBlueSnapDirectRedirectResponse(e)){const t=e.body.provider_data&&JSON.parse(e.body.provider_data);let n=e.body.additional_action_required.data.redirect_url;if(function(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!t.merchantid&&"string"==typeof t.merchantid}(t)){const e=new URLSearchParams(t).toString();n=`${n}&${e}`}return new Promise(()=>window.location.replace(n))}return Promise.reject(e)}},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}initialize(){return Promise.resolve()}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_formatePaymentPayload({payment:e}){if(!e)throw new co(["payment"]);return e.paymentData&&xd(e.paymentData)&&jd(e.paymentData)?Object.assign(Object.assign({},e),{paymentData:{instrumentId:e.paymentData.instrumentId,shouldSetAsDefaultInstrument:!!e.paymentData.shouldSetAsDefaultInstrument}}):(t=e.paymentData,Boolean("object"==typeof t&&null!==t&&"accountNumber"in t&&"accountType"in t&&"shopperPermission"in t&&"routingNumber"in t)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{ecp:Object.assign({account_number:e.paymentData.accountNumber,account_type:e.paymentData.accountType,shopper_permission:e.paymentData.shopperPermission,routing_number:e.paymentData.routingNumber},e.paymentData.companyName?{company_name:e.paymentData.companyName}:{}),vault_payment_instrument:e.paymentData.shouldSaveInstrument,set_as_default_stored_instrument:e.paymentData.shouldSetAsDefaultInstrument}}}):(n=e.paymentData,Boolean("object"==typeof n&&null!==n&&"iban"in n&&"firstName"in n&&"lastName"in n&&"shopperPermission"in n)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{sepa_direct_debit:{iban:e.paymentData.iban,first_name:e.paymentData.firstName,last_name:e.paymentData.lastName,shopper_permission:e.paymentData.shopperPermission},vault_payment_instrument:e.paymentData.shouldSaveInstrument,set_as_default_stored_instrument:e.paymentData.shouldSetAsDefaultInstrument}}}):function(e){return Boolean("object"==typeof e&&null!==e&&"bic"in e)}(e.paymentData)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{ideal:{bic:e.paymentData.bic}}}}):function(e){return Boolean("object"==typeof e&&null!==e&&"iban"in e&&!("firstName"in e)&&!("lastName"in e)&&!("shopperPermission"in e))}(e.paymentData)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{pay_by_bank:{iban:e.paymentData.iban}}}}):{methodId:e.methodId}));var t,n}_isBlueSnapDirectRedirectResponse(e){var t;if("object"!=typeof e||null===e)return!1;const n=e;if(!n.body)return!1;const i=n.body;return"additional_action_required"===i.status&&!!(null===(t=i.additional_action_required)||void 0===t?void 0:t.data.redirect_url)}}const al=vi(e=>new ol(e),[{gateway:"bluesnapdirect"}]);var sl;!function(e){e.ACKNOWLEDGE="ACKNOWLEDGE",e.FINALIZE="FINALIZE",e.INITIALIZE="INITIALIZE"}(sl||(sl={}));const dl=sl;var cl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ll{constructor(e){this._paymentIntegrationService=e}execute(e,t){return cl(this,void 0,void 0,function*(){const{payment:n}=e;if(!n)throw new co(["payment"]);if(!this._initializeOptions)throw new ri(ei.PaymentNotInitialized);const{onLoad:i,style:r}=this._initializeOptions,o=this._createIframe("bluesnapv2_hosted_payment_page",r),a=new En(new Promise(ce));i(o,()=>a.cancel(new Wi)),yield this._paymentIntegrationService.submitOrder(e,t),yield this._paymentIntegrationService.initializeOffsitePayment({methodId:n.methodId,gatewayId:n.gatewayId,shouldSaveInstrument:!1,target:o.name,promise:a.promise})})}finalize(e){return cl(this,void 0,void 0,function*(){const t=this._paymentIntegrationService.getState(),n=t.getOrder(),i=t.getPaymentStatus();if(!n||i!==dl.ACKNOWLEDGE&&i!==dl.FINALIZE)return Promise.reject(new Cd);yield this._paymentIntegrationService.finalizeOrder(e)})}initialize(e){return cl(this,void 0,void 0,function*(){this._initializeOptions=e&&e.bluesnapv2,yield Promise.resolve()})}deinitialize(){return Promise.resolve()}_createIframe(e,t){const n=document.createElement("iframe");if(n.setAttribute("sandbox","allow-top-navigation allow-scripts allow-forms allow-same-origin"),n.name=e,t){const{border:e,height:i,width:r}=t;n.style.border=null!=e?e:"",n.style.height=null!=i?i:"",n.style.width=null!=r?r:""}return n}}const ul=vi(e=>new ll(e),[{gateway:"bluesnapv2"}]);class hl{constructor(e){this.storage=e}saveExtraItemsData(e,t){const n=[...t.physicalItems,...t.digitalItems].reduce((e,t)=>(e[t.productId]={brand:t.brand?t.brand:"",category:t.categoryNames?t.categoryNames.join(", "):""},e),{});try{return this.storage.setItem(this.getStorageKey(e),JSON.stringify(n)),n}catch(e){return{}}}readExtraItemsData(e){try{const t=this.storage.getItem(this.getStorageKey(e));if(!t)return null;const n=JSON.parse(t);return function(e){if(!Z(e))return!1;const t=Object.values(e).some(e=>!Z(e)||!("brand"in e)||!("category"in e));return Boolean(!t)}(n)?n:null}catch(e){return null}}clearExtraItemData(e){try{this.storage.removeItem(this.getStorageKey(e))}catch(e){}}getStorageKey(e){return e?`ORDER_ITEMS_${e}`:""}}function pl(e){return Boolean(e.hasOwnProperty("analytics"))}function ml(e){return"object"==typeof e&&null!==e&&"shouldCreateAccount"in e}class yl extends Qn{constructor(e){super(),this.errorCode=e,this.name="BoltPaymentsFieldError",this.type="bolt_payments_field_error",this.body={errors:[yl.getError(e)]}}static getError(e){switch(e){case"1000":case"2000":case"3000":return{code:"invalid_number"};case"1001":case"2001":case"3001":return{code:"invalid_expiry_date"};case"1002":case"2002":return{code:"invalid_cvc"};case"1003":return{code:"invalid_zip"};case"2003":return{code:"incorrect_zip"};default:return{code:"general_error"}}}}var gl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vl{constructor(e,t,n){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.analyticsExtraItemsManager=n,this.useBoltClient=!1,this.useBoltEmbedded=!1}initialize(e){return gl(this,void 0,void 0,function*(){const{bolt:t,methodId:n}=e,{containerId:i,onPaymentSelect:r,useBigCommerceCheckout:o}=t||{};if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)return void(this.boltClient=yield this.boltScriptLoader.loadBoltClient());const a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{initializationData:s,config:d}=a,{publishableKey:c,developerConfig:l,embeddedOneClickEnabled:u}=s||{},{testMode:h}=d;if(!c)throw new ti(Xn.MissingPaymentMethod);if(this.boltClient=yield this.boltScriptLoader.loadBoltClient(c,h,l),this.useBoltClient=!u,this.useBoltEmbedded=!!u,this.useBoltEmbedded){if(!i)throw new fi('Unable to initialize payment because "options.bolt.containerId" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.bolt.onPaymentSelect" argument is not provided.');this.boltEmbedded=yield this.boltScriptLoader.loadBoltEmbedded(c,h,l),this.mountBoltEmbeddedField(i),r(yield this.hasBoltAccount())}})}deinitialize(){var e;return null===(e=this.embeddedField)||void 0===e||e.unmount(),this.boltClient=void 0,this.boltEmbedded=void 0,Promise.resolve()}finalize(){return Promise.reject(new Cd)}execute(e,t){return gl(this,void 0,void 0,function*(){this.setExtraItemsForAnalytics();const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const n={success:(n,i)=>{n.reference?e(n):t(new Qr("Unable to proceed because transaction reference is unavailable. Please try again later.")),i()},close:()=>{t(new Wi)}};s.configure({orderToken:r},{},n).open()});return{methodId:e,paymentData:{nonce:d.reference,shouldSaveInstrument:a}}})}getBoltEmbeddedPaymentPayload(e,t){var n;return gl(this,void 0,void 0,function*(){if(!ml(t))throw new ti(Xn.MissingPayment);const i=this.validateTokenizeResultOrThrow(yield null===(n=this.embeddedField)||void 0===n?void 0:n.tokenize());return{methodId:e,paymentData:{formattedPayload:{credit_card_token:{token:i.token,last_four_digits:i.last4,iin:i.bin,expiration_month:+i.expiration.split("-")[1],expiration_year:+i.expiration.split("-")[0]},provider_data:{create_account:!!t.shouldCreateAccount,embedded_checkout:!0}}}}})}getBoltFullCheckoutPaymentPayload(e,t){return gl(this,void 0,void 0,function*(){yield this.setBoltOrderId();const n=this.getBoltClientOrThrow(),i=yield n.getTransactionReference();if(!i)throw new Xr;return{methodId:e,paymentData:Object.assign(Object.assign({},t),{nonce:i})}})}getBoltClientOrThrow(){if(!this.boltClient)throw new ri(ei.PaymentNotInitialized);return this.boltClient}getBoltEmbeddedOrThrow(){if(!this.boltEmbedded)throw new ri(ei.PaymentNotInitialized);return this.boltEmbedded}hasBoltAccount(){return gl(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCustomer(),n=e.getBillingAddress(),i=(null==t?void 0:t.email)||(null==n?void 0:n.email)||"",r=this.getBoltClientOrThrow();try{return yield r.hasBoltAccount(i)}catch(e){throw new Xr}})}setBoltOrderId(){return gl(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getOrderOrThrow(),t=this.getBoltClientOrThrow();try{yield t.setOrderId(e.orderId)}catch(e){throw new Xr}})}mountBoltEmbeddedField(e){const t=this.getBoltEmbeddedOrThrow().create("payment_field",{styles:{backgroundColor:"#fff"},renderSeparateFields:!0});t.mount(`#${e}`),this.embeddedField=t}validateTokenizeResultOrThrow(e){if(!e)throw new Xr;if(e instanceof Error)throw new yl(e.message);const{token:t,last4:n,bin:i,expiration:r}=e,o=+n,a=+i,s=+`${r}`.split("-")[1],d=+`${r}`.split("-")[0];if(!t||Number.isNaN(o)||Number.isNaN(a)||Number.isNaN(s)||Number.isNaN(d))throw new co;return e}setExtraItemsForAnalytics(){const e=this.paymentIntegrationService.getState(),t=e.getStoreConfigOrThrow(),n=e.getCartOrThrow();if(t.checkoutSettings.isAnalyticsEnabled&&pl(window)){const{id:e,lineItems:t}=n;this.analyticsExtraItemsManager.saveExtraItemsData(e,t)}}}const fl=vi(e=>new vl(e,new ao(a()),new hl(Te)),[{id:"bolt"}]);function Sl(e){return!!e&&"accountNumber"in e&&"routingNumber"in e&&"ownershipType"in e&&"accountType"in e}var _l=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class wl{constructor(e,t){this.paymentIntegrationService=e,this.braintreeSdk=t}initialize(e){return _l(this,void 0,void 0,function*(){const{methodId:t,braintreeach:n}=e||{};if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');this.getMandateText=null==n?void 0:n.getMandateText,yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{clientToken:r,initializationData:o}=i;if(!r||!o)throw new ti(Xn.MissingPaymentMethod);this.braintreeSdk.initialize(r);try{this.usBankAccount=yield this.braintreeSdk.getUsBankAccount()}catch(e){this.handleBraintreeError(e)}})}execute(e,t){return _l(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew wl(e,(e=>{const t=new Ei(e),n=new Hi(a(),window,t);return new Ui(n)})(e)),[{id:"braintreeach"}]);class Cl{constructor(e){this.paymentIntegrationService=e,this.braintreeHostWindow=window}render(e,t,n){const i=t&&document.getElementById(t);if(this.braintreeHostWindow.paypal&&i){const r=this.paymentIntegrationService.getState(),o=r.getCartOrThrow(),a=r.getBillingAddressOrThrow(),s=r.getPaymentMethodOrThrow(e);if(!s.initializationData)return;const{paypalBNPLConfiguration:d=[]}=s.initializationData,c=n===fo.PAYMENT?"checkout":n,l=d&&d.find(({id:e})=>e===c);if(!l||!l.status)return;n===fo.CART&&(i.removeAttribute("data-pp-style-logo-type"),i.removeAttribute("data-pp-style-logo-position"),i.removeAttribute("data-pp-style-text-color"),i.removeAttribute("data-pp-style-text-size")),this.braintreeHostWindow.paypal.Messages({amount:o.cartAmount,buyerCountry:a.countryCode,placement:n,style:this.getPaypalMessagesStylesFromBNPLConfig(l)}).render(`#${t}`)}}getPaypalMessagesStylesFromBNPLConfig({styles:e}){const t={};return e.color&&(t.color=e.color),e.layout&&(t.layout=e.layout),(e["logo-type"]||e["logo-position"])&&(t.logo={},e["logo-type"]&&(t.logo.type=e["logo-type"]),e["logo-position"]&&(t.logo.position=e["logo-position"])),e.ratio&&(t.ratio=e.ratio),(e["text-color"]||e["text-size"])&&(t.text={},e["text-color"]&&(t.text.color=e["text-color"]),e["text-size"]&&(t.text.size=+e["text-size"])),t}}class bl{constructor(e){const{element:t,closeElement:n,mainElement:i}=this._createElements(e);this._element=t,this._closeElement=n,this._mainElement=i}show(e){this._mainElement.parentElement||(this._registerClick(e),document.body.appendChild(this._mainElement),setTimeout(()=>this._element.style.opacity="1"))}remove(){this._mainElement.parentElement&&(this._unregisterClick&&this._unregisterClick(),this._removeAfterTransition(),setTimeout(()=>this._element.style.opacity="0"))}_createElements(e){const t=document.createElement("div"),{background:n="rgba(0, 0, 0, 0.8)",id:i="checkoutOverlay",transitionDuration:r=400,hasCloseButton:o=!1,innerHtml:a=null}=e||{};let s,d,c,l,u=t;if(i&&(t.id=i),a){const e=document.createElement("div");l=`${i}--overlayText`,e.className=l,e.appendChild(a),t.appendChild(e)}return o&&(c=`${i}--close`,s=document.createElement("div"),s.className=c,d=`${i}--layout`,u=document.createElement("div"),u.className=d,u.appendChild(t),u.appendChild(s)),u.appendChild(function(e){const{id:t,background:n,transitionDuration:i,classLayout:r,classOverlayText:o,classClose:a}=e,s=document.createElement("style"),d=r?`, .${r}`:"";return s.id=`${t}--styles`,s.type="text/css",s.innerText=`\n #${t}${d} {\n display: block;\n height: 100%;\n width: 100%;\n left: 0;\n top: 0;\n position: fixed;\n z-index: 2147483647;\n }\n #${t} {\n transition: opacity ${i}ms ease-out;\n background: ${n};\n opacity: 0;\n }\n `,o&&(s.innerText+=`\n #${t} {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n #${t} .${o} {\n color: white;\n max-width: 330px;\n font-size: 1.2em;\n text-align: center;\n }\n `),a&&(s.innerText+=`\n #${t} {\n opacity: 1;\n }\n .${r} .${a} {\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 .${r} .${a}::after, .${r} .${a}::before {\n position: absolute;\n left: 8px;\n content: '';\n height: 16px;\n width: 2px;\n background-color: #fff;\n }\n .${r} .${a}::after {\n transform: rotate(-45deg);\n }\n .${r} .${a}::before {\n transform: rotate(45deg);\n }\n `),s}({id:i,background:n,transitionDuration:r,classLayout:d,classOverlayText:l,classClose:c})),{element:t,closeElement:s,mainElement:u}}_addEventListener(e,t){e&&t&&e.addEventListener("click",t)}_removeEventListener(e,t){e&&t&&e.removeEventListener("click",t)}_registerClick(e){if(this._unregisterClick&&this._unregisterClick(),e){const{onClick:t,onClickClose:n}=e;this._addEventListener(this._element,t),this._addEventListener(this._closeElement,n),this._unregisterClick=()=>{this._removeEventListener(this._element,t),this._removeEventListener(this._closeElement,n),this._unregisterClick=void 0}}}_removeAfterTransition(){const e=t=>{"opacity"===t.propertyName&&(this._mainElement.parentElement&&this._mainElement.remove(),this._element.removeEventListener("transitionend",e))};this._element.addEventListener("transitionend",e)}}const Pl={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"};function Ol(e){return"object"==typeof e&&null!==e&&"name"in e&&"BraintreeError"===e.name}function El(e){return{recipientName:`${e.firstName} ${e.lastName}`,line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,postalCode:e.postalCode,countryCode:e.countryCode,phone:e.phone}}var Al=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Tl{constructor(e,t,n,i){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeMessages=n,this.loadingIndicator=i,this.braintreeHostWindow=window}initialize(e){return Al(this,void 0,void 0,function*(){const{braintree:t,methodId:n}=e;if((null==t?void 0:t.containerId)&&(this.braintreeButtonOptions=t),this.paymentMethod&&this.paymentMethod.nonce||(this.paymentMethod=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n)),this.paymentMethod.clientToken&&(null==t?void 0:t.bannerContainerId))return yield this.loadPaypal(),this.loadPaypalCheckoutInstance(t);if(this.paymentMethod.clientToken)return this.loadPaypal();const i=yield this.paymentIntegrationService.loadPaymentMethod(n);if(this.paymentMethod=i.getPaymentMethodOrThrow(n),null==t?void 0:t.bannerContainerId)return this.loadPaypalCheckoutInstance(t);if(!this.paymentMethod.clientToken)throw new ti(Xn.MissingPaymentMethod);return this.loadPaypal()})}execute(e,t){var n;return Al(this,void 0,void 0,function*(){const{payment:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{o&&"function"==typeof o&&o(new Error("INSTRUMENT_DECLINED")),t()})),this.handleError(e)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.braintreeTokenizePayload=void 0,null===(e=this.paypalButtonRender)||void 0===e||e.close(),this.braintreeIntegrationService.teardown()}preparePaymentData(e,t){var n;return Al(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),r=i.getOutstandingBalance(t),o=i.getStoreConfig();if(!r)throw new ti(Xn.MissingCheckout);if(!o)throw new ti(Xn.MissingCheckoutConfig);if(!this.paymentMethod)throw new ri(ei.PaymentNotInitialized);const{currency:a,storeProfile:{storeLanguage:s}}=o,{nonce:d,config:{isVaultingEnabled:c}}=this.paymentMethod,{methodId:l,paymentData:u={}}=e,h=(null===(n=this.braintreeTokenizePayload)||void 0===n?void 0:n.nonce)||d;if(h){const t=yield this.paymentIntegrationService.loadPaymentMethod(l);return this.paymentMethod=t.getPaymentMethod(l),Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(h)})}if(xd(u)||(p=u,Boolean(p.instrumentId)&&!Object.prototype.hasOwnProperty.call(p,"ccNumber")&&!Object.prototype.hasOwnProperty.call(p,"ccCvv"))){if(!c)throw new fi("Vaulting is disabled but a vaulted instrument was being used for this transaction");return Promise.resolve(e)}var p;if(!jd(u))throw new ti(Xn.MissingPayment);const{shouldSaveInstrument:m,shouldSetAsDefaultInstrument:y}=u;if(m&&!c)throw new fi("Vaulting is disabled but shouldSaveInstrument is set to true");const g=i.getShippingAddress(),v=g?El(g):void 0;return Promise.all([this.braintreeIntegrationService.paypal({amount:r,locale:s,currency:a.code,offerCredit:"braintreepaypalcredit"===this.paymentMethod.id,shippingAddressOverride:v,shouldSaveInstrument:m||!1,shippingAddressEditable:!1}),this.braintreeIntegrationService.getSessionId()]).then(([{nonce:t,details:n}={},i])=>Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(t,n&&n.email,i,m,y)}))})}formattedPayload(e,t,n,i,r){return{formattedPayload:{vault_payment_instrument:i||null,set_as_default_stored_instrument:r||null,device_info:n||null,paypal_account:{token:e,email:t||null}}}}loadPaypalCheckoutInstance(e){return Al(this,void 0,void 0,function*(){const{clientToken:t,initializationData:n,id:i}=this.paymentMethod||{};if(!t)throw new ti(Xn.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(t);const r={currency:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,intent:null==n?void 0:n.intent,isCreditEnabled:null==n?void 0:n.isCreditEnabled},o="braintreepaypalcredit"===i||!(null==n?void 0:n.isCreditEnabled);yield this.braintreeIntegrationService.getPaypalCheckout(r,t=>{o&&i&&(null==e?void 0:e.bannerContainerId)&&this.renderPayPalMessages(i,e.bannerContainerId),this.renderPayPalButton(t,e)},this.handleError)}catch(e){this.handleError(e)}})}renderPayPalMessages(e,t){this.braintreeMessages.render(e,t,fo.PAYMENT)}renderPayPalButton(e,t){const{onPaymentError:n,submitForm:i,onRenderButton:r,containerId:o,onError:a}=t||{};if(!o)return;const s=this.getSmartButtonContainerId(o);if(!document.getElementById(s))throw new fi(`Unable to initialize payment because element with id ${o} does not exist.`);if(!this.paymentMethod)throw new ri(ei.PaymentNotInitialized);this.loadingIndicatorContainer=o.split("#")[1];const{id:d,config:{testMode:c}}=this.paymentMethod,{paypal:l}=this.braintreeHostWindow,u=null==l?void 0:l.FUNDING.PAYPAL;l&&u?(this.paypalButtonRender=l.Buttons({env:c?"sandbox":"production",commit:!1,fundingSource:u,onClick:()=>{this.toggleLoadingIndicator(!0)},createOrder:()=>this.setupPayment(e,d,n),onApprove:t=>Al(this,void 0,void 0,function*(){this.braintreeTokenizePayload=yield this.tokenizePaymentOrThrow(t,e),i&&"function"==typeof i&&i()}),onCancel:()=>{this.toggleLoadingIndicator(!1)},onError:e=>{this.toggleLoadingIndicator(!1),null==a||a(e)}}),r&&"function"==typeof r&&r(),this.paypalButtonRender.isEligible()&&this.paypalButtonRender.render(`${o}`)):this.removeElement(o.split("#")[1])}setupPayment(e,t,n){return Al(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState();try{const n=i.getCustomer(),r=i.getPaymentMethodOrThrow(t),o=i.getCheckoutOrThrow().outstandingBalance,a=i.getStoreConfigOrThrow().currency.code,s=i.getShippingAddress()||(null==n?void 0:n.addresses[0]),d=s?El(s):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:d,amount:o,currency:a,offerCredit:!1,intent:r.initializationData.intent})}catch(e){throw n&&(Ol(e)||e instanceof Qn)&&n(e),e}})}tokenizePaymentOrThrow(e,t,n){return Al(this,void 0,void 0,function*(){try{return yield t.tokenizePayment(e)}catch(e){throw n&&(Ol(e)||e instanceof Qn)&&n(e),e}})}loadPaypal(){return Al(this,void 0,void 0,function*(){const{clientToken:e,initializationData:t}=this.paymentMethod||{};if(!e||!t)throw new ti(Xn.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(e),yield this.braintreeIntegrationService.getPaypal()}catch(e){this.handleError(e)}return Promise.resolve()})}handleError(e){if(!Ol(e))throw e;if("PAYPAL_POPUP_CLOSED"===e.code)throw new Wi(e.message);throw new Qr(e.message)}isProviderError(e){var t,n,i;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"2046"===(null===(i=null===(n=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===n?void 0:n.provider_error)||void 0===i?void 0:i.code)}removeElement(e){const t=e&&document.getElementById(e);t&&t.remove()}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}getSmartButtonContainerId(e){var t;return null!==(t=e.split("#")[1])&&void 0!==t?t:e}}const kl=vi(e=>{const t=window,n=new bl,i=new Ei(e),r=new _o(new Hi(a(),t,i),t,n),o=new Cl(e);return new Tl(e,r,o,new vd({containerStyles:Pl}))},[{id:"braintreepaypal"},{id:"braintreepaypalcredit"}]);class Dl{constructor(e){this.requestSender=e}getOrderStatus(e="braintreelocalmethods",t){return n=this,i=void 0,o=function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}var Ml=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class zl{constructor(e,t,n,i,r=3e3,o=3e5){this.paymentIntegrationService=e,this.braintreeSdk=t,this.braintreeRequestSender=n,this.loadingIndicator=i,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.isLPMsUpdateExperimentEnabled=!1,this.pollingTimer=0,this.stopPolling=ce,this.isPollingEnabled=!1}initialize(e){return Ml(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,braintreelocalmethods:i}=e;if(this.gatewayId=t,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.braintreelocalmethods" argument is not provided.');this.braintreelocalmethods=i,this.loadingIndicatorContainer=i.container.split("#")[1],yield this.paymentIntegrationService.loadPaymentMethod(t);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(t),{clientToken:a,config:s,initializationData:d}=o,c=r.getStoreConfigOrThrow().checkoutSettings.features;if(this.isPollingEnabled=Ci(c,"PAYPAL-5258.braintree_local_methods_polling"),this.isLPMsUpdateExperimentEnabled=Ci(c,"PAYPAL-4853.add_new_payment_flow_for_braintree_lpms"),!a||!d||!s.merchantId)throw new ti(Xn.MissingPaymentMethod);try{this.braintreeSdk.initialize(a),this.isNonInstantPaymentMethod(n)||(this.braintreeLocalPayment=yield this.braintreeSdk.getBraintreeLocalPayment(s.merchantId))}catch(e){this.handleError(e)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return Ml(this,void 0,void 0,function*(){return this.toggleLoadingIndicator(!1),Promise.resolve()})}execute(e,t){return Ml(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{window.location.replace(t),this.toggleLoadingIndicator(!1),n()})}return this.handleError(e),Promise.reject(e)}})}executeWithInstantLPM(e,t,n){return Ml(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment)throw new Xr;yield new Promise((i,r)=>{var o;null===(o=this.braintreeLocalPayment)||void 0===o||o.startPayment(this.getInstantLPMConfig(e,t,n),this.getInstantLPMCallback(i,r,e,t,n))})})}getLPMsBasicPaymentData(){return Ml(this,void 0,void 0,function*(){const{deviceData:e}=yield this.braintreeSdk.getDataCollectorOrThrow();return{deviceSessionId:e}})}getInstantLPMConfig(e,t,n){const i=this.paymentIntegrationService.getState(),r=i.getCartOrThrow(),o=i.getBillingAddressOrThrow(),{firstName:a,lastName:s,countryCode:d}=o,{currency:c,email:l,lineItems:u}=r,h=u.physicalItems.length>0,p=i.getCheckoutOrThrow().outstandingBalance,m=i.getStoreConfigOrThrow().links.checkoutLink;return{paymentType:e,amount:p,fallback:{url:m,buttonText:"Complete Payment"},currencyCode:c.code,shippingAddressRequired:h,email:l,givenName:a,surname:s,address:{countryCode:d},onPaymentStart:(i,r)=>Ml(this,void 0,void 0,function*(){if(!this.isLPMsUpdateExperimentEnabled)return this.orderId=i.paymentId,void r();const o=yield this.getLPMsBasicPaymentData(),a=Object.assign(Object.assign({},o),{formattedPayload:{method:e,[`${e}_account`]:{order_id:i.paymentId}}});try{yield this.paymentIntegrationService.submitOrder(t,n),yield this.paymentIntegrationService.submitPayment({methodId:e,paymentData:a})}catch(t){if(this.isBraintreeOrderSavedResponse(t)&&t.body.additional_action_required.data.order_id_saved_successfully)return r(),this.isPollingEnabled?new Promise((t,n)=>{this.initializePollingMechanism(e,t,n,this.gatewayId)}):void 0;throw t}})}}getInstantLPMCallback(e,t,n,i,r){const o=this.paymentIntegrationService.getState().getCartOrThrow();return(a,s)=>Ml(this,void 0,void 0,function*(){if(a)return"LOCAL_PAYMENT_WINDOW_CLOSED"===a.code?(this.toggleLoadingIndicator(!1),this.resetPollingMechanism(),t()):(this.isPollingEnabled&&this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t(new Xr));const d=yield this.getLPMsBasicPaymentData(),c=Object.assign(Object.assign({},d),{formattedPayload:{method:n,[`${n}_account`]:Object.assign({email:o.email,token:s.nonce},this.isLPMsUpdateExperimentEnabled?{}:{order_id:this.orderId})}});try{return this.isLPMsUpdateExperimentEnabled||(yield this.paymentIntegrationService.submitOrder(i,r)),yield this.paymentIntegrationService.submitPayment({methodId:n,paymentData:c}),e(void 0)}catch(e){return this.handleError(e),t(e)}})}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}handleError(e){const{onError:t}=this.braintreelocalmethods||{};this.isPollingEnabled&&this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}isNonInstantPaymentMethod(e){return e.toUpperCase()in Di}isBraintreeRedirectError(e){var t;if("object"!=typeof e||null===e)return!1;const{body:n}=e;return!!n&&!!(null===(t=n.additional_action_required)||void 0===t?void 0:t.data.redirect_url)}isBraintreeOrderSavedResponse(e){var t;if("object"!=typeof e||null===e)return!1;const{body:n}=e;return!!n&&(null===(t=n.additional_action_required)||void 0===t?void 0:t.data.hasOwnProperty("order_id_saved_successfully"))}initializePollingMechanism(e,t,n,i){return Ml(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.braintreeRequestSender.getOrderStatus(i,{params:{useMetadata:!1}}),o=r.status===ki.Pending,a=r.status===ki.Completed,s=r.status===ki.Failed;if(a)return this.deinitializePollingMechanism(),t();if(s)return n();if(!a&&o&&this.pollingTimer{const t=window,i=new Ei(e),r=new Ui(new Hi(a(),t,i)),o=n(),s=new Dl(o);return new zl(e,r,s,new vd({styles:{backgroundColor:"black"}}))},[{gateway:"braintreelocalmethods"}]);function xl(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var Rl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Fl{constructor(e,t,n){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.braintreeSdk=n}initialize(e){var t;return Rl(this,void 0,void 0,function*(){const{methodId:n,braintreefastlane:i}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.braintreefastlane" argument is not provided.');if(!i.onInit||"function"!=typeof i.onInit)throw new fi('Unable to initialize payment because "options.braintreefastlane.onInit" argument is not provided or it is not a function.');if(!i.onChange||"function"!=typeof i.onChange)throw new fi('Unable to initialize payment because "options.braintreefastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(n);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(n),{initializationData:a,clientToken:s}=o||{},{isFastlaneStylingEnabled:d}=a||{},c=Ci(r.getStoreConfigOrThrow().checkoutSettings.features,"PROJECT-7080.braintree_fastlane_three_ds");this.is3DSEnabled=o.config.is3dsEnabled,s&&c&&this.braintreeSdk.initialize(s);const l=Ao(d?null===(t=o.initializationData)||void 0===t?void 0:t.fastlaneStyles:void 0,i.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(n,l),this.shouldRunAuthenticationFlow()&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow()),yield this.initializeCardComponent(),this.onError=i.onError,i.onInit(e=>this.renderBraintreeCardComponent(e)),i.onChange(()=>this.handleBraintreeStoredInstrumentChange(n))})}execute(e,t){return Rl(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{i.verifyCard({amount:null==r?void 0:r.orderAmount,nonce:e,bin:t,onLookupComplete:(e,t)=>{i.on("customer-canceled",()=>{"function"==typeof this.onError&&this.onError(new Wi),o(new Wi)}),t()}},(e,t)=>(e&&"THREEDS_VERIFY_CARD_CANCELED_BY_MERCHANT"===e.code&&("function"==typeof this.onError&&this.onError(new Wi),o(new Wi)),n(t.nonce)))})})}mapToPayPalAddress(e){return{streetAddress:(null==e?void 0:e.address1)||"",locality:(null==e?void 0:e.city)||"",region:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCodeAlpha2:(null==e?void 0:e.countryCode)||""}}shouldRunAuthenticationFlow(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getCustomerOrThrow(),i=e.getPaymentProviderCustomer(),r=xl(i)?i:{},o=this.braintreeFastlaneUtils.getSessionIdFromCookies();return!(!n.isGuest||(null==r?void 0:r.authenticationState)===Mi.CANCELED||(null==r?void 0:r.authenticationState)||o!==t.id)}getBraintreeCardComponentOrThrow(){if(!this.braintreeCardComponent)throw new mi;return this.braintreeCardComponent}getPayPalInstruments(){const e=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow();return(xl(e)?e:{}).instruments||[]}handleBraintreeStoredInstrumentChange(e){return Rl(this,void 0,void 0,function*(){const t=this.braintreeFastlaneUtils.getBraintreeFastlaneOrThrow(),{selectionChanged:n,selectedCard:i}=yield t.profile.showCardSelector();if(n){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),n=xl(t)?t:{},r=this.braintreeFastlaneUtils.mapPayPalToBcInstrument(e,[i]);if(r&&r.length>0)return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},n),{instruments:[...r]})),r[0]}})}}const Ll=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t),r=new Mo(e,i),o=new Hi(a(),t,n),s=new Ui(o);return new Fl(e,r,s)},[{id:"braintreeacceleratedcheckout"}]);var Bl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class jl{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n}initialize(e){return Bl(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:n}=e;if(!t)throw new fi('Unable to initialize payment because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState();this.paymentMethod=i.getPaymentMethodOrThrow(n);const r=i.getCheckoutOrThrow(),o=i.getStoreConfigOrThrow(),{clientToken:a,config:s}=this.paymentMethod||{};if(!a)throw new ti(Xn.MissingPaymentMethod);const{onError:d=ce,onPaymentSelect:c=ce}=t;this.braintreeSdk.initialize(a);const l=yield this.braintreeSdk.getBraintreeVisaCheckout(),u=yield this.braintreeSdk.getVisaCheckoutSdk(null==s?void 0:s.testMode),h=l.createInitOptions({settings:{locale:o.storeProfile.storeLanguage,shipping:{collectShipping:!1}},paymentRequest:{currencyCode:o.currency.code,subtotal:String(r.subtotal)}});yield u.init(h),u.on("payment.success",e=>this.tokenizePayment(l,e).then(()=>Promise.all([this.paymentIntegrationService.loadCheckout(),this.paymentIntegrationService.loadPaymentMethod(n)])).then(()=>c()).catch(e=>d(e))),u.on("payment.error",(e,t)=>d(t))})}execute(e,t){var n,i;return Bl(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const n=this.paymentIntegrationService.getState(),i=n.getShippingAddress(),r=n.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(i),billingAddress:a=this.mapToVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}mapToVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}postForm(e,t){const{userData:n,billingAddress:i,shippingAddress:r,details:o}=e,{userEmail:a}=n,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,i)),shipping_address:JSON.stringify(this.getAddress(a,r))})}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}handleError(e){if(e instanceof Error&&"BraintreeError"===e.name)throw new Qr(e.message);throw e}}const Ul=vi(e=>{const t=window,n=new Ei(e),i=new Ui(new Hi(a(),t,n));return new jl(e,Ee(),i)},[{id:"braintreevisacheckout"}]);var ql=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vl{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}initialize(e){return ql(this,void 0,void 0,function*(){const{methodId:t}=e;yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState();this.venmoOptions=e.braintreevenmo;const i=n.getPaymentMethodOrThrow(t);yield this.initializeBraintreeVenmo(i)})}execute(e){return ql(this,void 0,void 0,function*(){const{payment:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{var n;null===(n=this.braintreeVenmoCheckout)||void 0===n||n.tokenize((n,i)=>{if(n)return t(n);e(i)})})}}const Gl=vi(e=>{const t=window,n=a(),i=new Ei(e),r=new Hi(n,t,i),o=new _o(r,t);return new Vl(e,o)},[{id:"braintreevenmo"}]);var Hl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Wl{constructor(e,t,n){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeHostedForm=n}initialize(e){return Hl(this,void 0,void 0,function*(){const{methodId:t,gatewayId:n,braintree:i}=e;yield this.paymentIntegrationService.loadPaymentMethod(t);const r=this.paymentIntegrationService.getState();this.paymentMethod=r.getPaymentMethodOrThrow(t);const{clientToken:o}=this.paymentMethod;if(!o)throw new ti(Xn.MissingPaymentMethod);this.threeDSecure=null==i?void 0:i.threeDSecure,this.onPaymentError=null==i?void 0:i.onPaymentError;try{this.braintreeIntegrationService.initialize(o,this.threeDSecure),this.isHostedPaymentFormEnabled(t,n)&&(null==i?void 0:i.form)&&(yield this.braintreeHostedForm.initialize(i.form,i.unsupportedCardBrands,o),this.isHostedFormInitialized=this.braintreeHostedForm.isInitialized()),this.is3dsEnabled=this.paymentMethod.config.is3dsEnabled,this.deviceSessionId=yield this.braintreeIntegrationService.getSessionId(),this.shouldInitializeBraintreeFastlane()&&(yield this.initializeBraintreeFastlaneOrThrow(t))}catch(e){return this.handleError(e,t)}})}execute(e){return Hl(this,void 0,void 0,function*(){const{payment:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r"string"==typeof e));var n}var Kl,Jl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e[e.CreditCard=0]="CreditCard",e[e.StoredCardVerification=1]="StoredCardVerification"}(Kl||(Kl={}));class Zl{constructor(e,t){this.braintreeScriptLoader=e,this.braintreeSDKVersionManager=t,this.isInitializedHostedForm=!1,this.handleBlur=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onBlur)||void 0===n||n.call(t,{fieldType:this.mapFieldType(e.emittedBy),errors:this.mapErrors(e.fields)})},this.handleFocus=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onFocus)||void 0===n||n.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleCardTypeChange=e=>{var t,n;const i=1===e.cards.length?e.cards[0].type.replace(/^master-card$/,"mastercard"):void 0;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onCardTypeChange)||void 0===n||n.call(t,{cardType:i})},this.handleInputSubmitRequest=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onEnter)||void 0===n||n.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleValidityChange=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===n||n.call(t,{isValid:this.isValidForm(e),errors:this.mapValidationErrors(e.fields)})}}initialize(e,t,n){var i,r,o,a,s;return Jl(this,void 0,void 0,function*(){this.clientToken=n,this.formOptions=e,this.type=$l(e.fields)?Kl.CreditCard:Kl.StoredCardVerification;const d=this.mapFieldOptions(e.fields,t);$(d)?this.isInitializedHostedForm=!1:(this.cardFields=yield this.createHostedFields({fields:d,styles:e.styles&&this.mapStyleOptions(e.styles)}),null===(i=this.cardFields)||void 0===i||i.on("blur",this.handleBlur),null===(r=this.cardFields)||void 0===r||r.on("focus",this.handleFocus),null===(o=this.cardFields)||void 0===o||o.on("cardTypeChange",this.handleCardTypeChange),null===(a=this.cardFields)||void 0===a||a.on("validityChange",this.handleValidityChange),null===(s=this.cardFields)||void 0===s||s.on("inputSubmitRequest",this.handleInputSubmitRequest),this.isInitializedHostedForm=!0)})}isInitialized(){return!!this.isInitializedHostedForm}deinitialize(){var e;return Jl(this,void 0,void 0,function*(){this.isInitializedHostedForm&&(this.isInitializedHostedForm=!1,yield null===(e=this.cardFields)||void 0===e?void 0:e.teardown())})}validate(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);const e=this.cardFields.getState();if(!this.isValidForm(e)){this.handleValidityChange(e);const t=this.mapValidationErrors(e.fields);throw new lo(t)}}tokenize(e){var t,n,i,r,o;return Jl(this,void 0,void 0,function*(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);try{const r=yield this.cardFields.tokenize(ue({billingAddress:e&&this.mapBillingAddress(e)},J));return null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===n||n.call(t,{isValid:!0,errors:{}}),{nonce:r.nonce,bin:null===(i=r.details)||void 0===i?void 0:i.bin}}catch(e){if(Yl(e)){const t=this.mapTokenizeError(e);if(t)throw null===(o=null===(r=this.formOptions)||void 0===r?void 0:r.onValidate)||void 0===o||o.call(r,{isValid:!1,errors:t}),new lo(t)}throw e}})}tokenizeForStoredCardVerification(){var e,t,n,i,r;return Jl(this,void 0,void 0,function*(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);try{const i=yield this.cardFields.tokenize();return null===(t=null===(e=this.formOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,{isValid:!0,errors:{}}),{nonce:i.nonce,bin:null===(n=i.details)||void 0===n?void 0:n.bin}}catch(e){if(Yl(e)){const t=this.mapTokenizeError(e,!0);if(t)throw null===(r=null===(i=this.formOptions)||void 0===i?void 0:i.onValidate)||void 0===r||r.call(i,{isValid:!1,errors:t}),new lo(t)}throw e}})}createHostedFields(e){return Jl(this,void 0,void 0,function*(){const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadHostedFields(),i=this.braintreeSDKVersionManager.getSDKVersion()===bi?Object.assign(Object.assign({},e),{preventCursorJumps:!0}):e;return n.create(Object.assign(Object.assign({},i),{client:t}))})}getClient(){return Jl(this,void 0,void 0,function*(){if(!this.clientToken)throw new ri(ei.PaymentNotInitialized);if(!this.client){const e=yield this.braintreeScriptLoader.loadClient();this.client=e.create({authorization:this.clientToken})}return this.client})}mapBillingAddress(e){return{countryName:e.country,postalCode:e.postalCode,streetAddress:e.address2?`${e.address1} ${e.address2}`:e.address1}}mapFieldOptions(e,t){if($l(e)){const n={};return null==t||t.forEach(e=>{(e=>Object.values(xi).includes(e))(e)&&(n[e]=!1)}),ue({number:Object.assign({container:`#${e.cardNumber.containerId}`,placeholder:e.cardNumber.placeholder,internalLabel:e.cardNumber.accessibilityLabel},Object.keys(n).length>0?{supportedCardBrands:n}:{}),expirationDate:{container:`#${e.cardExpiry.containerId}`,placeholder:e.cardExpiry.placeholder,internalLabel:e.cardExpiry.accessibilityLabel},cvv:e.cardCode&&{container:`#${e.cardCode.containerId}`,placeholder:e.cardCode.placeholder,internalLabel:e.cardCode.accessibilityLabel},cardholderName:{container:`#${e.cardName.containerId}`,placeholder:e.cardName.placeholder,internalLabel:e.cardName.accessibilityLabel}},J)}return ue({number:e.cardNumberVerification&&{container:`#${e.cardNumberVerification.containerId}`,placeholder:e.cardNumberVerification.placeholder},cvv:e.cardCodeVerification&&{container:`#${e.cardCodeVerification.containerId}`,placeholder:e.cardCodeVerification.placeholder}},J)}mapStyleOptions(e){const t=(e={})=>ue({color:e.color,"font-family":e.fontFamily,"font-size":e.fontSize,"font-weight":e.fontWeight},J);return{input:t(e.default),".invalid":t(e.error),":focus":t(e.focus)}}mapFieldType(e){switch(e){case"number":return this.type===Kl.StoredCardVerification?Bi.CardNumberVerification:Bi.CardNumber;case"expirationDate":return Bi.CardExpiry;case"cvv":return this.type===Kl.StoredCardVerification?Bi.CardCodeVerification:Bi.CardCode;case"cardholderName":return Bi.CardName;default:throw new Error("Unexpected field type")}}mapErrors(e){const t={};if(e)for(const[n,i]of Object.entries(e))if(i&&this.isValidParam(n)){const{isValid:e,isEmpty:r,isPotentiallyValid:o}=i;t[n]={isValid:e,isEmpty:r,isPotentiallyValid:o}}return t}mapValidationErrors(e){return Object.keys(e).reduce((t,n)=>{var i;return Object.assign(Object.assign({},t),{[this.mapFieldType(n)]:(null===(i=e[n])||void 0===i?void 0:i.isValid)?void 0:[this.createInvalidError(this.mapFieldType(n))]})},{})}mapTokenizeError(e,t=!1){var n,i;if("HOSTED_FIELDS_FIELDS_EMPTY"===e.code){const e=[this.createRequiredError(this.mapFieldType("cvv"))];return t?{[this.mapFieldType("cvv")]:e}:{[this.mapFieldType("cvv")]:e,[this.mapFieldType("expirationDate")]:[this.createRequiredError(this.mapFieldType("expirationDate"))],[this.mapFieldType("number")]:[this.createRequiredError(this.mapFieldType("number"))],[this.mapFieldType("cardholderName")]:[this.createRequiredError(this.mapFieldType("cardholderName"))]}}return null===(i=null===(n=e.details)||void 0===n?void 0:n.invalidFieldKeys)||void 0===i?void 0:i.reduce((e,t)=>{const n=this.mapFieldType(t);return Object.assign(Object.assign({},e),{[n]:[this.createInvalidError(n)]})},{})}createRequiredError(e){var t;return{fieldType:e,message:null!==(t={[Bi.CardCode]:"CVV is required",[Bi.CardCodeVerification]:"CVV is required",[Bi.CardNumber]:"Credit card number is required",[Bi.CardNumberVerification]:"Credit card number is required",[Bi.CardExpiry]:"Expiration date is required",[Bi.CardName]:"Full name is required"}[e])&&void 0!==t?t:"Field is required",type:"required"}}createInvalidError(e){var t,n,i,r;const o={[Bi.CardCode]:{message:"Invalid card code",type:"invalid_card_code"},[Bi.CardCodeVerification]:{message:"Invalid card code",type:"invalid_card_code"},[Bi.CardNumber]:{message:"Invalid card number",type:"invalid_card_number"},[Bi.CardNumberVerification]:{message:"Invalid card number",type:"invalid_card_number"},[Bi.CardExpiry]:{message:"Invalid card expiry",type:"invalid_card_expiry"},[Bi.CardName]:{message:"Invalid card name",type:"invalid_card_name"}};return{fieldType:e,message:null!==(n=null===(t=o[e])||void 0===t?void 0:t.message)&&void 0!==n?n:"Invalid field",type:null!==(r=null===(i=o[e])||void 0===i?void 0:i.type)&&void 0!==r?r:"invalid"}}isValidForm(e){return Object.keys(e.fields).every(t=>{var n;return null===(n=e.fields[t])||void 0===n?void 0:n.isValid})}isValidParam(e){return["number","cvv","expirationDate","postalCode","cardholderName","cardType"].includes(e)}}const Ql=vi(e=>{const t=window,n=new Ei(e),i=new Hi(a(),t,n),r=new _o(i,t),o=new Zl(i,n);return new Wl(e,r,o)},[{id:"braintree"}]);var Xl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})},eu=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r(this._shouldRenderHostedForm=!0,this._hostedForm=r,Promise.resolve()))}deinitialize(){return this._hostedForm&&this._hostedForm.detach(),Promise.resolve()}finalize(){return Promise.reject(new Cd)}_executeWithoutHostedForm(e,t){return Xl(this,void 0,void 0,function*(){const{payment:n}=e,i=eu(e,["payment"]),r=n&&n.paymentData;if(!n||!r)throw new co(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(i,t),yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:r}))})}_executeWithHostedForm(e,t){return Xl(this,void 0,void 0,function*(){const{payment:n}=e,i=eu(e,["payment"]),r=this._hostedForm;if(!r)throw new ri(ei.PaymentNotInitialized);if(!n||!n.methodId)throw new co(["payment.methodId"]);yield this._paymentIntegrationService.submitOrder(i,t),yield r.validate().then(()=>r.submit(n))})}_isHostedPaymentFormEnabled(e,t){return!!e&&!0===this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t).config.isHostedFormEnabled}_isHostedFieldAvailable(e){return!Ce(e&&e.creditCard&&e.creditCard.form.fields).every(J)}}var nu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class iu extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this.cbaMGPSScriptLoader=t,this.sessionId=""}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return nu(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{methodId:n}=e;yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(n);if(!function(e){return"object"==typeof e&&null!==e&&"initializationData"in e&&"object"==typeof e.initializationData&&null!==e.initializationData&&"merchantId"in e.initializationData&&"string"==typeof e.initializationData.merchantId&&("boolean"==typeof e.initializationData.isTestModeFlagEnabled||void 0===e.initializationData.isTestModeFlagEnabled)}(r))throw new ti(Xn.MissingPaymentMethod);const{clientToken:o,initializationData:{isTestModeFlagEnabled:a=!1,merchantId:s},config:{is3dsEnabled:d}}=r;if(d){if(this.threeDSjs=yield this.cbaMGPSScriptLoader.load(a),!this.threeDSjs)throw new ri(ei.PaymentNotInitialized);if(!o||!s)throw new ti(Xn.MissingPaymentMethod);if(this.sessionId=o,this.locale=i.getLocale(),!this.locale)throw new ti(Xn.MissingCart);yield this.threeDSjs.configure({merchantId:s,sessionId:this.sessionId,callback:()=>{var e;if(null===(e=this.threeDSjs)||void 0===e?void 0:e.isConfigured())return this.paymentIntegrationService.getState();throw new Qr("Failed to configure 3DS API.")},configuration:{userLanguage:this.locale,wsVersion:62}})}return Promise.resolve()})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return nu(this,void 0,void 0,function*(){const{payment:i}=e,r=i&&i.paymentData;if(!i||!r)throw new co(["payment.paymentData"]);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i.methodId),{is3dsEnabled:a}=o.config;if(a){const t=Object.assign(Object.assign({},r),{threeDSecure:{token:this.sessionId}});e.payment&&(e.payment.paymentData=t)}return n.execute.call(this,e,t).catch(e=>{if(!a||!pa(e)||!ve(e.body.errors,{code:"three_d_secure_required"}))return Promise.reject(e);const t=this.paymentIntegrationService.getState(),n=t.getOrder(),{storeProfile:{storeId:i}}=t.getStoreConfigOrThrow();if(!n||!this.sessionId)throw new ti(Xn.MissingCheckout);const r=`${i}_${n.orderId}`;if("object"!=typeof(o=e.body)||null===o||!("three_ds_result"in o)||"object"!=typeof o.three_ds_result||null===o.three_ds_result||!("token"in o.three_ds_result)||"string"!=typeof o.three_ds_result.token)throw new nr;var o;const{three_ds_result:{token:s}}=e.body;return s?this.initiateAuthentication(r,s):Promise.reject(e)})})}finalize(e){return nu(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE?(yield this.paymentIntegrationService.finalizeOrder(e),Promise.resolve()):Promise.reject(new Cd)})}deinitialize(){return this.threeDSjs=void 0,this.sessionId="",super.deinitialize()}initiateAuthentication(e,t){return nu(this,void 0,void 0,function*(){const n=yield new Promise((n,i)=>{if(!this.threeDSjs)throw new ri(ei.PaymentNotInitialized);this.threeDSjs.initiateAuthentication(e,t,e=>{const t=e.error;return t?i(new Qr(t.msg)):this.threeDSjs&&"PROCEED"===e.gatewayRecommendation?n(e.restApiResponse):i(new Qr)})});if(n.transaction&&"AUTHENTICATION_AVAILABLE"===n.transaction.authenticationStatus)return this.authenticatePayer(e,t);throw new Qr})}authenticatePayer(e,t,n=1){return nu(this,void 0,void 0,function*(){return new Promise((i,r)=>{if(!this.threeDSjs)return r(new ri(ei.PaymentNotInitialized));this.threeDSjs.authenticatePayer(e,t,i=>nu(this,void 0,void 0,function*(){const o=i.error;return o?o.cause&&"SERVER_BUSY"===o.cause&&n<5?(yield new Promise(e=>setTimeout(e,3e3)),this.authenticatePayer(e,t,++n)):r(new Qr):new Promise(ce)}),{fullScreenRedirect:!0})})})}}class ru{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e){return t=this,n=void 0,r=function*(){if(yield this._scriptLoader.loadScript(`//${e?"test":"ap"}-gateway.mastercard.com/static/threeDS/1.3.0/three-ds.min.js`),!this._window.ThreeDS)throw new mi;return this._window.ThreeDS},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const ou=vi(e=>new iu(e,new ru(a())),[{id:"cba_mpgs"}]);var au;!function(e){e.OffsiteRedirect="offsite_redirect"}(au||(au={}));class su extends tu{constructor(e){super(e),this.paymentIntegrationService=e}finalize(e){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),Promise.reject(new Cd)}_executeWithHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{window.location.replace(e.data.redirect_url)})}}class du extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew du(e),[{gateway:"checkoutcom",id:"fawry"}]);function lu(e){return pa(e)&&ve(e.body.errors,{code:"three_d_secure_required"})}var uu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})},hu=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rthis.formPoster.postForm(t,{PaReq:n||null,TermUrl:i||null,MD:r||null}))}}const mu=vi(e=>new pu(e,Ee()),[{gateway:"checkoutcom",id:"credit_card"},{gateway:"checkoutcom",id:"card"}]);class yu extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew yu(e),[{gateway:"checkoutcom",id:"sepa"}]);class vu extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew vu(e),[{gateway:"checkoutcom",id:"ideal"}]);const Su=["boleto","oxxo","qpay","ideal"];class _u extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew _u(e),[{gateway:"checkoutcom"}]);var Iu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Cu{constructor(e,t){this._paymentIntegrationService=e,this._clearpayScriptLoader=t}initialize(e){return Iu(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:t}=this._paymentIntegrationService.getState(),n=t(e.methodId,e.gatewayId),i=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features;this._clearpaySdk=yield this._clearpayScriptLoader.load(n,i)})}deinitialize(){return this._clearpaySdk=void 0,Promise.resolve()}execute(e,t){return Iu(this,void 0,void 0,function*(){const{gatewayId:n,methodId:i}=e.payment||{};if(!n||!i)throw new co(["payment.gatewayId","payment.methodId"]);const r=this._paymentIntegrationService.getState(),{isStoreCreditApplied:o}=r.getCheckoutOrThrow();yield this._paymentIntegrationService.applyStoreCredit(o),yield this._paymentIntegrationService.validateCheckout(r.getCheckout(),t);const{countryCode:a}=r.getBillingAddressOrThrow();if(!this._isCountrySupported(a))throw new fi("Unable to proceed because billing country is not supported.");return yield this._loadPaymentMethod(n,i,t),yield this._redirectToClearpay(a,this._paymentIntegrationService.getState().getPaymentMethod(i,n)),new Promise(ce)})}finalize(e){var t,n,i;return Iu(this,void 0,void 0,function*(){const r=this._paymentIntegrationService.getState(),o=r.getPaymentId(),a=r.getContextConfig();if(!o)throw new ti(Xn.MissingCheckout);if(!a||!a.payment.token)throw new ti(Xn.MissingCheckoutConfig);const s={methodId:o.providerId,paymentData:{nonce:a.payment.token}};yield this._paymentIntegrationService.submitOrder({},e);try{yield this._paymentIntegrationService.submitPayment(s)}catch(e){if(yield this._paymentIntegrationService.forgetCheckout(o.providerId),yield this._paymentIntegrationService.loadPaymentMethods(),pa(e))throw new Kd(null===(i=null===(n=null===(t=e.body)||void 0===t?void 0:t.errors)||void 0===n?void 0:n[0])||void 0===i?void 0:i.message)}})}_redirectToClearpay(e,t){return Iu(this,void 0,void 0,function*(){if(!this._clearpaySdk||!t||!t.clientToken)throw new ri(ei.PaymentNotInitialized);return this._clearpaySdk.initialize({countryCode:e}),this._clearpaySdk.redirect({token:t.clientToken}),Promise.resolve()})}_isCountrySupported(e){return"GB"===e}_loadPaymentMethod(e,t,n){var i;return Iu(this,void 0,void 0,function*(){try{return yield this._paymentIntegrationService.loadPaymentMethod(e,Object.assign(Object.assign({},n),{params:Object.assign(Object.assign({},null==n?void 0:n.params),{method:t})}))}catch(e){if(e instanceof nr&&422===(null===(i=e.body)||void 0===i?void 0:i.status))throw new fi("Clearpay can't process your payment for this order, please try another payment method");throw e}})}}class bu{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e,t={}){return n=this,i=void 0,o=function*(){if(yield this._scriptLoader.loadScript(this._getScriptUrl(e.config.testMode,t)),!this._window.AfterPay)throw new mi;return this._window.AfterPay},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_getScriptUrl(e,t={}){const n=Ci(t,"PI-4555.clearpay_add_https_to_prod_script",!1);return e?n?"https://portal.sandbox.clearpay.co.uk/afterpay-async.js":"//portal.sandbox.clearpay.co.uk/afterpay-async.js":n?"https://portal.clearpay.co.uk/afterpay-async.js":"//portal.clearpay.co.uk/afterpay-async.js"}}const Pu=vi(e=>new Cu(e,new bu(a())),[{gateway:"clearpay"},{id:"clearpay"}]),Ou=vi(e=>new tu(e),[{default:!0}]);var Eu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Au{constructor(e,t){this._paymentIntegrationService=e,this._cardinalClient=t}prepare(e){return Eu(this,void 0,void 0,function*(){yield this._cardinalClient.load(e.id,e.config.testMode),yield this._cardinalClient.configure(yield this._getClientToken(e))})}start(e,t,n,i){return Eu(this,void 0,void 0,function*(){const{getCardInstrument:r,getPaymentMethodOrThrow:o}=this._paymentIntegrationService.getState(),{payment:{methodId:a="",paymentData:s={}}={}}=t,d=xd(s)&&r(s.instrumentId),c=d?d.iin:i&&i.getBin();c&&(yield this._cardinalClient.runBinProcess(c));try{return yield e(de(t,{payment:{paymentData:{threeDSecure:{token:o(a).clientToken}}}}),n)}catch(e){if(!pa(e)||!ve(e.body.errors,{code:"three_d_secure_required"}))throw e;const n=yield this._cardinalClient.getThreeDSecureData(e.body.three_ds_result,this._getOrderData());if(!i)return void(yield this._paymentIntegrationService.submitPayment(de(t.payment,{paymentData:{threeDSecure:n}})));yield i.submit(de(t.payment,{paymentData:{threeDSecure:n}}))}})}_getClientToken(e){return Eu(this,void 0,void 0,function*(){return e.clientToken?e.clientToken:(yield this._paymentIntegrationService.loadPaymentMethod(e.id),this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.id).clientToken||"")})}_getOrderData(){const e=this._paymentIntegrationService.getState(),t=e.getBillingAddressOrThrow(),n=e.getShippingAddress(),i=e.getCheckoutOrThrow(),r=e.getOrderOrThrow();return{billingAddress:t,shippingAddress:n,currencyCode:i.cart.currency.code,id:r.orderId.toString(),amount:i.cart.cartAmount}}}const Tu=[100004,1010,1011,1020];var ku,Du,Mu,zu,Nu,xu,Ru;!function(e){e.SetupCompleted="payments.setupComplete",e.Validated="payments.validated"}(ku||(ku={})),function(e){e.Init="init",e.Complete="complete",e.Confirm="confirm"}(Du||(Du={})),function(e){e.Success="SUCCESS",e.NoAction="NOACTION",e.Failure="FAILURE",e.Error="ERROR"}(Mu||(Mu={})),function(e){e.CCA="CCA",e.Paypal="Paypal",e.Wallet="Wallet",e.VisaCheckout="VisaCheckout",e.ApplePay="ApplePay",e.DiscoverWallet="DiscoverWallet"}(zu||(zu={})),function(e){e.BinProcess="bin.process"}(Nu||(Nu={})),function(e){e.CCA="cca"}(xu||(xu={})),function(e){e.Yes="Y",e.No="N"}(Ru||(Ru={}));class Fu{constructor(e){this._scriptLoader=e,this._provider="",this._testMode=!1,this._configurationToken=""}load(e,t=!1){return this._provider=e,this._testMode=t,this._sdk||(this._sdk=this._scriptLoader.load(e,t)),this._sdk.then(ce)}configure(e){if(this._configurationToken){if(this._configurationToken===e)return Promise.resolve();this._sdk=this._scriptLoader.load(`${this._provider}.${Date.now()}`,this._testMode)}return this._getClientSDK().then(t=>new Promise((n,i)=>{t.on(ku.SetupCompleted,()=>{t.off(ku.SetupCompleted),t.off(ku.Validated),this._configurationToken=e,n()}),t.on(ku.Validated,e=>{t.off(ku.SetupCompleted),t.off(ku.Validated),e.ActionCode===Mu.Error&&(H(Tu,e.ErrorNumber)&&i(new ti(Xn.MissingPaymentMethod)),i(new Qr(e.ErrorDescription)))}),t.setup(Du.Init,{jwt:e})}))}runBinProcess(e){return this._getClientSDK().then(t=>t.trigger(Nu.BinProcess,e).catch(ce)).then(e=>{if(!e||!e.Status)throw new ri(ei.PaymentNotInitialized)})}getThreeDSecureData(e,t){return this._getClientSDK().then(n=>new Promise((i,r)=>{n.on(ku.Validated,(e,t)=>{if(n.off(ku.Validated),!t)return r(new Qr(e.ErrorDescription?e.ErrorDescription:"An error was encountered while processing the transaction."));if(!e.ActionCode)return i({token:t});switch(e.ActionCode){case Mu.Success:return i({token:t});case Mu.NoAction:return e.ErrorNumber>0?r(new Qr(e.ErrorDescription)):e.Payment&&e.Payment.ExtendedData&&e.Payment.ExtendedData.SignatureVerification===Ru.Yes?i({token:t}):r(new Qr("Transaction signature could not be validated."));case Mu.Failure:return r(new Qr("User failed authentication or an error was encountered while processing the transaction."));case Mu.Error:return r(new Qr(e.ErrorDescription))}});const o={AcsUrl:e.acs_url,Payload:e.merchant_data},a=this._mapToPartialOrder(t,e.payer_auth_request);n.continue(xu.CCA,o,a)}))}_mapToPartialOrder(e,t){const n={BillingAddress:this._mapToCardinalAddress(e.billingAddress)};return e.paymentData&&(n.Account=this._mapToCardinalAccount(e.paymentData)),e.billingAddress.email&&(n.Email1=e.billingAddress.email),e.shippingAddress&&(n.ShippingAddress=this._mapToCardinalAddress(e.shippingAddress)),{Consumer:n,OrderDetails:{OrderNumber:e.id,Amount:e.amount,CurrencyCode:e.currencyCode,OrderChannel:"S",TransactionId:t}}}_mapToCardinalAccount(e){return{AccountNumber:Number(e.ccNumber),ExpirationMonth:Number(e.ccExpiry.month),ExpirationYear:Number(e.ccExpiry.year),NameOnAccount:e.ccName,CardCode:Number(e.ccCvv)}}_mapToCardinalAddress(e){const t={FirstName:e.firstName,LastName:e.lastName,Address1:e.address1,City:e.city,State:e.stateOrProvince,PostalCode:e.postalCode,CountryCode:e.countryCode};return e.address2&&(t.Address2=e.address2),e.phone&&(t.Phone1=e.phone),t}_getClientSDK(){if(!this._sdk)throw new ri(ei.PaymentNotInitialized);return this._sdk}}class Lu{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e,t){const n=t?"https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js":"https://static.client.cardinaltrusted.com/songbird/v2.0.0/songbird.js";return this._scriptLoader.loadScript(`${n}?v=${e}`).then(()=>{if(!this._window.Cardinal)throw new mi;return this._window.Cardinal})}}var Bu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ju extends tu{constructor(e,t){super(e),this._threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Bu(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),i=n(e.methodId);i.config.is3dsEnabled&&(yield this._threeDSecureFlow.prepare(i))})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return Bu(this,void 0,void 0,function*(){const{payment:{methodId:i=""}={}}=e,{getPaymentMethodOrThrow:r}=this._paymentIntegrationService.getState();return r(i).config.is3dsEnabled?this._threeDSecureFlow.start(n.execute.bind(this),e,t,this._hostedForm):n.execute.call(this,e,t)})}}const Uu=vi(e=>new ju(e,new Au(e,new Fu(new Lu(a())))),[{id:"cybersource"}]);var qu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vu{constructor(e,t){this._paymentIntegrationService=e,this._cardinalClient=t}prepare(e){return qu(this,void 0,void 0,function*(){yield this._cardinalClient.load(e.id,e.config.testMode)})}start(e,t,n,i){var r,o,a,s;return qu(this,void 0,void 0,function*(){const{getCardInstrument:d}=this._paymentIntegrationService.getState(),{payment:c={methodId:""}}=t,{paymentData:l={}}=c;try{return yield e(t,n)}catch(e){if(pa(e)&&"additional_action_required"===(null===(r=e.body)||void 0===r?void 0:r.status)){const t=null===(a=null===(o=e.body.additional_action_required)||void 0===o?void 0:o.data)||void 0===a?void 0:a.token,n=null===(s=e.body.three_ds_result)||void 0===s?void 0:s.payer_auth_request;yield this._cardinalClient.configure(t);const r=this._getBin(l,d,i);r&&(yield this._cardinalClient.runBinProcess(r));try{return yield this._submitPayment(c,{xid:n},i)}catch(e){if(pa(e)&&ve(e.body.errors,{code:"three_d_secure_required"})){const t=e.body.three_ds_result,n=null==t?void 0:t.payer_auth_request;return yield this._cardinalClient.getThreeDSecureData(t,this._getOrderData()),this._submitPayment(c,{token:n},i)}throw e}}throw e}})}_getOrderData(){const e=this._paymentIntegrationService.getState(),t=e.getBillingAddressOrThrow(),n=e.getShippingAddress(),{cart:{currency:{code:i},cartAmount:r}}=e.getCheckoutOrThrow();return{billingAddress:t,shippingAddress:n,currencyCode:i,id:e.getOrderOrThrow().orderId.toString(),amount:r}}_submitPayment(e,t,n){return qu(this,void 0,void 0,function*(){const i=de({},e,{paymentData:{threeDSecure:t}});n||(yield this._paymentIntegrationService.submitPayment(i)),yield null==n?void 0:n.submit(i)})}_getBin(e,t,n){const i=xd(e)&&t(e.instrumentId),r=function(e){const t=e;return!xd(t)&&"string"==typeof t.ccName&&"string"==typeof t.ccNumber&&"object"==typeof t.ccExpiry&&"string"==typeof t.ccExpiry.month&&"string"==typeof t.ccExpiry.year}(e)&&e.ccNumber,o=n?n.getBin():r;return(i?i.iin:o)||""}}var Gu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Hu extends tu{constructor(e,t){super(e),this._threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Gu(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),i=n(e.methodId);i.config.is3dsEnabled&&(yield this._threeDSecureFlow.prepare(i))})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return Gu(this,void 0,void 0,function*(){const{payment:{methodId:i=""}={}}=e,{getPaymentMethodOrThrow:r}=this._paymentIntegrationService.getState();return r(i).config.is3dsEnabled?this._threeDSecureFlow.start(n.execute.bind(this),e,t,this._hostedForm):n.execute.call(this,e,t)})}}const Wu=vi(e=>new Hu(e,new Vu(e,new Fu(new Lu(a())))),[{id:"cybersourcev2"},{id:"bnz"}]);function $u(e){return"object"==typeof e&&null!==e&&"errors"in e&&Array.isArray(e.errors)&&"code"in e.errors[0]&&"string"==typeof e.errors[0].code&&"provider_data"in e&&"object"==typeof e.provider_data}var Yu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ku extends ea{constructor(e,t){super("adyen",e),this._scriptLoader=t,this._service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Yu(this,void 0,void 0,function*(){yield i.initialize.call(this,e,t,n);const r=i.getPaymentMethod.call(this),o=this._service.getState().getStoreConfig();if(!o)throw new ti(Xn.MissingCheckoutConfig);return this._adyenClient=yield this._scriptLoader.load({environment:r.config.testMode?"test":"live",locale:o.storeProfile.storeLanguage}),Promise.resolve()})}getNonce(e){const t=Object.create(null,{getNonce:{get:()=>super.getNonce},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Yu(this,void 0,void 0,function*(){const n=yield t.getNonce.call(this,e),i=t.getPaymentMethod.call(this);return JSON.stringify({type:i.method,googlePayToken:n,browser_info:ss()})})}processAdditionalAction(e){return Yu(this,void 0,void 0,function*(){if(!pa(e)||!$u(e.body))throw e;const t=yield this._handleAction(e.body.provider_data);try{return yield this._service.submitPayment(t)}catch(e){return this.processAdditionalAction(e)}})}_handleAction(e){return new Promise((t,n)=>{const i=JSON.parse(e.action);this._getAdyenClient().createFromAction(i,{onAdditionalDetails:e=>{const n={methodId:i.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};t(n)},size:"05",onError:e=>n(e)}).mount("body"),n(new Wi)})}_getAdyenClient(){if(!this._adyenClient)throw new ri(ei.PaymentNotInitialized);return this._adyenClient}}var Ju=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Zu{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t,this._isDeinitializationBlocked=!1,this._loadingIndicator=new vd({containerStyles:yd})}initialize(e){var t,n;return Ju(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId)||!na(e.methodId))throw new fi('Unable to proceed because "methodId" is not a valid key.');this._methodId=e.methodId;const i=e[this._getMethodId()];if(!(null==i?void 0:i.walletButton))throw new fi("Unable to proceed without valid options.");const{walletButton:r,loadingContainerId:o}=i,a=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rs,this._getGooglePayClientOptions(null===(n=s.initializationData)||void 0===n?void 0:n.storeCountry)),this._addPaymentButton(r,a)})}execute({payment:e}){return Ju(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new co(["payment"]);yield this._paymentIntegrationService.submitOrder();const t=yield this._googlePayPaymentProcessor.getNonce(e.methodId),n=yield this._googlePayPaymentProcessor.extraPaymentData();try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:Object.assign({nonce:t},n)}))}catch(t){yield this._googlePayPaymentProcessor.processAdditionalAction(t,e.methodId)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this._isDeinitializationBlocked||(this._clickListener&&(null===(e=this._paymentButton)||void 0===e||e.removeEventListener("click",this._clickListener)),this._paymentButton=void 0,this._clickListener=void 0,this._methodId=void 0),Promise.resolve()}_addPaymentButton(e,t){if(this._paymentButton)return;const n=document.getElementById(e);if(!n)throw new fi("Unable to proceed without a walletButton.");this._paymentButton=n,this._clickListener=this._handleClick(t),this._paymentButton.addEventListener("click",this._clickListener)}_handleClick({onPaymentSelect:e,onError:t}){return n=>Ju(this,void 0,void 0,function*(){n.preventDefault();try{this._googlePayPaymentProcessor.setShouldRequestShipping(!1),yield this._googlePayPaymentProcessor.initializeWidget(),this._isDirectPayOnClickEnabled()?yield this._interactWithPaymentSheetAndPay():yield this._interactWithPaymentSheet()}catch(e){let n=e;if(this._toggleLoadingIndicator(!1),ta(e)){if("CANCELED"===e.statusCode)throw new Wi;n=new Qr(JSON.stringify(e))}throw null==t||t(new Qr("An error occurred while requesting your Google Pay payment details.")),n}finally{this._toggleBlockDeinitialization(!1)}null==e||e()})}_interactWithPaymentSheetAndPay(){return Ju(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet();this._toggleBlockDeinitialization(!0),this._toggleLoadingIndicator(!0);const t=this._getMethodId(),n=this._paymentIntegrationService.getState(),{features:i}=n.getStoreConfigOrThrow().checkoutSettings,r=Ci(i,"PI-5031.google_pay_dont_override_address"),o=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e);o&&!r&&(yield this._paymentIntegrationService.updateBillingAddress(o)),yield this._googlePayPaymentProcessor.setExternalCheckoutXhr(t,e),yield this._paymentIntegrationService.loadCheckout(),yield this._paymentIntegrationService.loadPaymentMethod(t);const a=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(t);yield this._googlePayPaymentProcessor.initialize(()=>a),yield this.execute({useStoreCredit:!1,payment:{methodId:t}}),this._completeCheckoutFlow()})}_completeCheckoutFlow(){window.location.replace("/checkout/order-confirmation"),this._toggleLoadingIndicator(!1),this._toggleBlockDeinitialization(!1)}_interactWithPaymentSheet(){return Ju(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet(),t=this._paymentIntegrationService.getState(),{features:n}=t.getStoreConfigOrThrow().checkoutSettings,i=Ci(n,"PI-5031.google_pay_dont_override_address");this._toggleBlockDeinitialization(!0),this._toggleLoadingIndicator(!0);const r=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e);r&&!i&&(yield this._paymentIntegrationService.updateBillingAddress(r)),yield this._googlePayPaymentProcessor.setExternalCheckoutXhr(this._getMethodId(),e),yield this._paymentIntegrationService.loadCheckout(),yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodId()),this._toggleLoadingIndicator(!1),this._toggleBlockDeinitialization(!1)})}_getMethodId(){return ii(this._methodId,()=>new ri(ei.PaymentNotInitialized))}_getIsSignedInOrThrow(){return Ju(this,void 0,void 0,function*(){try{return!!(yield this._googlePayPaymentProcessor.getNonce(this._getMethodId()))}catch(e){if(e instanceof ti&&e.subtype===Xn.MissingPaymentToken)return!1;throw e}})}_handleOfferTrigger(e){return Ju(this,void 0,void 0,function*(){let t=!1,n="Sign in to Google Pay first to apply or remove promo codes.";try{t=yield this._getIsSignedInOrThrow()}catch(e){e instanceof ti&&(n=e.message)}if(t){const{newOfferInfo:t,error:n}=yield this._googlePayPaymentProcessor.handleCoupons(e);return{newOfferInfo:t,error:n}}return{error:{reason:Ko.OFFER_INVALID,message:n,intent:Jo.OFFER}}})}_getGooglePayClientOptions(e){return this._googlePayPaymentProcessor.isWebViewWithRestrictions()?{}:{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:t,offerData:n})=>Ju(this,void 0,void 0,function*(){if(t!==Jo.INITIALIZE&&t!==Jo.OFFER)return;const{offerChangeTriggers:i}=this._googlePayPaymentProcessor.getCallbackTriggers(),{newOfferInfo:r,error:o}=i.includes(t)?yield this._handleOfferTrigger(n):{},a=o;yield this._paymentIntegrationService.loadCheckout();const{code:s}=this._paymentIntegrationService.getState().getCartOrThrow().currency,d=this._googlePayPaymentProcessor.getTotalPrice();return Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},e&&{countryCode:e}),{currencyCode:s,totalPriceStatus:Wo.FINAL,totalPrice:d})},r&&{newOfferInfo:r}),a&&{error:a})})}}}_isDirectPayOnClickEnabled(){const{features:e}=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings;return Ci(e,"PI-5111.google_pay_direct_pay_on_click")}_toggleBlockDeinitialization(e){this._isDeinitializationBlocked=e}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this._loadingIndicator.show(this._loadingIndicatorContainer):this._loadingIndicator.hide()}}const Qu=vi(e=>new Zu(e,new aa(da(),new Ku(e,new zd(a(),s())),n(),Ee())),[{id:"googlepayadyenv2"}]);var Xu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class eh extends ea{constructor(e,t){super("adyen",e),this._scriptLoader=t,this._service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Xu(this,void 0,void 0,function*(){yield i.initialize.call(this,e,t,n);const r=i.getPaymentMethod.call(this),o=this._service.getState().getStoreConfig();if(!o)throw new ti(Xn.MissingCheckoutConfig);return this._adyenClient=yield this._scriptLoader.load({environment:r.config.testMode?"test":"live",locale:o.storeProfile.storeLanguage}),Promise.resolve()})}processAdditionalAction(e){return Xu(this,void 0,void 0,function*(){if(!pa(e)||!$u(e.body))throw e;const t=yield this._handleAction(e.body.provider_data);try{return yield this._service.submitPayment(t)}catch(e){return this.processAdditionalAction(e)}})}getNonce(e){const t=Object.create(null,{getNonce:{get:()=>super.getNonce},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Xu(this,void 0,void 0,function*(){const n=yield t.getNonce.call(this,e),i=t.getPaymentMethod.call(this);return JSON.stringify({type:i.method,googlePayToken:n,browser_info:ss()})})}_handleAction(e){return new Promise((t,n)=>{const i=JSON.parse(e.action);this._getAdyenClient().createFromAction(i,{onAdditionalDetails:e=>{const n={methodId:i.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};t(n)},size:"05",onError:e=>n(e)}).mount("body"),n(new Wi)})}_getAdyenClient(){if(!this._adyenClient)throw new ri(ei.PaymentNotInitialized);return this._adyenClient}}const th=vi(e=>new Zu(e,new aa(da(),new eh(e,new Bd(a(),s())),n(),Ee())),[{id:"googlepayadyenv3"}]),nh=vi(e=>new Zu(e,new aa(da(),new ua(e),n(),Ee())),[{id:"googlepayauthorizenet"}]),ih=vi(e=>{const t=n();return new Zu(e,new aa(da(),new ga(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]),rh=vi(e=>new Zu(e,new aa(da(),new fa(e),n(),Ee())),[{id:"googlepaycybersourcev2"},{id:"googlepaybnz"}]),oh=vi(e=>new Zu(e,new aa(da(),new wa(e),n(),Ee())),[{id:"googlepayorbital"}]),ah=vi(e=>new Zu(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeupe"},{id:"googlepaystripeocs"}]),sh=vi(e=>new Zu(e,new aa(da(),new Ga(e),n(),Ee())),[{id:"googlepayworldpayaccess"}]),dh=vi(e=>{const t=n(),i=window,r=new Ei(e),o=new Ui(new Hi(a(),i,r));return new Zu(e,new aa(da(),new $a(e,o),t,Ee()))},[{id:"googlepaybraintree"}]);var ch,lh;!function(e){e.Approved="APPROVED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(ch||(ch={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(lh||(lh={}));var uh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class hh extends Zu{constructor(e,t,n,i){super(e,t),this._payPalCommerceSdk=n,this._requestSender=i}execute({payment:e}){return uh(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new co(["payment"]);const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow().id,{initializationData:i}=t.getPaymentMethodOrThrow(this._getMethodId()),{orderId:r}=yield this.getOrderId(n),{card_information:o}=i||{},a=yield this._googlePayPaymentProcessor.getNonce(e.methodId),s={tokenizationData:{type:"PAYMENT_GATEWAY",token:atob(a)},info:{cardNetwork:(null==o?void 0:o.type)||"",cardDetails:(null==o?void 0:o.number)||""},type:"CARD"};yield this.confirmOrder(r,s),yield this._paymentIntegrationService.submitOrder();try{const t={formattedPayload:{method_id:e.methodId,paypal_account:{order_id:r}}};yield this._paymentIntegrationService.submitPayment({methodId:e.methodId,paymentData:t})}catch(e){yield this._googlePayPaymentProcessor.processAdditionalAction(e)}})}confirmOrder(e,t){return uh(this,void 0,void 0,function*(){const n=this._paymentIntegrationService.getState(),i=n.getPaymentMethodOrThrow(this._getMethodId());if(!i.initializationData)throw new ti(Xn.MissingPaymentMethod);const r=n.getCartOrThrow().currency.code,o=yield this._payPalCommerceSdk.getPayPalGooglePaySdk(i,r,n.getLocale(),!0),{status:a}=yield o.Googlepay().confirmOrder({orderId:e,paymentMethodData:t});if(a===ch.PayerActionRequired)return yield o.Googlepay().initiatePayerAction({orderId:e}),Promise.resolve();if(a!==ch.Approved)throw new fi("Payment is not approved.");return Promise.resolve()})}getOrderId(e){return uh(this,void 0,void 0,function*(){const t={cartId:e,shouldSaveInstrument:!1},{body:n}=yield this._requestSender.post("/api/storefront/payments/googlepaypaypalcommercecheckout",{headers:Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr),body:t});return n})}}const ph=vi(e=>{const t=new Xa(a());return new hh(e,new aa(da(),new ns(e,t),n(),Ee()),t,n())},[{id:"googlepaypaypalcommerce"}]);var mh,yh;!function(e){e.Approved="APPROVED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(mh||(mh={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(yh||(yh={}));var gh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vh extends Zu{constructor(e,t,n,i){super(e,t),this._payPalSdkHelper=n,this._requestSender=i}execute({payment:e}){return gh(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new co(["payment"]);const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow().id,{initializationData:i}=t.getPaymentMethodOrThrow(this._getMethodId()),{orderId:r}=yield this.getOrderId(n),{card_information:o}=i||{},a=yield this._googlePayPaymentProcessor.getNonce(e.methodId),s={tokenizationData:{type:"PAYMENT_GATEWAY",token:atob(a)},info:{cardNetwork:(null==o?void 0:o.type)||"",cardDetails:(null==o?void 0:o.number)||""},type:"CARD"};yield this.confirmOrder(r,s),yield this._paymentIntegrationService.submitOrder();try{const t={formattedPayload:{method_id:e.methodId,paypal_account:{order_id:r}}};yield this._paymentIntegrationService.submitPayment({methodId:e.methodId,paymentData:t})}catch(e){yield this._googlePayPaymentProcessor.processAdditionalAction(e)}})}confirmOrder(e,t){return gh(this,void 0,void 0,function*(){const n=this._paymentIntegrationService.getState(),i=n.getPaymentMethodOrThrow(this._getMethodId());if(!i.initializationData)throw new ti(Xn.MissingPaymentMethod);const r=n.getCartOrThrow().currency.code,o=yield this._payPalSdkHelper.getPayPalGooglePaySdk(i,r,!0),{status:a}=yield o.Googlepay().confirmOrder({orderId:e,paymentMethodData:t});if(a===mh.PayerActionRequired)return yield o.Googlepay().initiatePayerAction({orderId:e}),Promise.resolve();if(a!==mh.Approved)throw new fi("Payment is not approved.");return Promise.resolve()})}getOrderId(e){return gh(this,void 0,void 0,function*(){const t={cartId:e,shouldSaveInstrument:!1},{body:n}=yield this._requestSender.post("/api/storefront/payments/googlepay_bigcommerce_paymentscheckout",{headers:Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr),body:t});return n})}}const fh=vi(e=>{const t=new xr(a());return new vh(e,new aa(da(),new os(e,t),n(),Ee()),t,n())},[{id:"googlepay_bigcommerce_payments"}]),Sh=vi(e=>new Zu(e,new aa(da(),new cs(e,Ee()),n(),Ee())),[{id:"googlepaytdonlinemart"}]);class _h extends Qn{constructor(e,t,n){super(n||"Payment cannot be processed for this order, please select another payment method"),this.type="custom_provider_execute_error",this.name=t,this.subtype=e}}class wh{constructor(e,t){this.paymentIntegrationService=e,this.formPoster=t}execute(e,t){var n,i,r,o,a;return i=this,r=void 0,a=function*(){const{payment:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.formPoster.postForm(t,JSON.parse(n),e)})}isOffsiteRedirectResponse(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!t.body)return!1;const n=t.body;return"additional_action_required"===n.status&&!!n.additional_action_required&&"offsite_redirect"===n.additional_action_required.type&&"string"==typeof n.provider_data}}const Ih=vi(e=>new wh(e,Ee()),[{id:"humm"}]),Ch=["AT","BE","CA","CH","CZ","DE","DK","ES","FI","FR","GB","GR","IE","IT","NL","NO","NZ","PL","PT","SE"],bh=["AU"];var Ph=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Oh{constructor(e,t){this.paymentIntegrationService=e,this.klarnaScriptLoader=t}initialize(e){return Ph(this,void 0,void 0,function*(){this.klarnaCredit=yield this.klarnaScriptLoader.load(),this.unsubscribe=this.paymentIntegrationService.subscribe(t=>{t.isPaymentMethodInitialized({methodId:e.methodId,gatewayId:e.gatewayId})&&this.loadWidget(e)},e=>{const t=e.getCheckout();return t&&t.outstandingBalance},e=>{const t=e.getCheckout();return t&&t.coupons}),yield this.loadWidget(e)})}deinitialize(){return this.unsubscribe&&this.unsubscribe(),Promise.resolve()}execute(e,t){return Ph(this,void 0,void 0,function*(){if(!e.payment)throw new fi('Unable to proceed because "payload.payment" argument is not provided.');const n=e.payment,{paymentData:i}=n,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const r=this.paymentIntegrationService.getState().getPaymentMethod(t);if(!r)throw new ti(Xn.MissingPaymentMethod);if(!this.klarnaCredit||!r.clientToken)throw new ri(ei.PaymentNotInitialized);this.klarnaCredit.init({client_token:r.clientToken}),this.klarnaCredit.load({container:n},t=>{i&&i(t),e(t)})})})}getUpdateSessionData(e,t){if(!H([...Ch,...bh],e.countryCode))return{};const n={billing_address:this.mapToKlarnaAddress(e,e.email)};return t&&(n.shipping_address=this.mapToKlarnaAddress(t,e.email)),n}needsStateCode(e){return H(bh,e)}mapToKlarnaAddress(e,t){const n={street_address:e.address1,city:e.city,country:e.countryCode,given_name:e.firstName,family_name:e.lastName,postal_code:e.postalCode,region:this.needsStateCode(e.countryCode)?e.stateOrProvinceCode:e.stateOrProvince,email:t};return e.address2&&(n.street_address2=e.address2),e.phone&&(n.phone=e.phone),n}authorize(){return new Promise((e,t)=>{const n=this.paymentIntegrationService.getState(),i=n.getBillingAddress(),r=n.getShippingAddress();if(!i)throw new ti(Xn.MissingBillingAddress);if(!this.klarnaCredit)throw new ri(ei.PaymentNotInitialized);const o=this.getUpdateSessionData(i,r);this.klarnaCredit.authorize(o,n=>n.approved?e(n):n.show_form?t(new Wi):void t(new Xr))})}}class Eh{constructor(e,t=window){this.scriptLoader=e,this.klarnaWindow=t}load(){var e,t,n,i,r,o;return n=this,i=void 0,o=function*(){if((null===(e=this.klarnaWindow.Klarna)||void 0===e?void 0:e.Credit)||(yield this.scriptLoader.loadScript("//credit.klarnacdn.net/lib/v1/api.js")),!(null===(t=this.klarnaWindow.Klarna)||void 0===t?void 0:t.Credit))throw new mi;return this.klarnaWindow.Klarna.Credit},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}}const Ah=vi(e=>new Oh(e,new Eh(a())),[{id:"klarna"}]);var Th=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class kh{constructor(e,t,n){this.paymentIntegrationService=e,this.klarnav2ScriptLoader=t,this.klarnav2TokenUpdater=n}initialize(e){return Th(this,void 0,void 0,function*(){this.klarnaPayments=yield this.klarnav2ScriptLoader.load(),this.unsubscribe=this.paymentIntegrationService.subscribe(t=>{t.isPaymentMethodInitialized({methodId:e.methodId,gatewayId:e.gatewayId})&&this.loadPaymentsWidget(e)},e=>{const t=e.getCheckout();return t&&t.outstandingBalance},e=>{const t=e.getCheckout();return t&&t.coupons}),yield this.loadPaymentsWidget(e)})}deinitialize(){return this.unsubscribe&&this.unsubscribe(),Promise.resolve()}execute(e,t){return Th(this,void 0,void 0,function*(){if(!e.payment)throw new fi('Unable to proceed because "payload.payment" argument is not provided.');const n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{throw new ti(Xn.MissingPaymentMethod)}),new Promise(e=>{const a=o.getPaymentMethodOrThrow(t),{klarnaMultipleRadioButton:s}=a.initializationData||{};if(!this.klarnaPayments||!a.clientToken)throw new ri(ei.PaymentNotInitialized);this.klarnaPayments.init({client_token:a.clientToken}),this.klarnaPayments.load({container:i,payment_method_category:this.isKlarnaMultipleRadioButtonEnabled(s,n,t)},t=>{r&&r(t),e(t)})})})}getUpdateSessionData(e,t,n){if(!H([...Ch,...bh],t.countryCode))return{};const i={billing_address:this.mapToKlarnaAddress(e,t,t.email)};return n&&(i.shipping_address=this.mapToKlarnaAddress(e,n,t.email)),i}needsStateCode(e){return H(bh,e)}isKlarnaMultipleRadioButtonEnabled(e,t,n){return e?n:t}mapToKlarnaAddress(e,t,n){const i=this.paymentIntegrationService.getState(),{checkoutSettings:r}=i.getStoreConfigOrThrow(),o=i.getPaymentMethodOrThrow(e),{enableBillie:a}=o.initializationData||{},s={street_address:t.address1,city:t.city,country:t.countryCode,given_name:t.firstName,family_name:t.lastName,postal_code:t.postalCode,region:this.needsStateCode(t.countryCode)?t.stateOrProvinceCode:t.stateOrProvince,email:n};return t.address2&&(s.street_address2=t.address2),t.phone&&(s.phone=t.phone),t.company&&a&&Ci(r.features,"PI-3915.b2b_payment_session_for_klarna")&&(s.organization_name=t.company),s}authorizeOrThrow(e,t){return Th(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const n=this.paymentIntegrationService.getState(),i=n.getBillingAddressOrThrow(),r=n.getShippingAddress(),o=this.getUpdateSessionData(t,i,r);return new Promise((t,n)=>{if(!this.klarnaPayments)return n(new ri(ei.PaymentNotInitialized));this.klarnaPayments.authorize({payment_method_category:e},o,e=>e.approved?t(e):e.show_form?n(new Wi):void n(new Xr))})})}}class Dh{constructor(e,t=window){this.scriptLoader=e,this.klarnaWindow=t}load(){var e,t,n,i,r,o;return n=this,i=void 0,o=function*(){if((null===(e=this.klarnaWindow.Klarna)||void 0===e?void 0:e.Payments)||(yield this.scriptLoader.loadScript("https://x.klarnacdn.net/kp/lib/v1/api.js")),!(null===(t=this.klarnaWindow.Klarna)||void 0===t?void 0:t.Payments))throw new mi;return this.klarnaWindow.Klarna.Payments},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}}class Mh{constructor(e){this.requestSender=e}updateClientToken(e,{timeout:t,params:n}={}){const i=`/api/storefront/payments/${e}`;return this.requestSender.get(i,{timeout:t,headers:Object.assign({Accept:mr.JsonV1,"X-API-INTERNAL":hr},yr),params:n})}klarnaOrderInitialization(e,t){return n=this,i=void 0,o=function*(){const n={headers:Object.assign({Accept:mr.JsonV1,"X-API-INTERNAL":hr},yr),body:{cartId:e,clientToken:t}};yield this.requestSender.put("/api/storefront/initialization/klarna",n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const zh=vi(e=>{const{getHost:t}=e.getState(),i=n({host:t()});return new kh(e,new Dh(a()),new Mh(i))},[{gateway:"klarna"}]);class Nh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return n=this,i=void 0,o=function*(){return yield this._paymentIntegrationService.submitOrder(e,t),Promise.resolve()},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const xh=vi(e=>new Nh(e),[{id:"testgateway"}]);var Rh,Fh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.CREDIT_CARD="credit_card"}(Rh||(Rh={}));const Lh=["klarnapaylater","klarnasliceit"];class Bh{constructor(e,t){this.mollieScriptLoader=e,this.paymentIntegrationService=t}initialize(e){return Fh(this,void 0,void 0,function*(){const{mollie:t,methodId:n,gatewayId:i}=e;if(!t)throw new fi('Unable to initialize payment because "options.mollie" argument is not provided.');if(!n||!i)throw new fi('Unable to initialize payment because "methodId" and/or "gatewayId" argument is not provided.');const r=document.querySelectorAll(".mollie-components-controller");F(r,e=>e.remove());const o=this.paymentIntegrationService.getState(),a=o.getStoreConfigOrThrow();this.initializeOptions=t;const s=o.getPaymentMethodOrThrow(n,i),{config:{merchantId:d,testMode:c}}=s;if(this.locale=o.getLocale(),!d)throw new ti(Xn.MissingPaymentMethod);return this.isCreditCard(n)&&t.form&&this.shouldShowTSVHostedForm(n,i)?this.hostedForm=yield this.mountCardVerificationfields(t.form):this.isCreditCard(n)&&(this.mollieClient=yield this.loadMollieJs(d,a.storeProfile.storeLanguage,c),this.mountElements()),this.unsubscribe=()=>{if(this.paymentIntegrationService.getState().isPaymentMethodInitialized({methodId:e.methodId,gatewayId:e.gatewayId})){const e=document.getElementById(`${i}-${n}-paragraph`);e&&e.remove(),t.disableButton(!1),this.loadPaymentMethodsAllowed(t,n,i)}},this.unsubscribe(),this.loadPaymentMethodsAllowed(t,n,i),Promise.resolve()})}execute(e,t){return Fh(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rFh(this,void 0,void 0,function*(){try{const n=this.paymentIntegrationService.getState().getStoreConfig(),i=null==n?void 0:n.paymentSettings.bigpayBaseUrl;if(!i)throw new ti(Xn.MissingCheckoutConfig);const r=this.paymentIntegrationService.createHostedForm(i,e);yield r.attach(),t(r)}catch(e){n(e)}}))}isHostedPaymentFormEnabled(e,t){const{getPaymentMethodOrThrow:n}=this.paymentIntegrationService.getState();return!0===n(e,t).config.isHostedFormEnabled}isHostedFieldAvailable(){var e;return!!(null===(e=this.getInitializeOptions().form)||void 0===e?void 0:e.fields)}processAdditionalAction(e){if(!pa(e))return Promise.reject(e);if(ve(e.body.errors,{code:"additional_action_required"})){const{additional_action_required:{data:{redirect_url:t}}}=e.body;return new Promise(()=>window.location.replace(t))}return Promise.reject(e)}getInitializeOptions(){if(!this.initializeOptions)throw new ri(ei.PaymentNotInitialized);return this.initializeOptions}loadMollieJs(e,t,n=!1){return this.mollieClient?Promise.resolve(this.mollieClient):this.mollieScriptLoader.load(e,t,n)}getMollieClient(){if(!this.mollieClient)throw new ri(ei.PaymentNotInitialized);return this.mollieClient}getShopperLocale(){if(!this.locale)throw new ri(ei.PaymentNotInitialized);return this.locale}mountElements(){const{containerId:e,cardNumberId:t,cardCvcId:n,cardExpiryId:i,cardHolderId:r,styles:o}=this.getInitializeOptions();let a;e&&(a=document.getElementById(e)),setTimeout(()=>{if(!e||"none"!==(null==a?void 0:a.style.display)){const e=this.getMollieClient();this.cardHolderElement=e.createComponent("cardHolder",{styles:o}),this.cardHolderElement.mount(`#${r}`),this.cardNumberElement=e.createComponent("cardNumber",{styles:o}),this.cardNumberElement.mount(`#${t}`),this.verificationCodeElement=e.createComponent("verificationCode",{styles:o}),this.verificationCodeElement.mount(`#${n}`),this.expiryDateElement=e.createComponent("expiryDate",{styles:o}),this.expiryDateElement.mount(`#${i}`)}},0)}loadPaymentMethodsAllowed(e,t,n){var i;if(Lh.includes(t)){const r=null===(i=this.paymentIntegrationService.getState().getCartOrThrow().lineItems)||void 0===i?void 0:i.digitalItems;if(r&&r.length>0){const{containerId:i}=this.getInitializeOptions();if(i){const r=document.getElementById(i);if(r){const i=document.createElement("p");i.setAttribute("id",`${n}-${t}-paragraph`),e.unsupportedMethodMessage&&(i.innerText=e.unsupportedMethodMessage,r.appendChild(i),e.disableButton(!0))}}}}}}class jh{constructor(e,t=window){this.scriptLoader=e,this.mollieHostWindow=t}load(e,t,n){return i=this,r=void 0,a=function*(){if(yield this.scriptLoader.loadScript("https://js.mollie.com/v1/mollie.js"),!function(e){return"Mollie"in e}(this.mollieHostWindow))throw new mi;return this.mollieHostWindow.Mollie(e,{locale:t,testmode:n})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a}}const Uh=vi(e=>new Bh(new jh(a()),e),[{gateway:"mollie"},{gateway:"mollie",id:"applepay"}]);var qh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const Vh="moneris-payment-iframe";class Gh{constructor(e){this.paymentIntegrationService=e}initialize(e){return qh(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),{moneris:n,methodId:i}=e;if(!i)throw new fi('Unable to initialize payment because "methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.moneris" argument is not provided.');this.initializeOptions=n;const{config:r,initializationData:o}=t.getPaymentMethodOrThrow(i);if(!(null==o?void 0:o.profileId))throw new ti(Xn.MissingPaymentMethod);return n.form&&this.shouldShowTSVHostedForm(i)&&(this.hostedForm=yield this.mountCardVerificationfields(n.form)),this.iframe||(this.iframe=this.createIframe(n.containerId,o,!!r.testMode)),Promise.resolve()})}execute(e,t){return qh(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(!this.iframe)throw new ri(ei.PaymentNotInitialized);const i=this.iframe.contentWindow;if(null===i)throw new ri(ei.PaymentNotInitialized);i.postMessage("tokenize",this.monerisURL(!!t)),this.windowEventListener=i=>{if("string"==typeof i.data&&i.origin===`https://${t?"esqa":"www3"}.moneris.com`)try{e(this.handleMonerisResponse(i))}catch(e){n(e)}},window.addEventListener("message",this.windowEventListener)});void 0!==a&&(yield this.paymentIntegrationService.submitPayment({methodId:e.methodId,paymentData:{nonce:a,shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o}}))})}executeWithVaulted(e){return qh(this,void 0,void 0,function*(){if(this.hostedForm){const t=this.hostedForm;return yield t.validate(),yield t.submit(e),this.paymentIntegrationService.loadCurrentOrder()}return this.paymentIntegrationService.submitPayment(e)})}shouldShowTSVHostedForm(e){return this.isHostedPaymentFormEnabled(e)&&this.isHostedFieldAvailable()}isHostedPaymentFormEnabled(e){const t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e);return Boolean(t.config.isHostedFormEnabled)}isHostedFieldAvailable(){var e;const t=this.getInitializeOptions(),n=ue(null===(e=t.form)||void 0===e?void 0:e.fields,$);return!$(n)}getInitializeOptions(){if(!this.initializeOptions)throw new ri(ei.PaymentNotInitialized);return this.initializeOptions}mountCardVerificationfields(e){var t;return qh(this,void 0,void 0,function*(){const n=null===(t=this.paymentIntegrationService.getState().getStoreConfig())||void 0===t?void 0:t.paymentSettings.bigpayBaseUrl;if(!n)throw new ti(Xn.MissingCheckoutConfig);const i=this.paymentIntegrationService.createHostedForm(n,e);return yield i.attach(),i})}createIframe(e,t,n,i){const r=document.getElementById(e);if(!r)throw new fi("Unable to create iframe without valid container ID.");const o=document.createElement("iframe"),a={id:t.profileId,pmmsg:!0,display_labels:1,enable_exp:1,enable_cvd:1,css_body:(null==i?void 0:i.cssBody)||"font-family: Arial, Helvetica,sans-serif;background: transparent;",css_textbox:(null==i?void 0:i.cssTextbox)||"border-radius:4px;border: 2px solid rgb(00,00,00);width: 100%;font-weight: 600;padding: 8px 8px;outline: 0;",css_textbox_pan:(null==i?void 0:i.cssTextboxCardNumber)||"width: 240px;",css_textbox_exp:(null==i?void 0:i.cssTextboxExpiryDate)||"margin-bottom: 0;width: calc(30% - 12px);",css_textbox_cvd:(null==i?void 0:i.cssTextboxCVV)||"margin-bottom: 0;width: calc(30% - 12px);",css_input_label:(null==i?void 0:i.cssInputLabel)||"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;",pan_label:t.creditCardLabel||"Credit Card Number",exp_label:t.expiryDateLabel||"Expiration",cvd_label:t.cvdLabel||"CVD"},s=oe(a,(e,t)=>`${t}=${e}`).join("&");return o.width="100%",o.height="100%",o.name=Vh,o.id=Vh,o.style.border="none",o.src=`${this.monerisURL(n)}?${s}`,o.allow="payment",r.appendChild(o),o}handleMonerisResponse(e){const t=JSON.parse(e.data);if("001"!==t.responseCode[0])throw new Error(t.errorMessage);return t.dataKey}monerisURL(e){return`https://${e?"esqa":"www3"}.moneris.com/HPPtoken/index.php`}}const Hh=vi(e=>new Gh(e),[{id:"moneris"}]);class Wh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return n=this,i=void 0,o=function*(){return yield this._paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:e.payment?{methodId:e.payment.methodId}:void 0}),t),Promise.resolve()},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const $h=vi(e=>new Wh(e),[{type:"PAYMENT_TYPE_OFFLINE"}]);var Yh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Kh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return Yh(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew Kh(e),[{type:"PAYMENT_TYPE_HOSTED"}]),Zh=function({styles:e}){const t={};return e.color&&(t.color=e.color),e.layout&&(t.layout=e.layout),(e["logo-type"]||e["logo-position"])&&(t.logo={},e["logo-type"]&&(t.logo.type=e["logo-type"]),e["logo-position"]&&(t.logo.position=e["logo-position"])),e.ratio&&(t.ratio=e.ratio),(e["text-color"]||e["text-size"])&&(t.text={},e["text-color"]&&(t.text.color=e["text-color"]),e["text-size"]&&(t.text.size=+e["text-size"])),t};var Qh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Xh{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.payPalSdkScriptLoader=n,this.loadingIndicator=i}initialize(e){var t;return Qh(this,void 0,void 0,function*(){const{methodId:n,paypalcommerce:i}=e||{};if(this.paypalcommerce=i,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(n),{container:a,bannerContainerId:s}=i,{orderId:d,paypalBNPLConfiguration:c=[],isPayPalCreditAvailable:l}=o.initializationData||{};if(void 0!==s){if(!document.getElementById(s))return void console.error("Unable to create banner without valid banner container ID.");const e=null==c?void 0:c.find(({id:e})=>"checkout"===e);if(l||!(null==e?void 0:e.status))return;const t=yield this.payPalSdkScriptLoader.getPayPalMessages(o,r.getCartOrThrow().currency.code,r.getLocale());return t&&"function"==typeof(null==t?void 0:t.Messages)?this.renderMessages(t,s,e):void console.error("[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK")}d?this.orderId=null===(t=o.initializationData)||void 0===t?void 0:t.orderId:(this.loadingIndicatorContainer=null==a?void 0:a.split("#")[1],yield this.paypalIntegrationService.loadPayPalSdk(n),i.onInit&&"function"==typeof i.onInit&&i.onInit(()=>this.renderButton(n,i)),(void 0===i.shouldRenderPayPalButtonOnInitialization||i.shouldRenderPayPalButtonOnInitialization)&&this.renderButton(n,i))})}execute(e,t){var n,i;return Qh(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rwindow.location.replace(t))}return this.isProviderError(e)&&(yield this.paypalIntegrationService.loadPayPalSdk(r.methodId),yield new Promise((e,t)=>{var n;this.paypalcommerce&&(null===(n=this.paypalButton)||void 0===n||n.close(),this.renderButton(r.methodId,this.paypalcommerce),this.handleError(new Error("INSTRUMENT_DECLINED"),a)),t()})),this.handleError(e,a),Promise.reject()}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}prepareVaultedInstrumentPaymentPayload(e,t,n){const{instrumentId:i,shouldSetAsDefaultInstrument:r}=n,o=!this.isTrustedVaultingFlow(n);return o?{methodId:e,paymentData:{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}:{methodId:e,paymentData:{instrumentId:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t},bigpay_token:{token:i}}}}}preparePaymentPayload(e,t,n){const{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:r=!1}=jd(n)?n:{};return{methodId:e,paymentData:{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}}renderButton(e,t){var n,i,r,o;const a=this.paypalIntegrationService.getPayPalSdkOrThrow(),s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:d}=s.initializationData||{},{checkoutPaymentButtonStyles:c}=d||{},{container:l,onError:u,onRenderButton:h,onValidate:p,submitForm:m}=t;if(!l)throw new fi('Unable to initialize payment because "container" argument is not provided.');const y=this.getSmartButtonContainerId(l);if(!document.getElementById(y))throw new fi(`Unable to initialize payment because element with id ${y} does not exist.`);const g=Object.assign(Object.assign({},this.isPaypalCommerceAppSwitchEnabled(e)&&{appSwitchWhenAvailable:!0}),{fundingSource:a.FUNDING.PAYPAL,style:this.paypalIntegrationService.getValidButtonStyle(c),createOrder:()=>this.createOrder(),onClick:(e,t)=>this.handleClick(t,p),onApprove:e=>this.handleApprove(e,m),onError:e=>this.handleError(e,u),onCancel:()=>this.toggleLoadingIndicator(!1)});this.paypalButton=a.Buttons(g),this.paypalButton.isEligible()&&(h&&"function"==typeof h&&h(),(null===(i=(n=this.paypalButton).hasReturned)||void 0===i?void 0:i.call(n))&&this.isPaypalCommerceAppSwitchEnabled(e)?null===(o=(r=this.paypalButton).resume)||void 0===o||o.call(r):this.paypalButton.render(l))}handleClick(e,t){return Qh(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;return null==t?void 0:t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,null==t||t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createOrder(){return Qh(this,void 0,void 0,function*(){const e=this.getFieldsValues();return this.paypalIntegrationService.createOrder("paypalcommercecheckout",{shouldSaveInstrument:(null==e?void 0:e.shouldSaveInstrument)||!1})})}getFieldsValues(){const{getFieldsValues:e}=this.paypalcommerce||{};return"function"==typeof e?e():void 0}isTrustedVaultingFlow(e){if(e&&xd(e)){const t=this.paymentIntegrationService.getState().getInstruments(),n=null==t?void 0:t.find(t=>uc(t)&&t.bigpayToken===e.instrumentId);return!(uc(n)&&!n.trustedShippingAddress)}return!1}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isPayPalVaultedInstrumentPaymentData(e){return!!e&&xd(e)&&jd(e)}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:Zh(n)};e.Messages(i).render(`#${t}`)}isProviderError(e){var t,n,i;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"INSTRUMENT_DECLINED"===(null===(i=null===(n=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===n?void 0:n.provider_error)||void 0===i?void 0:i.code)}isPaypalCommerceAppSwitchEnabled(e){var t;return(null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)||!1}getSmartButtonContainerId(e){var t;return null!==(t=e.split("#")[1])&&void 0!==t?t:e}}const ep=vi(e=>new Xh(e,As(e),new Is(a()),new vd({containerStyles:Ka})),[{id:"paypalcommerce"}]);var tp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class np{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.loadingIndicator=n,this.payPalSdkScriptLoader=i}initialize(e){return tp(this,void 0,void 0,function*(){const{methodId:t,paypalcommerce:n,paypalcommercecredit:i}=e||{},r=i||n;if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const o=this.paymentIntegrationService.getState(),a=o.getPaymentMethodOrThrow(t),{paypalBNPLConfiguration:s=[],orderId:d}=a.initializationData||{},{bannerContainerId:c,container:l}=r;if(void 0!==c){if(!document.getElementById(c))return void console.error("Unable to create banner without valid banner container ID.");const e=s&&s.find(({id:e})=>"checkout"===e);if(!(null==e?void 0:e.status))return;const t=yield this.payPalSdkScriptLoader.getPayPalMessages(a,o.getCartOrThrow().currency.code,o.getLocale());return this.renderMessages(t,c,e)}d?this.orderId=d:(yield this.paypalIntegrationService.loadPayPalSdk(t),this.loadingIndicatorContainer=null==l?void 0:l.split("#")[1],this.renderButton(t,r))})}execute(e,t){return tp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(h)return;const t={fundingSource:e,style:this.paypalIntegrationService.getValidButtonStyle(o),createOrder:()=>this.paypalIntegrationService.createOrder("paypalcommercecreditcheckout"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=n.Buttons(t),this.paypalButton.isEligible()||e!==n.FUNDING.PAYLATER){if(!this.paypalButton.isEligible()&&e===n.FUNDING.CREDIT)throw new Si(`PayPal ${e} is not available for your region. Please use PayPal Checkout instead.`);d&&"function"==typeof d&&d(),this.paypalButton.render(a),h=!0}})}handleClick(e,t){return tp(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;if(t&&"function"==typeof t)return t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,t&&"function"==typeof t&&t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:Zh(n)};e.Messages(i).render(`#${t}`)}}const ip=vi(e=>new np(e,As(e),new vd({containerStyles:Ka}),Cs()),[{id:"paypalcommercecredit"}]);var rp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class op{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.loadingIndicator=n}initialize(e){var t,n;return rp(this,void 0,void 0,function*(){const{methodId:i,paypalcommerce:r,paypalcommercevenmo:o}=e||{},a=o||r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!a)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i);(null===(t=s.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(n=s.initializationData)||void 0===n?void 0:n.orderId:(yield this.paypalIntegrationService.loadPayPalSdk(i),this.loadingIndicatorContainer=a.container.split("#")[1],this.renderButton(i,a))})}execute(e,t){return rp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rthis.paypalIntegrationService.createOrder("paypalcommercevenmocheckout"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=n.Buttons(u),!this.paypalButton.isEligible())throw new Si("PayPal Venmo is not available for your region. Please use PayPal Checkout instead.");d&&"function"==typeof d&&d(),this.paypalButton.render(a)}handleClick(e,t){return rp(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;return t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,t(),this.toggleLoadingIndicator(!1)}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const ap=vi(e=>new op(e,As(e),new vd({styles:{backgroundColor:"black"}})),[{id:"paypalcommercevenmo"}]),sp={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"};var dp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class cp{constructor(e,t,n,i,r=3e3,o=3e5){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.paypalSdkScriptLoader=n,this.loadingIndicator=i,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.pollingTimer=0,this.stopPolling=ce,this.isOrderApprovedProcessing=!1}initialize(e){return dp(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,paypalcommerce:i,paypalcommercealternativemethods:r}=e,o=r||i;if(this.paypalcommercealternativemethods=r,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!o)throw new fi('Unable to initialize payment because "options.paypalcommercealternativemethods" argument is not provided.');const a=this.paymentIntegrationService.getState(),s=a.getPaymentMethodOrThrow(n,t),{orderId:d,shouldRenderFields:c}=s.initializationData||{},l=a.getStoreConfigOrThrow().checkoutSettings.features;this.isOrderApprovedProcessing=Ci(l,"PAYPAL-5431.order_approved_processing",!1),d?this.orderId=d:(this.paypalApms=yield this.paypalSdkScriptLoader.getPayPalApmsSdk(s,a.getCartOrThrow().currency.code,a.getLocale()),this.loadingIndicatorContainer=o.container.split("#")[1],this.renderButton(n,t,o),c&&this.renderFields(n,o))})}execute(e,t){return dp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.initializePollingMechanism(r,e,t,o)})),this.isNonInstantPaymentMethod(r)&&(r!==Bs.IDEAL||this.isOrderApprovedProcessing)||(yield this.paymentIntegrationService.submitOrder(i,t)),yield this.paypalCommerceIntegrationService.submitPayment(r,this.orderId,o)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,this.isOrderApprovedProcessing||this.resetPollingMechanism(),null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}initializePollingMechanism(e,t,n,i){return dp(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.paypalCommerceIntegrationService.getOrderStatus(null!=i?i:"paypalcommerce"),o=r===js.Approved,a=r===js.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimern.onInitButton(t),createOrder:()=>this.onCreateOrder(e,t,n),onApprove:e=>this.handleApprove(e,c),onCancel:()=>{this.toggleLoadingIndicator(!1),this.deinitializePollingMechanism()},onError:e=>{this.deinitializePollingMechanism(),this.handleFailure(e,s)},onClick:(e,t)=>dp(this,void 0,void 0,function*(){return n.onValidate(t.resolve,t.reject)})};this.paypalButton=i.Buttons(l),this.paypalButton.isEligible()&&(d&&"function"==typeof d&&d(),this.paypalButton.render(a))}onCreateOrder(e,t,n){var i;return dp(this,void 0,void 0,function*(){const{onValidate:r}=n;yield r(()=>(this.toggleLoadingIndicator(!0),()=>Promise.resolve()),ce);const o=yield this.paypalCommerceIntegrationService.createOrder("paypalcommercealternativemethodscheckout");if(this.isNonInstantPaymentMethod(e)&&(e===Bs.IDEAL&&this.isOrderApprovedProcessing||e===Bs.OXXO)){const n={useStoreCredit:!1},r={params:{methodId:e,gatewayId:t}};if(yield this.paymentIntegrationService.submitOrder(n,r),e===Bs.IDEAL){const t=this.paymentIntegrationService.getState(),n=null===(i=t.getOrder())||void 0===i?void 0:i.orderId;yield this.paypalCommerceIntegrationService.updateOrder("paypalcommercealternativemethods",e,n)}yield this.paypalCommerceIntegrationService.submitPayment(e,o,t)}return o})}handleApprove({orderID:e},t){this.orderId=e,t()}handleFailure(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderFields(e,t){const n=this.getPaypalAmpsSdkOrThrow(),i=this.paymentIntegrationService.getState(),{firstName:r,lastName:o,email:a}=i.getBillingAddressOrThrow(),{apmFieldsContainer:s,apmFieldsStyles:d}=t;if(!s)throw new fi('Unable to initialize payment because "options.paypalcommercealternativemethods" argument should contain "apmFieldsContainer".');const c=document.querySelector(s);c&&(c.innerHTML="");const l={fundingSource:e,style:d||{},fields:{name:{value:`${r} ${o}`},email:{value:a}}};n.PaymentFields(l).render(s)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isNonInstantPaymentMethod(e){return e.toUpperCase()in Bs}getPaypalAmpsSdkOrThrow(){if(!this.paypalApms)throw new mi;return this.paypalApms}}const lp=vi(e=>new cp(e,As(e),Cs(),new vd({containerStyles:sp})),[{gateway:"paypalcommercealternativemethods"}]);var up=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class hp{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.paypalSdkScriptLoader=n,this.paypalFastlaneUtils=i}initialize(e){return up(this,void 0,void 0,function*(){const{methodId:t,paypalcommercecreditcards:n,paypalcommerce:i}=e,r=n||i,{form:o,onCreditCardFieldsRenderingError:a,onLoadComplete:s}=r||{};if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)throw new fi('Unable to proceed because "options.paypalcommercecreditcards.form" argument is not provided.');this.hostedFormOptions=o,this.isCreditCardForm=Ac(o.fields),this.isCreditCardVaultedForm=Tc(o.fields)&&!this.hasUndefinedValues(),yield this.paymentIntegrationService.loadPaymentMethod(t),yield this.paypalIntegrationService.loadPayPalSdk(t,void 0,!0,!0),(this.isCreditCardForm||this.isCreditCardVaultedForm)&&(yield this.initializeFields(o,a)),null==s||s(),this.shouldInitializePayPalFastlane(t)&&(yield this.initializePayPalFastlaneOrThrow(t))})}execute(e,t){return up(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(n===Ns.No||n===Ns.Unknown)throw new Error;return this.handleApprove({orderID:e,vaultSetupToken:t})},onError:()=>{throw new Qr},inputEvents:{onChange:t=>this.onChangeHandler(e,t),onFocus:t=>this.onFocusHandler(e,t),onBlur:t=>this.onBlurHandler(e,t),onInputSubmitRequest:t=>this.onInputSubmitRequest(e,t)}},o);if(this.cardFields=yield r.CardFields(a),!this.cardFields.isEligible())throw new ri(ei.PaymentNotInitialized);try{this.stylizeInputContainers(n),Ac(n)&&(yield this.renderFields(n)),Tc(n)&&(yield this.renderVaultedFields(n))}catch(e){"function"==typeof t&&t(e)}})}getExecuteCallback(e){return Tc(e)?this.createVaultSetupTokenCallback():this.createOrderCallback()}createVaultSetupTokenCallback(){return{createVaultSetupToken:()=>up(this,void 0,void 0,function*(){const{setupToken:e}=(yield this.paypalIntegrationService.createOrderCardFields("paypalcommercecreditcardscheckout",Object.assign(Object.assign({},this.getInstrumentParams()),{setupToken:!0})))||{};return e})}}createOrderCallback(){return{createOrder:()=>up(this,void 0,void 0,function*(){const{orderId:e}=(yield this.paypalIntegrationService.createOrderCardFields("paypalcommercecreditcardscheckout",this.getInstrumentParams()))||{};return e})}}handleApprove({orderID:e,vaultSetupToken:t}){e&&(this.returnedOrderId=e),t&&(this.returnedVaultedToken=t)}renderFields(e){var t,n,i,r;return up(this,void 0,void 0,function*(){const o=this.getCardFieldsOrThrow();(null===(t=e.cardCode)||void 0===t?void 0:t.containerId)&&(this.cvvField=o.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCode.containerId}`)),(null===(n=e.cardExpiry)||void 0===n?void 0:n.containerId)&&(this.expiryField=o.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiry.containerId}`)),(null===(i=e.cardName)||void 0===i?void 0:i.containerId)&&(this.nameField=o.NameField({placeholder:""}),yield this.nameField.render(`#${e.cardName.containerId}`)),(null===(r=e.cardNumber)||void 0===r?void 0:r.containerId)&&(this.numberField=o.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumber.containerId}`))})}renderVaultedFields(e){var t,n,i;return up(this,void 0,void 0,function*(){const r=this.getCardFieldsOrThrow();(null===(t=e.cardCodeVerification)||void 0===t?void 0:t.containerId)&&(this.cvvField=r.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCodeVerification.containerId}`)),(null===(n=e.cardExpiryVerification)||void 0===n?void 0:n.containerId)&&(this.expiryField=r.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiryVerification.containerId}`)),(null===(i=e.cardNumberVerification)||void 0===i?void 0:i.containerId)&&(this.numberField=r.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumberVerification.containerId}`))})}getInstrumentParams(){if(!this.executionPaymentData)return{};if(jd(this.executionPaymentData)){const{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}=this.executionPaymentData;return{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}}if(xd(this.executionPaymentData)){const{instrumentId:e}=this.executionPaymentData;return{instrumentId:e}}return{}}getFieldTypeByEmittedField({emittedBy:e}){return{fieldType:this.mapFieldType(e)}}submitHostedForm(){return up(this,void 0,void 0,function*(){const e=this.getCardFieldsOrThrow(),t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),n={billingAddress:{company:t.company,addressLine1:t.address1,addressLine2:t.address2,adminArea1:t.stateOrProvinceCode,adminArea2:t.city,postalCode:t.postalCode,countryCode:t.countryCode}};try{this.isCreditCardVaultedForm?yield e.submit():yield e.submit(n)}catch(e){throw new Qr("Failed authentication. Please try to authorize again.")}})}validateHostedFormOrThrow(){var e,t;return up(this,void 0,void 0,function*(){const n=this.getCardFieldsOrThrow(),i=yield n.getState().then(e=>e),r=this.getValidityData(i);if(!r.isValid)throw null===(t=null===(e=this.hostedFormOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,r),new lo(this.mapValidationErrors(r.errors))})}getValidityData({fields:e}){const t=Object.assign({},e);delete t.cardNameField;const n=Object.keys(t);return{isValid:n.every(e=>{var n;return null===(n=t[e])||void 0===n?void 0:n.isValid}),errors:n.reduce((e,n)=>{var i;const r=this.mapFieldType(n);return Object.assign(Object.assign({},e),{[r]:(null===(i=t[n])||void 0===i?void 0:i.isValid)?void 0:[this.getInvalidErrorByFieldType(r)]})},{})}}getInvalidErrorByFieldType(e){switch(e){case Ec.CardCode:case Ec.CardCodeVerification:return{fieldType:e,message:"Invalid card code",type:"invalid_card_code"};case Ec.CardNumber:case Ec.CardNumberVerification:return{fieldType:e,message:"Invalid card number",type:"invalid_card_number"};case Ec.CardExpiry:case Ec.CardExpiryVerification:return{fieldType:e,message:"Invalid card expiry",type:"invalid_card_expiry"};default:return{fieldType:e,message:"Invalid field",type:"invalid"}}}mapValidationErrors(e={}){const t={};return Object.keys(e).forEach(n=>{var i,r;t[n]=[{message:(null===(r=null===(i=e[n])||void 0===i?void 0:i[0])||void 0===r?void 0:r.message)||"",type:n}]}),t}mapFieldType(e){switch(e){case"name":return Ec.CardName;case"cardNumberField":case"number":return this.isCreditCardForm?Ec.CardNumber:Ec.CardNumberVerification;case"cardExpiryField":case"expiry":return this.isCreditCardForm?Ec.CardExpiry:Ec.CardExpiryVerification;case"cardCvvField":case"cvv":return this.isCreditCardForm?Ec.CardCode:Ec.CardCodeVerification;default:throw new Error("Unexpected field type")}}getCardFieldsOrThrow(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);return this.cardFields}getInputStyles(e){var t,n,i;const r={"font-size":(null===(t=null==e?void 0:e.default)||void 0===t?void 0:t.fontSize)||"1rem","font-family":(null===(n=null==e?void 0:e.default)||void 0===n?void 0:n.fontFamily)||"Montserrat, Arial, Helvetica, sans-serif","font-weight":(null===(i=null==e?void 0:e.default)||void 0===i?void 0:i.fontWeight)||"400",outline:"none",padding:"9px 13px"},o=Object.assign(Object.assign({},r),{color:"#333333"});return{input:o,".invalid":Object.assign(Object.assign({},r),{color:"red"}),".valid":o,":focus":o}}stylizeInputContainers(e){Object.values(e||{}).forEach(e=>{const t=document.getElementById(`${(null==e?void 0:e.containerId)||""}`);t&&(t.style.padding="0px",t.style.boxShadow="none",t.style.border="none",t.style.background="transparent",t.style.marginBottom="10px",t.style.marginLeft="-5px")})}hasUndefinedValues(){return!this.hostedFormOptions||Object.values(this.hostedFormOptions.fields).some(e=>void 0===e)}onChangeHandler(e,t){var n;null===(n=null==e?void 0:e.onValidate)||void 0===n||n.call(e,this.getValidityData(t))}onFocusHandler(e,t){var n;null===(n=null==e?void 0:e.onFocus)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onBlurHandler(e,t){var n;null===(n=null==e?void 0:e.onBlur)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onInputSubmitRequest(e,t){var n;null===(n=null==e?void 0:e.onEnter)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}shouldInitializePayPalFastlane(e){var t,n;const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(e),o=i.getPaymentProviderCustomer(),a=(s=o)&&("authenticationState"in s||"addresses"in s||"instruments"in s)?o:{};var s;return(null===(t=null==r?void 0:r.initializationData)||void 0===t?void 0:t.isAcceleratedCheckoutEnabled)&&(null===(n=null==r?void 0:r.initializationData)||void 0===n?void 0:n.isPayPalCommerceAnalyticsV2Enabled)&&!(null==a?void 0:a.authenticationState)}initializePayPalFastlaneOrThrow(e){return up(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getPaymentMethodOrThrow(e),{initializationData:r}=i;if(!(null==r?void 0:r.connectClientToken))return;const o=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(i,n.currency.code,n.id,t.getLocale());yield this.paypalFastlaneUtils.initializePayPalFastlane(o,!!(null==r?void 0:r.isDeveloperModeApplicable))}catch(e){}})}}const pp=vi(e=>new hp(e,As(e),Cs(),nd()),[{id:"paypalcommercecreditcards"}]);var mp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class yp{constructor(e,t,n,i=3e3,r=3e5){this.paymentIntegrationService=e,this.paypalCommerceService=t,this.loadingIndicator=n,this.pollingInterval=i,this.maxPollingIntervalTime=r,this.pollingTimer=0,this.stopPolling=ce}initialize(e){return mp(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,paypalcommerceratepay:i}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.paypalcommerceratepay" argument is not provided.');const{legalTextContainer:r,container:o,loadingContainerId:a}=i;if(!o)throw new fi('Unable to initialize payment because "options.container" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.legalTextContainer" argument is not provided.');if(!a)throw new fi('Unable to initialize payment because "options.loadingContainerId" argument is not provided.');this.loadingIndicatorContainer=a;const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t),{merchantId:d}=s.initializationData||{};if(!d)throw new fi("Unable to initialize payment because merchantId argument is not provided.");this.paypalcommerceratepay=i,yield this.paypalCommerceService.loadPayPalSdk(n),this.createFraudNetScript(d,n,t),this.loadFraudnetConfig(),this.renderLegalText(r,o)})}execute(e,t){return mp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.initializePollingMechanism(n.methodId,e,t,n.gatewayId)})}catch(e){return this.handleError(e),new Promise((e,t)=>t())}})}finalize(){return Promise.reject(new Cd)}deinitialize(){const{legalTextContainer:e}=this.paypalcommerceratepay||{},t=document.querySelectorAll('[data-id="fraudnetScript"]')[0],n=document.querySelectorAll('[data-id="fraudnetConfig"]')[0];if(this.deinitializePollingMechanism(),t.remove(),n.remove(),e){const t=document.getElementById(e);null==t||t.remove()}return Promise.resolve()}normalizeDate(e){const t=this.formatDate(e.getDate()),n=this.formatDate(e.getMonth()+1);return`${e.getFullYear()}-${n}-${t}`}formatDate(e){return`${e<10?0:""}${e}`}renderLegalText(e,t){const n=e,i=t.split("#")[1],r=document.getElementById(i),o=null==r?void 0:r.parentNode,a=document.createElement("div");a.style.marginBottom="20px",a.setAttribute("id",n),null==o||o.prepend(a);const s=this.paypalCommerceService.getPayPalSdkOrThrow(),d=s.Legal({fundingSource:s.Legal.FUNDING.PAY_UPON_INVOICE});if(!document.getElementById(n))throw new fi('Unable to initialize payment because "legalTextContainerElement" argument is not found.');d.render(`#${n}`)}handleError(e){const{onError:t}=this.paypalcommerceratepay||{};this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createFraudNetScript(e,t,n){const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{testMode:r}=i.config,o=document.createElement("script");o.setAttribute("type","application/json"),o.setAttribute("fncls","fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99"),o.setAttribute("data-id","fraudnetScript"),this.guid=this.generateGUID();const a={f:this.guid,s:`${e}_checkout-page`,sandbox:r};o.innerHTML=JSON.stringify(a),document.body.appendChild(o)}generateGUID(){let e="";for(let t=0;t<32;t+=1)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(62*Math.random())];return e}loadFraudnetConfig(){const e=document.createElement("script");e.setAttribute("data-id","fraudnetConfig"),e.src="https://c.paypal.com/da/r/fb.js",document.body.appendChild(e)}reinitializeStrategy(e){return mp(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}initializePollingMechanism(e,t,n,i){return mp(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.paypalCommerceService.getOrderStatus("paypalcommercealternativemethods",{params:{useMetadata:!0}}),o=r===_s.PollingStop,a=r===_s.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimernew yp(e,As(e),new vd({containerStyles:Object.assign(Object.assign({},Ka),{position:"fixed"})})),[{gateway:"paypalcommercealternativemethods",id:"ratepay"}]);function vp(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var fp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Sp{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalCommerceRequestSender=t,this.paypalSdkScriptLoader=n,this.paypalFastlaneUtils=i}initialize(e){var t,n;return fp(this,void 0,void 0,function*(){const{methodId:i,paypalcommercefastlane:r}=e;if(this.methodId=i,this.paypalcommercefastlane=r,!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.paypalcommercefastlane" argument is not provided.');if(!r.onInit||"function"!=typeof r.onInit)throw new fi('Unable to initialize payment because "options.paypalcommercefastlane.onInit" argument is not provided or it is not a function.');if(!r.onChange||"function"!=typeof r.onChange)throw new fi('Unable to initialize payment because "options.paypalcommercefastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState(),a=o.getCartOrThrow(),s=o.getPaymentMethodOrThrow(i),{isDeveloperModeApplicable:d,isFastlaneStylingEnabled:c}=s.initializationData||{};this.threeDSVerificationMethod=null===(t=s.initializationData)||void 0===t?void 0:t.threeDSVerificationMethod,this.paypalFastlaneSdk=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(s,a.currency.code,a.id,o.getLocale());const l=rd(c?null===(n=null==s?void 0:s.initializationData)||void 0===n?void 0:n.fastlaneStyles:{},null==r?void 0:r.styles);yield this.paypalFastlaneUtils.initializePayPalFastlane(this.paypalFastlaneSdk,!!d,l),this.shouldRunAuthenticationFlow()&&(yield this.runPayPalAuthenticationFlowOrThrow(i)),yield this.initializePayPalPaymentComponent(),r.onInit(e=>this.renderPayPalPaymentComponent(e)),r.onChange(()=>this.handlePayPalStoredInstrumentChange(i))})}execute(e,t){return fp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const{getHost:t}=e.getState();return new Sp(e,new Gs(n({host:t()})),Cs(),nd())},[{id:"paypalcommerceacceleratedcheckout"}]);var wp,Ip,Cp,bp,Pp,Op;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(wp||(wp={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(Ip||(Ip={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black"}(Cp||(Cp={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(bp||(bp={})),function(e){e.PILL="pill",e.RECT="rect"}(Pp||(Pp={})),function(e){e.ACKNOWLEDGE="ACKNOWLEDGE",e.FINALIZE="FINALIZE",e.INITIALIZE="INITIALIZE"}(Op||(Op={}));var Ep=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ap{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t,this.useRedirectFlow=!1,this.window=window}initialize(e){return Ep(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState();this.paymentMethod=t.getPaymentMethodOrThrow(e.methodId),this.useRedirectFlow=!0===(e.paypalexpress&&e.paypalexpress.useRedirectFlow);const n=this.paymentMethod.config.merchantId;if(!this.isInContextEnabled()||!n)throw new ti(Xn.MissingPaymentMethod);const i=yield this.scriptLoader.loadPaypalSDK();this.paypalSdk=i,this.paypalSdk.checkout.setup(n,{button:"paypal-button",environment:this.paymentMethod.config.testMode?"sandbox":"production"})})}deinitialize(){return this.isInContextEnabled()&&this.paypalSdk&&(this.paypalSdk.checkout.closeFlow(),this.paypalSdk=void 0),Promise.resolve()}execute(e,t){return Ep(this,void 0,void 0,function*(){let n,i;const r=this.paypalSdk;if(!this.isAcknowledgedOrFinalized()){if(!this.isInContextEnabled()||this.useRedirectFlow)return n=yield this.paymentIntegrationService.submitOrder(e,t),i=n.getPaymentRedirectUrl(),i&&this.window.top&&(this.window.top.location.href=i),new Promise(ce);if(!r)throw new ri(ei.PaymentNotInitialized);r.checkout.initXO();try{n=yield this.paymentIntegrationService.submitOrder(e,t)}catch(e){return r.checkout.closeFlow(),Promise.reject(e)}return i=n.getPaymentRedirectUrl(),i&&r.checkout.startFlow(i),new Promise(ce)}yield this.paymentIntegrationService.submitOrder(e,t)})}finalize(e){return Ep(this,void 0,void 0,function*(){return this.paymentIntegrationService.getState().getOrder()&&this.isAcknowledgedOrFinalized()?(yield this.paymentIntegrationService.finalizeOrder(e),Promise.resolve()):Promise.reject(new Cd)})}isAcknowledgedOrFinalized(){const e=this.paymentIntegrationService.getState();return e.getPaymentStatus()===Op.ACKNOWLEDGE||e.getPaymentStatus()===Op.FINALIZE}isInContextEnabled(){return!(!this.paymentMethod||!this.paymentMethod.config.merchantId)}}class Tp{constructor(e){this.scriptLoader=e,this.window=window}loadPaypalSDK(e=""){return t=this,n=void 0,r=function*(){const t=Object.assign({async:!0,attributes:{"data-merchant-id":e}},e&&{attributes:{"data-merchant-id":e}});if(yield this.scriptLoader.loadScript("//www.paypalobjects.com/api/checkout.min.js",t),!this.window.paypal)throw new mi;return this.window.paypal},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const kp=vi(e=>new Ap(e,new Tp(a())),[{id:"paypalexpress",type:"PAYMENT_TYPE_HOSTED"},{id:"paypalexpresscredit",type:"PAYMENT_TYPE_HOSTED"}]);var Dp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Mp extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this.threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Dp(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);n.config.is3dsEnabled&&(yield this.threeDSecureFlow.prepare(n))})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return Dp(this,void 0,void 0,function*(){const{payment:{methodId:i=""}={}}=e,r=this.paymentIntegrationService.getState();return r.getPaymentStatus()===dl.ACKNOWLEDGE?(yield this.paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:{methodId:i}}),t),Promise.resolve()):r.getPaymentMethodOrThrow(i).config.is3dsEnabled?this.threeDSecureFlow.start(n.execute.bind(this),e,t,this._hostedForm):n.execute.call(this,e,t)})}}const zp=vi(e=>new Mp(e,new Au(e,new Fu(new Lu(a())))),[{id:"paypal"}]);class Np extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this._formPoster=t}execute(e,t){const{payment:n}=e;if(!n)throw new ri(ei.PaymentNotInitialized);const{paymentData:i}=n;if(!i)throw new ti(Xn.MissingPayment);if(this._isThreeDSTwoExperimentOn()){const t=Object.assign(Object.assign({},i),{browser_info:ss()});e.payment&&(e.payment.paymentData=t)}return super.execute(e,t).catch(e=>pa(e)&&ve(e.body.errors,{code:"three_d_secure_required"})?new Promise(()=>{let t;t=this._isThreeDSTwoExperimentOn()&&!e.body.three_ds_result.merchant_data?{creq:e.body.three_ds_result.payer_auth_request}:{PaReq:e.body.three_ds_result.payer_auth_request,TermUrl:e.body.three_ds_result.callback_url,MD:e.body.three_ds_result.merchant_data},this._formPoster.postForm(e.body.three_ds_result.acs_url,t,void 0,"_top")}):Promise.reject(e))}finalize(e){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),super.finalize()}_isThreeDSTwoExperimentOn(){return!0===this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features["INT-4994.Opayo_3DS2"]}}const xp=vi(e=>new Np(e,Ee()),[{id:"sagepay"}]);class Rp{constructor(e,t){this._formPoster=e,this._paymentIntegrationService=t}execute(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.redirectUrl(t)})}var o},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}redirectUrl(e){return this._formPoster.postForm(e,{})}_isAdditionalActionRequired(e){const{additional_action_required:t,status:n}=e;return"additional_action_required"===n&&t&&"offsite_redirect"===t.type}}class Fp extends Rp{redirectUrl(e){window.location.replace(e)}}const Lp=vi(e=>new Fp(Ee(),e),[{id:"sezzle"}]);var Bp;!function(e){e.CHARGE="CHARGE",e.STORE="STORE"}(Bp||(Bp={}));var jp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Up{constructor(e,t){this._scriptLoader=e,this._paymentIntegrationService=t}initialize({testMode:e,applicationId:t,locationId:n}){return jp(this,void 0,void 0,function*(){const i=yield this._scriptLoader.load(e);this._payments=i.payments(t,n)})}deinitialize(){return jp(this,void 0,void 0,function*(){this._formValidationSubscription&&this._formValidationSubscription.unsubscribe(),this._card&&(yield this._card.destroy()),this._formValidationSubscription=void 0,this._card=void 0,this._payments=void 0})}initializeCard({containerId:e,style:t,onValidationChange:n}){return jp(this,void 0,void 0,function*(){const{postalCode:i}=this._paymentIntegrationService.getState().getBillingAddress()||{};this._card=yield this._getPayments().card(),yield this._card.attach(`#${e}`);try{yield this._card.configure({postalCode:i,style:t})}catch(e){}n&&(this._formValidationSubscription=this._subscribeToFormValidation(this._card,n))})}tokenize(){return jp(this,void 0,void 0,function*(){const e=yield this._getCard().tokenize();if("OK"!==e.status||!e.token){let t=`Tokenization failed with status: ${e.status}`;throw"errors"in e&&e.errors&&(t+=` and errors: ${JSON.stringify(e.errors)}`),new _h("payment.errors.card_error","SquareV2TokenizationError",t)}return e.token})}verifyBuyer(e,t){return jp(this,void 0,void 0,function*(){return t===Bp.CHARGE?this._chargeVerifyBuyer(e):this._storeVerifyBuyer(e)})}_getPayments(){return ii(this._payments,()=>new ri(ei.PaymentNotInitialized))}_subscribeToFormValidation(e,t){const n=["cardNumber","cvv"],i=new Set(n),r=["focusClassAdded","focusClassRemoved","errorClassAdded","errorClassRemoved","cardBrandChanged","postalCodeChanged"].map(t=>_(e,t));return w(...r).pipe(T(e=>{const{detail:{field:t,currentState:{isCompletelyValid:r}}}=e;return n.includes(t)&&i[r?"delete":"add"](t),0===i.size}),E()).subscribe(t)}_getCard(){return ii(this._card,()=>new ri(ei.PaymentNotInitialized))}_mapToSquareBillingContact({firstName:e,lastName:t,address1:n,address2:i,city:r,stateOrProvinceCode:o,postalCode:a,countryCode:s,email:d,phone:c}){return{givenName:e,familyName:t,addressLines:[n,i],city:r,state:o,postalCode:a,countryCode:s,email:d,phone:c}}_chargeVerifyBuyer(e){return jp(this,void 0,void 0,function*(){const{getCheckoutOrThrow:t,getBillingAddressOrThrow:n}=this._paymentIntegrationService.getState(),{outstandingBalance:i,cart:r}=t(),o={amount:i.toString(),billingContact:this._mapToSquareBillingContact(n()),currencyCode:r.currency.code,intent:Bp.CHARGE},a=yield this._getPayments().verifyBuyer(e,o);return a?a.token:""})}_storeVerifyBuyer(e){return jp(this,void 0,void 0,function*(){const{getBillingAddressOrThrow:t}=this._paymentIntegrationService.getState(),n={billingContact:this._mapToSquareBillingContact(t()),intent:Bp.STORE},i=yield this._getPayments().verifyBuyer(e,n);return i?i.token:""})}}var qp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vp{constructor(e,t){this._paymentIntegrationService=e,this._squareV2PaymentProcessor=t}initialize(e){var t;return qp(this,void 0,void 0,function*(){if(!(null===(t=null==e?void 0:e.squarev2)||void 0===t?void 0:t.containerId))throw new fi('Unable to proceed because "containerId" argument is not provided.');const{methodId:n,squarev2:i}=e,{config:{testMode:r},initializationData:o}=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(n),{applicationId:a,locationId:s}=o||{};if(!a)throw new Xr;yield this._squareV2PaymentProcessor.initialize({applicationId:a,locationId:s,testMode:r}),yield this._squareV2PaymentProcessor.initializeCard(i)})}execute({payment:e}){return qp(this,void 0,void 0,function*(){if(!e)throw new co(["payment"]);const{methodId:t,paymentData:n}=e,{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r}=jd(n)?n:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1};yield this._paymentIntegrationService.submitOrder();const o=n&&xd(n)?yield this._getVaultedInstrumentPayload(t,n):yield this._getCardPayload(t,i);yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:{formattedPayload:Object.assign(Object.assign({},o),{vault_payment_instrument:i||!1,set_as_default_stored_instrument:r||!1})}}))})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this._squareV2PaymentProcessor.deinitialize()}shouldVerify(){const{features:e}=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings;return e["PROJECT-3828.add_3ds_support_on_squarev2"]}_getCardPayload(e,t){return qp(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),{initializationData:i}=n(e),r=yield this._squareV2PaymentProcessor.tokenize();if(i&&"isSquareV2ApiV2Enabled"in i?!i.isSquareV2ApiV2Enabled:!this.shouldVerify())return{credit_card_token:{token:r}};let o={nonce:r,token:yield this._squareV2PaymentProcessor.verifyBuyer(r,Bp.CHARGE)};if(t){const e=yield this._squareV2PaymentProcessor.tokenize();o=Object.assign(Object.assign({},o),{store_card_nonce:e,store_card_token:yield this._squareV2PaymentProcessor.verifyBuyer(e,Bp.STORE)})}return{credit_card_token:{token:JSON.stringify(o)}}})}_getVaultedInstrumentPayload(e,t){return qp(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),{initializationData:i}=n(e),{instrumentId:r}=t,o=(i&&"isSquareV2ApiV2Enabled"in i?i.isSquareV2ApiV2Enabled:this.shouldVerify())?yield this._squareV2PaymentProcessor.verifyBuyer(yield this._getSquareCardIdOrThrow(e,r),Bp.CHARGE):void 0;return{bigpay_token:Object.assign({token:r},o&&{three_d_secure:{token:o}})}})}_getSquareCardIdOrThrow(e,t){return qp(this,void 0,void 0,function*(){const n=yield this._paymentIntegrationService.loadPaymentMethod(e,{params:{method:e,bigpayToken:t}}),{initializationData:i}=n.getPaymentMethodOrThrow(e),{cardId:r}=i||{};if(!r)throw new co(["cardId"]);return r})}}var Gp;!function(e){e.LIVE="https://web.squarecdn.com/v1/square.js",e.SANDBOX="https://sandbox.web.squarecdn.com/v1/square.js"}(Gp||(Gp={}));class Hp{constructor(e){this._scriptLoader=e}load(e=!1){return t=this,n=void 0,r=function*(){return yield this._scriptLoader.loadScript(e?Gp.SANDBOX:Gp.LIVE),function(e){if(!function(e){return"Square"in e}(e))throw new mi}(window),window.Square},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const Wp=vi(e=>new Vp(e,new Up(new Hp(a()),e)),[{id:"squarev2"}]);function $p(e){return null!==e&&"object"==typeof e&&"cardNumberElementOptions"in e&&"cardCvcElementOptions"in e&&"cardExpiryElementOptions"in e&&void 0!==e.cardNumberElementOptions&&void 0!==e.cardCvcElementOptions&&void 0!==e.cardExpiryElementOptions}var Yp,Kp,Jp,Zp;!function(e){e.Solid="solid",e.Default="default"}(Yp||(Yp={})),function(e){e.Alipay="alipay",e.CardCvc="cardCvc",e.CardExpiry="cardExpiry",e.CardNumber="cardNumber",e.CreditCard="card",e.IDEAL="idealBank",e.Sepa="iban"}(Kp||(Kp={})),function(e){e.Alipay="alipay",e.CreditCard="card",e.IDEAL="ideal",e.Sepa="sepa_debit"}(Jp||(Jp={})),function(e){e.AuthFailure="auth_failure"}(Zp||(Zp={}));class Qp extends Qn{constructor(e){super(e===Zp.AuthFailure?"User did not authenticate":"There was an error while processing your payment. Please try again or contact us."),this.type="stripev3_error",this.subtype=e}}var Xp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const em=[Kp.Alipay,Kp.IDEAL];class tm{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){return Xp(this,void 0,void 0,function*(){const{stripev3:t,methodId:n,gatewayId:i}=e;if(!i)throw new fi('Unable to initialize payment because "gatewayId" argument is not provided.');this.initializeOptions=t,this.isDeinitialize=!1;const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n),{initializationData:{stripePublishableKey:o,stripeConnectedAccount:a,useIndividualCardFields:s,allowRedisplayForStoredInstruments:d}}=r;this._allowRedisplayForStoredInstruments=d;const c=this.getInitializeOptions().form;this.useIndividualCardFields=s,this.stripeV3Client=yield this.loadStripeJs(o,a),this.isCreditCard(n)&&this.shouldShowTSVHostedForm(n,i)&&c?this.hostedForm=yield this.mountCardVerificationFields(c):this.stripeElement=yield this.mountCardFields(n)})}execute(e,t){var n,i;return Xp(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{switch(this.stripeElements||(this.stripeElements=this.getStripeJs().elements()),e){case Kp.CreditCard:if(this.useIndividualCardFields&&$p(t)){const{cardNumberElementOptions:e,cardExpiryElementOptions:n,cardCvcElementOptions:r}=t,a=this.stripeElements.getElement(Kp.CardNumber)||this.stripeElements.create(Kp.CardNumber,e),s=this.stripeElements.getElement(Kp.CardExpiry)||this.stripeElements.create(Kp.CardExpiry,n),d=this.stripeElements.getElement(Kp.CardCvc)||this.stripeElements.create(Kp.CardCvc,r);this.stripeCardElements=[a,s,d],i=this.stripeCardElements[0];try{a.mount(`#${e.containerId}`),s.mount(`#${n.containerId}`),d.mount(`#${r.containerId}`)}catch(e){this.isDeinitialize||o(new fi("Unable to mount Stripe component without valid container ID."))}}else{i=this.stripeElements.getElement(e)||this.stripeElements.create(e,t);try{i.mount(`#${n}`)}catch(e){this.isDeinitialize||o(new fi("Unable to mount Stripe component without valid container ID."))}}break;case Kp.IDEAL:case Kp.Sepa:i=this.stripeElements.getElement(e)||this.stripeElements.create(e,t);try{i.mount(`#${n}`)}catch(e){this.isDeinitialize||o(new fi("Unable to mount Stripe component without valid container ID."))}case Kp.Alipay:}r(i)})}mountCardVerificationFields(e){return Xp(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getStoreConfig();if(!t)throw new ti(Xn.MissingCheckoutConfig);const n=t.paymentSettings.bigpayBaseUrl,i=this.paymentIntegrationService.createHostedForm(n,e);return yield i.attach(),i})}processAdditionalAction(e,t,n=!1,i=!1){return Xp(this,void 0,void 0,function*(){if(!pa(e))throw e;const r=ve(e.body.errors,{code:"additional_action_required"}),o=ve(e.body.errors,{code:"three_d_secure_required"});if(r){const t=e.body.additional_action_required;if(t&&"redirect_to_url"===t.type)return new Promise(()=>{t.data.redirect_url&&window.location.replace(t.data.redirect_url)})}if(o){const r=e.body.three_ds_result.token,o=!1;let a,s=!1;try{a=yield this.getStripeJs().confirmCardPayment(r)}catch(e){s=!0}if(null==a?void 0:a.error){if(this.isCancellationError(a.error))throw new Wi;if(this.isAuthError(a.error))throw new Qp(Zp.AuthFailure);throw new Error(a.error.message)}const d={credit_card_token:{token:this.getPaymentToken(null==a?void 0:a.paymentIntent,r,s)},vault_payment_instrument:n,confirm:o},c=this.buildPaymentPayload(t,d,i);try{return yield this.paymentIntegrationService.submitPayment(c)}catch(e){throw this.handleEmptyPaymentIntentError(e,null==a?void 0:a.error)}}throw e})}getPaymentToken(e,t,n){return!e||n?t:e.id}shouldShowTSVHostedForm(e,t){return this.isHostedFieldAvailable()&&this.isHostedPaymentFormEnabled(e,t)}unmountElement(){this.stripeElement&&(this.stripeElement.unmount(),this.stripeElement=void 0)}}class nm{constructor(e,t=window){this.scriptLoader=e,this.stripeWindow=t}load(e,t,n){return this.scriptLoader.loadScript("https://js.stripe.com/v3/").then(()=>{if(!this.stripeWindow.Stripe)throw new mi;return this.stripeWindow.Stripe(e,{stripeAccount:t,locale:n,betas:["payment_intent_beta_3","alipay_pm_beta_1"],apiVersion:"2020-03-02;alipay_beta=v1"})})}}const im=vi(e=>new tm(e,new nm(a())),[{gateway:"stripev3"}]),rm={ar:["ar"],bg:["bg"],cs:["cs"],da:["da"],de:["de"],el:["el"],en:["en","en-GB"],es:["es","es-419"],et:["et"],fi:["fi"],fil:["fil"],fr:["fr","fr-CA"],he:["he"],hr:["hr"],hu:["hu"],id:["id"],it:["it"],ja:["ja"],ko:["ko"],lt:["lt"],lv:["lv"],ms:["ms"],mt:["mt"],nb:["nb"],nl:["nl"],pl:["pl"],pt:["pt","pt-BR"],ro:["ro"],ru:["ru"],sk:["sk"],sl:["sl"],sv:["sv"],th:["th"],tr:["tr"],vi:["vi"],zh:["zh","zh-HK","zh-TW"]};function om(e){const[t,n]=e.replace(/_/g,"-").toLowerCase().split("-"),i=rm[t];if(!i)return"auto";const r=n?`${t}-${n.toUpperCase()}`:t;return i.indexOf(r)>-1?r:i[0]}var am=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class sm{constructor(e,t,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n}initialize(e){return am(this,void 0,void 0,function*(){const{stripeupe:t,methodId:n,gatewayId:i}=e;if(!(null==t?void 0:t.containerId))throw new ri(ei.PaymentNotInitialized);if(!i)throw new fi('Unable to initialize payment because "gatewayId" argument is not provided.');return this._loadStripeElement(t,i,n).catch(e=>{var n;return null===(n=t.onError)||void 0===n?void 0:n.call(t,e)}),this.stripeIntegrationService.initCheckoutEventsSubscription(i,n,t,this._stripeElements),Promise.resolve()})}execute(e,t){return am(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{o()}),f.on(za.CHANGE,e=>{(null==e?void 0:e.value)&&"type"in e.value&&this._updateStripeLinkStateByElementType(e.value.type)}),this._isStripeElementUpdateEnabled&&(null==a||a(this._updateStripeElement.bind(this)))})}_processAdditionalActionWithStripeConfirmation(e,t,n,i=!1,r=!1){return am(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new ri(ei.PaymentNotInitialized);const{data:o}=e.body.additional_action_required,{token:a}=o,{paymentIntent:s,error:d}=yield this._confirmStripePaymentOrThrow(t,o),c=this._getPaymentPayload(t,(null==s?void 0:s.id)||a,i,r);if(d||!s){const{initializationData:e}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{sendSecondPaymentRequestOnStripeError:i}=e||{};if(i)try{const e=de({},c,{paymentData:{formattedPayload:{client_side_error:!0}}});yield this.paymentIntegrationService.submitPayment(e)}catch(e){}this.stripeIntegrationService.throwStripeError(d)}try{yield this.paymentIntegrationService.submitPayment(c)}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}})}_confirmStripePaymentOrThrow(e,t){return am(this,void 0,void 0,function*(){if(!this._stripeUPEClient)throw new ri(ei.PaymentNotInitialized);const{token:n,redirect_url:i}=t,r=this.stripeIntegrationService.mapStripePaymentData(this._stripeElements,i,!!this._allowRedisplayForStoredInstruments);return(yield this.stripeIntegrationService.isPaymentCompleted(e,this._stripeUPEClient))?this._stripeUPEClient.retrievePaymentIntent(n||""):this._stripeUPEClient.confirmPayment(r)})}_processVaultedAdditionalAction(e,t,n=!1){var i;return am(this,void 0,void 0,function*(){if(!t||!pa(e)||!ve(e.body.errors,{code:"three_d_secure_required"}))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new ri(ei.PaymentNotInitialized);const r=e.body.three_ds_result.token;let o,a=!1;try{o=yield this._stripeUPEClient.confirmCardPayment(r)}catch(e){try{o=yield this._stripeUPEClient.retrievePaymentIntent(r)}catch(e){a=!0}}if((null==o?void 0:o.error)&&this.stripeIntegrationService.throwStripeError(o.error),!(null==o?void 0:o.paymentIntent)&&!a)throw new nr;const s=this._getPaymentPayload(t,a?r:null===(i=null==o?void 0:o.paymentIntent)||void 0===i?void 0:i.id,!1,n);return this.paymentIntegrationService.submitPayment(s)})}_loadStripeJs(e){return am(this,void 0,void 0,function*(){if(this._stripeUPEClient)return this._stripeUPEClient;const t=this.paymentIntegrationService.getState();return this.scriptLoader.getStripeClient(e,t.getCartLocale(),ka.V3,Fa,La)})}_getPaymentPayload(e,t,n=!1,i=!1){var r;return{methodId:e,paymentData:{formattedPayload:{cart_id:(null===(r=this.paymentIntegrationService.getState().getCart())||void 0===r?void 0:r.id)||"",credit_card_token:{token:t},confirm:!1,vault_payment_instrument:n,set_as_default_stored_instrument:i}}}}_updateStripeElement({shouldShowTerms:e}){var t;const n=null===(t=this._stripeElements)||void 0===t?void 0:t.getElement(Da.PAYMENT);null==n||n.update(Object.assign({},this._getStripeElementTerms(e)))}_getStripeElementTerms(e){let t=Ta.AUTO;return this._isStripeElementUpdateEnabled&&(t=e?Ta.AUTO:Ta.NEVER),{terms:{card:t}}}_updateStripeLinkStateByElementType(e){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow(),n=e===Aa.Link;!cd(t)&&n&&this.paymentIntegrationService.updatePaymentProviderCustomer({stripeLinkAuthenticationState:n})}}const dm=vi(e=>{const t=new Ra(a());return new sm(e,t,new pd(e,t))},[{gateway:"stripeupe"},{gateway:"stripeupe",id:"klarna"}]),cm=e=>"object"==typeof e&&null!==e&&"value"in e&&"collapsed"in e;var lm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class um{constructor(e,t,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n}initialize(e){var t;return lm(this,void 0,void 0,function*(){const{stripeocs:n,methodId:i,gatewayId:r}=e;if(!(null==n?void 0:n.containerId))throw new ri(ei.PaymentNotInitialized);if(!r)throw new fi('Unable to initialize payment because "gatewayId" argument is not provided.');try{yield this._initializeStripeElement(n,r,i)}catch(e){e instanceof Error&&(null===(t=n.onError)||void 0===t||t.call(n,e))}this.stripeIntegrationService.initCheckoutEventsSubscription(r,i,n,this.stripeElements)})}execute(e,t){return lm(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{null==y||y(!1)}),_.on(za.READY,()=>{h()}),_.on(za.CHANGE,e=>{this._onStripeElementChange(e,t,n,p)}),null==m||m(this._collapseStripeElement.bind(this))})}_loadStripeJs(e){return lm(this,void 0,void 0,function*(){if(this.stripeClient)return this.stripeClient;const t=this.paymentIntegrationService.getState(),n=this.stripeIntegrationService.getStripeJsVersion(e);return this.scriptLoader.getStripeClient(e,t.getCartLocale(),n)})}_collapseStripeElement(){var e;const t=null===(e=this.stripeElements)||void 0===e?void 0:e.getElement(Da.PAYMENT);null==t||t.collapse()}_getPaymentPayload(e,t,n){var i;const r=(null===(i=this.paymentIntegrationService.getState().getCart())||void 0===i?void 0:i.id)||"",{card:o,us_bank_account:a}=n||{},s=this._shouldSaveInstrument(o)||this._shouldSaveInstrument(a),d=this._getTokenizedOptions(t,n);return{methodId:e,paymentData:{formattedPayload:Object.assign({cart_id:r,confirm:!1,method:this.selectedMethodId,vault_payment_instrument:s},d)}}}_processAdditionalAction(e,t,n){return lm(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this.stripeClient||!this.stripeElements)throw new ri(ei.PaymentNotInitialized);const{data:i}=e.body.additional_action_required,{token:r}=i,{paymentIntent:o,error:a}=yield this._confirmStripePaymentOrThrow(t,i),{client_secret:s,payment_method_options:d}=o||{},c=this._getPaymentPayload(t,s||r,d);if(a||!o){const{initializationData:e}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{sendSecondPaymentRequestOnStripeError:i}=e||{};if(i)try{const e=de({},c,{paymentData:{formattedPayload:{client_side_error:!0}}});yield this.paymentIntegrationService.submitPayment(e)}catch(e){}this.stripeIntegrationService.throwStripeError(a)}try{return yield this.paymentIntegrationService.submitPayment(c)}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}})}_confirmStripePaymentOrThrow(e,t){return lm(this,void 0,void 0,function*(){if(!this.stripeClient)throw new ri(ei.PaymentNotInitialized);const{token:n,redirect_url:i}=t,r=this.stripeIntegrationService.mapStripePaymentData(this.stripeElements,i);return(yield this.stripeIntegrationService.isPaymentCompleted(e,this.stripeClient))?this.stripeClient.retrievePaymentIntent(n||""):this.stripeClient.confirmPayment(r)})}_onStripeElementChange(e,t,n,i){cm(e)&&!e.collapsed&&(this.selectedMethodId=e.value.type,null==i||i(`${t}-${n}`))}_shouldSaveInstrument(e){const t=null==e?void 0:e.setup_future_usage;return t===Na.ON_SESSION||t===Na.OFF_SESSION}_getTokenizedOptions(e,t){return this._shouldSaveInstrument(null==t?void 0:t.us_bank_account)?{tokenized_ach:{token:e}}:{credit_card_token:{token:e}}}}const hm=vi(e=>{const t=new Ra(a());return new um(e,t,new pd(e,t))},[{gateway:"stripeocs",id:"optimized_checkout"}]);var pm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class mm{constructor(e,t,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n}initialize(e){var t;return pm(this,void 0,void 0,function*(){const{stripeocs:n,methodId:i,gatewayId:r}=e;if(!(null==n?void 0:n.containerId)||!r)throw new ri(ei.PaymentNotInitialized);let o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,r);(null==o?void 0:o.clientToken)||(yield this.paymentIntegrationService.loadPaymentMethod(r,{params:{method:i}}),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,r));try{yield this._initStripeCheckoutSession(n,o),yield this._updateStripeShopperData(),this._initializePaymentElement(n,o),this._initializeAdaptivePricingElement(n,o)}catch(e){e instanceof Error&&(null===(t=n.onError)||void 0===t||t.call(n,e))}})}execute(e,t){return pm(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{null==u||u(!1)}),h.on(za.READY,()=>{d()}),h.on(za.CHANGE,e=>{this._onStripeElementChange(e,r,i,c)}),null==l||l(this._collapseStripeElement.bind(this))}_loadStripeJs(e){return pm(this,void 0,void 0,function*(){if(this.stripeClient)return this.stripeClient;const t=this.paymentIntegrationService.getState();return this.scriptLoader.getStripeClient(e,t.getCartLocale(),ka.CLOVER)})}_getStripeActionsOrThrow(){return pm(this,void 0,void 0,function*(){if(!this.stripeCheckout)throw new ri(ei.PaymentNotInitialized);const{actions:e,error:t}=yield this.stripeCheckout.loadActions();if(!e||t)throw new Qr(null==t?void 0:t.message);return e})}_getStripeElement(e){var t,n;return(null===(t=this.stripeCheckout)||void 0===t?void 0:t.getPaymentElement())||(null===(n=this.stripeCheckout)||void 0===n?void 0:n.createPaymentElement(e))}_onStripeElementChange(e,t,n,i){cm(e)&&!e.collapsed&&(this.selectedMethodId=e.value.type,null==i||i(`${t}-${n}`))}_collapseStripeElement(){var e;const t=null===(e=this.stripeCheckout)||void 0===e?void 0:e.getPaymentElement();null==t||t.collapse()}_updateCheckoutSessionData(e,t){return pm(this,void 0,void 0,function*(){yield this._updateStripeShopperData(),yield this.paymentIntegrationService.loadPaymentMethod(e,{params:{method:t}})})}_getPaymentPayload(e,t,n){var i;const r=(null===(i=this.paymentIntegrationService.getState().getCart())||void 0===i?void 0:i.id)||"",o=this._getTokenizedOptions(t,n);return{methodId:e,paymentData:{formattedPayload:Object.assign({cart_id:r,confirm:!1,method:this.selectedMethodId,vault_payment_instrument:!!n},o)}}}_processAdditionalAction(e,t,n){var i;return pm(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;const{data:r}=(null===(i=e.body)||void 0===i?void 0:i.additional_action_required)||{},{token:o}=r||{},a=yield this._getStripeSavedPaymentMethodsOrThrow(),{session:s,error:d}=yield this._confirmStripePayment(r),c=yield this._getStripeSavedPaymentMethodsOrThrow(s),{id:l,status:u}=s||{},h=this._getNewVaultedStripeInstrument(a,c),p=this._getPaymentPayload(n,l||o,h),{initializationData:m}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t),{sendSecondPaymentRequestOnStripeError:y}=m||{};if(d||!s){if(y)try{const e=de({},p,{paymentData:{formattedPayload:{client_side_error:!0}}});yield this.paymentIntegrationService.submitPayment(e)}catch(e){}throw new Qr(null==d?void 0:d.message)}try{return yield this.paymentIntegrationService.submitPayment(p)}catch(e){throw(null==u?void 0:u.paymentStatus)===Oa.Paid&&this.stripeIntegrationService.throwPaymentConfirmationProceedMessage(),e}})}_confirmStripePayment(e){return pm(this,void 0,void 0,function*(){const{redirect_url:t}=e||{};if(!this.stripeCheckout)throw new ri(ei.PaymentNotInitialized);return(yield this._getStripeActionsOrThrow()).confirm({redirect:Ta.IF_REQUIRED,returnUrl:t})})}_updateStripeShopperData(){return pm(this,void 0,void 0,function*(){const e=yield this._getStripeActionsOrThrow();yield this._updateStripeEmail(e),yield this._updateStripeShippingAddress(e),yield this._updateStripeBillingAddress(e)})}_updateStripeEmail(e){return pm(this,void 0,void 0,function*(){if((yield e.getSession()).email)return;const{getBillingAddress:t}=this.paymentIntegrationService.getState(),n=t();yield e.updateEmail((null==n?void 0:n.email)||"")})}_updateStripeShippingAddress(e){return pm(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getShippingAddress();t&&(yield e.updateShippingAddress({name:this.stripeIntegrationService.getShopperFullName(t),address:this.stripeIntegrationService.mapStripeAddress(t)}))})}_updateStripeBillingAddress(e){return pm(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getBillingAddress();t&&(yield e.updateBillingAddress({name:this.stripeIntegrationService.getShopperFullName(t),address:this.stripeIntegrationService.mapStripeAddress(t)}))})}_getStripeSavedPaymentMethodsOrThrow(e){return pm(this,void 0,void 0,function*(){if(null==e?void 0:e.savedPaymentMethods)return e.savedPaymentMethods;const t=yield this._getStripeActionsOrThrow(),{savedPaymentMethods:n}=yield t.getSession();return n||[]})}_getNewVaultedStripeInstrument(e,t){return t.find(t=>!e.some(e=>e.id===t.id))}_getTokenizedOptions(e,t){return(null==t?void 0:t.type)===Aa.ACH?{tokenized_ach:{token:e}}:{credit_card_token:{token:e}}}_initializeAdaptivePricingElement(e,t){const{initializationData:n}=t,{currencySelectorContainerId:i}=e;if(!(null==n?void 0:n.adaptivePricingEnabled))return;if(!i)throw new ri(ei.PaymentNotInitialized);const r=this._getCurrencySelectorElement();r&&(r.mount(`#${i}`),this._initAdaptivePricingEvents(r))}_getCurrencySelectorElement(){var e,t;return(null===(e=this.stripeCheckout)||void 0===e?void 0:e.getCurrencySelectorElement())||(null===(t=this.stripeCheckout)||void 0===t?void 0:t.createCurrencySelectorElement())}_initAdaptivePricingEvents(e){e.on(za.CHANGE,e=>pm(this,void 0,void 0,function*(){if(!e.value||!("currency"in e.value))return;const{currency:t}=this.paymentIntegrationService.getState().getCartOrThrow(),n=t.code.toLowerCase(),i=e.value.currency.toLowerCase();yield this.paymentIntegrationService.updatePaymentProviderCustomer({isCustomerCurrencySelected:n!==i,customerCurrency:i})}))}}const ym=vi(e=>{const t=new Ra(a());return new mm(e,t,new pd(e,t))},[{gateway:"stripeocs",id:"checkout_session"}]);var gm;!function(e){e.CARD_NUMBER="card-number",e.CVV="cvv",e.EXPIRY="expiry"}(gm||(gm={}));var vm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class fm{constructor(e,t,n){this.paymentIntegrationService=e,this.tdOnlineMartScriptLoader=t,this.formPoster=n,this.tdInputs=[{id:"ccNumber",fieldType:gm.CARD_NUMBER},{id:"ccCvv",fieldType:gm.CVV},{id:"ccExpiry",fieldType:gm.EXPIRY}]}initialize(e){return vm(this,void 0,void 0,function*(){const{methodId:t}=e;if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');this.tdOnlineMartClient=yield this.loadTDOnlineMartJs(),this.mountHostedFields(t)})}execute(e,t){return vm(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{null==e||e.unmount()}),Promise.resolve()}getPaymentPayloadOrThrow(e){return vm(this,void 0,void 0,function*(){const{methodId:t,paymentData:n}=e,{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:r=!1}=jd(n)?n:{},o={browser_info:ss(),shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r};if(jd(n)&&xd(n)&&n.instrumentId){const e=!!this.paymentIntegrationService.getState().getCartOrThrow().lineItems.digitalItems.length,i=!this.isTrustedVaultingInstrument(n.instrumentId)||e;return{methodId:t,paymentData:Object.assign(Object.assign(Object.assign({},o),{instrumentId:n.instrumentId}),i?{nonce:n.instrumentId}:{})}}let a;try{a=yield this.getTokenOrThrow()}catch(e){this.throwTokenizationError(e)}return{methodId:t,paymentData:Object.assign(Object.assign({},o),{nonce:a})}})}mountHostedFields(e){const t=this.getHostedFieldsOptions(),n=this.getTDOnlineMartClientOrThrow();this.tdInputs.forEach(i=>{const r=`${e}-${i.id}`;document.getElementById(r)&&(i.inputElement=n.create(i.fieldType,t),i.inputElement.mount(`#${r}`))})}loadTDOnlineMartJs(){return vm(this,void 0,void 0,function*(){return this.tdOnlineMartClient?this.tdOnlineMartClient:this.tdOnlineMartScriptLoader.load()})}getTokenOrThrow(){return new Promise((e,t)=>{this.getTDOnlineMartClientOrThrow().createToken(n=>{const{error:i,token:r}=n;if(i||!r)return t(i);e(r)})})}getTDOnlineMartClientOrThrow(){if(!this.tdOnlineMartClient)throw new ri(ei.PaymentNotInitialized);return this.tdOnlineMartClient}processWithAdditionalAction(e){return vm(this,void 0,void 0,function*(){if(!function(e){return pa(e)&&(t=e.body,Z(t)&&"object"==typeof t&&"errors"in t&&"three_ds_result"in t&&W(t.errors)&&ve(t.errors,{code:"three_d_secure_required"}));var t}(e))throw e;const{three_ds_result:t}=e.body,{acs_url:n,payer_auth_request:i,merchant_data:r}=t||{};if(!n||!i||!r)throw new co(["formUrl","threeDSSessionData","creq"]);return new Promise(e=>{this.formPoster.postForm(n,{threeDSSessionData:i,creq:r},e,"_top")})})}throwTokenizationError(e){if(!function(e){return"object"==typeof e&&null!==e&&"field"in e&&"type"in e&&"message"in e}(e))throw new ti(Xn.MissingPaymentToken);throw new Error(e.message)}getHostedFieldsOptions(){return{style:{error:{color:"#d14343"}},classes:{error:"form-input--error"}}}isTrustedVaultingInstrument(e){const t=this.paymentIntegrationService.getState().getInstruments(),n=null==t?void 0:t.find(t=>uc(t)&&t.bigpayToken===e);return!(uc(n)&&!n.trustedShippingAddress)}}class Sm{constructor(e,t=window){this.scriptLoader=e,this.tdOnlineMartWindow=t}load(){return e=this,t=void 0,i=function*(){if(this.tdOnlineMartWindow.customcheckout||(yield this.scriptLoader.loadScript("https://libs.na.bambora.com/customcheckout/1/customcheckout.js")),!this.tdOnlineMartWindow.customcheckout)throw new mi;return this.tdOnlineMartWindow.customcheckout()},new((n=void 0)||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())});var e,t,n,i}}const _m=vi(e=>new fm(e,new Sm(a()),Ee()),[{id:"tdonlinemart"}]);var wm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const Im="Payment cannot continue";let Cm;class bm extends tu{initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return wm(this,void 0,void 0,function*(){if(this._initializeOptions=e&&e.worldpay,!this._initializeOptions)throw new ri(ei.PaymentNotInitialized);return t.initialize.call(this,e)})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return wm(this,void 0,void 0,function*(){const{payment:i}=e;if(Cm=this._submitAdditionalAction(),!i)throw new co(["payment"]);try{return yield n.execute.call(this,e,t)}catch(e){return this._processAdditionalAction(e,i)}})}_processAdditionalAction(e,t){return wm(this,void 0,void 0,function*(){return pa(e)&&ve(e.body.errors,{code:"additional_action_required"})?new Promise((n,i)=>{const r=e=>wm(this,void 0,void 0,function*(){if(-1===e.origin.indexOf("cardinalcommerce.com"))return;if("string"!=typeof e.data||!this._isValidJsonWithSessionId(e.data))return i(new Error(Im));window.removeEventListener("message",r),o.remove();const a=JSON.parse(e.data),s=de({},t,{paymentData:{threeDSecure:{token:a.SessionId}}});try{n(yield Cm(s))}catch(e){if(!pa(e)||!ve(e.body.errors,{code:"three_d_secure_required"}))return i(e);if(!this._initializeOptions)return i(new ri(ei.PaymentNotInitialized));const{onLoad:t}=this._initializeOptions,n=this._createIframe(e.body.three_ds_result);try{t(n,()=>i(new Error("Payment was cancelled")))}catch(e){i(new Error(Im))}}});let o;window.addEventListener("message",r);try{o=this._createHiddenIframe(e.body)}catch(e){throw window.removeEventListener("message",r),new Error(Im)}}):Promise.reject(e)})}_createHiddenIframe(e){const t=document.createElement("iframe");if(document.body.appendChild(t),!t.contentWindow)throw new Error;t.id="worldpay_hosted_hidden_payment_page",t.height="0px",t.width="0px";const n=document.createElement("form"),i="collectionForm";n.id=i,n.name="devicedata",n.method="post";const r=e.additional_action_required.data.redirect_url;n.action=r;const o=document.createElement("input");o.name="Bin",o.type="hidden",o.value=e.provider_data.source_id,n.appendChild(o);const a=document.createElement("input");a.name="JWT",a.type="hidden",a.value=e.provider_data.data,n.appendChild(a);const s=document.createElement("button");s.type="submit",s.id="btnsubmit",n.appendChild(s),navigator.userAgent.match("Firefox")?t.srcdoc=n.outerHTML:t.contentWindow.document.body.appendChild(n);const d=document.createElement("script");return d.innerHTML=`\n document.getElementById('${i}').submit();\n `,t.contentWindow.document.body.appendChild(d),t}_createIframe(e){const t=document.createElement("form");t.id="challengeForm",t.method="POST",t.action=e.acs_url;const n=document.createElement("input");n.name="JWT",n.type="hidden",n.value=e.payer_auth_request,t.appendChild(n);const i=document.createElement("input");i.name="MD",i.type="hidden",i.value=`merchantSessionId=${e.merchant_data}`,t.appendChild(i);const r=document.createElement("script");r.type="text/javascript",r.innerHTML="window.onload = function() { document.getElementById('challengeForm').submit(); }";const o=document.createElement("iframe");return o.name="worldpay_hosted_payment_page",o.height="400",o.width="100%",o.srcdoc=`${t.outerHTML} ${r.outerHTML}`,o}_submitAdditionalAction(){if(this._shouldRenderHostedForm){if(!this._hostedForm)throw new ri(ei.PaymentNotInitialized);const e=this._hostedForm;return t=>wm(this,void 0,void 0,function*(){yield e.submit(t)})}return e=>wm(this,void 0,void 0,function*(){yield this._paymentIntegrationService.submitPayment(e)})}_isValidJsonWithSessionId(e){try{const t=JSON.parse(e);return!(!t.SessionId||!t.Status)}catch(e){return!1}}}const Pm=vi(e=>new bm(e),[{gateway:"worldpayaccess",id:"credit_card"},{id:"worldpayaccess"}]);class Om{constructor(e){this._paymentIntegrationService=e}execute({payment:e}){return t=this,n=void 0,r=function*(){if(!e)throw new co(["payment"]);yield this._paymentIntegrationService.submitOrder();try{yield this._paymentIntegrationService.submitPayment(this._buildOpenBankingSubmitPayment(e))}catch(e){if(this._isWorldpayAccessRedirectResponse(e)){const t=e.body.additional_action_required.data.redirect_url;return new Promise(()=>window.location.replace(t))}return Promise.reject(e)}},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}initialize(){return Promise.resolve()}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_buildOpenBankingSubmitPayment(e){const{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n}=jd(e.paymentData)?e.paymentData:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1};return Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{open_banking:{},vault_payment_instrument:t||!1,set_as_default_stored_instrument:n||!1}}})}_isWorldpayAccessRedirectResponse(e){var t,n;if("object"!=typeof e||null===e)return!1;const i=e;if(!i.body)return!1;const r=i.body;return"additional_action_required"===r.status&&!!(null===(n=null===(t=r.additional_action_required)||void 0===t?void 0:t.data)||void 0===n?void 0:n.redirect_url)}}const Em=vi(e=>new Om(e),[{id:"open_banking",gateway:"worldpayaccess"}]);class Am{constructor(e){this._requestSender=e}saveExternalId(e,t){return n=this,i=void 0,o=function*(){const n=`/api/storefront/payment/${e}/save-external-id`,i={headers:Object.assign({Accept:mr.JsonV1,"X-API-INTERNAL":hr},yr),body:{externalId:t,provider:e}};yield this._requestSender.post(n,i)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}class Tm{constructor(e,t){this.paymentIntegrationService=e,this.storefrontPaymentRequestSender=t}initialize(){return Promise.resolve()}execute(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rwindow.location.replace(d));throw e}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_prepareForReferredRegistration(e,t){return this.storefrontPaymentRequestSender.saveExternalId(e,t)}}const km=vi(e=>{const{getHost:t}=e.getState(),i=n({host:t()}),r=new Am(i);return new Tm(e,r)},[{id:"zip"},{id:"quadpay"}]);var Dm,Mm;!function(e){e.LoadCountriesRequested="LOAD_COUNTRIES_REQUESTED",e.LoadCountriesSucceeded="LOAD_COUNTRIES_SUCCEEDED",e.LoadCountriesFailed="LOAD_COUNTRIES_FAILED"}(Dm||(Dm={}));class zm{constructor(e){this._countryRequestSender=e}loadCountries(e){return m.create(t=>{t.next(l(Dm.LoadCountriesRequested)),this._countryRequestSender.loadCountries(e).then(e=>{t.next(l(Dm.LoadCountriesSucceeded,e.body.data)),t.complete()}).catch(e=>{t.error(h(Dm.LoadCountriesFailed,e))})})}}class Nm{constructor(e,t){this._requestSender=e,this._config=t}loadCountries({timeout:e}={}){const t=Object.assign({"Accept-Language":this._config.locale},Xe);return this._requestSender.get("/internalapi/v1/store/countries",{headers:t,timeout:e})}}class xm extends it{constructor(e){super(e||"Your checkout could not be processed because some details have changed. Please review your order and try again."),this.name="CartConsistencyError",this.type="cart_consistency"}}class Rm extends it{constructor(e,t){super(t||"At least one item changed stock position. Please review your cart and try again."),this.name="CartStockPositionsChangedError",this.type="cart_stock_positions_changed",this.changedItemIds=e}}class Fm extends it{constructor(e){super(e||"The tax provider is unavailable."),this.name="OrderTaxProviderUnavailableError",this.type="tax_provider_unavailable"}}class Lm extends it{constructor(e){super(e),this.name="MissingShippingMethodError",this.type="missing_shipping_method"}}class Bm extends it{constructor(e){super(e),this.name="InvalidShippingAddressError",this.type="invalid_shipping_address"}}class jm{constructor(e){this._requestSender=e}loadOrder(e,{timeout:t}={}){const n=`/api/storefront/orders/${e}`,i=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.get(n,{params:{include:Ft(["payments","lineItems.physicalItems.socialMedia","lineItems.physicalItems.options","lineItems.physicalItems.categories","lineItems.digitalItems.socialMedia","lineItems.digitalItems.options","lineItems.digitalItems.categories"])},headers:i,timeout:t})}submitOrder(e,{headers:t,timeout:n}={}){return this._requestSender.post("/internalapi/v1/checkout/order",{body:e,headers:ue(Object.assign({"X-Checkout-Variant":t&&t.checkoutVariant},Xe),J),timeout:n}).catch(e=>{var t,n;if("tax_provider_unavailable"===e.body.type)throw new Fm;if("cart_has_changed"===e.body.type)throw new xm;if("cart_stock_positions_changed"===e.body.type){const i=null!==(n=null===(t=e.body.errors)||void 0===t?void 0:t.changedItemIds)&&void 0!==n?n:[];throw new Rm(i)}if("missing_shipping_method"===e.body.type)throw new Lm(e.body.detail);if("invalid_shipping_address"===e.body.type)throw new Bm(e.body.detail);if("empty_cart"===e.body.type)throw new dt;throw e})}finalizeOrder(e,{timeout:t}={}){const n=`/internalapi/v1/checkout/order/${e}`;return this._requestSender.post(n,{timeout:t,headers:Xe})}}class Um extends it{constructor(){super("You haven't complete our spam check. Please try again."),this.name="SpamProtectionNotCompletedError",this.type="spam_protection_not_completed"}}!function(e){e.LoadOrderRequested="LOAD_ORDER_REQUESTED",e.LoadOrderSucceeded="LOAD_ORDER_SUCCEEDED",e.LoadOrderFailed="LOAD_ORDER_FAILED",e.LoadOrderPaymentsRequested="LOAD_ORDER_PAYMENTS_REQUESTED",e.LoadOrderPaymentsSucceeded="LOAD_ORDER_PAYMENTS_SUCCEEDED",e.LoadOrderPaymentsFailed="LOAD_ORDER_PAYMENTS_FAILED",e.SubmitOrderRequested="SUBMIT_ORDER_REQUESTED",e.SubmitOrderSucceeded="SUBMIT_ORDER_SUCCEEDED",e.SubmitOrderFailed="SUBMIT_ORDER_FAILED",e.FinalizeOrderRequested="FINALIZE_ORDER_REQUESTED",e.FinalizeOrderSucceeded="FINALIZE_ORDER_SUCCEEDED",e.FinalizeOrderFailed="FINALIZE_ORDER_FAILED"}(Mm||(Mm={}));var qm;class Vm{constructor(e,t){this._orderRequestSender=e,this._checkoutValidator=t}loadOrder(e,t){return new m(n=>{n.next(l(Mm.LoadOrderRequested)),this._orderRequestSender.loadOrder(e,t).then(e=>{n.next(l(Mm.LoadOrderSucceeded,e.body)),n.complete()}).catch(e=>{n.error(h(Mm.LoadOrderFailed,e))})})}loadOrderPayments(e,t){return new m(n=>{n.next(l(Mm.LoadOrderPaymentsRequested)),this._orderRequestSender.loadOrder(e,t).then(e=>{n.next(l(Mm.LoadOrderPaymentsSucceeded,e.body)),n.complete()}).catch(e=>{n.error(h(Mm.LoadOrderPaymentsFailed,e))})})}loadCurrentOrder(e){return t=>v(()=>{const n=this._getCurrentOrderId(t.getState());if(!n)throw new rt(et.MissingOrderId);return this.loadOrder(n,e)})}submitOrder(e,t){return n=>g(C(l(Mm.SubmitOrderRequested)),v(()=>{const i=n.getState(),r=i.config.getExternalSource(),o=i.config.getVariantIdentificationToken(),a=i.checkout.getCheckout();if(!a)throw new rt(et.MissingCheckout);if(a.shouldExecuteSpamCheck)throw new Um;return S(this._checkoutValidator.validate(a,t).then(()=>this._orderRequestSender.submitOrder(this._mapToOrderRequestBody(null!=e?e:{},a.id,a.customerMessage,r),Object.assign(Object.assign({},t),{headers:{checkoutVariant:o}})))).pipe(M(e=>g(this.loadOrder(e.body.data.order.orderId,t),C(l(Mm.SubmitOrderSucceeded,e.body.data,Object.assign(Object.assign({},e.body.meta),{token:e.headers.token}))))))}).pipe(P(e=>Je(Mm.SubmitOrderFailed,e))))}finalizeOrder(e,t){return g(C(l(Mm.FinalizeOrderRequested)),S(this._orderRequestSender.finalizeOrder(e,t)).pipe(M(n=>g(this.loadOrder(e,t),C(l(Mm.FinalizeOrderSucceeded,n.body.data)))))).pipe(P(e=>Je(Mm.FinalizeOrderFailed,e)))}_getCurrentOrderId(e){const t=e.order.getOrder(),n=e.checkout.getCheckout();return t&&t.orderId||n&&n.orderId}_mapToOrderRequestBody(e,t,n,i){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const n=e.config.getStoreConfig();n&&t.setHost(n.paymentSettings.bigpayBaseUrl)},e=>e.config.getStoreConfig()),t}!function(e){e.LoadPaymentMethodRequested="LOAD_PAYMENT_METHOD_REQUESTED",e.LoadPaymentMethodSucceeded="LOAD_PAYMENT_METHOD_SUCCEEDED",e.LoadPaymentMethodFailed="LOAD_PAYMENT_METHOD_FAILED",e.LoadPaymentMethodsRequested="LOAD_PAYMENT_METHODS_REQUESTED",e.LoadPaymentMethodsSucceeded="LOAD_PAYMENT_METHODS_SUCCEEDED",e.LoadPaymentMethodsFailed="LOAD_PAYMENT_METHODS_FAILED"}(qm||(qm={}));const Hm=e=>!!e;class Wm{constructor(e){this._requestSender=e}loadPaymentMethodsById(e,t){return n=>new m(i=>{var r;const o=null===(r=n.getState().cart.getCart())||void 0===r?void 0:r.id,a=o?Object.assign(Object.assign({},null==t?void 0:t.params),{cartId:o}):Object.assign({},null==t?void 0:t.params);i.next(l(qm.LoadPaymentMethodsRequested)),Promise.all(e.map(e=>{return n=this,i=void 0,o=function*(){try{return(yield this._requestSender.loadPaymentMethod(e,Object.assign(Object.assign({},t),{params:a}))).body}catch(e){return}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).then(e=>{const t=e.filter(Hm);i.next(l(qm.LoadPaymentMethodsSucceeded,t)),i.complete()}).catch(e=>{i.next(l(qm.LoadPaymentMethodsFailed,e)),i.complete()})})}loadPaymentMethods(e){return t=>m.create(n=>{const i=t.getState().cart.getCartOrThrow();n.next(l(qm.LoadPaymentMethodsRequested)),this._requestSender.loadPaymentMethods(Object.assign(Object.assign({},e),{params:Object.assign(Object.assign({},null==e?void 0:e.params),{cartId:i.id})})).then(e=>{const t={deviceSessionId:e.headers["x-device-session-id"],sessionHash:e.headers["x-session-hash"]},i=e.body;n.next(l(qm.LoadPaymentMethodsSucceeded,i,t)),n.complete()}).catch(e=>{n.error(h(qm.LoadPaymentMethodsFailed,e))})})}loadPaymentMethod(e,t){return n=>m.create(i=>{var r;const o=null===(r=n.getState().cart.getCart())||void 0===r?void 0:r.id,a=o?Object.assign(Object.assign({},null==t?void 0:t.params),{cartId:o}):Object.assign({},null==t?void 0:t.params);i.next(l(qm.LoadPaymentMethodRequested,void 0,{methodId:e})),this._requestSender.loadPaymentMethod(e,Object.assign(Object.assign({},t),{params:a})).then(t=>{i.next(l(qm.LoadPaymentMethodSucceeded,t.body,{methodId:e})),i.complete()}).catch(t=>{i.error(h(qm.LoadPaymentMethodFailed,t,{methodId:e}))})})}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([It],Wm.prototype,"loadPaymentMethod",null);class $m{constructor(e){this._requestSender=e}loadPaymentMethods({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/payments",{timeout:e,headers:Object.assign({Accept:ct.JsonV1,"X-API-INTERNAL":At},Xe),params:t})}loadPaymentMethod(e,{timeout:t,params:n}={}){const i=`/api/storefront/payments/${e}`;return this._requestSender.get(i,{timeout:t,headers:Object.assign({Accept:ct.JsonV1,"X-API-INTERNAL":At},Xe),params:n})}}class Ym extends it{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}var Km,Jm;!function(e){e.ExecuteFailed="PAYMENT_STRATEGY_EXECUTE_FAILED",e.ExecuteRequested="PAYMENT_STRATEGY_EXECUTE_REQUESTED",e.ExecuteSucceeded="PAYMENT_STRATEGY_EXECUTE_SUCCEEDED",e.FinalizeFailed="PAYMENT_STRATEGY_FINALIZE_FAILED",e.FinalizeRequested="PAYMENT_STRATEGY_FINALIZE_REQUESTED",e.FinalizeSucceeded="PAYMENT_STRATEGY_FINALIZE_SUCCEEDED",e.InitializeFailed="PAYMENT_STRATEGY_INITIALIZE_FAILED",e.InitializeRequested="PAYMENT_STRATEGY_INITIALIZE_REQUESTED",e.InitializeSucceeded="PAYMENT_STRATEGY_INITIALIZE_SUCCEEDED",e.DeinitializeFailed="PAYMENT_STRATEGY_DEINITIALIZE_FAILED",e.DeinitializeRequested="PAYMENT_STRATEGY_DEINITIALIZE_REQUESTED",e.DeinitializeSucceeded="PAYMENT_STRATEGY_DEINITIALIZE_SUCCEEDED",e.WidgetInteractionStarted="PAYMENT_STRATEGY_WIDGET_INTERACTION_STARTED",e.WidgetInteractionFinished="PAYMENT_STRATEGY_WIDGET_INTERACTION_FINISHED",e.WidgetInteractionFailed="PAYMENT_STRATEGY_WIDGET_INTERACTION_FAILED"}(Km||(Km={})),function(e){e.ADYENV2="adyenv2",e.ADYENV2_GOOGLEPAY="googlepayadyenv2",e.ADYENV3="adyenv3",e.ADYENV3_GOOGLEPAY="googlepayadyenv3",e.AFFIRM="affirm",e.AFTERPAY="afterpay",e.AUTHORIZENET_GOOGLE_PAY="googlepayauthorizenet",e.AMAZONPAY="amazonpay",e.APPLEPAY="applepay",e.BLUESNAPV2="bluesnapv2",e.BOLT="bolt",e.CBA_MPGS="cba_mpgs",e.CHECKOUTCOM="checkoutcom",e.CHECKOUTCOM_APM="checkoutcomapm",e.CHECKOUTCOM_FAWRY="checkoutcomfawry",e.CHECKOUTCOM_SEPA="checkoutcomsepa",e.CHECKOUTCOM_IDEAL="checkoutcomideal",e.CREDIT_CARD="creditcard",e.CHECKOUTCOM_GOOGLE_PAY="googlepaycheckoutcom",e.CLEARPAY="clearpay",e.CONVERGE="converge",e.CYBERSOURCE="cybersource",e.CYBERSOURCEV2="cybersourcev2",e.BNZ="bnz",e.BNZ_GOOGLEPAY="googlepaybnz",e.CYBERSOURCEV2_GOOGLE_PAY="googlepaycybersourcev2",e.HUMM="humm",e.KLARNA="klarna",e.KLARNAV2="klarnav2",e.LEGACY="legacy",e.MOLLIE="mollie",e.MONERIS="moneris",e.NO_PAYMENT_DATA_REQUIRED="nopaymentdatarequired",e.OFFLINE="offline",e.OFFSITE="offsite",e.ORBITAL_GOOGLE_PAY="googlepayorbital",e.PAYPAL_EXPRESS="paypalexpress",e.PAYPAL_EXPRESS_CREDIT="paypalexpresscredit",e.PAYPAL_COMMERCE="paypalcommerce",e.PAYPAL_COMMERCE_CREDIT="paypalcommercecredit",e.PAYPAL_COMMERCE_CREDIT_CARD="paypalcommercecreditcards",e.PAYPAL_COMMERCE_ALTERNATIVE_METHODS="paypalcommercealternativemethods",e.PAYPAL_COMMERCE_VENMO="paypalcommercevenmo",e.PPSDK="PAYMENT_TYPE_SDK",e.QUADPAY="quadpay",e.SAGE_PAY="sagepay",e.SQUARE="squarev2",e.STRIPEV3="stripev3",e.STRIPE_UPE="stripeupe",e.STRIPE_UPE_GOOGLE_PAY="googlepaystripeupe",e.BRAINTREE="braintree",e.BRAINTREE_PAYPAL="braintreepaypal",e.BRAINTREE_VENMO="braintreevenmo",e.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",e.BRAINTREE_VISA_CHECKOUT="braintreevisacheckout",e.BRAINTREE_GOOGLE_PAY="googlepaybraintree",e.WORLDPAYACCESS="worldpayaccess",e.WORLDPAYACCESS_GOOGLE_PAY="googlepayworldpayaccess",e.STRIPE_GOOGLE_PAY="googlepaystripe",e.SEZZLE="sezzle",e.ZIP="zip"}(Jm||(Jm={}));const Zm=Jm;class Qm{widgetInteraction(e,t){const n={methodId:t&&t.methodId};return g(C(l(Km.WidgetInteractionStarted,void 0,n)),v(()=>e().then(()=>l(Km.WidgetInteractionFinished,void 0,n)))).pipe(P(e=>Je(Km.WidgetInteractionFailed,e,n)))}}class Xm{constructor(e,t,n,i,r){this._strategyRegistry=e,this._strategyRegistryV2=t,this._orderActionCreator=n,this._spamProtectionActionCreator=i,this._paymentIntegrationService=r,this._paymentStrategyWidgetActionCreator=new Qm}execute(e,t){const{payment:n={},useStoreCredit:i}=e,r={methodId:n.methodId};return o=>{const{checkout:a}=o.getState(),{shouldExecuteSpamCheck:s}=a.getCheckoutOrThrow();return g(s?this._spamProtectionActionCreator.verifyCheckoutSpamProtection()(o):f(),C(l(Km.ExecuteRequested,void 0,r)),v(()=>{const a=o.getState();let s;if(a.payment.isPaymentDataRequired(i)){const e=a.paymentMethods.getPaymentMethod(n.methodId,n.gatewayId);if(!e)throw new rt(et.MissingPaymentMethod);s=this._getStrategy(e)}else s=this._strategyRegistryV2.get({id:Zm.NO_PAYMENT_DATA_REQUIRED});return s.execute(e,Object.assign(Object.assign({},t),{methodId:n.methodId,gatewayId:n.gatewayId})).then(()=>l(Km.ExecuteSucceeded,void 0,r))})).pipe(P(e=>Je(Km.ExecuteFailed,e,r)))}}finalize(e){const{integrations:t}=null!=e?e:{};return n=>g(C(l(Km.FinalizeRequested)),this._loadOrderPaymentsIfNeeded(n,e),v(()=>{return i=this,r=void 0,a=function*(){const i=n.getState(),{providerId:r="",gatewayId:o=""}=i.payment.getPaymentId()||{},a=i.paymentMethods.getPaymentMethod(r,o);if(!a)throw new Ym;let s;Zt(this._strategyRegistryV2,null!=t?t:[],this._paymentIntegrationService);try{s=this._getStrategy(a)}catch(e){throw new Ym}return yield s.finalize(Object.assign(Object.assign({},e),{methodId:a.id,gatewayId:a.gateway})),l(Km.FinalizeSucceeded,void 0,{methodId:a.id})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a})).pipe(P(e=>{const t=n.getState().payment.getPaymentId();return Je(Km.FinalizeFailed,e,{methodId:t&&t.providerId})}))}initialize(e){const{methodId:t,gatewayId:n,integrations:i}=e;return r=>v(()=>{const o=r.getState(),a=o.paymentMethods.getPaymentMethod(t,n);if(!a)throw new rt(et.MissingPaymentMethod);if(t&&o.paymentStrategies.isInitialized({methodId:t,gatewayId:n}))return f();Zt(this._strategyRegistryV2,null!=i?i:[],this._paymentIntegrationService);const s=this._getStrategy(a).initialize(Object.assign(Object.assign({},e),{methodId:t,gatewayId:n}));return g(C(l(Km.InitializeRequested,void 0,{methodId:t,gatewayId:n})),s.then(()=>l(Km.InitializeSucceeded,void 0,{methodId:t,gatewayId:n})))}).pipe(P(e=>Je(Km.InitializeFailed,e,{methodId:t,gatewayId:n})))}deinitialize(e){const{methodId:t,gatewayId:n}=e;return i=>v(()=>{const r=i.getState(),o=r.paymentMethods.getPaymentMethod(t,n);if(!o)throw new rt(et.MissingPaymentMethod);if(t&&!r.paymentStrategies.isInitialized({methodId:t,gatewayId:n}))return f();const a=this._getStrategy(o).deinitialize(Object.assign(Object.assign({},e),{methodId:t,gatewayId:n}));return g(C(l(Km.DeinitializeRequested,void 0,{methodId:t,gatewayId:n})),a.then(()=>l(Km.DeinitializeSucceeded,void 0,{methodId:t,gatewayId:n})))}).pipe(P(e=>Je(Km.DeinitializeFailed,e,{methodId:t,gatewayId:n})))}widgetInteraction(e,t){return this._paymentStrategyWidgetActionCreator.widgetInteraction(e,t)}_getStrategy(e){let t;try{t=this._strategyRegistry.getByMethod(e)}catch(n){try{t=this._strategyRegistryV2.get({id:e.id,gateway:e.gateway,type:e.type})}catch(t){throw wt().error(`[PaymentStrategyActionCreator] Unable to resolve V2 strategy for id: ${e.id}, gateway: ${e.gateway}, type: ${e.type}`),t}}return t}_loadOrderPaymentsIfNeeded(e,t){const n=e.getState().checkout.getCheckout();return n&&n.orderId?this._orderActionCreator.loadOrderPayments(n.orderId,t):f()}}class ey{isEqual(e,t){return Y(this._normalize(e),this._normalize(t))}_normalize(e){return{cartAmount:e.cartAmount,currency:e.currency,id:e.id,lineItems:{digitalItems:e.lineItems.digitalItems.slice().sort((e,t)=>`${e.productId}${e.variantId}`.localeCompare(`${t.productId}${t.variantId}`)).map(e=>({extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId})),giftCertificates:e.lineItems.giftCertificates.slice().sort((e,t)=>`${e.id}`.localeCompare(`${t.id}`)).map(e=>({amount:e.amount,recipient:e.recipient})),physicalItems:e.lineItems.physicalItems.slice().sort((e,t)=>`${e.productId}${e.variantId}`.localeCompare(`${t.productId}${t.variantId}`)).map(e=>({extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId,giftWrapping:e.giftWrapping}))}}}}class ty extends it{constructor(e,t){super("An update to your shopping cart has been detected and your available shipping costs have been updated."),this.name="CartChangedError",this.type="cart_changed",this.data={previous:e,updated:t}}}class ny{constructor(e){this._checkoutRequestSender=e}validate(e,t){if(!e)throw new rt(et.MissingCheckout);return this._checkoutRequestSender.loadCheckout(e.id,t).then(t=>{const n=new ey;if(!(e.outstandingBalance===t.body.outstandingBalance&&this._compareCoupons(e.coupons,t.body.coupons)&&this._compareGiftCertificates(e.giftCertificates,t.body.giftCertificates)&&n.isEqual(e.cart,t.body.cart)))throw new ty(this._getComparableCheckout(e),this._getComparableCheckout(t.body))})}_compareCoupons(e,t){return Y(oe(e,"code"),oe(t,"code"))}_compareGiftCertificates(e,t){return Y(oe(e,"code"),oe(t,"code"))}_getComparableCheckout(e){const{cart:t,coupons:n,giftCertificates:i,outstandingBalance:r}=e;return{cart:{cartAmount:t.cartAmount,currency:t.currency,lineItems:t.lineItems},coupons:n,giftCertificates:i,outstandingBalance:r}}}class iy{constructor(e){this._namespace=e}getItem(e){const t=Te.getItem(this.withNamespace(e));if(null===t)return null;try{return JSON.parse(t)}catch(t){return this.removeItem(this.withNamespace(e)),null}}getItemOnce(e){const t=this.getItem(e);return this.removeItem(e),t}setItem(e,t){return Te.setItem(this.withNamespace(e),JSON.stringify(t))}removeItem(e){return Te.removeItem(this.withNamespace(e))}withNamespace(e){return`${this._namespace}.${e}`}}class ry extends it{constructor(){super("Please complete our human verification challenge and try again."),this.name="CardingProtectionChallengeNotCompletedError",this.type="carding_protection_challenge_not_completed"}}class oy extends it{constructor(){super("We were not able to verify that you are not a robot. Please try again."),this.name="CardingProtectionFailedError",this.type="carding_protection_failed"}}var ay,sy,dy=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class cy{constructor(e){this._googleRecaptcha=e}handle(e,t){return dy(this,void 0,void 0,function*(){return"string"==typeof e?this.handleWithRecaptchaSitekey(e,t):this.handleWithPaymentHumanVerificationRequestError(e)})}handleWithPaymentHumanVerificationRequestError(e){return dy(this,void 0,void 0,function*(){if(!this._isPaymentHumanVerificationRequest(e))throw e;return yield this._initialize(e.body.additional_action_required.data.key),this._performRecaptcha()})}handleWithRecaptchaSitekey(e,t){return dy(this,void 0,void 0,function*(){if("recaptcha_v2"!==e)throw Error("Human verification method is not supported.");if(!t)throw Error("Recaptcha site key is missing.");return yield this._initialize(t),this._performRecaptcha()})}_performRecaptcha(){return this._googleRecaptcha.execute().pipe(z(1)).pipe(M(({error:e,token:t})=>dy(this,void 0,void 0,function*(){if(e instanceof sn)throw new ry;if(e||!t)throw new oy;return{type:"recaptcha_v2_verification",data:{human_verification_token:t}}}))).toPromise()}_initialize(e){const t="cardingProtectionContainer";let n=document.getElementById(t);return n&&n.parentNode&&n.parentNode.removeChild(n),n=document.createElement("div"),n.setAttribute("id",t),document.body.appendChild(n),this._googleRecaptcha.load(t,e)}_isPaymentHumanVerificationRequest(e){const{additional_action_required:t,status:n}=e.body||{};return"additional_action_required"===n&&t&&"recaptcha_v2_verification"===t.type}}function ly(e,t){const{body:n}=e,{errors:i=[]}=n;return new Ot(e,{message:uy(i)||t,errors:i})}function uy(e){if(Array.isArray(e))return e.reduce((e,t)=>t&&t.message?[...e,t.message]:e,[]).join(" ")}class hy extends it{constructor(e){super(e||"Unable to proceed due to invalid configuration provided for the hosted payment form."),this.name="InvalidHostedFormConfigError",this.type="invalid_hosted_form_config"}}class py extends it{constructor(e){super(e||"Unable to proceed due to an unknown error with the hosted payment form."),this.name="InvalidHostedFormError",this.type="invalid_hosted_form"}}class my extends it{constructor(e){super(["Unable to proceed due to invalid user input values",...U(Ce(e),e=>oe(e,({message:e})=>e))].join(". ")),this.errors=e,this.name="InvalidHostedFormValueError",this.type="invalid_hosted_form_value"}}!function(e){e.AttachRequested="HOSTED_FIELD:ATTACH_REQUESTED",e.SubmitRequested="HOSTED_FIELD:SUBMITTED_REQUESTED",e.ValidateRequested="HOSTED_FIELD:VALIDATE_REQUESTED",e.StoredCardRequested="HOSTED_FIELD:STORED_CARD_REQUESTED"}(ay||(ay={})),function(e){e.AttachSucceeded="HOSTED_INPUT:ATTACH_SUCCEEDED",e.AttachFailed="HOSTED_INPUT:ATTACH_FAILED",e.BinChanged="HOSTED_INPUT:BIN_CHANGED",e.Blurred="HOSTED_INPUT:BLURRED",e.Changed="HOSTED_INPUT:CHANGED",e.CardTypeChanged="HOSTED_INPUT:CARD_TYPE_CHANGED",e.Entered="HOSTED_INPUT:ENTERED",e.Focused="HOSTED_INPUT:FOCUSED",e.SubmitSucceeded="HOSTED_INPUT:SUBMIT_SUCCEEDED",e.SubmitFailed="HOSTED_INPUT:SUBMIT_FAILED",e.Validated="HOSTED_INPUT:VALIDATED",e.StoredCardSucceeded="HOSTED_INPUT:STORED_CARD_SUCCEEDED",e.StoredCardFailed="HOSTED_INPUT:STORED_CARD_FAILED"}(sy||(sy={}));var yy=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class gy{constructor(e,t,n,i,r,o,a,s,d,c){this._type=e,this._containerId=t,this._placeholder=n,this._accessibilityLabel=i,this._styles=r,this._eventPoster=o,this._eventListener=a,this._detachmentObserver=s,this._checkoutId=d,this._cardInstrument=c,this._iframe=document.createElement("iframe");const l=this._checkoutId?`/checkout/payment/hosted-field?version=1.909.5&checkoutId=${this._checkoutId}`:"/checkout/payment/hosted-field?version=1.909.5";this._iframe.src=l,this._iframe.style.border="none",this._iframe.style.height="100%",this._iframe.style.overflow="hidden",this._iframe.style.width="100%"}getType(){return this._type}attach(){return yy(this,void 0,void 0,function*(){const e=document.getElementById(this._containerId);if(!e)throw new hy("Unable to proceed because the provided container ID is not valid.");e.appendChild(this._iframe),this._eventListener.listen();const t=_(this._iframe,"load").pipe(M(({target:e})=>yy(this,void 0,void 0,function*(){const t=e&&e.contentWindow;if(!t)throw new Error("The content window of the iframe cannot be accessed.");this._eventPoster.setTarget(t),yield this._eventPoster.post({type:ay.AttachRequested,payload:{accessibilityLabel:this._accessibilityLabel,cardInstrument:this._cardInstrument,fontUrls:this._getFontUrls(),placeholder:this._placeholder,styles:this._styles,origin:document.location.origin,type:this._type}},{successType:sy.AttachSucceeded,errorType:sy.AttachFailed})})),z(1)).toPromise();yield this._detachmentObserver.ensurePresence([this._iframe],t)})}detach(){this._iframe.parentElement&&(this._iframe.parentElement.removeChild(this._iframe),this._eventListener.stopListen())}submitForm(e,t){return yy(this,void 0,void 0,function*(){try{const n=this._eventPoster.post({type:ay.SubmitRequested,payload:{fields:e,data:t}},{successType:sy.SubmitSucceeded,errorType:sy.SubmitFailed});return yield this._detachmentObserver.ensurePresence([this._iframe],n)}catch(e){if(this._isSubmitErrorEvent(e)){if("hosted_form_error"===e.payload.error.code)throw new py(e.payload.error.message);if(e.payload.response)throw ly(e.payload.response);throw new Error(e.payload.error.message)}throw e}})}submitStoredCardForm(e,t){return yy(this,void 0,void 0,function*(){const n=this._eventPoster.post({type:ay.StoredCardRequested,payload:{fields:e,data:t}},{successType:sy.StoredCardSucceeded,errorType:sy.StoredCardFailed});return this._detachmentObserver.ensurePresence([this._iframe],n)})}validateForm(){return yy(this,void 0,void 0,function*(){const e=this._eventPoster.post({type:ay.ValidateRequested},{successType:sy.Validated}),{payload:t}=yield this._detachmentObserver.ensurePresence([this._iframe],e);if(!t.isValid)throw new my(t.errors)})}_getFontUrls(){const e="fonts.googleapis.com",t=document.querySelectorAll(`link[href*='${e}'][rel='stylesheet']`);return Array.prototype.slice.call(t).filter(t=>In(t.href).hostname===e).filter(e=>Ce(this._styles).map(e=>e&&e.fontFamily).filter(e=>"string"==typeof e).some(t=>t.split(/,\s/).some(t=>-1!==e.href.indexOf(t.replace(" ","+"))))).map(e=>e.href)}_isSubmitErrorEvent(e){return e.type===sy.SubmitFailed}}var vy,fy=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Sy{constructor(e,t,n,i,r){this._fields=e,this._eventListener=t,this._payloadTransformer=n,this._eventCallbacks=i,this._paymentHumanVerificationHandler=r,this._handleEnter=({payload:e})=>fy(this,void 0,void 0,function*(){try{yield this.validate()}catch(e){if(e instanceof Error&&"InvalidHostedFormValueError"!==e.name)throw e}const{onEnter:t=ce}=this._eventCallbacks;t(e)});const{onBlur:o=ce,onCardTypeChange:a=ce,onFocus:s=ce,onValidate:d=ce}=this._eventCallbacks;this._eventListener.addListener(sy.Blurred,({payload:e})=>o(e)),this._eventListener.addListener(sy.CardTypeChanged,({payload:e})=>a(e)),this._eventListener.addListener(sy.Focused,({payload:e})=>s(e)),this._eventListener.addListener(sy.Validated,({payload:e})=>d(e)),this._eventListener.addListener(sy.Entered,this._handleEnter),this._eventListener.addListener(sy.CardTypeChanged,({payload:e})=>this._cardType=e.cardType),this._eventListener.addListener(sy.BinChanged,({payload:e})=>this._bin=e.bin)}getBin(){return this._bin}getCardType(){return this._cardType}attach(){return fy(this,void 0,void 0,function*(){this._eventListener.listen();const e=this._getFirstField(),t=be(this._fields,e);yield e.attach(),yield Promise.all(t.map(e=>e.attach()))})}detach(){this._eventListener.stopListen(),this._fields.forEach(e=>{e.detach()})}submit(e,t){return fy(this,void 0,void 0,function*(){try{return yield this._getFirstField().submitForm(this._fields.map(e=>e.getType()),this._payloadTransformer.transform(e,t))}catch(t){const n=yield this._paymentHumanVerificationHandler.handle(t);return yield this._getFirstField().submitForm(this._fields.map(e=>e.getType()),this._payloadTransformer.transform(e,n))}})}submitStoredCard(e){return fy(this,void 0,void 0,function*(){return this._getFirstField().submitStoredCardForm(e.fields,e.data)})}validate(){return fy(this,void 0,void 0,function*(){return this._getFirstField().validateForm()})}_getFirstField(){const e=this._fields[0];if(!e)throw new hy("Unable to proceed because the payment form has no field defined.");return e}}function _y(e){return Boolean(e.instrumentId)}class wy{constructor(e){this._store=e}transform(e,t){const n=this._store.getState(),i=n.checkout.getCheckout(),r=n.config.getConfig(),o=n.instruments.getInstrumentsMeta(),a=n.order.getOrder(),s=n.order.getOrderMeta(),d=le(e.paymentData,"ccExpiry","ccName","ccNumber","ccCvv");let c=n.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId);"worldpayaccess"===(null==c?void 0:c.gateway)&&"credit_card"===(null==c?void 0:c.id)&&(c=Object.assign(Object.assign({},c),{id:"worldpayaccess",method:"credit-card"}));const l=n.paymentMethods.getPaymentMethodsMeta(),u=o&&d&&_y(d)?`${n.payment.getPaymentToken()}, ${o.vaultAccessToken}`:n.payment.getPaymentToken();if(!u)throw new rt(et.MissingPaymentToken);return{additionalAction:t,authToken:u,checkout:i,config:r,order:a,orderMeta:s,payment:d,paymentMethod:c,paymentMethodMeta:l}}}class Iy{constructor(e){this._store=e}create(e,t,n){const i=Object.keys(t.fields).reduce((i,r)=>{const o=t.fields[r];return o?[...i,new gy(r,o.containerId,o.placeholder||"",o.accessibilityLabel||"",t.styles||{},new Pn(e),new Yn(e),new kn(new mn),n,"instrumentId"in o?this._getCardInstrument(o.instrumentId):void 0)]:i},[]);return new Sy(i,new Yn(e),new wy(this._store),pe(t,"onBlur","onEnter","onFocus","onCardTypeChange","onValidate"),new cy(Sn(o())))}_getCardInstrument(e){const{instruments:{getCardInstrument:t}}=this._store.getState(),n=t(e);if(!n)throw new rt(et.MissingPaymentInstrument);return n}}!function(e){e.SubmitPaymentRequested="SUBMIT_PAYMENT_REQUESTED",e.SubmitPaymentSucceeded="SUBMIT_PAYMENT_SUCCEEDED",e.SubmitPaymentFailed="SUBMIT_PAYMENT_FAILED",e.InitializeOffsitePaymentRequested="INITIALIZE_OFFSITE_PAYMENT_REQUESTED",e.InitializeOffsitePaymentSucceeded="INITIALIZE_OFFSITE_PAYMENT_SUCCEEDED",e.InitializeOffsitePaymentFailed="INITIALIZE_OFFSITE_PAYMENT_FAILED"}(vy||(vy={}));class Cy{constructor(e,t,n,i){this._paymentRequestSender=e,this._orderActionCreator=t,this._paymentRequestTransformer=n,this._paymentHumanVerificationHandler=i,this.initializeOffsitePayment=({methodId:e,gatewayId:t,instrumentId:n,target:i,promise:r,shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a})=>s=>{let d;n?d={formattedPayload:{bigpay_token:n}}:o&&(d={formattedPayload:{vault_payment_instrument:o,set_as_default_stored_instrument:a||null}});const c=this._paymentRequestTransformer.transform({gatewayId:t,methodId:e,paymentData:d},s.getState());return g(C(l(vy.InitializeOffsitePaymentRequested)),Promise.race([this._paymentRequestSender.initializeOffsitePayment(c,i),r].filter(Boolean)).then(()=>l(vy.InitializeOffsitePaymentSucceeded))).pipe(P(e=>Je(vy.InitializeOffsitePaymentFailed,e)))}}submitPayment(e){return t=>g(C(l(vy.SubmitPaymentRequested)),v(()=>{return n=this,i=void 0,o=function*(){try{return yield this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(e,t.getState()))}catch(n){const i=yield this._paymentHumanVerificationHandler.handle(n);return yield this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(Object.assign(Object.assign({},e),{additionalAction:i}),t.getState()))}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}).pipe(M(({body:e})=>g(this._orderActionCreator.loadCurrentOrder()(t),C(l(vy.SubmitPaymentSucceeded,e)))))).pipe(P(e=>Je(vy.SubmitPaymentFailed,e)))}}class by{constructor(e){this._client=e}submitPayment(e){return new Promise((t,n)=>{this._client.submitPayment(e,(e,i)=>{e?n(this._transformResponse(e)):t(this._transformResponse(i))})})}initializeOffsitePayment(e,t){return new Promise(()=>{this._client.initializeOffsitePayment(e,null,t)})}_transformResponse(e){return{headers:e.headers,body:e.data,status:e.status,statusText:e.statusText}}}function Py(e,t){let n;return function(e){return void 0!==e.id}(e)?n=e.id:t&&t.length&&(n=t[0].id),{id:n,firstName:e.firstName,lastName:e.lastName,company:e.company,addressLine1:e.address1,addressLine2:e.address2,city:e.city,province:e.stateOrProvince,provinceCode:e.stateOrProvinceCode,postCode:e.postalCode,country:e.country,countryCode:e.countryCode,phone:e.phone,customFields:e.customFields}}const Oy=["per_item_discount","percentage_discount","per_total_discount","shipping_discount","free_shipping"];function Ey(e){return{code:e.code,discount:e.displayName,discountType:Oy.indexOf(e.couponType)}}function Ay(e){return{code:e.code,discountedAmount:e.used,remainingBalance:e.remaining,giftCertificate:{balance:e.balance,code:e.code,purchaseDate:e.purchaseDate}}}function Ty(e){const t=[];return(e||[]).forEach(e=>{(e.banners||[]).forEach(e=>{t.push({placeholders:[],discountType:null,message:"",messageHtml:e.text})})}),t}function ky(e,t,n="id"){return Object.keys(e).reduce((i,r)=>[...i,...e[r].map(e=>"giftCertificates"===r?function(e,t){const n=new fd(t);return{id:e.id,imageUrl:"",name:e.name,amount:e.amount,amountAfterDiscount:e.amount,discount:0,integerAmount:n.toInteger(e.amount),integerAmountAfterDiscount:n.toInteger(e.amount),integerUnitPrice:n.toInteger(e.amount),integerUnitPriceAfterDiscount:n.toInteger(e.amount),integerDiscount:0,quantity:1,sender:e.sender,recipient:e.recipient,type:"ItemGiftCertificateEntity",attributes:[],variantId:null}}(e,t):function(e,t,n,i="id"){const r=new fd(n);return{id:e[i],imageUrl:e.imageUrl,amount:e.extendedListPrice,amountAfterDiscount:e.extendedSalePrice,discount:e.discountAmount,integerAmount:r.toInteger(e.extendedListPrice),integerAmountAfterDiscount:r.toInteger(e.extendedSalePrice),integerDiscount:r.toInteger(e.discountAmount),integerUnitPrice:r.toInteger(e.listPrice),integerUnitPriceAfterDiscount:r.toInteger(e.salePrice),downloadsPageUrl:e.downloadPageUrl,name:e.name,quantity:e.quantity,brand:e.brand,sku:e.sku,categoryNames:e.categoryNames,variantId:e.variantId,productId:e.productId,attributes:(e.options||[]).map(e=>({name:e.name,value:e.value})),addedByPromotion:e.addedByPromotion,type:t}}(e,function(e){switch(e){case"physicalItems":return"ItemPhysicalEntity";case"digitalItems":return"ItemDigitalEntity";case"giftCertificates":return"ItemGiftCertificateEntity";default:return""}}(r),t,n))],[])}function Dy(e){const t=e.cart.currency.decimalPlaces,n=new fd(t);return{id:e.cart.id,items:ky(e.cart.lineItems,t),currency:e.cart.currency.code,coupon:{discountedAmount:ye(e.cart.coupons,(e,t)=>e+t.discountedAmount,0),coupons:e.cart.coupons.map(Ey)},discount:{amount:e.cart.discountAmount,integerAmount:n.toInteger(e.cart.discountAmount)},discountNotifications:Ty(e.promotions),giftCertificate:{totalDiscountedAmount:ye(e.giftCertificates,(e,t)=>e+t.used,0),appliedGiftCertificates:ne(e.giftCertificates.map(Ay),"code")},shipping:{amount:e.shippingCostTotal,integerAmount:n.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:n.toInteger(e.shippingCostBeforeDiscount),required:ve(e.cart.lineItems.physicalItems,e=>e.isShippingRequired)},subtotal:{amount:e.subtotal,integerAmount:n.toInteger(e.subtotal)},storeCredit:{amount:e.customer?e.customer.storeCredit:0},taxSubtotal:{amount:e.taxTotal,integerAmount:n.toInteger(e.taxTotal)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:n.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:n.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.grandTotal,integerAmount:n.toInteger(e.grandTotal)}}}var My;!function(e){e.APPLEPAY="applepay",e.AMAZON_PAY_V2="amazonpay",e.BRAINTREE_PAYPAL="braintreepaypal",e.BRAINTREE_VENMO="braintreevenmo",e.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",e.GOOGLEPAY_ADYENV2="googlepayadyenv2",e.GOOGLEPAY_ADYENV3="googlepayadyenv3",e.GOOGLEPAY_AUTHORIZENET="googlepayauthorizenet",e.GOOGLEPAY_BNZ="googlepaybnz",e.GOOGLEPAY_BRAINTREE="googlepaybraintree",e.GOOGLEPAY_CHECKOUTCOM="googlepaycheckoutcom",e.GOOGLEPAY_CYBERSOURCEV2="googlepaycybersourcev2",e.GOOGLEPAY_ORBITAL="googlepayorbital",e.GOOGLEPAY_STRIPE="googlepaystripe",e.GOOGLEPAY_STRIPEUPE="googlepaystripeupe",e.GOOGLEPAY_WORLDPAYACCESS="googlepayworldpayaccess",e.PAYPALEXPRESS="paypalexpress"}(My||(My={}));const zy=My;function Ny(e,t){const n=e.firstName||t.firstName||"",i=e.lastName||t.lastName||"";return{addresses:(e.addresses||[]).map(e=>Py(e)),customerId:e.id,isGuest:e.isGuest,storeCredit:e.storeCredit,email:e.email||t.email||"",firstName:n,lastName:i,name:e.fullName||[n,i].join(" "),customerGroupName:e.customerGroup&&e.customerGroup.name}}class xy{format(e){const[t="",n=""]=e.split(new RegExp("\\s*/\\s*")),i=t.slice(0,2),r=4===n.length?n.slice(-2):n?n.slice(0,2):t.slice(2);return e.length<2?t:e.length>3&&!r?i:`${i} / ${r}`}toObject(e){const[t="",n=""]=e.split(new RegExp("\\s*/\\s*"));return/^\d+$/.test(t)&&/^\d+$/.test(n)?{month:1===t.length?`0${t}`:t.slice(0,2),year:2===n.length?`20${n}`:n.slice(0,4)}:{month:"",year:""}}}class Ry{format(e){const{card:t}=Me(e);if(!t)return e;const n=ae(De(e).map(e=>ae(e.lengths))),i=this.unformat(e).slice(0,n);return t.gaps.filter(e=>i.length>e).reduce((e,t,n)=>[e.slice(0,t+n),e.slice(t+n)].join(" "),i)}unformat(e){const{card:t}=Me(e);return t?e.replace(new RegExp(" ","g"),""):e}}function Fy(e,t={}){const n=e.currency.decimalPlaces,i=new fd(n);return{id:e.orderId,items:ky(e.lineItems,e.currency.decimalPlaces,"productId"),orderId:e.orderId,currency:e.currency.code,customerCanBeCreated:e.customerCanBeCreated,payment:jy(e.payments,t.payment),subtotal:{amount:e.baseAmount,integerAmount:i.toInteger(e.baseAmount)},coupon:{discountedAmount:ye(e.coupons,(e,t)=>e+t.discountedAmount,0),coupons:e.coupons.map(Ey)},discount:{amount:e.discountAmount,integerAmount:i.toInteger(e.discountAmount)},token:t.orderToken,callbackUrl:t.callbackUrl,discountNotifications:[],giftCertificate:By(e.payments),socialData:qy(e),status:e.status,hasDigitalItems:e.hasDigitalItems,isDownloadable:e.isDownloadable,isComplete:e.isComplete,shipping:{amount:e.shippingCostTotal,integerAmount:i.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:i.toInteger(e.shippingCostBeforeDiscount)},storeCredit:{amount:Ly(e.payments)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:i.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:i.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.orderAmount,integerAmount:e.orderAmountAsInteger}}}function Ly(e){const t=B(e,{providerId:"storecredit"});return t?t.amount:0}function By(e){const t=L(e,{providerId:"giftcertificate"});return{totalDiscountedAmount:ye(t,(e,t)=>t.amount+e,0),appliedGiftCertificates:ne(t.map(e=>({code:e.detail.code,discountedAmount:e.amount,remainingBalance:e.detail.remaining,giftCertificate:{balance:e.amount+e.detail.remaining,code:e.detail.code,purchaseDate:""}})),"code")}}function jy(e,t={}){const n=B(e,Uy);return n?{id:n.providerId,status:(i=n.detail.step,`PAYMENT_STATUS_${i}`),helpText:n.detail.instructions,returnUrl:t.returnUrl}:{};var i}function Uy(e){return"giftcertificate"!==e.providerId&&"storecredit"!==e.providerId}function qy(e){const t={};return[...e.lineItems.physicalItems,...e.lineItems.digitalItems].forEach(e=>{var n;t[e.id]=(n=e,["fb","tw","gp"].reduce((e,t)=>{const i=n.socialMedia&&B(n.socialMedia,e=>e.code===t);return i?(e[t]={name:n.name,description:n.name,image:n.imageUrl,url:i.link,shareText:i.text,sharingLink:i.link,channelName:i.channel,channelCode:i.code},e):e},{}))}),t}function Vy(e,t){return{description:e.description,module:e.type,price:e.cost,id:e.id,selected:t,isRecommended:e.isRecommended,imageUrl:e.imageUrl,transitTime:e.transitTime}}class Gy{constructor(){this._cardExpiryFormatter=new xy,this._cardNumberFormatter=new Ry}transform(e,t){const n=t.billingAddress.getBillingAddress(),i=t.checkout.getCheckout(),r=t.customer.getCustomer(),o=t.order.getOrder(),a=t.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId),s=this._mapShippingAddress(t,a),d=t.consignments.getConsignments(),c=t.consignments.getShippingOption(),l=t.config.getStoreConfig(),u=t.config.getContextConfig(),h=t.instruments.getInstrumentsMeta(),p=t.paymentMethods.getPaymentMethodsMeta(),m=t.order.getOrderMeta(),y=r&&n&&Ny(r,n),g=h&&e.paymentData&&(_y(e.paymentData)||function(e){const t=e.formattedPayload;return!!t&&("string"==typeof t.bigpay_token||Boolean(t.bigpay_token&&t.bigpay_token.token))}(e.paymentData))?`${t.payment.getPaymentToken()}, ${h.vaultAccessToken}`:t.payment.getPaymentToken();if(!g)throw new rt(et.MissingPaymentToken);return{additionalAction:e.additionalAction,authToken:g,customer:y,billingAddress:n&&Py(n),shippingAddress:s&&Py(s,d),shippingOption:c&&Vy(c,!0),cart:i&&Dy(i),order:o&&Fy(o,m),orderMeta:m,payment:e.paymentData,paymentMethod:a&&this._transformPaymentMethod(a),quoteMeta:{request:Object.assign(Object.assign({},p),{geoCountryCode:u&&u.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:pe(l&&l.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}}transformWithHostedFormData(e,t,n){const{additionalAction:i,authToken:r,checkout:o,config:a,order:s,orderMeta:d,payment:c={},paymentMethod:l,paymentMethodMeta:u}=t,h=o&&o.consignments[0],p=h&&h.shippingAddress,m=h&&h.selectedShippingOption;return{additionalAction:i,authToken:r,paymentMethod:l&&this._transformPaymentMethod(l),customer:s&&s.billingAddress&&o&&Ny(o.customer,s.billingAddress),billingAddress:s&&s.billingAddress&&Py(s.billingAddress),shippingAddress:p&&o&&Py(p,o.consignments),shippingOption:m&&Vy(m,!0),cart:o&&Dy(o),order:s&&Fy(s,d),orderMeta:d,payment:this._transformHostedInputValues(e,c,n),quoteMeta:{request:Object.assign(Object.assign({},u),{geoCountryCode:a&&a.context.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:a&&pe(a.storeConfig.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}}_transformPaymentMethod(e){if("multi-option"===e.method&&!e.gateway)return Object.assign(Object.assign({},e),{gateway:e.id});if(e.initializationData&&e.initializationData.gateway)return Object.assign(Object.assign({},e),{id:e.initializationData.gateway});if("worldpayaccess"===e.gateway){if("credit_card"===e.id)return Object.assign(Object.assign({},e),{id:"worldpayaccess",method:"credit-card"});if("open_banking"===e.id)return Object.assign(Object.assign({},e),{id:"worldpayaccess",method:"open_banking"})}return e.id===zy.BRAINTREE_VENMO?Object.assign(Object.assign({},e),{id:zy.BRAINTREE_PAYPAL}):e}_transformHostedInputValues(e,t,n){return"instrumentId"in t?Object.assign(Object.assign({},t),{ccCvv:e.cardCodeVerification,ccNumber:e.cardNumberVerification&&this._cardNumberFormatter.unformat(e.cardNumberVerification),hostedFormNonce:n}):Object.assign(Object.assign({},t),{ccCvv:e.cardCode,ccExpiry:this._cardExpiryFormatter.toObject(e.cardExpiry||""),ccName:e.cardName||"",ccNumber:this._cardNumberFormatter.unformat(e.cardNumber||""),hostedFormNonce:n})}_mapShippingAddress(e,t){var n,i,r,o;if(t){const a=null===(i=null===(n=t.initializationData)||void 0===n?void 0:n.bopis)||void 0===i?void 0:i.enabled,s=null===(o=null===(r=t.initializationData)||void 0===r?void 0:r.bopis)||void 0===o?void 0:o.requiredAddress,d=e.consignments.getConsignments(),c=null==d?void 0:d.every(e=>e.selectedPickupOption);if(a&&c&&"none"===s)return}return e.shippingAddress.getShippingAddress()}}const Hy=e=>{const{type:t,initializationStrategy:n}=e;return t===Zm.PPSDK&&"string"==typeof(null==n?void 0:n.type)};class Wy extends Vt{getByMethod(e){if(!e)return this.get();const t=this._getToken(e),n=[e.gateway,e.id].filter(e=>null!=e).join("-");return this.get(t,n)}_getToken(e){if(Hy(e))return Zm.PPSDK;if("klarna"===e.gateway)return Zm.KLARNAV2;const t=e.gateway||e.id;if(this._hasFactoryForMethod(t))return t;if("PAYMENT_TYPE_OFFLINE"===e.type)return Zm.OFFLINE;throw new qt(`'${t}' is not registered.`)}_hasFactoryForMethod(e){return this._hasFactory(e)}}const $y="FINALIZE";class Yy extends qt{constructor(e){let t="Unable to submit payment for the order because the payload is invalid.";e&&(t=`${t} Make sure the following fields are provided correctly: ${e.join(", ")}.`),super(t),this.name="PaymentArgumentInvalidError"}}var Ky=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r(this._shouldRenderHostedForm=!0,this._hostedForm=r,this._store.getState()))}deinitialize(e){return this._hostedForm&&this._hostedForm.detach(),Promise.resolve(this._store.getState())}_executeWithoutHostedForm(e,t){const{payment:n}=e,i=Ky(e,["payment"]),r=n&&n.paymentData;if(!n||!r)throw new Yy(["payment.paymentData"]);return this._store.dispatch(this._orderActionCreator.submitOrder(i,t)).then(()=>this._store.dispatch(this._paymentActionCreator.submitPayment(Object.assign(Object.assign({},n),{paymentData:r}))))}_executeWithHostedForm(e,t){const{payment:n}=e,i=Ky(e,["payment"]),r=this._hostedForm;if(!r)throw new yn(cn.PaymentNotInitialized);if(!n||!n.methodId)throw new Yy(["payment.methodId"]);return r.validate().then(()=>this._store.dispatch(this._orderActionCreator.submitOrder(i,t))).then(()=>r.submit(n)).then(()=>this._store.dispatch(this._orderActionCreator.loadCurrentOrder()))}_isHostedPaymentFormEnabled(e,t){if(!e)return!1;const{paymentMethods:{getPaymentMethodOrThrow:n}}=this._store.getState();return!0===n(e,t).config.isHostedFormEnabled}_isHostedFieldAvailable(e){return!Ce(e&&e.creditCard&&e.creditCard.form.fields).every(J)}}class Zy extends Jy{constructor(e,t,n,i,r){super(e,t,n,i),this._formPoster=r}execute(e,t){return super.execute(e,t).catch(e=>e instanceof Ot&&ve(e.body.errors,{code:"three_d_secure_required"})?new Promise(()=>{this._formPoster.postForm(e.body.three_ds_result.acs_url,{PaReq:e.body.three_ds_result.payer_auth_request,TermUrl:e.body.three_ds_result.callback_url,MD:e.body.three_ds_result.merchant_data})}):Promise.reject(e))}finalize(e){const t=this._store.getState(),n=t.order.getOrder();return n&&t.payment.getPaymentStatus()===$y?this._store.dispatch(this._orderActionCreator.finalizeOrder(n.orderId,e)):Promise.reject(new Ym)}}class Qy extends it{constructor(e){super(e||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}const Xy="redirecting";class eg{constructor(){this._isRedirecting=this.currentUrlHasRedirectingParam()}isRedirecting(){return this._isRedirecting}setRedirecting(e){e?this.setRedirectingParamOnUrl():this.removeRedirectingParamFromUrl(),this._isRedirecting=e}currentUrlHasRedirectingParam(){return Xy in this.getCurrentUrl().query}getCurrentUrl(){return Ne(window.location.href)}replaceCurrentUrl(e){window.history.replaceState(null,"",e)}setRedirectingParamOnUrl(){if(this.currentUrlHasRedirectingParam())return;const e=this.getCurrentUrl(),t=Object.assign(Object.assign({},e),{query:Object.assign(Object.assign({},e.query),{[Xy]:"true"})});this.replaceCurrentUrl(xe(t))}removeRedirectingParamFromUrl(){this.currentUrlHasRedirectingParam()&&this.replaceCurrentUrl(ze(window.location.href,[Xy]))}}const tg=he([e=>"continue"===V(e,"type")&&"redirect"===V(e,"code")&&(e=>{const t=V(e,"form_fields");return X(V(e,"url"))&&(ee(t)||Z(t))})(V(e,"parameters")),e=>"continue"===V(e,"type")&&"resubmit_with_human_verification"===V(e,"code")&&(e=>{const t=V(e,"available_methods");return W(t)})(V(e,"parameters"))]);class ng{constructor(e,t){this._formPoster=e,this._humanVerificationHandler=t}handle(e,t){switch(e.code){case"redirect":return(({url:e,form_fields:t},n)=>{const i=new eg;return i.isRedirecting()?(i.setRedirecting(!1),Promise.reject(new Qy)):(i.setRedirecting(!0),t?n.postForm(e,t):window.location.assign(e),new Promise(ce))})(e.parameters,this._formPoster);case"resubmit_with_human_verification":return(({available_methods:e},t,n)=>{return i=void 0,r=void 0,a=function*(){if(!n)throw new Error("PPSDK human verification callback function is missing.");if(!t)throw new Error("PPSDK human verification handler is missing.");if(0===e.length)throw Error("Human verification method is missing.");const{id:i,parameters:r}=e[0],o=yield t.handle(i,r.key);return n(o)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a})(e.parameters,this._humanVerificationHandler,null==t?void 0:t.humanVerification)}}}class ig{constructor(e){this._continueHandler=e}handle(e,t){const{body:n}=e;return(e=>"success"===V(e,"type"))(n)?Promise.resolve():(e=>tg(e))(n)?this._continueHandler.handle(n,null==t?void 0:t.continue):(e=>"failure"===V(e.body,"type")&&X(V(e.body,"code")))(e)?(e=>{return Promise.reject(new Ot((t=e,Object.assign(Object.assign({},t),{body:{errors:[{code:t.body.code}]}}))));var t})(e):((e=>{V(e.body,"type")})(e),(e=>Promise.reject(new Ot(e)))(e))}}const rg="completed-payments";class og{constructor(e){this._browserStorage=e}isCompleted(e){return this.getCompletedPayments().indexOf(e)>=0}setCompleted(e){const t=this.getCompletedPayments();t.push(e),this.setCompletedPayments(t)}getCompletedPayments(){return this._browserStorage.getItem(rg)||[]}setCompletedPayments(e){this._browserStorage.setItem(rg,e)}}var ag,sg=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class dg{constructor(e,t,n,i,r){this._store=e,this._orderActionCreator=t,this._subStrategyRegistry=n,this._paymentResumer=i,this._completedPayments=new og(r)}execute(e,t){var n;return sg(this,void 0,void 0,function*(){const{bigpayBaseUrl:i}=this._store.getState().config.getStoreConfigOrThrow().paymentSettings;if(!(null==t?void 0:t.methodId))throw new qt('Unable to submit payment because "options.methodId" argument is not provided.');const{methodId:r}=t,{payment:o}=e,a=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{throw this._completedPayments.setCompleted(i),e}),this._store.getState()})}initialize(e){return sg(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new qt('Unable to submit payment because "options.methodId" argument is not provided.');const t=((e,t)=>{const n=e.getState().paymentMethods.getPaymentMethod(t);if(n&&Hy(n))return n})(this._store,e.methodId);if(!t)throw new yn(cn.PaymentNotInitialized);if(this._subStrategy=this._subStrategyRegistry.getByMethod(t),!this._subStrategy)throw new yn(cn.PaymentNotInitialized);return yield this._subStrategy.initialize(e),this._store.getState()})}deinitialize(e){var t;return sg(this,void 0,void 0,function*(){return null===(t=this._subStrategy)||void 0===t||t.deinitialize(),this._store.getState()})}}!function(e){e.CARD="card_ui",e.NONE="none",e.UNSUPPORTED="unsupported"}(ag||(ag={}));const cg=N([[e=>"card_ui"===e.type,x(ag.CARD)],[e=>"none"===e.type,x(ag.NONE)],[fe,x(ag.UNSUPPORTED)]]);class lg extends Vt{getByMethod(e){const t=cg(e.initializationStrategy);return this.get(t)}}var ug=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class hg{constructor(e,t,n,i){this._store=e,this._orderActionCreator=t,this._hostedFormFactory=n,this._ppsdkStepHandler=i}execute(e){return ug(this,void 0,void 0,function*(){const t=this._hostedForm;if(!t)throw new yn(cn.PaymentNotInitialized);const{additionalAction:n,payment:i}=e;if(!i||!i.methodId)throw new Yy(["payment.methodId"]);yield t.validate();const{payload:r}=yield t.submit(i,n),{response:o}=r;yield this._ppsdkStepHandler.handle(o,{continue:{humanVerification:t=>ug(this,void 0,void 0,function*(){return this.execute(Object.assign({additionalAction:t},e))})}}),yield this._store.dispatch(this._orderActionCreator.loadCurrentOrder())})}initialize(e){return ug(this,void 0,void 0,function*(){const t=e&&e.creditCard&&e.creditCard.form,{config:n,checkout:i}=this._store.getState(),{paymentSettings:{bigpayBaseUrl:r=""}={}}=n.getStoreConfig()||{},o=i.getCheckoutOrThrow().id;if(!t)throw new qt;const a=t&&this._hostedFormFactory.create(r,t,o);yield a.attach(),this._hostedForm=a})}deinitialize(){this._hostedForm&&this._hostedForm.detach()}}class pg{constructor(e,t){this._requestSender=e,this._stepHandler=t}execute({methodId:e,bigpayBaseUrl:t,token:n}){const i={credentials:!1,body:{payment_method_id:e},headers:{authorization:n,"X-XSRF-TOKEN":null}};return this._requestSender.post(`${t}/payments`,i).then(e=>this._stepHandler.handle(e))}initialize(){return Promise.resolve()}deinitialize(){}}var mg,yg,gg=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vg{constructor(e,t){this._requestSender=e,this._stepHandler=t}resume({paymentId:e,bigpayBaseUrl:t,orderId:n}){return gg(this,void 0,void 0,function*(){const i={credentials:!1,headers:{authorization:yield this._getToken(n).catch(()=>{throw new Ym}),"X-XSRF-TOKEN":null}};return this._requestSender.get(`${t}/payments/${e}`,i).then(e=>this._stepHandler.handle(e))})}_getToken(e){return gg(this,void 0,void 0,function*(){const t={params:{order_id:e}};return this._requestSender.get("/api/storefront/payments/auth-token",t).then(({body:e})=>e.auth_token)})}}class fg{constructor(e){this._requestSender=e}createBuyNowCart(e,{timeout:t}={}){const n=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post("/api/storefront/carts",{body:e,headers:n,timeout:t})}}!function(e){e.UpdatePaymentProviderCustomer="UPDATE_PAYMENT_PROVIDER_CUSTOMER"}(mg||(mg={}));class Sg{updatePaymentProviderCustomer(e){return C(l(mg.UpdatePaymentProviderCustomer,e))}}!function(e){e.ForgetCheckoutRemoteCustomerRequested="FORGET_CHECKOUT_REMOTE_CUSTOMER_REQUESTED",e.ForgetCheckoutRemoteCustomerSucceeded="FORGET_CHECKOUT_REMOTE_CUSTOMER_SUCCEEDED",e.ForgetCheckoutRemoteCustomerFailed="FORGET_CHECKOUT_REMOTE_CUSTOMER_FAILED",e.InitializeRemoteBillingRequested="INITIALIZE_REMOTE_BILLING_REQUESTED",e.InitializeRemoteBillingSucceeded="INITIALIZE_REMOTE_BILLING_SUCCEEDED",e.InitializeRemoteBillingFailed="INITIALIZE_REMOTE_BILLING_FAILED",e.InitializeRemoteShippingRequested="INITIALIZE_REMOTE_SHIPPING_REQUESTED",e.InitializeRemoteShippingSucceeded="INITIALIZE_REMOTE_SHIPPING_SUCCEEDED",e.InitializeRemoteShippingFailed="INITIALIZE_REMOTE_SHIPPING_FAILED",e.InitializeRemotePaymentRequested="INITIALIZE_REMOTE_PAYMENT_REQUESTED",e.InitializeRemotePaymentSucceeded="INITIALIZE_REMOTE_PAYMENT_SUCCEEDED",e.InitializeRemotePaymentFailed="INITIALIZE_REMOTE_PAYMENT_FAILED",e.LoadRemoteSettingsRequested="LOAD_REMOTE_SETTINGS_REQUESTED",e.LoadRemoteSettingsSucceeded="LOAD_REMOTE_SETTINGS_SUCCEEDED",e.LoadRemoteSettingsFailed="LOAD_REMOTE_SETTINGS_FAILED",e.SignOutRemoteCustomerRequested="SIGN_OUT_REMOTE_CUSTOMER_REQUESTED",e.SignOutRemoteCustomerSucceeded="SIGN_OUT_REMOTE_CUSTOMER_SUCCEEDED",e.SignOutRemoteCustomerFailed="SIGN_OUT_REMOTE_CUSTOMER_FAILED",e.UpdateRemoteCheckout="UPDATE_REMOTE_CHECKOUT"}(yg||(yg={}));var _g;class wg{constructor(e,t){this._remoteCheckoutRequestSender=e,this._checkoutActionCreator=t}initializeBilling(e,t,n){return m.create(i=>{i.next(l(yg.InitializeRemoteBillingRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializeBilling(e,t,n).then(({body:t={}})=>{i.next(l(yg.InitializeRemoteBillingSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(yg.InitializeRemoteBillingFailed,t,{methodId:e}))})})}initializeShipping(e,t,n){return m.create(i=>{i.next(l(yg.InitializeRemoteShippingRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializeShipping(e,t,n).then(({body:t={}})=>{i.next(l(yg.InitializeRemoteShippingSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(yg.InitializeRemoteShippingFailed,t,{methodId:e}))})})}initializePayment(e,t,n){return m.create(i=>{i.next(l(yg.InitializeRemotePaymentRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializePayment(e,t,n).then(({body:t={}})=>{i.next(l(yg.InitializeRemotePaymentSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(yg.InitializeRemotePaymentFailed,t,{methodId:e}))})})}loadSettings(e,t){return m.create(n=>{n.next(l(yg.LoadRemoteSettingsRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.loadSettings(e,t).then(({body:t})=>{n.next(l(yg.LoadRemoteSettingsSucceeded,t,{methodId:e})),n.complete()}).catch(t=>{n.error(h(yg.LoadRemoteSettingsFailed,t,{methodId:e}))})})}signOut(e,t){return m.create(n=>{n.next(l(yg.SignOutRemoteCustomerRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.signOut(e,t).then(()=>{n.next(l(yg.SignOutRemoteCustomerSucceeded,void 0,{methodId:e})),n.complete()}).catch(t=>{n.error(h(yg.SignOutRemoteCustomerFailed,t,{methodId:e}))})})}forgetCheckout(e,t){return g(C(l(yg.ForgetCheckoutRemoteCustomerRequested,void 0,{methodId:e})),v(()=>{return n=this,i=void 0,o=function*(){return yield this._remoteCheckoutRequestSender.forgetCheckout(t),yield this._checkoutActionCreator.loadCurrentCheckout(),l(yg.ForgetCheckoutRemoteCustomerSucceeded,void 0,{methodId:e})},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(t=>Je(yg.ForgetCheckoutRemoteCustomerFailed,t,{methodId:e})))}updateCheckout(e,t){return l(yg.UpdateRemoteCheckout,t,{methodId:e})}}class Ig{constructor(e){this._requestSender=e}initializeBilling(e,t,{timeout:n}={}){const i=`/remote-checkout/${e}/billing`;return this._requestSender.get(i,{params:t,timeout:n,headers:Xe})}initializeShipping(e,t,{timeout:n}={}){const i=`/remote-checkout/${e}/shipping`;return this._requestSender.get(i,{params:t,timeout:n,headers:Xe})}initializePayment(e,t,{timeout:n}={}){const i=`/remote-checkout/${e}/payment`;return this._requestSender.get(i,{params:t,timeout:n,headers:Xe})}loadSettings(e,{timeout:t}={}){const n=`/remote-checkout/${e}/settings`;return this._requestSender.get(n,{timeout:t,headers:Xe})}signOut(e,{timeout:t}={}){const n=`/remote-checkout/${e}/signout`;return this._requestSender.get(n,{timeout:t,headers:Xe})}generateToken({timeout:e}={}){return this._requestSender.get("/remote-checkout-token",{timeout:e,headers:Xe})}trackAuthorizationEvent({timeout:e}={}){return this._requestSender.post("/remote-checkout/events/shopper-checkout-service-provider-authorization-requested",{timeout:e,headers:Xe})}forgetCheckout({timeout:e}={}){return this._requestSender.post("/remote-checkout/forget-checkout",{timeout:e,headers:Xe})}}!function(e){e.CreateConsignmentsRequested="CREATE_CONSIGNMENTS_REQUESTED",e.CreateConsignmentsSucceeded="CREATE_CONSIGNMENTS_SUCCEEDED",e.CreateConsignmentsFailed="CREATE_CONSIGNMENTS_FAILED",e.UpdateConsignmentRequested="UPDATE_CONSIGNMENT_REQUESTED",e.UpdateConsignmentSucceeded="UPDATE_CONSIGNMENT_SUCCEEDED",e.UpdateConsignmentFailed="UPDATE_CONSIGNMENT_FAILED",e.DeleteConsignmentRequested="DELETE_CONSIGNMENT_REQUESTED",e.DeleteConsignmentSucceeded="DELETE_CONSIGNMENT_SUCCEEDED",e.DeleteConsignmentFailed="DELETE_CONSIGNMENT_FAILED",e.UpdateShippingOptionRequested="UPDATE_SHIPPING_OPTION_REQUESTED",e.UpdateShippingOptionSucceeded="UPDATE_SHIPPING_OPTION_SUCCEEDED",e.UpdateShippingOptionFailed="UPDATE_SHIPPING_OPTION_FAILED",e.LoadShippingOptionsRequested="LOAD_SHIPPING_OPTIONS_REQUESTED",e.LoadShippingOptionsSucceeded="LOAD_SHIPPING_OPTIONS_SUCCEEDED",e.LoadShippingOptionsFailed="LOAD_SHIPPING_OPTIONS_FAILED"}(_g||(_g={}));class Cg{constructor(e,t){this._consignmentRequestSender=e,this._checkoutRequestSender=t}unassignItemsByAddress(e,t){return n=>{const i=n.getState();if(!i.checkout.getCheckout())throw new rt(et.MissingCheckout);const r=this._consignmentHasAddress(e)?e.address:e.shippingAddress,o=i.consignments.getConsignmentByAddress(r);if(!o)throw new qt("No consignment found for the specified address");const a=this._removeLineItems(e.lineItems,o,i.cart.getCart());return a.length?this.updateConsignment({id:o.id,address:r,lineItems:a},t)(n):this.deleteConsignment(o.id,t)(n)}}assignItemsByAddress(e,t){return n=>{const i=n.getState(),r=this._consignmentHasAddress(e)?e.address:e.shippingAddress,o=i.consignments.getConsignmentByAddress(r);return this._createOrUpdateConsignment({id:o&&o.id,address:r,lineItems:this._addLineItems(e.lineItems,o,i.cart.getCart())},t)(n)}}selectShippingOption(e,t){return n=>m.create(i=>{const r=n.getState(),o=r.checkout.getCheckout(),a=r.consignments.getConsignments();if(!o)throw new rt(et.MissingCheckout);if(!a||!a.length)throw new rt(et.MissingConsignments);const s={id:a[0].id,shippingOptionId:e},d={id:a[0].id};i.next(l(_g.UpdateShippingOptionRequested,void 0,d)),this._consignmentRequestSender.updateConsignment(o.id,s,t).then(({body:e})=>{i.next(l(_g.UpdateShippingOptionSucceeded,e,d)),i.complete()}).catch(e=>{i.error(h(_g.UpdateShippingOptionFailed,e,d))})})}loadShippingOptions(e){return t=>m.create(n=>{const i=t.getState().checkout.getCheckout();if(!i)throw new rt(et.MissingCheckout);n.next(l(_g.LoadShippingOptionsRequested)),this._checkoutRequestSender.loadCheckout(i.id,Object.assign(Object.assign({},e),{params:{include:[zt.AvailableShippingOptions]}})).then(({body:e})=>{n.next(l(_g.LoadShippingOptionsSucceeded,e)),n.complete()}).catch(e=>{n.error(h(_g.LoadShippingOptionsFailed,e))})})}updateAddress(e,t){return n=>{const i=this._getUpdateAddressRequestBody(e,n),r=n.getState().consignments.getConsignments();return r&&r.length&&(i.id=r[0].id),this._createOrUpdateConsignment(i,t)(n)}}createConsignments(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r||!r.id)throw new rt(et.MissingCheckout);i.next(l(_g.CreateConsignmentsRequested)),this._consignmentRequestSender.createConsignments(r.id,e,t).then(({body:e})=>{i.next(l(_g.CreateConsignmentsSucceeded,e)),i.complete()}).catch(e=>{i.error(h(_g.CreateConsignmentsFailed,e))})})}updateConsignment(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r||!r.id)throw new rt(et.MissingCheckout);const o={id:e.id};i.next(l(_g.UpdateConsignmentRequested,void 0,o)),this._consignmentRequestSender.updateConsignment(r.id,e,t).then(({body:e})=>{i.next(l(_g.UpdateConsignmentSucceeded,e,o)),i.complete()}).catch(e=>{i.error(h(_g.UpdateConsignmentFailed,e,o))})})}deleteConsignment(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout(),o={id:e};if(!r||!r.id)throw new rt(et.MissingCheckout);i.next(l(_g.DeleteConsignmentRequested,void 0,o)),this._consignmentRequestSender.deleteConsignment(r.id,e,t).then(({body:e})=>{i.next(l(_g.DeleteConsignmentSucceeded,e,o)),i.complete()}).catch(e=>{i.error(h(_g.DeleteConsignmentFailed,e,o))})})}updateShippingOption(e,t){return n=>m.create(i=>{var r;const o=n.getState().checkout.getCheckout(),a=n.getState().consignments.getConsignmentById(e.id);if((null===(r=null==a?void 0:a.selectedShippingOption)||void 0===r?void 0:r.id)===e.shippingOptionId)return void i.complete();if(!o||!o.id)throw new rt(et.MissingCheckout);const s={id:e.id};i.next(l(_g.UpdateShippingOptionRequested,void 0,s)),this._consignmentRequestSender.updateConsignment(o.id,e,t).then(({body:e})=>{i.next(l(_g.UpdateShippingOptionSucceeded,e,s)),i.complete()}).catch(e=>{i.error(h(_g.UpdateShippingOptionFailed,e,s))})})}_createOrUpdateConsignment(e,t){return n=>{const i=n.getState().checkout.getCheckout();if(!i||!i.id)throw new rt(et.MissingCheckout);return this._isUpdateConsignmentRequest(e)?this.updateConsignment(e,t)(n):this.createConsignments([e],t)(n)}}_getUpdateAddressRequestBody(e,t){const n=t.getState().cart.getCart();if(!n)throw new rt(et.MissingCart);const{physicalItems:i,customItems:r=[]}=n.lineItems;return{address:e,lineItems:[...i,...r].map(e=>({itemId:e.id,quantity:e.quantity}))}}_removeLineItems(e,t,n){if(!n)throw new rt(et.MissingCart);return this._hydrateLineItems(t.lineItemIds,n).map(t=>{const n=B(e,e=>e.itemId===t.itemId);return Object.assign(Object.assign({},t),{quantity:n?t.quantity-n.quantity:t.quantity})}).filter(e=>e.quantity>0)}_addLineItems(e,t,n){if(!t)return e;if(!n)throw new rt(et.MissingCart);return e.concat(this._hydrateLineItems(t.lineItemIds,n)).filter(e=>e.quantity>0)}_hydrateLineItems(e,t){return e.map(e=>{const n=B(t.lineItems.physicalItems,t=>t.id===e);return{itemId:e,quantity:n?n.quantity:0}})}_isUpdateConsignmentRequest(e){return!!e.id}_consignmentHasAddress(e){return"object"==typeof e&&"address"in e}}const bg=["consignments.availableShippingOptions","cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","promotions.banners"];class Pg{constructor(e){this._requestSender=e}createConsignments(e,t,{timeout:n,params:{include:i}={}}={}){const r=`/api/storefront/checkouts/${e}/consignments`,o=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(r,{body:t,params:{include:Xt(bg,i)},headers:o,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}updateConsignment(e,t,{timeout:n,params:{include:i}={}}={}){const{id:r}=t,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if("empty_cart"===e.body.type)throw new dt;throw e})}deleteConsignment(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/consignments/${t}`,r=Object.assign({Accept:ct.JsonV1},Xe),o=Ft(bg);return this._requestSender.delete(i,{params:{include:o},headers:r,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}var Og,Eg;!function(e){e.LoadShippingCountriesRequested="LOAD_SHIPPING_COUNTRIES_REQUESTED",e.LoadShippingCountriesSucceeded="LOAD_SHIPPING_COUNTRIES_SUCCEEDED",e.LoadShippingCountriesFailed="LOAD_SHIPPING_COUNTRIES_FAILED"}(Og||(Og={}));class Ag{constructor(e,t){this._shippingCountryRequestSender=e,this._store=t}loadCountries(e){const{checkout:t}=this._store.getState(),n=t.getCheckout(),i=n?n.channelId:null;return m.create(t=>{t.next(l(Og.LoadShippingCountriesRequested)),this._shippingCountryRequestSender.loadCountries(i,e).then(e=>{t.next(l(Og.LoadShippingCountriesSucceeded,e.body.data)),t.complete()}).catch(e=>{t.error(h(Og.LoadShippingCountriesFailed,e))})})}}class Tg{constructor(e,t){this._requestSender=e,this._config=t}loadCountries(e,{timeout:t}={}){const n="/internalapi/v1/shipping/countries"+(e?`?channel_id=${e}`:""),i=Object.assign({"Accept-Language":this._config.locale},Xe);return this._requestSender.get(n,{headers:i,timeout:t})}}!function(e){e.ApplyStoreCreditRequested="APPLY_STORE_CREDIT_REQUESTED",e.ApplyStoreCreditSucceeded="APPLY_STORE_CREDIT_SUCCEEDED",e.ApplyStoreCreditFailed="APPLY_STORE_CREDIT_FAILED"}(Eg||(Eg={}));var kg;class Dg{constructor(e){this._storeCreditRequestSender=e}applyStoreCredit(e,t){return n=>g(C(l(Eg.ApplyStoreCreditRequested)),v(()=>{return i=this,r=void 0,a=function*(){var i;const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);const{id:o}=r,a=null!==(i=null==t?void 0:t.version)&&void 0!==i?i:r.version,{body:s}=yield e?this._storeCreditRequestSender.applyStoreCredit(o,Object.assign(Object.assign({},t),{version:a})):this._storeCreditRequestSender.removeStoreCredit(o,Object.assign(Object.assign({},t),{version:a}));return l(Eg.ApplyStoreCreditSucceeded,s)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a})).pipe(P(e=>Je(Eg.ApplyStoreCreditFailed,e)))}}class Mg{constructor(e){this._requestSender=e}applyStoreCredit(e,{timeout:t,version:n}={}){const i=`/api/storefront/checkouts/${e}/store-credit`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{headers:r,timeout:t,params:{include:Ft(Mt)},body:{version:n}})}removeStoreCredit(e,{timeout:t,version:n}={}){const i=`/api/storefront/checkouts/${e}/store-credit`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.delete(i,{headers:r,timeout:t,params:{include:Ft(Mt)},body:{version:n}})}}!function(e){e.UpdateSubscriptionsRequested="UPDATE_SUBSCRIPTIONS_REQUESTED",e.UpdateSubscriptionsSucceeded="UPDATE_SUBSCRIPTIONS_SUCCEEDED",e.UpdateSubscriptionsFailed="UPDATE_SUBSCRIPTIONS_FAILED"}(kg||(kg={}));class zg extends Ot{constructor(e){super(e),this.name="UpdateSubscriptionsError",this.type="update_subscriptions"}}class Ng{constructor(e){this._subscriptionsRequestSender=e}updateSubscriptions(e,t){return g(C(l(kg.UpdateSubscriptionsRequested)),v(()=>{return n=this,i=void 0,o=function*(){const{body:n}=yield this._subscriptionsRequestSender.updateSubscriptions(e,t);return l(kg.UpdateSubscriptionsSucceeded,n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Je(kg.UpdateSubscriptionsFailed,new zg(e))))}}class xg{constructor(e){this._requestSender=e}updateSubscriptions(e,{timeout:t}={}){const n=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post("/api/storefront/subscriptions",{body:e,headers:n,timeout:t})}}function Rg(e){return Q(e)}const Fg=se(e=>Array.isArray(e)?e.map(e=>Lg(e)):Rg(e)?Object.keys(e).reduce((t,n)=>Object.assign(Object.assign({},t),{[n]:Lg(e[n])}),{}):e);Fg.cache=new WeakMap;const Lg=e=>"object"==typeof e&&null!==e?Fg(e):e;function Bg(e){return(...t)=>Lg(e(...t))}function jg({billingAddress:{getBillingAddress:e,getBillingAddressOrThrow:t},cart:{getCart:n,getCartOrThrow:i,getLocale:r},checkout:{getCheckout:o,getCheckoutOrThrow:a,getOutstandingBalance:s},config:{getContextConfig:d,getHost:c,getLocale:l,getStoreConfig:u,getStoreConfigOrThrow:h,getConfig:p},consignments:{getConsignments:m,getConsignmentsOrThrow:y},countries:{getCountries:g},customer:{getCustomer:v,getCustomerOrThrow:f},instruments:{getCardInstrument:S,getCardInstrumentOrThrow:_,getInstruments:w,getInstrumentsMeta:I},order:{getOrder:C,getOrderOrThrow:b,getOrderMeta:P},payment:{getPaymentToken:O,getPaymentTokenOrThrow:E,getPaymentId:A,getPaymentIdOrThrow:T,getPaymentStatus:k,getPaymentStatusOrThrow:D,getPaymentRedirectUrl:M,getPaymentRedirectUrlOrThrow:z,isPaymentDataRequired:N},paymentMethods:{getPaymentMethod:x,getPaymentMethodOrThrow:R,getPaymentMethodsMeta:F},paymentProviderCustomer:{getPaymentProviderCustomer:L,getPaymentProviderCustomerOrThrow:B},paymentStrategies:{isInitialized:j},shippingAddress:{getShippingAddress:U,getShippingAddressOrThrow:q,getShippingAddresses:V,getShippingAddressesOrThrow:G},shippingCountries:{getShippingCountries:H}}){return{getHost:Bg(c),getLocale:Bg(l),getCartLocale:Bg(r),getBillingAddress:Bg(e),getBillingAddressOrThrow:Bg(t),getCart:Bg(n),getCartOrThrow:Bg(i),getCheckout:Bg(o),getCheckoutOrThrow:Bg(a),getCountries:Bg(g),getStoreConfig:Bg(u),getStoreConfigOrThrow:Bg(h),getConfig:Bg(p),getConsignments:Bg(m),getConsignmentsOrThrow:Bg(y),getContextConfig:Bg(d),getCustomer:Bg(v),getCustomerOrThrow:Bg(f),getCardInstrument:Bg(S),getInstruments:Bg(w),getCardInstrumentOrThrow:Bg(_),getOrder:Bg(C),getOrderOrThrow:Bg(b),getOrderMeta:Bg(P),getInstrumentsMeta:Bg(I),getPaymentToken:O,getPaymentTokenOrThrow:E,getPaymentId:A,getPaymentIdOrThrow:T,getPaymentStatus:k,getPaymentStatusOrThrow:D,getPaymentRedirectUrl:M,getPaymentRedirectUrlOrThrow:z,getPaymentMethod:Bg(x),getPaymentMethodOrThrow:Bg(R),getPaymentMethodsMeta:Bg(F),getPaymentProviderCustomer:Bg(L),getPaymentProviderCustomerOrThrow:Bg(B),getShippingAddress:Bg(U),getShippingAddressOrThrow:Bg(q),getShippingAddresses:Bg(V),getShippingAddressesOrThrow:Bg(G),getShippingCountries:Bg(H),getOutstandingBalance:Bg(s),isPaymentDataRequired:N,isPaymentMethodInitialized:j}}var Ug,qg=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vg{constructor(e,t,n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S){this._store=e,this._storeProjectionFactory=t,this._checkoutActionCreator=n,this._checkoutValidator=i,this._hostedFormFactory=r,this._orderActionCreator=o,this._billingAddressActionCreator=a,this._consignmentActionCreator=s,this._paymentMethodActionCreator=d,this._paymentActionCreator=c,this._paymentHumanVerificationHandler=l,this._customerActionCreator=u,this._cartRequestSender=h,this._storeCreditActionCreator=p,this._couponActionCreator=m,this._spamProtectionActionCreator=y,this._paymentProviderCustomerActionCreator=g,this._shippingCountryActionCreator=v,this._remoteCheckoutActionCreator=f,this._paymentStrategyWidgetActionCreator=S,this._storeProjection=this._storeProjectionFactory.create(this._store)}createHostedForm(e,t){const n=this._storeProjection.getState().getCheckoutOrThrow().id;return this._hostedFormFactory.create(e,t,n)}subscribe(e,...t){return this._storeProjection.subscribe(e,...t)}getState(){return this._storeProjection.getState()}initializeOffsitePayment(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentActionCreator.initializeOffsitePayment(e)),this._storeProjection.getState()})}loadCheckout(e){return qg(this,void 0,void 0,function*(){return e?yield this._store.dispatch(this._checkoutActionCreator.loadCheckout(e)):yield this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),this._storeProjection.getState()})}loadDefaultCheckout(){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()),this._storeProjection.getState()})}loadPaymentMethod(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e,t)),this._storeProjection.getState()})}loadPaymentMethods(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethods(e)),this._storeProjection.getState()})}submitOrder(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._orderActionCreator.submitOrder(e,t)),this._storeProjection.getState()})}submitPayment(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentActionCreator.submitPayment(e)),this._storeProjection.getState()})}finalizeOrder(e){return qg(this,void 0,void 0,function*(){const{order:{getOrderOrThrow:t}}=this._store.getState();return yield this._store.dispatch(this._orderActionCreator.finalizeOrder(t().orderId,e)),this._storeProjection.getState()})}updateBillingAddress(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(e)),this._storeProjection.getState()})}updateShippingAddress(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.updateAddress(e)),this._storeProjection.getState()})}selectShippingOption(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t)),this._storeProjection.getState()})}signInCustomer(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._customerActionCreator.signInCustomer(e,t)),this._storeProjection.getState()})}signOutCustomer(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._customerActionCreator.signOutCustomer(e)),this._storeProjection.getState()})}createBuyNowCart(e,t){return qg(this,void 0,void 0,function*(){const{body:n}=yield this._cartRequestSender.createBuyNowCart(e,t);return n})}applyStoreCredit(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(e,t)),this._storeProjection.getState()})}applyCoupon(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._couponActionCreator.applyCoupon(e,t)),this._storeProjection.getState()})}removeCoupon(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._couponActionCreator.removeCoupon(e,t)),this._storeProjection.getState()})}verifyCheckoutSpamProtection(){return qg(this,void 0,void 0,function*(){const{checkout:e}=this._store.getState(),{shouldExecuteSpamCheck:t}=e.getCheckoutOrThrow();return t&&(yield this._store.dispatch(this._spamProtectionActionCreator.verifyCheckoutSpamProtection())),this._storeProjection.getState()})}loadCurrentOrder(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._orderActionCreator.loadCurrentOrder(e)),this._storeProjection.getState()})}updatePaymentProviderCustomer(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(e)),this._storeProjection.getState()})}loadShippingCountries(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._shippingCountryActionCreator.loadCountries(e)),this._storeProjection.getState()})}deleteConsignment(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.deleteConsignment(e,t)),this._storeProjection.getState()})}initializePayment(e,t,n){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.initializePayment(e,t,n)),this._storeProjection.getState()})}forgetCheckout(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.forgetCheckout(e,t)),this._storeProjection.getState()})}remoteCheckoutSignOut(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.signOut(e,t)),this._storeProjection.getState()})}validateCheckout(e,t){return qg(this,void 0,void 0,function*(){yield this._checkoutValidator.validate(e,t)})}handlePaymentHumanVerification(e,t){return qg(this,void 0,void 0,function*(){return"string"==typeof e?this._paymentHumanVerificationHandler.handle(e,null!=t?t:""):this._paymentHumanVerificationHandler.handle(e)})}widgetInteraction(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentStrategyWidgetActionCreator.widgetInteraction(e),{queueId:"widgetInteraction"}),this._storeProjection.getState()})}}class Gg{constructor(e){this._transformSelectors=e}create(e){return mt(e,this._transformSelectors)}}function Hg(e,t){const{config:{getHost:i,getLocale:r}}=e.getState();t||(t=n({host:i()}));const a=new Gg(jg),s=new nn(new en(t),new bt(new Tt(t)),new on(new an(t))),d=new ny(new en(t)),c=new Iy(e),l=new Vm(new jm(t),new ny(new en(t))),u=new st(new ut(t),new Ng(new xg(t))),h=new Cg(new Pg(t),new en(t)),p=new Wm(new $m(t)),m=new Cy(new by(Gm(e)),l,new Gy,new cy(Sn(o()))),y=new cy(Sn(o())),g=new Kt(new Jt(t),s,new pn(Sn(o()),new _n(t))),v=new Dg(new Mg(t)),f=new Dt(new Lt(t)),S=Sn(o()),_=new _n(t),w=new pn(S,_),I=new fg(t),C=new Sg,b=new Ag(new Tg(t,{locale:r()}),e),P=new wg(new Ig(t),s),O=new Qm;return new Vg(e,a,s,d,c,l,u,h,p,m,y,g,I,v,f,w,C,b,P,O)}!function(e){e.LoadInstrumentsRequested="LOAD_INSTRUMENTS_REQUESTED",e.LoadInstrumentsSucceeded="LOAD_INSTRUMENTS_SUCCEEDED",e.LoadInstrumentsFailed="LOAD_INSTRUMENTS_FAILED",e.DeleteInstrumentRequested="DELETE_INSTRUMENT_REQUESTED",e.DeleteInstrumentSucceeded="DELETE_INSTRUMENT_SUCCEEDED",e.DeleteInstrumentFailed="DELETE_INSTRUMENT_FAILED"}(Ug||(Ug={}));class Wg{constructor(e){this._instrumentRequestSender=e}loadInstruments(){return e=>m.create(t=>{t.next(l(Ug.LoadInstrumentsRequested));const n=this._getSessionContext(e),i=this._getCurrentAccessToken(e),r=this._getShippingAddress(e);return this._getValidAccessToken(i).then(e=>this._instrumentRequestSender.loadInstruments(Object.assign(Object.assign({},n),{authToken:e.vaultAccessToken}),r).then(({body:n})=>{t.next(l(Ug.LoadInstrumentsSucceeded,n,e)),t.complete()})).catch(e=>{t.error(h(Ug.LoadInstrumentsFailed,e))})})}deleteInstrument(e){return t=>m.create(n=>{n.next(l(Ug.DeleteInstrumentRequested,void 0,{instrumentId:e}));const i=this._getSessionContext(t),r=this._getCurrentAccessToken(t);return this._getValidAccessToken(r).then(t=>this._instrumentRequestSender.deleteInstrument(Object.assign(Object.assign({},i),{authToken:t.vaultAccessToken}),e).then(({body:i})=>{n.next(l(Ug.DeleteInstrumentSucceeded,i,Object.assign({instrumentId:e},t))),n.complete()})).catch(t=>{n.error(h(Ug.DeleteInstrumentFailed,t,{instrumentId:e}))})})}_isValidVaultAccessToken(e){if(!e||!e.vaultAccessToken)return!1;return function(e){const t=new Date(e.getTime());return t.setMinutes(e.getMinutes()+2),t}(new Date(e.vaultAccessExpiry)).valueOf()>Date.now()}_getCurrentAccessToken(e){const{instruments:t}=e.getState(),n=t.getInstrumentsMeta();if(n)return{vaultAccessToken:n.vaultAccessToken,vaultAccessExpiry:n.vaultAccessExpiry}}_getValidAccessToken(e){return e&&this._isValidVaultAccessToken(e)?Promise.resolve(e):this._instrumentRequestSender.getVaultAccessToken().then(({body:e})=>e)}_getShippingAddress(e){const t=e.getState(),n=t.shippingAddress.getShippingAddresses();return n.length>1?n:t.shippingAddress.getShippingAddress()}_getSessionContext(e){const t=e.getState(),n=t.config.getStoreConfig(),i=t.cart.getCart();if(!n)throw new rt(et.MissingCheckoutConfig);if(!i)throw new rt(et.MissingCart);const{customerId:r}=i,{storeId:o}=n.storeProfile,{code:a}=n.shopperCurrency.isTransactional?n.shopperCurrency:n.currency;return{customerId:r,storeId:o,currencyCode:a}}}var $g,Yg,Kg=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rthis._isPayPalInstrument(e)?function(e){return{bigpayToken:e.bigpay_token,defaultInstrument:e.default_instrument,provider:e.provider,externalId:e.external_id,trustedShippingAddress:e.trusted_shipping_address,method:"paypal",type:"account"}}(e):this._isBankInstrument(e)?function(e){return{bigpayToken:e.bigpay_token,defaultInstrument:e.default_instrument,provider:e.provider,trustedShippingAddress:e.trusted_shipping_address,accountNumber:e.account_number,issuer:e.issuer,iban:e.iban,method:e.method,type:"bank"}}(e):function(e){return{bigpayToken:e.bigpay_token,defaultInstrument:e.default_instrument,provider:e.provider,iin:e.iin,last4:e.last_4,expiryMonth:e.expiry_month,expiryYear:e.expiry_year,brand:e.brand,trustedShippingAddress:e.trusted_shipping_address,untrustedShippingCardVerificationMode:e.untrusted_shipping_address_card_verification_mode,method:e.method,type:"card"}}(e))}_isPayPalInstrument(e){return"paypal"===e.method_type}_isBankInstrument(e){return"bank"===e.method_type}_transformResponse(e){const{data:t}=e,n=Kg(e,["data"]);return Object.assign(Object.assign({},n),{body:t})}}class Zg{constructor(e,t){this._client=e,this._requestSender=t,this._transformer=new Jg}getVaultAccessToken({timeout:e}={}){return this._requestSender.get("/internalapi/v1/checkout/payments/vault-access-token",{timeout:e}).then(e=>Object.assign(Object.assign({},e),{body:{vaultAccessToken:e.body.data.token,vaultAccessExpiry:e.body.data.expires_at}}))}loadInstruments(e,t){return t?this._loadInstrumentsWithAddress(e,t):this._loadInstruments(e)}deleteInstrument(e,t){const n=Object.assign(Object.assign({},e),{instrumentId:t});return new Promise((e,t)=>{this._client.deleteShopperInstrument(n,(n,i)=>n?t(this._transformer.transformErrorResponse(n)):e(this._transformer.transformResponse(i)))})}_loadInstruments(e){return new Promise((t,n)=>{this._client.loadInstruments(e,(e,i)=>e?n(this._transformer.transformErrorResponse(e)):t(this._transformer.transformResponse(i)))})}_loadInstrumentsWithAddress(e,t){const n=Object.assign(Object.assign({},e),{shippingAddress:Array.isArray(t)?t.map(e=>Py(e)):Py(t)});return new Promise((e,t)=>{this._client.loadInstrumentsWithAddress(n,(n,i)=>n?t(this._transformer.transformErrorResponse(n)):e(this._transformer.transformResponse(i)))})}}!function(e){e.LoadPickupOptionsRequested="LOAD_PICKUP_OPTIONS_REQUESTED",e.LoadPickupOptionsSucceeded="LOAD_PICKUP_OPTIONS_SUCCEEDED",e.LoadPickupOptionsFailed="LOAD_PICKUP_OPTIONS_FAILED"}($g||($g={}));class Qg{constructor(e){this._pickupOptionRequestSender=e}loadPickupOptions(e){return t=>new m(n=>{const i=this._hydrateApiQuery(t,e);n.next(l($g.LoadPickupOptionsRequested)),this._pickupOptionRequestSender.fetchPickupOptions(i).then(t=>{n.next(l($g.LoadPickupOptionsSucceeded,t.body.results,e)),n.complete()}).catch(e=>{n.error(h($g.LoadPickupOptionsFailed,e))})})}_hydrateApiQuery(e,t){const n=e.getState(),i=n.cart.getCartOrThrow();if(!i)throw new rt(et.MissingCart);const r=n.consignments.getConsignmentById(t.consignmentId);if(!r)throw new rt(et.MissingConsignments);const o=r.lineItemIds,a=i.lineItems.physicalItems.filter(e=>H(o,e.id)).map(e=>({variantId:e.variantId,quantity:e.quantity}));return{searchArea:t.searchArea,items:a}}}class Xg{constructor(e){this._requestSender=e}fetchPickupOptions(e){return this._requestSender.post("/api/storefront/pickup-options",{headers:Object.assign({Accept:ct.Json},Xe),body:e})}}!function(e){e.UpdateAddressFailed="SHIPPING_STRATEGY_UPDATE_ADDRESS_FAILED",e.UpdateAddressRequested="SHIPPING_STRATEGY_UPDATE_ADDRESS_REQUESTED",e.UpdateAddressSucceeded="SHIPPING_STRATEGY_UPDATE_ADDRESS_SUCCEEDED",e.SelectOptionFailed="SHIPPING_STRATEGY_SELECT_OPTION_FAILED",e.SelectOptionRequested="SHIPPING_STRATEGY_SELECT_OPTION_REQUESTED",e.SelectOptionSucceeded="SHIPPING_STRATEGY_SELECT_OPTION_SUCCEEDED",e.InitializeFailed="SHIPPING_STRATEGY_INITIALIZE_FAILED",e.InitializeRequested="SHIPPING_STRATEGY_INITIALIZE_REQUESTED",e.InitializeSucceeded="SHIPPING_STRATEGY_INITIALIZE_SUCCEEDED",e.DeinitializeFailed="SHIPPING_STRATEGY_DEINITIALIZE_FAILED",e.DeinitializeRequested="SHIPPING_STRATEGY_DEINITIALIZE_REQUESTED",e.DeinitializeSucceeded="SHIPPING_STRATEGY_DEINITIALIZE_SUCCEEDED",e.WidgetInteractionStarted="SHIPPING_STRATEGY_WIDGET_INTERACTION_STARTED",e.WidgetInteractionFinished="SHIPPING_STRATEGY_WIDGET_INTERACTION_FINISHED",e.WidgetInteractionFailed="SHIPPING_STRATEGY_WIDGET_INTERACTION_FAILED"}(Yg||(Yg={}));class ev{constructor(e){this._strategyRegistry=e}updateAddress(e,t){return n=>m.create(i=>{const r=n.getState().payment.getPaymentId(),o=t&&t.methodId||r&&r.providerId;i.next(l(Yg.UpdateAddressRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).updateAddress(e,Object.assign(Object.assign({},t),{methodId:o})).then(()=>{i.next(l(Yg.UpdateAddressSucceeded,void 0,{methodId:o})),i.complete()}).catch(e=>{i.error(h(Yg.UpdateAddressFailed,e,{methodId:o}))})})}selectOption(e,t){return n=>m.create(i=>{const r=n.getState().payment.getPaymentId(),o=t&&t.methodId||r&&r.providerId;i.next(l(Yg.SelectOptionRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).selectOption(e,Object.assign(Object.assign({},t),{methodId:o})).then(()=>{i.next(l(Yg.SelectOptionSucceeded,void 0,{methodId:o})),i.complete()}).catch(e=>{i.error(h(Yg.SelectOptionFailed,e,{methodId:o}))})})}initialize(e){return t=>m.create(n=>{const i=t.getState(),r=i.payment.getPaymentId(),o=e&&e.methodId||r&&r.providerId,a=Object.assign(Object.assign({},e),{methodId:o});if(o&&i.shippingStrategies.isInitialized(o))return n.complete();n.next(l(Yg.InitializeRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).initialize(a).then(()=>{n.next(l(Yg.InitializeSucceeded,void 0,{methodId:o})),n.complete()}).catch(e=>{n.error(h(Yg.InitializeFailed,e,{methodId:o}))})})}deinitialize(e){return t=>m.create(n=>{const i=t.getState(),r=i.payment.getPaymentId(),o=e&&e.methodId||r&&r.providerId;if(o&&!i.shippingStrategies.isInitialized(o))return n.complete();n.next(l(Yg.DeinitializeRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).deinitialize(Object.assign(Object.assign({},e),{methodId:o})).then(()=>{n.next(l(Yg.DeinitializeSucceeded,void 0,{methodId:o})),n.complete()}).catch(e=>{n.error(h(Yg.DeinitializeFailed,e,{methodId:o}))})})}widgetInteraction(e,t){return m.create(n=>{const i={methodId:t&&t.methodId};n.next(l(Yg.WidgetInteractionStarted,void 0,i)),e().then(()=>{n.next(l(Yg.WidgetInteractionFinished,void 0,i)),n.complete()}).catch(e=>{n.error(h(Yg.WidgetInteractionFailed,e,i))})})}}var tv,nv=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class iv{constructor(e,t,n,i,r){this._store=e,this._consignmentActionCreator=t,this._paymentMethodActionCreator=n,this._amazonPayV2PaymentProcessor=i,this._shippingStrategyActionCreator=r}updateAddress(e,t){const n=this._store.getState().shippingAddress.getShippingAddress();if(!n)throw new rt(et.MissingShippingAddress);const i=Object.assign(Object.assign({},n),{customFields:e.customFields});return this._store.dispatch(this._consignmentActionCreator.updateAddress(i,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(e){return nv(this,void 0,void 0,function*(){const{amazonpay:t,methodId:n}=e;if(!t||!n)throw new qt('Unable to proceed because "options.amazonpay" argument is not provided.');const i=(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n))).paymentMethods.getPaymentMethodOrThrow(n);yield this._amazonPayV2PaymentProcessor.initialize(i);const{paymentToken:r,region:o}=i.initializationData,a=t.editAddressButtonId;if(r&&a){const e=this._shouldShowLoadingSpinner(o);this._bindEditButton(a,r,"changeAddress",e)}return this._store.getState()})}deinitialize(){return nv(this,void 0,void 0,function*(){return yield this._amazonPayV2PaymentProcessor.deinitialize(),Promise.resolve(this._store.getState())})}_bindEditButton(e,t,n,i){const r=document.getElementById(e);if(r&&r.parentNode){if(i){const e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener("click",()=>this._showLoadingSpinner())}this._amazonPayV2PaymentProcessor.bindButton(e,t,n)}}_showLoadingSpinner(){return this._store.dispatch(this._shippingStrategyActionCreator.widgetInteraction(()=>new Promise(I)),{queueId:"widgetInteraction"})}_shouldShowLoadingSpinner(e){return"us"!==e}}!function(e){e.CVV="cvv",e.PAN="pan"}(tv||(tv={}));var rv=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ov{constructor(e,t,n,i,r,o){this._store=e,this._billingAddressActionCreator=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=i,this._paymentProviderCustomerActionCreator=r,this._braintreeIntegrationService=o}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}deinitialize(){return Promise.resolve(this._store.getState())}initialize(e){var t;return rv(this,void 0,void 0,function*(){const{methodId:n,braintreefastlane:i,fastlane:r}=e||{},o=r||i,{onPayPalFastlaneAddressChange:a}=o||{};if(!n)throw new qt('Unable to proceed because "methodId" argument is not provided.');const s=this._store.getState();if(!s.customer.getCustomerOrThrow().isGuest)return Promise.resolve(this._store.getState());try{if(this._shouldRunAuthenticationFlow()){const e=s.paymentMethods.getPaymentMethod(n),{clientToken:i,isFastlaneStylingEnabled:r}=(null==e?void 0:e.initializationData)||{};i||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n)));const a=Ao(r?null===(t=null==e?void 0:e.initializationData)||void 0===t?void 0:t.fastlaneStyles:void 0,null==o?void 0:o.styles);yield this._runAuthenticationFlowOrThrow(n,a)}"function"==typeof a&&(yield this._shouldUseBraintreeFastlaneShippingComponent(n))&&a(()=>this._handleBraintreeFastlaneShippingAddressChange())}catch(e){}return Promise.resolve(this._store.getState())})}_shouldRunAuthenticationFlow(){var e;const t=this._store.getState(),n=null===(e=t.cart.getCart())||void 0===e?void 0:e.id,i=Fr.get("bc-fastlane-sessionId")||"",r=t.paymentProviderCustomer.getPaymentProviderCustomer(),o=xl(r)?r:{};return(null==o?void 0:o.authenticationState)!==Mi.CANCELED&&!(null==o?void 0:o.authenticationState)&&i===n}_runAuthenticationFlowOrThrow(e,t){var n,i;return rv(this,void 0,void 0,function*(){const r=this._store.getState(),o=r.cart.getCartOrThrow(),a=r.countries.getCountries()||[],s=r.paymentMethods.getPaymentMethodOrThrow(e),{clientToken:d,config:c}=s;if(!d)throw new rt(et.MissingPaymentMethod);this._braintreeIntegrationService.initialize(d);const l=yield this._braintreeIntegrationService.getBraintreeFastlane(null==o?void 0:o.id,null==c?void 0:c.testMode,t),u=(null===(n=r.customer.getCustomer())||void 0===n?void 0:n.email)||(null===(i=r.billingAddress.getBillingAddress())||void 0===i?void 0:i.email);if(!u)return;const{lookupCustomerByEmail:h,triggerAuthenticationFlow:p}=l.identity,{customerContextId:m}=yield h(u);if(!m)return;const{authenticationState:y,profileData:g}=yield p(m);if(y===Mi.CANCELED)return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:y,addresses:[],instruments:[]})),void Fr.remove("bc-fastlane-sessionId");const v=this._getPayPalBillingAddress(g),f=g.shippingAddress,S=g.shippingAddress.phoneNumber,_=this._mapPayPalToBcAddress(f,a,S),w=this._mapPayPalToBcAddress(v,a,S);if(w&&_){const t=this._mergeShippingAndBillingAddresses(_,w),n=this._mapPayPalToBcInstrument(e,g.card),i=n?[n]:[];yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:y,addresses:t,instruments:i})),w&&(yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(Object.assign(Object.assign({},w),{id:String(w.id)})))),_&&o.lineItems.physicalItems.length>0&&(yield this._store.dispatch(this._consignmentActionCreator.updateAddress(_)))}})}_getPayPalBillingAddress(e){const{name:t,card:n}=e,i=n.paymentSource.card.billingAddress;return Object.assign(Object.assign({},i),{firstName:i.firstName||(null==t?void 0:t.firstName),lastName:i.lastName||(null==t?void 0:t.lastName)})}_getCountryNameByCountryCode(e,t){const n=t.find(t=>t.code===e);return(null==n?void 0:n.name)||""}_mapPayPalToBcAddress(e,t,n,i){return{id:Number(Date.now()),type:"paypal-address",firstName:e.firstName||"",lastName:e.lastName||"",company:e.company||"",address1:e.streetAddress,address2:e.extendedAddress||"",city:e.locality,stateOrProvince:e.region,stateOrProvinceCode:e.region,country:this._getCountryNameByCountryCode(e.countryCodeAlpha2,t),countryCode:e.countryCodeAlpha2,postalCode:e.postalCode,phone:n||"",customFields:i||[]}}_normalizeAddress(e){return le(e,["id"])}_mergeShippingAndBillingAddresses(e,t){return Y(this._normalizeAddress(e),this._normalizeAddress(t))?[e]:[e,t]}_mapPayPalToBcInstrument(e,t){if(!t)return;const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a}=i.card,[s,d]=o.split("-");return{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:tv.CVV,type:"card"}}_handleBraintreeFastlaneShippingAddressChange(){var e;return rv(this,void 0,void 0,function*(){const t=this._store.getState().countries.getCountries()||[],n=yield this._braintreeIntegrationService.getBraintreeFastlane(),{selectionChanged:i,selectedAddress:r}=yield n.profile.showShippingAddressSelector();if(i){const n=this._store.getState(),i=n.shippingAddress.getShippingAddressesOrThrow(),o=n.paymentProviderCustomer.getPaymentProviderCustomer(),a=xl(o)?o:{},s=this._mapPayPalToBcAddress(r,t,r.phoneNumber,null===(e=i[0])||void 0===e?void 0:e.customFields);if(s){const e=this._filterAddresses([s,...a.addresses||[]]);return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(Object.assign(Object.assign({},a),{addresses:e}))),yield this._store.dispatch(this._consignmentActionCreator.updateAddress(s)),s}}})}_filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this._isEqualAddresses(e,t))?e:[...e,t]:e,[])}_isEqualAddresses(e,t){return Y(this._normalizeAddress(e),this._normalizeAddress(t))}_shouldUseBraintreeFastlaneShippingComponent(e){var t;return rv(this,void 0,void 0,function*(){const n=this._store.getState().paymentProviderCustomer.getPaymentProviderCustomer(),i=xl(n)?n:{};if(i&&(null==i?void 0:i.authenticationState)!==Mi.CANCELED){const n=yield this._getBraintreePaymentMethodOrThrow(e);return!!(null===(t=null==n?void 0:n.initializationData)||void 0===t?void 0:t.isFastlaneEnabled)}return!1})}_getBraintreePaymentMethodOrThrow(e){return rv(this,void 0,void 0,function*(){const t=this._store.getState().paymentMethods.getPaymentMethod(e);return t||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e))).paymentMethods.getPaymentMethodOrThrow(e)})}}class av{constructor(e,t){this._store=e,this._consignmentActionCreator=t}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(){return Promise.resolve(this._store.getState())}deinitialize(){return Promise.resolve(this._store.getState())}}var sv=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class dv{constructor(e,t,n,i,r,o,a){this._store=e,this._billingAddressActionCreator=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=i,this._paymentProviderCustomerActionCreator=r,this._paypalSdkScriptLoader=o,this._paypalCommerceFastlaneUtils=a}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}deinitialize(){return Promise.resolve(this._store.getState())}initialize(e){return sv(this,void 0,void 0,function*(){const{methodId:t,paypalcommercefastlane:n,fastlane:i}=e||{},r=i||n,{onPayPalFastlaneAddressChange:o,styles:a}=r||{};if(!t)throw new qt('Unable to proceed because "methodId" argument is not provided.');const s=this._store.getState().customer.getCustomerOrThrow();if(!(null==s?void 0:s.isGuest))return Promise.resolve(this._store.getState());try{this._shouldAuthenticateUserWithFastlane()&&(yield this._initializePayPalSdk(t,a),yield this._authenticateUserWithFastlaneOtp(t)),"function"==typeof o&&this._shouldUsePayPalFastlaneShippingComponent()&&(yield this._initializePayPalSdk(t,a),o(()=>this._handlePayPalShippingAddressChange()))}catch(e){}return Promise.resolve(this._store.getState())})}_getPayPalPaymentMethodOrThrow(e){return sv(this,void 0,void 0,function*(){const t=this._store.getState().paymentMethods.getPaymentMethod(e);return t||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e))).paymentMethods.getPaymentMethodOrThrow(e)})}_getPayPalCustomerAuthenticationState(){const e=this._store.getState().paymentProviderCustomer.getPaymentProviderCustomerOrThrow();var t;return((t=e)&&("authenticationState"in t||"addresses"in t||"instruments"in t)?e:{}).authenticationState}_shouldAuthenticateUserWithFastlane(){const e=this._store.getState().cart.getCartOrThrow(),t=this._paypalCommerceFastlaneUtils.getStorageSessionId();return!this._getPayPalCustomerAuthenticationState()&&t===e.id}_shouldUsePayPalFastlaneShippingComponent(){const e=this._getPayPalCustomerAuthenticationState();return!!e&&e!==fs.CANCELED}_initializePayPalSdk(e,t){var n;return sv(this,void 0,void 0,function*(){const i=this._store.getState().cart.getCartOrThrow(),r=yield this._getPayPalPaymentMethodOrThrow(e),{isDeveloperModeApplicable:o,isFastlaneStylingEnabled:a}=(null==r?void 0:r.initializationData)||{},s=!!o,d=rd(a?null===(n=null==r?void 0:r.initializationData)||void 0===n?void 0:n.fastlaneStyles:{},t),c=yield this._paypalSdkScriptLoader.getPayPalFastlaneSdk(r,i.currency.code,i.id,i.locale);yield this._paypalCommerceFastlaneUtils.initializePayPalFastlane(c,s,d)})}_authenticateUserWithFastlaneOtp(e){var t,n;return sv(this,void 0,void 0,function*(){const i=this._store.getState(),r=i.cart.getCartOrThrow(),o=null===(t=i.customer.getCustomer())||void 0===t?void 0:t.email,a=null===(n=i.billingAddress.getBillingAddress())||void 0===n?void 0:n.email,s=o||a||"",{customerContextId:d}=yield this._paypalCommerceFastlaneUtils.lookupCustomerOrThrow(s),c=yield this._paypalCommerceFastlaneUtils.triggerAuthenticationFlowOrThrow(d),{authenticationState:l,addresses:u,billingAddress:h,shippingAddress:p,instruments:m}=this._paypalCommerceFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,c);yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:l,addresses:u,instruments:m})),c.authenticationState===fs.CANCELED?this._paypalCommerceFastlaneUtils.removeStorageSessionId():this._paypalCommerceFastlaneUtils.updateStorageSessionId(r.id),h&&(yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(Object.assign(Object.assign({},h),{id:String(h.id)})))),p&&r.lineItems.physicalItems.length>0&&(yield this._store.dispatch(this._consignmentActionCreator.updateAddress(p)))})}_handlePayPalShippingAddressChange(){var e;return sv(this,void 0,void 0,function*(){const t=this._paypalCommerceFastlaneUtils.getPayPalFastlaneOrThrow(),{selectionChanged:n,selectedAddress:i}=yield t.profile.showShippingAddressSelector();if(n){const t=this._store.getState(),n=t.shippingAddress.getShippingAddressesOrThrow(),r=t.paymentProviderCustomer.getPaymentProviderCustomer(),o=vp(r)?r:{},a=this._paypalCommerceFastlaneUtils.mapPayPalToBcAddress(i.address,i.name,i.phoneNumber,null===(e=n[0])||void 0===e?void 0:e.customFields),s=this._paypalCommerceFastlaneUtils.filterAddresses([a,...o.addresses||[]]);return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(Object.assign(Object.assign({},o),{addresses:s}))),yield this._store.dispatch(this._consignmentActionCreator.updateAddress(a)),a}})}}var cv;class lv{constructor(e,t,n,i){this._store=e,this._stripeScriptLoader=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=i}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(e){return t=this,n=void 0,r=function*(){if(!e.stripeupe)throw new qt('Unable to proceed because "options" argument is not provided.');const{container:t,gatewayId:n,methodId:i,onChangeShipping:r,getStyles:o,availableCountries:a,getStripeState:s}=e.stripeupe;Object.entries(e.stripeupe).forEach(([e,t])=>{if(!t)throw new qt(`Unable to proceed because "${e}" argument is not provided.`)});const d=yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n,{params:{method:i}})),c=d.paymentMethods.getPaymentMethodOrThrow(i,n),{initializationData:l}=c;if(!c||!c.initializationData.stripePublishableKey||!c.clientToken)throw new rt(et.MissingPaymentMethod);let u;this._stripeUPEClient=yield this._stripeScriptLoader.getStripeClient(l,d.cart.getLocale(),ka.V3,Fa,La);const h=o&&o(),{form:{getShippingAddressFields:p},shippingAddress:{getShippingAddress:m}}=this._store.getState(),y=p([],"");u=h?{variables:{colorPrimary:h.fieldInnerShadow,colorBackground:h.fieldBackground,colorText:h.labelText,colorDanger:h.fieldErrorText,colorTextSecondary:h.labelText,colorTextPlaceholder:h.fieldPlaceholderText,spacingUnit:"4px",borderRadius:"4px"},rules:{".Input":{borderColor:h.fieldBorder,color:h.fieldText,boxShadow:h.fieldInnerShadow}}}:{variables:{spacingUnit:"4px",borderRadius:"4px"}},this._stripeElements=yield this._stripeScriptLoader.getElements(this._stripeUPEClient,{clientSecret:c.clientToken,appearance:u});const g=m(),v=y.find(e=>"phone"===e.name);let f={mode:Ca.SHIPPING,allowedCountries:[a],fields:{phone:"always"},validation:{phone:{required:v&&v.required?"always":"never"}},display:{name:ba.SPLIT}};if(g){const{stateOrProvinceCode:e,countryCode:t,lastName:n,firstName:i,phone:r,address1:o,address2:a,city:d,postalCode:c}=g,l=e&&t?s(t,e):e;f=Object.assign(Object.assign({},f),{defaultValues:{firstName:i,lastName:n,phone:r,address:{line1:o,line2:a,city:d,state:l,postal_code:c,country:t}}})}let S=this._stripeElements.getElement(Da.SHIPPING);return S&&S.destroy(),S=this._stripeElements.create(Da.SHIPPING,f),S.on(za.CHANGE,e=>{if(!("isNewAddress"in e))throw new rt(et.MissingShippingAddress);(e.complete||e.isNewAddress)&&(this.sendData&&clearTimeout(this.sendData),this.sendData=setTimeout(()=>{r(Object.assign(Object.assign({},e),{phoneFieldRequired:!!v&&v.required}))},1e3))}),S.mount(`#${t}`),Promise.resolve(this._store.getState())},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}deinitialize(){return Promise.resolve(this._store.getState())}}!function(e){e.SendSignInEmailRequested="SEND_SIGNIN_EMAIL_REQUESTED",e.SendSignInEmailSucceeded="SEND_SIGNIN_EMAIL_SUCCEEDED",e.SendSignInEmailFailed="SEND_SIGNIN_EMAIL_FAILED"}(cv||(cv={}));class uv{constructor(e){this._requestSender=e}sendSignInEmail(e,t){return g(C(l(cv.SendSignInEmailRequested)),v(()=>{return n=this,i=void 0,o=function*(){const{body:n}=yield this._requestSender.sendSignInEmail(e,t);return l(cv.SendSignInEmailSucceeded,n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Je(cv.SendSignInEmailFailed,e)))}}class hv{constructor(e){this._requestSender=e}sendSignInEmail({email:e,redirectUrl:t},{timeout:n}={}){const i=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post("/login.php?action=passwordless_login",{body:{email:e,redirect_url:t||In(window.top?window.top.location.href:"").pathname},headers:i,timeout:n})}}class pv{constructor(e){this._messageCustomizer=e}transform(e){var t;return e.message=(t=this._messageCustomizer(e))?t.split(/(?:\r\n|\n|\r)/).map(e=>e.replace(/^\s+/gm,"")).join(" ").trim():"",e}}let mv=class{constructor(e,t,n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,_,w,I,C,b,P,O,E,A){this._store=e,this._storeProjection=t,this._extensionMessenger=n,this._extensionEventBroadcaster=i,this._b2bTokenActionCreator=r,this._billingAddressActionCreator=o,this._checkoutActionCreator=a,this._configActionCreator=s,this._customerActionCreator=d,this._consignmentActionCreator=c,this._countryActionCreator=l,this._couponActionCreator=u,this._customerStrategyActionCreator=h,this._errorActionCreator=p,this._giftCertificateActionCreator=m,this._instrumentActionCreator=y,this._orderActionCreator=g,this._paymentMethodActionCreator=v,this._paymentStrategyActionCreator=f,this._pickupOptionActionCreator=S,this._shippingCountryActionCreator=_,this._shippingStrategyActionCreator=w,this._signInEmailActionCreator=I,this._spamProtectionActionCreator=C,this._storeCreditActionCreator=b,this._subscriptionsActionCreator=P,this._formFieldsActionCreator=O,this._extensionActionCreator=E,this._workerExtensionMessenger=A,this._errorTransformer=function(e="development"===vt()){return new pv(t=>{if(!e||!function(e){return!(!e.subtype&&!e.type)}(t))return t.message;switch(t.subtype||t.type){case et.MissingConsignments:return`\n ${t.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 `;case et.MissingCart:case et.MissingCheckout:return`\n ${t.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 `;case et.MissingCheckoutConfig:return`\n ${t.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 `;case et.MissingOrder:return`\n ${t.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 `;case et.MissingOrderId:return`\n ${t.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 `;case et.MissingPaymentMethod:return`\n ${t.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 `;case cn.CustomerNotInitialized: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 ";case cn.PaymentNotInitialized:return`\n ${t.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 `;case cn.ShippingNotInitialized:return`\n ${t.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 `;default:return t.message}})}()}getState(){return this._storeProjection.getState()}notifyState(){this._storeProjection.notifyState()}subscribe(e,...t){return this._storeProjection.subscribe(e,...t)}hydrateInitialState(e){return this._dispatch(this._checkoutActionCreator.hydrateInitialState(e))}loadCheckout(e,t){return this._dispatch(e?this._checkoutActionCreator.loadCheckout(e,t):this._checkoutActionCreator.loadDefaultCheckout(t))}updateCheckout(e,t){const n=this._checkoutActionCreator.updateCheckout(e,t);return this._dispatch(n)}loadOrder(e,t){const n=this._orderActionCreator.loadOrder(e,t),i=this._formFieldsActionCreator.loadFormFields(t),r=this._configActionCreator.loadConfig(t);return Promise.all([this._dispatch(n),this._dispatch(r,{queueId:"config"}),this._dispatch(i,{queueId:"formFields"})]).then(()=>this.getState())}submitOrder(e,t){const n=this._paymentStrategyActionCreator.execute(e,t);return this._dispatch(n,{queueId:"paymentStrategy"})}finalizeOrderIfNeeded(e){const t=this._paymentStrategyActionCreator.finalize(e);return this._dispatch(t,{queueId:"paymentStrategy"})}loadPaymentMethods(e){const t=this._paymentMethodActionCreator.loadPaymentMethods(e);return this._dispatch(t,{queueId:"paymentMethods"})}loadPaymentMethodByIds(e,t){const n=this._paymentMethodActionCreator.loadPaymentMethodsById(e,t);return this._dispatch(n,{queueId:"paymentMethods"})}loadPaymentMethod(e,t){const n=this._paymentMethodActionCreator.loadPaymentMethod(e,t);return this._dispatch(n,{queueId:"paymentMethods"})}initializePayment(e){const t=this._paymentStrategyActionCreator.initialize(e);return this._dispatch(t,{queueId:"paymentStrategy"})}deinitializePayment(e){const t=this._paymentStrategyActionCreator.deinitialize(e);return this._dispatch(t,{queueId:"paymentStrategy"})}loadBillingCountries(e){const t=this._countryActionCreator.loadCountries(e);return this._dispatch(t,{queueId:"billingCountries"})}loadShippingCountries(e){const t=this._shippingCountryActionCreator.loadCountries(e);return this._dispatch(t,{queueId:"shippingCountries"})}loadPickupOptions(e){const t=this._pickupOptionActionCreator.loadPickupOptions(e);return this._dispatch(t,{queueId:"pickupOptions"})}loadBillingAddressFields(e){return this.loadBillingCountries(e)}loadShippingAddressFields(e){return this.loadShippingCountries(e)}initializeCustomer(e){const t=this._customerStrategyActionCreator.initialize(e);return this._dispatch(t,{queueId:"customerStrategy"})}deinitializeCustomer(e){const t=this._customerStrategyActionCreator.deinitialize(e);return this._dispatch(t,{queueId:"customerStrategy"})}sendSignInEmail(e,t){const n=this._signInEmailActionCreator.sendSignInEmail(e,t);return this._dispatch(n,{queueId:"signInEmail"})}getB2BToken(e){const t=this._b2bTokenActionCreator.loadB2BToken(e);return this._dispatch(t,{queueId:"b2bToken"})}createCustomerAccount(e,t){const n=this._customerActionCreator.createCustomer(e,t);return this._dispatch(n)}createCustomerAddress(e,t){const n=this._customerActionCreator.createAddress(e,t);return this._dispatch(n)}updateSubscriptions(e,t){const n=this._subscriptionsActionCreator.updateSubscriptions(e,t);return this._dispatch(n,{queueId:"subscriptions"})}continueAsGuest(e,t){const n=this._billingAddressActionCreator.continueAsGuest(e,t);return this._dispatch(n)}signInCustomer(e,t){const n=this._customerStrategyActionCreator.signIn(e,t);return this._dispatch(n,{queueId:"customerStrategy"})}signOutCustomer(e){const t=this._customerStrategyActionCreator.signOut(e);return this._dispatch(t,{queueId:"customerStrategy"})}executePaymentMethodCheckout(e){const t=this._customerStrategyActionCreator.executePaymentMethodCheckout(e);return this._dispatch(t,{queueId:"customerStrategy"})}loadShippingOptions(e){const t=this._consignmentActionCreator.loadShippingOptions(e);return this._dispatch(t)}initializeShipping(e){const t=this._shippingStrategyActionCreator.initialize(e);return this._dispatch(t,{queueId:"shippingStrategy"})}deinitializeShipping(e){const t=this._shippingStrategyActionCreator.deinitialize(e);return this._dispatch(t,{queueId:"shippingStrategy"})}selectShippingOption(e,t){const n=this._shippingStrategyActionCreator.selectOption(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}updateShippingAddress(e,t){const n=this._shippingStrategyActionCreator.updateAddress(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}createConsignments(e,t){const n=this._consignmentActionCreator.createConsignments(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}deleteConsignment(e,t){const n=this._consignmentActionCreator.deleteConsignment(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}updateConsignment(e,t){const n=this._consignmentActionCreator.updateConsignment(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}assignItemsToAddress(e,t){const n=this._consignmentActionCreator.assignItemsByAddress(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}unassignItemsToAddress(e,t){const n=this._consignmentActionCreator.unassignItemsByAddress(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}selectConsignmentShippingOption(e,t,n){const i=this._consignmentActionCreator.updateShippingOption({id:e,shippingOptionId:t},n);return this._dispatch(i,{queueId:"shippingStrategy"})}updateBillingAddress(e,t={}){const n=this._billingAddressActionCreator.updateAddress(e,t);return this._dispatch(n)}applyStoreCredit(e,t){const n=this._storeCreditActionCreator.applyStoreCredit(e,t);return this._dispatch(n)}applyCoupon(e,t){const n=this._couponActionCreator.applyCoupon(e,t);return this._dispatch(n)}removeCoupon(e,t){const n=this._couponActionCreator.removeCoupon(e,t);return this._dispatch(n)}applyGiftCertificate(e,t){const n=this._giftCertificateActionCreator.applyGiftCertificate(e,t);return this._dispatch(n)}removeGiftCertificate(e,t){const n=this._giftCertificateActionCreator.removeGiftCertificate(e,t);return this._dispatch(n)}loadInstruments(){const e=this._instrumentActionCreator.loadInstruments();return this._dispatch(e)}deleteInstrument(e){const t=this._instrumentActionCreator.deleteInstrument(e);return this._dispatch(t).then(()=>this.loadInstruments())}clearError(e){const t=this._errorActionCreator.clearError(e);return this._dispatch(t)}initializeSpamProtection(e){const t=this._spamProtectionActionCreator.initialize(e);return this._dispatch(t,{queueId:"spamProtection"})}executeSpamCheck(){const e=this._spamProtectionActionCreator.verifyCheckoutSpamProtection();return this._dispatch(e,{queueId:"spamProtection"})}loadExtensions(e){const t=this._extensionActionCreator.loadExtensions(e);return this._dispatch(t,{queueId:"extensions"})}renderExtension(e,t){return n=this,i=void 0,o=function*(){const n=this._extensionActionCreator.renderExtension(e,t,this._workerExtensionMessenger),i=yield this._dispatch(n,{queueId:"extensions"});return this._extensionEventBroadcaster.listen(),i},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}clearExtensionCache(e){this._extensionMessenger.clearCacheByRegion(e)}postMessageToExtension(e,t){this._extensionMessenger.post(e,t)}handleExtensionCommand(e,t,n){return this._extensionMessenger.listenForCommand(e,t,n)}handleExtensionQuery(e,t,n){return this._extensionMessenger.listenForQuery(e,t,n)}_dispatch(e,t){return this._store.dispatch(e,t).then(()=>this.getState()).catch(e=>{throw this._errorTransformer.transform(e)})}};mv=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],mv);const yv=mv;function gv(e){return(...t)=>{const n=t.pop();return e(...t,(...e)=>{const t=n(...e);return"function"==typeof t?Pe(t):t})}}const vv=gv(Re),fv=gv(Fe(Le,(e,t)=>Be(e,t)));class Sv extends Ot{constructor(e,t){super(e,{message:t||"An unexpected error has occurred. The checkout process cannot continue as a result."}),this.name="UnrecoverableError",this.type="unrecoverable"}}function _v(e){return e.reduce((e,t)=>t?[...e,t]:e,[]).join(" ")}class wv extends Ot{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}class Iv{constructor(){this._factoryMethods={},this.register("default",(e,t)=>new Ot(e,{message:t})),this.register("internal",(e,t)=>function(e,t){const{body:n}=e,{errors:i=[]}=n;return new Ot(e,{message:_v(i)||n.detail||n.title||t,errors:i.length?i.map(e=>({code:n.type,message:e})):[{code:n.type,message:n.detail||n.title}]})}(e,t)),this.register("storefront",(e,t)=>function(e,t){const{body:n}=e;return new Ot(e,{message:t||n.detail||n.title,errors:[{code:n.code||n.type,message:n.detail||n.title}]})}(e,t)),this.register("payment",(e,t)=>ly(e,t)),this.register("timeout",e=>new wv(e))}register(e,t){this._factoryMethods[e]=t}createError(e,t){return(this._factoryMethods[this._getType(e)]||this._factoryMethods.default)(e,t)}_getType(e){if(0===e.status)return"timeout";if(this._isStorefrontErrorResponseBody(e.body))return"storefront";if(this._isInternalErrorResponseBody(e.body)){const t=re(e.body.type.split("/"));return t&&this._factoryMethods[t]?t:"internal"}const t=re(e.body&&e.body.errors);return t&&t.code&&this._factoryMethods[t.code]?t.code:"payment"}_isStorefrontErrorResponseBody(e){const t=e;return!this._isInternalErrorResponseBody(e)&&"string"==typeof t.title&&"string"==typeof t.type&&"number"==typeof t.status&&"string"==typeof t.detail}_isInternalErrorResponseBody(e){const t=e;return"object"==typeof t.errors&&"string"==typeof t.title&&"string"==typeof t.type&&"number"==typeof t.status}}function Cv(e,t){return Array.isArray(e)?e.map(e=>Cv(e,t)):Q(e)?Se(ue(e,t),(e,n,i)=>{e[i]=Cv(n,t)},{}):e}function bv(e,t){return function(e){return e.type===pt.ClearError}(t)?Cv(e,e=>e===t.payload):e}function Pv(e,t,n){return e===t||(e&&t&&"object"==typeof e&&"object"==typeof t?Array.isArray(e)&&Array.isArray(t)?function(e,t,n){if(e.length!==t.length)return!1;for(let i=0,r=e.length;ivoid 0!==e.id&&e.id===t.id}=i||{};if(!t)return n;if(!n||t===n)return t;let o=0,a=0;const s=(e,t,n)=>(o+=e===t?1:0,a+=e===n?1:0,e),d=n.map((n,i)=>{const o=t&&t[i];return Rg(o)&&Rg(n)?r(o,n)?s(Bv(o,n),o,n):s(Mv(o,n),o,n):W(o)&&W(n)?s(e(o,n),o,n):s(Mv(o,n),o,n)});return o===n.length&&t&&t.length===n.length?t:a===n.length?n:d},Bv=function e(t,n){return t?n&&t!==n?Object.keys(n).reduce((t,i)=>{const r=t[i],o=n[i];return Rg(r)&&Rg(o)?Ov(t,i,e(r,o)):W(r)&&W(o)?Ov(t,i,Lv(r,o)):Ov(t,i,o)},t):t:n},jv={errors:{},statuses:{}};function Uv(e=jv,t){return d({data:qv,errors:c(Gv,bv),statuses:Vv})(e,t)}function qv(e,t){var n,i;switch(t.type){case tt.UpdateBillingAddressSucceeded:case $t.LoadCheckoutSucceeded:case _g.CreateConsignmentsSucceeded:case _g.DeleteConsignmentSucceeded:case _g.UpdateConsignmentSucceeded:case _g.UpdateShippingOptionSucceeded:case _g.LoadShippingOptionsSucceeded:case kt.ApplyCouponSucceeded:case kt.RemoveCouponSucceeded:case Nt.ApplyGiftCertificateSucceeded:case Nt.RemoveGiftCertificateSucceeded:return Bv(e,t.payload&&t.payload.cart);case Yt.HydrateInitialState:return Bv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.cart);default:return e}}function Vv(e=jv.statuses,t){switch(t.type){case $t.LoadCheckoutRequested:return Ov(e,"isLoading",!0);case $t.LoadCheckoutFailed:case $t.LoadCheckoutSucceeded:return Ov(e,"isLoading",!1);default:return e}}function Gv(e=jv.errors,t){switch(t.type){case $t.LoadCheckoutRequested:case $t.LoadCheckoutSucceeded:return Ov(e,"loadError",void 0);case $t.LoadCheckoutFailed:return Ov(e,"loadError",t.payload);default:return e}}var Hv;!function(e){e.InitializeButtonFailed="INITIALIZE_BUTTON_FAILED",e.InitializeButtonRequested="INITIALIZE_BUTTON_REQUESTED",e.InitializeButtonSucceeded="INITIALIZE_BUTTON_SUCCEEDED",e.DeinitializeButtonFailed="DEINITIALIZE_BUTTON_FAILED",e.DeinitializeButtonRequested="DEINITIALIZE_BUTTON_REQUESTED",e.DeinitializeButtonSucceeded="DEINITIALIZE_BUTTON_SUCCEEDED"}(Hv||(Hv={}));const Wv={data:{},errors:{},statuses:{}},$v={initializedContainers:{}},Yv={},Kv={};function Jv(e=Wv,t){return t.meta&&t.meta.methodId?d({data:d({[t.meta.methodId]:Zv}),errors:d({[t.meta.methodId]:Qv}),statuses:d({[t.meta.methodId]:Xv})})(e,t):e}function Zv(e=$v,t){switch(t.type){case Hv.InitializeButtonSucceeded:return t.meta&&t.meta.containerId?Bv(e,{initializedContainers:{[t.meta.containerId]:!0}}):e;case Hv.DeinitializeButtonSucceeded:return Ov(e,"initializedContainers",{})}return e}function Qv(e=Yv,t){switch(t.type){case Hv.InitializeButtonRequested:case Hv.InitializeButtonSucceeded:return Ov(e,"initializeError",void 0);case Hv.InitializeButtonFailed:return Ov(e,"initializeError",t.payload);case Hv.DeinitializeButtonRequested:case Hv.DeinitializeButtonSucceeded:return Ov(e,"deinitializeError",void 0);case Hv.DeinitializeButtonFailed:return Ov(e,"deinitializeError",t.payload);default:return e}}function Xv(e=Kv,t){switch(t.type){case Hv.InitializeButtonRequested:return Ov(e,"isInitializing",!0);case Hv.InitializeButtonFailed:case Hv.InitializeButtonSucceeded:return Ov(e,"isInitializing",!1);case Hv.DeinitializeButtonRequested:return Ov(e,"isDeinitializing",!0);case Hv.DeinitializeButtonFailed:case Hv.DeinitializeButtonSucceeded:return Ov(e,"isDeinitializing",!1);default:return e}}const ef={meta:{},errors:{},statuses:{}};function tf(e=ef,t){return d({data:nf,errors:c(rf,bv),statuses:of})(e,t)}function nf(e,t){var n,i;switch(t.type){case Ct.LoadConfigSucceeded:return Bv(e,t.payload);case Yt.HydrateInitialState:{const r=Bv(e,null===(n=t.payload)||void 0===n?void 0:n.config);return r&&(null===(i=t.payload)||void 0===i?void 0:i.b2bApiSettings)?Object.assign(Object.assign({},r),{storeConfig:Object.assign(Object.assign({},r.storeConfig),{b2bApiSettings:t.payload.b2bApiSettings})}):r}default:return e}}function rf(e=ef.errors,t){switch(t.type){case Ct.LoadConfigSucceeded:return Ov(e,"loadError",void 0);case Ct.LoadConfigFailed:return Ov(e,"loadError",t.payload);default:return e}}function of(e=ef.statuses,t){switch(t.type){case Ct.LoadConfigRequested:return Ov(e,"isLoading",!0);case Ct.LoadConfigSucceeded:case Ct.LoadConfigFailed:return Ov(e,"isLoading",!1);default:return e}}const af={errors:{},statuses:{}};function sf(e=af,t){return d({data:df,errors:c(cf,bv),statuses:lf})(e,t)}function df(e,t){var n,i;switch(t.type){case $t.LoadCheckoutSucceeded:case kt.ApplyCouponSucceeded:case _g.UpdateShippingOptionSucceeded:case kt.RemoveCouponSucceeded:case Mm.LoadOrderSucceeded:return Lv(e,t.payload&&t.payload.coupons);case Yt.HydrateInitialState:return Lv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.coupons);default:return e}}function cf(e={},t){switch(t.type){case kt.ApplyCouponRequested:case kt.ApplyCouponSucceeded:return Ov(e,"applyCouponError",void 0);case kt.ApplyCouponFailed:return Ov(e,"applyCouponError",t.payload);case kt.RemoveCouponRequested:case kt.RemoveCouponSucceeded:return Ov(e,"removeCouponError",void 0);case kt.RemoveCouponFailed:return Ov(e,"removeCouponError",t.payload);default:return e}}function lf(e={},t){switch(t.type){case kt.ApplyCouponRequested:return Ov(e,"isApplyingCoupon",!0);case kt.ApplyCouponSucceeded:case kt.ApplyCouponFailed:return Ov(e,"isApplyingCoupon",!1);case kt.RemoveCouponRequested:return Ov(e,"isRemovingCoupon",!0);case kt.RemoveCouponSucceeded:case kt.RemoveCouponFailed:return Ov(e,"isRemovingCoupon",!1);default:return e}}const uf={errors:{},statuses:{}};function hf(e=uf,t){return d({data:pf,errors:c(mf,bv),statuses:yf})(e,t)}function pf(e,t){var n,i;switch(t.type){case $t.LoadCheckoutSucceeded:case _g.CreateConsignmentsSucceeded:case _g.UpdateConsignmentSucceeded:case _g.DeleteConsignmentSucceeded:case _g.UpdateShippingOptionSucceeded:case kt.ApplyCouponSucceeded:case kt.RemoveCouponSucceeded:case Nt.ApplyGiftCertificateSucceeded:case Nt.RemoveGiftCertificateSucceeded:return Lv(e,t.payload&&t.payload.giftCertificates);case Yt.HydrateInitialState:return Lv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.giftCertificates);default:return e}}function mf(e=uf.errors,t){switch(t.type){case Nt.ApplyGiftCertificateRequested:case Nt.ApplyGiftCertificateSucceeded:return Ov(e,"applyGiftCertificateError",void 0);case Nt.ApplyGiftCertificateFailed:return Ov(e,"applyGiftCertificateError",t.payload);case Nt.RemoveGiftCertificateRequested:case Nt.RemoveGiftCertificateSucceeded:return Ov(e,"removeGiftCertificateError",void 0);case Nt.RemoveGiftCertificateFailed:return Ov(e,"removeGiftCertificateError",t.payload);default:return e}}function yf(e=uf.statuses,t){switch(t.type){case Nt.ApplyGiftCertificateRequested:return Ov(e,"isApplyingGiftCertificate",!0);case Nt.ApplyGiftCertificateSucceeded:case Nt.ApplyGiftCertificateFailed:return Ov(e,"isApplyingGiftCertificate",!1);case Nt.RemoveGiftCertificateRequested:return Ov(e,"isRemovingGiftCertificate",!0);case Nt.RemoveGiftCertificateSucceeded:case Nt.RemoveGiftCertificateFailed:return Ov(e,"isRemovingGiftCertificate",!1);default:return e}}const gf={errors:{},statuses:{}};function vf(e=gf,t){return d({data:ff,errors:c(Sf,bv),statuses:_f})(e,t)}function ff(e,t){var n,i;switch(t.type){case tt.ContinueAsGuestSucceeded:case $t.LoadCheckoutSucceeded:return Bv(e,t.payload&&t.payload.customer);case Rt.CreateCustomerAddressSucceeded:return Bv(e,t.payload);case Yt.HydrateInitialState:return Bv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.customer);default:return e}}function Sf(e=gf.errors,t){switch(t.type){case Rt.CreateCustomerRequested:case Rt.CreateCustomerSucceeded:return Ov(e,"createError",void 0);case Rt.CreateCustomerFailed:return Ov(e,"createError",t.payload);case Rt.CreateCustomerAddressRequested:case Rt.CreateCustomerAddressSucceeded:return Ov(e,"createAddressError",void 0);case Rt.CreateCustomerAddressFailed:return Ov(e,"createAddressError",t.payload);default:return e}}function _f(e=gf.statuses,t){switch(t.type){case Rt.CreateCustomerRequested:return Ov(e,"isCreating",!0);case Rt.CreateCustomerFailed:case Rt.CreateCustomerSucceeded:return Ov(e,"isCreating",!1);case Rt.CreateCustomerAddressRequested:return Ov(e,"isCreatingAddress",!0);case Rt.CreateCustomerAddressFailed:case Rt.CreateCustomerAddressSucceeded:return Ov(e,"isCreatingAddress",!1);default:return e}}const wf={data:{},errors:{},statuses:{}};function If(e=wf,t){return d({data:Cf,errors:c(bf,bv),statuses:Pf})(e,t)}function Cf(e=wf.data,t){switch(t.type){case Wt.InitializeSucceeded:return Bv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!0}});case Wt.DeinitializeSucceeded:return Bv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!1}})}return e}function bf(e=wf.errors,t){switch(t.type){case Wt.InitializeRequested:case Wt.InitializeSucceeded:return Bv(e,{initializeErrors:Object.assign({},e.initializeErrors),initializeMethodId:e.initializeMethodId?e.initializeMethodId:void 0});case Wt.InitializeFailed:return Bv(e,{initializeErrors:Object.assign(Object.assign({},e.initializeErrors),{[t.meta&&t.meta.methodId]:t.payload}),initializeMethodId:t.meta&&t.meta.methodId});case Wt.DeinitializeRequested:case Wt.DeinitializeSucceeded:return Bv(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Wt.DeinitializeFailed:return Bv(e,{deinitializeError:t.payload,deinitializeMethodId:t.meta&&t.meta.methodId});case Wt.SignInRequested:case Wt.SignInSucceeded:return Bv(e,{signInError:void 0,signInMethodId:void 0});case Wt.SignInFailed:return Bv(e,{signInError:t.payload,signInMethodId:t.meta&&t.meta.methodId});case Wt.SignOutRequested:case Wt.SignOutSucceeded:return Bv(e,{signOutError:void 0,signOutMethodId:void 0});case Wt.SignOutFailed:return Bv(e,{signOutError:t.payload,signOutMethodId:t.meta&&t.meta.methodId});case Wt.ExecutePaymentMethodCheckoutRequested:case Wt.ExecutePaymentMethodCheckoutSucceeded:return Bv(e,{executePaymentMethodCheckoutError:void 0,executePaymentMethodCheckoutMethodId:void 0});case Wt.ExecutePaymentMethodCheckoutFailed:return Bv(e,{executePaymentMethodCheckoutError:t.payload,executePaymentMethodCheckoutMethodId:t.meta&&t.meta.methodId});case Wt.WidgetInteractionStarted:case Wt.WidgetInteractionFinished:return Bv(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Wt.WidgetInteractionFailed:return Bv(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta.methodId});default:return e}}function Pf(e=wf.statuses,t){switch(t.type){case Wt.InitializeRequested:return Bv(e,{isInitializing:!0,initializeMethodId:t.meta&&t.meta.methodId});case Wt.InitializeFailed:case Wt.InitializeSucceeded:return Bv(e,{isInitializing:!1,initializeMethodId:void 0});case Wt.DeinitializeRequested:return Bv(e,{isDeinitializing:!0,deinitializeMethodId:t.meta&&t.meta.methodId});case Wt.DeinitializeFailed:case Wt.DeinitializeSucceeded:return Bv(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Wt.SignInRequested:return Bv(e,{isSigningIn:!0,signInMethodId:t.meta&&t.meta.methodId});case Wt.SignInFailed:case Wt.SignInSucceeded:return Bv(e,{isSigningIn:!1,signInMethodId:void 0});case Wt.SignOutRequested:return Bv(e,{isSigningOut:!0,signOutMethodId:t.meta&&t.meta.methodId});case Wt.SignOutFailed:case Wt.SignOutSucceeded:return Bv(e,{isSigningOut:!1,signOutMethodId:void 0});case Wt.ExecutePaymentMethodCheckoutRequested:return Bv(e,{isExecutingPaymentMethodCheckout:!0,executePaymentMethodCheckoutMethodId:t.meta&&t.meta.methodId});case Wt.ExecutePaymentMethodCheckoutFailed:case Wt.ExecutePaymentMethodCheckoutSucceeded:return Bv(e,{isExecutingPaymentMethodCheckout:!1,executePaymentMethodCheckoutMethodId:void 0});case Wt.WidgetInteractionStarted:return Bv(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta.methodId});case Wt.WidgetInteractionFinished:case Wt.WidgetInteractionFailed:return Bv(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const Of={errors:{},statuses:{}};function Ef(e=Of,t){return d({data:Af,errors:c(Tf,bv),statuses:kf})(e,t)}function Af(e,t){var n;return t.type===ln.LoadExtensionsSucceeded?Lv(e,t.payload):t.type===Yt.HydrateInitialState?Lv(e,null===(n=t.payload)||void 0===n?void 0:n.extensions):e}function Tf(e=Of.errors,t){switch(t.type){case ln.LoadExtensionsRequested:case ln.LoadExtensionsSucceeded:return Ov(e,"loadError",void 0);case ln.RenderExtensionRequested:case ln.RenderExtensionSucceeded:return Ov(e,"renderError",void 0);case ln.LoadExtensionsFailed:return Ov(e,"loadError",t.payload);case ln.RenderExtensionFailed:return Ov(e,"renderError",t.payload);default:return e}}function kf(e=Of.statuses,t){switch(t.type){case ln.LoadExtensionsRequested:return Ov(e,"isLoading",!0);case ln.LoadExtensionsSucceeded:case ln.LoadExtensionsFailed:return Ov(e,"isLoading",!1);default:return e}}const Df={errors:{},statuses:{}};function Mf(e=Df,t){return d({data:zf,extraFields:Nf,errors:c(xf,bv),statuses:Rf})(e,t)}function zf(e,t){var n;switch(t.type){case tn.LoadFormFieldsSucceeded:return Bv(e,t.payload);case Yt.HydrateInitialState:return Bv(e,null===(n=t.payload)||void 0===n?void 0:n.formFields);default:return e}}function Nf(e,t){var n,i;return t.type===Yt.HydrateInitialState&&null!==(i=null===(n=t.payload)||void 0===n?void 0:n.extraFields)&&void 0!==i?i:e}function xf(e=Df.errors,t){switch(t.type){case tn.LoadFormFieldsSucceeded:return Ov(e,"loadError",void 0);case tn.LoadFormFieldsFailed:return Ov(e,"loadError",t.payload);default:return e}}function Rf(e=Df.statuses,t){switch(t.type){case tn.LoadFormFieldsRequested:return Ov(e,"isLoading",!0);case tn.LoadFormFieldsSucceeded:case tn.LoadFormFieldsFailed:return Ov(e,"isLoading",!1);default:return e}}const Ff={errors:{},statuses:{}};function Lf(e=Ff,t){return d({data:Bf,errors:c(jf,bv),statuses:Uf})(e,t)}function Bf(e,t){return t.type===Dm.LoadCountriesSucceeded?Lv(e,t.payload):e}function jf(e=Ff.errors,t){switch(t.type){case Dm.LoadCountriesRequested:case Dm.LoadCountriesSucceeded:return Ov(e,"loadError",void 0);case Dm.LoadCountriesFailed:return Ov(e,"loadError",t.payload);default:return e}}function Uf(e=Ff.statuses,t){switch(t.type){case Dm.LoadCountriesRequested:return Ov(e,"isLoading",!0);case Dm.LoadCountriesSucceeded:case Dm.LoadCountriesFailed:return Ov(e,"isLoading",!1);default:return e}}const qf={errors:{},meta:{},statuses:{}};function Vf(e=qf,t){return d({data:Gf,errors:c(Wf,bv),meta:Hf,statuses:$f})(e,t)}function Gf(e,t){switch(t.type){case Mm.LoadOrderSucceeded:case Mm.LoadOrderPaymentsSucceeded:return Bv(e,le(t.payload,["billingAddress","coupons"]));default:return e}}function Hf(e,t){switch(t.type){case Mm.FinalizeOrderSucceeded:case Mm.SubmitOrderSucceeded:return Bv(e,Object.assign(Object.assign({},t.meta),{callbackUrl:t.payload&&t.payload.order.callbackUrl,orderToken:t.payload&&t.payload.order.token,payment:t.payload&&t.payload.order&&t.payload.order.payment}));default:return e}}function Wf(e=qf.errors,t){switch(t.type){case Mm.LoadOrderRequested:case Mm.LoadOrderSucceeded:case Mm.LoadOrderPaymentsSucceeded:case Mm.LoadOrderPaymentsRequested:return Ov(e,"loadError",void 0);case Mm.LoadOrderFailed:case Mm.LoadOrderPaymentsFailed:return Ov(e,"loadError",t.payload);default:return e}}function $f(e=qf.statuses,t){switch(t.type){case Mm.LoadOrderRequested:case Mm.LoadOrderPaymentsRequested:return Ov(e,"isLoading",!0);case Mm.LoadOrderSucceeded:case Mm.LoadOrderFailed:case Mm.LoadOrderPaymentsSucceeded:case Mm.LoadOrderPaymentsFailed:return Ov(e,"isLoading",!1);default:return e}}const Yf={};function Kf(e=Yf,t){return d({data:Jf})(e,t)}function Jf(e,t){switch(t.type){case Mm.LoadOrderPaymentsSucceeded:case Mm.LoadOrderSucceeded:return Mv(e,t.payload&&t.payload.billingAddress);default:return e}}function Zf(e={},t){return d({data:Qf})(e,t)}function Qf(e,t){return t.type===vy.SubmitPaymentSucceeded?t.payload:e}const Xf={errors:{},statuses:{}};function eS(e=Xf,t){return d({data:tS,errors:c(iS,bv),meta:nS,statuses:rS})(e,t)}function tS(e,t){switch(t.type){case qm.LoadPaymentMethodSucceeded:return function(e,t,n){if(!t)return e;const i=pe(t,"id"),r="object"==typeof n?me(n):n||i,o=j(e,r),a=[...e];if(-1===o)a.push(t);else{const n=e[o];a[o]=Rg(n)&&Rg(t)?Bv(n,t):t}return a}(e||[],t.payload,t.payload&&{id:t.payload.id,gateway:t.payload.gateway});case qm.LoadPaymentMethodsSucceeded:return Lv(e,t.payload,{matchObject:(e,t)=>e.id===t.id&&e.gateway===t.gateway});default:return e}}function nS(e,t){return t.type===qm.LoadPaymentMethodsSucceeded?Bv(e,t.meta):e}function iS(e=Xf.errors,t){switch(t.type){case qm.LoadPaymentMethodsRequested:case qm.LoadPaymentMethodsSucceeded:return Ov(e,"loadError",void 0);case qm.LoadPaymentMethodsFailed:return Ov(e,"loadError",t.payload);case qm.LoadPaymentMethodRequested:case qm.LoadPaymentMethodSucceeded:return Bv(e,{loadMethodId:void 0,loadMethodError:void 0});case qm.LoadPaymentMethodFailed:return Bv(e,{loadMethodId:t.meta.methodId,loadMethodError:t.payload});default:return e}}function rS(e=Xf.statuses,t){switch(t.type){case qm.LoadPaymentMethodsRequested:return Ov(e,"isLoading",!0);case qm.LoadPaymentMethodsSucceeded:case qm.LoadPaymentMethodsFailed:return Ov(e,"isLoading",!1);case qm.LoadPaymentMethodRequested:return Bv(e,{isLoadingMethod:!0,loadMethodId:t.meta.methodId});case qm.LoadPaymentMethodSucceeded:case qm.LoadPaymentMethodFailed:return Bv(e,{isLoadingMethod:!1,loadMethodId:void 0});default:return e}}const oS={data:{},errors:{},statuses:{}};function aS(e=oS,t){return d({data:sS,errors:c(dS,bv),statuses:cS})(e,t)}function sS(e=oS.data,t){switch(t.type){case Km.InitializeSucceeded:if(t.meta){const{methodId:n,gatewayId:i}=t.meta,r=i?`${n}.${i}`:n;return Bv(e,{[r]:{isInitialized:!0}})}break;case Km.DeinitializeSucceeded:if(t.meta){const{methodId:n,gatewayId:i}=t.meta,r=i?`${n}.${i}`:n;return Bv(e,{[r]:{isInitialized:!1}})}}return e}function dS(e=oS.errors,t){switch(t.type){case Km.InitializeRequested:case Km.InitializeSucceeded:return Bv(e,{initializeError:void 0,initializeMethodId:void 0});case Km.InitializeFailed:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return Bv(e,{initializeError:t.payload,initializeMethodId:n})}case Km.DeinitializeRequested:case Km.DeinitializeSucceeded:return Bv(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Km.DeinitializeFailed:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return Bv(e,{deinitializeError:t.payload,deinitializeMethodId:n})}case Km.ExecuteRequested:case Km.ExecuteSucceeded:return Bv(e,{executeError:void 0,executeMethodId:void 0});case Km.ExecuteFailed:return Bv(e,{executeError:t.payload,executeMethodId:t.meta&&t.meta.methodId});case Km.FinalizeRequested:case Km.FinalizeSucceeded:return Bv(e,{finalizeError:void 0,finalizeMethodId:void 0});case Km.FinalizeFailed:return Bv(e,{finalizeError:t.payload,finalizeMethodId:t.meta&&t.meta.methodId});case Km.WidgetInteractionStarted:case Km.WidgetInteractionFinished:return Bv(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Km.WidgetInteractionFailed:return Bv(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta.methodId});default:return e}}function cS(e=oS.statuses,t){switch(t.type){case Km.InitializeRequested:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return Bv(e,{isInitializing:!0,initializeMethodId:n})}case Km.InitializeFailed:case Km.InitializeSucceeded:return Bv(e,{isInitializing:!1,initializeMethodId:void 0});case Km.DeinitializeRequested:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return Bv(e,{isDeinitializing:!0,deinitializeMethodId:n})}case Km.DeinitializeFailed:case Km.DeinitializeSucceeded:return Bv(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Km.ExecuteRequested:return Bv(e,{isExecuting:!0,executeMethodId:t.meta&&t.meta.methodId});case Km.ExecuteFailed:case Km.ExecuteSucceeded:return Bv(e,{isExecuting:!1,executeMethodId:void 0});case Km.FinalizeRequested:return Bv(e,{isFinalizing:!0,finalizeMethodId:t.meta&&t.meta.methodId});case Km.FinalizeFailed:case Km.FinalizeSucceeded:return Bv(e,{isFinalizing:!1,finalizeMethodId:void 0});case Km.WidgetInteractionStarted:return Bv(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta.methodId});case Km.WidgetInteractionFinished:case Km.WidgetInteractionFailed:return Bv(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const lS={data:{}};function uS(e=lS,t){return d({data:hS})(e,t)}function hS(e=lS.data,t){return t.type===mg.UpdatePaymentProviderCustomer?Bv(e,t.payload):e}const pS={data:[],errors:{},statuses:{}};function mS(e=pS,t){return d({data:yS,errors:c(vS,bv),meta:gS,statuses:fS})(e,t)}function yS(e=pS.data,t){return t.type===Ug.LoadInstrumentsSucceeded?Lv(e,t.payload&&t.payload.vaultedInstruments||[]):e}function gS(e,t){switch(t.type){case Ug.LoadInstrumentsSucceeded:case Ug.DeleteInstrumentSucceeded:return Bv(e,t.meta);default:return e}}function vS(e=pS.errors,t){switch(t.type){case Ug.LoadInstrumentsRequested:case Ug.LoadInstrumentsSucceeded:return Ov(e,"loadError",void 0);case Ug.DeleteInstrumentRequested:case Ug.DeleteInstrumentSucceeded:return Bv(e,{deleteError:void 0,failedInstrument:void 0});case Ug.LoadInstrumentsFailed:return Ov(e,"loadError",t.payload);case Ug.DeleteInstrumentFailed:return Bv(e,{deleteError:t.payload,failedInstrument:t.meta.instrumentId});default:return e}}function fS(e=pS.statuses,t){switch(t.type){case Ug.LoadInstrumentsRequested:return Ov(e,"isLoading",!0);case Ug.DeleteInstrumentRequested:return Bv(e,{isDeleting:!0,deletingInstrument:t.meta.instrumentId});case Ug.LoadInstrumentsSucceeded:case Ug.LoadInstrumentsFailed:return Ov(e,"isLoading",!1);case Ug.DeleteInstrumentSucceeded:case Ug.DeleteInstrumentFailed:return Bv(e,{isDeleting:!1,deletingInstrument:void 0});default:return e}}const SS={data:{}};function _S(e=SS,t){return t.meta&&t.meta.methodId?d({data:d({[t.meta.methodId]:wS})})(e,t):e}function wS(e,t){switch(t.type){case yg.InitializeRemoteBillingSucceeded:return Ov(e,"billing",t.payload&&t.payload.billing);case yg.InitializeRemoteShippingSucceeded:return Ov(e,"shipping",t.payload&&t.payload.shipping);case yg.LoadRemoteSettingsSucceeded:return Ov(e,"settings",t.payload);case yg.UpdateRemoteCheckout:return Bv(e,t.payload);default:return e}}const IS={errors:{updateShippingOptionError:{},updateError:{},deleteError:{}},statuses:{isUpdating:{},isUpdatingShippingOption:{},isDeleting:{}}};function CS(e=IS,t){return d({data:bS,errors:c(PS,bv),statuses:OS})(e,t)}function bS(e,t){var n,i;switch(t.type){case $t.LoadCheckoutSucceeded:case _g.LoadShippingOptionsSucceeded:case _g.CreateConsignmentsSucceeded:case _g.UpdateConsignmentSucceeded:case _g.DeleteConsignmentSucceeded:case _g.UpdateShippingOptionSucceeded:case kt.ApplyCouponSucceeded:case kt.RemoveCouponSucceeded:return Lv(e,t.payload&&t.payload.consignments);case Rt.SignOutCustomerSucceeded:return Lv(e,[]);case Yt.HydrateInitialState:return Lv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.consignments);default:return e}}function PS(e=IS.errors,t){switch(t.type){case $t.LoadCheckoutRequested:case $t.LoadCheckoutSucceeded:case _g.LoadShippingOptionsSucceeded:case _g.LoadShippingOptionsRequested:return Ov(e,"loadError",void 0);case $t.LoadCheckoutFailed:case _g.LoadShippingOptionsFailed:return Ov(e,"loadError",t.payload);case _g.CreateConsignmentsRequested:case _g.CreateConsignmentsSucceeded:return Ov(e,"createError",void 0);case _g.CreateConsignmentsFailed:return Ov(e,"createError",t.payload);case _g.UpdateConsignmentSucceeded:case _g.UpdateConsignmentRequested:return t.meta?Bv(e,{updateError:{[t.meta.id]:void 0}}):e;case _g.UpdateConsignmentFailed:return t.meta?Bv(e,{updateError:{[t.meta.id]:t.payload}}):e;case _g.DeleteConsignmentSucceeded:case _g.DeleteConsignmentRequested:return t.meta?Bv(e,{deleteError:{[t.meta.id]:void 0}}):e;case _g.DeleteConsignmentFailed:return t.meta?Bv(e,{deleteError:{[t.meta.id]:t.payload}}):e;case _g.UpdateShippingOptionRequested:case _g.UpdateShippingOptionSucceeded:return t.meta?Bv(e,{updateShippingOptionError:{[t.meta.id]:void 0}}):e;case _g.UpdateShippingOptionFailed:return t.meta?Bv(e,{updateShippingOptionError:{[t.meta.id]:t.payload}}):e;default:return e}}function OS(e=IS.statuses,t){switch(t.type){case $t.LoadCheckoutRequested:return Ov(e,"isLoading",!0);case _g.LoadShippingOptionsRequested:return Ov(e,"isLoadingShippingOptions",!0);case $t.LoadCheckoutSucceeded:case $t.LoadCheckoutFailed:return Ov(e,"isLoading",!1);case _g.LoadShippingOptionsSucceeded:case _g.LoadShippingOptionsFailed:return Ov(e,"isLoadingShippingOptions",!1);case _g.CreateConsignmentsRequested:return Ov(e,"isCreating",!0);case _g.CreateConsignmentsSucceeded:case _g.CreateConsignmentsFailed:return Ov(e,"isCreating",!1);case _g.UpdateConsignmentRequested:return t.meta?Bv(e,{isUpdating:{[t.meta.id]:!0}}):e;case _g.UpdateConsignmentSucceeded:case _g.UpdateConsignmentFailed:return t.meta?Bv(e,{isUpdating:{[t.meta.id]:!1}}):e;case _g.DeleteConsignmentRequested:return t.meta?Bv(e,{isDeleting:{[t.meta.id]:!0}}):e;case _g.DeleteConsignmentSucceeded:case _g.DeleteConsignmentFailed:return t.meta?Bv(e,{isDeleting:{[t.meta.id]:!1}}):e;case _g.UpdateShippingOptionRequested:return t.meta?Bv(e,{isUpdatingShippingOption:{[t.meta.id]:!0}}):e;case _g.UpdateShippingOptionSucceeded:case _g.UpdateShippingOptionFailed:return t.meta?Bv(e,{isUpdatingShippingOption:{[t.meta.id]:!1}}):e;default:return e}}function ES(e,t){const n={};return Object.keys(e).forEach(i=>{const r=e[i],o=t?`${t}.${i}`:i;"object"==typeof r?Object.assign(n,ES(r,o)):n[o]=r}),n}function AS(e){return Object.keys(e).sort().reduce((t,n)=>Object.assign(Object.assign({},t),{[n]:e[n]}),{})}const TS={errors:{},statuses:{}};function kS(e=TS,t){return d({data:DS,errors:c(MS,bv),statuses:zS})(e,t)}function DS(e,t){if(t.type!==$g.LoadPickupOptionsSucceeded)return e;if(t.meta){const n=AS(ES({consignmentId:t.meta.consignmentId,searchArea:t.meta.searchArea}));return Ov(e,btoa(`${JSON.stringify(n)}`),t.payload)}}function MS(e=TS.errors,t){switch(t.type){case $g.LoadPickupOptionsRequested:case $g.LoadPickupOptionsSucceeded:return Ov(e,"loadError",void 0);case $g.LoadPickupOptionsFailed:return Ov(e,"loadError",t.payload);default:return e}}function zS(e=TS.statuses,t){switch(t.type){case $g.LoadPickupOptionsRequested:return Ov(e,"isLoading",!0);case $g.LoadPickupOptionsSucceeded:case $g.LoadPickupOptionsFailed:return Ov(e,"isLoading",!1);default:return e}}const NS={errors:{},statuses:{}};function xS(e=NS,t){return d({data:RS,errors:c(FS,bv),statuses:LS})(e,t)}function RS(e,t){return t.type===Og.LoadShippingCountriesSucceeded?Lv(e,t.payload):e}function FS(e=NS.errors,t){switch(t.type){case Og.LoadShippingCountriesRequested:case Og.LoadShippingCountriesSucceeded:return Ov(e,"loadError",void 0);case Og.LoadShippingCountriesFailed:return Ov(e,"loadError",t.payload);default:return e}}function LS(e=NS.statuses,t){switch(t.type){case Og.LoadShippingCountriesRequested:return Ov(e,"isLoading",!0);case Og.LoadShippingCountriesSucceeded:case Og.LoadShippingCountriesFailed:return Ov(e,"isLoading",!1);default:return e}}const BS={data:{},errors:{},statuses:{}};function jS(e=BS,t){return d({data:US,errors:c(qS,bv),statuses:VS})(e,t)}function US(e=BS.data,t){switch(t.type){case Yg.InitializeSucceeded:return Bv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!0}});case Yg.DeinitializeSucceeded:return Bv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!1}})}return e}function qS(e=BS.errors,t){switch(t.type){case Yg.InitializeRequested:case Yg.InitializeSucceeded:return Bv(e,{initializeError:void 0,initializeMethodId:void 0});case Yg.InitializeFailed:return Bv(e,{initializeError:t.payload,initializeMethodId:t.meta&&t.meta.methodId});case Yg.DeinitializeRequested:case Yg.DeinitializeSucceeded:return Bv(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Yg.DeinitializeFailed:return Bv(e,{deinitializeError:t.payload,deinitializeMethodId:t.meta&&t.meta.methodId});case Yg.UpdateAddressRequested:case Yg.UpdateAddressSucceeded:return Bv(e,{updateAddressError:void 0,updateAddressMethodId:void 0});case Yg.UpdateAddressFailed:return Bv(e,{updateAddressError:t.payload,updateAddressMethodId:t.meta&&t.meta.methodId});case Yg.SelectOptionRequested:case Yg.SelectOptionSucceeded:return Bv(e,{selectOptionError:void 0,selectOptionMethodId:void 0});case Yg.SelectOptionFailed:return Bv(e,{selectOptionError:t.payload,selectOptionMethodId:t.meta&&t.meta.methodId});case Yg.WidgetInteractionStarted:case Yg.WidgetInteractionFinished:return Bv(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Yg.WidgetInteractionFailed:return Bv(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta&&t.meta.methodId});default:return e}}function VS(e=BS.statuses,t){switch(t.type){case Yg.InitializeRequested:return Bv(e,{isInitializing:!0,initializeMethodId:t.meta&&t.meta.methodId});case Yg.InitializeFailed:case Yg.InitializeSucceeded:return Bv(e,{isInitializing:!1,initializeMethodId:void 0});case Yg.DeinitializeRequested:return Bv(e,{isDeinitializing:!0,deinitializeMethodId:t.meta&&t.meta.methodId});case Yg.DeinitializeFailed:case Yg.DeinitializeSucceeded:return Bv(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Yg.UpdateAddressRequested:return Bv(e,{isUpdatingAddress:!0,updateAddressMethodId:t.meta&&t.meta.methodId});case Yg.UpdateAddressFailed:case Yg.UpdateAddressSucceeded:return Bv(e,{isUpdatingAddress:!1,updateAddressMethodId:void 0});case Yg.SelectOptionRequested:return Bv(e,{isSelectingOption:!0,selectOptionMethodId:t.meta&&t.meta.methodId});case Yg.SelectOptionFailed:case Yg.SelectOptionSucceeded:return Bv(e,{isSelectingOption:!1,selectOptionMethodId:void 0});case Yg.WidgetInteractionStarted:return Bv(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta&&t.meta.methodId});case Yg.WidgetInteractionFinished:case Yg.WidgetInteractionFailed:return Bv(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const GS={errors:{},statuses:{}};function HS(e=GS,t){return d({data:WS,errors:c($S,bv),statuses:YS})(e,t)}function WS(e,t){return t.type===cv.SendSignInEmailSucceeded?Bv(e,t.payload):e}function $S(e=GS.errors,t){switch(t.type){case cv.SendSignInEmailRequested:case cv.SendSignInEmailSucceeded:return Ov(e,"sendError",void 0);case cv.SendSignInEmailFailed:return Ov(e,"sendError",t.payload);default:return e}}function YS(e=GS.statuses,t){switch(t.type){case cv.SendSignInEmailRequested:return Ov(e,"isSending",!0);case cv.SendSignInEmailFailed:case cv.SendSignInEmailSucceeded:return Ov(e,"isSending",!1);default:return e}}const KS={errors:{},statuses:{}};function JS(e=KS,t){return d({errors:c(ZS,bv),statuses:QS})(e,t)}function ZS(e=KS.errors,t){switch(t.type){case Eg.ApplyStoreCreditRequested:case Eg.ApplyStoreCreditSucceeded:return Ov(e,"applyError",void 0);case Eg.ApplyStoreCreditFailed:return Ov(e,"applyError",t.payload);default:return e}}function QS(e=KS.statuses,t){switch(t.type){case Eg.ApplyStoreCreditRequested:return Ov(e,"isApplying",!0);case Eg.ApplyStoreCreditSucceeded:case Eg.ApplyStoreCreditFailed:return Ov(e,"isApplying",!1);default:return e}}const XS={errors:{},statuses:{}};function e_(e=XS,t){return d({errors:c(t_,bv),statuses:n_})(e,t)}function t_(e=XS.errors,t){switch(t.type){case kg.UpdateSubscriptionsRequested:case kg.UpdateSubscriptionsSucceeded:return Ov(e,"updateError",void 0);case kg.UpdateSubscriptionsFailed:return Ov(e,"updateError",t.payload);default:return e}}function n_(e=XS.statuses,t){switch(t.type){case kg.UpdateSubscriptionsRequested:return Ov(e,"isUpdating",!0);case kg.UpdateSubscriptionsFailed:case kg.UpdateSubscriptionsSucceeded:return Ov(e,"isUpdating",!1);default:return e}}const i_={errors:{},statuses:{}};function r_(e=i_,t){return d({data:o_,errors:c(a_,bv),statuses:s_})(e,t)}function o_(e,t){var n;switch(t.type){case $t.LoadCheckoutSucceeded:case $t.UpdateCheckoutSucceeded:case Eg.ApplyStoreCreditSucceeded:case tt.UpdateBillingAddressSucceeded:case kt.ApplyCouponSucceeded:case kt.RemoveCouponSucceeded:case _g.CreateConsignmentsSucceeded:case _g.UpdateConsignmentSucceeded:case _g.DeleteConsignmentSucceeded:case _g.UpdateShippingOptionSucceeded:case _g.LoadShippingOptionsSucceeded:case Nt.ApplyGiftCertificateSucceeded:case Nt.RemoveGiftCertificateSucceeded:case rn.VerifyCheckoutSucceeded:return Bv(e,le(t.payload,["billingAddress","cart","consignments","customer","coupons","giftCertificates"]));case Mm.SubmitOrderSucceeded:return Ov(e,"orderId",t.payload&&t.payload.order.orderId);case Yt.HydrateInitialState:return Bv(e,le(null===(n=t.payload)||void 0===n?void 0:n.checkout,["billingAddress","cart","consignments","customer","coupons","giftCertificates"]));default:return e}}function a_(e=i_.errors,t){switch(t.type){case $t.LoadCheckoutRequested:case $t.LoadCheckoutSucceeded:return Ov(e,"loadError",void 0);case $t.LoadCheckoutFailed:return Ov(e,"loadError",t.payload);case $t.UpdateCheckoutRequested:case $t.UpdateCheckoutSucceeded:return Ov(e,"updateError",void 0);case $t.UpdateCheckoutFailed:return Ov(e,"updateError",t.payload);default:return e}}function s_(e=i_.statuses,t){switch(t.type){case $t.LoadCheckoutRequested:return Ov(e,"isLoading",!0);case $t.LoadCheckoutFailed:case $t.LoadCheckoutSucceeded:return Ov(e,"isLoading",!1);case $t.UpdateCheckoutRequested:return Ov(e,"isUpdating",!0);case $t.UpdateCheckoutFailed:case $t.UpdateCheckoutSucceeded:return Ov(e,"isUpdating",!1);case rn.ExecuteRequested:return Ov(e,"isExecutingSpamCheck",!0);case rn.ExecuteFailed:case rn.ExecuteSucceeded:return Ov(e,"isExecutingSpamCheck",!1);default:return e}}function d_(e,t){if(null==e)throw t?t():new Error("An unexpected error has occurred.");return e}function c_(e){return function(e){const t=Object.create(e);return function(e,t){let n=Object.getPrototypeOf(e);for(;n;)t(n),n=Object.getPrototypeOf(n)}(e,n=>{Object.getOwnPropertyNames(n).forEach(n=>{"constructor"!==n&&"function"==typeof t[n]&&"_"!==n.charAt(0)&&(t[n]=((e,t)=>(...n)=>p(e[t].call(e,...n)))(e,n))})}),t}(e)}const l_={"mollie.credit_card":{provider:"mollie",method:"credit_card"},"adyenv2.scheme":{provider:"adyenv2",method:"scheme"},"adyenv3.scheme":{provider:"adyenv3",method:"scheme"},"adyenv2.bcmc":{provider:"adyenv2",method:"bcmc"},"adyenv2.ideal":{provider:"adyenv2",method:"ideal"},"adyenv2.sepadirectdebit":{provider:"adyenv2",method:"sepadirectdebit"},"adyenv2.directEbanking":{provider:"adyenv2",method:"directEbanking"},"adyenv2.giropay":{provider:"adyenv2",method:"giropay"},braintree:{provider:"braintree",method:"credit_card"},braintreepaypal:{provider:"braintree",method:"paypal"},braintreeach:{provider:"braintree",method:"ach"},authorizenet:{provider:"authorizenet",method:"credit_card"},elavon:{provider:"elavon",method:"credit_card"},checkoutcom:{provider:"checkoutcom",method:"credit_card"},"checkoutcom.credit_card":{provider:"checkoutcom",method:"credit_card"},"checkoutcom.card":{provider:"checkoutcom",method:"card"},sagepay:{provider:"sagepay",method:"credit_card"},stripe:{provider:"stripe",method:"credit_card"},"stripev3.card":{provider:"stripev3",method:"card"},"stripeupe.card":{provider:"stripeupe",method:"card"},cybersource:{provider:"cybersource",method:"credit_card"},cybersourcev2:{provider:"cybersourcev2",method:"credit_card"},bnz:{provider:"bnz",method:"credit_card"},converge:{provider:"converge",method:"credit_card"},bluesnapv2:{provider:"bluesnapv2",method:"credit_card"},"bluesnapdirect.credit_card":{provider:"bluesnapdirect",method:"credit_card"},"bluesnapdirect.ecp":{provider:"bluesnapdirect",method:"ecp"},"bluesnapdirect.sepa_direct_debit":{provider:"bluesnapdirect",method:"sepa_direct_debit"},orbital:{provider:"orbital",method:"credit_card"},paymetric:{provider:"paymetric",method:"credit_card"},bolt:{provider:"bolt",method:"credit_card"},"barclaycard.credit_card":{provider:"barclaycard",method:"credit_card"},moneris:{provider:"moneris",method:"credit_card"},cba_mpgs:{provider:"cba_mpgs",method:"credit_card"},worldpayaccess:{provider:"worldpayaccess",method:"credit_card"},"worldpayaccess.credit_card":{provider:"worldpayaccess",method:"credit_card"},squarev2:{provider:"squarev2",method:"credit_card"},paypalcommercecreditcards:{provider:"paypalcommerce",method:"credit_card"},paypalcommerce:{provider:"paypalcommerce",method:"paypal"},bigcommerce_payments_creditcards:{provider:"bigcommerce_payments",method:"credit_card"},bigcommerce_payments:{provider:"bigcommerce_payments",method:"paypal"},tdonlinemart:{provider:"tdonlinemart",method:"credit_card"}};function u_(e){return me({firstName:e.firstName,lastName:e.lastName,company:e.company,address1:e.address1,address2:e.address2,city:e.city,stateOrProvince:e.stateOrProvince,countryCode:e.countryCode,postalCode:e.postalCode,phone:e.phone,customFields:e.customFields},G)}const h_={errors:{},statuses:{}};function p_(){const e=function(){const e=vv(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.token},e=>()=>e),t=vv(e=>e.errors.loadError,e=>()=>e),n=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((i=Ev)=>({getToken:e(i),getLoadError:t(i),isLoading:n(i)}))}(),t=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingBillingAddress))),n=vv(e=>e.errors.updateError,e=>()=>e),i=vv(e=>e.errors.continueAsGuestError,e=>()=>e),r=vv(e=>e.errors.loadError,e=>()=>e),o=vv(e=>!!e.statuses.isUpdating,e=>()=>e),a=vv(e=>!!e.statuses.isContinuingAsGuest,e=>()=>e),s=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((d=zv)=>({getBillingAddress:e(d),getBillingAddressOrThrow:t(d),getUpdateError:n(d),getContinueAsGuestError:i(d),getLoadError:r(d),isUpdating:o(d),isContinuingAsGuest:a(d),isLoading:s(d)}))}(),n=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingCart))),n=vv(e=>e.errors.loadError,e=>()=>e),i=vv(e=>!!e.statuses.isLoading,e=>()=>e),r=vv(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.locale},e=>()=>e);return Oe((o=jv)=>({getCart:e(o),getCartOrThrow:t(o),getLoadError:n(o),isLoading:i(o),getLocale:r(o)}))}(),i=function(){const e=vv(e=>e,e=>()=>e),t=vv(e=>e.statuses,e=>Pe(t=>{if(t){const n=e[t];return!0===(n&&n.isInitializing)}return ve(e,{isInitializing:!0})})),n=vv(e=>e.data,e=>Pe((t,n)=>{const i=e[t];return!!i&&(n?!0===i.initializedContainers[n]:ve(i.initializedContainers,e=>!0===e))})),i=vv(e=>e.statuses,e=>Pe(t=>{if(t){const n=e[t];return!0===(n&&n.isDeinitializing)}return ve(e,{isDeinitializing:!0})})),r=vv(e=>e.errors,e=>Pe(t=>{const n=t?e[t]:B(Ce(e),e=>!(!e||!e.initializeError));return n&&n.initializeError})),o=vv(e=>e.errors,e=>Pe(t=>{const n=t?e[t]:B(Ce(e),e=>!(!e||!e.deinitializeError));return n&&n.deinitializeError}));return Oe((a=Wv)=>({getState:e(a),isInitializing:t(a),isInitialized:n(a),isDeinitializing:i(a),getInitializeError:r(a),getDeinitializeError:o(a)}))}(),r=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.data,e=>t=>{if(!e)return;const{flashMessages:n}=e.context;return n?void 0!==t?n.filter(({type:e})=>t===e):n:void 0}),n=vv(e=>e.data,(e,{formState:t})=>t&&t.data,(e,t={customerAccount:[],shippingAddress:[],billingAddress:[]})=>()=>e?Object.assign(Object.assign({},e.storeConfig),{formFields:t}):void 0),i=vv(n,e=>()=>d_(e(),()=>new rt(et.MissingCheckoutConfig))),r=vv(e=>e.data&&e.data.context,e=>()=>e),o=vv(e=>e.meta&&e.meta.externalSource,e=>()=>e),a=vv(e=>{var t;return null===(t=e.meta)||void 0===t?void 0:t.host},e=>()=>e),s=vv(e=>{var t;return null===(t=e.meta)||void 0===t?void 0:t.locale},e=>()=>e),d=vv(e=>e.meta&&e.meta.variantIdentificationToken,e=>()=>e),c=vv(e=>e.errors.loadError,e=>()=>e),l=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((u=ef,h)=>({getConfig:e(u),getFlashMessages:t(u),getStoreConfig:n(u,{formState:h}),getStoreConfigOrThrow:i(u,{formState:h}),getContextConfig:r(u),getExternalSource:o(u),getHost:a(u),getLocale:s(u),getVariantIdentificationToken:d(u),getLoadError:c(u),isLoading:l(u)}))}(),o=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.loadError,e=>()=>e),n=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((i=Ff)=>({getCountries:e(i),getLoadError:t(i),isLoading:n(i)}))}(),a=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.removeCouponError,e=>()=>e),n=vv(e=>e.errors.applyCouponError,e=>()=>e),i=vv(e=>!!e.statuses.isApplyingCoupon,e=>()=>e),r=vv(e=>!!e.statuses.isRemovingCoupon,e=>()=>e);return Oe((o=af)=>({getCoupons:e(o),getRemoveError:t(o),getApplyError:n(o),isApplying:i(o),isRemoving:r(o)}))}(),s=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingCustomer))),n=vv(e=>e.errors.createError,e=>()=>e),i=vv(e=>!!e.statuses.isCreating,e=>()=>e),r=vv(e=>e.errors.createAddressError,e=>()=>e),o=vv(e=>!!e.statuses.isCreatingAddress,e=>()=>e);return Oe((a=gf)=>({getCustomer:e(a),getCustomerOrThrow:t(a),getCreateAccountError:n(a),isCreatingCustomerAccount:i(a),getCreateAddressError:r(a),isCreatingCustomerAddress:o(a)}))}(),d=function(){const e=vv(e=>e.errors.signInMethodId,e=>e.errors.signInError,(e,t)=>n=>{if(!n||e===n)return t}),t=vv(e=>e.errors.signOutMethodId,e=>e.errors.signOutError,(e,t)=>n=>{if(!n||e===n)return t}),n=vv(e=>e.errors.executePaymentMethodCheckoutMethodId,e=>e.errors.executePaymentMethodCheckoutError,(e,t)=>n=>{if(!n||e===n)return t}),i=vv(e=>e.errors.initializeMethodId,e=>e.errors.initializeErrors,(e,t)=>n=>{if(e&&t)return n?t[n]:t[e]}),r=vv(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>n=>{if(!n||e===n)return t}),o=vv(e=>e.statuses.signInMethodId,e=>e.statuses.isSigningIn,(e,t)=>n=>!(n&&e!==n||!t)),a=vv(e=>e.statuses.signOutMethodId,e=>e.statuses.isSigningOut,(e,t)=>n=>!(n&&e!==n||!t)),s=vv(e=>e.statuses.executePaymentMethodCheckoutMethodId,e=>e.statuses.isExecutingPaymentMethodCheckout,(e,t)=>n=>!(n&&e!==n||!t)),d=vv(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>n=>!(n&&e!==n||!t)),c=vv(e=>e.data,e=>t=>!(!e[t]||!e[t].isInitialized)),l=vv(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((u=wf)=>({getSignInError:e(u),getSignOutError:t(u),getExecutePaymentMethodCheckoutError:n(u),getInitializeError:i(u),getWidgetInteractionError:r(u),isSigningIn:o(u),isSigningOut:a(u),isExecutingPaymentMethodCheckout:s(u),isInitializing:d(u),isInitialized:c(u),isWidgetInteracting:l(u)}))}(),c=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.removeGiftCertificateError,e=>()=>e),n=vv(e=>e.errors.applyGiftCertificateError,e=>()=>e),i=vv(e=>!!e.statuses.isApplyingGiftCertificate,e=>()=>e),r=vv(e=>!!e.statuses.isRemovingGiftCertificate,e=>()=>e);return Oe((o=uf)=>({getGiftCertificates:e(o),getRemoveError:t(o),getApplyError:n(o),isApplying:i(o),isRemoving:r(o)}))}(),l=function(){const e=vv(e=>e.data,e=>t=>{if(!e)return;const n=t.gateway?`${t.gateway}.${t.id}`:t.id,i=l_[n];return i?L(e,i):[]}),t=vv(e=>e.data,(e=[])=>t=>{const n=Ce(l_);return e.find(e=>e.bigpayToken===t&&"card"===e.type&&n.some(t=>K(e,t)))}),n=vv(t,e=>t=>d_(e(t),()=>new rt(et.MissingPaymentInstrument))),i=vv(e=>e.data,e=>()=>{if(e)return U(l_,t=>L(e,e=>K(e,t)))}),r=vv(e=>e.meta,e=>()=>e),o=vv(e=>e.errors.loadError,e=>()=>e),a=vv(e=>e.errors.failedInstrument,e=>e.errors.deleteError,(e,t)=>n=>{if(!n||e===n)return t}),s=vv(e=>e.statuses.isLoading,e=>()=>!!e),d=vv(e=>e.statuses.deletingInstrument,e=>e.statuses.isDeleting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((c=pS)=>({getCardInstrument:t(c),getCardInstrumentOrThrow:n(c),getInstruments:i(c),getInstrumentsByPaymentMethod:e(c),getInstrumentsMeta:r(c),getLoadError:o(c),getDeleteError:a(c),isLoading:s(c),isDeleting:d(c)}))}(),u=function(){const e=vv(e=>e.data,e=>(t=[],n)=>{const i=B(t,{code:n});return(e?e.shippingAddress:[]).map(e=>a(e,t,i))}),t=vv(e=>e.data,e=>(t=[],n)=>{const i=B(t,{code:n});return(e?e.billingAddress:[]).map(e=>a(e,t,i))}),n=vv(e=>e.data,e=>()=>e?e.customerAccount:[]),i=vv(e=>e.extraFields,e=>()=>e&&e.address.length?e.address.map(Ke):[]),r=vv(e=>e.errors.loadError,e=>()=>e),o=vv(e=>!!e.statuses.isLoading,e=>()=>e);function a(e,t,n){return"countryCode"===e.name?function(e,t=[],n){if(!t.length)return e;const{code:i=""}=n||{},r=t.map(({code:e,name:t})=>({value:e,label:t}));return Object.assign(Object.assign({},e),{options:{items:r},default:i,type:"array",fieldType:"dropdown",itemtype:"string"})}(e,t,n):"stateOrProvince"===e.name?function(e,t){const{subdivisions:n=[],requiresState:i}=t||{};if(!n.length)return Object.assign(Object.assign({},e),{required:null!=i&&i});const r=n.map(({code:e,name:t})=>({value:e,label:t}));return Object.assign(Object.assign({},e),{name:"stateOrProvinceCode",options:{items:r},required:null==i||i,type:"array",fieldType:"dropdown",itemtype:"string"})}(e,n):"postalCode"===e.name?function(e,t){const{hasPostalCodes:n=[]}=t||{};return void 0===n?e:Object.assign(Object.assign({},e),{required:Boolean(n)})}(e,n):e}return Oe((a=Df)=>({getShippingAddressFields:e(a),getBillingAddressFields:t(a),getCustomerAccountFields:n(a),getAddressExtraFields:i(a),getLoadError:r(a),isLoading:o(a)}))}(),h=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.meta,e=>()=>e),n=vv(e=>e.data,e=>(t,n)=>B(e,n?{id:t,gateway:n}:{id:t})),i=vv(n,e=>(t,n)=>d_(e(t,n),()=>new rt(et.MissingPaymentMethod))),r=vv(e=>e.errors.loadError,e=>()=>e),o=vv(e=>e.errors.loadMethodId,e=>e.errors.loadMethodError,(e,t)=>n=>{if(!n||e===n)return t}),a=vv(e=>e.statuses.isLoading,e=>()=>!!e),s=vv(e=>e.statuses.loadMethodId,e=>e.statuses.isLoadingMethod,(e,t)=>n=>!(n&&e!==n||!t));return Oe((d=Xf)=>({getPaymentMethods:e(d),getPaymentMethodsMeta:t(d),getPaymentMethod:n(d),getPaymentMethodOrThrow:i(d),getLoadError:r(d),getLoadMethodError:o(d),isLoading:a(d),isLoadingMethod:s(d)}))}(),p=function(){const e=vv(e=>e.errors.initializeMethodId,e=>e.errors.initializeError,(e,t)=>n=>{if(!n||e===n)return t}),t=vv(e=>e.errors.executeMethodId,e=>e.errors.executeError,(e,t)=>n=>{if(!n||e===n)return t}),n=vv(e=>e.errors.finalizeMethodId,e=>e.errors.finalizeError,(e,t)=>n=>{if(!n||e===n)return t}),i=vv(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>n=>{if(!n||e===n)return t}),r=vv(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>n=>!(n&&e!==n||!t)),o=vv(e=>e.data,e=>t=>{const n=t.gatewayId?`${t.methodId}.${t.gatewayId}`:t.methodId;return!(!e[n]||!e[n].isInitialized)}),a=vv(e=>e.statuses.executeMethodId,e=>e.statuses.isExecuting,(e,t)=>n=>!(n&&e!==n||!t)),s=vv(e=>e.statuses.finalizeMethodId,e=>e.statuses.isFinalizing,(e,t)=>n=>!(n&&e!==n||!t)),d=vv(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((c=oS)=>({getInitializeError:e(c),getExecuteError:t(c),getFinalizeError:n(c),getWidgetInteractingError:i(c),isInitializing:r(c),isInitialized:o(c),isExecuting:a(c),isFinalizing:s(c),isWidgetInteracting:d(c)}))}(),m=function(){const e=vv(e=>e.data,e=>(t,n)=>{if(!e)return;const i=AS(ES({consignmentId:t,searchArea:n})),r=btoa(`${JSON.stringify(i)}`);return e[r]}),t=vv(e=>e.errors.loadError,e=>()=>e),n=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((i=TS)=>({getPickupOptions:e(i),getLoadError:t(i),isLoading:n(i)}))}(),y=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingPaymentProviderCustomer)));return Oe((n=lS)=>({getPaymentProviderCustomer:e(n),getPaymentProviderCustomerOrThrow:t(n)}))}(),g=function(){const e=vv(e=>e.data,e=>t=>e[t]);return Oe((t=SS)=>({getCheckout:e(t)}))}(),v=function(){const e=vv(e=>e.data,e=>()=>{const t=null==e?void 0:e.find(e=>!e.selectedPickupOption);return null==t?void 0:t.shippingAddress}),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingShippingAddress))),n=vv(e=>e.data,e=>()=>{const t=null==e?void 0:e.filter(e=>!e.selectedPickupOption);return t?t.map(e=>e.shippingAddress):[]}),i=vv(n,e=>()=>d_(e(),()=>new rt(et.MissingShippingAddress)));return Oe((r=IS)=>({getShippingAddress:e(r),getShippingAddressOrThrow:t(r),getShippingAddresses:n(r),getShippingAddressesOrThrow:i(r)}))}(),f=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.loadError,e=>()=>e),n=vv(e=>e.statuses.isLoading,e=>()=>!!e);return Oe((i=NS)=>({getShippingCountries:e(i),getLoadError:t(i),isLoading:n(i)}))}(),S=function(){const e=vv(e=>e.errors.updateAddressMethodId,e=>e.errors.updateAddressError,(e,t)=>n=>{if(!n||e===n)return t}),t=vv(e=>e.errors.selectOptionMethodId,e=>e.errors.selectOptionError,(e,t)=>n=>{if(!n||e===n)return t}),n=vv(e=>e.errors.initializeMethodId,e=>e.errors.initializeError,(e,t)=>n=>{if(!n||e===n)return t}),i=vv(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>n=>{if(!n||e===n)return t}),r=vv(e=>e.statuses.updateAddressMethodId,e=>e.statuses.isUpdatingAddress,(e,t)=>n=>!(n&&e!==n||!t)),o=vv(e=>e.statuses.selectOptionMethodId,e=>e.statuses.isSelectingOption,(e,t)=>n=>!(n&&e!==n||!t)),a=vv(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>n=>!(n&&e!==n||!t)),s=vv(e=>e.data,e=>t=>!(!e[t]||!e[t].isInitialized)),d=vv(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((c=BS)=>({getUpdateAddressError:e(c),getSelectOptionError:t(c),getInitializeError:n(c),getWidgetInteractionError:i(c),isUpdatingAddress:r(c),isSelectingOption:o(c),isInitializing:a(c),isInitialized:s(c),isWidgetInteracting:d(c)}))}(),_=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingConsignments))),n=vv(e=>e.data,e=>t=>{if(e&&e.length)return B(e,{id:t})}),i=vv(e=>e.data,e=>t=>{if(e&&e.length)return B(e,e=>{return n=e.shippingAddress,i=t,Y(u_(n),u_(i));var n,i})}),r=vv(e=>e.data,e=>()=>{if(e&&e.length)return e[0].selectedShippingOption}),o=vv(e=>e.errors.loadError,e=>()=>e),a=vv(e=>e.errors.createError,e=>()=>e),s=vv(e=>e.errors.loadShippingOptionsError,e=>()=>e),d=vv(e,(e,{cart:t})=>t.getCart,(e,t)=>()=>{const n=t();if(!n)return[];const i=(e()||[]).reduce((e,t)=>e.concat(t.lineItemIds),[]);return(n.lineItems.physicalItems||[]).filter(e=>i.indexOf(e.id)<0)}),c=vv(e=>e.errors.updateError,e=>t=>t?e[t]:B(e)),l=vv(e=>e.errors.deleteError,e=>t=>t?e[t]:B(e)),u=vv(i,c,a,(e,t,n)=>i=>{const r=e(i);return r?t(r.id):n()}),h=vv(e=>e.errors.updateShippingOptionError,e=>t=>t?e[t]:B(e)),p=vv(e=>e.statuses.isLoading,e=>()=>!0===e),m=vv(e=>e.statuses.isLoadingShippingOptions,e=>()=>!0===e),y=vv(e=>e.statuses.isCreating,e=>()=>!0===e),g=vv(e=>e.statuses.isUpdating,e=>t=>t?!0===e[t]:!0===B(e)),v=vv(e=>e.statuses.isDeleting,e=>t=>t?!0===e[t]:!0===B(e)),f=vv(i,g,y,(e,t,n)=>i=>{const r=e(i);return r?t(r.id):n()}),S=vv(e=>e.statuses.isUpdatingShippingOption,e=>t=>t?!0===e[t]:!0===B(e));return Oe((_=IS,w)=>({getConsignments:e(_),getConsignmentsOrThrow:t(_),getConsignmentById:n(_),getConsignmentByAddress:i(_),getShippingOption:r(_),getLoadError:o(_),getCreateError:a(_),getLoadShippingOptionsError:s(_),getUnassignedItems:d(_,{cart:w}),getUpdateError:c(_),getDeleteError:l(_),getItemAssignmentError:u(_),getUpdateShippingOptionError:h(_),isLoading:p(_),isLoadingShippingOptions:m(_),isCreating:y(_),isUpdating:g(_),isDeleting:v(_),isAssigningItems:f(_),isUpdatingShippingOption:S(_)}))}(),w=function(){const e=vv(e=>e.data,(e,{billingAddress:t})=>t.getBillingAddress,(e,{cart:t})=>t.getCart,(e,{customer:t})=>t.getCustomer,(e,{consignments:t})=>t.getConsignments,(e,{coupons:t})=>t.getCoupons,(e,{giftCertificates:t})=>t.getGiftCertificates,(e,t,n,i,r,o,a)=>()=>{const s=t(),d=n(),c=i(),l=r()||[],u=o()||[],h=a()||[];if(e&&d&&c)return Object.assign(Object.assign({},e),{billingAddress:s,cart:d,customer:c,consignments:l,coupons:u,giftCertificates:h})}),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingCheckout))),n=vv(e,e=>t=>{const n=e();if(!n)return;const i=n.grandTotal||0,r=n.customer.storeCredit||0;return t?Math.max(i-r,0):n.outstandingBalance}),i=vv(e=>e.errors.loadError,e=>()=>e),r=vv(e=>e.errors.updateError,e=>()=>e),o=vv(e=>e.statuses.isExecutingSpamCheck,e=>()=>!0===e),a=vv(e=>e.statuses.isLoading,e=>()=>!0===e),s=vv(e=>e.statuses.isUpdating,e=>()=>!0===e);return Oe((d=i_,c,l,u,h,p,m)=>({getCheckout:e(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getCheckoutOrThrow:t(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getOutstandingBalance:n(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getLoadError:i(d),getUpdateError:r(d),isExecutingSpamCheck:o(d),isLoading:a(d),isUpdating:s(d)}))}(),I=function(){const e=vv(e=>e.data,(e,{billingAddress:t})=>t.getOrderBillingAddress(),(e,{coupons:t})=>t.getCoupons(),(e,t,n=[])=>()=>{if(e&&t)return Object.assign(Object.assign({},e),{billingAddress:t,coupons:n})}),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingOrder))),n=vv(e=>e.meta,e=>()=>e),i=vv(e=>e.errors.loadError,e=>()=>e),r=vv(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.payments},(e=[])=>t=>{const n=e.find(({providerId:e})=>e===t);return null==n?void 0:n.paymentId}),o=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((a=qf,s,d)=>({getOrder:e(a,{billingAddress:s,coupons:d}),getOrderOrThrow:t(a,{billingAddress:s,coupons:d}),getOrderMeta:n(a),getLoadError:i(a),getPaymentId:r(a),isLoading:o(a)}))}(),C=function(){const e=vv(e=>e.data,e=>()=>e);return Oe((t=Yf)=>({getOrderBillingAddress:e(t)}))}(),b=function(){const e=vv(({order:e})=>e.getOrderMeta,e=>()=>{const t=e();return t&&t.payment}),t=vv(({order:e})=>e.getOrder,e=>()=>{const t=e();return B(t&&t.payments,({providerId:e})=>"giftcertificate"!==e&&"storecredit"!==e)}),n=vv(({checkout:e})=>e.getCheckout,e=>()=>{const t=e();return B(t&&t.payments,({providerType:e})=>"PAYMENT_TYPE_HOSTED"===e)}),i=vv(e,n,t,(e,t,n)=>()=>{const i=e();if(i&&i.id)return{providerId:i.id,gatewayId:i.gateway};const r=t()||n();return r&&r.providerId?{providerId:r.providerId,gatewayId:r.gatewayId}:void 0}),r=vv(i,e=>()=>d_(e(),()=>new rt(et.MissingPaymentId))),o=vv(e,n,t,(e,t,n)=>()=>{const i=e();if(i&&i.status)return i.status.replace("PAYMENT_STATUS_","");const r=t()||n();return r?r.detail.step:void 0}),a=vv(o,e=>()=>d_(e(),()=>new rt(et.MissingPaymentStatus))),s=vv(({order:e})=>e.getOrderMeta,e=>()=>{const t=e();return t&&t.token}),d=vv(s,e=>()=>d_(e(),()=>new rt(et.MissingPaymentToken))),c=vv(e,e=>()=>{const t=e();return t&&t.redirectUrl}),l=vv(c,e=>()=>d_(e(),()=>new rt(et.MissingPaymentRedirectUrl))),u=vv(({checkout:e})=>e.getOutstandingBalance,e=>(t=!1)=>{const n=e(t);return!!n&&n>0}),h=vv(o,e=>t=>!(!t||!t.nonce)||"ACKNOWLEDGE"===e()||e()===$y);return Oe((e,t)=>({getPaymentId:i({checkout:e,order:t}),getPaymentIdOrThrow:r({checkout:e,order:t}),getPaymentStatus:o({checkout:e,order:t}),getPaymentStatusOrThrow:a({checkout:e,order:t}),getPaymentToken:s({checkout:e,order:t}),getPaymentTokenOrThrow:d({checkout:e,order:t}),getPaymentRedirectUrl:c({checkout:e,order:t}),getPaymentRedirectUrlOrThrow:l({checkout:e,order:t}),isPaymentDataRequired:u({checkout:e,order:t}),isPaymentDataSubmitted:h({checkout:e,order:t})}))}(),P=function(){const e=vv(e=>e.errors.applyError,e=>()=>e),t=vv(e=>!!e.statuses.isApplying,e=>()=>e);return Oe((n=h_)=>({getApplyError:e(n),isApplying:t(n)}))}(),O=function(){const e=vv(e=>e.errors.updateError,e=>()=>e),t=vv(e=>!!e.statuses.isUpdating,e=>()=>e);return Oe((n=XS)=>({getUpdateError:e(n),isUpdating:t(n)}))}(),E=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.sendError,e=>()=>e),n=vv(e=>!!e.statuses.isSending,e=>()=>e);return Oe((i=GS)=>({getEmail:e(i),getSendError:t(i),isSending:n(i)}))}(),A=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.data,e=>t=>null==e?void 0:e.find(e=>e.region===t)),n=vv(e=>e.errors.loadError,e=>()=>e),i=vv(e=>e.statuses.isLoading,e=>()=>!!e);return Oe((r=Of)=>({getExtensions:e(r),getExtensionByRegion:t(r),getLoadError:n(r),isLoading:i(r)}))}();return(T,k={})=>{const D=e(T.b2bToken),M=t(T.billingAddress),z=n(T.cart),N=i(T.checkoutButton),x=o(T.countries),R=a(T.coupons),F=s(T.customer),L=d(T.customerStrategies),B=A(T.extensions),j=u(T.formFields),U=c(T.giftCertificates),q=l(T.instruments),V=C(T.orderBillingAddress),G=h(T.paymentMethods),H=y(T.paymentProviderCustomer),W=p(T.paymentStrategies),$=m(T.pickupOptions),Y=g(T.remoteCheckout),K=v(T.consignments),J=f(T.shippingCountries),Z=S(T.shippingStrategies),Q=O(T.subscriptions),X=P(T.storeCredit),ee=E(T.signInEmail),te=_(T.consignments,z),ne=w(T.checkout,M,z,te,R,F,U),ie=I(T.order,V,R),re=b(ne,ie),oe={b2bToken:D,billingAddress:M,cart:z,checkout:ne,checkoutButton:N,config:r(T.config,T.formFields),consignments:te,countries:x,coupons:R,customer:F,customerStrategies:L,extensions:B,form:j,giftCertificates:U,instruments:q,order:ie,orderBillingAddress:V,payment:re,paymentMethods:G,paymentProviderCustomer:H,paymentStrategies:W,pickupOptions:$,remoteCheckout:Y,shippingAddress:K,shippingCountries:J,shippingStrategies:Z,signInEmail:ee,subscriptions:Q,storeCredit:X};return k.shouldWarnMutation?(ae=oe,Object.keys(ae).reduce((e,t)=>(e[t]=c_(ae[t]),e),{})):oe;var ae}}function m_(e={},t){const n=(o=function(){const e=new Iv;return["catalog_only","empty_cart","invalid_order_id","invalid_order_token","missing_order_token","missing_provider_token","missing_shipping_method","order_completion_error","order_could_not_be_finalized_error","order_create_failed","provider_fatal_error","provider_setup_error","stock_too_low"].forEach(t=>{e.register(t,(e,t)=>new Sv(e,t))}),e.register("invalid_payment_provider",e=>new Xr(e)),e.register("payment_config_not_found",e=>new Xr(e)),e}(),e=>S(e).pipe(P(e=>{if(e instanceof Error||e.payload instanceof Error)throw e;if((t=e.payload)&&"object"==typeof t&&["body","headers","status","statusText"].every(e=>Object.prototype.hasOwnProperty.call(t,e))){const t=e.payload.body&&e.payload.body.detail;throw Object.assign(Object.assign({},e),{payload:o.createError(e.payload,t)})}var t;throw e}))),i=p_(),r=d({b2bToken:Av,billingAddress:Nv,cart:Uv,checkout:r_,checkoutButton:Jv,config:tf,consignments:CS,countries:Lf,coupons:sf,customer:vf,customerStrategies:If,extensions:Ef,formFields:Mf,giftCertificates:hf,instruments:mS,orderBillingAddress:Kf,order:Vf,payment:Zf,paymentMethods:eS,paymentStrategies:aS,pickupOptions:kS,paymentProviderCustomer:uS,remoteCheckout:_S,shippingCountries:xS,shippingStrategies:jS,signInEmail:HS,subscriptions:e_,storeCredit:JS});var o;return u(r,e,Object.assign({actionTransformer:n,stateTransformer:e=>i(e)},t))}function y_(e){"https:"!==document.location.protocol&&wt().warn("The BigCommerce Checkout SDK should not be used on a non-HTTPS page"),"production"!==vt()&&wt().warn("Note that the development build is not optimized. To create a production build, set process​.env.NODE_ENV to `production`.");const t={meta:{externalSource:e&&e.externalSource,host:null==e?void 0:e.host,locale:null==e?void 0:e.locale,variantIdentificationToken:window.checkoutVariantIdentificationToken},errors:{},statuses:{}},{locale:i="",shouldWarnMutation:r=!0}=e||{},s=n({host:e&&e.host}),d=m_({config:t},{shouldWarnMutation:r}),c=new gt(s,{getBasePath:()=>{var e,t;return null!==(t=null===(e=d.getState().config.getStoreConfig())||void 0===e?void 0:e.links.baseUrl)&&void 0!==t?t:void 0},getFeatures:()=>{var e,t,n;return null!==(n=null===(t=null===(e=d.getState().config.getStoreConfig())||void 0===e?void 0:e.checkoutSettings)||void 0===t?void 0:t.features)&&void 0!==n?n:{}}}),l=Gm(d),u=new jm(c),h=new en(c),p=new bt(new Tt(s)),m=Sn(o()),y=new _n(c),g=new pn(m,y),v=new Vm(u,new ny(h)),f=new Ng(new xg(c)),S=new on(new an(c)),_=new nn(h,p,S),w=Hg(d,c),I=function(e,t,n={useFallback:!1}){const{useFallback:i}=n,r=new Gt(i);for(const[,n]of Object.entries(t))if(Ut(n))for(const t of n.resolveIds)r.register(t,()=>n(e));return r}(w,He,{useFallback:!0}),C=function(e,t){const n=new Gt;for(const[,i]of Object.entries(t))if(Ut(i))for(const t of i.resolveIds)n.register(t,()=>i(e));return n}(w,Ge),b=new xn(new Rn(c)),P=new Hn,O=new Kn(d,P),E=mt(d,function(){const e=function(){const e=vv(({checkout:e})=>e.getCheckout,e=>Bg(e)),t=vv(({order:e})=>e.getOrder,e=>Bg(e)),n=vv(({config:e})=>e.getStoreConfig,e=>Bg(e)),i=vv(({shippingAddress:e})=>e.getShippingAddress,({config:e})=>e.getContextConfig,(e,t)=>Bg(()=>{const n=e(),i=t();if(!n){if(!i||!i.geoCountryCode)return;return{firstName:"",lastName:"",company:"",address1:"",address2:"",city:"",stateOrProvince:"",stateOrProvinceCode:"",postalCode:"",country:"",phone:"",customFields:[],countryCode:i.geoCountryCode}}return n})),r=vv(({consignments:e})=>e.getConsignments,e=>Bg(()=>{const t=e(),n=null==t?void 0:t.find(e=>!e.selectedPickupOption);return null==n?void 0:n.availableShippingOptions})),o=vv(({consignments:e})=>e.getConsignments,e=>Bg(e)),a=vv(({consignments:e})=>e.getConsignments,e=>Bg(()=>{const t=e(),n=null==t?void 0:t.find(e=>!e.selectedPickupOption);return null==n?void 0:n.selectedShippingOption})),s=vv(({shippingCountries:e})=>e.getShippingCountries,e=>Bg(e)),d=vv(({billingAddress:e})=>e.getBillingAddress,({config:e})=>e.getContextConfig,(e,t)=>Bg(()=>{const n=e(),i=t();return(!n||Ce(le(n,"shouldSaveAddress","email","id")).every(e=>!e||!e.length))&&i&&i.geoCountryCode?{id:n?n.id:"",firstName:"",lastName:"",company:"",address1:"",address2:"",city:"",email:n?n.email:"",stateOrProvince:"",stateOrProvinceCode:"",postalCode:"",country:"",phone:"",customFields:[],countryCode:i.geoCountryCode}:n})),c=vv(({countries:e})=>e.getCountries,e=>Bg(e)),l=vv(({paymentMethods:e})=>e.getPaymentMethods,e=>Bg(e)),u=vv(({paymentMethods:e})=>e.getPaymentMethod,e=>Bg(e)),h=vv(({payment:e})=>e.getPaymentId,({paymentMethods:e})=>e.getPaymentMethod,(e,t)=>Bg(()=>{const n=e();return n&&t(n.providerId,n.gatewayId)})),p=vv(({cart:e})=>e.getCart,e=>Bg(e)),m=vv(({coupons:e})=>e.getCoupons,e=>Bg(e)),y=vv(({giftCertificates:e})=>e.getGiftCertificates,e=>Bg(e)),g=vv(({customer:e})=>e.getCustomer,e=>Bg(e)),v=vv(({signInEmail:e})=>e.getEmail,e=>Bg(e)),f=vv(({b2bToken:e})=>e.getToken,e=>Bg(e)),S=vv(({payment:e})=>e.isPaymentDataRequired,e=>Bg(e)),_=vv(({payment:e})=>e.isPaymentDataSubmitted,({paymentMethods:e})=>e.getPaymentMethod,(e,t)=>Bg((n,i)=>e(t(n,i)))),w=vv(({instruments:e})=>e.getInstruments,({instruments:e})=>e.getInstrumentsByPaymentMethod,(e,t)=>Bg(function(n){return n?t(n):e()})),I=vv(({form:e})=>e.getCustomerAccountFields,e=>Bg(e)),C=vv(({form:e})=>e.getBillingAddressFields,({countries:e})=>e.getCountries,(e,t)=>Bg(n=>e(t(),n))),b=vv(({form:e})=>e.getShippingAddressFields,({shippingCountries:e})=>e.getShippingCountries,(e,t)=>Bg(n=>e(t(),n))),P=vv(({form:e})=>e.getAddressExtraFields,e=>Bg(e)),O=vv(({config:e})=>e.getFlashMessages,e=>Bg(e)),E=vv(({pickupOptions:e})=>e.getPickupOptions,e=>Bg(e)),A=vv(({config:e})=>e.getStoreConfig,e=>Bg(()=>{const t=e();if(t)return t.checkoutSettings.checkoutUserExperienceSettings})),T=vv(({extensions:e})=>e.getExtensions,e=>Bg(e)),k=vv(({paymentProviderCustomer:e})=>e.getPaymentProviderCustomer,e=>Bg(e)),D=vv(({extensions:e})=>e.getExtensionByRegion,e=>Bg(e));return Oe(M=>({getCheckout:e(M),getOrder:t(M),getConfig:n(M),getExtensions:T(M),getExtensionByRegion:D(M),getFlashMessages:O(M),getShippingAddress:i(M),getShippingOptions:r(M),getConsignments:o(M),getSelectedShippingOption:a(M),getShippingCountries:s(M),getBillingAddress:d(M),getBillingCountries:c(M),getPaymentMethods:l(M),getPaymentMethod:u(M),getSelectedPaymentMethod:h(M),getCart:p(M),getCoupons:m(M),getGiftCertificates:y(M),getCustomer:g(M),isPaymentDataRequired:S(M),isPaymentDataSubmitted:_(M),getSignInEmail:v(M),getB2BToken:f(M),getInstruments:w(M),getCustomerAccountFields:I(M),getBillingAddressFields:C(M),getShippingAddressFields:b(M),getAddressExtraFields:P(M),getPickupOptions:E(M),getUserExperienceSettings:A(M),getPaymentProviderCustomer:k(M)}))}(),t=function(){const e=fv(e=>e,e=>()=>{for(const t of Object.keys(e)){const n=e[t]();if(n)return n}}),t=vv(({shippingStrategies:e})=>e.getSelectOptionError,({consignments:e})=>e.getUpdateShippingOptionError,(e,t)=>n=>e()||t(n));return Oe(n=>{const i={getLoadCheckoutError:n.checkout.getLoadError,getUpdateCheckoutError:n.checkout.getUpdateError,getSubmitOrderError:n.paymentStrategies.getExecuteError,getFinalizeOrderError:n.paymentStrategies.getFinalizeError,getLoadOrderError:n.order.getLoadError,getLoadCartError:n.cart.getLoadError,getLoadBillingCountriesError:n.countries.getLoadError,getLoadShippingCountriesError:n.shippingCountries.getLoadError,getLoadPaymentMethodsError:n.paymentMethods.getLoadError,getLoadPaymentMethodError:n.paymentMethods.getLoadMethodError,getInitializePaymentError:n.paymentStrategies.getInitializeError,getSignInError:n.customerStrategies.getSignInError,getSignOutError:n.customerStrategies.getSignOutError,getInitializeCustomerError:n.customerStrategies.getInitializeError,getLoadShippingOptionsError:n.consignments.getLoadShippingOptionsError,getSelectShippingOptionError:t(n),getContinueAsGuestError:n.billingAddress.getContinueAsGuestError,getUpdateBillingAddressError:n.billingAddress.getUpdateError,getUpdateSubscriptionsError:n.subscriptions.getUpdateError,getUpdateShippingAddressError:n.shippingStrategies.getUpdateAddressError,getDeleteConsignmentError:n.consignments.getDeleteError,getUpdateConsignmentError:n.consignments.getUpdateError,getCreateConsignmentsError:n.consignments.getCreateError,getInitializeShippingError:n.shippingStrategies.getInitializeError,getApplyStoreCreditError:n.storeCredit.getApplyError,getApplyCouponError:n.coupons.getApplyError,getRemoveCouponError:n.coupons.getRemoveError,getApplyGiftCertificateError:n.giftCertificates.getApplyError,getRemoveGiftCertificateError:n.giftCertificates.getRemoveError,getLoadInstrumentsError:n.instruments.getLoadError,getDeleteInstrumentError:n.instruments.getDeleteError,getLoadConfigError:n.config.getLoadError,getSignInEmailError:n.signInEmail.getSendError,getLoadB2BTokenError:n.b2bToken.getLoadError,getCreateCustomerAccountError:n.customer.getCreateAccountError,getCreateCustomerAddressError:n.customer.getCreateAddressError,getPickupOptionsError:n.pickupOptions.getLoadError,getLoadExtensionsError:n.extensions.getLoadError};return Object.assign({getError:e(i)},i)})}(),n=function(){const e=fv(e=>e,e=>()=>Object.keys(e).some(t=>e[t]())),t=vv(({shippingStrategies:e})=>e.isSelectingOption,({consignments:e})=>e.isUpdatingShippingOption,(e,t)=>n=>e()||t(n)),n=vv(({customerStrategies:e})=>e.isInitializing,({customerStrategies:e})=>e.isSigningIn,({customerStrategies:e})=>e.isSigningOut,({customerStrategies:e})=>e.isExecutingPaymentMethodCheckout,({customerStrategies:e})=>e.isWidgetInteracting,(e,t,n,i,r)=>o=>e(o)||t(o)||n(o)||i(o)||r(o)),i=vv(({shippingStrategies:e})=>e.isInitializing,({shippingStrategies:e})=>e.isUpdatingAddress,({shippingStrategies:e})=>e.isSelectingOption,({shippingStrategies:e})=>e.isWidgetInteracting,(e,t,n,i)=>r=>e(r)||t(r)||n(r)||i(r)),r=vv(({paymentStrategies:e})=>e.isInitializing,({paymentStrategies:e})=>e.isExecuting,({paymentStrategies:e})=>e.isFinalizing,({paymentStrategies:e})=>e.isWidgetInteracting,(e,t,n,i)=>r=>e(r)||t(r)||n(r)||i(r)),o=vv(({paymentStrategies:e})=>e.isExecuting,({checkout:e})=>e.isExecutingSpamCheck,(e,t)=>n=>e(n)||t());return Oe(a=>{const s={isLoadingCheckout:a.checkout.isLoading,isUpdatingCheckout:a.checkout.isUpdating,isExecutingSpamCheck:a.checkout.isExecutingSpamCheck,isSubmittingOrder:o(a),isFinalizingOrder:a.paymentStrategies.isFinalizing,isLoadingOrder:a.order.isLoading,isLoadingCart:a.cart.isLoading,isLoadingBillingCountries:a.countries.isLoading,isLoadingShippingCountries:a.shippingCountries.isLoading,isLoadingPaymentMethods:a.paymentMethods.isLoading,isLoadingPaymentMethod:a.paymentMethods.isLoadingMethod,isInitializingPayment:a.paymentStrategies.isInitializing,isSigningIn:a.customerStrategies.isSigningIn,isSigningOut:a.customerStrategies.isSigningOut,isExecutingPaymentMethodCheckout:a.customerStrategies.isExecutingPaymentMethodCheckout,isInitializingCustomer:a.customerStrategies.isInitializing,isInitializedCustomer:a.customerStrategies.isInitialized,isLoadingShippingOptions:a.consignments.isLoadingShippingOptions,isSelectingShippingOption:t(a),isUpdatingBillingAddress:a.billingAddress.isUpdating,isUpdatingSubscriptions:a.subscriptions.isUpdating,isCreatingCustomerAccount:a.customer.isCreatingCustomerAccount,isCreatingCustomerAddress:a.customer.isCreatingCustomerAddress,isContinuingAsGuest:a.billingAddress.isContinuingAsGuest,isUpdatingShippingAddress:a.shippingStrategies.isUpdatingAddress,isUpdatingConsignment:a.consignments.isUpdating,isDeletingConsignment:a.consignments.isDeleting,isCreatingConsignments:a.consignments.isCreating,isInitializingShipping:a.shippingStrategies.isInitializing,isApplyingStoreCredit:a.storeCredit.isApplying,isApplyingCoupon:a.coupons.isApplying,isRemovingCoupon:a.coupons.isRemoving,isApplyingGiftCertificate:a.giftCertificates.isApplying,isRemovingGiftCertificate:a.giftCertificates.isRemoving,isLoadingInstruments:a.instruments.isLoading,isDeletingInstrument:a.instruments.isDeleting,isLoadingConfig:a.config.isLoading,isSendingSignInEmail:a.signInEmail.isSending,isLoadingB2BToken:a.b2bToken.isLoading,isCustomerStepPending:n(a),isShippingStepPending:i(a),isPaymentStepPending:r(a),isLoadingPickupOptions:a.pickupOptions.isLoading};return Object.assign({isPending:e(s)},s)})}();return i=>({data:e(i),errors:t(i),statuses:n(i)})}());return new yv(d,E,O,function(e,t){const n={[$n.ConsignmentsChanged]:Zn};return new Jn(e,t,n)}(E,O),new Qe(new nt(s)),new st(new ut(c),f),_,p,new Kt(new Jt(c),_,g),new Cg(new Pg(c),h),new zm(new Nm(c,{locale:i})),new Dt(new Lt(c)),new Qt(function(e,t){const n=new Vt,i=a(),r=new en(t),o=new nn(r,new bt(new Tt(t)),new on(new an(t))),s=new pn(Sn(i),new _n(t)),d=new Kt(new Jt(t),o,s);return n.register("default",()=>new wn(e,d)),n}(d,c),C,w),new yt,new Bt(new jt(c)),new Wg(new Zg(l,c)),v,new Wm(new $m(c)),new Xm(function(e,t,n){const i=new Wy({defaultToken:Zm.CREDIT_CARD}),r=new Gy,a=new by(t),s=new en(n),d=new ny(s),c=new Vm(new jm(n),d),l=new cy(Sn(o())),u=new Cy(a,c,r,l),h=Ee(),p=((e,t)=>new ig(new ng(e,t)))(h,l),m=new Iy(e);return i.register(Zm.CONVERGE,()=>new Zy(e,c,u,m,h)),i.register(Zm.PPSDK,()=>new dg(e,c,((e,t,n,i,r)=>{const o=new lg;return o.register(ag.CARD,()=>new hg(e,t,r,i)),o.register(ag.NONE,()=>new pg(n,i)),o.register(ag.UNSUPPORTED,()=>{}),o})(e,c,n,p,m),new vg(n,p),new iy("PPSDK"))),i}(d,l,c),I,v,g,w),new Qg(new Xg(c)),new Ag(new Tg(c,{locale:i}),d),new ev(function(e,t){const n=new Vt,i=Hg(e),r=new en(t),o=new Pg(t),s=new Cg(o,r),d=new Wm(new $m(t)),c=a(),l=new Ng(new xg(t)),u=new st(new ut(t),l),h=window,p=new Ei(i);return n.register("amazonpay",()=>new iv(e,s,new Wm(new $m(t)),gi(),new ev(n))),n.register("stripeupe",()=>new lv(e,new Ra(c),s,d)),n.register("braintreeacceleratedcheckout",()=>new ov(e,u,s,d,new Sg,new _o(new Hi(a(),h,p),h))),n.register("paypalcommerceacceleratedcheckout",()=>new dv(e,u,s,d,new Sg,Cs(),nd())),n.register("default",()=>new av(e,s)),n}(d,c)),new uv(new hv(c)),g,new Dg(new Mg(c)),f,S,b,P)}class g_ extends Qn{constructor(e){super(e||"An unexpected error has occurred during config creation process. Please try again later."),this.name="AmazonPayV2ConfigCreationError",this.type="amazon_pay_v2_config_creation_error"}}function v_(e){return e instanceof Object&&"buyNowInitializeOptions"in e}var f_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class S_{constructor(e,t,n){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t,this.amazonPayV2ConfigRequestSender=n}initialize(e){var t;return f_(this,void 0,void 0,function*(){const{methodId:n,containerId:i,amazonpay:r}=e,{buttonColor:o}=r||{};if(!n||!i)throw new fi('Unable to proceed because "methodId" or "containerId" argument is not provided.');const{getPaymentMethodOrThrow:a}=this.paymentIntegrationService.getState(),s=a(n),{initializationData:d}=s;yield this.amazonPayV2PaymentProcessor.initialize(s),r||(yield this.paymentIntegrationService.loadDefaultCheckout());const c=v_(r)?void 0:r;v_(r)&&"function"==typeof(null===(t=r.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody)&&(this._buyNowInitializeOptions=r.buyNowInitializeOptions,this.amazonPayV2PaymentProcessor.updateBuyNowFlowFlag(!0)),this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:this.paymentIntegrationService.getState(),containerId:i,methodId:n,options:c,placement:si.Cart,buttonColor:o,isButtonMicroTextDisabled:null==d?void 0:d.isButtonMicroTextDisabled}),this._buyNowInitializeOptions&&this.amazonPayV2PaymentProcessor.prepareCheckoutWithCreationRequestConfig(this._getCheckoutCreationRequestConfig.bind(this))})}deinitialize(){return this.amazonPayV2PaymentProcessor.deinitialize()}_createBuyNowCartOrThrow(){var e,t;return f_(this,void 0,void 0,function*(){const n=null===(t=null===(e=this._buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody)||void 0===t?void 0:t.call(e);if(!n)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(n)}catch(e){throw new er}})}_createCheckoutConfig(e){return f_(this,void 0,void 0,function*(){try{const t=(yield this.amazonPayV2ConfigRequestSender.createCheckoutConfig(e)).body,{payload:n,public_key:i}=t,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const t=n(),i=new __(t),r=gi();return new S_(e,r,i)},[{id:"amazonpay"}]);var I_,C_,b_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}(I_||(I_={})),function(e){e.Black="black",e.White="white",e.WhiteBorder="white-border"}(C_||(C_={}));class P_{constructor(e,t,n,i,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._braintreeSdk=i,this._applePayScriptLoader=r,this._onAuthorizeCallback=ce,this._subTotalLabel=I_.Subtotal,this._shippingLabel=I_.Shipping}initialize(e){var t,n;return b_(this,void 0,void 0,function*(){const{methodId:i,containerId:r,applepay:o}=e;if(!i||!o)throw new ti(Xn.MissingPaymentMethod);yield this._applePayScriptLoader.loadSdk();const{onPaymentAuthorize:a,buyNowInitializeOptions:s,requiresShipping:d}=o;this._requiresShipping=d,this._buyNowInitializeOptions=s,this._onAuthorizeCallback=a,s||(yield this._paymentIntegrationService.loadDefaultCheckout()),yield this._paymentIntegrationService.loadPaymentMethod(i);const c=this._paymentIntegrationService.getState();return this._paymentMethod=c.getPaymentMethodOrThrow(i),c.getCart()&&(yield this._paymentIntegrationService.verifyCheckoutSpamProtection()),(null===(t=this._paymentMethod.initializationData)||void 0===t?void 0:t.gateway)===Vi.BRAINTREE&&this._paymentMethod.clientToken&&this._braintreeSdk.initialize(this._paymentMethod.clientToken),this._applePayButton=this._createButton(r,null===(n=this._paymentMethod.initializationData)||void 0===n?void 0:n.styleOption),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),Promise.resolve()})}deinitialize(){return Promise.resolve()}_createButton(e,t){const n=document.getElementById(e);if(!n)throw new fi("Unable to create wallet button without valid container ID.");const i=this._createApplePayButtonElement(t);return n.appendChild(i),i}_createApplePayButtonElement(e){const t=document.createElement("apple-pay-button");return t.setAttribute("buttonstyle",(e=>{switch(e){case C_.White:return"white";case C_.WhiteBorder:return"white-outline";case C_.Black:default:return"black"}})(e)),t.setAttribute("type","plain"),t.setAttribute("style","--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;"),t}_handleWalletButtonClick(e){var t;return b_(this,void 0,void 0,function*(){if(e.preventDefault(),!this._paymentMethod||!this._paymentMethod.initializationData)throw new ti(Xn.MissingPaymentMethod);if(this._buyNowInitializeOptions&&"function"==typeof this._buyNowInitializeOptions.getBuyNowCartRequestBody){const{countryCode:e,currencyCode:n,merchantCapabilities:i,supportedNetworks:r,storeName:o}=this._paymentMethod.initializationData,a=this._getRequestWithEmptyTotal(e,n,r,i);this._requiresShipping&&(null===(t=a.requiredShippingContactFields)||void 0===t||t.push("postalAddress"));const s=this._sessionFactory.create(a);this._handleApplePayEvents(s,this._paymentMethod,o),s.begin()}else{const e=this._paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getStoreConfigOrThrow(),i=e.getCheckoutOrThrow(),r=this._getBaseRequest(t,i,n,this._paymentMethod),o=this._sessionFactory.create(r);this._handleApplePayEvents(o,this._paymentMethod,n.storeProfile.storeName),o.begin()}})}_getRequestWithEmptyTotal(e,t,n,i){return{countryCode:e,currencyCode:t,supportedNetworks:n,merchantCapabilities:i,total:{label:"",amount:"0",type:"pending"},requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"]}}_getBaseRequest(e,t,n,i){var r;const{storeProfile:{storeCountryCode:o,storeName:a}}=n,{currency:{code:s,decimalPlaces:d}}=e,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=i,u=e.lineItems.physicalItems.length>0,h={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:o,currencyCode:s,merchantCapabilities:c,supportedNetworks:l,lineItems:[],total:u?{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"pending"}:{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"final"}};if(u)null===(r=h.requiredShippingContactFields)||void 0===r||r.push("postalAddress");else{const e=[{label:this._subTotalLabel,amount:`${t.subtotal.toFixed(d)}`}];t.taxes.forEach(t=>e.push({label:t.name,amount:`${t.amount.toFixed(d)}`})),h.lineItems=e}return h}_handleApplePayEvents(e,t,n){e.onvalidatemerchant=n=>b_(this,void 0,void 0,function*(){try{const{body:i}=yield this._onValidateMerchant(t,n);e.completeMerchantValidation(i)}catch(e){throw new Error("Merchant validation failed")}}),this._buyNowInitializeOptions&&!this._requiresShipping&&(e.onpaymentmethodselected=()=>b_(this,void 0,void 0,function*(){yield this._createBuyNowCart(),this._handlePaymentMethodSelected(e)})),e.onshippingcontactselected=t=>b_(this,void 0,void 0,function*(){this._buyNowInitializeOptions&&this._requiresShipping&&(yield this._createBuyNowCart()),yield this._handleShippingContactSelected(e,n,t)}),e.onshippingmethodselected=t=>b_(this,void 0,void 0,function*(){yield this._handleShippingMethodSelected(e,n,t)}),e.oncancel=()=>b_(this,void 0,void 0,function*(){try{const e=`/remote-checkout/${t.id}/signout`;return yield this._requestSender.get(e),yield this._paymentIntegrationService.loadCheckout()}catch(e){throw new Wi}}),e.onpaymentauthorized=n=>b_(this,void 0,void 0,function*(){return this._onPaymentAuthorized(n,e,t)})}_createBuyNowCart(){var e,t;return b_(this,void 0,void 0,function*(){try{const n=null===(t=null===(e=this._buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody)||void 0===t?void 0:t.call(e);if(!n)throw new ti(Xn.MissingCart);const i=yield this._paymentIntegrationService.createBuyNowCart(n);yield this._paymentIntegrationService.loadCheckout(i.id);const r=this._paymentIntegrationService.getState(),{shouldExecuteSpamCheck:o}=r.getCheckoutOrThrow();o&&(yield this._paymentIntegrationService.verifyCheckoutSpamProtection())}catch(e){throw new er}})}_handlePaymentMethodSelected(e){const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getStoreConfigOrThrow(),r=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new ti(Xn.MissingPaymentMethod);const o=this._getBaseRequest(n,r,i,this._paymentMethod);delete o.total.type,e.completePaymentMethodSelection({newTotal:o.total,newLineItems:o.lineItems})}_handleShippingContactSelected(e,t,n){var i;return b_(this,void 0,void 0,function*(){const r=this._transformContactToAddress(n.shippingContact);try{yield this._paymentIntegrationService.updateShippingAddress(r)}catch(t){throw e.abort(),new Error("Shipping address update failed")}let o=this._paymentIntegrationService.getState();const{currency:{decimalPlaces:a}}=o.getCartOrThrow();let s=o.getCheckoutOrThrow();const d=null===(i=s.consignments[0].selectedShippingOption)||void 0===i?void 0:i.id,c=s.consignments[0].availableShippingOptions,l=null==c?void 0:c.find(({id:e})=>e===d),u=null==c?void 0:c.filter(e=>e.id!==d),h=l?[{label:l.description,amount:`${l.cost.toFixed(a)}`,detail:l.additionalDescription,identifier:l.id}]:[];if(u&&[...u.filter(e=>e.isRecommended),...u.filter(e=>!e.isRecommended)].forEach(e=>h.push({label:e.description,amount:`${e.cost.toFixed(a)}`,detail:e.additionalDescription,identifier:e.id})),!(c instanceof Array))throw new Error("Shipping options not available.");if(0===c.length)return void e.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:t,amount:`${s.grandTotal.toFixed(a)}`},[]);const p=c.find(e=>e.isRecommended),m=p?p.id:c[0].id,y=l?l.id:m;try{yield this._updateShippingOption(y)}catch(e){throw new Error("Shipping options update failed")}o=this._paymentIntegrationService.getState(),s=o.getCheckoutOrThrow(),e.completeShippingContactSelection({newShippingMethods:h,newTotal:{type:"final",label:t,amount:`${s.grandTotal.toFixed(a)}`},newLineItems:this._getUpdatedLineItems(s,a)})})}_handleShippingMethodSelected(e,t,n){return b_(this,void 0,void 0,function*(){const{shippingMethod:{identifier:i}}=n;try{yield this._updateShippingOption(i)}catch(t){throw e.abort(),new Error("Shipping option selection update failed.")}const r=this._paymentIntegrationService.getState(),{currency:{decimalPlaces:o}}=r.getCartOrThrow(),a=r.getCheckoutOrThrow();e.completeShippingMethodSelection({newTotal:{type:"final",label:t,amount:`${a.grandTotal.toFixed(o)}`},newLineItems:this._getUpdatedLineItems(a,o)})})}_getUpdatedLineItems(e,t){const n=[{label:this._subTotalLabel,amount:`${e.subtotal.toFixed(t)}`}];return e.taxes.forEach(e=>n.push({label:e.name,amount:`${e.amount.toFixed(t)}`})),n.push({label:this._shippingLabel,amount:`${e.shippingCostTotal.toFixed(t)}`}),n}_updateShippingOption(e){return b_(this,void 0,void 0,function*(){return this._paymentIntegrationService.selectShippingOption(e)})}_onValidateMerchant(e,t){return b_(this,void 0,void 0,function*(){const n=[`validationUrl=${t.validationURL}`,`merchantIdentifier=${e.initializationData.merchantId}`,`displayName=${e.initializationData.storeName}`,`domainName=${window.location.hostname}`].join("&");return this._requestSender.post(`${e.initializationData.paymentsUrl}/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})})}_onPaymentAuthorized(e,t,n){var i;return b_(this,void 0,void 0,function*(){const{token:r,billingContact:o,shippingContact:a}=e.payment,s=this._paymentIntegrationService.getState().getCartOrThrow().lineItems.physicalItems.length>0;let d;(null===(i=n.initializationData)||void 0===i?void 0:i.gateway)===Vi.BRAINTREE&&(d=yield this._getBraintreeDeviceData());const c={methodId:n.id,paymentData:{deviceSessionId:d,formattedPayload:{apple_pay_token:{payment_data:r.paymentData,payment_method:r.paymentMethod,transaction_id:r.transactionIdentifier}}}},l=this._transformContactToAddress(o),u=this._transformContactToAddress(a),h=null==a?void 0:a.emailAddress,p=(null==a?void 0:a.phoneNumber)||"";try{return yield this._paymentIntegrationService.updateBillingAddress(Object.assign(Object.assign({},l),{email:h,phone:p})),s&&(yield this._paymentIntegrationService.updateShippingAddress(u)),yield this._paymentIntegrationService.submitOrder({useStoreCredit:!1}),yield this._paymentIntegrationService.submitPayment(c),t.completePayment(ApplePaySession.STATUS_SUCCESS),this._onAuthorizeCallback()}catch(e){throw t.completePayment(ApplePaySession.STATUS_FAILURE),new Error("Payment cannot complete")}})}_transformContactToAddress(e){return{firstName:(null==e?void 0:e.givenName)||"",lastName:(null==e?void 0:e.familyName)||"",city:(null==e?void 0:e.locality)||"",company:"",address1:(null==e?void 0:e.addressLines)&&e.addressLines[0]||"",address2:(null==e?void 0:e.addressLines)&&e.addressLines[1]||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||"",phone:(null==e?void 0:e.phoneNumber)||"",stateOrProvince:(null==e?void 0:e.administrativeArea)||"",stateOrProvinceCode:(null==e?void 0:e.administrativeArea)||"",customFields:[]}}_getBraintreeDeviceData(){return b_(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}const O_=vi(e=>{const{getHost:t}=e.getState(),i=new Ei(e);return new P_(n({host:t()}),e,new Zi,new Ui(new Hi(a(),window,i)),new Qi(new r))},[{id:"applepay"}]);var E_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class A_{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){var t;return E_(this,void 0,void 0,function*(){const{bigcommerce_payments:n,containerId:i,methodId:r}=e,o=Boolean(null==n?void 0:n.buyNowInitializeOptions);if(!r)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');if(o&&!n.currencyCode)throw new fi('Unable to initialize payment because "options.bigcommerce_payments.currencyCode" argument is not provided.');if(o&&"function"!=typeof(null===(t=n.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.bigcommerce_payments.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');o||(yield this.paymentIntegrationService.loadDefaultCheckout());const a=o?n.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(r,a,!1),this.renderButton(i,r,n,o)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n,i){var r,o;const{buyNowInitializeOptions:a,style:s,onComplete:d,onEligibilityFailure:c}=n,l=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),u=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:h,isAppSwitchEnabled:p}=u.initializationData||{},m=Object.assign(Object.assign({},!i&&this.isPaypalCommerceAppSwitchEnabled(t)&&{appSwitchWhenAvailable:!0}),{createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)}),y={onClick:()=>this.handleClick(a),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},g=Object.assign(Object.assign({},!p&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(e,n)=>this.onHostedCheckoutApprove(e,n,t,d)}),v=Object.assign(Object.assign(Object.assign({fundingSource:l.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(s)},m),a&&y),h&&g),f=l.Buttons(v);f.isEligible()?(null===(r=f.hasReturned)||void 0===r?void 0:r.call(f))&&this.isPaypalCommerceAppSwitchEnabled(t)?null===(o=f.resume)||void 0===o||o.call(f):f.render(`#${e}`):c&&"function"==typeof c?c():this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return E_(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,n,i){return E_(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return E_(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return E_(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}isPaypalCommerceAppSwitchEnabled(e){var t,n;return null!==(n=null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)&&void 0!==n&&n}}const T_=vi(e=>new A_(e,_r(e)),[{id:"bigcommerce_payments"}]);var k_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class D_{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return k_(this,void 0,void 0,function*(){const{bigcommerce_payments_paylater:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');if(a&&!o)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=this.paymentIntegrationService.getState(),d=a?o:s.getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i,d,!1),this.renderButton(n,i,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){const{buyNowInitializeOptions:i,style:r,onComplete:o,onEligibilityFailure:a}=n,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:c}=d.initializationData||{},l={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},u={onClick:()=>this.handleClick(i),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},h={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(e,n)=>this.onHostedCheckoutApprove(e,n,t,o)},p=[s.FUNDING.PAYLATER,s.FUNDING.CREDIT];let m=!1;p.forEach(t=>{if(!m){const n=Object.assign(Object.assign(Object.assign({fundingSource:t,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(r)},l),i&&u),c&&h),o=s.Buttons(n);o.isEligible()?(o.render(`#${e}`),m=!0):a&&"function"==typeof a&&a()}}),m||this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return k_(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,n,i){return k_(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return k_(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return k_(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}}const M_=vi(e=>new D_(e,_r(e)),[{id:"bigcommerce_payments_paylater"}]);var z_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class N_{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return z_(this,void 0,void 0,function*(){const{bigcommerce_payments_venmo:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');if(a&&!o)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=a?o:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i,s,!1),this.renderButton(n,i,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){const{buyNowInitializeOptions:i,style:r,onEligibilityFailure:o}=n,a=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),s=a.FUNDING.VENMO,d={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},c={onClick:()=>this.handleClick(i),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},l=Object.assign(Object.assign({fundingSource:s,style:this.getValidVenmoButtonStyles(r)},d),i&&c),u=a.Buttons(l);u.isEligible()?u.render(`#${e}`):o&&"function"==typeof o?o():this.bigCommercePaymentsIntegrationService.removeElement(e)}getValidVenmoButtonStyles(e){const t=this.bigCommercePaymentsIntegrationService.getValidButtonStyle(e);return t.color===ar.gold?Object.assign(Object.assign({},t),{color:void 0}):t}handleClick(e){return z_(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const x_=vi(e=>new N_(e,_r(e)),[{id:"bigcommerce_payments_venmo"}]);class R_{constructor(e,t,n=window){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=n}initialize(e){return t=this,n=void 0,r=function*(){const{bolt:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,style:o}=t||{};if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bolt" argument is not provided.');if(!Boolean(r))throw new Si("Only buy now flow is implemented for Bolt button");if(!(null==r?void 0:r.storefrontApiToken)||"string"!=typeof r.storefrontApiToken)throw new fi('Unable to initialize payment because "options.storefrontApiToken" argument is not provided.');const a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i),{initializationData:s,config:d}=a,{publishableKey:c,developerConfig:l}=s||{};yield this.boltScriptLoader.loadBoltClient(c,d.testMode,l,"BigCommerce",r.storefrontApiToken),this.renderButton(n,a,o)},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}deinitialize(){return Promise.resolve()}renderButton(e,t,n){var i;"function"==typeof(null===(i=this.boltHostWindow.BoltConnect)||void 0===i?void 0:i.setupProductPageCheckout)&&(this.addButtonContainer(e,t,n),this.boltHostWindow.BoltConnect.setupProductPageCheckout())}addButtonContainer(e,t,n){const i=document.getElementById(e);if(!i)return;const r=document.createElement("div"),o=document.createElement("object");r.setAttribute("id","product-page-checkout-wrapper"),r.setAttribute("class","bolt-button-wrapper"),r.setAttribute("style","display:none"),r.setAttribute("data-tid","product-page-checkout-wrapper"),o.setAttribute("data",this.getBoltObjectData(t,n)),o.setAttribute("class","bolt-product-checkout-button"),r.append(o),i.innerHTML="",i.append(r)}getBoltObjectData(e,t){const{initializationData:n,config:i}=e,{publishableKey:r,developerConfig:o}=n||{},a=this.boltScriptLoader.getDomainURL(!!i.testMode,o),s=this.getButtonHeight(null==t?void 0:t.size),d=this.getButtonBorderRadius(null==t?void 0:t.shape,s);return xe({url:`https://${a}/v1/checkout_button`,query:{publishable_key:r,variant:"ppc",height:s,border_radius:d}})}getButtonHeight(e){if(e)switch(e){case to.Small:return 25;case to.Large:return 45;case to.Medium:default:return 40}}getButtonBorderRadius(e,t){if(e)switch(e){case no.Pill:return t?Math.round(t/2):void 0;case no.Rect:default:return 4}}}const F_=vi(e=>new R_(e,new ao(a())),[{id:"bolt"}]);function L_(e){const{color:t,fundingicons:n,height:i=40,layout:r,shape:o,size:a,tagline:s}=e||{},d={color:t,fundingicons:n,height:B_(i),layout:r,shape:o||"rect",size:a,tagline:s};return ue(d,J)}function B_(e){const t=Number(e);return!t||Number.isNaN(t)?40:t>55?55:t<25?25:t}var j_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class U_{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return j_(this,void 0,void 0,function*(){const{braintreepaypal:t,containerId:n,methodId:i}=e;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');let r,o=this.paymentIntegrationService.getState();if(t.buyNowInitializeOptions){if(!t.currencyCode)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');r=t.currencyCode}else yield this.paymentIntegrationService.loadDefaultCheckout(),o=this.paymentIntegrationService.getState(),r=o.getCartOrThrow().currency.code;const a=o.getPaymentMethodOrThrow(i),{clientToken:s,config:d,initializationData:c}=a;if(!s||!c)throw new ti(Xn.MissingPaymentMethod);const l={currency:r,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(l,e=>{this.renderPayPalButton(e,t,n,i,!!d.testMode)},e=>this.handleError(e,n,t.onError))})}deinitialize(){return j_(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}renderPayPalButton(e,t,n,i,r){const{style:o,shouldProcessPayment:a,onAuthorizeError:s,onEligibilityFailure:d}=t,{paypal:c}=this.braintreeHostWindow;if(c){const l=c.Buttons({env:r?"sandbox":"production",fundingSource:c.FUNDING.PAYPAL,style:L_(o),createOrder:()=>this.setupPayment(e,t,i),onApprove:t=>this.tokenizePayment(t,e,i,a,s)});l.isEligible()?l.render(`#${n}`):d&&"function"==typeof d&&d()}else this.braintreeIntegrationService.removeElement(n)}setupPayment(e,t,n){var i;return j_(this,void 0,void 0,function*(){const{onPaymentError:r,shippingAddress:o,buyNowInitializeOptions:a}=t;try{const r="function"==typeof(null==a?void 0:a.getBuyNowCartRequestBody)?yield this.createBuyNowCart(a.getBuyNowCartRequestBody()):void 0;this.buyNowCartId=null==r?void 0:r.id;const s=this.paymentIntegrationService.getState(),d=s.getCustomer(),c=s.getPaymentMethodOrThrow(n),l=r?r.cartAmount:s.getCartOrThrow().cartAmount,u=r?t.currencyCode:s.getCartOrThrow().currency.code,h=o||(null==d?void 0:d.addresses[0]),p=h?El(h):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:p,amount:l,currency:u,offerCredit:!1,intent:null===(i=c.initializationData)||void 0===i?void 0:i.intent})}catch(e){throw r&&(Ri(e)||e instanceof Qn)&&r(e),e}})}tokenizePayment(e,t,n,i,r){return j_(this,void 0,void 0,function*(){try{const{deviceData:r}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),o=yield t.tokenizePayment(e),{details:a,nonce:s}=o,d=this.braintreeIntegrationService.mapToLegacyBillingAddress(a),c=this.braintreeIntegrationService.mapToLegacyShippingAddress(a);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",provider:n,action:i?"process_payment":"set_external_checkout",nonce:s,device_data:r,billing_address:JSON.stringify(d),shipping_address:JSON.stringify(c)},this.buyNowCartId&&{cart_id:this.buyNowCartId})),o}catch(e){throw r&&(Ri(e)||e instanceof Qn)&&r(e),e}})}createBuyNowCart(e){return j_(this,void 0,void 0,function*(){if(!e)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(e)}catch(e){throw new er}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const q_=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t);return new U_(e,Ee(),i,t)},[{id:"braintreepaypal"}]);var V_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class G_{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return V_(this,void 0,void 0,function*(){const{braintreepaypalcredit:t,containerId:n,methodId:i}=e;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');let r,o=this.paymentIntegrationService.getState();if(t.buyNowInitializeOptions){if(!t.currencyCode)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');r=t.currencyCode}else yield this.paymentIntegrationService.loadDefaultCheckout(),o=this.paymentIntegrationService.getState(),r=o.getCartOrThrow().currency.code;const a=o.getPaymentMethodOrThrow(i),{clientToken:s,config:d,initializationData:c}=a;if(!s||!c)throw new ti(Xn.MissingPaymentMethod);const l={currency:r,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(l,e=>{this.renderPayPalButton(e,t,n,i,!!d.testMode)},e=>this.handleError(e,n,t.onError))})}deinitialize(){return V_(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}renderPayPalButton(e,t,n,i,r){const{style:o,shouldProcessPayment:a,onAuthorizeError:s,onEligibilityFailure:d}=t,{paypal:c}=this.braintreeHostWindow;let l=!1;c&&[c.FUNDING.PAYLATER,c.FUNDING.CREDIT].forEach(u=>{const h=u===c.FUNDING.CREDIT?Object.assign({label:go.CREDIT},L_(o)):L_(o);if(!l){const o=c.Buttons({env:r?"sandbox":"production",fundingSource:u,style:h,createOrder:()=>this.setupPayment(e,t,i),onApprove:t=>this.tokenizePayment(t,e,i,a,s)});o.isEligible()?(o.render(`#${n}`),l=!0):c.FUNDING.CREDIT&&d&&"function"==typeof d&&d()}}),c&&l||this.braintreeIntegrationService.removeElement(n)}setupPayment(e,t,n){var i;return V_(this,void 0,void 0,function*(){const{onPaymentError:r,shippingAddress:o,buyNowInitializeOptions:a}=t;try{const r="function"==typeof(null==a?void 0:a.getBuyNowCartRequestBody)?yield this.createBuyNowCart(a.getBuyNowCartRequestBody()):void 0;this.buyNowCartId=null==r?void 0:r.id;const s=this.paymentIntegrationService.getState(),d=s.getCustomer(),c=s.getPaymentMethodOrThrow(n),l=r?r.cartAmount:s.getCartOrThrow().cartAmount,u=r?t.currencyCode:s.getCartOrThrow().currency.code,h=o||(null==d?void 0:d.addresses[0]),p=h?El(h):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:p,amount:l,currency:u,offerCredit:!0,intent:null===(i=c.initializationData)||void 0===i?void 0:i.intent})}catch(e){throw r&&(Ri(e)||e instanceof Qn)&&r(e),e}})}tokenizePayment(e,t,n,i,r){return V_(this,void 0,void 0,function*(){try{const{deviceData:r}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),o=yield t.tokenizePayment(e),{details:a,nonce:s}=o,d=this.braintreeIntegrationService.mapToLegacyBillingAddress(a),c=this.braintreeIntegrationService.mapToLegacyShippingAddress(a);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",provider:n,action:i?"process_payment":"set_external_checkout",nonce:s,device_data:r,billing_address:JSON.stringify(d),shipping_address:JSON.stringify(c)},this.buyNowCartId&&{cart_id:this.buyNowCartId})),o}catch(e){throw r&&(Ri(e)||e instanceof Qn)&&r(e),e}})}createBuyNowCart(e){return V_(this,void 0,void 0,function*(){if(!e)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(e)}catch(e){throw new er}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const H_=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t);return new G_(e,Ee(),i,t)},[{id:"braintreepaypalcredit"}]);var W_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class $_{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n}initialize(e){return W_(this,void 0,void 0,function*(){const{containerId:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState(),{clientToken:r,initializationData:o,config:a}=i.getPaymentMethodOrThrow(n);if(!r||!o)throw new ti(Xn.MissingPaymentMethod);this.braintreeSdk.initialize(r);const s=yield this.braintreeSdk.getBraintreeVisaCheckout(),{currency:{code:d},cartAmount:c}=i.getCartOrThrow(),l=yield this.braintreeSdk.getVisaCheckoutSdk(a.testMode),u=s.createInitOptions({paymentRequest:{currencyCode:d,subtotal:String(c)},settings:{shipping:{collectShipping:!0}}});this.createSignInButton(t),yield l.init(u),l.on("payment.success",e=>W_(this,void 0,void 0,function*(){yield this.paymentSuccess(s,e)}))})}deinitialize(){return Promise.resolve()}paymentSuccess(e,t){return W_(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const n=this.paymentIntegrationService.getState(),i=n.getShippingAddress(),r=n.getBillingAddress(),{shippingAddress:o=this.toVisaCheckoutAddress(i),billingAddress:a=this.toVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}postForm(e,t){const{userData:n,billingAddress:i,shippingAddress:r,details:o}=e,{userEmail:a}=n,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,i)),shipping_address:JSON.stringify(this.getAddress(a,r))})}toVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}createSignInButton(e){const t=document.querySelector(`#${e}`);if(!t)throw new Error("Need a container to place the button");return this.insertVisaCheckoutButton(t)}insertVisaCheckoutButton(e){const t=document.createElement("div");return t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="flex-end",t.innerHTML='\n \n Tell Me More',e.appendChild(t),t}}const Y_=vi(e=>{const t=window,n=new Ei(e),i=new Ui(new Hi(a(),t,n));return new $_(e,Ee(),i)},[{id:"braintreevisacheckout"}]);function K_(e){const{billingAddress:t,email:n,firstName:i,lastName:r,phone:o,shippingAddress:a}=e,s=t||a;return{email:n,first_name:i,last_name:r,phone_number:o,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 J_(e){const{email:t,phone:n,shippingAddress:i}=e,r=(null==i?void 0:i.recipientName)||"",[o,a]=r.split(" ");return{email:t,first_name:o||"",last_name:a||"",phone_number:n,address_line_1:null==i?void 0:i.line1,address_line_2:null==i?void 0:i.line2,city:null==i?void 0:i.city,state:null==i?void 0:i.state,country_code:null==i?void 0:i.countryCode,postal_code:null==i?void 0:i.postalCode}}var Z_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const Q_=e=>{const{color:t,height:n}=e;return{backgroundColor:(i=t||"",i===yo.WHITE?"#FFFFFF":"#3D95CE"),backgroundPosition:"50% 50%",backgroundSize:"80px auto",backgroundImage:`url("/app/assets/img/payment-providers/venmo-logo-${t===yo.WHITE?yo.BLUE:yo.WHITE}.svg")`,backgroundRepeat:"no-repeat",borderRadius:"4px",cursor:"pointer",transition:"0.2s ease",minHeight:`${n||40}px`,minWidth:"150px",height:"100%",width:"100%",border:t===yo.WHITE?"1px solid black":"none"};var i};class X_{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n,this.onError=ce}initialize(e){return Z_(this,void 0,void 0,function*(){const{braintreevenmo:t,containerId:n,methodId:i}=e;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i),{clientToken:o,initializationData:a}=r,{paymentButtonStyles:s}=a,{cartButtonStyles:d}=s||{},c=(null==t?void 0:t.style)||d;if(!o||!a)throw new ti(Xn.MissingPaymentMethod);if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');yield this.paymentIntegrationService.loadDefaultCheckout(),this.onError=(null==t?void 0:t.onError)||this.handleError,this.braintreeSdk.initialize(o);try{const e=yield this.braintreeSdk.getVenmoCheckoutOrThrow();this.renderVenmoButton(e,n,null==t?void 0:t.buyNowInitializeOptions,c)}catch(e){(Ol(e)||function(e){return e instanceof Ai}(e))&&this.handleInitializationVenmoError(e,n)}})}deinitialize(){return Z_(this,void 0,void 0,function*(){return yield this.braintreeSdk.deinitialize(),Promise.resolve()})}handleError(e){throw new Error(e.message)}createBuyNowCart(e){return Z_(this,void 0,void 0,function*(){if("function"==typeof(null==e?void 0:e.getBuyNowCartRequestBody)){const t=null==e?void 0:e.getBuyNowCartRequestBody();if(!t)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}}})}handleInitializationVenmoError(e,t){return this.removeVenmoContainer(t),this.onError(e)}removeVenmoContainer(e){const t=document.getElementById(e);t&&t.remove()}renderVenmoButton(e,t,n,i){const r=document.getElementById(t),{color:o}=i||{};if(!r)throw new fi("Unable to create wallet button without valid container ID.");r.setAttribute("aria-label","Venmo"),Object.assign(r.style,Q_(i||{})),r.addEventListener("click",()=>Z_(this,void 0,void 0,function*(){r.setAttribute("disabled","true");const t=yield this.createBuyNowCart(n);e.tokenize&&e.tokenize((e,n)=>Z_(this,void 0,void 0,function*(){r.removeAttribute("disabled"),e&&this.onError(e),yield this.handlePostForm(n,null==t?void 0:t.id)}))})),o===yo.BLUE&&(r.addEventListener("mouseenter",()=>{r.style.backgroundColor="#0a7fc2"}),r.addEventListener("mouseleave",()=>{r.style.backgroundColor=Q_(i||{}).backgroundColor}))}handlePostForm(e,t){return Z_(this,void 0,void 0,function*(){const{deviceData:n}=yield this.braintreeSdk.getDataCollectorOrThrow(),{nonce:i,details:r}=e;this.formPoster.postForm("/checkout.php",Object.assign({nonce:i,provider:"braintreevenmo",payment_type:"paypal",device_data:n,action:"set_external_checkout",billing_address:JSON.stringify(K_(r)),shipping_address:JSON.stringify(J_(r))},t&&{cart_id:t}))})}}const ew=vi(e=>{const t=window,n=a(),i=new Ei(e),r=new Hi(n,t,i),o=new Ui(r);return new X_(e,Ee(),o)},[{id:"braintreevenmo"}]);var tw=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class nw{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t}initialize(e){var t,n,i;return tw(this,void 0,void 0,function*(){if(!e.methodId||!na(e.methodId))throw new fi('Unable to proceed because "methodId" is not a valid key.');if(this._methodId=e.methodId,!e.containerId)throw new fi('Unable to proceed because "containerId" is not a valid key.');const r=e[this._getMethodOrThrow()];if(!r)throw new fi("Unable to proceed without valid options.");const{buyNowInitializeOptions:o,currencyCode:a,buttonColor:s,buttonType:d,onError:c}=r;let l,u=this._paymentIntegrationService.getState();try{l=u.getPaymentMethodOrThrow(this._getMethodOrThrow())}catch(e){u=yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodOrThrow()),l=u.getPaymentMethodOrThrow(this._getMethodOrThrow())}if(this._countryCode=null===(t=l.initializationData)||void 0===t?void 0:t.storeCountry,this._googlePayPaymentProcessor.setIsWebViewExperimentOn(!!(null===(n=l.initializationData)||void 0===n?void 0:n.isWebViewExperimentOn)),o){if(!a)throw new fi('Unable to initialize payment because "options.currencyCode" argument is not provided.');this._currencyCode=a,this._buyNowInitializeOptions=o,yield this._googlePayPaymentProcessor.initialize(()=>l,this._getGooglePayClientOptions(),!!o,a)}else yield this._paymentIntegrationService.loadDefaultCheckout(),yield this._googlePayPaymentProcessor.initialize(()=>l,this._getGooglePayClientOptions());this._paymentButton=null!==(i=this._paymentButton)&&void 0!==i?i:this._googlePayPaymentProcessor.addPaymentButton(e.containerId,{buttonColor:null!=s?s:"default",buttonType:null!=d?d:"plain",onClick:this._handleClick(c)})})}deinitialize(){var e;return null===(e=this._paymentButton)||void 0===e||e.remove(),this._paymentButton=void 0,this._methodId=void 0,Promise.resolve()}_handleClick(e){return t=>tw(this,void 0,void 0,function*(){t.preventDefault();try{this._buyNowInitializeOptions?yield this._createBuyNowCartOrThrow(this._buyNowInitializeOptions):yield this._paymentIntegrationService.loadDefaultCheckout(),yield this._googlePayPaymentProcessor.initializeWidget(),yield this._interactWithPaymentSheet()}catch(t){let n=t;if(ta(t)){if("CANCELED"===t.statusCode)throw new Wi;n=new Qr(JSON.stringify(t))}throw null==e||e(new Qr("An error occurred while requesting your Google Pay payment details.")),n}})}_interactWithPaymentSheet(){var e;return tw(this,void 0,void 0,function*(){const t=yield this._googlePayPaymentProcessor.showPaymentSheet(),n=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(t),i=this._googlePayPaymentProcessor.mapToShippingAddressRequestBody(t),r="/embedded-checkout"===window.location.pathname?this._paymentIntegrationService.getState().getStoreConfigOrThrow().links.siteLink:void 0;n&&(yield this._paymentIntegrationService.updateBillingAddress(n)),i&&!(null===(e=this._buyNowCart)||void 0===e?void 0:e.lineItems.digitalItems.length)&&(yield this._paymentIntegrationService.updateShippingAddress(i)),yield this._googlePayPaymentProcessor.setExternalCheckoutForm(this._getMethodOrThrow(),t,r)})}_getGooglePayClientOptions(){return this._googlePayPaymentProcessor.isWebViewWithRestrictions()?{}:{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:e,shippingAddress:t,shippingOptionData:n,offerData:i})=>tw(this,void 0,void 0,function*(){const{availableTriggers:r,addressChangeTriggers:o,shippingOptionsChangeTriggers:a,offerChangeTriggers:s}=this._googlePayPaymentProcessor.getCallbackTriggers();if(!r.includes(e))return;const d=o.includes(e)?yield this._googlePayPaymentProcessor.handleShippingAddressChange(t):void 0;a.includes(e)&&(yield this._googlePayPaymentProcessor.handleShippingOptionChange(n.id));const{newOfferInfo:c,error:l}=s.includes(e)?yield this._googlePayPaymentProcessor.handleCoupons(i):{},u=l;return this._buyNowInitializeOptions?this._getBuyNowTransactionInfo(d,c,u):this._getTransactionInfo(d,c,u)})}}}_createBuyNowCartOrThrow(e){return tw(this,void 0,void 0,function*(){if("function"==typeof(null==e?void 0:e.getBuyNowCartRequestBody)){const t=e.getBuyNowCartRequestBody();try{this._buyNowCart=yield this._paymentIntegrationService.createBuyNowCart(t),yield this._paymentIntegrationService.loadCheckout(this._buyNowCart.id)}catch(e){if("string"==typeof e)throw new er(e);throw e}}})}_getBuyNowTransactionInfo(e,t,n){if(!this._buyNowCart)return;const{cartAmount:i}=this._buyNowCart,r=this._googlePayPaymentProcessor.getTotalPrice();return Object.assign(Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},this._countryCode&&{countryCode:this._countryCode}),{currencyCode:this._getCurrencyCodeOrThrow(),totalPrice:r||String(i),totalPriceStatus:Wo.FINAL})},e&&{newShippingOptionParameters:e}),t&&{newOfferInfo:t}),n&&{error:n})}_getTransactionInfo(e,t,n){return tw(this,void 0,void 0,function*(){yield this._paymentIntegrationService.loadCheckout();const i=this._googlePayPaymentProcessor.getTotalPrice(),{code:r}=this._paymentIntegrationService.getState().getCartOrThrow().currency;return Object.assign(Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},this._countryCode&&{countryCode:this._countryCode}),{currencyCode:r,totalPriceStatus:Wo.FINAL,totalPrice:i})},e&&{newShippingOptionParameters:e}),t&&{newOfferInfo:t}),n&&{error:n})})}_getMethodOrThrow(){return ii(this._methodId,()=>new ri(ei.PaymentNotInitialized))}_getCurrencyCodeOrThrow(){return ii(this._currencyCode,()=>new fi('Unable to initialize payment because "options.currencyCode" argument is not provided.'))}}const iw=vi(e=>{const t=n(),i=window,r=new Ei(e),o=new Ui(new Hi(a(),i,r));return new nw(e,new aa(da(),new $a(e,o),t,Ee()))},[{id:"googlepaybraintree"}]),rw=vi(e=>new nw(e,new aa(da(),new ns(e,new Xa(a())),n(),Ee())),[{id:"googlepaypaypalcommerce"}]),ow=vi(e=>new nw(e,new aa(da(),new os(e,new xr(a())),n(),Ee())),[{id:"googlepay_bigcommerce_payments"}]),aw=vi(e=>{const t=n();return new nw(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv2"}]),sw=vi(e=>{const t=n();return new nw(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv3"}]),dw=vi(e=>new nw(e,new aa(da(),new ua(e),n(),Ee())),[{id:"googlepayauthorizenet"}]),cw=vi(e=>{const t=n();return new nw(e,new aa(da(),new ga(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]),lw=vi(e=>new nw(e,new aa(da(),new fa(e),n(),Ee())),[{id:"googlepaycybersourcev2"},{id:"googlepaybnz"}]),uw=vi(e=>new nw(e,new aa(da(),new wa(e),n(),Ee())),[{id:"googlepayorbital"}]),hw=vi(e=>new nw(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeupe"},{id:"googlepaystripeocs"}]),pw=vi(e=>new nw(e,new aa(da(),new Ga(e),n(),Ee())),[{id:"googlepayworldpayaccess"}]),mw=vi(e=>new nw(e,new aa(da(),new cs(e,Ee()),n(),Ee())),[{id:"googlepaytdonlinemart"}]);class yw{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.paypalButtonCreationService=n}initialize(e){var t,n,i,r,o;return n=this,i=void 0,o=function*(){const{paypalcommerce:n,containerId:i,methodId:r}=e,o=Boolean(null==n?void 0:n.buyNowInitializeOptions);if(!r)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(o&&!n.currencyCode)throw new fi('Unable to initialize payment because "options.paypalcommerce.currencyCode" argument is not provided.');if(o&&"function"!=typeof(null===(t=n.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.paypalcommerce.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');o||(yield this.paymentIntegrationService.loadDefaultCheckout());const a=o?n.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.paypalIntegrationService.loadPayPalSdk(r,a,!1),this.renderButton(i,r,n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){var i,r;const{buyNowInitializeOptions:o,style:a,onComplete:s,onEligibilityFailure:d}=n,c=this.paypalIntegrationService.getPayPalSdkOrThrow(),l=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:u,isAppSwitchEnabled:h}=l.initializationData||{},p={onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},m=Object.assign(Object.assign({fundingSource:c.FUNDING.PAYPAL,style:this.paypalIntegrationService.getValidButtonStyle(a),isAppSwitchEnabled:h,isHostedCheckoutEnabled:u},o&&p),u&&s&&{onPaymentComplete:()=>s()}),y=this.paypalButtonCreationService.createPayPalButton("paypalcommerce",t,m,o);y.isEligible()?(null===(i=y.hasReturned)||void 0===i?void 0:i.call(y))&&h?null===(r=y.resume)||void 0===r||r.call(y):y.render(`#${e}`):d&&"function"==typeof d?d():this.paypalIntegrationService.removeElement(e)}}const gw=vi(e=>{const t=As(e),n=new ks(e,t);return new yw(e,t,n)},[{id:"paypalcommerce"}]);var vw=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class fw{constructor(e,t){this.paymentIntegrationService=e,this.paypalIntegrationService=t}initialize(e){return vw(this,void 0,void 0,function*(){const{paypalcommercecredit:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(a&&!o)throw new fi('Unable to initialize payment because "options.paypalcommercecredit.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.paypalcommercecredit.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=this.paymentIntegrationService.getState(),d=a?o:s.getCartOrThrow().currency.code;yield this.paypalIntegrationService.loadPayPalSdk(i,d,!1),this.renderButton(n,i,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){const{buyNowInitializeOptions:i,style:r,onComplete:o,onEligibilityFailure:a}=n,s=this.paypalIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:c,isAppSwitchEnabled:l}=d.initializationData||{},u={createOrder:()=>this.paypalIntegrationService.createOrder("paypalcommercecredit"),onApprove:({orderID:e})=>this.paypalIntegrationService.tokenizePayment(t,e)},h={onClick:()=>this.handleClick(i),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},p=Object.assign(Object.assign({},!l&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(e,n)=>this.onHostedCheckoutApprove(e,n,t,o)}),m=[s.FUNDING.PAYLATER,s.FUNDING.CREDIT];let y=!1;m.forEach(t=>{if(!y){const n=Object.assign(Object.assign(Object.assign({fundingSource:t,style:this.paypalIntegrationService.getValidButtonStyle(r)},u),i&&h),c&&p),o=s.Buttons(n);o.isEligible()?(o.render(`#${e}`),y=!0):a&&"function"==typeof a&&a()}}),y||this.paypalIntegrationService.removeElement(e)}handleClick(e){return vw(this,void 0,void 0,function*(){if(e){const t=yield this.paypalIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,n,i){return vw(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.paypalIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.paypalIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.paypalIntegrationService.updateOrder("paypalcommerce")}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.paypalIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return vw(this,void 0,void 0,function*(){const t=this.paypalIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.paypalIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.paypalIntegrationService.updateOrder("paypalcommerce")}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return vw(this,void 0,void 0,function*(){const t=this.paypalIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.paypalIntegrationService.updateOrder("paypalcommerce")}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}}const Sw=vi(e=>new fw(e,As(e)),[{id:"paypalcommercecredit"}]);var _w=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ww{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}initialize(e){return _w(this,void 0,void 0,function*(){const{paypalcommercevenmo:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(a&&!o)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.paypalcommercevenmo.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=a?o:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.paypalCommerceIntegrationService.loadPayPalSdk(i,s,!1),this.renderButton(n,i,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){const{buyNowInitializeOptions:i,style:r,onEligibilityFailure:o}=n,a=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),s=a.FUNDING.VENMO,d={createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo"),onApprove:({orderID:e})=>this.paypalCommerceIntegrationService.tokenizePayment(t,e)},c={onClick:()=>this.handleClick(i),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},l=Object.assign(Object.assign({fundingSource:s,style:this.getValidVenmoButtonStyles(r)},d),i&&c),u=a.Buttons(l);u.isEligible()?u.render(`#${e}`):o&&"function"==typeof o?o():this.paypalCommerceIntegrationService.removeElement(e)}getValidVenmoButtonStyles(e){const t=this.paypalCommerceIntegrationService.getValidButtonStyle(e);return t.color===Fs.gold?Object.assign(Object.assign({},t),{color:void 0}):t}handleClick(e){return _w(this,void 0,void 0,function*(){if(e){const t=yield this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const Iw=vi(e=>new ww(e,$s(e)),[{id:"paypalcommercevenmo"}]);var Cw=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class bw{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalExpressScriptLoader=t,this.formPoster=n}initialize(e){return Cw(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);if(!e.paypal)throw new fi;if(!t.config.merchantId)throw new ti(Xn.MissingPaymentMethod);const n=yield this.paypalExpressScriptLoader.loadPaypalSDK(t.config.merchantId);this.renderButton(e,n)})}deinitialize(){return Promise.resolve()}renderButton(e,t){const{containerId:n,methodId:i,paypal:r}=e,{allowCredit:o,clientId:a,onPaymentError:s,shouldProcessPayment:d,style:c}=r,l=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);if(!l.config.merchantId)throw new ti(Xn.MissingPaymentMethod);const u=l.config.merchantId,h=l.config.testMode?"sandbox":"production",p={[h]:a},m=t.FUNDING.CREDIT||"credit",y=o?[m]:[],g=o?[]:[m];return t.Button.render({env:h,client:p,commit:d,funding:{allowed:y,disallowed:g},style:this.getStyle(c),payment:(e,t)=>this.setupPayment(u,t,s),onAuthorize:(e,t)=>this.tokenizePayment(e,i,t,d)},n)}getStyle(e){const{color:t,fundingicons:n,label:i,layout:r,shape:o,size:a,tagline:s}=e||{};return{color:t,fundingicons:n,label:i,layout:r,shape:o||Pp.RECT,size:"small"===a?Ip.RESPONSIVE:a,tagline:s}}setupPayment(e,t,n){return Cw(this,void 0,void 0,function*(){if(!t)throw new ri(ei.CheckoutButtonNotInitialized);try{const n=yield this.paymentIntegrationService.loadDefaultCheckout(),{id:i}=n.getCartOrThrow(),r=n.getHost()||"";return(yield t.request.post(`${r}/api/storefront/payment/paypalexpress`,{merchantId:e,cartId:i},{headers:Object.assign({"X-API-INTERNAL":hr},yr)})).id}catch(e){throw n&&e instanceof Qn&&n(e),e}})}tokenizePayment(e,t,n,i){return Cw(this,void 0,void 0,function*(){if(!n)throw new ri(ei.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new ti(Xn.MissingPayment);const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),o=yield n.payment.get(e.paymentID);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:r.id,action:i?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(o.payer.payer_info)})})}}const Pw=vi(e=>new bw(e,new Tp(a()),Ee()),[{id:"paypalexpress"}]);var Ow=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ew{constructor(e,t,n,i){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n,this.loadingIndicator=i}initialize(e){return Ow(this,void 0,void 0,function*(){const{stripeocs:t,containerId:n}=e||{};if(!t||!n)throw new ri(ei.PaymentNotInitialized);const{gatewayId:i}=t;if(!i)throw new ti(Xn.MissingPaymentMethod);const r=this._getMethodId(i),o=yield this.paymentIntegrationService.loadPaymentMethod(i,{params:{method:r}}),a=o.getPaymentMethodOrThrow(r,i),{loadingContainerId:s,buttonHeight:d,onComplete:c}=t;if(this._loadingIndicatorContainer=s,this._onComplete=c,!dd(a))throw new ti(Xn.MissingPaymentMethod);const{initializationData:l}=a,{captureMethod:u}=l,h=this.stripeIntegrationService.getStripeJsVersion(l);this._captureMethod=u,this._stripeClient=yield this.scriptLoader.getStripeClient(l,o.getCartLocale(),h),yield this.paymentIntegrationService.loadDefaultCheckout(),yield this._mountExpressCheckoutElement(n,this._stripeClient,d),this._initializeEvents(r)})}signIn(){return Promise.resolve()}signOut(){return Promise.resolve()}executePaymentMethodCheckout(){return Promise.resolve()}deinitialize(){return Promise.resolve()}_mountExpressCheckoutElement(e,t,n=40){return Ow(this,void 0,void 0,function*(){const i=this._shouldRequireShippingAddress(),r=Object.assign(Object.assign(Object.assign({shippingAddressRequired:i},i?{allowedShippingCountries:yield this._getAvailableCountries()}:{}),i?{shippingRates:[{id:"_",amount:0,displayName:"Pending rates"}]}:{}),{billingAddressRequired:!0,emailRequired:!0,phoneNumberRequired:!0,paymentMethods:{link:Ta.AUTO,applePay:Ta.NEVER,googlePay:Ta.NEVER,amazonPay:Ta.NEVER,paypal:Ta.NEVER,klarna:Ta.NEVER},buttonHeight:n}),{cartAmount:o=1}=this.paymentIntegrationService.getState().getCart()||{},a=Object.assign({mode:"payment",amount:this._toCents(o),currency:this._getCurrency()},this._captureMethod?{captureMethod:this._captureMethod}:{});this._stripeElements=t.elements(a),this._linkV2Element=this._stripeElements.create(Da.EXPRESS_CHECKOUT,r),this._linkV2Element.mount(`#${e}`)})}_initializeEvents(e){this._linkV2Element&&(this._shouldRequireShippingAddress()&&(this._linkV2Element.on(za.SHIPPING_ADDRESS_CHANGE,e=>Ow(this,void 0,void 0,function*(){return this._onShippingAddressChange(e)})),this._linkV2Element.on(za.SHIPPING_RATE_CHANGE,e=>Ow(this,void 0,void 0,function*(){return this._onShippingRateChange(e)}))),this._linkV2Element.on(za.CONFIRM,t=>Ow(this,void 0,void 0,function*(){return this._onConfirm(t,e)})),this._linkV2Element.on(za.CANCEL,this._onCancel))}_onShippingAddressChange(e){return Ow(this,void 0,void 0,function*(){if(!("address"in e))return;const t=e.address,n={firstName:"",lastName:"",phone:"",company:"",address1:"",address2:"",city:(null==t?void 0:t.city)||"",countryCode:(null==t?void 0:t.country)||"",postalCode:(null==t?void 0:t.postal_code)||"",stateOrProvince:(null==t?void 0:t.state)||"",stateOrProvinceCode:(null==t?void 0:t.state)||"",customFields:[]};yield this.paymentIntegrationService.updateShippingAddress(n);const i=yield this._getAvailableShippingOptions();yield this._updateDisplayedPrice(),(null==i?void 0:i.length)?e.resolve({shippingRates:i}):e.reject()})}_onCancel(){throw new Wi}_onShippingRateChange(e){return Ow(this,void 0,void 0,function*(){if("shippingRate"in e){const{shippingRate:t}=e;yield this._handleShippingOptionChange(null==t?void 0:t.id),yield this._updateDisplayedPrice(),e.resolve({})}})}_onConfirm(e,t){return Ow(this,void 0,void 0,function*(){if("billingDetails"in e&&"shippingAddress"in e&&this._stripeClient&&this._stripeElements){yield this._updateShippingAndBillingAddress(e),yield this.paymentIntegrationService.submitOrder();const n=this._getPaymentPayload(t);try{yield this.paymentIntegrationService.submitPayment(n)}catch(e){yield this._processAdditionalAction(e,t)}}return Promise.resolve()})}_updateShippingAndBillingAddress(e){var t,n,i,r,o,a,s,d;return Ow(this,void 0,void 0,function*(){const c=this._shouldRequireShippingAddress(),l=(null===(n=null===(t=e.shippingAddress)||void 0===t?void 0:t.name)||void 0===n?void 0:n.split(" ")[0])||(null===(r=null===(i=e.billingDetails)||void 0===i?void 0:i.name)||void 0===r?void 0:r.split(" ")[0])||"",u=(null===(a=null===(o=e.shippingAddress)||void 0===o?void 0:o.name)||void 0===a?void 0:a.split(" ")[1])||(null===(d=null===(s=e.billingDetails)||void 0===s?void 0:s.name)||void 0===d?void 0:d.split(" ")[1])||"";if(c){const t=this._mapShippingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateShippingAddress(t)}const h=this._mapBillingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateBillingAddress(h)})}_mapShippingAddress(e,t,n,i){var r,o,a,s,d,c,l;return{firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==e?void 0:e.address)||void 0===r?void 0:r.line1)||"",address2:(null===(o=null==e?void 0:e.address)||void 0===o?void 0:o.line2)||"",city:(null===(a=null==e?void 0:e.address)||void 0===a?void 0:a.city)||"",countryCode:(null===(s=null==e?void 0:e.address)||void 0===s?void 0:s.country)||"",postalCode:(null===(d=null==e?void 0:e.address)||void 0===d?void 0:d.postal_code)||"",stateOrProvince:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",stateOrProvinceCode:(null===(l=null==e?void 0:e.address)||void 0===l?void 0:l.state)||"",customFields:[]}}_mapBillingAddress(e,t,n,i){var r,o,a,s,d,c;return{email:(null==t?void 0:t.email)||"",firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==t?void 0:t.address)||void 0===r?void 0:r.line1)||"",address2:"",city:(null===(o=null==t?void 0:t.address)||void 0===o?void 0:o.city)||"",countryCode:(null===(a=null==t?void 0:t.address)||void 0===a?void 0:a.country)||"",postalCode:(null===(s=null==t?void 0:t.address)||void 0===s?void 0:s.postal_code)||"",stateOrProvince:(null===(d=null==t?void 0:t.address)||void 0===d?void 0:d.state)||"",stateOrProvinceCode:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",customFields:[]}}_processAdditionalAction(e,t){return Ow(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeClient||!this._stripeElements)throw new ri(ei.PaymentNotInitialized);const{data:n}=e.body.additional_action_required,{token:i}=n,{paymentIntent:r}=yield this._confirmStripePaymentOrThrow(n,t),o=this._getPaymentPayload(t,(null==r?void 0:r.id)||i);try{this._toggleLoadingIndicator(!0),yield this.paymentIntegrationService.submitPayment(o),yield this._completeCheckoutFlow()}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}finally{this._toggleLoadingIndicator(!1)}})}_confirmStripePaymentOrThrow(e,t){var n,i,r;return Ow(this,void 0,void 0,function*(){const{token:o,redirect_url:a}=e,s=this.stripeIntegrationService.mapStripePaymentData(this._stripeElements,a);let d;try{const e=(yield this.stripeIntegrationService.isPaymentCompleted(t,this._stripeClient))?yield null===(r=this._stripeClient)||void 0===r?void 0:r.retrievePaymentIntent(o||""):yield null===(n=this._stripeClient)||void 0===n?void 0:n.confirmPayment({elements:s.elements,clientSecret:o,redirect:Ta.IF_REQUIRED,confirmParams:{return_url:null===(i=s.confirmParams)||void 0===i?void 0:i.return_url}});if(d=null==e?void 0:e.error,d||!(null==e?void 0:e.paymentIntent))throw new Qr;return e}catch(e){return this.stripeIntegrationService.throwStripeError(d)}})}_completeCheckoutFlow(){return Ow(this,void 0,void 0,function*(){return"function"==typeof this._onComplete?this._onComplete():(window.location.replace("/checkout/order-confirmation"),Promise.resolve())})}_getPaymentPayload(e,t){var n;const i=(null===(n=this.paymentIntegrationService.getState().getCart())||void 0===n?void 0:n.id)||"";return{methodId:e,paymentData:{formattedPayload:Object.assign(Object.assign({cart_id:i},t?{credit_card_token:{token:t}}:{}),{confirm:!1,method:Aa.Link})}}}_shouldRequireShippingAddress(){const{getCart:e}=this.paymentIntegrationService.getState(),{lineItems:t}=e()||{};return!!(null==t?void 0:t.physicalItems.length)}_updateDisplayedPrice(){return Ow(this,void 0,void 0,function*(){this._stripeElements&&this._stripeElements.update({currency:this._getCurrency(),mode:"payment",amount:yield this._getTotalPrice()})})}_getCurrency(){var e;if(!this._currencyCode){const t=null===(e=this.paymentIntegrationService.getState().getCart())||void 0===e?void 0:e.currency;t&&(this._currencyCode=t.code.toLowerCase())}return this._currencyCode}_getTotalPrice(){var e;return Ow(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const{getCheckoutOrThrow:t,getCart:n}=this.paymentIntegrationService.getState(),{decimalPlaces:i}=(null===(e=n())||void 0===e?void 0:e.currency)||{},r=ge(t().outstandingBalance,i).toFixed(i);return this._toCents(+r)})}_getAvailableCountries(){var e;return Ow(this,void 0,void 0,function*(){const t=yield this.paymentIntegrationService.loadShippingCountries();return((null===(e=t.getShippingCountries())||void 0===e?void 0:e.map(e=>e.code))||[]).filter(e=>Sd.includes(e))})}_getAvailableShippingOptions(){var e,t,n;return Ow(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getConsignments();if(!(null==i?void 0:i[0]))return;const r=i[0],o=(r.availableShippingOptions||[]).map(this._getStripeShippingOption.bind(this)),a=null===(e=r.availableShippingOptions)||void 0===e?void 0:e.find(e=>e.isRecommended),s=null===(t=r.selectedShippingOption)||void 0===t?void 0:t.id,d=null==a?void 0:a.id;return s?o.sort(e=>e.id===s?-1:0):d?(o.sort(e=>e.id===d?-1:0),yield this._handleShippingOptionChange(d)):yield this._handleShippingOptionChange(null===(n=o[0])||void 0===n?void 0:n.id),o.slice(0,9)})}_getStripeShippingOption({id:e,cost:t,description:n}){return{id:e,displayName:n,amount:this._toCents(t)}}_handleShippingOptionChange(e){return Ow(this,void 0,void 0,function*(){if(e&&"shipping_option_unselected"!==e)return this.paymentIntegrationService.selectShippingOption(e)})}_getAmountTransformer(){if(this._amountTransformer)return this._amountTransformer;const{getCart:e}=this.paymentIntegrationService.getState(),{currency:t}=e()||{};return t?new fd(t.decimalPlaces):void 0}_toCents(e){const t=Math.round(100*e),n=this._getAmountTransformer();return n?n.toInteger(e):t}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this.loadingIndicator.show(this._loadingIndicatorContainer):this.loadingIndicator.hide()}_getMethodId(e){const{initializationData:{checkoutSessionEnabled:t}={}}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e);return t?Aa.CHECKOUT_SESSION:Aa.OCS}}const Aw=vi(e=>{const t=new Ra(a()),n=new vd({containerStyles:yd});return new Ew(e,t,new pd(e,t),n)},[{id:"stripeocs"}]),Tw=e=>{const t=Ie(e);return document.getElementById(t)?Tw(e):t};function kw(e){return Object.prototype.hasOwnProperty.call(e,"cacheKey")}class Dw{constructor(e){this._lastId=0,this._map={maps:[]},this._usedMaps=[],this._options=Object.assign({maxSize:0,isEqual:Be,onExpire:ce},e)}getKey(...e){const t=this._resolveMap(...e),{index:n,parentMap:i}=t;let{map:r}=t;return r&&r.cacheKey?r.usedCount++:r=this._generateMap(i,e.slice(n)),this._removeLeastUsedMap(r),r.cacheKey}getUsedCount(...e){const{map:t}=this._resolveMap(...e);return t?t.usedCount:0}_resolveMap(...e){let t=0,n=this._map;for(;n.maps.length;){let i=!1;for(let r=0;r{const i=Object.getOwnPropertyDescriptor(e.prototype,n);i&&"constructor"!==n&&Object.defineProperty(t.prototype,n,function(e,t,n){if("function"!=typeof n.value)return n;let i=new Dw,r=n.value,o=Pe(r);return Fn(e,t,{get(){const e=(...e)=>{const t=o.call(this,...e);if(1===i.getUsedCount(...e))return t;const n=r.call(this,...e);return Pv(n,t,{keyFilter:e=>!function(e){return 0===`${e}`.indexOf("$$")||0===`${e}`.indexOf("_")}(e)})?t:(o.cache.set(i.getKey(...e),n),n)};return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e},set(e){i=new Dw,r=e,o=Pe(r)}})}(e.prototype,n,i))}),t}let zw=class{constructor(e){this._checkoutButton=e.checkoutButton}getInitializeButtonError(e){return this._checkoutButton.getInitializeError(e)}getDeinitializeButtonError(e){return this._checkoutButton.getDeinitializeError(e)}};zw=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Mw],zw);const Nw=zw;let xw=class{constructor(e){this._checkoutButton=e.checkoutButton}isInitializingButton(e){return this._checkoutButton.isInitializing(e)}isDeinitializingButton(e){return this._checkoutButton.isDeinitializing(e)}};xw=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Mw],xw);const Rw=xw;function Fw(e){return{errors:new Nw(e),statuses:new Rw(e)}}let Lw=class{constructor(e,t){this._store=e,this._buttonStrategyActionCreator=t,this._state=Fw(this._store.getState()),this._store.subscribe(e=>{this._state=Fw(e)})}getState(){return this._state}subscribe(e,...t){return this._store.subscribe(()=>e(this.getState()),e=>e.checkoutButton.getState(),...t.map(e=>t=>e(Fw(t))))}initializeButton(e){const t=(n=e.containerId,/^\w[\w\-\:\.]*$/.test(n)?[e.containerId]:function(e,t){const n=document.querySelectorAll(e);if(!n.length)throw new qt(`Unable to find any element with the specified selector: ${e}`);return Array.prototype.slice.call(n).map(e=>(e.id||(e.id=Tw(t)),e.id))}(e.containerId,`${e.methodId}-container`));var n;return Promise.all(t.map(t=>{const n=this._buttonStrategyActionCreator.initialize(Object.assign(Object.assign({},e),{containerId:t})),i=`checkoutButtonStrategy:${e.methodId}:${t}`;return this._store.dispatch(n,{queueId:i})})).then(()=>this.getState())}deinitializeButton(e){const t=this._buttonStrategyActionCreator.deinitialize(e),n=`checkoutButtonStrategy:${e.methodId}`;return this._store.dispatch(t,{queueId:n}).then(()=>this.getState())}};Lw=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],Lw);const Bw=Lw;class jw{constructor(e,t,n){this._registry=e,this._registryV2=t,this._paymentMethodActionCreator=n}initialize(e){return t=>{const n={methodId:e.methodId,containerId:e.containerId};if(t.getState().checkoutButton.isInitialized(e.methodId,e.containerId))return f();const i=e.currencyCode?{params:{currencyCode:e.currencyCode}}:{},r=Object.assign(Object.assign({},i),{timeout:e.timeout,useCache:!0});return g(C(l(Hv.InitializeButtonRequested,void 0,n)),this._paymentMethodActionCreator.loadPaymentMethod(e.methodId,r)(t),v(()=>this._getStrategy(e.methodId).initialize(e).then(()=>l(Hv.InitializeButtonSucceeded,void 0,n)))).pipe(P(e=>Je(Hv.InitializeButtonFailed,e,n)))}}deinitialize(e){return t=>{const n={methodId:e.methodId};return t.getState().checkoutButton.isInitialized(e.methodId)?g(C(l(Hv.DeinitializeButtonRequested,void 0,n)),v(()=>this._getStrategy(e.methodId).deinitialize().then(()=>l(Hv.DeinitializeButtonSucceeded,void 0,n)))).pipe(P(e=>Je(Hv.DeinitializeButtonFailed,e,n))):f()}}_getStrategy(e){let t;try{t=this._registryV2.get({id:e})}catch(n){t=this._registry.get(e)}return t}}class Uw extends it{constructor(e){super(e||"Unable to proceed because the client library of a payment method is not loaded or ready to be used."),this.name="PaymentMethodClientUnavailableError",this.type="payment_method_client_unavailable"}}var qw,Vw,Gw,Hw,Ww,$w,Yw,Kw;class Jw{constructor(e){this._scriptLoader=e,this._window=window}loadPaypal(e=""){return t=this,n=void 0,r=function*(){const t="//www.paypalobjects.com/api/checkout.min.js",n={async:!0,attributes:{"data-merchant-id":e}};if(e?yield this._scriptLoader.loadScript(t,n):yield this._scriptLoader.loadScript(t),!this._window.paypal)throw new Uw;return this._window.paypal},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(qw||(qw={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(Vw||(Vw={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black",e.WHITE="white"}(Gw||(Gw={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(Hw||(Hw={})),function(e){e.PILL="pill",e.RECT="rect"}(Ww||(Ww={}));class Zw{constructor(e,t,n,i,r=""){this._store=e,this._checkoutActionCreator=t,this._paypalScriptLoader=n,this._formPoster=i,this._host=r}initialize(e){const t=e.paypal,n=this._store.getState(),i=this._paymentMethod=n.paymentMethods.getPaymentMethod(e.methodId);if(!t)throw new qt;if(!i)throw new rt(et.MissingPaymentMethod);return this._paypalScriptLoader.loadPaypal(i.config.merchantId).then(n=>{var r,o;if(!i||!i.config.merchantId)throw new rt(et.MissingPaymentMethod);const a=i.config.merchantId,s=i.config.testMode?"sandbox":"production",d={[s]:t.clientId},c=n.FUNDING.CREDIT||"credit",l=t.allowCredit?[c]:[],u=t.allowCredit?[]:[c];return n.Button.render({env:s,client:d,commit:t.shouldProcessPayment,funding:{allowed:l,disallowed:u},style:Object.assign(Object.assign({shape:Ww.RECT},pe(t.style,"layout","color","label","shape","tagline","fundingicons")),{size:"paypalexpress"===i.id&&"small"===(null===(r=t.style)||void 0===r?void 0:r.size)?Vw.RESPONSIVE:null===(o=t.style)||void 0===o?void 0:o.size}),payment:(e,n)=>this._setupPayment(a,n,t.onPaymentError),onAuthorize:(e,n)=>this._tokenizePayment(e,n,t.shouldProcessPayment,t.onAuthorizeError)},e.containerId)})}deinitialize(){return this._paymentMethod=void 0,Promise.resolve()}_setupPayment(e,t,n){if(!t)throw new yn(cn.CheckoutButtonNotInitialized);return this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then(n=>{const i=n.cart.getCart(),r=i?i.id:"";return t.request.post(`${this._host}/api/storefront/payment/paypalexpress`,{merchantId:e,cartId:r},{headers:Object.assign({"X-API-INTERNAL":At},Xe)})}).then(e=>e.id).catch(e=>{throw n&&n(e),e})}_tokenizePayment(e,t,n,i){if(!this._paymentMethod)throw new yn(cn.CheckoutButtonNotInitialized);if(!t)throw new yn(cn.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new rt(et.MissingPayment);const r=this._paymentMethod.id;return t.payment.get(e.paymentID).then(t=>{this._formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:r,action:n?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(t.payer.payer_info)})})}}function Qw(e){const{host:t}=null!=e?e:{},i=m_({config:{meta:{host:null==e?void 0:e.host,locale:null==e?void 0:e.locale},errors:{},statuses:{}}}),r=n({host:t}),o=Ee({host:t}),s=function(e,t){const n=new Gt;for(const[,i]of Object.entries(t))if(Ut(i))for(const t of i.resolveIds)n.register(t,()=>i(e));return n}(Hg(i),We);return new Bw(i,new jw(function(e,t,n,i){const r=new Vt,o=a(),s=new en(t),d=new nn(s,new bt(new Tt(t)),new on(new an(t)));return r.register(zy.PAYPALEXPRESS,()=>new Zw(e,d,new Jw(o),n,i)),r}(i,r,o,t),s,new Wm(new $m(r))))}!function(e){e.CheckoutComplete="CHECKOUT_COMPLETE",e.CheckoutError="CHECKOUT_ERROR",e.CheckoutLoaded="CHECKOUT_LOADED",e.FrameError="FRAME_ERROR",e.FrameLoaded="FRAME_LOADED",e.SignedOut="SIGNED_OUT"}($w||($w={}));class Xw extends Ot{constructor(e){super(e,{message:e.body.title}),this.name="InvalidLoginTokenError",this.type="invalid_login_token"}}!function(e){e.MissingContainer="missing_container",e.MissingContent="missing_content",e.UnknownError="unknown_error"}(Yw||(Yw={}));class eI extends it{constructor(e,t=Yw.UnknownError){super(e||"Unable to embed the checkout form."),this.subtype=t,this.name="NotEmbeddableError",this.type="not_embeddable"}}!function(e){e.StyleConfigured="STYLE_CONFIGURED"}(Kw||(Kw={}));const tI="isCookieAllowed",nI="lastAllowCookieAttempt";let iI=class{constructor(e,t,n,i,r,o,a,s){this._iframeCreator=e,this._messageListener=t,this._messagePoster=n,this._loadingIndicator=i,this._requestSender=r,this._storage=o,this._location=a,this._options=s,this._isAttached=!1,this._options.onComplete&&this._messageListener.addListener($w.CheckoutComplete,this._options.onComplete),this._options.onError&&this._messageListener.addListener($w.CheckoutError,this._options.onError),this._options.onLoad&&this._messageListener.addListener($w.CheckoutLoaded,this._options.onLoad),this._options.onFrameLoad&&this._messageListener.addListener($w.FrameLoaded,this._options.onFrameLoad),this._options.onSignOut&&this._messageListener.addListener($w.SignedOut,this._options.onSignOut),this._messageListener.addListener($w.FrameLoaded,()=>this._configureStyles())}attach(){return this._isAttached?Promise.resolve(this):(this._isAttached=!0,this._messageListener.listen(),this._loadingIndicator.show(this._options.containerId),this._allowCookie().then(()=>this._attemptLogin()).then(e=>this._iframeCreator.createFrame(e,this._options.containerId)).then(e=>{this._iframe=e,this._configureStyles(),this._loadingIndicator.hide()}).catch(e=>(this._isAttached=!1,this._retryAllowCookie(e).catch(()=>{throw this._messageListener.trigger({type:$w.FrameError,payload:e}),this._loadingIndicator.hide(),e}))).then(()=>this))}detach(){this._isAttached&&(this._isAttached=!1,this._messageListener.stopListen(),this._iframe&&this._iframe.parentNode&&(this._iframe.parentNode.removeChild(this._iframe),this._iframe.iFrameResizer.close()))}_configureStyles(){this._iframe&&this._iframe.contentWindow&&this._options.styles&&(this._messagePoster.setTarget(this._iframe.contentWindow),this._messagePoster.post({type:Kw.StyleConfigured,payload:this._options.styles}))}_attemptLogin(){return/^\/login\/token/.test(In(this._options.url).pathname)?this._requestSender.post(this._options.url).then(({body:{redirectUrl:e}})=>e).catch(e=>Promise.reject(new Xw(e))):Promise.resolve(this._options.url)}_allowCookie(){if(this._storage.getItem(tI))return Promise.resolve();this._storage.setItem(tI,!0),this._storage.setItem(nI,Date.now());const{origin:e}=In(this._options.url),t=`${e}/embedded-checkout/allow-cookie?returnUrl=${encodeURIComponent(this._location.href)}`;return document.body.style.visibility="hidden",this._location.replace(t),new Promise(()=>{})}_retryAllowCookie(e){const t=Number(this._storage.getItem(nI));return(!t||Date.now()-t>6e5)&&e instanceof eI&&e.subtype===Yw.MissingContent?(this._storage.removeItem(nI),this._storage.removeItem(tI),this._allowCookie()):Promise.reject()}};iI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],iI);const rI=iI;class oI{constructor(e){this._options=e}createFrame(e,t){const n=document.getElementById(t),{timeout:i=6e4}=this._options||{};if(!n)throw new eI("Unable to embed the iframe because the container element could not be found.",Yw.MissingContainer);const r=document.createElement("iframe");return r.src=e,r.style.border="none",r.style.display="none",r.style.width="100%",r.allowPaymentRequest=!0,r.allow="payment",n.appendChild(r),this._toResizableFrame(r,i).catch(e=>{throw n.removeChild(r),e})}_toResizableFrame(e,t){return new Promise((n,i)=>{const r=window.setTimeout(()=>{i(new eI("Unable to embed the iframe because the content could not be loaded."))},t),o=t=>{if((t.origin===In(e.src).origin||t.origin===Wn(In(e.src)).origin)&&(bn(t.data,$w.FrameError)&&(a(),i(new eI(t.data.payload.message,Yw.MissingContent))),bn(t.data,$w.FrameLoaded))){e.style.display="";const i=Dn({scrolling:!1,sizeWidth:!1,heightCalculationMethod:t.data.payload&&t.data.payload.contentId?"taggedElement":"lowestElement"},e);a(),n(i[i.length-1])}},a=()=>{window.removeEventListener("message",o),window.clearTimeout(r)};window.addEventListener("message",o)})}}function aI(e){const t=In(e.url).origin;return new rI(new oI,new Yn(t),new Pn(t),new vd({styles:e.styles&&e.styles.loadingIndicator}),n(),new iy("BigCommerce.EmbeddedCheckout"),window.location,e).attach()}function sI(e){if(!e.payload||!e.payload.contentId)return;const t=document.getElementById(e.payload.contentId);t&&!t.hasAttribute("data-iframe-height")&&t.setAttribute("data-iframe-height","")}function dI(e){return"object"==typeof e&&null!==e&&"message"in e&&"type"in e}let cI=class{constructor(e,t,n,i={}){this._messageListener=e,this._messagePoster=t,this._untargetedMessagePoster=n,this._messageHandlers=i,this._messageListener.listen()}postComplete(){const e={type:$w.CheckoutComplete};this._postMessage(e)}postError(e){const t={type:$w.CheckoutError,payload:this._transformError(e)};this._postMessage(t)}postFrameError(e){const t={type:$w.FrameError,payload:this._transformError(e)};this._postMessage(t,{untargeted:!0})}postFrameLoaded(e){const t={type:$w.FrameLoaded,payload:e};this._postMessage(t)}postLoaded(){const e={type:$w.CheckoutLoaded};this._postMessage(e)}postSignedOut(){const e={type:$w.SignedOut};this._postMessage(e)}receiveStyles(e){this._messageListener.addListener(Kw.StyleConfigured,({payload:t})=>{e(t)})}_postMessage(e,t){if(this._notifyMessageHandlers(e),t&&t.untargeted)return this._untargetedMessagePoster.post(e);this._messagePoster.post(e)}_notifyMessageHandlers(e){Object.keys(this._messageHandlers).forEach(t=>{if(e.type!==t)return;const n=this._messageHandlers[t];n&&n.call(null,e)})}_transformError(e){return{message:e.message,type:dI(e)?e.type:void 0,subtype:dI(e)?e.subtype:void 0}}};cI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],cI);const lI=cI;let uI=class{postComplete(){}postError(){}postFrameError(){}postFrameLoaded(){}postLoaded(){}postSignedOut(){}receiveStyles(){}};uI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],uI);const hI=uI;function pI(e){Ve(939);const t=e.parentWindow||window.parent;return window===t?new hI:new lI(new Yn(e.parentOrigin),new Pn(e.parentOrigin,t),new Pn("*",t),{[$w.FrameLoaded]:sI})}const mI="en",yI="optimized_checkout";let gI=class{constructor(e,t){this._logger=t;const{locale:n,locales:i,translations:r}=this._transformConfig(e);this._locale=n,this._locales=i,this._translations=r,this._formatters={}}mapKeys(e){Object.keys(e).forEach(t=>{const n=`${yI}.${e[t]}`;this._translations[`${yI}.${t}`]=this._translations[n]})}getLocale(){return this._hasTranslations()?this._locale:mI}translate(e,t={}){var n;const i=`${yI}.${e}`;if("string"!=typeof this._translations[i])return this._logger.warn(`Translation key "${i}" is missing`),i;this._formatters[i]||(this._formatters[i]=new je(this._escapeSpecialCharacters(this._translations[i]||""),this._locales[i],void 0,{ignoreTag:!0}));try{return this._formatters[i].format(this._transformData(t))}catch(e){if(this._isFormatError(e))return null!==(n=e.originalMessage)&&void 0!==n?n:"";throw e}}_transformConfig(e={}){const t={defaultLocale:"",defaultTranslations:{},translations:{},locales:{},locale:e.locale||mI},n=e.locales||{},i=this._flattenObject(e.translations||{}),r=this._flattenObject(e.defaultTranslations||{}),o=this._flattenObject(e.fallbackTranslations||{});return _e(Object.keys(o),Object.keys(r),Object.keys(i)).forEach(a=>{var s,d;i&&i[a]?(t.translations[a]=i[a],t.locales[a]=n[a]||t.locale):r[a]?(t.translations[a]=r[a],t.locales[a]=null!==(s=e.defaultLocale)&&void 0!==s?s:mI):(t.translations[a]=o[a],t.locales[a]=null!==(d=e.fallbackLocale)&&void 0!==d?d:mI)}),t}_flattenObject(e,t={},n=""){try{Object.keys(e).forEach(i=>{const r=e[i],o=n?`${n}.${i}`:i;if(Z(r))return this._flattenObject(r,t,o);t[o]=r})}catch(e){this._logger.warn(`Unable to parse object: ${e}`)}return t}_transformData(e){return Object.keys(e).reduce((t,n)=>{const i=e[n];return t[n]=null==i?"":i,t},{})}_hasTranslations(){return Object.keys(this._locales).map(e=>this._locales[e]).filter(e=>e.split("-")[0]===this._locale.split("-")[0]).length>0}_isFormatError(e){return"object"==typeof e&&null!==e&&"originalMessage"in e}_escapeSpecialCharacters(e){return e.replace(/(\w+)='([^']*)'/g,"$1=''$2''")}};gI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],gI);const vI=gI;function fI(e={}){return new vI(e,wt())}let SI=class{constructor(e){this._storeConfig=e,this._customerFormatter=new Fo(this._storeConfig.shopperCurrency),this._storeFormatter=new Fo(this._storeConfig.currency)}toCustomerCurrency(e){const t=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(e*t)}toStoreCurrency(e){return this._storeFormatter.format(e)}};SI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],SI);const _I=SI;function wI(e){return new _I(e)}function II(e){return e&&"ga"in e&&"function"==typeof e.ga}function CI(e,t){II(window)&&window.ga("send",e,Object.assign(Object.assign({},t),{nonInteraction:!1}))}function bI(e){return PI(e).length>=8096}function PI(e){return Object.keys(e).reduce((t,n)=>{const i=typeof e[n];return"string"===i||"number"===i?[...t,`${n}=${e[n]}`]:"object"===i&&null!==e[n]?[...t,PI(e[n])]:t},[]).join("&")}var OI;!function(e){e[e.CUSTOMER=1]="CUSTOMER",e[e.SHIPPING=2]="SHIPPING",e[e.BILLING=3]="BILLING",e[e.PAYMENT=4]="PAYMENT"}(OI||(OI={}));const EI={customer:OI.CUSTOMER,shipping:OI.SHIPPING,billing:OI.BILLING,payment:OI.PAYMENT};class AI{constructor(e,t,n,{checkoutSteps:i}={}){if(this.checkoutService=e,this.analyticsExtraItemsManager=t,this.analytics=n,this._checkoutStarted=!1,this._completedSteps={},this._viewedSteps={},this._analyticStepOrder=["customer","shipping","billing","payment"],void 0!==i){if(i.some(e=>!(e in EI)))throw new qt(`Invalid checkout steps provided. Valid values are: ${ie(EI).join(", ")}.`);this._analyticStepOrder=i}}trackCheckoutStarted(){if(this._checkoutStarted)return;const e=this.getCheckout();if(!e)return;const{coupons:t,grandTotal:n,shippingCostTotal:i,taxTotal:r,cart:{lineItems:o,discountAmount:a,id:s}}=e,d=this.analyticsExtraItemsManager.saveExtraItemsData(s,o);this.analytics.track("Checkout Started",this.getTrackingPayload({revenue:n,shipping:i,tax:r,discount:a,coupons:t,lineItems:o,extraItemsData:d})),this._checkoutStarted=!0}trackOrderComplete(){var e;const t=this.getOrder();if(!t)return;const{isComplete:n,orderId:i,orderAmount:r,shippingCostTotal:o,taxTotal:a,discountAmount:s,coupons:d,lineItems:c,cartId:l}=t;if(!n)return;const u=this.analyticsExtraItemsManager.readExtraItemsData(l);if(null===u)return;const h=null===(e=this.checkoutService.getState().data.getConfig())||void 0===e?void 0:e.checkoutSettings.features["DATA-6891.missing_orders_within_GA"],p=this.getTrackingPayload({orderId:i,revenue:r,shipping:o,tax:a,discount:s,coupons:d,extraItemsData:u,lineItems:c});if(h&&pl(window)&&II(window)&&bI(p))return CI("transaction",{"&ti":p.order_id,"&ta":p.affiliation,"&tr":p.revenue,"&ts":p.shipping,"&tt":p.tax,"&tcc":p.coupon,"&cu":p.currency}),p.products.forEach(e=>{CI("item",{"&ti":p.order_id,"&in":e.name,"&ic":e.sku,"&iv":`${e.category}`,"&ip":e.price,"&iq":e.quantity})}),this.analyticsExtraItemsManager.clearExtraItemData(l);this.analytics.track("Order Completed",p),this.analyticsExtraItemsManager.clearExtraItemData(l)}trackStepViewed(e){const t=this.getIdFromStep(e);t&&!this.hasStepViewed(t)&&(this.trackViewed(t),this.backfill(t))}trackStepCompleted(e){const t=this.getIdFromStep(e);t&&!this.hasStepCompleted(t)&&(this.backfill(t),this.trackCompleted(t))}backfill(e){for(const t of this._analyticStepOrder){const n=this.getIdFromStep(t);if(!n)break;if(this.hasStepViewed(n)||this.trackViewed(n),n===e)break;this.hasStepCompleted(n)||this.trackCompleted(n)}}trackCompleted(e){const t=this.getSelectedShippingOption(),{code:n=""}=this.getShopperCurrency()||{},i=this.getPaymentMethodName(),r={step:e,currency:n};t&&(r.shipping_method=t.description),i&&(r.payment_method=i),r.shipping_method||r.payment_method||(r.shipping_method=" "),this.analytics.track("Checkout Step Completed",r);const o=t?t.id:"",a=e===OI.SHIPPING?`${e}-${o}`:e;this._completedSteps[a]=!0}getTrackingPayload({orderId:e,revenue:t,shipping:n,tax:i,discount:r,coupons:o,extraItemsData:a,lineItems:s}){const{code:d=""}=this.getShopperCurrency()||{},{storeName:c=""}=this.getStoreProfile()||{};return{order_id:String(e),affiliation:c,revenue:this.toShopperCurrency(t),shipping:this.toShopperCurrency(n),tax:this.toShopperCurrency(i),discount:this.toShopperCurrency(r),coupon:(o||[]).map(e=>e.code.toUpperCase()).join(","),currency:d,products:this.getProducts(a,s)}}hasStepCompleted(e){const t=this.getSelectedShippingOption(),n=t?t.id:"";return Object.prototype.hasOwnProperty.call(this._completedSteps,e)||e===OI.SHIPPING&&Object.prototype.hasOwnProperty.call(this._completedSteps,`${e}-${n}`)}hasStepViewed(e){return!!this._viewedSteps[e]}getIdFromStep(e){const t=e.split(".");return EI[t[0]]||null}trackViewed(e){const t=this.getShopperCurrency();this.analytics.track("Checkout Step Viewed",{step:e,currency:t?t.code:""}),this._viewedSteps[e]=!0}getOrder(){const{data:{getOrder:e}}=this.checkoutService.getState();return e()}getCheckout(){const{data:{getCheckout:e}}=this.checkoutService.getState();return e()}getShopperCurrency(){const{data:{getConfig:e}}=this.checkoutService.getState(),t=e();return t&&t.shopperCurrency}getStoreProfile(){const{data:{getConfig:e}}=this.checkoutService.getState(),t=e();return t&&t.storeProfile}toShopperCurrency(e){const{exchangeRate:t=1}=this.getShopperCurrency()||{};return Math.round(e*t*100)/100}getSelectedShippingOption(){const{data:e}=this.checkoutService.getState(),t=e.getSelectedShippingOption();return t&&t.id&&t.description?t:null}getPaymentMethodName(){const{data:e}=this.checkoutService.getState(),t=e.getSelectedPaymentMethod();return t&&t.config&&t.config.displayName||""}getProducts(e,t){const n=(t.customItems||[]).map(e=>({product_id:e.id,sku:e.sku,price:e.listPrice,quantity:e.quantity,name:e.name})),i=t.giftCertificates.map(e=>({product_id:e.id,price:this.toShopperCurrency(e.amount),name:e.name,quantity:1}));return[...n,...[...t.physicalItems,...t.digitalItems].map(t=>{let n;t.options&&t.options.length&&(n=t.options.map(e=>`${e.name}:${e.value}`),n.sort());const i=Array.isArray(n)&&n.length?n.join(", "):"single-product-option",r=e[t.productId]&&e[t.productId].brand;return Object.assign({product_id:String(t.productId),sku:t.sku,price:t.salePrice,image_url:t.imageUrl,name:t.name,quantity:t.quantity,category:e[t.productId]?e[t.productId].category:"",variant:i},r&&{brand:r})}),...i]}}class TI{trackCheckoutStarted(){}trackOrderComplete(){}trackStepViewed(){}trackStepCompleted(){}}function kI(e,t){const{data:n}=e.getState(),i=n.getConfig();if(!i)throw new rt(et.MissingCheckoutConfig);const{isAnalyticsEnabled:r}=i.checkoutSettings;return r&&pl(window)?new AI(e,new hl(Te),window.analytics,t):new TI}function DI(e){return Boolean(e.hasOwnProperty("braintreeFastlane"))}class MI{constructor(e){this.checkoutService=e,this._selectedPaymentMethodId=""}customerPaymentMethodExecuted(){this._shouldTrackFastlaneEvent()&&this._trackEmailSubmitted()}paymentComplete(){this._shouldTrackFastlaneEvent()&&this._trackOrderPlaced(this._selectedPaymentMethodId)}selectedPaymentMethod(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!1))}walletButtonClick(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!0))}_shouldTrackFastlaneEvent(){const e=this.checkoutService.getState(),t=e.data.getPaymentMethod("braintree")||e.data.getPaymentMethod("braintreeacceleratedcheckout"),n=null==t?void 0:t.initializationData.isBraintreeAnalyticsV2Enabled,i=DI(window)&&window.braintreeFastlane.events;return n&&i}_getBraintreeEventsOrThrow(){if(DI(window))return window.braintreeFastlane.events;throw new mi}_trackEmailSubmitted(){const{emailSubmitted:e}=this._getBraintreeEventsOrThrow();e(this._getEmailSubmittedEventOptions())}_trackApmSelected(e,t){const{apmSelected:n}=this._getBraintreeEventsOrThrow();n(this._getApmSelectedEventOptions(e,t))}_trackOrderPlaced(e){const{orderPlaced:t}=this._getBraintreeEventsOrThrow();t(this._getOrderPlacedEventOptions(e))}_getEventCommonOptions(){var e,t;const n=this.checkoutService.getState(),i=n.data.getCart(),r=null===(e=n.data.getConfig())||void 0===e?void 0:e.storeProfile,o=null===(t=n.data.getCustomer())||void 0===t?void 0:t.isGuest,a=n.data.getPaymentMethod("braintreeacceleratedcheckout"),s=[{treatment_group:!n.errors.getLoadPaymentMethodError("braintreeacceleratedcheckout")&&(null==a?void 0:a.initializationData.shouldRunAcceleratedCheckout)?"test":"control"}];return{context_type:"cs_id",context_id:(null==i?void 0:i.id)||"",page_type:"checkout_page",page_name:window.document.title,partner_name:"bigc",user_type:o?"store_guest":"store_member",store_id:(null==r?void 0:r.storeId)||"",merchant_name:(null==r?void 0:r.storeName)||"",experiment:JSON.stringify(s)}}_getEmailSubmittedEventOptions(){const e=(this.checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{user_email_saved:!1,apm_shown:e.length>1?"1":"0",apm_list:e.join(",")})}_getApmSelectedEventOptions(e,t){const n=(this.checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{apm_shown:n.length>1?"1":"0",apm_list:n.join(","),apm_selected:e,apm_location:t?"pre-email section":"payment section"})}_getOrderPlacedEventOptions(e){const t=this.checkoutService.getState().data.getCart();return Object.assign(Object.assign({},this._getEventCommonOptions()),{selected_payment_method:e,currency_code:(null==t?void 0:t.currency.code)||""})}}function zI(e){return new MI(e)}class NI{constructor(e){this._checkoutService=e,this._selectedPaymentMethodId=""}customerPaymentMethodExecuted(){this._shouldTrackFastlaneEvent()&&this._trackEmailSubmitted()}paymentComplete(){this._shouldTrackFastlaneEvent()&&this._trackOrderPlaced(this._selectedPaymentMethodId)}selectedPaymentMethod(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!1))}walletButtonClick(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!0))}_shouldTrackFastlaneEvent(){const e=this._checkoutService.getState().data.getPaymentMethod("paypalcommerce"),t=((null==e?void 0:e.initializationData)||{}).isPayPalCommerceAnalyticsV2Enabled,n=window,i=!!n.paypalFastlane&&!!n.paypalFastlane.events;return t&&i}_getPayPalEventsOrThrow(){const e=window;if(e.paypalFastlane&&e.paypalFastlane.events)return e.paypalFastlane.events;throw new mi}_trackEmailSubmitted(){const{emailSubmitted:e}=this._getPayPalEventsOrThrow();e(this._getEmailSubmittedEventOptions())}_trackApmSelected(e,t){const{apmSelected:n}=this._getPayPalEventsOrThrow();n(this._getApmSelectedEventOptions(e,t))}_trackOrderPlaced(e){const{orderPlaced:t}=this._getPayPalEventsOrThrow();t(this._getOrderPlacedEventOptions(e))}_getEventCommonOptions(){var e,t;const n=this._checkoutService.getState(),i=n.data.getCart(),r=null===(e=n.data.getConfig())||void 0===e?void 0:e.storeProfile,o=null===(t=n.data.getCustomer())||void 0===t?void 0:t.isGuest,a="paypalcommerceacceleratedcheckout",s=n.data.getPaymentMethod(a),d=[{treatment_group:!n.errors.getLoadPaymentMethodError(a)&&(null==s?void 0:s.initializationData.shouldRunAcceleratedCheckout)?"test":"control"}];return{context_type:"cs_id",context_id:(null==i?void 0:i.id.replace(/-/g,""))||"",page_type:"checkout_page",page_name:window.document.title,partner_name:"bigc",user_type:o?"store_guest":"store_member",store_id:(null==r?void 0:r.storeId)||"",merchant_name:(null==r?void 0:r.storeName)||"",experiment:JSON.stringify(d)}}_getEmailSubmittedEventOptions(){const e=(this._checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{user_email_saved:!1,apm_shown:e.length>1?"1":"0",apm_list:e.join(",")})}_getApmSelectedEventOptions(e,t){const n=(this._checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{apm_shown:n.length>1?"1":"0",apm_list:n.join(","),apm_selected:e,apm_location:t?"pre-email section":"payment section"})}_getOrderPlacedEventOptions(e){const t=this._checkoutService.getState().data.getCart();return Object.assign(Object.assign({},this._getEventCommonOptions()),{selected_payment_method:e,currency_code:(null==t?void 0:t.currency.code)||""})}}function xI(e){return new NI(e)}var RI;class FI{constructor(e,t){this._host=e,this._hostedFormFactory=t}submitStoredCard(e,t){return n=this,i=void 0,o=function*(){const n=this._hostedForm;if(!n)throw new yn(cn.PaymentNotInitialized);yield n.validate().then(()=>n.submitStoredCard({fields:e,data:t}))},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}initialize(e){const t=this._hostedFormFactory.create(this._host,e);return t.attach().then(()=>{this._hostedForm=t})}deinitialize(){this._hostedForm&&this._hostedForm.detach()}}function LI(e){const t=m_();return new FI(e,new Iy(t))}!function(e){e.CUSTOMER="customer",e.SHIPPING="shipping",e.BILLING="billing",e.PAYMENT="payment"}(RI||(RI={}));const BI=[RI.CUSTOMER,RI.SHIPPING,RI.BILLING,RI.PAYMENT];class jI{constructor(e,t){this.subscribe=e,this.bodlEvents=t,this._checkoutStarted=!1,this._emailEntryBegan=!1,this._shippingOptionsShown=!1,this._completedSteps={},this.subscribe(e=>{var t;if(this.setState(e.data),!(null===(t=this.state)||void 0===t?void 0:t.getConfig()))throw new rt(et.MissingCheckoutConfig)})}setState(e){this.state=e}checkoutBegin(){const e=this._getCommonCheckoutData();!this._checkoutStarted&&e&&(this.bodlEvents.emitCheckoutBeginEvent(e),this._checkoutStarted=!0)}orderPurchased(){var e;const t=null===(e=this.state)||void 0===e?void 0:e.getOrder();if(!t)return;const{currency:n,isComplete:i,orderId:r,orderAmount:o,shippingCostTotal:a,lineItems:s,cartId:d,coupons:c,channelId:l,taxTotal:u}=t;i&&this.bodlEvents.emitOrderPurchasedEvent({event_id:d,currency:n.code,order_id:r,tax:u,channel_id:l,cart_value:o,coupon_codes:c.map(e=>e.code.toUpperCase()),shipping_cost:a,line_items:this._getProducts(s,n.code)})}stepCompleted(e){e&&BI.some(t=>(this._hasStepCompleted(t)||this._trackCompletedStep(t),t===e))}customerEmailEntry(e){!this._emailEntryBegan&&(null==e?void 0:e.length)&&(this._emailEntryBegan=!0,this.bodlEvents.emit("bodl_checkout_email_entry_began"))}customerSuggestionInit(e){this.bodlEvents.emit("bodl_checkout_customer_suggestion_initialization",e)}customerSuggestionExecute(){this.bodlEvents.emit("bodl_checkout_customer_suggestion_execute")}customerPaymentMethodExecuted(e){this.bodlEvents.emit("bodl_checkout_customer_payment_method_executed",e)}showShippingMethods(){this._shippingOptionsShown||(this._shippingOptionsShown=!0,this.bodlEvents.emit("bodl_checkout_show_shipping_options"))}selectedPaymentMethod(e){const t=this._getCommonCheckoutData();t&&e&&this.bodlEvents.emitPaymentDetailsProvidedEvent(Object.assign(Object.assign({},t),{payment_type:e}))}clickPayButton(e){this.bodlEvents.emit("bodl_checkout_click_pay_button",e)}paymentRejected(){this.bodlEvents.emit("bodl_checkout_payment_rejected")}paymentComplete(){this.bodlEvents.emit("bodl_checkout_payment_complete")}exitCheckout(){this.bodlEvents.emit("bodl_checkout_exit")}_trackCompletedStep(e){this._completedSteps[e]=!0;const t={[RI.SHIPPING]:this._trackShippingStepCompleted.bind(this)}[e];t?t():this.bodlEvents.emit("bodl_checkout_step_completed",{step:e})}_trackShippingStepCompleted(){var e,t;const n=null===(t=null===(e=this.state)||void 0===e?void 0:e.getSelectedShippingOption())||void 0===t?void 0:t.description,i=this._getCommonCheckoutData();i&&n&&this.bodlEvents.emitShippingDetailsProvidedEvent(Object.assign(Object.assign({},i),{shipping_method:n}))}_getCommonCheckoutData(){var e;const t=null===(e=this.state)||void 0===e?void 0:e.getCheckout();if(!t)return null;const{cart:{cartAmount:n,currency:i,lineItems:r,id:o,coupons:a},channelId:s}=t;return{event_id:o,currency:i.code,cart_value:n,coupon_codes:a.map(e=>e.code.toUpperCase()),line_items:this._getProducts(r,i.code),channel_id:s}}_getProducts(e,t){const n=(e.customItems||[]).map(e=>({product_id:e.id,sku:e.sku,base_price:e.listPrice,sale_price:e.listPrice,purchase_price:e.listPrice,quantity:e.quantity,product_name:e.name,currency:t})),i=e.giftCertificates.map(e=>({product_id:e.id,gift_certificate_id:e.id,base_price:e.amount,sale_price:e.amount,purchase_price:e.amount,product_name:e.name,gift_certificate_name:e.name,gift_certificate_theme:e.theme,quantity:1,currency:t}));return[...n,...[...e.physicalItems,...e.digitalItems].map(e=>{let n;return e.options&&e.options.length&&(n=e.options.map(e=>`${e.name}:${e.value}`),n.sort()),{product_id:e.productId,quantity:e.quantity,product_name:e.name,base_price:e.listPrice,sale_price:e.salePrice,purchase_price:e.salePrice>0?e.salePrice:e.listPrice,sku:e.sku,variant_id:e.variantId,discount:e.discountAmount,coupon_amount:e.couponAmount,brand_name:e.brand,currency:t,category_names:(i=e,Array.isArray(i.categoryNames)?i.categoryNames:Array.isArray(i.categories)?q(i.categories).map(({name:e})=>e):[]),retail_price:e.retailPrice};var i}),...i].map(e=>Object.assign(Object.assign({},e),{product_id:String(e.product_id)}))}_hasStepCompleted(e){return this._completedSteps[e]}}class UI{checkoutBegin(){}orderPurchased(){}stepCompleted(){}customerEmailEntry(){}customerSuggestionInit(){}customerSuggestionExecute(){}customerPaymentMethodExecuted(){}showShippingMethods(){}selectedPaymentMethod(){}clickPayButton(){}paymentRejected(){}paymentComplete(){}exitCheckout(){}}function qI(e){return function(e){return"bodlEvents"in e}(window)?new jI(e,window.bodlEvents.checkout):new UI}export{Bn as ExtensionCommandType,jn as ExtensionQueryType,qI as createBodlService,zI as createBraintreeAnalyticTracker,Qw as createCheckoutButtonInitializer,y_ as createCheckoutService,wI as createCurrencyService,pI as createEmbeddedCheckoutMessenger,fI as createLanguageService,xI as createPayPalCommerceAnalyticTracker,kI as createStepTracker,LI as createStoredCardHostedFormService,i as createTimeout,aI as embedCheckout,Ye as isExtraField}; +import*as e from"iframe-resizer";import*as t from"iframe-resizer/js/iframeResizer.contentWindow";import{createRequestSender as n,createTimeout as i}from"@bigcommerce/request-sender";import{ScriptLoader as r,createScriptLoader as o,getScriptLoader as a,getStylesheetLoader as s}from"@bigcommerce/script-loader";import{combineReducers as d,composeReducers as c,createAction as l,createDataStore as u,createErrorAction as h,deepFreeze as p}from"@bigcommerce/data-store";import{Observable as m,Subject as y,concat as g,defer as v,empty as f,from as S,fromEvent as _,merge as w,noop as I,of as C,throwError as b}from"rxjs";import{catchError as P,delay as O,distinctUntilChanged as E,filter as A,map as T,retryWhen as k,shareReplay as D,switchMap as M,take as z}from"rxjs/operators";import{cond as N,constant as x,difference as R,each as F,filter as L,find as B,findIndex as j,flatMap as U,flatten as q,get as V,identity as G,includes as H,isArray as W,isEmpty as $,isEqual as Y,isMatch as K,isNil as J,isObject as Z,isPlainObject as Q,isString as X,isUndefined as ee,kebabCase as te,keyBy as ne,keys as ie,last as re,map as oe,max as ae,memoize as se,merge as de,noop as ce,omit as le,omitBy as ue,overSome as he,pick as pe,pickBy as me,reduce as ye,round as ge,some as ve,stubTrue as fe,transform as Se,union as _e,uniq as we,uniqueId as Ie,values as Ce,without as be}from"lodash";import{memoize as Pe,memoizeOne as Oe}from"@bigcommerce/memoize";import{createFormPoster as Ee}from"@bigcommerce/form-poster";import{supportsPopups as Ae}from"@braintree/browser-detection";import{default as Te}from"local-storage-fallback";import{createClient as ke}from"@bigcommerce/bigpay-client";import{creditCardType as De,number as Me}from"card-validator";import{exclude as ze,parseUrl as Ne,stringifyUrl as xe}from"query-string";import{createSelector as Re,createSelectorCreator as Fe,defaultMemoize as Le}from"reselect";import{default as Be}from"shallowequal";import{IntlMessageFormat as je}from"intl-messageformat";var Ue={785(t,n,i){var r,o;t.exports=(r={iframeResizer:()=>e.iframeResizer},o={},i.d(o,r),o)},939(e){e.exports=t}},qe={};function Ve(e){var t=qe[e];if(void 0!==t)return t.exports;var n=qe[e]={exports:{}};return Ue[e](n,n.exports,Ve),n.exports}Ve.d=(e,t)=>{for(var n in t)Ve.o(t,n)&&!Ve.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},Ve.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ve.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var Ge={};Ve.r(Ge),Ve.d(Ge,{createAmazonPayV2CustomerStrategy:()=>Ii,createApplePayCustomerStrategy:()=>Xi,createBigCommercePaymentsCustomerStrategy:()=>br,createBigCommercePaymentsFastlaneCustomerStrategy:()=>Hr,createBigCommercePaymentsPayLaterCustomerStrategy:()=>Yr,createBigCommercePaymentsVenmoCustomerStrategy:()=>Zr,createBoltCustomerStrategy:()=>so,createBraintreeFastlaneCustomerStrategy:()=>zo,createBraintreePaypalCreditCustomerStrategy:()=>Oo,createBraintreePaypalCustomerStrategy:()=>Co,createBraintreeVisaCheckoutCustomerStrategy:()=>Ro,createGooglePayAdyenV2CustomerStrategy:()=>ca,createGooglePayAdyenV3CustomerStrategy:()=>la,createGooglePayAuthorizeDotNetCustomerStrategy:()=>ha,createGooglePayBigCommercePaymentsCustomerStrategy:()=>as,createGooglePayBnzCustomerStrategy:()=>_a,createGooglePayBraintreeCustomerStrategy:()=>Ya,createGooglePayCheckoutComCustomerStrategy:()=>va,createGooglePayCybersourceCustomerStrategy:()=>Sa,createGooglePayOrbitalCustomerStrategy:()=>Ia,createGooglePayPayPalCommerceCustomerStrategy:()=>is,createGooglePayStripeCustomerStrategy:()=>qa,createGooglePayStripeUpeCustomerStrategy:()=>Va,createGooglePayTdOnlineMartCustomerStrategy:()=>ls,createGooglePayWorldpayAccessCustomerStrategy:()=>Ha,createPayPalCommerceCreditCustomerStrategy:()=>Js,createPayPalCommerceCustomerStrategy:()=>zs,createPayPalCommerceFastlaneCustomerStrategy:()=>sd,createPayPalCommerceVenmoCustomerStrategy:()=>Xs,createStripeLinkV2CustomerStrategy:()=>Id,createStripeUPECustomerStrategy:()=>ud});var He={};Ve.r(He),Ve.d(He,{createAdyenV2PaymentStrategy:()=>Ld,createAdyenV3PaymentStrategy:()=>Vd,createAffirmPaymentStrategy:()=>Yd,createAfterpayPaymentStrategy:()=>tc,createAmazonPayV2PaymentStrategy:()=>rc,createApplePayPaymentStrategy:()=>dc,createBigCommercePaymentsAlternativeMethodsPaymentStrategy:()=>xc,createBigCommercePaymentsCreditCardsPaymentStrategy:()=>Mc,createBigCommercePaymentsFastlanePaymentStrategy:()=>fc,createBigCommercePaymentsPayLaterPaymentStrategy:()=>wc,createBigCommercePaymentsPaymentStrategy:()=>mc,createBigCommercePaymentsRatePayPayPaymentStrategy:()=>Pc,createBigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy:()=>Fc,createBigCommercePaymentsVenmoPaymentStrategy:()=>jc,createBlueSnapDirectAPMPaymentStrategy:()=>al,createBlueSnapDirectCreditCardPaymentStrategy:()=>rl,createBlueSnapV2PaymentStrategy:()=>ul,createBoltPaymentStrategy:()=>fl,createBraintreeAchPaymentStrategy:()=>Il,createBraintreeCreditCardPaymentStrategy:()=>Ql,createBraintreeFastlanePaymentStrategy:()=>Ll,createBraintreeLocalMethodsPaymentStrategy:()=>Nl,createBraintreePaypalPaymentStrategy:()=>kl,createBraintreeVenmoPaymentStrategy:()=>Gl,createBraintreeVisaCheckoutPaymentStrategy:()=>Ul,createCBAMPGSPaymentStrategy:()=>ou,createCheckoutComAPMPaymentStrategy:()=>wu,createCheckoutComCreditCardPaymentStrategy:()=>mu,createCheckoutComFawryPaymentStrategy:()=>cu,createCheckoutComIdealPaymentStrategy:()=>fu,createCheckoutComSepaPaymentStrategy:()=>gu,createClearpayPaymentStrategy:()=>Pu,createCreditCardPaymentStrategy:()=>Ou,createCyberSourcePaymentStrategy:()=>Uu,createCyberSourceV2PaymentStrategy:()=>Wu,createGooglePayAdyenV2PaymentStrategy:()=>Qu,createGooglePayAdyenV3PaymentStrategy:()=>th,createGooglePayAuthorizeNetPaymentStrategy:()=>nh,createGooglePayBigCommercePaymentsPaymentStrategy:()=>fh,createGooglePayBraintreePaymentStrategy:()=>dh,createGooglePayCheckoutComPaymentStrategy:()=>ih,createGooglePayCybersourcePaymentStrategy:()=>rh,createGooglePayOrbitalPaymentStrategy:()=>oh,createGooglePayPPCPPaymentStrategy:()=>ph,createGooglePayStripePaymentStrategy:()=>ah,createGooglePayTdOnlineMartPaymentStrategy:()=>Sh,createGooglePayWorldpayAccessPaymentStrategy:()=>sh,createHummPaymentStrategy:()=>Ih,createKlarnaPaymentStrategy:()=>Ah,createKlarnaV2PaymentStrategy:()=>zh,createLegacyPaymentStrategy:()=>xh,createMolliePaymentStrategy:()=>Uh,createMonerisPaymentStrategy:()=>Hh,createNoPaymentStrategy:()=>Pd,createOfflinePaymentStrategy:()=>$h,createOffsitePaymentStrategy:()=>Jh,createPayPalCommerceAlternativeMethodsPaymentStrategy:()=>lp,createPayPalCommerceCreditCardsPaymentStrategy:()=>pp,createPayPalCommerceCreditPaymentStrategy:()=>ip,createPayPalCommerceFastlanePaymentStrategy:()=>_p,createPayPalCommercePaymentStrategy:()=>ep,createPayPalCommerceRatePayPaymentStrategy:()=>gp,createPayPalCommerceVenmoPaymentStrategy:()=>ap,createPayPalProPaymentStrategy:()=>zp,createPaypalExpressPaymentStrategy:()=>kp,createSagePayPaymentStrategy:()=>xp,createSezzlePaymentStrategy:()=>Lp,createSquareV2PaymentStrategy:()=>Wp,createStripeCSPaymentStrategy:()=>ym,createStripeOCSPaymentStrategy:()=>hm,createStripeUPEPaymentStrategy:()=>dm,createStripeV3PaymentStrategy:()=>im,createTDOnlineMartPaymentStrategy:()=>_m,createWorldpayAccessOpenBankingPaymentStrategy:()=>Em,createWorldpayAccessPaymentStrategy:()=>Pm,createZipPaymentStrategy:()=>km});var We={};Ve.r(We),Ve.d(We,{createAmazonPayV2ButtonStrategy:()=>w_,createApplePayButtonStrategy:()=>O_,createBigCommercePaymentsButtonStrategy:()=>T_,createBigCommercePaymentsPayLaterButtonStrategy:()=>M_,createBigCommercePaymentsVenmoButtonStrategy:()=>x_,createBoltButtonStrategy:()=>F_,createBraintreePaypalButtonStrategy:()=>q_,createBraintreePaypalCreditButtonStrategy:()=>H_,createBraintreeVenmoButtonStrategy:()=>ew,createBraintreeVisaCheckoutButtonStrategy:()=>Y_,createGooglePayAdyenV2ButtonStrategy:()=>aw,createGooglePayAdyenV3ButtonStrategy:()=>sw,createGooglePayAuthorizeDotNetButtonStrategy:()=>dw,createGooglePayBigCommercePaymentsButtonStrategy:()=>ow,createGooglePayBraintreeButtonStrategy:()=>iw,createGooglePayCheckoutComButtonStrategy:()=>cw,createGooglePayCybersourceButtonStrategy:()=>lw,createGooglePayOrbitalButtonStrategy:()=>uw,createGooglePayPayPalCommerceButtonStrategy:()=>rw,createGooglePayStripeButtonStrategy:()=>hw,createGooglePayTdOnlineMartButtonStrategy:()=>mw,createGooglePayWorldpayAccessButtonStrategy:()=>pw,createLinkV2ButtonStrategy:()=>Aw,createPayPalCommerceButtonStrategy:()=>gw,createPayPalCommerceCreditButtonStrategy:()=>Sw,createPayPalCommerceVenmoButtonStrategy:()=>Iw,createPaypalExpressButtonStrategy:()=>Pw});const $e="b2bExtraField_";function Ye(e){return e.name.startsWith($e)}function Ke(e){var t;const{fieldType:n,type:i}=function(e){switch(e){case"multiline_text":return{fieldType:"multiline",type:"string"};case"number":return{fieldType:"text",type:"integer"};case"dropdown":return{fieldType:"dropdown",type:"array"};default:return{fieldType:"text",type:"string"}}}(e.type);let r;return e.config.numberOfRows&&(r={rows:e.config.numberOfRows}),(null===(t=e.config.options)||void 0===t?void 0:t.length)&&(r=Object.assign(Object.assign({},r),{items:e.config.options.map(e=>({value:e,label:e}))})),{id:`${$e}${e.id}`,name:`${$e}${e.id}`,custom:!1,label:e.name,hidden:!e.visibleToStorefront,required:e.isRequired,default:null!=e.config.defaultValue?String(e.config.defaultValue):void 0,fieldType:n,type:i,maxLength:e.config.maxLength,max:e.config.maxValue,options:r}}function Je(e,t,n){return(i=t)&&i.type&&i.error?g(C(t),b(h(e,t.payload,n))):b(h(e,t,n));var i}var Ze;!function(e){e.LoadB2BTokenRequested="LOAD_B2B_TOKEN_REQUESTED",e.LoadB2BTokenSucceeded="LOAD_B2B_TOKEN_SUCCEEDED",e.LoadB2BTokenFailed="LOAD_B2B_TOKEN_FAILED"}(Ze||(Ze={}));class Qe{constructor(e){this._requestSender=e}loadB2BToken(e){return t=>{var n;const i=t.getState(),r=i.config.getStoreConfigOrThrow(),{storeHash:o}=r.storeProfile,{baseUrl:a="",clientId:s=""}=null!==(n=r.b2bApiSettings)&&void 0!==n?n:{},{id:d}=i.customer.getCustomerOrThrow(),{channelId:c}=i.checkout.getCheckoutOrThrow();return g(C(l(Ze.LoadB2BTokenRequested)),v(()=>{return t=this,n=void 0,r=function*(){const{body:t}=yield this._requestSender.getB2BToken(s,d,o,c,a,e);return l(Ze.LoadB2BTokenSucceeded,{token:t.data.token})},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r})).pipe(P(e=>Je(Ze.LoadB2BTokenFailed,e)))}}}const Xe={"X-Checkout-SDK-Version":"1.909.5"};var et,tt;class nt{constructor(e){this._requestSender=e}getB2BToken(e,t,n,i,r,o){return a=this,s=void 0,c=function*(){const{body:a}=yield this._requestSender.get("/customer/current.jwt",{timeout:null==o?void 0:o.timeout,params:{app_client_id:e},headers:Xe});return this._requestSender.post(`${r}/api/v2/login`,{timeout:null==o?void 0:o.timeout,credentials:!1,headers:{"Content-Type":"application/json"},body:{bcToken:a.token,customerId:t,storeHash:n,channelId:i}})},new((d=void 0)||(d=Promise))(function(e,t){function n(e){try{r(c.next(e))}catch(e){t(e)}}function i(e){try{r(c.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof d?r:new d(function(e){e(r)})).then(n,i)}r((c=c.apply(a,s||[])).next())});var a,s,d,c}}class it extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}!function(e){e[e.MissingBillingAddress=0]="MissingBillingAddress",e[e.MissingCart=1]="MissingCart",e[e.MissingCheckout=2]="MissingCheckout",e[e.MissingConsignments=3]="MissingConsignments",e[e.MissingCustomer=4]="MissingCustomer",e[e.MissingCheckoutConfig=5]="MissingCheckoutConfig",e[e.MissingOrder=6]="MissingOrder",e[e.MissingOrderConfig=7]="MissingOrderConfig",e[e.MissingOrderId=8]="MissingOrderId",e[e.MissingPayment=9]="MissingPayment",e[e.MissingPaymentId=10]="MissingPaymentId",e[e.MissingPaymentInstrument=11]="MissingPaymentInstrument",e[e.MissingPaymentMethod=12]="MissingPaymentMethod",e[e.MissingPaymentProviderCustomer=13]="MissingPaymentProviderCustomer",e[e.MissingPaymentRedirectUrl=14]="MissingPaymentRedirectUrl",e[e.MissingPaymentStatus=15]="MissingPaymentStatus",e[e.MissingPaymentToken=16]="MissingPaymentToken",e[e.MissingShippingAddress=17]="MissingShippingAddress"}(et||(et={}));class rt extends it{constructor(e){super(function(e){switch(e){case et.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case et.MissingCart:return"Unable to proceed because cart data is unavailable.";case et.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case et.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case et.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case et.MissingCheckoutConfig:case et.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case et.MissingOrder:return"Unable to proceed because order data is unavailable.";case et.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case et.MissingPayment:return"Unable to proceed because payment data is unavailable.";case et.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case et.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case et.MissingPaymentProviderCustomer:return"Unable to proceed because payment provider customer is unavailable.";case et.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e)),this.subtype=e,this.name="MissingDataError",this.type="missing_data"}}!function(e){e.UpdateBillingAddressRequested="UPDATE_BILLING_ADDRESS_REQUESTED",e.UpdateBillingAddressSucceeded="UPDATE_BILLING_ADDRESS_SUCCEEDED",e.UpdateBillingAddressFailed="UPDATE_BILLING_ADDRESS_FAILED",e.ContinueAsGuestRequested="CONTINUE_AS_GUEST_REQUESTED",e.ContinueAsGuestSucceeded="CONTINUE_AS_GUEST_SUCCEEDED",e.ContinueAsGuestFailed="CONTINUE_AS_GUEST_FAILED"}(tt||(tt={}));class ot extends it{constructor(e){super(e||"Unable to continue as a guest because the customer is already signed in."),this.name="UnableToContinueAsGuestError",this.type="unable_to_continue_as_guest"}}var at;class st{constructor(e,t){this._requestSender=e,this._subscriptionActionCreator=t}continueAsGuest(e,t){return n=>{const i=n.getState(),r=i.checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);const o=i.customer.getCustomer();if(o&&!o.isGuest)throw new ot;const a=i.billingAddress.getBillingAddress();let s;if(a){const{country:t}=a,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{return e=this,n=void 0,o=function*(){const{body:e}=yield this._createOrUpdateBillingAddress(r.id,s,d,t);return l(tt.ContinueAsGuestSucceeded,e)},new((i=void 0)||(i=Promise))(function(t,r){function a(e){try{d(o.next(e))}catch(e){r(e)}}function s(e){try{d(o.throw(e))}catch(e){r(e)}}function d(e){var n;e.done?t(e.value):(n=e.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((o=o.apply(e,n||[])).next())});var e,n,i,o})).pipe(P(e=>Je(tt.ContinueAsGuestFailed,e))),this._updateCustomerConsent(e,t))}}updateAddress(e,t){return n=>m.create(i=>{const r=n.getState(),o=r.checkout.getCheckout();if(!o)throw new rt(et.MissingCheckout);i.next(l(tt.UpdateBillingAddressRequested));const a=r.billingAddress.getBillingAddress(),s=!$(a),d=Object.assign(Object.assign({},e),{email:void 0===e.email&&a?a.email:e.email});a&&a.id&&(d.id=a.id),this._createOrUpdateBillingAddress(o.id,d,s,t).then(({body:e})=>{i.next(l(tt.UpdateBillingAddressSucceeded,e)),i.complete()}).catch(e=>{i.error(h(tt.UpdateBillingAddressFailed,e))})})}_updateCustomerConsent({email:e,acceptsAbandonedCartEmails:t,acceptsMarketingNewsletter:n},i){return null==t&&null==n?f():this._subscriptionActionCreator.updateSubscriptions({email:e,acceptsMarketingNewsletter:n||!1,acceptsAbandonedCartEmails:t||!1},i)}_createOrUpdateBillingAddress(e,t,n,i){return n?this._requestSender.updateAddress(e,t,i):this._requestSender.createAddress(e,t,i)}}class dt extends it{constructor(e){super(e||"Your checkout could not be processed because your cart is empty. Please add items to your cart and try again."),this.name="EmptyCartError",this.type="empty_cart"}}!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(at||(at={}));const ct=at;const lt={include:["cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","promotions.banners"].join(",")};class ut{constructor(e){this._requestSender=e}createAddress(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/billing-address`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{body:t,params:lt,headers:r,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}updateAddress(e,t,{timeout:n}={}){const{id:i}=t,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if("empty_cart"===e.body.type)throw new dt;throw e})}}var ht,pt;function mt(e,t){const n=u((e,t)=>t.type===ht.Synchronize?t.payload:e,e.getState(),{stateTransformer:t});return e.subscribe(e=>{n.dispatch(l(ht.Synchronize,e))},{initial:!1}),n}!function(e){e.Synchronize="SYNCHRONIZE"}(ht||(ht={})),function(e){e.ClearError="CLEAR_ERROR"}(pt||(pt={}));class yt{clearError(e){return{type:pt.ClearError,payload:e}}}class gt{constructor(e,t){this._requestSender=e,this._config=t}sendRequest(e,t){return this._requestSender.sendRequest(e,t)}get(e,t){return this._requestSender.get(e,t)}post(e,t){return this._requestSender.post(this._prefixed(e),t)}put(e,t){return this._requestSender.put(this._prefixed(e),t)}patch(e,t){return this._requestSender.patch(this._prefixed(e),t)}delete(e,t){return this._requestSender.delete(this._prefixed(e),t)}_prefixed(e){const t=this._config.getBasePath();return!this._config.getFeatures()["CHECKOUT-9950.update_sf_checkout_url_for_subfolder"]||!t||t.endsWith("/checkout")||/^https?:\/\//.test(e)?e:`${t}${e}`}}function vt(){try{return"production"}catch(e){return"development"}}class ft{constructor(e){this._console=e}log(...e){this._logToConsole("log",...e)}info(...e){this._logToConsole("info",...e)}warn(...e){this._logToConsole("warn",...e)}error(...e){this._logToConsole("error",...e)}debug(...e){this._logToConsole("debug",...e)}_logToConsole(e,...t){this._console&&this._console[e]&&this._console[e].call(this._console,...t)}}class St{log(){}info(){}warn(){}error(){}debug(){}}const _t=function(e=!0){return e?new ft(console):new St}("test"!==vt());function wt(){return _t}function It(e,t,n){const i=new WeakMap;function r(e){return(...n)=>{const r=n[n.length-1],{useCache:o}=(a=r)&&"boolean"==typeof a.useCache?r:{useCache:!1};var a;if(!o)return e.call(this,...n);const s=i.get(this)||{};var d;return i.get(this)||i.set(this,s),s[t]||(s[t]=(d=e,Pe(function(...e){const t=d.call(this,...e);return t instanceof m?S(t).pipe(D()):"function"==typeof t?Pe(e=>S(t(e)).pipe(D()),{isEqual:Y}):t},{isEqual:Y}))),s[t].call(this,...n)}}return{get(){if("function"!=typeof n.value)throw new Error("Decorator should be used in functions");const e=r.call(this,n.value);return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e}}}var Ct;!function(e){e.LoadConfigRequested="LOAD_CONFIG_REQUESTED",e.LoadConfigSucceeded="LOAD_CONFIG_SUCCEEDED",e.LoadConfigFailed="LOAD_CONFIG_FAILED"}(Ct||(Ct={}));class bt{constructor(e){this._configRequestSender=e}loadConfig(e){return m.create(t=>{t.next(l(Ct.LoadConfigRequested)),this._configRequestSender.loadConfig(e).then(e=>{t.next(l(Ct.LoadConfigSucceeded,e.body)),t.complete()}).catch(e=>{t.error(h(Ct.LoadConfigFailed,e))})})}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([It],bt.prototype,"loadConfig",null);const Pt={body:{},headers:{},status:0};class Ot extends it{constructor(e,{message:t,errors:n}={}){const{body:i,headers:r,status:o}=e||Pt;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=i,this.headers=r,this.status=o,this.errors=n||[]}}class Et extends Ot{constructor(e){super(e,{message:e.body.title}),this.name="CheckoutNotAvailableError",this.type="checkout_not_available"}}const At="This API endpoint is for internal use only and may change in the future";class Tt{constructor(e){this._requestSender=e}loadConfig({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/checkout-settings",{timeout:e,headers:Object.assign({Accept:ct.JsonV1,"X-API-INTERNAL":At},Xe),params:t}).catch(e=>{if(e.status>=400&&e.status<500)throw new Et(e);throw e})}}var kt;!function(e){e.ApplyCouponRequested="APPLY_COUPON_REQUESTED",e.ApplyCouponSucceeded="APPLY_COUPON_SUCCEEDED",e.ApplyCouponFailed="APPLY_COUPON_FAILED",e.RemoveCouponRequested="REMOVE_COUPON_REQUESTED",e.RemoveCouponSucceeded="REMOVE_COUPON_SUCCEEDED",e.RemoveCouponFailed="REMOVE_COUPON_FAILED"}(kt||(kt={}));class Dt{constructor(e){this._couponRequestSender=e}applyCoupon(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l(kt.ApplyCouponRequested)),this._couponRequestSender.applyCoupon(r.id,e,t).then(({body:e})=>{i.next(l(kt.ApplyCouponSucceeded,e)),i.complete()}).catch(e=>{i.error(h(kt.ApplyCouponFailed,e))})})}removeCoupon(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l(kt.RemoveCouponRequested)),this._couponRequestSender.removeCoupon(r.id,e,t).then(({body:e})=>{i.next(l(kt.RemoveCouponSucceeded,e)),i.complete()}).catch(e=>{i.error(h(kt.RemoveCouponFailed,e))})})}}const Mt=["cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","customer.customerGroup","payments","promotions.banners"];var zt,Nt,xt,Rt;function Ft(e){return we(e).join(",")}!function(e){e.AvailableShippingOptions="consignments.availableShippingOptions",e.PhysicalItemsCategoryNames="cart.lineItems.physicalItems.categoryNames",e.DigitalItemsCategoryNames="cart.lineItems.digitalItems.categoryNames"}(zt||(zt={}));class Lt{constructor(e){this._requestSender=e}applyCoupon(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/coupons`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{headers:r,timeout:n,params:{include:Ft([...Mt,zt.AvailableShippingOptions])},body:{couponCode:t}}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}removeCoupon(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/coupons/${t}`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.delete(i,{headers:r,timeout:n,params:{include:Ft([...Mt,zt.AvailableShippingOptions])}}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}!function(e){e.ApplyGiftCertificateRequested="APPLY_GIFT_CERTIFICATE_REQUESTED",e.ApplyGiftCertificateSucceeded="APPLY_GIFT_CERTIFICATE_SUCCEEDED",e.ApplyGiftCertificateFailed="APPLY_GIFT_CERTIFICATE_FAILED",e.RemoveGiftCertificateRequested="REMOVE_GIFT_CERTIFICATE_REQUESTED",e.RemoveGiftCertificateSucceeded="REMOVE_GIFT_CERTIFICATE_SUCCEEDED",e.RemoveGiftCertificateFailed="REMOVE_GIFT_CERTIFICATE_FAILED"}(Nt||(Nt={}));class Bt{constructor(e){this._giftCertificateRequestSender=e}applyGiftCertificate(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l(Nt.ApplyGiftCertificateRequested)),this._giftCertificateRequestSender.applyGiftCertificate(r.id,e,t).then(({body:e})=>{i.next(l(Nt.ApplyGiftCertificateSucceeded,e)),i.complete()}).catch(e=>{i.error(h(Nt.ApplyGiftCertificateFailed,e))})})}removeGiftCertificate(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l(Nt.RemoveGiftCertificateRequested)),this._giftCertificateRequestSender.removeGiftCertificate(r.id,e,t).then(({body:e})=>{i.next(l(Nt.RemoveGiftCertificateSucceeded,e)),i.complete()}).catch(e=>{i.error(h(Nt.RemoveGiftCertificateFailed,e))})})}}class jt{constructor(e){this._requestSender=e}applyGiftCertificate(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/gift-certificates`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{headers:r,timeout:n,params:{include:Ft(Mt)},body:{giftCertificateCode:t}}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}removeGiftCertificate(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/gift-certificates/${t}`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.delete(i,{headers:r,timeout:n,params:{include:Ft(Mt)}}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}function Ut(e){return e&&"resolveIds"in e}class qt extends it{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class Vt{constructor(e){var t,n,i;this._factories={},this._instances={},this._defaultToken=null!==(t=null==e?void 0:e.defaultToken)&&void 0!==t?t:"default",this._useFallback=null===(n=null==e?void 0:e.useFallback)||void 0===n||n,this._tokenResolver=null!==(i=null==e?void 0:e.tokenResolver)&&void 0!==i?i:e=>e}get(e,t){try{return this._getInstance(e||this._defaultToken,t||e||this._defaultToken)}catch(e){if(!this._useFallback)throw e;return this._getInstance(this._defaultToken,t||this._defaultToken)}}getFactory(e,t){const n=this._tokenResolver(e,Object.keys(this._factories),t);return n?this._factories[n]:void 0}register(e,t){if(this._hasFactory(e))throw new qt(`'${e}' is already registered.`);this._factories[e]=t}_hasFactory(e){return!!this._factories[e]}_hasInstance(e){return!!this._instances[e]}_getInstance(e,t){if(!this._hasInstance(t)){const n=this.getFactory(e);if(!n)throw new qt(`'${e}' is not registered.`);this._instances[t]=n()}return this._instances[t]}}class Gt{constructor(e=!1){this._useFallback=e,this._registry=new Vt({tokenResolver:this._resolveToken.bind(this),defaultToken:this._encodeToken({default:!0}),useFallback:this._useFallback})}get(e){return this._registry.get(this._encodeToken(e))}getFactory(e,t){try{return this._registry.getFactory(this._encodeToken(e),t)}catch(e){return}}getUseFallback(){return this._useFallback}register(e,t){this._registry.register(this._encodeToken(e),t)}_encodeToken(e){return btoa(JSON.stringify(e))}_decodeToken(e){return JSON.parse(atob(e))}_resolveToken(e,t,n){var i;const r=this._decodeToken(e),o=[];t.forEach(e=>{const t=this._decodeToken(e),n={token:e,matches:0,default:!1,totalKeys:Object.keys(t).length};for(const[e,i]of Object.entries(t)){if(e in r&&r[e]!==i){n.matches=0;break}e in r&&r[e]===i&&n.matches++,"default"===e&&!0===i&&(n.default=!0)}o.push(n)});const a=o.sort((e,t)=>t.matches-e.matches).filter(e=>e.matches>0);a.length>1&&a[0].matches===a[1].matches&&"development"===vt()&&wt().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.");const s=Object.keys(r).length;if(n){const e=a.find(e=>e.matches===s&&e.matches===e.totalKeys);if(!e)throw new Error(`Unable to resolve to a registered token with the provided token for ${JSON.stringify(r)} with exact match.`);return e.token}const d=a[0];if(d&&d.token)return d.token;if(this._useFallback){const e=null===(i=o.find(e=>e.default))||void 0===i?void 0:i.token;if(e)return e}throw new Error(`Unable to resolve to a registered token with the provided token for ${JSON.stringify(r)}.`)}}function Ht(e){const t=e;return"object"==typeof t&&"object"==typeof t.payload&&"string"==typeof t.payload.token}!function(e){e.BuyNow="BUY_NOW"}(xt||(xt={})),function(e){e.SignInCustomerRequested="SIGN_IN_CUSTOMER_REQUESTED",e.SignInCustomerSucceeded="SIGN_IN_CUSTOMER_SUCCEEDED",e.SignInCustomerFailed="SIGN_IN_CUSTOMER_FAILED",e.SignOutCustomerRequested="SIGN_OUT_CUSTOMER_REQUESTED",e.SignOutCustomerSucceeded="SIGN_OUT_CUSTOMER_SUCCEEDED",e.SignOutCustomerFailed="SIGN_OUT_CUSTOMER_FAILED",e.CreateCustomerRequested="CREATE_CUSTOMER_REQUESTED",e.CreateCustomerSucceeded="CREATE_CUSTOMER_SUCCEEDED",e.CreateCustomerFailed="CREATE_CUSTOMER_FAILED",e.CreateCustomerAddressRequested="CREATE_CUSTOMER_ADDRESS_REQUESTED",e.CreateCustomerAddressSucceeded="CREATE_CUSTOMER_ADDRESS_SUCCEEDED",e.CreateCustomerAddressFailed="CREATE_CUSTOMER_ADDRESS_FAILED",e.StripeLinkAuthenticated="STRIPE_LINK_AUTHENTICATED"}(Rt||(Rt={}));var Wt,$t,Yt;class Kt{constructor(e,t,n){this._customerRequestSender=e,this._checkoutActionCreator=t,this._spamProtectionActionCreator=n}createCustomer(e,t){return n=>{const i=n.getState().config.getStoreConfigOrThrow(),{isStorefrontSpamProtectionEnabled:r}=i.checkoutSettings,o=i=>S(this._customerRequestSender.createAccount(Object.assign(Object.assign({},e),{token:i}),t)).pipe(M(()=>g(this._checkoutActionCreator.loadCurrentCheckout(t)(n),C(l(Rt.CreateCustomerSucceeded)))));return g(C(l(Rt.CreateCustomerRequested)),r?S(this._spamProtectionActionCreator.execute()(n)).pipe(M(e=>{var t;return Ht(e)?g(C(e),o(null===(t=e.payload)||void 0===t?void 0:t.token)):C(e)})):o()).pipe(P(e=>Je(Rt.CreateCustomerFailed,e)))}}createAddress(e,t){return g(C(l(Rt.CreateCustomerAddressRequested)),v(()=>{return n=this,i=void 0,o=function*(){const{body:n}=yield this._customerRequestSender.createAddress(e,t);return l(Rt.CreateCustomerAddressSucceeded,n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Je(Rt.CreateCustomerAddressFailed,e)))}signInCustomer(e,t){return n=>{const i=n.getState().checkout.getCheckoutOrThrow(),r=i.cart.source===xt.BuyNow?i.id:void 0;return g(C(l(Rt.SignInCustomerRequested)),S(this._customerRequestSender.signInCustomer(Object.assign(Object.assign({},e),{cartId:r}),t)).pipe(M(({body:e})=>e.data.persistentCartRetrievalInformation?g(this._checkoutActionCreator.loadCheckout(e.data.persistentCartRetrievalInformation.id,t)(n),C(l(Rt.SignInCustomerSucceeded,e.data))):g(this._checkoutActionCreator.loadCurrentCheckout(t)(n),C(l(Rt.SignInCustomerSucceeded,e.data)))))).pipe(P(e=>Je(Rt.SignInCustomerFailed,e)))}}signOutCustomer(e){return t=>{const n=t.getState().checkout.getCheckoutOrThrow(),i=n.cart.source===xt.BuyNow?n.id:void 0;return g(C(l(Rt.SignOutCustomerRequested)),S(this._customerRequestSender.signOutCustomer(e,i)).pipe(M(({body:n})=>g(this._checkoutActionCreator.loadCurrentCheckout(e)(t),C(l(Rt.SignOutCustomerSucceeded,n.data)))))).pipe(P(e=>Je(Rt.SignOutCustomerFailed,e)))}}}class Jt{constructor(e){this._requestSender=e}createAccount(e,{timeout:t}={}){return this._requestSender.post("/api/storefront/customer",{timeout:t,headers:Xe,body:e})}createAddress(e,{timeout:t}={}){return this._requestSender.post("/api/storefront/customer-address",{timeout:t,headers:Xe,body:e})}signInCustomer(e,{timeout:t}={}){return this._requestSender.post("/internalapi/v1/checkout/customer",{timeout:t,headers:Xe,body:e})}signOutCustomer({timeout:e}={},t){return this._requestSender.delete("/internalapi/v1/checkout/customer",Object.assign({timeout:e,headers:Xe},t&&{body:{cartId:t}}))}}function Zt(e,t,n){t.forEach(t=>{Ut(t)&&t.resolveIds.forEach(i=>{e.getFactory(i,!0)||e.register(i,()=>t(n))})})}!function(e){e.SignInFailed="CUSTOMER_STRATEGY_SIGN_IN_FAILED",e.SignInRequested="CUSTOMER_STRATEGY_SIGN_IN_REQUESTED",e.SignInSucceeded="CUSTOMER_STRATEGY_SIGN_IN_SUCCEEDED",e.SignOutFailed="CUSTOMER_STRATEGY_SIGN_OUT_FAILED",e.SignOutRequested="CUSTOMER_STRATEGY_SIGN_OUT_REQUESTED",e.SignOutSucceeded="CUSTOMER_STRATEGY_SIGN_OUT_SUCCEEDED",e.ExecutePaymentMethodCheckoutFailed="CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_FAILED",e.ExecutePaymentMethodCheckoutRequested="CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_REQUESTED",e.ExecutePaymentMethodCheckoutSucceeded="CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_SUCCEEDED",e.InitializeFailed="CUSTOMER_STRATEGY_INITIALIZE_FAILED",e.InitializeRequested="CUSTOMER_STRATEGY_INITIALIZE_REQUESTED",e.InitializeSucceeded="CUSTOMER_STRATEGY_INITIALIZE_SUCCEEDED",e.DeinitializeFailed="CUSTOMER_STRATEGY_DEINITIALIZE_FAILED",e.DeinitializeRequested="CUSTOMER_STRATEGY_DEINITIALIZE_REQUESTED",e.DeinitializeSucceeded="CUSTOMER_STRATEGY_DEINITIALIZE_SUCCEEDED",e.WidgetInteractionStarted="CUSTOMER_STRATEGY_WIDGET_INTERACTION_STARTED",e.WidgetInteractionFinished="CUSTOMER_STRATEGY_WIDGET_INTERACTION_FINISHED",e.WidgetInteractionFailed="CUSTOMER_STRATEGY_WIDGET_INTERACTION_FAILED"}(Wt||(Wt={}));class Qt{constructor(e,t,n){this._strategyRegistry=e,this._strategyRegistryV2=t,this._paymentIntegrationService=n}signIn(e,t){return m.create(n=>{const i=t&&t.methodId,r={methodId:i};n.next(l(Wt.SignInRequested,void 0,r)),this._getStrategy(i).signIn(e,t).then(()=>{n.next(l(Wt.SignInSucceeded,void 0,r)),n.complete()}).catch(e=>{n.error(h(Wt.SignInFailed,e,r))})})}signOut(e){return m.create(t=>{const n=e&&e.methodId,i={methodId:n};t.next(l(Wt.SignOutRequested,void 0,i)),this._getStrategy(n).signOut(e).then(()=>{t.next(l(Wt.SignOutSucceeded,void 0,i)),t.complete()}).catch(e=>{t.error(h(Wt.SignOutFailed,e,i))})})}executePaymentMethodCheckout(e){return m.create(t=>{const n=e&&e.methodId,i={methodId:n};t.next(l(Wt.ExecutePaymentMethodCheckoutRequested,void 0,i)),this._getStrategy(n).executePaymentMethodCheckout(e).then(()=>{t.next(l(Wt.ExecutePaymentMethodCheckoutSucceeded,void 0,i)),t.complete()}).catch(e=>{t.error(h(Wt.ExecutePaymentMethodCheckoutFailed,e,i))})})}initialize(e){return t=>m.create(n=>{var i;const r=t.getState(),o=e&&e.methodId,a={methodId:o};if(Zt(this._strategyRegistryV2,null!==(i=null==e?void 0:e.integrations)&&void 0!==i?i:[],this._paymentIntegrationService),o&&r.customerStrategies.isInitialized(o))return n.complete();n.next(l(Wt.InitializeRequested,void 0,a)),this._getStrategy(o).initialize(e).then(()=>{n.next(l(Wt.InitializeSucceeded,void 0,a)),n.complete()}).catch(e=>{n.error(h(Wt.InitializeFailed,e,a))})})}deinitialize(e){return t=>m.create(n=>{const i=t.getState(),r=e&&e.methodId,o={methodId:r};if(r&&!i.customerStrategies.isInitialized(r))return n.complete();n.next(l(Wt.DeinitializeRequested,void 0,o)),this._getStrategy(r).deinitialize(e).then(()=>{n.next(l(Wt.DeinitializeSucceeded,void 0,o)),n.complete()}).catch(e=>{n.error(h(Wt.DeinitializeFailed,e,o))})})}widgetInteraction(e,t){return m.create(n=>{const i={methodId:t&&t.methodId};n.next(l(Wt.WidgetInteractionStarted,void 0,i)),e().then(()=>{n.next(l(Wt.WidgetInteractionFinished,void 0,i)),n.complete()}).catch(e=>{n.error(h(Wt.WidgetInteractionFailed,e,i))})})}_getStrategy(e){let t;try{t=this._strategyRegistryV2.get({id:e||""})}catch(n){t=this._strategyRegistry.get(e)}return t}}function Xt(e,t=[]){return Array.isArray(t)?Ft([...e,...t]):function(e,t){const n=ie(me(t,e=>!e)),i=ie(L(t));return Ft([...R(e,n),...i])}(e,t)}class en{constructor(e){this._requestSender=e}loadCheckout(e,{params:{include:t}={},timeout:n}={}){const i=`/api/storefront/checkout/${e}`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.get(i,{params:{include:Xt(Mt,t)},headers:r,timeout:n}).catch(e=>{if(e.status>=400&&e.status<500)throw new Et(e);throw e})}updateCheckout(e,t,{params:{include:n}={},timeout:i}={}){const r=`/api/storefront/checkout/${e}`,o=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.put(r,{params:{include:Xt(Mt,n)},body:t,headers:o,timeout:i}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}!function(e){e.LoadCheckoutRequested="LOAD_CHECKOUT_REQUESTED",e.LoadCheckoutSucceeded="LOAD_CHECKOUT_SUCCEEDED",e.LoadCheckoutFailed="LOAD_CHECKOUT_FAILED",e.UpdateCheckoutRequested="UPDATE_CHECKOUT_REQUESTED",e.UpdateCheckoutSucceeded="UPDATE_CHECKOUT_SUCCEEDED",e.UpdateCheckoutFailed="UPDATE_CHECKOUT_FAILED"}($t||($t={})),function(e){e.HydrateInitialState="HYDRATE_INITIAL_STATE"}(Yt||(Yt={}));var tn;class nn{constructor(e,t,n){this._checkoutRequestSender=e,this._configActionCreator=t,this._formFieldsActionCreator=n}loadCheckout(e,t){return()=>g(C(l($t.LoadCheckoutRequested)),w(this._configActionCreator.loadConfig({useCache:!0,timeout:null==t?void 0:t.timeout,params:{checkoutId:e}}),this._formFieldsActionCreator.loadFormFields({useCache:!0,timeout:null==t?void 0:t.timeout})),v(()=>this._checkoutRequestSender.loadCheckout(e,t).then(({body:e})=>l($t.LoadCheckoutSucceeded,this._transformCustomerAddresses(e))))).pipe(P(e=>Je($t.LoadCheckoutFailed,e)))}loadDefaultCheckout(e){return t=>g(C(l($t.LoadCheckoutRequested)),w(this._configActionCreator.loadConfig({useCache:!0,timeout:null==e?void 0:e.timeout}),this._formFieldsActionCreator.loadFormFields({useCache:!0,timeout:null==e?void 0:e.timeout})),v(()=>{return n=this,i=void 0,o=function*(){const n=t.getState().config.getContextConfig();if(!n||!n.checkoutId)throw new rt(et.MissingCheckoutConfig);const{body:i}=yield this._checkoutRequestSender.loadCheckout(n.checkoutId,e);return l($t.LoadCheckoutSucceeded,this._transformCustomerAddresses(i))},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Je($t.LoadCheckoutFailed,e)))}updateCheckout(e,t){return n=>new m(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l($t.UpdateCheckoutRequested)),this._checkoutRequestSender.updateCheckout(r.id,e,t).then(({body:e})=>{i.next(l($t.UpdateCheckoutSucceeded,e)),i.complete()}).catch(e=>{i.error(h($t.UpdateCheckoutFailed,e))})})}loadCurrentCheckout(e){return t=>{const n=t.getState().checkout.getCheckout();if(!n)throw new rt(et.MissingCheckout);return this.loadCheckout(n.id,e)(t)}}hydrateInitialState(e){return{type:Yt.HydrateInitialState,payload:e}}_transformCustomerAddresses(e){return Object.assign(Object.assign({},e),{customer:Object.assign(Object.assign({},e.customer),{addresses:e.customer.addresses.map(e=>Object.assign(Object.assign({},e),{shouldSaveAddress:!1}))})})}}!function(e){e.LoadFormFieldsRequested="LOAD_FORM_FIELDS_REQUESTED",e.LoadFormFieldsSucceeded="LOAD_FORM_FIELDS_SUCCEEDED",e.LoadFormFieldsFailed="LOAD_FORM_FIELDS_FAILED"}(tn||(tn={}));var rn;class on{constructor(e){this._formFieldsRequestSender=e}loadFormFields(e){return g(C(l(tn.LoadFormFieldsRequested)),v(()=>{return t=this,n=void 0,r=function*(){const{body:t}=yield this._formFieldsRequestSender.loadFields(e);return l(tn.LoadFormFieldsSucceeded,t)},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r})).pipe(P(e=>Je(tn.LoadFormFieldsFailed,e)))}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([It],on.prototype,"loadFormFields",null);class an{constructor(e){this._requestSender=e}loadFields({timeout:e}={}){return this._requestSender.get("/api/storefront/form-fields",{timeout:e,headers:Object.assign({Accept:ct.JsonV1,"X-API-INTERNAL":At},Xe)})}}class sn extends it{constructor(){super("You haven't complete our spam protection challenge. Please try again."),this.name="SpamProtectionChallengeNotCompletedError",this.type="spam_protection_challenge_not_completed"}}class dn extends it{constructor(){super("We were not able to complete your spam protection verification. Please try again."),this.name="SpamProtectionFailedError",this.type="spam_protection_failed"}}!function(e){e.InitializeFailed="SPAM_PROTECTION_INITIALIZE_FAILED",e.InitializeSucceeded="SPAM_PROTECTION_INITIALIZE_SUCCEEDED",e.InitializeRequested="SPAM_PROTECTION_INITIALIZE_REQUESTED",e.VerifyCheckoutRequested="SPAM_PROTECTION_CHECKOUT_VERIFY_REQUESTED",e.VerifyCheckoutSucceeded="SPAM_PROTECTION_CHECKOUT_VERIFY_SUCCEEDED",e.VerifyCheckoutFailed="SPAM_PROTECTION_CHECKOUT_VERIFY_FAILED",e.ExecuteRequested="SPAM_PROTECTION_EXECUTE_REQUESTED",e.ExecuteSucceeded="SPAM_PROTECTION_EXECUTE_SUCCEEDED",e.ExecuteFailed="SPAM_PROTECTION_EXECUTE_FAILED"}(rn||(rn={}));var cn,ln,un,hn=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pn{constructor(e,t){this._googleRecaptcha=e,this._requestSender=t}initialize(e){return t=>g(C(l(rn.InitializeRequested,void 0)),v(()=>hn(this,void 0,void 0,function*(){const n=e?e.containerId:"spamProtectionContainer";if(document.getElementById(n)&&this._googleRecaptcha.reset(n),!e&&!document.getElementById(n)){const e=document.createElement("div");e.setAttribute("id",n),document.body.appendChild(e)}const i=t.getState().config.getStoreConfigOrThrow().checkoutSettings.googleRecaptchaSitekey;return yield this._googleRecaptcha.load(n,i),l(rn.InitializeSucceeded)}))).pipe(P(e=>Je(rn.InitializeFailed,e)))}verifyCheckoutSpamProtection(){return e=>v(()=>{const t=e.getState().checkout.getCheckout();if(!t)throw new rt(et.MissingCheckout);return g(C(l(rn.VerifyCheckoutRequested)),S(this.execute()(e)).pipe(M(e=>Ht(e)&&e.payload?S(this._requestSender.validate(t.id,e.payload.token)).pipe(M(({body:t})=>g(C(e),C(l(rn.VerifyCheckoutSucceeded,t))))):C(e)))).pipe(P(e=>Je(rn.VerifyCheckoutFailed,e)))})}execute(){return e=>g(C(l(rn.ExecuteRequested)),this.initialize()(e),this._googleRecaptcha.execute().pipe(z(1)).pipe(M(({error:e,token:t})=>hn(this,void 0,void 0,function*(){if(e instanceof sn)throw e;if(e||!t)throw new dn;return l(rn.ExecuteSucceeded,{token:t})})))).pipe(P(e=>Je(rn.ExecuteFailed,e)))}}class mn{constructor(e=window){this._window=e}create(e){return new this._window.MutationObserver(e)}}!function(e){e[e.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",e[e.CustomerNotInitialized=1]="CustomerNotInitialized",e[e.PaymentNotInitialized=2]="PaymentNotInitialized",e[e.ShippingNotInitialized=3]="ShippingNotInitialized",e[e.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(cn||(cn={}));class yn extends it{constructor(e){super(function(e){switch(e){case cn.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case cn.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case cn.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case cn.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.subtype=e,this.name="NotInitializedError",this.type="not_initialized"}}class gn extends it{constructor(){super("Spam protection is not loaded. Please try again."),this.name="SpamProtectionNotLoadedError",this.type="spam_protection_failed"}}class vn{constructor(e,t){this.googleRecaptchaScriptLoader=e,this.mutationObserverFactory=t,this._memoized=Pe((e,t,n)=>{const i=new y;if(!n)throw new Error;return this._widgetId=e.render(n.id,{sitekey:t,size:"invisible",callback:()=>{i.next({token:e.getResponse(this._widgetId)}),e.reset(this._widgetId)},"error-callback":()=>{i.next({error:new dn})}}),i},{isEqual:(e,t)=>e===t})}load(e,t){return this.googleRecaptchaScriptLoader.load().then(n=>{n&&(this._event$=this._memoized(n,t,document.getElementById(e)),this._recaptcha=n)}).catch(e=>{throw e})}reset(e){var t;const n=document.getElementById(e);null==n||n.remove(),null===(t=this._recaptcha)||void 0===t||t.reset(this._widgetId)}execute(){return v(()=>{const e=this._event$,t=this._recaptcha;if(!e||!t)throw new yn(cn.SpamProtectionNotInitialized);return v(()=>{const e=document.querySelector('iframe[src*="bframe"]');return e?C(e):b(new gn)}).pipe(k(e=>e.pipe(O(250),M((e,t)=>t<28?C(e):b(e)))),M(n=>(this._watchRecaptchaChallengeWindow(e,n),t.execute(this._widgetId),e)),P(e=>C({error:e})))})}_watchRecaptchaChallengeWindow(e,t){const n=t.parentElement;if(!n)throw new gn;const i=n.parentElement;if(!i)throw new gn;this.mutationObserverFactory.create(()=>{"hidden"===i.style.visibility&&e.next({error:new sn})}).observe(i,{attributes:!0,attributeFilter:["style"]})}}class fn{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(){return this._loadPromise||(this._loadPromise=this._loadScript()),this._loadPromise}_loadScript(){const e="initRecaptcha",t=[`onload=${e}`,"render=explicit"].join("&");return new Promise((n,i)=>{this._window[e]=()=>n(this._window.grecaptcha),this._scriptLoader.loadScript(`//www.google.com/recaptcha/api.js?${t}`).catch(e=>{this._loadPromise=void 0,i(e)})})}}function Sn(e){return new vn(new fn(e),new mn)}class _n{constructor(e){this._requestSender=e}validate(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/spam-protection`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{body:{token:t},headers:r,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}class wn{constructor(e,t){this._store=e,this._customerActionCreator=t}signIn(e,t){return this._store.dispatch(this._customerActionCreator.signInCustomer(e,t))}signOut(e){return this._store.dispatch(this._customerActionCreator.signOutCustomer(e))}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())}initialize(){return Promise.resolve(this._store.getState())}deinitialize(){return Promise.resolve(this._store.getState())}}function In(e){if(!/^(https?:)?\/\//.test(e))throw new qt("The provided URL must be absolute.");const t=document.createElement("a");t.href=e;const n=t.port&&-1!==e.indexOf(`${t.hostname}:${t.port}`)?t.port:"";return{hash:t.hash,hostname:t.hostname,href:t.href,origin:`${t.protocol}//${t.hostname}${n?`:${n}`:""}`,pathname:t.pathname,port:n,protocol:t.protocol,search:t.search}}class Cn extends it{constructor(e){super(e||"Unable to proceed due to no extension configured for this region."),this.name="ExtensionNotFoundError",this.type="extension_not_found"}}function bn(e,t){return e.type===t}!function(e){e.LoadExtensionsRequested="LOAD_EXTENSIONS_REQUESTED",e.LoadExtensionsSucceeded="LOAD_EXTENSIONS_SUCCEEDED",e.LoadExtensionsFailed="LOAD_EXTENSIONS_FAILED",e.RenderExtensionRequested="RENDER_EXTENSION_REQUESTED",e.RenderExtensionSucceeded="RENDER_EXTENSION_SUCCEEDED",e.RenderExtensionFailed="RENDER_EXTENSION_FAILED"}(ln||(ln={}));class Pn{constructor(e,t,n){this._targetWindow=t,this._context=n,this._targetOrigin="*"===e?"*":In(e).origin}post(e,t){const n=this._targetWindow;if(window===n)return;if(!n)throw new Error("Unable to post message because target window is not set.");const i=t&&_(window,"message").pipe(A(e=>e.origin===this._targetOrigin&&bn(e.data,e.data.type)&&-1!==[t.successType,t.errorType].indexOf(e.data.type)),T(e=>{if(t.errorType===e.data.type)throw e.data;return e.data}),z(1)).toPromise();return n.postMessage(Object.assign(Object.assign({},e),{context:this._context}),this._targetOrigin),i}setTarget(e){this._targetWindow=e}setContext(e){this._context=e}}function On(e){var t;const n=null===(t=document.querySelector(`[data-extension-id="${e.id}"]`))||void 0===t?void 0:t.querySelector("iframe");if(!(null==n?void 0:n.contentWindow))throw new Cn(`Unable to post due to no extension rendered for ID: ${e.id}.`);return new Pn(e.url,n.contentWindow)}!function(e){e.ExtensionReady="EXTENSION:READY",e.ExtensionFailed="EXTENSION:FAILED"}(un||(un={}));class En{constructor(e){const t=new Promise((e,t)=>{this.cancel=t});this.promise=Promise.race([e,t])}}class An extends it{constructor(e){super(e||"Unable to proceed because the required element is unexpectedly detached from the page."),this.name="UnexpectedDetachmentError",this.type="unexpected_detachment"}}var Tn;class kn{constructor(e){this._mutationObserver=e}ensurePresence(e,t){return n=this,i=void 0,o=function*(){const n=new En(t),i=this._mutationObserver.create(t=>{t.forEach(t=>{0!==Array.from(t.removedNodes).filter(t=>e.some(e=>t===e||t.contains(e))).length&&n.cancel(new An)})});i.observe(document.body,{childList:!0,subtree:!0});try{const e=yield n.promise;return i.disconnect(),e}catch(e){throw i.disconnect(),e}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}function Dn(e,t){const{iframeResizer:n}=Ve(785);return n(e,t)}class Mn extends it{constructor(e){super(e||"Unable to load an extension"),this.name="ExtensionNotLoadedError",this.type="extension_not_loaded"}}!function(e){e.Subscribe="EXTENSION_INTERNAL:SUBSCRIBE",e.Unsubscribe="EXTENSION_INTERNAL:UNSUBSCRIBE",e.ResizeIframe="EXTENSION_INTERNAL:RESIZE_IFRAME"}(Tn||(Tn={}));class zn{constructor(e){this._options=e}createFrame(e,t,n,i){const r=document.getElementById(t),{timeout:o=6e4}=this._options||{};if(!r)throw new Mn("Unable to embed the iframe because the container element could not be found.");const a=document.createElement("iframe");return a.src=e,a.style.border="none",a.style.display="none",a.style.width="100%",r.appendChild(a),this._toResizableFrame(a,o,n,i).catch(e=>{throw r.removeChild(a),e})}_toResizableFrame(e,t,n,i){return r=this,o=void 0,s=function*(){const r=new kn(new mn),o=new Promise((r,o)=>{const a=window.setTimeout(()=>{try{i()}catch(e){e instanceof Error&&console.error(`Extension rendering timed out after ${t}ms, and the callback function could not be executed. Error: ${e.message}`)}o(new Mn("Unable to load the extension because the content could not be loaded."))},t),s=t=>{if(t.origin===In(e.src).origin&&bn(t.data,Tn.ResizeIframe)){e.style.display="";const t=Dn({autoResize:!1,scrolling:!1,sizeWidth:!1,heightCalculationMethod:"bodyOffset",initCallback:n},e);d(),r(t[t.length-1])}},d=()=>{window.removeEventListener("message",s),window.clearTimeout(a)};window.addEventListener("message",s)});return r.ensurePresence([e],o)},new((a=void 0)||(a=Promise))(function(e,t){function n(e){try{d(s.next(e))}catch(e){t(e)}}function i(e){try{d(s.throw(e))}catch(e){t(e)}}function d(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a(function(e){e(r)})).then(n,i)}d((s=s.apply(r,o||[])).next())});var r,o,a,s}}class Nn{constructor(e,t,n){this._containerId=e,this._extension=t,this._config=n;const{cartId:i,parentOrigin:r}=this._config;this._url=new URL(this._extension.url),this._url.searchParams.set("extensionId",this._extension.id),this._url.searchParams.set("cartId",i),this._url.searchParams.set("parentOrigin",r)}attach(){var e,t,n,i,r;return t=this,n=void 0,r=function*(){if(null===(e=document.querySelector(`[data-extension-id="${this._extension.id}"]`))||void 0===e?void 0:e.querySelector("iframe"))return;const t=new zn,n=e=>{On(this._extension).post({type:e})};this._iframe=yield t.createFrame(this._url.toString(),this._containerId,()=>{n(un.ExtensionReady)},()=>{n(un.ExtensionFailed)});const i=document.getElementById(this._containerId);null==i||i.setAttribute("data-extension-id",this._extension.id)},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())})}detach(){this._iframe&&this._iframe.parentElement&&this._iframe.parentElement.removeChild(this._iframe)}}class xn{constructor(e){this._requestSender=e}loadExtensions(e){return()=>m.create(t=>{t.next(l(ln.LoadExtensionsRequested)),this._requestSender.loadExtensions(e).then(e=>{const n=e.body;t.next(l(ln.LoadExtensionsSucceeded,n)),t.complete()}).catch(e=>{t.error(h(ln.LoadExtensionsFailed,e))})})}renderExtension(e,t,n){return i=>m.create(r=>{return o=this,a=void 0,d=function*(){const o=i.getState(),{id:a}=o.cart.getCartOrThrow(),{links:{checkoutLink:s}}=o.config.getStoreConfigOrThrow(),d=o.extensions.getExtensionByRegion(t);try{if(!d)throw new Cn(`Unable to proceed due to no extension configured for the region: ${t}.`);if(r.next(l(ln.RenderExtensionRequested)),"worker"===d.type){const e=function(e){if(!window.Worker)throw new Error("Unable to load the extension's web worker: your browser does not support Web Workers.");try{const t=URL.createObjectURL(new Blob([`importScripts=((i)=>(...a)=>i(...a.map((u)=>''+new URL(u,"${e}"))))(importScripts);importScripts("${e}")`],{type:"text/javascript"}));return new Worker(t)}catch(e){throw new Error("Unable to load the extension's web worker")}}(d.url);n.add(d.id,e)}else{const t=new Nn(e,d,{cartId:a,parentOrigin:In(s).origin});yield t.attach()}r.next(l(ln.RenderExtensionSucceeded)),r.complete()}catch(e){r.error(h(ln.RenderExtensionFailed,e))}},new((s=void 0)||(s=Promise))(function(e,t){function n(e){try{r(d.next(e))}catch(e){t(e)}}function i(e){try{r(d.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof s?r:new s(function(e){e(r)})).then(n,i)}r((d=d.apply(o,a||[])).next())});var o,a,s,d})}}class Rn{constructor(e){this._requestSender=e}loadExtensions({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/checkout-extensions",{timeout:e,headers:Object.assign({Accept:ct.JsonV1},Xe),params:t})}}const Fn=function(e,t,n){return t&&n?Ln(0,t,n):function(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(n=>{const i=Object.getOwnPropertyDescriptor(e.prototype,n);i&&"constructor"!==n&&Object.defineProperty(t.prototype,n,Ln(e.prototype,n,i))}),t}(e)};function Ln(e,t,n){if("function"!=typeof n.value)return n;let i=n.value;return{get(){const e=i.bind(this);return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e},set(e){i=e}}}var Bn,jn;class Un{constructor(e){this._worker=e,this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,this._worker.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,this._worker.removeEventListener("message",this._handleMessage))}addListener(e,t){let n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)}removeListener(e,t){const n=this._listeners[e];if(!n)return;const i=n.indexOf(t);i>=0&&n.splice(i,1)}trigger(e,t){const n=this._listeners[e.type];n&&n.forEach(n=>t?n(e,t):n(e))}_handleMessage(e){const t=e.data,{context:n}=t,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([Fn],Un.prototype,"_handleMessage",null);class qn{constructor(e,t){this._worker=e,this._context=t}post(e){if(!this._worker)throw new Error("WorkerPoster: Worker is not initialized or creation failed. Cannot post message.");this._worker.postMessage(Object.assign(Object.assign({},e),{context:this._context}))}}class Vn extends it{constructor(e){super(e||"Unable to proceed due to unsupported extension command."),this.name="UnsupportedExtensionCommandError",this.type="unsupported_extension_command_error"}}class Gn extends it{constructor(e){super(e||"Unable to proceed due to unsupported extension query."),this.name="UnsupportedExtensionQueryError",this.type="unsupported_extension_query_error"}}!function(e){e.ReloadCheckout="EXTENSION:RELOAD_CHECKOUT",e.ShowLoadingIndicator="EXTENSION:SHOW_LOADING_INDICATOR",e.SetIframeStyle="EXTENSION:SET_IFRAME_STYLE",e.ReRenderShippingForm="EXTENSION:RE_RENDER_SHIPPING_FORM",e.ReRenderShippingStep="EXTENSION:RE_RENDER_SHIPPING_STEP"}(Bn||(Bn={})),function(e){e.GetConsignments="EXTENSION:GET_CONSIGNMENTS"}(jn||(jn={}));class Hn{constructor(e={},t={},n={}){this._workers=e,this._commandListeners=t,this._queryListeners=n}add(e,t){this._workers[e]=t}listenForCommand(e,t,n){const i=this._getWorkerById(e);this._commandListeners[e]||(this._commandListeners[e]=new Un(i));const r=this._commandListeners[e];r.listen();const o=this._validateCommand(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}listenForQuery(e,t,n){const i=this._getWorkerById(e);this._queryListeners[e]||(this._queryListeners[e]=new Un(i));const r=this._queryListeners[e];r.listen();const o=this._validateQuery(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}stopListen(e){this._commandListeners[e]&&this._commandListeners[e].stopListen(),this._queryListeners[e]&&this._queryListeners[e].stopListen()}post(e,t){if(!this._workers[e])throw new Error(`Worker with extensionId ${e} not found`);new qn(this._workers[e],e).post(t)}clearCacheById(e){delete this._workers[e]}_getWorkerById(e){const t=this._workers[e];if(!t)throw new Cn(`Worker with extensionId ${e} not found`);return t}_validateCommand(e){if(Object.values(Bn).includes(e))return e;throw new Vn}_validateQuery(e){if(Object.values(jn).includes(e))return e;throw new Gn}}function Wn(e){return In(0===e.hostname.indexOf("www")?e.href:e.href.replace(e.hostname,`www.${e.hostname}`))}var $n;class Yn{constructor(e){this._sourceOrigins=[In(e).origin,Wn(In(e)).origin],this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))}addListener(e,t){let n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)}removeListener(e,t){const n=this._listeners[e];if(!n)return;const i=n.indexOf(t);i>=0&&n.splice(i,1)}trigger(e,t){const n=this._listeners[e.type];n&&n.forEach(n=>t?n(e,t):n(e))}_handleMessage(e){if(-1===this._sourceOrigins.indexOf(e.origin)||!bn(e.data,e.data.type))return;const t=e.data,{context:n}=t,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([Fn],Yn.prototype,"_handleMessage",null);class Kn{constructor(e,t,n={},i={},r={}){this._store=e,this._workerExtensionMessenger=t,this._commandListeners=n,this._queryListeners=i,this._posters=r}clearCacheByRegion(e){const t=this._getExtensionByRegion(e);"worker"!==t.type?this.clearCacheById(t.id):this._workerExtensionMessenger.clearCacheById(t.id)}clearCacheById(e){const t=this._getExtensionById(e);"worker"!==t.type?(this._commandListeners[e]&&delete this._commandListeners[e],this._queryListeners[e]&&delete this._queryListeners[e],this._posters[e]&&delete this._posters[e]):this._workerExtensionMessenger.clearCacheById(t.id)}listenForCommand(e,t,n){const i=this._getExtensionById(e);if("worker"===i.type)return this._workerExtensionMessenger.listenForCommand(e,t,n);this._commandListeners[e]||(this._commandListeners[e]=new Yn(i.url));const r=this._commandListeners[e];r.listen();const o=this._validateCommand(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}listenForQuery(e,t,n){const i=this._getExtensionById(e);if("worker"===i.type)return this._workerExtensionMessenger.listenForQuery(e,t,n);this._queryListeners[e]||(this._queryListeners[e]=new Yn(i.url));const r=this._queryListeners[e];r.listen();const o=this._validateQuery(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}stopListen(e){"worker"!==this._getExtensionById(e).type?(this._commandListeners[e]&&this._commandListeners[e].stopListen(),this._queryListeners[e]&&this._queryListeners[e].stopListen()):this._workerExtensionMessenger.stopListen(e)}post(e,t){try{const n=this._getExtensionById(e);if("worker"===n.type)return void this._workerExtensionMessenger.post(e,t);this._posters[e]||(this._posters[e]=On(n)),this._posters[e].post(t)}catch(n){this.clearCacheById(e),console.log(`Unable to post event to extension(${e}) because extension iframe is not mounted.\nThe event that could not be delivered:`,t)}}_getExtensionById(e){var t;this._getExtensions();const n=null===(t=this._extensions)||void 0===t?void 0:t.find(t=>t.id===e);if(!n)throw new Cn(`Unable to proceed due to no extension found for ID: ${e}.`);return n}_getExtensionByRegion(e){var t;this._getExtensions();const n=null===(t=this._extensions)||void 0===t?void 0:t.find(t=>t.region===e);if(!n)throw new Cn(`Unable to proceed due to no extension found for region: ${e}.`);return n}_getExtensions(){if(this._extensions)return;const{extensions:{getExtensions:e}}=this._store.getState();if(this._extensions=e(),!this._extensions)throw new Cn("Extension configurations not found.")}_validateCommand(e){if(Object.values(Bn).includes(e))return e;throw new Vn}_validateQuery(e){if(Object.values(jn).includes(e))return e;throw new Gn}}class Jn{constructor(e,t,n){this._store=e,this._extensionMessenger=t,this._subscribers=n,this._subscribed={},this._unsubscribers={},this._listeners={}}listen(){var e;const{data:{getExtensions:t}}=this._store.getState();null===(e=t())||void 0===e||e.forEach(e=>{if(this._listeners[e.id])return;const t=new Yn(e.url);t.addListener(Tn.Subscribe,this._handleSubscribe.bind(this)),t.addListener(Tn.Unsubscribe,this._handleUnsubscribe.bind(this)),t.listen(),this._listeners[e.id]=t})}broadcast(e){var t;const{data:{getExtensions:n}}=this._store.getState();null===(t=n())||void 0===t||t.forEach(t=>{this._subscribed[t.id]&&this._extensionMessenger.post(t.id,e)})}_handleSubscribe({payload:{eventType:e,extensionId:t}}){this._subscribed[t]=!0,this._unsubscribers[e]||(this._unsubscribers[e]=this._subscribers[e](this._store,this))}_handleUnsubscribe({payload:{eventType:e,extensionId:t}}){var n,i;delete this._subscribed[t],Object.keys(this._subscribed).length||(null===(i=(n=this._unsubscribers)[e])||void 0===i||i.call(n),delete this._unsubscribers[e])}}!function(e){e.ConsignmentsChanged="EXTENSION:CONSIGNMENTS_CHANGED"}($n||($n={}));const Zn=(e,t)=>{var n;const{data:{getConsignments:i}}=e.getState();let r=null!==(n=i())&&void 0!==n?n:[];return e.subscribe(({data:{getConsignments:e}})=>{var n;const i=null!==(n=e())&&void 0!==n?n:[];i!==r&&(t.broadcast({type:$n.ConsignmentsChanged,payload:{consignments:i,previousConsignments:r}}),r=i)},({data:{getConsignments:e}})=>e())};class Qn extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}var Xn,ei;!function(e){e[e.MissingBillingAddress=0]="MissingBillingAddress",e[e.MissingCart=1]="MissingCart",e[e.MissingCheckout=2]="MissingCheckout",e[e.MissingConsignments=3]="MissingConsignments",e[e.MissingCustomer=4]="MissingCustomer",e[e.MissingCheckoutConfig=5]="MissingCheckoutConfig",e[e.MissingOrder=6]="MissingOrder",e[e.MissingOrderConfig=7]="MissingOrderConfig",e[e.MissingOrderId=8]="MissingOrderId",e[e.MissingPayment=9]="MissingPayment",e[e.MissingPaymentId=10]="MissingPaymentId",e[e.MissingPaymentInstrument=11]="MissingPaymentInstrument",e[e.MissingPaymentMethod=12]="MissingPaymentMethod",e[e.MissingPaymentRedirectUrl=13]="MissingPaymentRedirectUrl",e[e.MissingPaymentStatus=14]="MissingPaymentStatus",e[e.MissingPaymentToken=15]="MissingPaymentToken",e[e.MissingShippingAddress=16]="MissingShippingAddress"}(Xn||(Xn={}));class ti extends Qn{constructor(e){super(function(e){switch(e){case Xn.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case Xn.MissingCart:return"Unable to proceed because cart data is unavailable.";case Xn.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case Xn.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case Xn.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case Xn.MissingCheckoutConfig:case Xn.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case Xn.MissingOrder:return"Unable to proceed because order data is unavailable.";case Xn.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case Xn.MissingPayment:return"Unable to proceed because payment data is unavailable.";case Xn.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case Xn.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case Xn.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e)),this.subtype=e,this.name="MissingDataError",this.type="missing_data"}}function ni(e){return t=e.lineItems.physicalItems.filter(e=>!e.addedByPromotion),ye(t,(e,t)=>e+t.quantity,0);var t}function ii(e,t){if(null==e)throw t?t():new Error("An unexpected error has occurred.");return e}!function(e){e[e.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",e[e.CustomerNotInitialized=1]="CustomerNotInitialized",e[e.PaymentNotInitialized=2]="PaymentNotInitialized",e[e.ShippingNotInitialized=3]="ShippingNotInitialized",e[e.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(ei||(ei={}));class ri extends Qn{constructor(e){super(function(e){switch(e){case ei.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case ei.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case ei.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case ei.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.subtype=e,this.name="NotInitializedError",this.type="not_initialized"}}const oi={de:"eu",jp:"fe",uk:"eu",us:"na"};var ai,si,di,ci,li,ui;!function(e){e.en_US="en_US",e.en_GB="en_GB",e.de_DE="de_DE",e.fr_FR="fr_FR",e.it_IT="it_IT",e.es_ES="es_ES",e.ja_JP="ja_JP"}(ai||(ai={})),function(e){e.Home="Home",e.Product="Product",e.Cart="Cart",e.Checkout="Checkout",e.Other="Other"}(si||(si={})),function(e){e.USD="USD",e.EUR="EUR",e.GBP="GBP",e.JPY="JPY"}(di||(di={})),function(e){e.PayAndShip="PayAndShip",e.PayOnly="PayOnly"}(ci||(ci={})),function(e){e.Gold="Gold",e.LightGray="LightGray",e.DarkGray="DarkGray"}(li||(li={})),function(e){e.C0001="C0001"}(ui||(ui={}));var hi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pi{constructor(e){this.amazonPayV2ScriptLoader=e}initialize(e){return hi(this,void 0,void 0,function*(){this.amazonPayV2SDK=yield this.amazonPayV2ScriptLoader.load(e),this.buttonParentContainer=this.buttonParentContainer||this.createAmazonPayButtonParentContainer()})}deinitialize(){var e;return this.amazonPayV2Button=void 0,null===(e=this.buttonParentContainer)||void 0===e||e.remove(),this.buttonParentContainer=void 0,this.amazonPayV2SDK=void 0,Promise.resolve()}bindButton(e,t,n){this.getAmazonPayV2SDK().Pay.bindChangeAction(`#${e}`,{amazonCheckoutSessionId:t,changeAction:n})}createButton(e,t){this.amazonPayV2Button=this.getAmazonPayV2SDK().Pay.renderButton(`#${e}`,t)}prepareCheckout(e){const t=this.prepareRequestConfig(e);this.getAmazonPayV2Button().onClick(()=>{this.getAmazonPayV2Button().initCheckout(t)})}prepareCheckoutWithCreationRequestConfig(e){this.getAmazonPayV2Button().onClick(()=>hi(this,void 0,void 0,function*(){const t=yield e();if(t){const e=this.prepareRequestConfig(t.createCheckoutSessionConfig,t.estimatedOrderAmount,t.productType);this.getAmazonPayV2Button().initCheckout(e)}}))}signout(){return hi(this,void 0,void 0,function*(){return this.amazonPayV2SDK&&this.amazonPayV2SDK.Pay.signout(),Promise.resolve()})}renderAmazonPayButton({buttonColor:e,checkoutState:t,containerId:n,decoupleCheckoutInitiation:i=!1,methodId:r,options:o,placement:a,isButtonMicroTextDisabled:s=!1}){const d=document.querySelector(`#${n}`);if(!d)return;const{id:c}=d.appendChild(this.getButtonParentContainer());o&&s&&(o.design=ui.C0001);const l=null!=o?o:this.getAmazonPayV2ButtonOptions(t,r,a,i,e);return this.createButton(c,l),this.getButtonParentContainer()}updateBuyNowFlowFlag(e){this.isBuyNowFlow=Boolean(e)}isPh4Enabled(e,t){const n=!!e["PROJECT-3483.amazon_pay_ph4"],i=!!e["INT-6885.amazon_pay_ph4_us_only"];return n&&i?"US"===t:n}prepareRequestConfig(e,t,n){const{publicKeyId:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew ri(ei.PaymentNotInitialized))}getCheckoutState(e){return"object"==typeof(t=e)&&null!==t&&"cart"in t&&"checkout"in t&&"config"in t&&"paymentMethods"in t?{getCart:e.cart.getCart,getCheckout:e.checkout.getCheckout,getStoreConfigOrThrow:e.config.getStoreConfigOrThrow,getPaymentMethodOrThrow:t=>e.paymentMethods.getPaymentMethodOrThrow(t)}:e;var t}}class mi extends Qn{constructor(e){super(e||"Unable to proceed because the client library of a payment method is not loaded or ready to be used."),this.name="PaymentMethodClientUnavailableError",this.type="payment_method_client_unavailable"}}class yi{constructor(e,t=window){this.scriptLoader=e,this.windowWithAmazonPay=t}load(e){return t=this,n=void 0,r=function*(){const{initializationData:t}=e,n=(null==t?void 0:t.region)||"us",i=oi[n];if(yield this.scriptLoader.loadScript(`https://static-${i}.payments-amazon.com/checkout.js`),!this.windowWithAmazonPay.amazon)throw new mi;return this.windowWithAmazonPay.amazon},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}function gi(){return new pi(new yi(a()))}function vi(e,t){return Object.assign(e,{resolveIds:t})}class fi extends Qn{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class Si extends Qn{constructor(e){super(e||"Not implemented."),this.name="NotImplementedError",this.type="not_implemented"}}var _i=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class wi{constructor(e,t){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t}initialize(e){return _i(this,void 0,void 0,function*(){const{methodId:t,amazonpay:n}=e;if(!t||!(null==n?void 0:n.container))throw new fi('Unable to proceed because "methodId" or "containerId" argument is not provided.');let i;try{i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)}catch(e){yield this.paymentIntegrationService.loadPaymentMethod(t),i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)}yield this.amazonPayV2PaymentProcessor.initialize(i),this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:this.paymentIntegrationService.getState(),containerId:n.container,methodId:t,placement:si.Checkout})})}deinitialize(){return _i(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize()})}signIn(){throw new Si('In order to sign in via Amazon, the shopper must click on "Amazon Pay" button.')}signOut(e){return _i(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getPaymentId();t&&(yield this.amazonPayV2PaymentProcessor.signout(),yield this.paymentIntegrationService.remoteCheckoutSignOut(t.providerId,e))})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}}const Ii=vi(e=>new wi(e,gi()),[{id:"amazonpay"}]);function Ci(e,t,n=!0){var i;return null!==(i=e[t])&&void 0!==i?i:n}const bi="3.128.0",Pi="3.123.2",Oi="3.106.0";class Ei{constructor(e){this.paymentIntegrationService=e,this.braintreeWindow=window}getSDKVersion(){const e=this.paymentIntegrationService.getState().getStoreConfig(),t=(null==e?void 0:e.checkoutSettings.features)||{};return this.getPreloadedSDKVersion()||(Ci(t,"PAYPAL-5809.braintree_hosted_fields_fix_version")?bi:Ci(t,"PAYPAL-5636.update_braintree_sdk_version")?Pi:Oi)}getPreloadedSDKVersion(){const e=this.braintreeWindow.braintree;if(e){const t=B(Object.values(e),e=>!!e.VERSION);return null==t?void 0:t.VERSION}}}class Ai extends Qn{constructor(e){super(e||"Unsupported browser error"),this.name="UnsupportedBrowserError",this.type="unsupported_browser"}}var Ti,ki,Di,Mi,zi,Ni,xi;function Ri(e){return Boolean("object"==typeof e&&null!==e&&("type"in e||"message"in e||"code"in e))}!function(e){e.ESTIMATED="ESTIMATED",e.FINAL="FINAL",e.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(Ti||(Ti={})),function(e){e.Completed="COMPLETED",e.Pending="PENDING",e.Failed="FAILED"}(ki||(ki={})),function(e){e.TRUSTLY="trustly"}(Di||(Di={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="cancelled",e.UNRECOGNIZED="unrecognized"}(Mi||(Mi={})),function(e){e.Customer="CUSTOMER",e.Merchant="MERCHANT",e.Network="NETWORK",e.Internal="INTERNAL",e.Unknown="UNKNOWN"}(zi||(zi={})),function(e){e.KountNotEnabled="DATA_COLLECTOR_KOUNT_NOT_ENABLED"}(Ni||(Ni={})),function(e){e.Visa="visa",e.Mastercard="mastercard",e.AmericanExpress="american-express",e.DinersClub="diners-club",e.Discover="discover",e.Jcb="jcb",e.UnionPay="union-pay",e.Maestro="maestro",e.Elo="elo",e.Mir="mir",e.Hiper="hiper",e.Hipercard="hipercard"}(xi||(xi={}));var Fi,Li,Bi,ji=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ui{constructor(e){this.braintreeScriptLoader=e}initialize(e){this.setClientToken(e)}deinitialize(){return ji(this,void 0,void 0,function*(){yield this.teardownModule(this.dataCollector),this.dataCollector=void 0})}getClient(){return ji(this,void 0,void 0,function*(){if(!this.client){const e=this.getClientTokenOrThrow(),t=yield this.braintreeScriptLoader.loadClient();this.client=yield t.create({authorization:e})}return this.client})}getDataCollectorOrThrow(e){return ji(this,void 0,void 0,function*(){const t={deviceData:void 0,teardown:()=>Promise.resolve()};if(!this.dataCollector)try{const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadDataCollector(),i=Object.assign({client:t,kount:!0},e);this.dataCollector=yield n.create(i)}catch(e){if(Ri(e)&&e.code===Ni.KountNotEnabled)return t;throw e}return this.dataCollector})}getBraintreeGooglePayment(){return ji(this,void 0,void 0,function*(){if(!this.googlePayment){const[e,t]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.loadGooglePayment()]);this.googlePayment=yield t.create({client:e})}return this.googlePayment})}getBraintreeThreeDS(){return ji(this,void 0,void 0,function*(){if(!this.threeDS){const[e,t]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.load3DS()]);this.threeDS=yield t.create({client:e,version:2})}return this.threeDS})}getBraintreeLocalPayment(e){return ji(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment){const[t,n]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.loadLocalPayment()]);this.braintreeLocalPayment=yield new Promise((i,r)=>{n.create({client:t,merchantAccountId:e},(e,t)=>{e&&r(e),i(t)})})}return this.braintreeLocalPayment})}getUsBankAccount(){return ji(this,void 0,void 0,function*(){if(!this.usBankAccount){const e=yield this.getClient(),t=yield this.braintreeScriptLoader.loadUsBankAccount();this.usBankAccount=yield t.create({client:e})}return this.usBankAccount})}getBraintreeVisaCheckout(){return this.visaCheckout||(this.visaCheckout=Promise.all([this.getClient(),this.braintreeScriptLoader.loadVisaCheckout()]).then(([e,t])=>t.create({client:e}))),this.visaCheckout}getVisaCheckoutSdk(e){return ji(this,void 0,void 0,function*(){return this.visaCheckoutSDK||(this.visaCheckoutSDK=yield this.braintreeScriptLoader.loadVisaCheckoutSdk(e)),this.visaCheckoutSDK})}getVenmoCheckoutOrThrow(){return ji(this,void 0,void 0,function*(){if(!this.braintreeVenmo){const e=yield this.getClient(),t=yield this.braintreeScriptLoader.loadVenmoCheckout(),n={client:e,allowDesktop:!0,paymentMethodUsage:"multi_use"},i=yield t.create(n);if(!i.isBrowserSupported())throw new Ai;this.braintreeVenmo=i}return this.braintreeVenmo})}setClientToken(e){this.clientToken=e}getClientTokenOrThrow(){if(!this.clientToken)throw new ri(ei.PaymentNotInitialized);return this.clientToken}teardownModule(e){return e?e.teardown():Promise.resolve()}}!function(e){e.Sandbox="sandbox",e.Production="production"}(Fi||(Fi={})),function(e){e.Client="client",e.DataCollector="dataCollector",e.Fastlane="fastlane",e.GooglePayment="googlePayment",e.HostedFields="hostedFields",e.LocalPayment="localPayment",e.Paypal="paypal",e.PaypalCheckout="paypalCheckout",e.ThreeDSecure="threeDSecure",e.UsBankAccount="usBankAccount",e.Venmo="venmo",e.VisaCheckout="visaCheckout"}(Li||(Li={})),function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification"}(Bi||(Bi={}));const qi={[Oi]:{[Li.Client]:"sha384-26BXDNnJI23JYRyFBj4xe4sVNrUSSiSSu11kxVXNM/vEPONm4LuL00w6ZaTgQewt",[Li.PaypalCheckout]:"sha384-B+vzbZwnQtzWBthpkT4TXKUibO65tyeK7eCxSvpblgprTep2+IAXB2Cxxjrn710O",[Li.Paypal]:"sha384-uyAGL1/3+XJAHnGoNy4eCoXdzJ4f7Ilzp+6w9PNnEjs6DCCz9WMyJjMN1gzc78U+",[Li.LocalPayment]:"sha384-LIvOEMkIVEwVuYBdVOQc1AC5YbGGlwyfUheS0ACK218D2STuVYQlZ4FyEPowAEfT",[Li.DataCollector]:"sha384-1bo9JDz+Kscthc085cCKWur8CLwUoBpoNyxsDi7932mCl0zFq3A5mv+FQLw9GHpV",[Li.UsBankAccount]:"sha384-xmHBVaU+w74V+OebD3AaPONFxHUGMf+QRs8G/JxVPXNNP7MDa2jL0ICWHIe2tTfJ",[Li.GooglePayment]:"sha384-WKDJl8mqoP82qZpMGH6AbZxnvXnSW8ILV4M64CyMLiugGMwu7LyP89wjCkHqsiBe",[Li.ThreeDSecure]:"sha384-VQUlpGHzsGvs5XeiGFip7EXRsvoHWEXDVmgCacfbyieZI9mdBOqq3NSoyo28OCOB",[Li.VisaCheckout]:"sha384-yx7mADfzTN0T43Q6rlH49LIg1EJ0iUZgBp/EczX9LXsUGkySgxrD+nWHQRBkyfoT",[Li.Venmo]:"sha384-QX4rPjoj1ZDhuG0aSyKs56lEKDqTMTcjYxUHY1SzO5VZDsqIE2NTkqot7KNSCyov",[Li.HostedFields]:"sha384-VvYBACfSu0Cr/J32uKmxG7AXcNOJE1AzIIL3kbikyS7YKp5fz5Is+NzNP/lyauNy",[Li.Fastlane]:"sha384-9oGsZMRZwpGtDEDYa/dFt76dECqj1xAni9gIKgc3KfMIiRnR73nEeeUDLiBzxhFa"},[Pi]:{[Li.Client]:"sha384-o+nbQGcwNNxIBeXeu3+XmbSq+Cg8R3EN3N0l5hXCgMMU2RGY0t1z0LroSEIAbfAO",[Li.PaypalCheckout]:"sha384-WrfbWPBS4mH86GAoycPSgiH8hQ8KH7A67C93Hjhunv/xhNk2YpBn3wbFA4Fhg9U/",[Li.Paypal]:"sha384-VF389nvvrRUgDsTXMxTYORDtVegB9IQa3Cxr//DyJnLYnz8/X8VCzEvck2c+Megt",[Li.LocalPayment]:"sha384-tZKx2rEQbfmZpoPSY5VPmJEhaq4X75dLvwHMs3VE9U+C8lPyw+hWTIL1+GPvWCIH",[Li.DataCollector]:"sha384-E6k3wOpP7syCDDwaRDLF06942Y00NkbwJvWi2OQXwwKzGwG5fd3E7RFUvCCecfvO",[Li.UsBankAccount]:"sha384-258FON8LZGG0W9Qaz4Jij83pZHu30YnKjJA7gNulLBh6CclkucgF+tHDQuYFRYfW",[Li.GooglePayment]:"sha384-taJ2p/0+n0VH328POAoBiuEbL3tnHUTE9S42hK1V+Txs3X+QYjZOyKW35JgHRFfO",[Li.ThreeDSecure]:"sha384-+NSZH4Zj3sO5bdWvPKhU5N16QDxeueTVTnUVeleeESkhLSaz4Ob1hh/5myecc9Ym",[Li.VisaCheckout]:"sha384-66DiBjghxk1OmBj8aksN8gbQ+CwoQcx1vPfiXUN08g1iQVM+BwewF0p7toM3i7SS",[Li.Venmo]:"sha384-B5UwY42kE4RoLoWbQ7YpqosUlUad2/DlGWiw0HhoZbSPk30CQAaSA10ohyLDTkDU",[Li.HostedFields]:"sha384-Aw9EesSaUeWxe36PqEHiOyOyOq8M6CIb1gw7/yHNVPRzGtFXXcd2OQ8qXrIlOj2P",[Li.Fastlane]:"sha384-rhBL1hpZ71JqG+2TsT0Dih47mbjx8cjJCpeZjk9tw3df1gFMKfCTmMyZunhr7H4Y"},[bi]:{[Li.Client]:"sha384-0WNxksIpRP+fYZiIdr12g6DBUQfLDzYCQJZtR/C8KkcwSGhPHfcFp3tTaGcMyFTq",[Li.PaypalCheckout]:"sha384-lWM1jk4BOxoDNV6Kop7tVNvQgINlmEVz0c/OwM+HNHK3QC8xqwd54Ovrt2QRDTjh",[Li.Paypal]:"sha384-fXUmVxC2EMZBDXZ7eTHSTL/LFBrHej/MSXT/vTBXvra4lzgLNGvREAp+x0GYObuH",[Li.LocalPayment]:"sha384-pha1xGuGSkmZH5x9aqHvRaO4xLea7rmQ/79PFj9zxNzxuFcOWZg7gOP7FibygOEC",[Li.DataCollector]:"sha384-Q6PI2F9eekWbAxhroybl+aEcvqhdowN/EQlGwBUyJOzPFn9982u9xl6SU6XfGKzc",[Li.UsBankAccount]:"sha384-W3RLQSKJL1tQ3+Y7mP6tmkamtZ8bV4Yw/XxL9Jj5JtXHraD8loMF8hAIG5m2zK7F",[Li.GooglePayment]:"sha384-TITQMsFWA3elDNGP2mWz2oKBo4qjt+TlqzovcaPoeBiAh/wPBi6nae50ADdgU1/i",[Li.ThreeDSecure]:"sha384-YiycYN89ZlL/Evcaq4y1ajW1mhd7JYfZBDuOwHtIn4/Jnm20GL+/XCM+zYAwWD8D",[Li.VisaCheckout]:"sha384-/OdaTv9qrkKzjObtUe6yzfDhHozFW/+uXlrSl736sOZRJpjGQETvpYXqMFFg69xv",[Li.Venmo]:"sha384-dA+ojdW9vbJS4JavcXyOs9d5uZHJg5dNtYupoPSH2zsXIiYDVS5amLb/u8qmQ6oz",[Li.HostedFields]:"sha384-31ZkS58+iaWsW06ftW52zzVZFp43WPd7pNYRiddYynSNg6Oh7WGbSFGorAUH6T1z",[Li.Fastlane]:"sha384-jlbrwNvL3HvLAUCtLSmrnQ2GH1udCUrRS/bVmReAS5fuIVvcW8Pko/Gkg82tlgtr"}};var Vi,Gi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Hi{constructor(e,t,n){this.scriptLoader=e,this.braintreeHostWindow=t,this.braintreeSDKVersionManager=n}loadClient(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.Client,"client.min.js")})}loadFastlane(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.Fastlane,"fastlane.min.js")})}loadPaypalCheckout(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.PaypalCheckout,"paypal-checkout.min.js")})}loadPaypal(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.Paypal,"paypal.min.js")})}loadLocalPayment(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.LocalPayment,"local-payment.min.js")})}loadDataCollector(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.DataCollector,"data-collector.min.js")})}loadUsBankAccount(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.UsBankAccount,"us-bank-account.min.js")})}loadGooglePayment(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.GooglePayment,"google-payment.min.js")})}load3DS(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.ThreeDSecure,"three-d-secure.min.js")})}loadVisaCheckout(){return this.loadBraintreeModuleOrThrow(Li.VisaCheckout,"visa-checkout.min.js")}loadVenmoCheckout(){return this.loadBraintreeModuleOrThrow(Li.Venmo,"venmo.min.js")}loadHostedFields(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.HostedFields,"hosted-fields.min.js")})}loadVisaCheckoutSdk(e){return Gi(this,void 0,void 0,function*(){if(this.braintreeHostWindow.V)return this.braintreeHostWindow.V;const t=e?"sha384-0eu1s1GtqzXlL9DtLgmwzC5WWlEH/ADRM0n38cVQkvtT+W/gey96rcb1LwuUOPDm":"sha384-1f1csvP3ZFxg4dILH1GaY4LHlZ0oX7Rk83rxmLlwbnIi4TM0NYzXoev1VoEiVDS6";return this.scriptLoader.loadScript(`//${e?"sandbox-":""}assets.secure.checkout.visa.com/checkout-widget/resources/js/integration/v1/sdk.js`,{async:!0,attributes:{integrity:t,crossorigin:"anonymous"}}).then(()=>{if(!this.braintreeHostWindow.V)throw new mi;return this.braintreeHostWindow.V})})}loadBraintreeModuleOrThrow(e,t){return Gi(this,void 0,void 0,function*(){let n=this.getBraintreeModule(e);if(n)return n;const i=this.braintreeSDKVersionManager.getSDKVersion(),r=`//js.braintreegateway.com/web/${i}/js/${t}`,o=i in qi?this.getIntegrityValuesByModuleName(e,i):void 0;if(yield this.scriptLoader.loadScript(r,o?{async:!0,attributes:{integrity:o,crossorigin:"anonymous"}}:void 0),n=this.getBraintreeModule(e),!n)throw new mi;return n})}getBraintreeModule(e){var t;return null===(t=this.braintreeHostWindow.braintree)||void 0===t?void 0:t[e]}getIntegrityValuesByModuleName(e,t){const n=qi[t][e];if(!n)throw new Error("Unexpected fileName value");return n}}class Wi extends Qn{constructor(e){super(e||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}!function(e){e.BRAINTREE="braintree",e.BRAINTREE_FASTLANE="braintreeacceleratedcheckout"}(Vi||(Vi={}));var $i,Yi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}($i||($i={}));class Ki{constructor(e,t,n,i,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._braintreeSdk=i,this._applePayScriptLoader=r,this._onAuthorizeCallback=ce,this._onError=ce,this._onClick=ce,this._subTotalLabel=$i.Subtotal,this._shippingLabel=$i.Shipping,this._hasApplePaySession=!1}initialize(e){var t;return Yi(this,void 0,void 0,function*(){const{methodId:n,applepay:i}=e;if(!n||!i)throw new ti(Xn.MissingPaymentMethod);const{container:r,shippingLabel:o,subtotalLabel:a,onError:s=ce,onClick:d=ce,onPaymentAuthorize:c}=i;this._shippingLabel=o||$i.Shipping,this._subTotalLabel=a||$i.Subtotal,this._onAuthorizeCallback=c,this._onError=s,this._onClick=d;let l=this._paymentIntegrationService.getState();yield this._applePayScriptLoader.loadSdk();try{this._paymentMethod=l.getPaymentMethodOrThrow(n)}catch(e){l=yield this._paymentIntegrationService.loadPaymentMethod(n),this._paymentMethod=l.getPaymentMethodOrThrow(n)}yield this._paymentIntegrationService.verifyCheckoutSpamProtection(),this._applePayButton=this._createButton(r),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),(null===(t=this._paymentMethod.initializationData)||void 0===t?void 0:t.gateway)===Vi.BRAINTREE&&this._paymentMethod.clientToken&&this._braintreeSdk.initialize(this._paymentMethod.clientToken)})}deinitialize(){return Promise.resolve()}signIn(){throw new Si('In order to sign in via Apple, the shopper must click on "Apple Pay" button.')}signOut(){throw new Si("Need to do signout via apple.")}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}_createButton(e){const t=document.getElementById(e);if(!t)throw new fi("Unable to create sign-in button without valid container ID.");const n=this._createApplePayButtonElement();return t.appendChild(n),n}_createApplePayButtonElement(){const e=document.createElement("apple-pay-button");return e.setAttribute("buttonstyle","black"),e.setAttribute("type","plain"),e.setAttribute("style","--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;"),e}_handleWalletButtonClick(e){if(e.preventDefault(),this._hasApplePaySession)return;this._onClick();const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getStoreConfigOrThrow(),r=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new ti(Xn.MissingPaymentMethod);const o=this._getBaseRequest(n,r,i,this._paymentMethod),a=this._sessionFactory.create(o);this._handleApplePayEvents(a,this._paymentMethod,i),a.begin(),this._hasApplePaySession=!0}_getBaseRequest(e,t,n,i){var r;const{storeProfile:{storeCountryCode:o,storeName:a}}=n,{currency:{code:s,decimalPlaces:d}}=e,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=i,u=e.lineItems.physicalItems.length>0,h={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:o,currencyCode:s,merchantCapabilities:c,supportedNetworks:l,lineItems:[],total:u?{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"pending"}:{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"final"}};if(u)null===(r=h.requiredShippingContactFields)||void 0===r||r.push("postalAddress");else{const e=[{label:this._subTotalLabel,amount:`${t.subtotal.toFixed(d)}`}];t.taxes.forEach(t=>e.push({label:t.name,amount:`${t.amount.toFixed(d)}`})),h.lineItems=e}return h}_handleApplePayEvents(e,t,n){e.onvalidatemerchant=n=>Yi(this,void 0,void 0,function*(){try{const{body:i}=yield this._onValidateMerchant(t,n);e.completeMerchantValidation(i)}catch(e){this._onError(e)}}),e.onshippingcontactselected=t=>Yi(this,void 0,void 0,function*(){return this._handleShippingContactSelected(e,n,t)}),e.onshippingmethodselected=t=>Yi(this,void 0,void 0,function*(){return this._handleShippingMethodSelected(e,n,t)}),e.oncancel=()=>Yi(this,void 0,void 0,function*(){this._hasApplePaySession=!1;try{const e=`/remote-checkout/${t.id}/signout`;return yield this._requestSender.get(e),yield this._paymentIntegrationService.loadCheckout()}catch(e){return this._onError(new Wi)}}),e.onpaymentauthorized=n=>Yi(this,void 0,void 0,function*(){return this._onPaymentAuthorized(n,e,t)})}_handleShippingContactSelected(e,t,n){var i;return Yi(this,void 0,void 0,function*(){const r=this._transformContactToAddress(n.shippingContact);try{yield this._paymentIntegrationService.updateShippingAddress(r)}catch(t){return e.abort(),this._hasApplePaySession=!1,this._onError(t)}const{storeProfile:{storeName:o}}=t;let a=this._paymentIntegrationService.getState();const{currency:{decimalPlaces:s}}=a.getCartOrThrow();let d=a.getCheckoutOrThrow();const c=null===(i=d.consignments[0].selectedShippingOption)||void 0===i?void 0:i.id,l=d.consignments[0].availableShippingOptions,u=null==l?void 0:l.find(({id:e})=>e===c),h=null==l?void 0:l.filter(e=>e.id!==c),p=u?[{label:u.description,amount:`${u.cost.toFixed(s)}`,detail:u.additionalDescription,identifier:u.id}]:[];if(h&&[...h.filter(e=>e.isRecommended),...h.filter(e=>!e.isRecommended)].forEach(e=>p.push({label:e.description,amount:`${e.cost.toFixed(s)}`,detail:e.additionalDescription,identifier:e.id})),!(l instanceof Array))throw new Error("Shipping options not available.");if(0===l.length)return void e.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:o,amount:`${d.grandTotal.toFixed(s)}`},[]);const m=l.find(e=>e.isRecommended),y=m?m.id:l[0].id,g=u?u.id:y;try{yield this._updateShippingOption(g)}catch(e){return this._onError(e)}a=this._paymentIntegrationService.getState(),d=a.getCheckoutOrThrow(),e.completeShippingContactSelection({newShippingMethods:p,newTotal:{type:"final",label:o,amount:`${d.grandTotal.toFixed(s)}`},newLineItems:this._getUpdatedLineItems(d,s)})})}_handleShippingMethodSelected(e,t,n){return Yi(this,void 0,void 0,function*(){const{storeProfile:{storeName:i}}=t,{shippingMethod:{identifier:r}}=n;try{yield this._updateShippingOption(r)}catch(t){return e.abort(),this._hasApplePaySession=!1,this._onError(t)}const o=this._paymentIntegrationService.getState(),{currency:{decimalPlaces:a}}=o.getCartOrThrow(),s=o.getCheckoutOrThrow();e.completeShippingMethodSelection({newTotal:{type:"final",label:i,amount:`${s.grandTotal.toFixed(a)}`},newLineItems:this._getUpdatedLineItems(s,a)})})}_getUpdatedLineItems(e,t){const n=[{label:this._subTotalLabel,amount:`${e.subtotal.toFixed(t)}`}];return e.taxes.forEach(e=>n.push({label:e.name,amount:`${e.amount.toFixed(t)}`})),n.push({label:this._shippingLabel,amount:`${e.shippingCostTotal.toFixed(t)}`}),n}_updateShippingOption(e){return Yi(this,void 0,void 0,function*(){return this._paymentIntegrationService.selectShippingOption(e)})}_onValidateMerchant(e,t){return Yi(this,void 0,void 0,function*(){const n=[`validationUrl=${t.validationURL}`,`merchantIdentifier=${e.initializationData.merchantId}`,`displayName=${e.initializationData.storeName}`,`domainName=${window.location.hostname}`].join("&");return this._requestSender.post(`${e.initializationData.paymentsUrl}/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})})}_onPaymentAuthorized(e,t,n){var i;return Yi(this,void 0,void 0,function*(){const{token:r,billingContact:o,shippingContact:a}=e.payment,s=this._paymentIntegrationService.getState().getCartOrThrow().lineItems.physicalItems.length>0;let d;(null===(i=n.initializationData)||void 0===i?void 0:i.gateway)===Vi.BRAINTREE&&(d=yield this._getBraintreeDeviceData());const c={methodId:n.id,paymentData:{deviceSessionId:d,formattedPayload:{apple_pay_token:{payment_data:r.paymentData,payment_method:r.paymentMethod,transaction_id:r.transactionIdentifier}}}},l=this._transformContactToAddress(o),u=this._transformContactToAddress(a),h=null==a?void 0:a.emailAddress,p=(null==a?void 0:a.phoneNumber)||"";try{return yield this._paymentIntegrationService.updateBillingAddress(Object.assign(Object.assign({},l),{email:h,phone:p})),s&&(yield this._paymentIntegrationService.updateShippingAddress(u)),yield this._paymentIntegrationService.submitOrder({useStoreCredit:!1}),yield this._paymentIntegrationService.submitPayment(c),t.completePayment(ApplePaySession.STATUS_SUCCESS),this._onAuthorizeCallback()}catch(e){return t.completePayment(ApplePaySession.STATUS_FAILURE),this._onError(e)}})}_transformContactToAddress(e){return{firstName:(null==e?void 0:e.givenName)||"",lastName:(null==e?void 0:e.familyName)||"",city:(null==e?void 0:e.locality)||"",company:"",address1:(null==e?void 0:e.addressLines)&&e.addressLines[0]||"",address2:(null==e?void 0:e.addressLines)&&e.addressLines[1]||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||"",phone:(null==e?void 0:e.phoneNumber)||"",stateOrProvince:(null==e?void 0:e.administrativeArea)||"",stateOrProvinceCode:(null==e?void 0:e.administrativeArea)||"",customFields:[]}}_getBraintreeDeviceData(){return Yi(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}function Ji(e){if(!function(e){return"ApplePaySession"in e}(e))throw new Error("Apple pay is not supported")}class Zi{create(e){return Ji(window),new ApplePaySession(1,e)}}class Qi{constructor(e){this.scriptLoader=e,this.sdkVersion="1.latest"}loadSdk(){return e=this,t=void 0,i=function*(){(function(e){return"ApplePaySDK"in e})(window)||(yield this.scriptLoader.loadScript(`https://applepay.cdn-apple.com/jsapi/${this.sdkVersion}/apple-pay-sdk.js`),Ji(window))},new((n=void 0)||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())});var e,t,n,i}}const Xi=vi(e=>{const{getHost:t}=e.getState(),i=new Ei(e);return new Ki(n({host:t()}),e,new Zi,new Ui(new Hi(a(),window,i)),new Qi(new r))},[{id:"applepay"}]);class er extends Qn{constructor(e){super(e||"An unexpected error has occurred during buy now cart creation process. Please try again later."),this.name="BuyNowCartCreationError",this.type="buy_now_cart_creation_error"}}const tr={body:{},headers:{},status:0};class nr extends Qn{constructor(e,{message:t,errors:n}={}){const{body:i,headers:r,status:o}=e||tr;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=i,this.headers=r,this.status=o,this.errors=n||[]}}var ir,rr,or,ar,sr,dr,cr;!function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(ir||(ir={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(rr||(rr={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(or||(or={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(ar||(ar={})),function(e){e.pill="pill",e.rect="rect"}(sr||(sr={})),function(e){e.OXXO="oxxo"}(dr||(dr={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(cr||(cr={}));var lr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ur{constructor(e,t,n,i){this.formPoster=e,this.paymentIntegrationService=t,this.bigCommercePaymentsRequestSender=n,this.bigCommercePaymentsScriptLoader=i}loadPayPalSdk(e,t,n,i){return lr(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e);return this.paypalSdk=yield this.bigCommercePaymentsScriptLoader.getPayPalSDK(a,o,n,i),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new mi;return this.paypalSdk}createBuyNowCartOrThrow(e){return lr(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}})}createOrder(e,t){return lr(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:n},t));return i})}createOrderCardFields(e,t){return lr(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i,setupToken:r}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:n},t));return Object.assign({orderId:i},r?{setupToken:r}:{})})}updateOrder(){return lr(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getConsignmentsOrThrow()[0];try{yield this.bigCommercePaymentsRequestSender.updateOrder({availableShippingOptions:n.availableShippingOptions,cartId:t.id,selectedShippingOption:n.selectedShippingOption})}catch(e){throw new nr}})}getOrderStatus(e,t){return lr(this,void 0,void 0,function*(){try{const{status:n}=yield this.bigCommercePaymentsRequestSender.getOrderStatus(e,t);return n}catch(e){throw new nr}})}tokenizePayment(e,t){const n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new ti(Xn.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===xt.BuyNow&&{cart_id:n.id}))}submitPayment(e,t,n){return lr(this,void 0,void 0,function*(){const i={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}};yield this.paymentIntegrationService.submitPayment(Object.assign({methodId:e,paymentData:i},n?{gatewayId:n}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],i=n.find(e=>e.isRecommended),r=(e?n.find(t=>t.id===e):n.find(e=>{var n;return e.id===(null===(n=t.selectedShippingOption)||void 0===n?void 0:n.id)}))||i||n[0];if(!r)throw new Error("Your order can't be shipped to this address");return r}getAddress(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:(null==e?void 0:e.phone)||"",company:"",address1:(null==e?void 0:e.address1)||"",address2:(null==e?void 0:e.address2)||"",city:(null==e?void 0:e.city)||"",countryCode:(null==e?void 0:e.countryCode)||"",postalCode:(null==e?void 0:e.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==e?void 0:e.stateOrProvinceCode)||"",customFields:[]}}getBillingAddressFromOrderDetails({payer:e}){var t,n;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,address2:e.address.address_line_2,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1,phone:null===(n=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===n?void 0:n.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:n}=e,{address:i,name:{full_name:r}}=n[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:i.address_line_1,address2:i.address_line_2,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})}getValidButtonStyle(e){const{color:t,height:n,label:i,shape:r}=e||{},o={color:t&&ar[t]?t:void 0,height:this.getValidHeight(n),label:i&&or[i]?i:void 0,shape:r&&sr[r]?r:void 0};return ue(o,J)}getValidHeight(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40}removeElement(e){const t=e&&document.getElementById(e);t&&(t.style.display="none")}}const hr="This API endpoint is for internal use only and may change in the future";var pr;!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(pr||(pr={}));const mr=pr,yr={"X-Checkout-SDK-Version":"1.909.5"};var gr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vr{constructor(e){this.requestSender=e}createOrder(e,t){return gr(this,void 0,void 0,function*(){const n=`/api/storefront/payment/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.post(n,{headers:r,body:i})).body})}updateOrder(e){return gr(this,void 0,void 0,function*(){const t=e,n=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.put("/api/storefront/initialization/bigcommerce_payments",{headers:n,body:t})).body})}getOrderStatus(e="bigcommerce_payments",t){return gr(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body})}}var fr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Sr{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,n,i){return fr(this,void 0,void 0,function*(){const r=this.getPayPalSdkScriptConfigOrThrow(e,t,n);return this.loadPayPalSDK(r,i)})}loadPayPalSDK(e,t=!1){return fr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsPayPalSDK||t){const t=this.transformConfig(e.options),n=this.transformConfig(e.attributes),i=`https://www.paypal.com/sdk/js?${new URLSearchParams(t).toString()}`;yield this.scriptLoader.loadScript(i,{async:!0,attributes:n})}if(!this.window.bigCommercePaymentsPayPalSDK)throw new mi;return this.window.bigCommercePaymentsPayPalSDK})}getPayPalSdkScriptConfigOrThrow(e,t,n=!0){const{id:i,clientToken:r,initializationData:o}=e;if(!(null==o?void 0:o.clientId))throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:c,attributionId:l,isVenmoEnabled:u,isHostedCheckoutEnabled:h,isPayPalCreditAvailable:p,isDeveloperModeApplicable:m,availableAlternativePaymentMethods:y=[],enabledAlternativePaymentMethods:g=[],isGooglePayEnabled:v}=o,f=h||n,S="bigcommerce_payments_creditcards"===i,_=S?["card"]:[],w=S?[]:["card"],I=p?["credit","paylater"]:[],C=p?[]:["credit","paylater"],b=u?["venmo"]:[],P=u?[]:["venmo"],O=y.filter(e=>!g.includes(e)),E=v?["googlepay"]:[],A=n?["card-fields"]:[],T=this.filterFundingOptions([...w,...C,...P,...O]),k=this.filterFundingOptions([..._,...I,...b,...g]);return{options:Object.assign({"client-id":s,"merchant-id":d,"enable-funding":k.length>0?k:void 0,"disable-funding":T.length>0?T:void 0,commit:f,components:["buttons","hosted-fields","payment-fields","legal",...E,...A],currency:t,intent:a},m&&{"buyer-country":c}),attributes:{"data-partner-attribution-id":l,"data-client-token":r,"data-namespace":"bigCommercePaymentsPayPalSDK"}}}filterFundingOptions(e){const t=["klarna","afterpay"];return e?e.filter(e=>!t.includes(e)):[]}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}const _r=e=>{const{getHost:t}=e.getState();return new ur(Ee(),e,new vr(n({host:t()})),new Sr(a()))},wr=40;var Ir=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Cr{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=ce}initialize(e){return Ir(this,void 0,void 0,function*(){const{bigcommerce_payments:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.bigcommerce_payments.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.bigcommerce_payments.onClick" argument is not a function.');this.onError=t.onError||ce,this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Ir(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return Ir(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){var n,i;const{container:r,onClick:o,onComplete:a}=t,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:c,paymentButtonStyles:l,isAppSwitchEnabled:u=!1}=d.initializationData||{},{checkoutTopButtonStyles:h}=l||{},p=Object.assign(Object.assign(Object.assign({},u&&{appSwitchWhenAvailable:!0}),{createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)}),o&&{onClick:()=>o()}),m=Object.assign(Object.assign({},!u&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(t,n)=>this.onHostedCheckoutApprove(t,n,e,a)}),y=Object.assign(Object.assign({fundingSource:s.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},h),{height:wr}))},p),c&&m),g=s.Buttons(y);g.isEligible()?(null===(n=g.hasReturned)||void 0===n?void 0:n.call(g))&&u?null===(i=g.resume)||void 0===i||i.call(g):g.render(`#${r}`):this.bigCommercePaymentsIntegrationService.removeElement(r)}onHostedCheckoutApprove(e,t,n,i){return Ir(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Ir(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}onShippingOptionsChange(e){return Ir(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const br=vi(e=>new Cr(e,_r(e)),[{id:"bigcommerce_payments"}]);var Pr,Or,Er,Ar,Tr,kr,Dr,Mr,zr,Nr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class xr{constructor(e){this.scriptLoader=e,this.window=window}getPayPalFastlaneSdk(e,t,n){return Nr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsFastlaneSdk){const i=this.getPayPalFastlaneSdkConfiguration(e,t,n);if(yield this.loadPayPalSdk(i),!this.window.bigCommercePaymentsFastlaneSdk)throw new mi}return this.window.bigCommercePaymentsFastlaneSdk})}getPayPalGooglePaySdk(e,t,n,i){return Nr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsGooglePay||i){const i=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n);yield this.loadPayPalSdk(i)}if(!this.window.bigCommercePaymentsGooglePay)throw new mi;return this.window.bigCommercePaymentsGooglePay})}getPayPalApmsSdk(e,t){return Nr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsApms){const n=this.getPayPalApmSdkConfiguration(e,t);if(yield this.loadPayPalSdk(n),!this.window.bigCommercePaymentsApms)throw new mi}return this.window.bigCommercePaymentsApms})}getPayPalMessages(e,t){return Nr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsMessages){const n=this.getPayPalSdkMessagesConfiguration(e,t);yield this.loadPayPalSdk(n)}if(!this.window.bigCommercePaymentsMessages)throw new mi;return this.window.bigCommercePaymentsMessages})}loadPayPalSdk({options:e,attributes:t}){return Nr(this,void 0,void 0,function*(){const n=this.transformConfig(e),i=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(n).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:i})})}getPayPalFastlaneSdkConfiguration(e,t,n){const{clientToken:i,initializationData:r}=e;if(!r||!r.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,attributionId:d}=r;return{options:{"client-id":a,"merchant-id":s,commit:!0,components:["fastlane","three-domain-secure"],currency:t,intent:o},attributes:{"data-client-metadata-id":n.replace(/-/g,""),"data-namespace":"bigCommercePaymentsFastlaneSdk","data-partner-attribution-id":d,"data-sdk-client-token":i}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n=!0){const{clientToken:i,initializationData:r}=e;if(!r||!r.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,buyerCountry:d,attributionId:c,isHostedCheckoutEnabled:l,isDeveloperModeApplicable:u}=r,h=l||n;return{options:Object.assign({"client-id":a,"merchant-id":s,commit:h,components:["googlepay"],currency:t,intent:o},u&&{"buyer-country":d}),attributes:{"data-partner-attribution-id":c,"data-client-token":i,"data-namespace":"bigCommercePaymentsGooglePay"}}}getPayPalApmSdkConfiguration(e,t){const{initializationData:n}=e;if(!n||!n.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:i,clientId:r,merchantId:o,buyerCountry:a,attributionId:s,isDeveloperModeApplicable:d,availableAlternativePaymentMethods:c=[],enabledAlternativePaymentMethods:l=[]}=n,u=this.filterFundingOptions(l),h=this.filterFundingOptions(c.filter(e=>!l.includes(e)));return{options:Object.assign({"client-id":r,"merchant-id":o,"enable-funding":u.length>0?u:void 0,"disable-funding":h.length>0?h:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:i},d&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":s,"data-namespace":"bigCommercePaymentsApms"}}}getPayPalSdkMessagesConfiguration(e,t){const{initializationData:n}=e;if(!n||!n.clientId)throw new ti(Xn.MissingPaymentMethod);const{clientId:i,merchantId:r,attributionId:o,isDeveloperModeApplicable:a,buyerCountry:s}=n;return{options:Object.assign({"client-id":i,"merchant-id":r,components:["messages"],currency:t},a&&{"buyer-country":s}),attributes:{"data-namespace":"bigCommercePaymentsMessages","data-partner-attribution-id":o}}}filterFundingOptions(e){const t=["klarna","afterpay"];return e?e.filter(e=>!t.includes(e)):[]}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}function Rr(){return new xr(o())}!function(e){e.CVV="cvv",e.PAN="pan"}(Pr||(Pr={}));class Fr{static get(e){const t=`${encodeURIComponent(`${e}`)}=`,n=document.cookie;let i=null;const r=n.indexOf(t);if(r>-1){let e=n.indexOf(";",r);-1===e&&(e=n.length),i=decodeURIComponent(n.substring(r+t.length,e))}return i}static set(e,t,n={secure:!0}){let i=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;const{expires:r,path:o,domain:a,secure:s}=n;if(r)i+=`; expires=${r.toUTCString()}`;else{const e=new Date,t=60;e.setTime(e.getTime()+60*t*1e3),i+=`; expires=${e.toUTCString()}`}o&&(i+=`; path=${o}`),a&&(i+=`; domain=${a}`),s&&(i+="; secure"),document.cookie=i}static remove(e,t){Fr.set(e,"",Object.assign({expires:new Date(0)},t))}}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Or||(Or={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(Er||(Er={})),function(e){e.Always="SCA_ALWAYS"}(Ar||(Ar={})),function(e){e.Succeeded="succeeded",e.Cancelled="cancelled",e.Errored="errored"}(Tr||(Tr={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(kr||(kr={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(Dr||(Dr={})),function(e){e.pill="pill",e.rect="rect"}(Mr||(Mr={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="canceled",e.UNRECOGNIZED="unrecognized"}(zr||(zr={}));var Lr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Br{constructor(){this.window=window}initializePayPalFastlane(e,t,n){return Lr(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("fastlaneEnv","sandbox"),window.localStorage.setItem("axoEnv","sandbox")),!this.window.bigCommercePaymentsFastlane){const t={root:{backgroundColorPrimary:"transparent"}};this.window.bigCommercePaymentsFastlane=yield e.Fastlane({styles:n||t})}return this.window.bigCommercePaymentsFastlane})}getPayPalFastlaneOrThrow(){if(!this.window.bigCommercePaymentsFastlane)throw new mi;return this.window.bigCommercePaymentsFastlane}lookupCustomerOrThrow(e){return Lr(this,void 0,void 0,function*(){return this.getPayPalFastlaneOrThrow().identity.lookupCustomerByEmail(e)})}triggerAuthenticationFlowOrThrow(e){return Lr(this,void 0,void 0,function*(){return e?this.getPayPalFastlaneOrThrow().identity.triggerAuthenticationFlow(e):{}})}updateStorageSessionId(e){const t=new Date;t.setDate(t.getDate()+14);const n={expires:t,secure:!0};Fr.set("bc-fastlane-sessionId",e,n)}removeStorageSessionId(){Fr.remove("bc-fastlane-sessionId")}getStorageSessionId(){return Fr.get("bc-fastlane-sessionId")||""}mapPayPalFastlaneProfileToBcCustomerData(e,t){var n,i,r;const{authenticationState:o,profileData:a}=t,s=null===(r=null===(i=null===(n=null==a?void 0:a.card)||void 0===n?void 0:n.paymentSource)||void 0===i?void 0:i.card)||void 0===r?void 0:r.billingAddress,d=null==a?void 0:a.shippingAddress,c=null==a?void 0:a.name,l=null==a?void 0:a.card,u=d?this.mapPayPalToBcAddress(d.address,d.name,d.phoneNumber):void 0,h=s&&c?this.mapPayPalToBcAddress(s,c,null==d?void 0:d.phoneNumber):void 0,p=l?this.mapPayPalToBcInstrument(e,l):[],m=this.filterAddresses([u,h]);return{authenticationState:o||zr.UNRECOGNIZED,addresses:m,billingAddress:h,shippingAddress:u,instruments:p}}mapPayPalToBcInstrument(e,t){const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a}=i.card,[s,d]=o.split("-");return[{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:Pr.PAN,type:"card"}]}mapBcToPayPalAddress(e){return{company:(null==e?void 0:e.company)||"",addressLine1:(null==e?void 0:e.address1)||"",addressLine2:(null==e?void 0:e.address2)||"",adminArea1:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",adminArea2:(null==e?void 0:e.city)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||""}}mapPayPalToBcAddress(e,t,n,i){const[r,o]=t.fullName.split(" "),a=(null==n?void 0:n.nationalNumber)||"",s=(null==n?void 0:n.countryCode)||"";return{id:Date.now(),type:"paypal-address",firstName:t.firstName||r||"",lastName:t.lastName||o||"",company:e.company||"",address1:e.addressLine1,address2:e.addressLine2||"",city:e.adminArea2,stateOrProvince:e.adminArea1,stateOrProvinceCode:e.adminArea1,country:e.countryCode||"",countryCode:e.countryCode||"",postalCode:e.postalCode,phone:s+a,customFields:i||[]}}filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this.isEqualAddresses(e,t))?e:[...e,t]:e,[])}isEqualAddresses(e,t){return Y(this.normalizeAddress(e),this.normalizeAddress(t))}normalizeAddress(e){return le(e,["id","phone"])}}function jr(){return new Br}function Ur(e){return"string"!=typeof e}function qr(e,t){if(t||e)return function(e){var t,n;const i={},r=ue(e.root,Ur),o=ue(e.input,Ur),a=ue(e.toggle,Ur),s=ue(null===(t=e.text)||void 0===t?void 0:t.body,Ur),d=ue(null===(n=e.text)||void 0===n?void 0:n.caption,Ur),c=e.branding;return Object.keys(r).length&&(i.root=r),Object.keys(o).length&&(i.input=o),Object.keys(a).length&&(i.toggle=a),Object.keys(s).length&&(i.text={},i.text.body=s),Object.keys(d).length&&(i.text=Object.assign({},i.text),i.text.caption=d),c&&(i.branding=c),i}(function(e,t){var n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,_,w,I,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(c=null==t?void 0:t.input)||void 0===c?void 0:c.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.focusBorderColor),backgroundColor:(null==e?void 0:e.fastlaneInputSettingsBackgroundColor)||(null===(u=null==t?void 0:t.input)||void 0===u?void 0:u.backgroundColor),borderWidth:(null==e?void 0:e.fastlaneInputSettingsBorderWidth)||(null===(h=null==t?void 0:t.input)||void 0===h?void 0:h.borderWidth),textColorBase:(null==e?void 0:e.fastlaneInputSettingsTextColorBase)||(null===(p=null==t?void 0:t.input)||void 0===p?void 0:p.textColorBase)},toggle:{colorPrimary:(null==e?void 0:e.fastlaneToggleSettingsColorPrimary)||(null===(m=null==t?void 0:t.toggle)||void 0===m?void 0:m.colorPrimary),colorSecondary:(null==e?void 0:e.fastlaneToggleSettingsColorSecondary)||(null===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(S=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===S?void 0:S.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(w=null===(_=null==t?void 0:t.text)||void 0===_?void 0:_.caption)||void 0===w?void 0:w.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(I=null==t?void 0:t.text)||void 0===I?void 0:I.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var Vr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Gr{constructor(e,t,n){this.paymentIntegrationService=e,this.bigCommercePaymentsSdk=t,this.bigCommercePaymentsFastlaneUtils=n}initialize(e){var t;return Vr(this,void 0,void 0,function*(){const{methodId:n,bigcommerce_payments_fastlane:i}=e;if(!n)throw new fi('Unable to proceed because "methodId" argument is not provided.');try{yield this.paymentIntegrationService.loadPaymentMethod(n);const e=this.paymentIntegrationService.getState(),r=e.getCartOrThrow(),o=e.getPaymentMethodOrThrow(n),a=!!(null===(t=o.initializationData)||void 0===t?void 0:t.isDeveloperModeApplicable),s=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(o,r.currency.code,r.id);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(s,a,this.getFastlaneStyles(n,i))}catch(e){}return Promise.resolve()})}deinitialize(){return Vr(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return Vr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:void 0,addresses:void 0,instruments:void 0}),this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId()})}signOut(e){return Vr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return Vr(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:n,methodId:i}=e||{};if(!i)throw new fi('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof n)throw new fi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(this.paymentIntegrationService.getState().getCustomerOrThrow().isGuest){t&&"function"==typeof t&&t();try{yield this.runPayPalAuthenticationFlowOrThrow(i)}catch(e){}}n()})}runPayPalAuthenticationFlowOrThrow(e){return Vr(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow().id,i=t.getCustomer(),r=t.getBillingAddress(),o=(null==i?void 0:i.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(a),d=s.authenticationState===zr.CANCELED;yield this.updateCustomerDataState(e,s),d?this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId():this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(n)})}updateCustomerDataState(e,t){var n;return Vr(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow(),{authenticationState:r,addresses:o,billingAddress:a,shippingAddress:s,instruments:d}=this.bigCommercePaymentsFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,t);if(yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:r,addresses:o,instruments:d}),a&&(yield this.paymentIntegrationService.updateBillingAddress(a)),s&&i.lineItems.physicalItems.length>0){const t=yield this.paymentIntegrationService.updateShippingAddress(s),i=t.getPaymentMethodOrThrow(e),{isFastlaneShippingOptionAutoSelectEnabled:r}=i.initializationData||{},o=t.getConsignments()||[],a=(null===(n=o[0])||void 0===n?void 0:n.availableShippingOptions)||[],d=a[0],c=a.find(e=>e.isRecommended);if((c||d)&&r){const e=(null==c?void 0:c.id)||d.id;yield this.paymentIntegrationService.selectShippingOption(e)}}})}getFastlaneStyles(e,t){const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{fastlaneStyles:i,isFastlaneStylingEnabled:r}=n.initializationData||{};return qr(r?i:{},null==t?void 0:t.styles)}}const Hr=vi(e=>new Gr(e,Rr(),jr()),[{id:"bigcommerce_payments_fastlane"},{id:"bigcommerce_payments_creditcards"}]);var Wr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class $r{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=ce}initialize(e){return Wr(this,void 0,void 0,function*(){const{bigcommerce_payments_paylater:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater.onClick" argument is not a function.');this.onError=t.onError||ce,this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC BigCommercePayments PayLater]: button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Wr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Wr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){const{container:n,onComplete:i,onClick:r}=t,o=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:s,paymentButtonStyles:d}=a.initializationData||{},{checkoutTopButtonStyles:c}=d||{},l=Object.assign({createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},r&&{onClick:()=>r()}),u={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(t,n)=>this.onHostedCheckoutApprove(t,n,e,i)},h=[o.FUNDING.PAYLATER,o.FUNDING.CREDIT];let p=!1;h.forEach(e=>{if(!p){const t=Object.assign(Object.assign({fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},c),{height:wr}))},l),s&&u),i=o.Buttons(t);i.isEligible()&&(i.render(`#${n}`),p=!0)}}),p||this.bigCommercePaymentsIntegrationService.removeElement(n)}onHostedCheckoutApprove(e,t,n,i){return Wr(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Wr(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}onShippingOptionsChange(e){return Wr(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const Yr=vi(e=>new $r(e,_r(e)),[{id:"bigcommerce_payments_paylater"}]);var Kr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Jr{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return Kr(this,void 0,void 0,function*(){const{bigcommerce_payments_venmo:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC Payments Venmo]: Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Kr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Kr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){const{container:n,onClick:i}=t,r=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:a}=o.initializationData||{},{checkoutTopButtonStyles:s}=a||{},d=Object.assign({fundingSource:r.FUNDING.VENMO,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},s),{height:wr})),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},i&&{onClick:()=>i()}),c=r.Buttons(d);c.isEligible()?c.render(`#${n}`):this.bigCommercePaymentsIntegrationService.removeElement(n)}}const Zr=vi(e=>new Jr(e,_r(e)),[{id:"bigcommerce_payments_venmo"}]);class Qr extends Qn{constructor(e){super(e||"Unable to proceed because the client library of a payment method has thrown an unexpected error."),this.name="PaymentMethodFailedError",this.type="payment_method_client_invalid"}}class Xr extends nr{constructor(e){super(e,{message:"There is a problem processing your payment. Please try again later."}),this.name="PaymentMethodInvalidError",this.type="payment_method_invalid"}}var eo,to,no,io=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ro{constructor(e,t){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=window}initialize(e){var t;return io(this,void 0,void 0,function*(){const{methodId:n,bolt:i}=e,{onInit:r}=i||{};if(!n)throw new fi('Unable to proceed because "methodId" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n);if(!(null===(t=o.initializationData)||void 0===t?void 0:t.publishableKey))throw new ti(Xn.MissingPaymentMethod);const{developerConfig:a,publishableKey:s}=o.initializationData;if(yield this.boltScriptLoader.loadBoltClient(s,o.config.testMode,a),r&&"function"==typeof r){const e=this.getCustomerEmail();r(yield this.hasBoltAccount(e),e)}})}deinitialize(){return Promise.resolve()}signIn(e,t){return io(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return io(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){return io(this,void 0,void 0,function*(){const{continueWithCheckoutCallback:t=I,checkoutPaymentMethodExecuted:n,methodId:i}=e||{},r=this.getCustomerEmail();if(!i)throw new fi('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof t)throw new fi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(r)return this.openBoltCheckoutModalOrThrow(r,i,t,n);t()})}openBoltCheckoutModalOrThrow(e,t,n,i){var r;return io(this,void 0,void 0,function*(){const o=this.getBoltClientOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethod(t);try{if(null===(r=null==a?void 0:a.initializationData)||void 0===r?void 0:r.embeddedOneClickEnabled){const t=yield this.hasBoltAccount(e);if(t){const t={close:()=>{n()}};yield o.openCheckout(e,t)}else n();"function"==typeof i&&i({hasBoltAccount:t})}else n()}catch(e){if(function(e){return"string"==typeof e.message&&"string"==typeof e.type&&("string"==typeof e.subtype||!e.subtype)&&e instanceof Error}(e)&&"MissingDataError"!==e.name&&"NotInitializedError"!==e.name)throw new Qr(e.message);throw e}})}getBoltClientOrThrow(){const e=this.boltHostWindow.BoltCheckout;if(!e)throw new ri(ei.PaymentNotInitialized);return e}hasBoltAccount(e){return io(this,void 0,void 0,function*(){const t=this.getBoltClientOrThrow();try{return yield t.hasBoltAccount(e)}catch(e){throw new Xr}})}getCustomerEmail(){const e=this.paymentIntegrationService.getState(),t=e.getCustomer(),n=e.getBillingAddress();return(null==t?void 0:t.email)||(null==n?void 0:n.email)||""}}!function(e){e.SandboxMode="bolt_sandbox",e.StagingMode="bolt_staging",e.DevelopmentMode="bolt_development"}(eo||(eo={})),function(e){e.Small="small",e.Medium="medium",e.Large="large"}(to||(to={})),function(e){e.Pill="pill",e.Rect="rect"}(no||(no={}));var oo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ao{constructor(e,t=window){this.scriptLoader=e,this.boltHostWindow=t}loadBoltClient(e,t,n,i,r){return oo(this,void 0,void 0,function*(){if(this.boltHostWindow.BoltCheckout)return this.boltHostWindow.BoltCheckout;if(!e)throw new fi('Unable to initialize payment because "publishableKey" argument is not provided.');if(yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,n)}/connect-bigcommerce.js`,this.getScriptOptions("bolt-connect",e,i,r)),yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,n)}/track.js`,this.getScriptOptions("bolt-track",e)),!this.boltHostWindow.BoltCheckout)throw new mi;return this.boltHostWindow.BoltCheckout})}loadBoltEmbedded(e,t,n){return oo(this,void 0,void 0,function*(){if(yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,n)}/embed.js`,{async:!0,attributes:{id:"bolt-embedded"}}),!this.boltHostWindow.Bolt)throw new mi;return this.boltHostWindow.Bolt(e)})}getDomainURL(e,t){if(!e)return"connect.bolt.com";if(t)switch(t.developerMode){case eo.StagingMode:return"connect-staging.bolt.com";case eo.DevelopmentMode:return`connect.${t.developerDomain}`}return"connect-sandbox.bolt.com"}getScriptOptions(e,t,n,i){return{async:!0,attributes:Object.assign(Object.assign({id:e,"data-publishable-key":t},n&&{"data-shopping-cart-id":n}),i&&{"data-storefront-api-token":i})}}}const so=vi(e=>new ro(e,new ao(a())),[{id:"bolt"}]);class co extends fi{constructor(e){let t="Unable to submit payment for the order because the payload is invalid.";e&&(t=`${t} Make sure the following fields are provided correctly: ${e.join(", ")}.`),super(t),this.name="PaymentArgumentInvalidError"}}class lo extends Qn{constructor(e,t){super(t||"Unable to proceed because the payment form contains invalid data."),this.details=e,this.name="PaymentInvalidFormError",this.type="payment_invalid_form"}}let uo=null;const ho=["buttons","messages"];var po,mo,yo,go,vo,fo;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(po||(po={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(mo||(mo={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black",e.WHITE="white"}(yo||(yo={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(go||(go={})),function(e){e.PILL="pill",e.RECT="rect"}(vo||(vo={})),function(e){e.CART="cart",e.HOME="homepage",e.PAYMENT="payment",e.PRODUCT="product"}(fo||(fo={}));var So=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class _o{constructor(e,t,n){this.braintreeScriptLoader=e,this.braintreeHostWindow=t,this.overlay=n,this.dataCollectors={}}initialize(e,t){this.clientToken=e,this.threeDSecureOptions=t}getBraintreeFastlane(e,t,n){return So(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("axoEnv","sandbox"),window.localStorage.setItem("fastlaneEnv","sandbox")),!this.braintreeHostWindow.braintreeFastlane){const t=this.getClientTokenOrThrow(),i=yield this.getClient(),r=yield this.getSessionId(e),o=yield this.braintreeScriptLoader.loadFastlane(),a={root:{backgroundColorPrimary:"transparent"}};this.braintreeHostWindow.braintreeFastlane=yield o.create({authorization:t,client:i,deviceData:r,styles:n||a})}return this.braintreeHostWindow.braintreeFastlane})}getClient(){return So(this,void 0,void 0,function*(){if(!this.client){const e=this.getClientTokenOrThrow(),t=yield this.braintreeScriptLoader.loadClient();this.client=t.create({authorization:e})}return this.client})}getPaypal(){return this.braintreePaypal||(this.braintreePaypal=Promise.all([this.getClient(),this.braintreeScriptLoader.loadPaypal()]).then(([e,t])=>t.create({client:e}))),this.braintreePaypal}paypal(e){var{shouldSaveInstrument:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{var r;return i&&(null===(r=this.overlay)||void 0===r||r.show({onClick:()=>e.focusWindow()})),e.tokenize(Object.assign({enableShippingAddress:!0,flow:t?"vault":"checkout",useraction:"commit"},n))}).then(e=>{var t;return null===(t=this.overlay)||void 0===t||t.remove(),e}).catch(e=>{var t;throw null===(t=this.overlay)||void 0===t||t.remove(),e})}getPaypalCheckout(e,t,n){return So(this,void 0,void 0,function*(){const i=yield this.getClient(),r=yield this.braintreeScriptLoader.loadPaypalCheckout(),o={client:i};return this.paypalCheckout=yield r.create(o,(i,r)=>{var o;if(i)return n(i);const a=Object.assign(Object.assign({currency:e.currency},e.isCreditEnabled&&{"enable-funding":"paylater"}),{components:ho.toString(),intent:e.intent,commit:null===(o=e.commit)||void 0===o||o});this.braintreeHostWindow.paypal?t(r):function(e,t){return uo||(uo=new Promise((n,i)=>{e.loadPayPalSDK(t,t=>{t?(uo=null,i(t)):n(e)})})),uo}(r,a).then(()=>t(r))}),this.paypalCheckout})}getDataCollector(e){return So(this,void 0,void 0,function*(){const t=(null==e?void 0:e.paypal)?"paypal":"default";let n=this.dataCollectors[t];if(!n){try{const t=yield this.getClient(),i=yield this.braintreeScriptLoader.loadDataCollector(),r=Object.assign({client:t,kount:!0},e);n=yield i.create(r)}catch(e){if(!Ri(e)||"DATA_COLLECTOR_KOUNT_NOT_ENABLED"!==e.code)throw e;n={deviceData:void 0,teardown:()=>Promise.resolve()}}this.dataCollectors[t]=n}return n})}getBraintreeEnv(e=!1){return e?Fi.Sandbox:Fi.Production}mapToBraintreeShippingAddressOverride(e){return{recipientName:`${e.firstName} ${e.lastName}`,line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,postalCode:e.postalCode,countryCode:e.countryCode,phone:e.phone}}mapToLegacyShippingAddress(e){const{email:t,phone:n,shippingAddress:i}=e,r=(null==i?void 0:i.recipientName)||"",[o,a]=r.split(" ");return{email:t,first_name:o||"",last_name:a||"",phone_number:n,address_line_1:null==i?void 0:i.line1,address_line_2:null==i?void 0:i.line2,city:null==i?void 0:i.city,state:null==i?void 0:i.state,country_code:null==i?void 0:i.countryCode,postal_code:null==i?void 0:i.postalCode}}mapToLegacyBillingAddress(e){const{billingAddress:t,email:n,firstName:i,lastName:r,phone:o,shippingAddress:a}=e,s=t||a;return{email:n,first_name:i,last_name:r,phone_number:o,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}}removeElement(e){const t=e&&document.getElementById(e);t&&t.remove()}getSessionId(e){return So(this,void 0,void 0,function*(){const{deviceData:t}=yield this.getDataCollector({riskCorrelationId:e});return t})}teardown(){return So(this,void 0,void 0,function*(){yield this.teardownModule(this.dataCollectors.default),yield this.teardownModule(this.dataCollectors.paypal),this.dataCollectors={},yield this.teardownModule(this.paypalCheckout),this.paypalCheckout=void 0})}get3DS(){return So(this,void 0,void 0,function*(){return this.threeDS||(this.threeDS=Promise.all([this.getClient(),this.braintreeScriptLoader.load3DS()]).then(([e,t])=>t.create({client:e,version:2}))),this.threeDS})}getVenmoCheckout(e){return So(this,void 0,void 0,function*(){if(!this.venmoCheckout){const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadVenmoCheckout(),i=Object.assign({client:t,allowDesktop:!0,paymentMethodUsage:"multi_use"},e||{});this.venmoCheckout=yield new Promise((e,t)=>{n.create(i,(n,i)=>n?t(n):i.isBrowserSupported()?void e(i):t(new Ai))})}return this.venmoCheckout})}verifyCard(e,t,n){return So(this,void 0,void 0,function*(){const i=yield this.tokenizeCard(e,t);return this.challenge3DSVerification(i,n)})}tokenizeCard(e,t){return So(this,void 0,void 0,function*(){const{paymentData:n}=e;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"object"==typeof t.ccExpiry&&null!==t.ccExpiry&&"string"==typeof t.ccNumber&&"string"==typeof t.ccName}(n))throw new co(["payment.paymentData"]);const i=this.getErrorsRequiredFields(n);if(!$(i))throw new lo(i);const r=this.mapToCreditCard(n,t),o=yield this.getClient(),{creditCards:a}=yield o.request(r);return{nonce:a[0].nonce,bin:a[0].details.bin}})}challenge3DSVerification(e,t){return So(this,void 0,void 0,function*(){const n=yield this.get3DS();return this.present3DSChallenge(n,t,e)})}teardownModule(e){return e?e.teardown():Promise.resolve()}getClientTokenOrThrow(){if(!this.clientToken)throw new ri(ei.PaymentNotInitialized);return this.clientToken}getErrorsRequiredFields(e){const{ccNumber:t,ccExpiry:n}=e,i={};return t||(i.ccNumber=[{message:"Credit card number is required",type:"required"}]),n||(i.ccExpiry=[{message:"Expiration date is required",type:"required"}]),i}mapToCreditCard(e,t){return{data:{creditCard:{cardholderName:e.ccName,number:e.ccNumber,cvv:e.ccCvv,expirationDate:`${e.ccExpiry.month}/${e.ccExpiry.year}`,options:{validate:!1},billingAddress:t&&{countryCodeAlpha2:t.countryCode,locality:t.city,countryName:t.country,postalCode:t.postalCode,streetAddress:t.address2?`${t.address1} ${t.address2}`:t.address1}}},endpoint:"payment_methods/credit_cards",method:"post"}}present3DSChallenge(e,t,n){const{nonce:i,bin:r}=n;if(!this.threeDSecureOptions||!i)throw new ri(ei.PaymentNotInitialized);const{addFrame:o,removeFrame:a,challengeRequested:s=!0,additionalInformation:d}=this.threeDSecureOptions,c=()=>So(this,void 0,void 0,function*(){const t=yield e.cancelVerifyCard();return u.cancel(new Wi),t}),l=t.toFixed(2),u=new En(e.verifyCard({addFrame:(e,t)=>{o&&o(e,t,c)},amount:Number(l),bin:r,challengeRequested:s,nonce:i,removeFrame:a,onLookupComplete:(e,t)=>{t()},collectDeviceData:!0,additionalInformation:d}));return u.promise}}var wo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Io{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return wo(this,void 0,void 0,function*(){const{braintreepaypal:t,methodId:n}=e,{container:i,onError:r}=t||{};if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.braintreepaypal.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(n),!o.clientToken)throw new ti(Xn.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(n),o=a.getPaymentMethodOrThrow(n)}const{clientToken:s,config:d,initializationData:c}=o,{paymentButtonStyles:l}=c||{},{checkoutTopButtonStyles:u}=l||{};if(!s||!c)throw new ti(Xn.MissingPaymentMethod);const h={currency:a.getCartOrThrow().currency.code,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{this.renderPayPalButton(e,t,n,Boolean(d.testMode),u)},e=>this.handleError(e,i,r))})}deinitialize(){return wo(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}signIn(e,t){return wo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return wo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderPayPalButton(e,t,n,i,r){const{container:o,onClick:a=ce}=t,{paypal:s}=this.braintreeHostWindow,d=null==s?void 0:s.FUNDING.PAYPAL;if(s&&d){const c=s.Buttons({env:this.braintreeIntegrationService.getBraintreeEnv(i),fundingSource:d,style:Object.assign(Object.assign({},r),{height:wr}),createOrder:()=>this.setupPayment(e,t,n),onApprove:i=>this.tokenizePayment(i,e,n,t),onClick:a});c.isEligible()&&c.render(`#${o}`)}else this.braintreeIntegrationService.removeElement(o)}setupPayment(e,t,n){var i;return wo(this,void 0,void 0,function*(){try{yield this.paymentIntegrationService.loadDefaultCheckout();const t=this.paymentIntegrationService.getState(),r=t.getCheckoutOrThrow().outstandingBalance,o=t.getCartOrThrow().currency.code,a=t.getCustomer(),s=t.getPaymentMethodOrThrow(n),d=null==a?void 0:a.addresses[0],c=d?this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(d):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:c,amount:r,currency:o,offerCredit:!1,intent:null===(i=s.initializationData)||void 0===i?void 0:i.intent})}catch(e){const{container:n,onError:i}=t;this.handleError(e,n,i)}})}tokenizePayment(e,t,n,i){return wo(this,void 0,void 0,function*(){try{const{deviceData:i}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),r=yield t.tokenizePayment(e),{details:o,nonce:a}=r,s=this.braintreeIntegrationService.mapToLegacyBillingAddress(o),d=this.braintreeIntegrationService.mapToLegacyShippingAddress(o);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:n,action:"set_external_checkout",nonce:a,device_data:i,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:n}=i;this.handleError(e,t,n)}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const Co=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t);return new Io(e,Ee(),i,t)},[{id:"braintreepaypal"}]);var bo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Po{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return bo(this,void 0,void 0,function*(){const{braintreepaypalcredit:t,methodId:n}=e,{container:i,onError:r}=t||{};if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(n),!o.clientToken)throw new ti(Xn.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(n),o=a.getPaymentMethodOrThrow(n)}const{clientToken:s,config:d,initializationData:c}=o,{paymentButtonStyles:l}=c||{},{checkoutTopButtonStyles:u}=l||{};if(!s||!c)throw new ti(Xn.MissingPaymentMethod);const h={currency:a.getCartOrThrow().currency.code,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{this.renderPayPalButton(e,t,n,Boolean(d.testMode),Object.assign(Object.assign({},u),{height:wr}))},e=>this.handleError(e,i,r))})}deinitialize(){return bo(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}signIn(e,t){return bo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return bo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderPayPalButton(e,t,n,i,r){const{container:o,onClick:a=ce}=t,{paypal:s}=this.braintreeHostWindow;let d=!1;s&&[s.FUNDING.PAYLATER,s.FUNDING.CREDIT].forEach(c=>{if(!d){const l=s.Buttons({env:i?"sandbox":"production",fundingSource:c,style:r,createOrder:()=>this.setupPayment(e,t,n),onApprove:i=>this.tokenizePayment(i,e,n,t),onClick:a});l.isEligible()&&(l.render(`#${o}`),d=!0)}}),s&&d||this.braintreeIntegrationService.removeElement(o)}setupPayment(e,t,n){var i;return bo(this,void 0,void 0,function*(){try{yield this.paymentIntegrationService.loadDefaultCheckout();const t=this.paymentIntegrationService.getState(),r=t.getCheckoutOrThrow().outstandingBalance,o=t.getCartOrThrow().currency.code,a=t.getCustomer(),s=t.getPaymentMethodOrThrow(n),d=null==a?void 0:a.addresses[0],c=d?this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(d):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:c,amount:r,currency:o,offerCredit:!0,intent:null===(i=s.initializationData)||void 0===i?void 0:i.intent})}catch(e){const{container:n,onError:i}=t;this.handleError(e,n,i)}})}tokenizePayment(e,t,n,i){return bo(this,void 0,void 0,function*(){try{const{deviceData:i}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),r=yield t.tokenizePayment(e),{details:o,nonce:a}=r,s=this.braintreeIntegrationService.mapToLegacyBillingAddress(o),d=this.braintreeIntegrationService.mapToLegacyShippingAddress(o);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:n,action:"set_external_checkout",nonce:a,device_data:i,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:n}=i;this.handleError(e,t,n)}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const Oo=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t);return new Po(e,Ee(),i,t)},[{id:"braintreepaypalcredit"}]);function Eo(e){return"string"!=typeof e}function Ao(e,t){if(t||e)return function(e){var t,n;const i={},r=ue(e.root,Eo),o=ue(e.input,Eo),a=ue(e.toggle,Eo),s=ue(null===(t=e.text)||void 0===t?void 0:t.body,Eo),d=ue(null===(n=e.text)||void 0===n?void 0:n.caption,Eo),c=e.branding;return Object.keys(r).length&&(i.root=r),Object.keys(o).length&&(i.input=o),Object.keys(a).length&&(i.toggle=a),Object.keys(s).length&&(i.text={},i.text.body=s),Object.keys(d).length&&(i.text=Object.assign({},i.text),i.text.caption=d),c&&(i.branding=c),i}(function(e,t){var n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,_,w,I,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(c=null==t?void 0:t.input)||void 0===c?void 0:c.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.focusBorderColor),backgroundColor:(null==e?void 0:e.fastlaneInputSettingsBackgroundColor)||(null===(u=null==t?void 0:t.input)||void 0===u?void 0:u.backgroundColor),borderWidth:(null==e?void 0:e.fastlaneInputSettingsBorderWidth)||(null===(h=null==t?void 0:t.input)||void 0===h?void 0:h.borderWidth),textColorBase:(null==e?void 0:e.fastlaneInputSettingsTextColorBase)||(null===(p=null==t?void 0:t.input)||void 0===p?void 0:p.textColorBase)},toggle:{colorPrimary:(null==e?void 0:e.fastlaneToggleSettingsColorPrimary)||(null===(m=null==t?void 0:t.toggle)||void 0===m?void 0:m.colorPrimary),colorSecondary:(null==e?void 0:e.fastlaneToggleSettingsColorSecondary)||(null===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(S=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===S?void 0:S.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(w=null===(_=null==t?void 0:t.text)||void 0===_?void 0:_.caption)||void 0===w?void 0:w.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(I=null==t?void 0:t.text)||void 0===I?void 0:I.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var To=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ko{constructor(e,t){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.isAcceleratedCheckoutEnabled=!1}initialize({methodId:e,braintreefastlane:t}){var n;return To(this,void 0,void 0,function*(){if(!e)throw new fi('Unable to proceed because "methodId" argument is not provided.');const i=yield this.getValidPaymentMethodOrThrow(e),{isAcceleratedCheckoutEnabled:r,isFastlaneStylingEnabled:o}=i.initializationData||{},a=o?null===(n=i.initializationData)||void 0===n?void 0:n.fastlaneStyles:void 0;this.isAcceleratedCheckoutEnabled=!!r;try{if(this.isAcceleratedCheckoutEnabled){const e=Ao(a,null==t?void 0:t.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(i.id,e)}}catch(e){}return Promise.resolve()})}deinitialize(){return To(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return To(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return To(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return To(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:n}=e||{};if("function"!=typeof n)throw new fi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');const i=this.paymentIntegrationService.getState().getCustomerOrThrow();if(this.isAcceleratedCheckoutEnabled&&i.isGuest){const e=yield this.shouldRunAuthenticationFlow();t&&"function"==typeof t&&t(),e&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow(void 0,!0))}n()})}shouldRunAuthenticationFlow(){var e;return To(this,void 0,void 0,function*(){const t="braintreeacceleratedcheckout";try{yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t);return(null===(e=n.initializationData)||void 0===e?void 0:e.shouldRunAcceleratedCheckout)||!1}catch(e){return!1}})}getValidPaymentMethodOrThrow(e){return To(this,void 0,void 0,function*(){let t=e;try{yield this.paymentIntegrationService.loadPaymentMethod(t)}catch(n){t="braintree"===e?"braintreeacceleratedcheckout":"braintree",yield this.paymentIntegrationService.loadPaymentMethod(t)}return this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)})}}var Do=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Mo{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}getDeviceSessionId(){return Do(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getCart();return this.braintreeIntegrationService.getSessionId(null==e?void 0:e.id)})}initializeBraintreeFastlaneOrThrow(e,t){return Do(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getCart(),{clientToken:r,config:o}=n.getPaymentMethodOrThrow(e);if(!r)throw new ti(Xn.MissingPaymentMethod);this.methodId=e,this.braintreeIntegrationService.initialize(r),this.braintreeFastlane=yield this.braintreeIntegrationService.getBraintreeFastlane(null==i?void 0:i.id,o.testMode,t)})}getBraintreeFastlaneOrThrow(){if(!this.braintreeFastlane)throw new mi;return this.braintreeFastlane}getBraintreeFastlaneComponentOrThrow(){return this.getBraintreeFastlaneOrThrow().FastlaneCardComponent}runPayPalAuthenticationFlowOrThrow(e,t){var n;return Do(this,void 0,void 0,function*(){try{const i=this.getMethodIdOrThrow(),r=this.getBraintreeFastlaneOrThrow(),{lookupCustomerByEmail:o,triggerAuthenticationFlow:a}=r.identity,s=this.paymentIntegrationService.getState(),d=s.getCartOrThrow(),c=s.getCustomer(),l=s.getBillingAddress(),{isFastlaneShippingOptionAutoSelectEnabled:u}=s.getPaymentMethodOrThrow(i).initializationData||{},h=e||(null==c?void 0:c.email)||(null==l?void 0:l.email)||"",{customerContextId:p}=yield o(h);if(!p)return yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:Mi.UNRECOGNIZED,addresses:[],instruments:[]}),void this.saveSessionIdToCookies(d.id);const{authenticationState:m,profileData:y}=yield a(p),g=(null===(n=null==y?void 0:y.shippingAddress)||void 0===n?void 0:n.phoneNumber)||"";if(m===Mi.CANCELED)return yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:[],instruments:[]}),void this.removeSessionIdFromCookies();const v=this.mapPayPalToBcAddress([y.shippingAddress],[g])||[],f=this.getPayPalBillingAddresses(y),S=f?this.mapPayPalToBcAddress([f],[g]):[],_=y.card?this.mapPayPalToBcInstrument(i,[y.card]):[],w=this.mergeShippingAndBillingAddresses(v,S);if(this.saveSessionIdToCookies(d.id),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:w,instruments:_}),S.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateBillingAddress(S[0])),S.length>0&&d.lineItems.digitalItems.length>0&&0===d.lineItems.physicalItems.length){const{firstName:e,lastName:t}=w[0],n=Object.assign(Object.assign({},S[0]),{firstName:e,lastName:t});yield this.paymentIntegrationService.updateBillingAddress(n)}v.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateShippingAddress(v[0]),t&&u&&(yield this.setShippingOption()))}catch(e){}})}getSessionIdFromCookies(){return Fr.get("bc-fastlane-sessionId")||""}saveSessionIdToCookies(e){const t=new Date;t.setDate(t.getDate()+14),Fr.set("bc-fastlane-sessionId",e,{expires:t,secure:!0})}removeSessionIdFromCookies(){Fr.remove("bc-fastlane-sessionId")}mapPayPalToBcInstrument(e,t){if(t)return t.map(t=>{const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a,binDetails:s}=i.card,[d,c]=o.split("-");return{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:c,expiryYear:d,iin:(null==s?void 0:s.bin)||"",last4:a,method:e,provider:e,trustedShippingAddress:!1,type:"card",untrustedShippingCardVerificationMode:Pr.PAN}})}mapPayPalToBcAddress(e,t){if(!e)return[];const n=this.paymentIntegrationService.getState().getCountries()||[],i=e=>{const t=n.find(t=>t.code===e);return(null==t?void 0:t.name)||""};return e.map(e=>({id:Date.now(),type:"paypal-address",firstName:e.firstName||"",lastName:e.lastName||"",company:e.company||"",address1:e.streetAddress,address2:e.extendedAddress||"",city:e.locality,stateOrProvince:e.region,stateOrProvinceCode:e.region,country:i(e.countryCodeAlpha2),countryCode:e.countryCodeAlpha2,postalCode:e.postalCode,phone:t&&t[0]||"",customFields:[]}))}getPayPalBillingAddresses(e){const{card:t,name:n}=e||{};if(!t)return;const{firstName:i,lastName:r}=t.paymentSource.card.billingAddress,{firstName:o,lastName:a}=n||{},{shippingAddress:s}=e||{},d=Object.assign(Object.assign({},t.paymentSource.card.billingAddress),{firstName:i||o,lastName:r||a});return s&&Y(this.normalizeAddress(d),this.normalizeAddress(s))?s:d}normalizeAddress(e){return le(e,["id"])}mergeShippingAndBillingAddresses(e,t){const n=t.filter(t=>!e.some(e=>Y(this.normalizeAddress(e),this.normalizeAddress(t))));return[...e,...n]}getMethodIdOrThrow(){if(!this.methodId)throw new fi('Unable to proceed because "methodId" argument is not provided.');return this.methodId}setShippingOption(){var e;return Do(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getConsignments()||[],n=(null===(e=t[0])||void 0===e?void 0:e.availableShippingOptions)||[],i=n.find(e=>e.isRecommended);if(i||n.length){const e=i||n[0];yield this.paymentIntegrationService.selectShippingOption(e.id)}})}}const zo=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t),r=new Mo(e,i);return new ko(e,r)},[{id:"braintreeacceleratedcheckout"},{id:"braintree"}]);var No=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class xo{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n,this.buttonClassName="visa-checkout-wrapper",this.onError=ce}initialize(e){return No(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:n}=e;if(!n)throw new fi('Unable to proceed because "methodId" argument is not provided.');if(!t)throw new fi('Unable to proceed because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState(),r=i.getCheckoutOrThrow(),{clientToken:o,config:a}=i.getPaymentMethodOrThrow(n),s=i.getStoreConfigOrThrow();if(!o)throw new ti(Xn.MissingPaymentMethod);this.braintreeSdk.initialize(o);const d=yield this.braintreeSdk.getBraintreeVisaCheckout(),c=yield this.braintreeSdk.getVisaCheckoutSdk(a.testMode),{container:l,onError:u}=t;this.onError=u||ce;const h=d.createInitOptions({paymentRequest:{currencyCode:s.currency.code,subtotal:String(r.subtotal)},settings:{locale:s.storeProfile.storeLanguage,shipping:{collectShipping:!0}}}),p=this.createSignInButton(l,this.buttonClassName);yield c.init(h),c.on("payment.success",e=>this.tokenizePayment(d,e).then(()=>this.paymentIntegrationService.loadCheckout()).catch(e=>this.handleError(e))),c.on("payment.error",(e,t)=>this.handleError(t)),p.style.visibility="visible"})}deinitialize(){return No(this,void 0,void 0,function*(){yield this.braintreeSdk.deinitialize()})}signIn(){throw new Si('In order to sign in via VisaCheckout, the shopper must click on "Visa Checkout" button.')}signOut(e){return No(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}tokenizePayment(e,t){return No(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const n=this.paymentIntegrationService.getState(),i=n.getShippingAddress(),r=n.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(i),billingAddress:a=this.mapToVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}postForm(e,t){const{userData:n,billingAddress:i,shippingAddress:r,details:o}=e,{userEmail:a}=n,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,i)),shipping_address:JSON.stringify(this.getAddress(a,r))})}mapToVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}createSignInButton(e,t){const n=document.querySelector(`#${e}`);if(!n)throw new Error("Unable to proceed because the provided container ID is not valid.");return this.insertVisaCheckoutButton(n,t)}insertVisaCheckoutButton(e,t){const n=document.createElement("div");return n.style.display="flex",n.style.flexDirection="column",n.style.visibility="hidden",n.style.width="max-content",n.className=t,n.innerHTML='\n \n Tell Me More',e.appendChild(n),n}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const Ro=vi(e=>{const t=window,n=new Ei(e),i=new Ui(new Hi(a(),t,n));return new xo(e,Ee(),i)},[{id:"braintreevisacheckout"}]);class Fo{constructor(e){if(!e)throw new Error("Currency settings missing");const{decimalPlaces:t,symbolLocation:n,symbol:i,thousandsSeparator:r,decimalSeparator:o}=e;if("string"!=typeof n||"string"!=typeof i||"string"!=typeof r||"string"!=typeof o||"string"!=typeof t)throw new fi("Invalid currency settings provided");this._decimalPlaces=parseInt(t,10),this._symbolLocation=n,this._symbol=i,this._thousandsSeparator=r,this._decimalSeparator=o}format(e){if("number"!=typeof e)throw new fi("Invalid amount provided");const t=this._formatNumber(e),n=this._formatCurrency(t);return e<0?`-${n}`:n}_formatNumber(e){const t=Math.abs(e),[n,i=""]=this._toFixed(t,this._decimalPlaces).split("."),r=n.replace(/\B(?=(\d{3})+(?!\d))/g,this._thousandsSeparator);return this._decimalPlaces<1?r:[r,i].join(this._decimalSeparator)}_formatCurrency(e){return"left"===this._symbolLocation.toLowerCase()?`${this._symbol}${e}`:`${e}${this._symbol}`}_toFixed(e,t){return(+`${Math.round(+`${e}e${t}`)}e${-t}`).toFixed(t)}}let Lo=class{constructor(e){this._storeConfig=e,this._customerFormatter=new Fo(this._storeConfig.shopperCurrency),this._storeFormatter=new Fo(this._storeConfig.currency)}toCustomerCurrency(e){const t=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(e*t)}toStoreCurrency(e){return this._storeFormatter.format(e)}};Lo=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],Lo);const Bo=Lo,jo=(e,t)=>!!e&&(!!e.lineItems.physicalItems.some(e=>e.isShippingRequired)||!(!t||!e.lineItems.customItems)&&e.lineItems.customItems.length>0);function Uo(){if("undefined"==typeof window)return!1;if(function(e){return"ReactNativeWebView"in e}(window))return!0;const e=navigator.userAgent||navigator.vendor||(function(e){return"opera"in e}(window)?window.opera:""),t=/android.+; wv/i.test(e),n=/iPhone|iPod|iPad/i.test(e)&&/AppleWebKit/i.test(e)&&!/Safari/i.test(e);return t||n}var qo,Vo,Go,Ho,Wo,$o,Yo,Ko,Jo;function Zo(e){return e in $o}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(qo||(qo={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Vo||(Vo={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(Go||(Go={})),function(e){e.pill="pill",e.rect="rect"}(Ho||(Ho={})),function(e){e.ESTIMATED="ESTIMATED",e.FINAL="FINAL",e.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(Wo||(Wo={})),function(e){e.AMEX="AMEX",e.DISCOVER="DISCOVER",e.INTERAC="INTERAC",e.JCB="JCB",e.MC="MASTERCARD",e.VISA="VISA"}($o||($o={})),function(e){e.OFFER="OFFER",e.PAYMENT_AUTHORIZATION="PAYMENT_AUTHORIZATION",e.SHIPPING_ADDRESS="SHIPPING_ADDRESS",e.SHIPPING_OPTION="SHIPPING_OPTION"}(Yo||(Yo={})),function(e){e.OFFER_INVALID="OFFER_INVALID",e.PAYMENT_DATA_INVALID="PAYMENT_DATA_INVALID",e.SHIPPING_ADDRESS_INVALID="SHIPPING_ADDRESS_INVALID",e.SHIPPING_ADDRESS_UNSERVICEABLE="SHIPPING_ADDRESS_UNSERVICEABLE",e.SHIPPING_OPTION_INVALID="SHIPPING_OPTION_INVALID",e.OTHER_ERROR="OTHER_ERROR"}(Ko||(Ko={})),function(e){e.INITIALIZE="INITIALIZE",e.SHIPPING_OPTION="SHIPPING_OPTION",e.SHIPPING_ADDRESS="SHIPPING_ADDRESS",e.OFFER="OFFER"}(Jo||(Jo={}));var Qo,Xo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ea{constructor(e,t){this._gatewayIdentifier=e,this._paymentIntegrationService=t,this._isBuyNowFlow=!1,this._shouldRequestShipping=!0,this._isWebViewExperimentOn=null}mapToShippingAddressRequestBody({shippingAddress:e}){if(!e)return;const{company:t="",phone:n=""}=this._paymentIntegrationService.getState().getShippingAddress()||{};return this._mapToAddressRequestBody(e,t,n)}mapToBillingAddressRequestBody(e){const{billingAddress:t}=e.paymentMethodData.info;if(!t)return;const{company:n="",phone:i="",email:r,customFields:o=[]}=this._paymentIntegrationService.getState().getBillingAddress()||{};return Object.assign(Object.assign({},this._mapToAddressRequestBody(t,n,i,o)),{email:r||e.email})}mapToExternalCheckoutData(e){var t;const{paymentMethodData:{tokenizationData:{token:n},info:{cardNetwork:i,cardDetails:r}}}=e;if(!n)throw new ti(Xn.MissingPaymentToken);return Promise.resolve(Object.assign({nonce:n,card_information:{type:i,number:r}},this._isBuyNowFlow&&{cart_id:null===(t=this._paymentIntegrationService.getState().getCart())||void 0===t?void 0:t.id}))}getRequiredData(){var e;return Xo(this,void 0,void 0,function*(){const t={emailRequired:!0};if(!this._isShippingAddressRequired())return t;const n=yield this._paymentIntegrationService.loadShippingCountries(),i=null===(e=n.getShippingCountries())||void 0===e?void 0:e.map(e=>e.code);return Object.assign(Object.assign({},t),{shippingAddressRequired:!0,shippingAddressParameters:Object.assign({phoneNumberRequired:!0},i&&{allowedCountryCodes:i}),shippingOptionRequired:!0})})}getCallbackIntents(){return this._isShippingAddressRequired()?[Yo.OFFER,Yo.SHIPPING_ADDRESS,Yo.SHIPPING_OPTION]:[Yo.OFFER]}getCallbackTriggers(){return{availableTriggers:[Jo.INITIALIZE,Jo.SHIPPING_ADDRESS,Jo.SHIPPING_OPTION,Jo.OFFER],initializationTrigger:[Jo.INITIALIZE],addressChangeTriggers:[Jo.INITIALIZE,Jo.SHIPPING_ADDRESS],shippingOptionsChangeTriggers:[Jo.SHIPPING_OPTION],offerChangeTriggers:[Jo.OFFER]}}getNonce(e){var t;const n=null===(t=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.nonce;if(!n)throw new ti(Xn.MissingPaymentToken);return Promise.resolve(n)}extraPaymentData(){return Promise.resolve(void 0)}getMerchantInfo(){const{googleMerchantName:e,googleMerchantId:t,platformToken:n}=this.getGooglePayInitializationData();return{merchantName:e,merchantId:t,authJwt:n}}getTransactionInfo(){let e;const{getCartOrThrow:t}=this._paymentIntegrationService.getState();e=this._isBuyNowFlow?this._getCurrencyCodeOrThrow():t().currency.code;const n=this.getGooglePayInitializationData().storeCountry;if(this.isWebViewWithRestrictions()){const t=this.getTotalPrice();return Object.assign(Object.assign({},n&&{countryCode:n}),{currencyCode:e,totalPrice:t,totalPriceStatus:Wo.ESTIMATED})}return Object.assign(Object.assign({},n&&{countryCode:n}),{currencyCode:e,totalPriceStatus:Wo.ESTIMATED,totalPrice:"0"})}isWebViewWithRestrictions(){return null!==this._isWebViewExperimentOn?this._isWebViewExperimentOn&&Uo():Uo()}setIsWebViewExperimentOn(e){this._isWebViewExperimentOn=e}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData().gatewayMerchantId;if(!e)throw new fi("Unable to proceed, gatewayMerchantId is missing.");return{gateway:this._gatewayIdentifier,gatewayMerchantId:e}}getCardParameters(){return{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:this.getPaymentMethod().supportedCards.filter(Zo).map(e=>$o[e]),billingAddressRequired:!0,billingAddressParameters:{format:"FULL",phoneNumberRequired:!0}}}initialize(e,t,n){return this._getPaymentMethodFn=e,this._isBuyNowFlow=Boolean(t),this._currencyCode=n,this._isBuyNowFlow&&this._getCurrencyCodeOrThrow(),Promise.resolve()}handleShippingAddressChange(e){var t,n,i,r;return Xo(this,void 0,void 0,function*(){e&&(e.name=e.name||"",e.address1=e.address1||"");const o=this.mapToShippingAddressRequestBody({shippingAddress:e});o&&(yield this._paymentIntegrationService.updateShippingAddress(o));const a=this._paymentIntegrationService.getState(),s=a.getConsignments();if(!(null==s?void 0:s[0]))return;const d=s[0],c=a.getStoreConfigOrThrow();this._currencyService||(this._currencyService=new Bo(c));const l=(d.availableShippingOptions||[]).map(this._getGooglePayShippingOption.bind(this)),u=null===(t=d.availableShippingOptions)||void 0===t?void 0:t.find(e=>e.isRecommended);if(l.length){const e=(null===(n=d.selectedShippingOption)||void 0===n?void 0:n.id)||(null==u?void 0:u.id)||(null===(i=l[0])||void 0===i?void 0:i.id);return!(null===(r=d.selectedShippingOption)||void 0===r?void 0:r.id)&&l[0]&&(yield this.handleShippingOptionChange((null==u?void 0:u.id)||l[0].id)),{defaultSelectedOptionId:e,shippingOptions:l}}})}handleShippingOptionChange(e){return Xo(this,void 0,void 0,function*(){if("shipping_option_unselected"!==e)return this._paymentIntegrationService.selectShippingOption(e)})}getTotalPrice(){const{getCheckoutOrThrow:e,getCartOrThrow:t,getStoreConfigOrThrow:n}=this._paymentIntegrationService.getState(),{decimalPlaces:i}=t().currency,r=Ci(n().checkoutSettings.features,"PI-5075.google_pay_round_total_price_to_max_2_decimal_places")?Math.min(i,2):i;return ge(e().outstandingBalance,r).toFixed(r)}handleCoupons(e){return Xo(this,void 0,void 0,function*(){const{redemptionCodes:t=[]}=e,{offers:n}=this.getAppliedCoupons()||{};let i;return yield t.reduce((e,t)=>Xo(this,void 0,void 0,function*(){if(yield e,(n||[]).some(({redemptionCode:e})=>e===t))return;const r=yield this.applyCoupon(t);r&&(i=r)}),Promise.resolve()),yield(n||[]).reduce((e,n)=>Xo(this,void 0,void 0,function*(){yield e,t.includes(n.redemptionCode)||(yield this._paymentIntegrationService.removeCoupon(n.redemptionCode))}),Promise.resolve()),{newOfferInfo:this.getAppliedCoupons(),error:i}})}getAppliedCoupons(){const e=this._paymentIntegrationService.getState(),{coupons:t}=e.getCheckout()||{};return{offers:(t||[]).map(e=>{const{displayName:t,code:n}=e;return{redemptionCode:n,description:t}})}}applyCoupon(e){return Xo(this,void 0,void 0,function*(){let t;try{yield this._paymentIntegrationService.applyCoupon(e)}catch(e){return e instanceof Error&&(t={reason:Ko.OFFER_INVALID,message:e.message,intent:Jo.OFFER}),t}})}setShouldRequestShipping(e){this._shouldRequestShipping=e}getGooglePayInitializationData(){return ii(this.getPaymentMethod().initializationData,()=>new fi("Missing initialization data."))}getPaymentMethod(){return ii(this._getPaymentMethodFn,()=>new ri(ei.PaymentNotInitialized))()}getGatewayIdentifier(){return this._gatewayIdentifier}setGatewayIdentifier(e){this._gatewayIdentifier=e||this.getGatewayIdentifier()}_isShippingAddressRequired(){const{getCartOrThrow:e,getStoreConfigOrThrow:t,getShippingAddress:n}=this._paymentIntegrationService.getState(),i=t();let r;return r=Ci(i.checkoutSettings.features,"PI-4290.google_pay_require_shipping_address")?this._shouldRequestShipping:void 0===n(),r&&jo(e(),i)}_mapToAddressRequestBody(e,t,n,i){const{name:r,address1:o,address2:a,address3:s,locality:d,administrativeArea:c,countryCode:l,postalCode:u,phoneNumber:h}=e,[p,m]=this._getFirstAndLastName(r);return{firstName:p,lastName:m,company:t,address1:o,address2:`${a} ${s}`.trim(),city:d||c,stateOrProvince:c,stateOrProvinceCode:c,countryCode:l,postalCode:u,phone:h||n,customFields:i||[]}}_getFirstAndLastName(e){const t=e.split(" ");return 1===t.length?[e,""]:[t.slice(0,-1).join(" "),t[t.length-1]]}_getCurrencyCodeOrThrow(){return ii(this._currencyCode,()=>new fi('Unable to initialize payment because "options.currencyCode" argument is not provided.'))}_getGooglePayShippingOption({id:e,cost:t,description:n,additionalDescription:i}){var r;return{id:e,label:`${(null===(r=this._currencyService)||void 0===r?void 0:r.toCustomerCurrency(t))||t} ${n}`,description:i}}}function ta(e){return"object"==typeof e&&null!==e&&"statusCode"in e}function na(e){return Object.values(Qo).includes(e)}!function(e){e.ADYEN_V2="googlepayadyenv2",e.ADYEN_V3="googlepayadyenv3",e.AUTHORIZE_NET="googlepayauthorizenet",e.BNZ="googlepaybnz",e.BRAINTREE="googlepaybraintree",e.PAYPAL_COMMERCE="googlepaypaypalcommerce",e.BIGCOMMERCE_PAYMENTS="googlepay_bigcommerce_payments",e.CHECKOUT_COM="googlepaycheckoutcom",e.CYBERSOURCE_V2="googlepaycybersourcev2",e.ORBITAL="googlepayorbital",e.STRIPE="googlepaystripe",e.STRIPE_UPE="googlepaystripeupe",e.STRIPE_OCS="googlepaystripeocs",e.WORLDPAY_ACCESS="googlepayworldpayaccess",e.TD_ONLINE_MART="googlepaytdonlinemart"}(Qo||(Qo={}));var ia=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ra{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t}initialize(e){var t,n;return ia(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId)||!na(e.methodId))throw new fi('Unable to proceed because "methodId" is not a valid key.');this._methodId=e.methodId;const i=e[this._getMethodId()];if(!i)throw new fi("Unable to proceed without valid options.");let r,o=this._paymentIntegrationService.getState();try{r=o.getPaymentMethodOrThrow(this._getMethodId())}catch(e){o=yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodId()),r=o.getPaymentMethodOrThrow(this._getMethodId())}try{this._googlePayPaymentProcessor.setIsWebViewExperimentOn(!!(null===(t=r.initializationData)||void 0===t?void 0:t.isWebViewExperimentOn)),yield this._googlePayPaymentProcessor.initialize(()=>r,this._getGooglePayClientOptions(null===(n=r.initializationData)||void 0===n?void 0:n.storeCountry))}catch(e){return}this._addPaymentButton(i)})}signIn(){return Promise.reject(new Si('In order to sign in via Google Pay, the shopper must click on "Google Pay" button.'))}signOut(){var e;return ia(this,void 0,void 0,function*(){const t=null===(e=this._paymentIntegrationService.getState().getPaymentId())||void 0===e?void 0:e.providerId;t&&(yield this._googlePayPaymentProcessor.signOut(t))})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}deinitialize(){var e;return null===(e=this._paymentButton)||void 0===e||e.remove(),this._paymentButton=void 0,this._methodId=void 0,Promise.resolve()}_getGooglePayClientOptions(e){return this._googlePayPaymentProcessor.isWebViewWithRestrictions()?{}:{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:t,shippingAddress:n,shippingOptionData:i,offerData:r})=>ia(this,void 0,void 0,function*(){const{availableTriggers:o,addressChangeTriggers:a,shippingOptionsChangeTriggers:s,offerChangeTriggers:d}=this._googlePayPaymentProcessor.getCallbackTriggers();if(!o.includes(t))return;const c=a.includes(t)?yield this._googlePayPaymentProcessor.handleShippingAddressChange(n):void 0;s.includes(t)&&(yield this._googlePayPaymentProcessor.handleShippingOptionChange(i.id));const{newOfferInfo:l,error:u}=d.includes(t)?yield this._googlePayPaymentProcessor.handleCoupons(r):{},h=u;yield this._paymentIntegrationService.loadCheckout();const p=this._googlePayPaymentProcessor.getTotalPrice(),{code:m}=this._paymentIntegrationService.getState().getCartOrThrow().currency;return Object.assign(Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},e&&{countryCode:e}),{currencyCode:m,totalPriceStatus:Wo.FINAL,totalPrice:p})},c&&{newShippingOptionParameters:c}),l&&{newOfferInfo:l}),h&&{error:h})})}}}_addPaymentButton({container:e,buttonColor:t,buttonType:n,onClick:i,onError:r}){var o;this._paymentButton=null!==(o=this._paymentButton)&&void 0!==o?o:this._googlePayPaymentProcessor.addPaymentButton(e,{buttonColor:null!=t?t:"default",buttonType:null!=n?n:"plain",onClick:this._handleClick(r,i)})}_handleClick(e,t){return n=>ia(this,void 0,void 0,function*(){n.preventDefault(),t&&"function"==typeof t&&t();try{yield this._googlePayPaymentProcessor.initializeWidget(),yield this._interactWithPaymentSheet()}catch(t){let n=t;if(ta(t)){if("CANCELED"===t.statusCode)throw new Wi;n=new Qr(JSON.stringify(t))}throw null==e||e(new Qr("An error occurred while requesting your Google Pay payment details.")),n}})}_interactWithPaymentSheet(){return ia(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet(),t=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e),n=this._googlePayPaymentProcessor.mapToShippingAddressRequestBody(e),i="/embedded-checkout"===window.location.pathname?this._paymentIntegrationService.getState().getStoreConfigOrThrow().links.siteLink:void 0;t&&(yield this._paymentIntegrationService.updateBillingAddress(t)),n&&(yield this._paymentIntegrationService.updateShippingAddress(n)),yield this._googlePayPaymentProcessor.setExternalCheckoutForm(this._getMethodId(),e,i)})}_getMethodId(){return ii(this._methodId,()=>new ri(ei.PaymentNotInitialized))}}var oa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class aa{constructor(e,t,n,i){this._scriptLoader=e,this._gateway=t,this._requestSender=n,this._formPoster=i,this._baseRequest={apiVersion:2,apiVersionMinor:0}}initialize(e,t,n,i){return oa(this,void 0,void 0,function*(){this._paymentsClient=yield this._scriptLoader.getGooglePaymentsClient(e().config.testMode,t),yield this._gateway.initialize(e,n,i),this._buildButtonPayloads()})}initializeWidget(){return oa(this,void 0,void 0,function*(){yield this._buildWidgetPayloads(),yield this._determineReadinessToPay(),this._prefetchGooglePaymentData()})}getNonce(e){return this._gateway.getNonce(e)}extraPaymentData(){return oa(this,void 0,void 0,function*(){return this._gateway.extraPaymentData()})}addPaymentButton(e,t){const n=document.querySelector(`#${e}`);if(!n)return;const i=this._getPaymentsClient().createButton(Object.assign(Object.assign({},t),{allowedPaymentMethods:[this._getBaseCardPaymentMethod()]}));return n.appendChild(i)}showPaymentSheet(){return oa(this,void 0,void 0,function*(){const e=this._getPaymentDataRequest();return this._getPaymentsClient().loadPaymentData(e)})}setExternalCheckoutXhr(e,t){return oa(this,void 0,void 0,function*(){return this._setExternalCheckout(e,t)})}setExternalCheckoutForm(e,t,n){return oa(this,void 0,void 0,function*(){return this._setExternalCheckout(e,t,!0,n)})}mapToBillingAddressRequestBody(e){return this._gateway.mapToBillingAddressRequestBody(e)}mapToShippingAddressRequestBody(e){return this._gateway.mapToShippingAddressRequestBody(e)}processAdditionalAction(e,t){return"processAdditionalAction"in this._gateway?this._gateway.processAdditionalAction(e,t):Promise.reject(e)}signOut(e){return oa(this,void 0,void 0,function*(){yield this._requestSender.get(`/remote-checkout/${e}/signout`)})}getCallbackTriggers(){return this._gateway.getCallbackTriggers()}setShouldRequestShipping(e){return this._gateway.setShouldRequestShipping(e)}handleShippingAddressChange(e){return oa(this,void 0,void 0,function*(){return this._gateway.handleShippingAddressChange(e)})}handleShippingOptionChange(e){return oa(this,void 0,void 0,function*(){yield this._gateway.handleShippingOptionChange(e)})}handleCoupons(e){return oa(this,void 0,void 0,function*(){return this._gateway.handleCoupons(e)})}getTotalPrice(){return this._gateway.getTotalPrice()}_setExternalCheckout(e,t,n=!1,i){return oa(this,void 0,void 0,function*(){const r="/checkout.php",o=Object.assign({action:"set_external_checkout",provider:e},yield this._gateway.mapToExternalCheckoutData(t));if(n)return new Promise(e=>{this._formPoster.postForm(i?`${i}/checkout`:r,Object.assign(Object.assign({},o),{card_information:JSON.stringify(o.card_information)}),e)});yield this._requestSender.post(r,{headers:Object.assign({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded"},yr),body:o})})}isWebViewWithRestrictions(){return this._gateway.isWebViewWithRestrictions()}setIsWebViewExperimentOn(e){return this._gateway.setIsWebViewExperimentOn(e)}_prefetchGooglePaymentData(){const e=this._getPaymentDataRequest();e.transactionInfo=this._gateway.getTransactionInfo(),this._getPaymentsClient().prefetchPaymentData(e)}_determineReadinessToPay(){return oa(this,void 0,void 0,function*(){try{const{result:e}=yield this._getPaymentsClient().isReadyToPay(this._getIsReadyToPayRequest());if(!1===e)throw new Qr("Google Pay is not supported by the current device and browser, please try another payment method.")}catch(e){if(e instanceof Qr)throw e;throw new Qr}})}_buildButtonPayloads(){this._baseCardPaymentMethod={type:"CARD",parameters:this._gateway.getCardParameters()}}_buildWidgetPayloads(){return oa(this,void 0,void 0,function*(){const e=this._getBaseCardPaymentMethod();this._cardPaymentMethod=Object.assign(Object.assign({},e),{tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:yield this._gateway.getPaymentGatewayParameters()}});const t=this._gateway.isWebViewWithRestrictions()?{shippingOptionRequired:!1}:{callbackIntents:this._gateway.getCallbackIntents(),offerInfo:this._gateway.getAppliedCoupons()};this._paymentDataRequest=Object.assign(Object.assign(Object.assign(Object.assign({},this._baseRequest),{allowedPaymentMethods:[this._cardPaymentMethod],transactionInfo:this._gateway.getTransactionInfo(),merchantInfo:this._gateway.getMerchantInfo()}),yield this._gateway.getRequiredData()),t),this._isReadyToPayRequest=Object.assign(Object.assign({},this._baseRequest),{allowedPaymentMethods:[e]})})}_getBaseCardPaymentMethod(){return this._getOrThrow(this._baseCardPaymentMethod)}_getPaymentDataRequest(){return this._getOrThrow(this._paymentDataRequest)}_getIsReadyToPayRequest(){return this._getOrThrow(this._isReadyToPayRequest)}_getPaymentsClient(){return this._getOrThrow(this._paymentsClient)}_getOrThrow(e){return ii(e,()=>new ri(ei.PaymentNotInitialized))}}class sa{constructor(e){this._scriptLoader=e,this._window=window}getGooglePaymentsClient(e=!1,t){return n=this,i=void 0,o=function*(){if(yield this._scriptLoader.loadScript("https://pay.google.com/gp/p/js/pay.js"),!this._window.google)throw new mi;return void 0===this._paymentsClient&&(this._paymentsClient=new this._window.google.payments.api.PaymentsClient(Object.assign({environment:e?"TEST":"PRODUCTION"},null!=t?t:{}))),this._paymentsClient},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}function da(){return new sa(a())}const ca=vi(e=>{const t=n();return new ra(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv2"}]),la=vi(e=>{const t=n();return new ra(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv3"}]);class ua extends ea{constructor(e){super("authorizenet",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();return function(e){if(!function(e){return"paymentGatewayId"in e}(e))throw new ti(Xn.MissingPaymentMethod)}(e),{gateway:this.getGatewayIdentifier(),gatewayMerchantId:e.paymentGatewayId}}}const ha=vi(e=>new ra(e,new aa(da(),new ua(e),n(),Ee())),[{id:"googlepayauthorizenet"}]),pa=e=>"object"==typeof e&&null!==e&&"body"in e;function ma(e){if(!function(e){return"checkoutcomkey"in e}(e))throw new ti(Xn.MissingPaymentMethod)}var ya=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ga extends ea{constructor(e,t){super("checkoutltd",e),this._requestSender=t}processAdditionalAction(e){return new Promise((t,n)=>{if(pa(e)&&function(e){var t;if("object"!=typeof e||null===e)return!1;const n=e;return"string"==typeof(null===(t=n.three_ds_result)||void 0===t?void 0:t.acs_url)&&"string"==typeof n.three_ds_result.code}(e.body)&&"three_d_secure_required"===e.body.three_ds_result.code)return window.location.assign(e.body.three_ds_result.acs_url);n(e)})}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ya(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);let i;try{i=JSON.parse(n.nonce)}catch(e){throw new fi("Unable to parse response from Google Pay.")}return function(e){if(!function(e){return"object"==typeof e&&null!==e&&"protocolVersion"in e&&"signature"in e&&"signedMessage"in e}(e))throw new ti(Xn.MissingPaymentToken)}(i),n.nonce=yield this._tokenize(i),n})}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();return ma(e),{gateway:this.getGatewayIdentifier(),gatewayMerchantId:e.checkoutcomkey}}_tokenize(e){return ya(this,void 0,void 0,function*(){const t=this.getPaymentMethod().config.testMode?"https://api.sandbox.checkout.com/tokens":"https://api.checkout.com/tokens",n=this.getGooglePayInitializationData();ma(n);const{body:i}=yield this._requestSender.post(t,{credentials:!1,body:{type:"googlepay",token_data:e},headers:{Authorization:n.checkoutcomkey,"Content-Type":mr.Json,"X-XSRF-TOKEN":null}});return i.token})}}const va=vi(e=>{const t=n();return new ra(e,new aa(da(),new ga(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]);class fa extends ea{constructor(e){super("cybersource",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const Sa=vi(e=>new ra(e,new aa(da(),new fa(e),n(),Ee())),[{id:"googlepaycybersourcev2"}]),_a=vi(e=>new ra(e,new aa(da(),new fa(e),n(),Ee())),[{id:"googlepaybnz"}]);class wa extends ea{constructor(e){super("chase",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const Ia=vi(e=>new ra(e,new aa(da(),new wa(e),n(),Ee())),[{id:"googlepayorbital"}]);var Ca,ba,Pa,Oa,Ea,Aa,Ta,ka,Da,Ma,za,Na;!function(e){e.SHIPPING="shipping",e.BILLING="billing"}(Ca||(Ca={})),function(e){e.SPLIT="split",e.FULL="full",e.ORGANIZATION="organization"}(ba||(ba={})),function(e){e.Open="open",e.Expired="expired",e.Complete="complete"}(Pa||(Pa={})),function(e){e.Paid="paid",e.UnPaid="unpaid",e.NoPaymentRequired="no_payment_required"}(Oa||(Oa={})),function(e){e.SUCCESS="success",e.ERROR="error"}(Ea||(Ea={})),function(e){e.CreditCard="card",e.ACH="us_bank_account",e.Link="link",e.EPS="eps",e.GRABPAY="grabpay",e.BANCONTACT="bancontact",e.IDEAL="ideal",e.ALIPAY="alipay",e.KLARNA="klarna",e.OCS="optimized_checkout",e.CHECKOUT_SESSION="checkout_session"}(Aa||(Aa={})),function(e){e.NEVER="never",e.AUTO="auto",e.ALWAYS="always",e.PAYMENT="payment",e.IF_REQUIRED="if_required"}(Ta||(Ta={})),function(e){e.V3="v3",e.ACACIA="acacia",e.BASIL="basil",e.CLOVER="clover"}(ka||(ka={})),function(e){e.PAYMENT="payment",e.AUTHENTICATION="linkAuthentication",e.SHIPPING="address",e.EXPRESS_CHECKOUT="expressCheckout"}(Da||(Da={})),function(e){e.REQUIRES_PAYMENT_METHOD="requires_payment_method",e.REQUIRES_CONFIRMATION="requires_confirmation",e.REQUIRES_ACTION="requires_action",e.PROCESSING="processing",e.SUCCEEDED="succeeded",e.CANCELED="canceled"}(Ma||(Ma={})),function(e){e.CLICK="click",e.CHANGE="change",e.READY="ready",e.SHIPPING_ADDRESS_CHANGE="shippingaddresschange",e.SHIPPING_RATE_CHANGE="shippingratechange",e.CONFIRM="confirm",e.CANCEL="cancel",e.LOADER_START="loaderstart"}(za||(za={})),function(e){e.ON_SESSION="on_session",e.OFF_SESSION="off_session"}(Na||(Na={}));var xa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ra{constructor(e,t=window){this.scriptLoader=e,this.stripeWindow=t}getStripeClient(e,t,n,i,r){return xa(this,void 0,void 0,function*(){if(this.stripeWindow.bcStripeClient)return this.stripeWindow.bcStripeClient;const o=yield this.load(n),{stripePublishableKey:a,stripeConnectedAccount:s}=e,d=o(a,Object.assign(Object.assign(Object.assign(Object.assign({},s?{stripeAccount:s}:{}),t?{locale:t}:{}),i?{betas:i}:{}),r?{apiVersion:r}:{}));return Object.assign(this.stripeWindow,{bcStripeClient:d}),d})}getElements(e,t){return xa(this,void 0,void 0,function*(){let n=this.stripeWindow.bcStripeElements;return n?yield this.updateStripeElements(t):(n=e.elements(t),Object.assign(this.stripeWindow,{bcStripeElements:n})),n})}updateStripeElements(e){return xa(this,void 0,void 0,function*(){const t=this.stripeWindow.bcStripeElements;t&&(t.update(e),yield t.fetchUpdates())})}getStripeCheckout(e,t){return xa(this,void 0,void 0,function*(){let n=yield this.getStoredStripeCheckout(t);return n||(n=yield e.initCheckout(t),Object.assign(this.stripeWindow,{bcStripeCheckout:n})),n})}load(e){return xa(this,void 0,void 0,function*(){if(!this.stripeWindow.Stripe&&(yield this.scriptLoader.loadScript(this.getScriptUrl(e)),!this.stripeWindow.Stripe))throw new mi;return this.stripeWindow.Stripe})}getScriptUrl(e){return e&&e!==ka.V3?`https://js.stripe.com/${e}/stripe.js`:"https://js.stripe.com/v3/"}getStoredStripeCheckout(e){return xa(this,void 0,void 0,function*(){const t=this.stripeWindow.bcStripeCheckout;if(t)try{const{actions:n,error:i}=yield t.loadActions();if(i||!n)return void this.logErrorToConsole(i);const r=yield n.getSession(),o=e.clientSecret.split("_secret_")[0];if(r.id===o)return t}catch(e){return void this.logErrorToConsole(e)}})}logErrorToConsole(e){e?console.error(e):console.error("No stripe checkout actions available on loadActions().")}}const Fa=["payment_element_beta_2","alipay_pm_beta_1","link_default_integration_beta_1","shipping_address_element_beta_1","address_element_beta_1"],La="2020-03-02;alipay_beta=v1;link_beta=v1";function Ba(e){if(!function(e){return"stripeConnectedAccount"in e&&"stripePublishableKey"in e&&"stripeVersion"in e}(e))throw new ti(Xn.MissingPaymentMethod)}var ja=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ua extends ea{constructor(e,t){super("stripe",e),this.paymentIntegrationService=e,this.scriptLoader=t}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ja(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);let i;try{i=JSON.parse(n.nonce)}catch(e){throw new fi("Unable to parse response from Google Pay.")}return function(e){if(!function(e){return"object"==typeof e&&null!==e&&"id"in e}(e))throw new ti(Xn.MissingPaymentToken)}(i),n.nonce=i.id,n})}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();Ba(e);const{stripeVersion:t,stripePublishableKey:n,stripeConnectedAccount:i}=e;return{gateway:this.getGatewayIdentifier(),"stripe:version":t,"stripe:publishableKey":`${n}/${i}`}}processAdditionalAction(e,t){var n;return ja(this,void 0,void 0,function*(){if(!t)throw new co(["payment"]);if(!pa(e)||("object"!=typeof(i=e.body)||null===i||!("three_ds_result"in i)||!("errors"in i)))throw e;var i;if(ve(e.body.errors,{code:"three_d_secure_required"})){const i=this.getGooglePayInitializationData();Ba(i),this.stripeUPEClient=yield this.loadStripeJs(i,t);const r=e.body.three_ds_result.token;let o,a=!1;try{o=yield this.stripeUPEClient.confirmCardPayment(r)}catch(e){try{o=yield this.stripeUPEClient.retrievePaymentIntent(r)}catch(e){a=!0}}if(null==o?void 0:o.error){if(this._throwDisplayableStripeError(o.error),this._isCancellationError(o.error))throw new Wi;throw new Qr}if(!(null==o?void 0:o.paymentIntent)&&!a)throw new nr;return this.paymentIntegrationService.submitPayment({methodId:t,paymentData:{nonce:(null===(n=null==o?void 0:o.paymentIntent)||void 0===n?void 0:n.id)||r}})}throw e})}loadStripeJs(e,t){return ja(this,void 0,void 0,function*(){if(this.stripeUPEClient)return this.stripeUPEClient;const n=this.paymentIntegrationService.getState().getCartLocale();return"googlepaystripeocs"===t&&e.useNewStripeJsVersion?this.scriptLoader.getStripeClient(e,n,ka.CLOVER):this.scriptLoader.getStripeClient(e,n,ka.V3,Fa,La)})}_isCancellationError(e){var t,n;return e&&-1!==(null===(n=null===(t=e.payment_intent.last_payment_error)||void 0===t?void 0:t.message)||void 0===n?void 0:n.indexOf("canceled"))}_throwDisplayableStripeError(e){if(H(["card_error","invalid_request_error","validation_error"],e.type))throw new Error(e.message)}}const qa=vi(e=>new ra(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeocs"}]),Va=vi(e=>new ra(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripeupe"}]);class Ga extends ea{constructor(e){super("worldpay",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const Ha=vi(e=>new ra(e,new aa(da(),new Ga(e),n(),Ee())),[{id:"googlepayworldpayaccess"}]);var Wa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class $a extends ea{constructor(e,t){super("braintree",e),this._braintreeSdk=t,this._methodId=Qo.BRAINTREE,this._service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Wa(this,void 0,void 0,function*(){yield i.initialize.call(this,e,t,n);let r=i.getPaymentMethod.call(this);if(r.clientToken||(r=(yield this._service.loadPaymentMethod(this._methodId)).getPaymentMethodOrThrow(this._methodId)),!r.clientToken||!r.initializationData)throw new ti(Xn.MissingPaymentMethod);return this._braintreeSdk.initialize(r.clientToken),this._braintreeGooglePayment=yield this._braintreeSdk.getBraintreeGooglePayment(),Promise.resolve()})}getNonce(e){const t=Object.create(null,{getNonce:{get:()=>super.getNonce},getPaymentMethod:{get:()=>super.getPaymentMethod}});var n;return Wa(this,void 0,void 0,function*(){const i=yield t.getNonce.call(this,e),{clientToken:r,initializationData:o}=t.getPaymentMethod.call(this);if(!r||!o||!(null===(n=o.card_information)||void 0===n?void 0:n.bin))throw new ti(Xn.MissingPaymentMethod);const{isThreeDSecureEnabled:a,card_information:{bin:s,isNetworkTokenized:d}}=o;if(a&&!d){const e=yield this._braintreeSdk.getBraintreeThreeDS(),{orderAmount:t}=this._service.getState().getOrderOrThrow();return(yield this._braintreePresent3DSChallenge(e,t,i,s)).nonce}return i})}extraPaymentData(){return Wa(this,void 0,void 0,function*(){return{deviceSessionId:yield this._getBraintreeDeviceData()}})}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return Wa(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);let i;try{i=JSON.parse(n.nonce)}catch(e){throw new fi("Unable to parse response from Google Pay.")}return function(e){if(!function(e){return"object"==typeof e&&null!==e&&"androidPayCards"in e}(e))throw new ti(Xn.MissingPaymentToken)}(i),n.nonce=i.androidPayCards[0].nonce,n.card_information.bin=i.androidPayCards[0].details.bin,n.card_information.isNetworkTokenized=i.androidPayCards[0].details.isNetworkTokenized,n})}getCardParameters(){return super.getCardParameters()}getPaymentGatewayParameters(){const e=Object.create(null,{getMerchantInfo:{get:()=>super.getMerchantInfo},getTransactionInfo:{get:()=>super.getTransactionInfo},getRequiredData:{get:()=>super.getRequiredData}});return Wa(this,void 0,void 0,function*(){return this.getBraintreeGooglePayment().createPaymentDataRequest(Object.assign({merchantInfo:e.getMerchantInfo.call(this),transactionInfo:e.getTransactionInfo.call(this),cardRequirements:{billingAddressRequired:!0,billingAddressFormat:"FULL"}},yield e.getRequiredData.call(this))).paymentMethodTokenizationParameters.parameters})}getBraintreeGooglePayment(){if(!this._braintreeGooglePayment)throw new ti(Xn.MissingPaymentMethod);return this._braintreeGooglePayment}_getBraintreeDeviceData(){return Wa(this,void 0,void 0,function*(){const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e})}_braintreePresent3DSChallenge(e,t,n,i){return new En(e.verifyCard({amount:t,bin:i,nonce:n,onLookupComplete:(e,t)=>{t()}})).promise}}const Ya=vi(e=>{const t=n(),i=window,r=new Ei(e),o=new Ui(new Hi(a(),i,r));return new ra(e,new aa(da(),new $a(e,o),t,Ee()))},[{id:"googlepaybraintree"}]),Ka={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},Ja=["ar_BH","ar_DZ","ar_EG","ar_JO","ar_KW","ar_MA","ar_OM","ar_QA","ar_SA","ar_TN","ar_YE","ar_AE","bg_BG","cs_CZ","da_DK","da_FO","da_GL","de_AT","de_CH","de_DE","de_LU","el_GR","en_AD","en_AE","en_AG","en_AI","en_AL","en_AM","en_AN","en_AO","en_AT","en_AU","en_AW","en_AZ","en_BB","en_BE","en_BH","en_BJ","en_BM","en_BN","en_BS","en_BT","en_BW","en_BY","en_BZ","en_C2","en_CA","en_CD","en_CG","en_CH","en_CI","en_CK","en_CL","en_CM","en_CN","en_CO","en_CR","en_CV","en_CY","en_CZ","en_DE","en_DJ","en_DK","en_DM","en_DO","en_DZ","en_EC","en_EE","en_EG","en_ER","en_ES","en_ET","en_FI","en_FJ","en_FK","en_FM","en_FO","en_FR","en_GA","en_GB","en_GD","en_GE","en_GF","en_GI","en_GL","en_GM","en_GN","en_GP","en_GR","en_GT","en_GW","en_GY","en_HK","en_HN","en_HR","en_HU","en_ID","en_IE","en_IL","en_IN","en_IS","en_IT","en_JM","en_JO","en_JP","en_KE","en_KG","en_KH","en_KI","en_KM","en_KN","en_KR","en_KW","en_KY","en_KZ","en_LA","en_LC","en_LI","en_LK","en_LS","en_LT","en_LU","en_LV","en_MA","en_MC","en_MD","en_ME","en_MG","en_MH","en_MK","en_ML","en_MN","en_MQ","en_MR","en_MS","en_MT","en_MU","en_MV","en_MW","en_MY","en_MZ","en_NA","en_NC","en_NE","en_NF","en_NG","en_NI","en_NL","en_NO","en_NP","en_NR","en_NU","en_NZ","en_OM","en_PA","en_PE","en_PF","en_PG","en_PH","en_PL","en_PM","en_PN","en_PT","en_PW","en_PY","en_QA","en_RE","en_RO","en_RS","en_RU","en_RW","en_SA","en_SB","en_SC","en_SE","en_SG","en_SH","en_SI","en_SJ","en_SK","en_SL","en_SM","en_SN","en_SO","en_SR","en_ST","en_SV","en_SZ","en_TC","en_TD","en_TG","en_TH","en_TJ","en_TM","en_TN","en_TO","en_TR","en_TT","en_TV","en_TW","en_TZ","en_UA","en_UG","en_US","en_UY","en_VA","en_VC","en_VE","en_VG","en_VN","en_VU","en_WF","en_WS","en_YE","en_YT","en_ZA","en_ZM","en_ZW","es_AD","es_AI","es_AO","es_AR","es_AW","es_BB","es_BJ","es_BM","es_BO","es_BS","es_BZ","es_CD","es_CG","es_CK","es_CL","es_CO","es_CR","es_CV","es_DJ","es_DM","es_DO","es_DZ","es_EC","es_EG","es_ER","es_ES","es_ET","es_FJ","es_FK","es_FO","es_GA","es_GD","es_GE","es_GI","es_GL","es_GM","es_GN","es_GT","es_GW","es_GY","es_HN","es_IE","es_JM","es_JO","es_KE","es_KG","es_KI","es_KM","es_KN","es_KW","es_KY","es_KZ","es_LC","es_LI","es_LS","es_LU","es_MA","es_MG","es_MH","es_ML","es_MR","es_MS","es_MU","es_MW","es_MX","es_MZ","es_NA","es_NC","es_NE","es_NF","es_NI","es_NR","es_NU","es_NZ","es_OM","es_PA","es_PE","es_PF","es_PG","es_PM","es_PN","es_PW","es_PY","es_QA","es_RS","es_RW","es_SA","es_SB","es_SC","es_SH","es_SJ","es_SL","es_SM","es_SN","es_SO","es_SR","es_ST","es_SV","es_SZ","es_TC","es_TD","es_TG","es_TJ","es_TM","es_TN","es_TT","es_TV","es_UA","es_UG","es_US","es_UY","es_VA","es_VC","es_VE","es_VG","es_VU","es_WF","es_YE","es_ZM","et_EE","fi_FI","fr_AD","fr_AE","fr_AI","fr_AM","fr_AO","fr_AW","fr_AZ","fr_BB","fr_BE","fr_BF","fr_BI","fr_BJ","fr_BM","fr_BS","fr_BZ","fr_CA","fr_CD","fr_CG","fr_CH","fr_CI","fr_CK","fr_CM","fr_CV","fr_DJ","fr_DM","fr_DO","fr_DZ","fr_EC","fr_ER","fr_ET","fr_FJ","fr_FK","fr_FO","fr_FR","fr_GA","fr_GD","fr_GE","fr_GF","fr_GI","fr_GL","fr_GM","fr_GN","fr_GP","fr_GT","fr_GW","fr_GY","fr_HN","fr_IE","fr_JM","fr_JO","fr_KE","fr_KG","fr_KI","fr_KM","fr_KN","fr_KW","fr_KY","fr_KZ","fr_LC","fr_LI","fr_LS","fr_LU","fr_MA","fr_MC","fr_MG","fr_MH","fr_ML","fr_MQ","fr_MR","fr_MS","fr_MU","fr_MW","fr_MZ","fr_NA","fr_NC","fr_NE","fr_NF","fr_NI","fr_NR","fr_NU","fr_NZ","fr_OM","fr_PA","fr_PE","fr_PF","fr_PG","fr_PM","fr_PN","fr_PW","fr_QA","fr_RE","fr_RS","fr_RW","fr_SA","fr_SB","fr_SC","fr_SH","fr_SJ","fr_SL","fr_SM","fr_SN","fr_SO","fr_SR","fr_ST","fr_SV","fr_SZ","fr_TC","fr_TD","fr_TG","fr_TJ","fr_TM","fr_TN","fr_TT","fr_TV","fr_UA","fr_UG","fr_US","fr_UY","fr_VA","fr_VC","fr_VE","fr_VG","fr_VU","fr_WF","fr_YE","fr_YT","fr_ZA","fr_ZM","he_IL","hu_HU","id_ID","it_IT","ja_JP","ko_KR","lv_LV","lt_LT","ms_BN","ms_MY","nl_BE","nl_NL","pl_PL","pt_BR","pt_PT","ro_RO","ru_EE","ru_LT","ru_LV","ru_RU","ru_UA","si_LK","sk_SK","sl_SI","sq_AL","sv_SE","tl_PH","th_TH","tr_TR","vi_VN","zh_C2","zh_CN","zh_HK","zh_TW","zh_AD","zh_AE","zh_AI","zh_AO","zh_AW","zh_BB","zh_BH","zh_BJ","zh_BM","zh_BS","zh_BZ","zh_CD","zh_CG","zh_CK","zh_CL","zh_CO","zh_CV","zh_DJ","zh_DM","zh_DO","zh_DZ","zh_EC","zh_EG","zh_ER","zh_ET","zh_FJ","zh_FK","zh_FO","zh_GA","zh_GD","zh_GE","zh_GI","zh_GL","zh_GM","zh_GN","zh_GT","zh_GW","zh_GY","zh_HN","zh_IE","zh_JM","zh_JO","zh_KE","zh_KG","zh_KI","zh_KM","zh_KN","zh_KW","zh_KY","zh_KZ","zh_LC","zh_LI","zh_LS","zh_LT","zh_LU","zh_MA","zh_MG","zh_MH","zh_ML","zh_MR","zh_MS","zh_MU","zh_MW","zh_MZ","zh_NA","zh_NC","zh_NE","zh_NF","zh_NI","zh_NR","zh_NU","zh_NZ","zh_OM","zh_PA","zh_PE","zh_PF","zh_PG","zh_PM","zh_PN","zh_PW","zh_QA","zh_RS","zh_RW","zh_SA","zh_SB","zh_SC","zh_SH","zh_SJ","zh_SL","zh_SM","zh_SN","zh_SO","zh_SR","zh_ST","zh_SV","zh_SZ","zh_TC","zh_TD","zh_TG","zh_TJ","zh_TM","zh_TN","zh_TT","zh_TV","zh_UA","zh_UG","zh_US","zh_UY","zh_VA","zh_VC","zh_VE","zh_VG","zh_VU","zh_WF","zh_YE","zh_ZA","zh_ZM"];function Za(e){if(!e)return;let t;if(e.includes("-")){const[n,i]=e.split("-");t=`${n}_${i.toUpperCase()}`}else t=`${e}_${e.toUpperCase()}`;return Ja.includes(t)?t:void 0}var Qa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Xa{constructor(e){this.scriptLoader=e,this.window=window}getPayPalFastlaneSdk(e,t,n,i){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const r=this.getPayPalFastlaneSdkConfiguration(e,t,n,i);if(yield this.loadPayPalSdk(r),!this.window.paypalFastlaneSdk)throw new mi}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,n,i,r){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||r){const r=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i);yield this.loadPayPalSdk(r)}if(!this.window.paypalGooglePay)throw new mi;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t,n){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t,n);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new mi}return this.window.paypalApms})}getPayPalMessages(e,t,n){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t,n);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new mi;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return Qa(this,void 0,void 0,function*(){const n=this.transformConfig(e),i=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(n).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:i})})}getPayPalFastlaneSdkConfiguration(e,t,n,i){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,attributionId:c}=o,l=Za(i);return{options:Object.assign({"client-id":s,"merchant-id":d,commit:!0,components:["fastlane","buttons","payment-fields","hosted-fields","three-domain-secure"],currency:t,intent:a},l&&{locale:l}),attributes:{"data-client-metadata-id":n.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":c,"data-sdk-client-token":r}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i=!0){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:c,attributionId:l,isHostedCheckoutEnabled:u,isDeveloperModeApplicable:h}=o,p=u||i,m=Za(n);return{options:Object.assign(Object.assign({"client-id":s,"merchant-id":d,commit:p,components:["googlepay"],currency:t,intent:a},h&&{"buyer-country":c}),m&&{locale:m}),attributes:{"data-partner-attribution-id":l,"data-client-token":r,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:r,clientId:o,merchantId:a,buyerCountry:s,attributionId:d,isDeveloperModeApplicable:c,availableAlternativePaymentMethods:l=[],enabledAlternativePaymentMethods:u=[]}=i,h=u,p=l.filter(e=>!u.includes(e)),m=Za(n);return{options:Object.assign(Object.assign({"client-id":o,"merchant-id":a,"enable-funding":h.length>0?h:void 0,"disable-funding":p.length>0?p:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:r},c&&{"buyer-country":s}),m&&{locale:m}),attributes:{"data-partner-attribution-id":d,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ti(Xn.MissingPaymentMethod);const{clientId:r,merchantId:o,attributionId:a,isDeveloperModeApplicable:s,buyerCountry:d}=i,c=Za(n);return{options:Object.assign(Object.assign({"client-id":r,"merchant-id":o,components:["messages"],currency:t},s&&{"buyer-country":d}),c&&{locale:c}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":a}}}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}function es(e){if(!function(e){return!!e.initializationData&&"attributionId"in e.initializationData&&"isVenmoEnabled"in e.initializationData&&"isGooglePayEnabled"in e.initializationData&&"isPayPalCreditAvailable"in e.initializationData}(e))throw new ti(Xn.MissingPaymentMethod)}var ts=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ns extends ea{constructor(e,t){super("paypalsb",e),this.payPalCommerceSdk=t,this.service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});var r,o,a,s,d;return ts(this,void 0,void 0,function*(){const c=this.service.getState(),l=null!==(o=null===(r=c.getStoreConfig())||void 0===r?void 0:r.currency.code)&&void 0!==o?o:n;if(!l)throw new ti(Xn.MissingPaymentMethod);yield i.initialize.call(this,e,t,l);const u=i.getPaymentMethod.call(this);if(!u.initializationData)throw new ti(Xn.MissingPaymentMethod);es(u);const h=yield this.payPalCommerceSdk.getPayPalGooglePaySdk(u,l,c.getLocale());this.googlepayConfig=yield h.Googlepay().config();const{allowedPaymentMethods:p}=this.googlepayConfig;this.setGatewayIdentifier(null===(d=null===(s=null===(a=p[0])||void 0===a?void 0:a.tokenizationSpecification)||void 0===s?void 0:s.parameters)||void 0===d?void 0:d.gateway)})}getPaymentGatewayParameters(){if(this.googlepayConfig){const{allowedPaymentMethods:e}=this.googlepayConfig,{gatewayMerchantId:t}=e[0].tokenizationSpecification.parameters;return{gateway:this.getGatewayIdentifier(),gatewayMerchantId:t}}return{gateway:this.getGatewayIdentifier()}}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ts(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n})}}const is=vi(e=>new ra(e,new aa(da(),new ns(e,new Xa(a())),n(),Ee())),[{id:"googlepaypaypalcommerce"}]);var rs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class os extends ea{constructor(e,t){super("googlepay_bigcommerce_payments",e),this.payPalSdkHelper=t,this.service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});var r,o,a,s,d;return rs(this,void 0,void 0,function*(){const c=null!==(o=null===(r=this.service.getState().getStoreConfig())||void 0===r?void 0:r.currency.code)&&void 0!==o?o:n;if(!c)throw new ti(Xn.MissingPaymentMethod);yield i.initialize.call(this,e,t,c);const l=i.getPaymentMethod.call(this);if(!l.initializationData)throw new ti(Xn.MissingPaymentMethod);es(l);const u=yield this.payPalSdkHelper.getPayPalGooglePaySdk(l,c);this.googlepayConfig=yield u.Googlepay().config();const{allowedPaymentMethods:h}=this.googlepayConfig;this.setGatewayIdentifier(null===(d=null===(s=null===(a=h[0])||void 0===a?void 0:a.tokenizationSpecification)||void 0===s?void 0:s.parameters)||void 0===d?void 0:d.gateway)})}getPaymentGatewayParameters(){if(this.googlepayConfig){const{allowedPaymentMethods:e}=this.googlepayConfig,{gatewayMerchantId:t}=e[0].tokenizationSpecification.parameters;return{gateway:this.getGatewayIdentifier(),gatewayMerchantId:t}}return{gateway:this.getGatewayIdentifier()}}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return rs(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n})}}const as=vi(e=>new ra(e,new aa(da(),new os(e,new xr(a())),n(),Ee())),[{id:"googlepay_bigcommerce_payments"}]);function ss(){const{navigator:e}=window;let t;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 ds=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class cs extends ea{constructor(e,t){super("worldlinena",e),this.formPoster=t}extraPaymentData(){return ds(this,void 0,void 0,function*(){return Promise.resolve({browser_info:ss()})})}processAdditionalAction(e){return ds(this,void 0,void 0,function*(){if(!function(e){return pa(e)&&(t=e.body,Z(t)&&"object"==typeof t&&"errors"in t&&"three_ds_result"in t&&W(t.errors)&&ve(t.errors,{code:"three_d_secure_required"}));var t}(e))throw e;const{three_ds_result:t}=e.body,{acs_url:n,payer_auth_request:i,merchant_data:r}=t||{};if(!n||!i||!r)throw new co(["formUrl","threeDSSessionData","creq"]);return new Promise(e=>{this.formPoster.postForm(n,{threeDSSessionData:i,creq:r},e,"_top")})})}}const ls=vi(e=>new ra(e,new aa(da(),new cs(e,Ee()),n(),Ee())),[{id:"googlepaytdonlinemart"}]);var us,hs,ps,ms,ys,gs,vs,fs,Ss,_s,ws=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Is{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,n,i,r){return ws(this,void 0,void 0,function*(){if(!this.window.paypal||r){const r=this.getPayPalSdkScriptConfigOrThrow(e,t,n,i);if(yield this.loadPayPalSdk(r),!this.window.paypal)throw new mi}return this.window.paypal})}getPayPalFastlaneSdk(e,t,n,i){return ws(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const r=this.getPayPalFastlaneSdkConfiguration(e,t,n,i);if(yield this.loadPayPalSdk(r),!this.window.paypalFastlaneSdk)throw new mi}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,n,i,r){return ws(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||r){const r=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i);yield this.loadPayPalSdk(r)}if(!this.window.paypalGooglePay)throw new mi;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t,n){return ws(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t,n);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new mi}return this.window.paypalApms})}getPayPalMessages(e,t,n){return ws(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t,n);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new mi;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return ws(this,void 0,void 0,function*(){const n=this.transformConfig(e),i=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(n).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:i})})}getPayPalSdkScriptConfigOrThrow(e,t,n,i=!0){const{id:r,clientToken:o,initializationData:a}=e;if(!a||!a.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:s,clientId:d,merchantId:c,buyerCountry:l,attributionId:u,isVenmoEnabled:h,isHostedCheckoutEnabled:p,isPayPalCreditAvailable:m,isDeveloperModeApplicable:y,availableAlternativePaymentMethods:g=[],enabledAlternativePaymentMethods:v=[],isGooglePayEnabled:f}=a,S=p||i,_="paypalcommercecreditcards"===r||"bigcommerce_payments_creditcards"===r,w=_?["card"]:[],I=m?["credit","paylater"]:[],C=h?["venmo"]:[],b=f?["googlepay"]:[],P=i?["card-fields"]:[],O=[..._?[]:["card"],...m?[]:["credit","paylater"],...h?[]:["venmo"],...g.filter(e=>!v.includes(e))],E=[...w,...I,...C,...v],A=Za(n);return{options:Object.assign(Object.assign({"client-id":d,"merchant-id":c,"enable-funding":E.length>0?E:void 0,"disable-funding":O.length>0?O:void 0,commit:S,components:["buttons","hosted-fields","payment-fields","legal",...b,...P],currency:t,intent:s},y&&{"buyer-country":l}),A&&{locale:A}),attributes:{"data-partner-attribution-id":u,"data-client-token":o}}}getPayPalFastlaneSdkConfiguration(e,t,n,i){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,attributionId:c}=o,l=Za(i);return{options:Object.assign(Object.assign({"client-id":s,"merchant-id":d,commit:!0,components:["fastlane","buttons","payment-fields","hosted-fields","three-domain-secure"],currency:t},l&&{locale:l}),{intent:a}),attributes:{"data-client-metadata-id":n.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":c,"data-sdk-client-token":r}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i=!0){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:c,attributionId:l,isHostedCheckoutEnabled:u,isDeveloperModeApplicable:h}=o,p=u||i,m=Za(n);return{options:Object.assign(Object.assign({"client-id":s,"merchant-id":d,commit:p,components:["googlepay"],currency:t,intent:a},h&&{"buyer-country":c}),m&&{locale:m}),attributes:{"data-partner-attribution-id":l,"data-client-token":r,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:r,clientId:o,merchantId:a,buyerCountry:s,attributionId:d,isDeveloperModeApplicable:c,availableAlternativePaymentMethods:l=[],enabledAlternativePaymentMethods:u=[]}=i,h=u,p=l.filter(e=>!u.includes(e)),m=Za(n);return{options:Object.assign(Object.assign({"client-id":o,"merchant-id":a,"enable-funding":h.length>0?h:void 0,"disable-funding":p.length>0?p:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:r},c&&{"buyer-country":s}),m&&{locale:m}),attributes:{"data-partner-attribution-id":d,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ti(Xn.MissingPaymentMethod);const{clientId:r,merchantId:o,attributionId:a,isDeveloperModeApplicable:s,buyerCountry:d}=i,c=Za(n);return{options:Object.assign(Object.assign({"client-id":r,"merchant-id":o,components:["messages"],currency:t},s&&{"buyer-country":d}),c&&{locale:c}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":a}}}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}function Cs(){return new Is(a())}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(us||(us={})),(hs||(hs={})).Always="SCA_ALWAYS",function(e){e.Succeeded="succeeded",e.Cancelled="cancelled",e.Errored="errored"}(ps||(ps={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(ms||(ms={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(ys||(ys={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(gs||(gs={})),function(e){e.pill="pill",e.rect="rect"}(vs||(vs={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="canceled",e.UNRECOGNIZED="unrecognized"}(fs||(fs={})),(Ss||(Ss={})).OXXO="oxxo",function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(_s||(_s={}));var bs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ps{constructor(e,t,n,i){this.formPoster=e,this.paymentIntegrationService=t,this.paypalRequestSender=n,this.paypalSdkLoader=i}loadPayPalSdk(e,t,n,i){return bs(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e),s=r.getLocale();return this.paypalSdk=yield this.paypalSdkLoader.getPayPalSDK(a,o,s,n,i),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new mi;return this.paypalSdk}createBuyNowCartOrThrow(e){return bs(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}})}createOrder(e,t){return bs(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i}=yield this.paypalRequestSender.createOrder(e,Object.assign({cartId:n},t));return i})}createOrderCardFields(e,t){return bs(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i,setupToken:r}=yield this.paypalRequestSender.createOrder(e,Object.assign({cartId:n},t));return Object.assign({orderId:i},r?{setupToken:r}:{})})}updateOrder(e,t,n){return bs(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),r=i.getCartOrThrow(),o=i.getConsignmentsOrThrow()[0];try{yield this.paypalRequestSender.updateOrder(e,Object.assign(Object.assign({availableShippingOptions:o.availableShippingOptions,cartId:r.id,selectedShippingOption:o.selectedShippingOption},t?{methodId:t}:{}),n?{orderId:n}:{}))}catch(e){throw new nr}})}getOrderStatus(e,t){return bs(this,void 0,void 0,function*(){try{const{status:n}=yield this.paypalRequestSender.getOrderStatus(e,t);return n}catch(e){throw new nr}})}tokenizePayment(e,t){const n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new ti(Xn.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===xt.BuyNow&&{cart_id:n.id}))}submitPayment(e,t,n){return bs(this,void 0,void 0,function*(){const i={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}};yield this.paymentIntegrationService.submitPayment(Object.assign({methodId:e,paymentData:i},n?{gatewayId:n}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],i=n.find(e=>e.isRecommended),r=(e?n.find(t=>t.id===e):n.find(e=>{if(t.selectedShippingOption){const n=t.selectedShippingOption.id;return e.id===n}return!1}))||i||n[0];if(!r)throw new Error("Your order can't be shipped to this address");return r}getAddress(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:(null==e?void 0:e.phone)||"",company:"",address1:(null==e?void 0:e.address1)||"",address2:(null==e?void 0:e.address2)||"",city:(null==e?void 0:e.city)||"",countryCode:(null==e?void 0:e.countryCode)||"",postalCode:(null==e?void 0:e.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==e?void 0:e.stateOrProvinceCode)||"",customFields:[]}}getBillingAddressFromOrderDetails({payer:e}){var t,n;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,address2:e.address.address_line_2,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1,phone:null===(n=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===n?void 0:n.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:n}=e,{address:i,name:{full_name:r}}=n[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:i.address_line_1,address2:i.address_line_2,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})}getValidButtonStyle(e={}){const{color:t,height:n,label:i,shape:r}=e,o={color:t&&gs[t]?t:void 0,height:this.getValidHeight(n),label:i&&ys[i]?i:void 0,shape:r&&vs[r]?r:void 0};return ue(o,J)}getValidHeight(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40}removeElement(e){const t=e&&document.getElementById(e);t&&(t.style.display="none")}}var Os=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Es{constructor(e){this.requestSender=e}createOrder(e,t){return Os(this,void 0,void 0,function*(){const n=`/api/storefront/payment/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.post(n,{headers:r,body:i})).body})}updateOrder(e,t){return Os(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.put(n,{headers:r,body:i})).body})}getOrderStatus(e,t){return Os(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body})}}const As=e=>{const{getHost:t}=e.getState();return new Ps(Ee(),e,new Es(n({host:t()})),Cs())};var Ts=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const ks=class{constructor(e,t){this.paymentIntegrationService=e,this.paypalIntegrationService=t}createPayPalButton(e,t,n,i){const{style:r,fundingSource:o,isAppSwitchEnabled:a,isHostedCheckoutEnabled:s,onClick:d,onCancel:c,onPaymentComplete:l,onError:u}=n;this.onError=u;const h=this.paypalIntegrationService.getPayPalSdkOrThrow();if(!Object.values(h.FUNDING).includes(o))throw new fi('Unable to initialize PayPal button because "fundingSource" argument is not valid funding source.');const p=Object.assign(Object.assign({},!a&&{onShippingAddressChange:t=>this.onShippingAddressChange(t,e),onShippingOptionsChange:t=>this.onShippingOptionsChange(t,e)}),{onApprove:(n,i)=>this.onHostedCheckoutApprove(n,i,t,e,l)});return h.Buttons(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({fundingSource:o,style:this.paypalIntegrationService.getValidButtonStyle(r)},a&&{appSwitchWhenAvailable:!0}),{createOrder:()=>Ts(this,void 0,void 0,function*(){if(i){const e=yield this.paypalIntegrationService.createBuyNowCartOrThrow(i);yield this.paymentIntegrationService.loadCheckout(e.id)}return this.paypalIntegrationService.createOrder(e)}),onApprove:({orderID:e})=>this.paypalIntegrationService.tokenizePayment(t,e)}),d?{onClick:d}:{}),c?{onCancel:c}:{}),s&&p))}onHostedCheckoutApprove(e,t,n,i,r){return Ts(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const o=this.paymentIntegrationService.getState().getCartOrThrow(),a=yield t.order.get();try{const t=this.paypalIntegrationService.getBillingAddressFromOrderDetails(a);if(yield this.paymentIntegrationService.updateBillingAddress(t),o.lineItems.physicalItems.length>0){const e=this.paypalIntegrationService.getShippingAddressFromOrderDetails(a);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.paypalIntegrationService.updateOrder(i)}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.paypalIntegrationService.submitPayment(n,e.orderID),r&&"function"==typeof r&&r()}catch(e){this.handleError(e)}})}onShippingAddressChange(e,t){return Ts(this,void 0,void 0,function*(){const n=this.paypalIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(n),yield this.paymentIntegrationService.updateShippingAddress(n);const e=this.paypalIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.paypalIntegrationService.updateOrder(t)}catch(e){this.handleError(e)}})}onShippingOptionsChange(e,t){return Ts(this,void 0,void 0,function*(){const n=this.paypalIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(n.id),yield this.paypalIntegrationService.updateOrder(t)}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}};var Ds=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ms{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.paypalButtonCreationService=n}initialize(e){return Ds(this,void 0,void 0,function*(){const{paypalcommerce:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.paypalcommerce.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.paypalcommerce.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.paypalIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Ds(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return Ds(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){var n,i;const{container:r,onClick:o,onComplete:a,onError:s}=t,d=this.paypalIntegrationService.getPayPalSdkOrThrow(),c=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:l,paymentButtonStyles:u,isAppSwitchEnabled:h}=c.initializationData||{},{checkoutTopButtonStyles:p}=u||{},m=Object.assign(Object.assign(Object.assign({fundingSource:d.FUNDING.PAYPAL,isAppSwitchEnabled:h,isHostedCheckoutEnabled:l,style:Object.assign(Object.assign({},p),{height:wr})},o&&{onClick:()=>o()}),l&&a&&{onPaymentComplete:()=>a()}),{onError:s}),y=this.paypalButtonCreationService.createPayPalButton("paypalcommerce",e,m);y.isEligible()?(null===(n=y.hasReturned)||void 0===n?void 0:n.call(y))&&h?null===(i=y.resume)||void 0===i||i.call(y):y.render(`#${r}`):this.paypalIntegrationService.removeElement(r)}}const zs=vi(e=>{const t=As(e),n=new ks(e,t);return new Ms(e,t,n)},[{id:"paypalcommerce"}]);var Ns,xs,Rs,Fs,Ls,Bs,js;!function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(Ns||(Ns={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(xs||(xs={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Rs||(Rs={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(Fs||(Fs={})),function(e){e.pill="pill",e.rect="rect"}(Ls||(Ls={})),function(e){e.OXXO="oxxo",e.IDEAL="ideal"}(Bs||(Bs={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(js||(js={}));var Us=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class qs{constructor(e,t,n,i){this.formPoster=e,this.paymentIntegrationService=t,this.paypalCommerceRequestSender=n,this.paypalCommerceScriptLoader=i}loadPayPalSdk(e,t,n,i){return Us(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e);return this.paypalSdk=yield this.paypalCommerceScriptLoader.getPayPalSDK(a,o,r.getLocale(),n,i),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new mi;return this.paypalSdk}createBuyNowCartOrThrow(e){return Us(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}})}createOrder(e,t){return Us(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i}=yield this.paypalCommerceRequestSender.createOrder(e,Object.assign({cartId:n},t));return i})}createOrderCardFields(e,t){return Us(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i,setupToken:r}=yield this.paypalCommerceRequestSender.createOrder(e,Object.assign({cartId:n},t));return Object.assign({orderId:i},r?{setupToken:r}:{})})}updateOrder(){return Us(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getConsignmentsOrThrow()[0];try{yield this.paypalCommerceRequestSender.updateOrder({availableShippingOptions:n.availableShippingOptions,cartId:t.id,selectedShippingOption:n.selectedShippingOption})}catch(e){throw new nr}})}getOrderStatus(e,t){return Us(this,void 0,void 0,function*(){try{const{status:n}=yield this.paypalCommerceRequestSender.getOrderStatus(e,t);return n}catch(e){throw new nr}})}tokenizePayment(e,t){const n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new ti(Xn.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===xt.BuyNow&&{cart_id:n.id}))}submitPayment(e,t,n){return Us(this,void 0,void 0,function*(){const i={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}};yield this.paymentIntegrationService.submitPayment(Object.assign({methodId:e,paymentData:i},n?{gatewayId:n}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],i=n.find(e=>e.isRecommended),r=(e?n.find(t=>t.id===e):n.find(e=>{var n;return e.id===(null===(n=t.selectedShippingOption)||void 0===n?void 0:n.id)}))||i||n[0];if(!r)throw new Error("Your order can't be shipped to this address");return r}getAddress(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:(null==e?void 0:e.phone)||"",company:"",address1:(null==e?void 0:e.address1)||"",address2:(null==e?void 0:e.address2)||"",city:(null==e?void 0:e.city)||"",countryCode:(null==e?void 0:e.countryCode)||"",postalCode:(null==e?void 0:e.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==e?void 0:e.stateOrProvinceCode)||"",customFields:[]}}getBillingAddressFromOrderDetails({payer:e}){var t,n;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,address2:e.address.address_line_2,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1,phone:null===(n=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===n?void 0:n.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:n}=e,{address:i,name:{full_name:r}}=n[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:i.address_line_1,address2:i.address_line_2,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})}getValidButtonStyle(e){const{color:t,height:n,label:i,shape:r}=e||{},o={color:t&&Fs[t]?t:void 0,height:this.getValidHeight(n),label:i&&Rs[i]?i:void 0,shape:r&&Ls[r]?r:void 0};return ue(o,J)}getValidHeight(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40}removeElement(e){const t=e&&document.getElementById(e);t&&(t.style.display="none")}}var Vs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Gs{constructor(e){this.requestSender=e}createOrder(e,t){return Vs(this,void 0,void 0,function*(){const n=`/api/storefront/payment/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.post(n,{headers:r,body:i})).body})}updateOrder(e){return Vs(this,void 0,void 0,function*(){const t=e,n=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.put("/api/storefront/initialization/paypalcommerce",{headers:n,body:t})).body})}getOrderStatus(e="paypalcommerce",t){return Vs(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body})}}var Hs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ws{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,n,i,r){return Hs(this,void 0,void 0,function*(){const o=this.getPayPalSdkScriptConfigOrThrow(e,t,n,i);return this.loadPayPalSDK(o,r)})}loadPayPalSDK(e,t=!1){return Hs(this,void 0,void 0,function*(){if(!this.window.paypal||t){const t=this.transformConfig(e.options),n=this.transformConfig(e.attributes),i=`https://www.paypal.com/sdk/js?${new URLSearchParams(t).toString()}`;yield this.scriptLoader.loadScript(i,{async:!0,attributes:n})}if(!this.window.paypal)throw new mi;return this.window.paypal})}getPayPalSdkScriptConfigOrThrow(e,t,n,i=!0){const{id:r,clientToken:o,initializationData:a}=e;if(!(null==a?void 0:a.clientId))throw new ti(Xn.MissingPaymentMethod);const{intent:s,clientId:d,merchantId:c,buyerCountry:l,attributionId:u,isVenmoEnabled:h,isHostedCheckoutEnabled:p,isPayPalCreditAvailable:m,isDeveloperModeApplicable:y,availableAlternativePaymentMethods:g=[],enabledAlternativePaymentMethods:v=[],isGooglePayEnabled:f}=a,S=p||i,_="paypalcommercecreditcards"===r,w=_?["card"]:[],I=m?["credit","paylater"]:[],C=h?["venmo"]:[],b=f?["googlepay"]:[],P=i?["card-fields"]:[],O=[..._?[]:["card"],...m?[]:["credit","paylater"],...h?[]:["venmo"],...g.filter(e=>!v.includes(e))],E=[...w,...I,...C,...v],A=Za(n);return{options:Object.assign(Object.assign({"client-id":d,"merchant-id":c,"enable-funding":E.length>0?E:void 0,"disable-funding":O.length>0?O:void 0,commit:S,components:["buttons","hosted-fields","payment-fields","legal",...b,...P],currency:t,intent:s},y&&{"buyer-country":l}),A&&{locale:A}),attributes:{"data-partner-attribution-id":u,"data-client-token":o}}}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}const $s=e=>{const{getHost:t}=e.getState();return new qs(Ee(),e,new Gs(n({host:t()})),new Ws(a()))};var Ys=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ks{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.onError=ce}initialize(e){return Ys(this,void 0,void 0,function*(){const{paypalcommercecredit:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.paypalcommercecredit.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.paypalcommercecredit.onClick" argument is not a function.');this.onError=t.onError||ce,this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.paypalCommerceIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Ys(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Ys(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){const{container:n,onComplete:i,onClick:r}=t,o=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:s,paymentButtonStyles:d,isAppSwitchEnabled:c}=a.initializationData||{},{checkoutTopButtonStyles:l}=d||{},u=Object.assign({createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercecredit"),onApprove:({orderID:t})=>this.paypalCommerceIntegrationService.tokenizePayment(e,t)},r&&{onClick:()=>r()}),h=Object.assign(Object.assign({},!c&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(t,n)=>this.onHostedCheckoutApprove(t,n,e,i)}),p=[o.FUNDING.PAYLATER,o.FUNDING.CREDIT];let m=!1;p.forEach(e=>{if(!m){const t=Object.assign(Object.assign({fundingSource:e,style:this.paypalCommerceIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},l),{height:wr}))},u),s&&h),i=o.Buttons(t);i.isEligible()&&(i.render(`#${n}`),m=!0)}}),m||this.paypalCommerceIntegrationService.removeElement(n)}onHostedCheckoutApprove(e,t,n,i){return Ys(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.paypalCommerceIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.paypalCommerceIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Ys(this,void 0,void 0,function*(){const t=this.paypalCommerceIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.paypalCommerceIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}onShippingOptionsChange(e){return Ys(this,void 0,void 0,function*(){const t=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.paypalCommerceIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const Js=vi(e=>new Ks(e,$s(e)),[{id:"paypalcommercecredit"}]);var Zs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Qs{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}initialize(e){return Zs(this,void 0,void 0,function*(){const{paypalcommercevenmo:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.paypalCommerceIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Zs(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Zs(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){const{container:n,onClick:i}=t,r=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:a}=o.initializationData||{},{checkoutTopButtonStyles:s}=a||{},d=Object.assign({fundingSource:r.FUNDING.VENMO,style:this.paypalCommerceIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},s),{height:wr})),createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo"),onApprove:({orderID:t})=>this.paypalCommerceIntegrationService.tokenizePayment(e,t)},i&&{onClick:()=>i()}),c=r.Buttons(d);c.isEligible()?c.render(`#${n}`):this.paypalCommerceIntegrationService.removeElement(n)}}const Xs=vi(e=>new Qs(e,$s(e)),[{id:"paypalcommercevenmo"}]);var ed=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class td{constructor(){this.window=window}initializePayPalFastlane(e,t,n){return ed(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("fastlaneEnv","sandbox"),window.localStorage.setItem("axoEnv","sandbox")),!this.window.paypalFastlane){const t={root:{backgroundColorPrimary:"transparent"}};this.window.paypalFastlane=yield e.Fastlane({styles:n||t})}return this.window.paypalFastlane})}getPayPalFastlaneOrThrow(){if(!this.window.paypalFastlane)throw new mi;return this.window.paypalFastlane}lookupCustomerOrThrow(e){return ed(this,void 0,void 0,function*(){return this.getPayPalFastlaneOrThrow().identity.lookupCustomerByEmail(e)})}triggerAuthenticationFlowOrThrow(e){return ed(this,void 0,void 0,function*(){return e?this.getPayPalFastlaneOrThrow().identity.triggerAuthenticationFlow(e):{}})}updateStorageSessionId(e){const t=new Date;t.setDate(t.getDate()+14);const n={expires:t,secure:!0};Fr.set("bc-fastlane-sessionId",e,n)}removeStorageSessionId(){Fr.remove("bc-fastlane-sessionId")}getStorageSessionId(){return Fr.get("bc-fastlane-sessionId")||""}mapPayPalFastlaneProfileToBcCustomerData(e,t){var n,i,r;const{authenticationState:o,profileData:a}=t,s=null===(r=null===(i=null===(n=null==a?void 0:a.card)||void 0===n?void 0:n.paymentSource)||void 0===i?void 0:i.card)||void 0===r?void 0:r.billingAddress,d=null==a?void 0:a.shippingAddress,c=null==a?void 0:a.name,l=null==a?void 0:a.card,u=d?this.mapPayPalToBcAddress(d.address,d.name,d.phoneNumber):void 0,h=s&&c?this.mapPayPalToBcAddress(s,c,null==d?void 0:d.phoneNumber):void 0,p=l?this.mapPayPalToBcInstrument(e,l):[],m=this.filterAddresses([u,h]);return{authenticationState:o||fs.UNRECOGNIZED,addresses:m,billingAddress:h,shippingAddress:u,instruments:p}}mapPayPalToBcInstrument(e,t){const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a}=i.card,[s,d]=o.split("-");return[{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:Pr.PAN,type:"card"}]}mapBcToPayPalAddress(e){return{company:(null==e?void 0:e.company)||"",addressLine1:(null==e?void 0:e.address1)||"",addressLine2:(null==e?void 0:e.address2)||"",adminArea1:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",adminArea2:(null==e?void 0:e.city)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||""}}mapPayPalToBcAddress(e,t,n,i){const[r,o]=t.fullName.split(" "),a=(null==n?void 0:n.nationalNumber)||"",s=(null==n?void 0:n.countryCode)||"";return{id:Date.now(),type:"paypal-address",firstName:t.firstName||r||"",lastName:t.lastName||o||"",company:e.company||"",address1:e.addressLine1,address2:e.addressLine2||"",city:e.adminArea2,stateOrProvince:e.adminArea1,stateOrProvinceCode:e.adminArea1,country:e.countryCode||"",countryCode:e.countryCode||"",postalCode:e.postalCode,phone:s+a,customFields:i||[]}}filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this.isEqualAddresses(e,t))?e:[...e,t]:e,[])}isEqualAddresses(e,t){return Y(this.normalizeAddress(e),this.normalizeAddress(t))}normalizeAddress(e){return le(e,["id","phone"])}}function nd(){return new td}function id(e){return"string"!=typeof e}function rd(e,t){if(t||e)return function(e){var t,n;const i={},r=ue(e.root,id),o=ue(e.input,id),a=ue(e.toggle,id),s=ue(null===(t=e.text)||void 0===t?void 0:t.body,id),d=ue(null===(n=e.text)||void 0===n?void 0:n.caption,id),c=e.branding;return Object.keys(r).length&&(i.root=r),Object.keys(o).length&&(i.input=o),Object.keys(a).length&&(i.toggle=a),Object.keys(s).length&&(i.text={},i.text.body=s),Object.keys(d).length&&(i.text=Object.assign({},i.text),i.text.caption=d),c&&(i.branding=c),i}(function(e,t){var n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,_,w,I,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(c=null==t?void 0:t.input)||void 0===c?void 0:c.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.focusBorderColor),backgroundColor:(null==e?void 0:e.fastlaneInputSettingsBackgroundColor)||(null===(u=null==t?void 0:t.input)||void 0===u?void 0:u.backgroundColor),borderWidth:(null==e?void 0:e.fastlaneInputSettingsBorderWidth)||(null===(h=null==t?void 0:t.input)||void 0===h?void 0:h.borderWidth),textColorBase:(null==e?void 0:e.fastlaneInputSettingsTextColorBase)||(null===(p=null==t?void 0:t.input)||void 0===p?void 0:p.textColorBase)},toggle:{colorPrimary:(null==e?void 0:e.fastlaneToggleSettingsColorPrimary)||(null===(m=null==t?void 0:t.toggle)||void 0===m?void 0:m.colorPrimary),colorSecondary:(null==e?void 0:e.fastlaneToggleSettingsColorSecondary)||(null===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(S=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===S?void 0:S.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(w=null===(_=null==t?void 0:t.text)||void 0===_?void 0:_.caption)||void 0===w?void 0:w.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(I=null==t?void 0:t.text)||void 0===I?void 0:I.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var od=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ad{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalSdkScriptLoader=t,this.paypalFastlaneUtils=n}initialize(e){var t;return od(this,void 0,void 0,function*(){const{methodId:n,paypalcommercefastlane:i}=e;if(!n)throw new fi('Unable to proceed because "methodId" argument is not provided.');try{yield this.paymentIntegrationService.loadPaymentMethod(n);const e=this.paymentIntegrationService.getState(),r=e.getCartOrThrow(),o=e.getPaymentMethodOrThrow(n),a=!!(null===(t=o.initializationData)||void 0===t?void 0:t.isDeveloperModeApplicable),s=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(o,r.currency.code,r.id,e.getLocale());yield this.paypalFastlaneUtils.initializePayPalFastlane(s,a,this.getFastlaneStyles(n,i))}catch(e){}return Promise.resolve()})}deinitialize(){return od(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return od(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:void 0,addresses:void 0,instruments:void 0}),this.paypalFastlaneUtils.removeStorageSessionId()})}signOut(e){return od(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return od(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:n,methodId:i}=e||{};if(!i)throw new fi('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof n)throw new fi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(this.paymentIntegrationService.getState().getCustomerOrThrow().isGuest){t&&"function"==typeof t&&t();try{yield this.runPayPalAuthenticationFlowOrThrow(i)}catch(e){}}n()})}runPayPalAuthenticationFlowOrThrow(e){return od(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow().id,i=t.getCustomer(),r=t.getBillingAddress(),o=(null==i?void 0:i.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.paypalFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.paypalFastlaneUtils.triggerAuthenticationFlowOrThrow(a),d=s.authenticationState===fs.CANCELED;yield this.updateCustomerDataState(e,s),d?this.paypalFastlaneUtils.removeStorageSessionId():this.paypalFastlaneUtils.updateStorageSessionId(n)})}updateCustomerDataState(e,t){var n;return od(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow(),{authenticationState:r,addresses:o,billingAddress:a,shippingAddress:s,instruments:d}=this.paypalFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,t);if(yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:r,addresses:o,instruments:d}),a&&(yield this.paymentIntegrationService.updateBillingAddress(a)),s&&i.lineItems.physicalItems.length>0){const t=yield this.paymentIntegrationService.updateShippingAddress(s),i=t.getPaymentMethodOrThrow(e),{isFastlaneShippingOptionAutoSelectEnabled:r}=i.initializationData||{},o=t.getConsignments()||[],a=(null===(n=o[0])||void 0===n?void 0:n.availableShippingOptions)||[],d=a[0],c=a.find(e=>e.isRecommended);if((c||d)&&r){const e=(null==c?void 0:c.id)||d.id;yield this.paymentIntegrationService.selectShippingOption(e)}}})}getFastlaneStyles(e,t){const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{fastlaneStyles:i,isFastlaneStylingEnabled:r}=n.initializationData||{};return rd(r?i:{},null==t?void 0:t.styles)}}const sd=vi(e=>new ad(e,Cs(),nd()),[{id:"paypalcommerceacceleratedcheckout"},{id:"paypalcommercecreditcards"}]);function dd(e){return"object"==typeof e&&null!==e&&"initializationData"in e&&void 0!==e.initializationData&&null!==e.initializationData&&"object"==typeof e.initializationData&&"stripePublishableKey"in e.initializationData&&"stripeConnectedAccount"in e.initializationData&&"shopperLanguage"in e.initializationData&&void 0!==e.initializationData.stripePublishableKey&&void 0!==e.initializationData.stripeConnectedAccount&&void 0!==e.initializationData.shopperLanguage}function cd(e){return"stripeLinkAuthenticationState"in e}class ld{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){var t,n,i,r,o;return n=this,i=void 0,o=function*(){let n;if(!e.stripeupe)throw new fi('Unable to proceed because "options" argument is not provided.');const{container:i,gatewayId:r,methodId:o,onEmailChange:a,getStyles:s,isLoading:d}=e.stripeupe;Object.entries(e.stripeupe).forEach(([e,t])=>{if(!t)throw new fi(`Unable to proceed because "${e}" argument is not provided.`)}),yield this.paymentIntegrationService.loadPaymentMethod(r,{params:{method:o}});const c=this.paymentIntegrationService.getState(),l=c.getPaymentMethodOrThrow(o,r),{clientToken:u}=l;if(!dd(l)||!u)throw new ti(Xn.MissingPaymentToken);const{email:h}=c.getCustomerOrThrow(),p=c.getPaymentProviderCustomerOrThrow(),m=(cd(p)?p:{}).stripeLinkAuthenticationState;if(!h){let e;const r="function"==typeof s&&s();e=r?{variables:{colorPrimary:r.fieldInnerShadow,colorBackground:r.fieldBackground,colorText:r.labelText,colorDanger:r.fieldErrorText,colorTextSecondary:r.labelText,colorTextPlaceholder:r.fieldPlaceholderText},rules:{".Input":{borderColor:r.fieldBorder,color:r.fieldText,boxShadow:r.fieldInnerShadow}}}:{},n=yield this.scriptLoader.getStripeClient(l.initializationData,c.getCartLocale(),ka.V3,Fa,La),this._stripeElements=yield this.scriptLoader.getElements(n,{clientSecret:u,appearance:e});const{getBillingAddress:o,getConsignments:h}=this.paymentIntegrationService.getState(),p=h(),y=null===(t=null==p?void 0:p[0])||void 0===t?void 0:t.id,{email:g}=o()||{},v=g?{defaultValues:{mode:Ca.SHIPPING,email:g}}:{},f=this._stripeElements.getElement(Da.AUTHENTICATION)||this._stripeElements.create(Da.AUTHENTICATION,v);f.on(za.CHANGE,e=>{if(!("authenticated"in e))throw new ti(Xn.MissingCustomer);this.paymentIntegrationService.updatePaymentProviderCustomer({stripeLinkAuthenticationState:e.authenticated}),e.complete?a(e.authenticated,e.value.email):a(!1,""),d&&d(!1),void 0===m&&e.authenticated&&y&&this.paymentIntegrationService.deleteConsignment(y)}),f.mount(`#${i}`)}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}deinitialize(){var e,t;return null===(t=null===(e=this._stripeElements)||void 0===e?void 0:e.getElement(Da.AUTHENTICATION))||void 0===t||t.unmount(),Promise.resolve()}signIn(e,t){return this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()}signOut(e){return this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}}const ud=vi(e=>new ld(e,new Ra(a())),[{id:"stripeupe"}]);var hd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pd{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t,this.isMounted=!1}deinitialize(){var e;null===(e=this.checkoutEventsUnsubscribe)||void 0===e||e.call(this),this.isMounted=!1}initCheckoutEventsSubscription(e,t,n,i){this.checkoutEventsUnsubscribe=this.paymentIntegrationService.subscribe(()=>hd(this,void 0,void 0,function*(){var r;const o=null==i?void 0:i.getElement(Da.PAYMENT);if(o){try{yield this.updateStripePaymentIntent(e,t)}catch(e){return this.isMounted&&(o.unmount(),this.isMounted=!1),void(e instanceof Error&&(null===(r=n.onError)||void 0===r||r.call(n,e)))}this.isMounted||(yield null==i?void 0:i.fetchUpdates(),this.mountElement(o,n.containerId))}}),e=>{var t;return null===(t=e.getCheckout())||void 0===t?void 0:t.outstandingBalance},e=>{var t;return null===(t=e.getCheckout())||void 0===t?void 0:t.coupons})}mountElement(e,t){document.getElementById(t)&&(e.mount(`#${t}`),this.isMounted=!0)}mapAppearanceVariables(e){return{colorPrimary:e.fieldInnerShadow,colorBackground:e.fieldBackground,colorText:e.labelText,colorDanger:e.fieldErrorText,colorTextSecondary:e.labelText,colorTextPlaceholder:e.fieldPlaceholderText,colorIcon:e.fieldPlaceholderText}}mapInputAppearanceRules(e){return{borderColor:e.fieldBorder,color:e.fieldText,boxShadow:e.fieldInnerShadow}}throwStripeError(e){if("object"==typeof(t=e)&&null!==t&&"type"in t&&(this.throwDisplayableStripeError(e),this.isCancellationError(e)))throw new Wi;var t;throw new Qr}throwDisplayableStripeError(e){if(H(["card_error","invalid_request_error","validation_error"],e.type))throw new Error(e.message)}isCancellationError(e){var t;const n=null===(t=null==e?void 0:e.payment_intent.last_payment_error)||void 0===t?void 0:t.message;return!!n&&-1!==n.indexOf("canceled")}throwPaymentConfirmationProceedMessage(){throw new Qr("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.")}isPaymentCompleted(e,t){return hd(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getPaymentMethodOrThrow(e),{features:r}=n.getStoreConfigOrThrow().checkoutSettings;if(!i.clientToken||!t||!r["PI-626.Block_unnecessary_payment_confirmation_for_StripeUPE"])return!1;const{paymentIntent:o}=yield t.retrievePaymentIntent(i.clientToken);return(null==o?void 0:o.status)===Ma.SUCCEEDED})}mapStripePaymentData(e,t,n=!1){const i=this.paymentIntegrationService.getState().getBillingAddress(),{firstName:r="",lastName:o="",email:a=""}=i||{},s=this.mapStripeAddress(i);if(!e)throw new ri(ei.PaymentNotInitialized);if(!(a&&s&&s.city&&s.country&&r&&o))throw new ti(Xn.MissingBillingAddress);return{elements:e,redirect:Ta.IF_REQUIRED,confirmParams:Object.assign({payment_method_data:Object.assign(Object.assign({},n?{allow_redisplay:"always"}:{}),{billing_details:{email:a,address:s,name:this.getShopperFullName(i)}})},t&&{return_url:t})}}isAdditionalActionError(e){return ve(e,{code:"additional_action_required"})}isRedirectAction(e){const{type:t,data:{redirect_url:n}}=e;return"redirect_to_url"===t&&!!n}isOnPageAdditionalAction(e){const{type:t,data:{token:n}}=e;return"additional_action_requires_payment_method"===t&&!!n}updateStripePaymentIntent(e,t){return hd(this,void 0,void 0,function*(){const n=yield this.paymentIntegrationService.loadPaymentMethod(e,{params:{method:t}}),{clientToken:i}=n.getPaymentMethodOrThrow(t);i&&this.scriptLoader.updateStripeElements({clientSecret:i})})}getStripeJsVersion(e){return e.useNewStripeJsVersion?ka.CLOVER:ka.V3}mapStripeAddress(e){if(e){const{city:t,address1:n,address2:i,countryCode:r,postalCode:o,stateOrProvinceCode:a}=e;return Object.assign({city:t,country:r,postal_code:o,line1:n,line2:i},a?{state:a}:{})}throw new ti(Xn.MissingBillingAddress)}getShopperFullName(e){const{firstName:t="",lastName:n=""}=e||{};return`${t} ${n}`.trim()}}const md={size:70,color:"#d9d9d9",backgroundColor:"#ffffff"},yd={position:"fixed","background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},gd="embedded-checkout-loading-indicator-rotation";class vd{constructor(e){this.styles=Object.assign(Object.assign({},md),e&&e.styles),this.containerStyles=Object.assign({},e&&e.containerStyles),this.defineAnimation(),this.container=this.buildContainer(),this.indicator=this.buildIndicator(),this.container.appendChild(this.indicator)}show(e){if(e){const t=document.getElementById(e);if(!t)throw new Error("Unable to attach the loading indicator because the parent ID is not valid.");t.appendChild(this.container)}this.container.style.visibility="visible",this.container.style.opacity="1"}hide(){const e=()=>{this.container.style.visibility="hidden",this.container.removeEventListener("transitionend",e)};this.container.addEventListener("transitionend",e),this.container.style.opacity="0"}buildContainer(){const e=document.createElement("div");return e.style.display="block",e.style.bottom="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.position="absolute",e.style.right="0",e.style.top="0",e.style.transition="all 250ms ease-out",e.style.opacity="0",this.setStyleAttribute(e,this.containerStyles),e}buildIndicator(){const e=document.createElement("div");return e.style.display="block",e.style.width=`${this.styles.size}px`,e.style.height=`${this.styles.size}px`,e.style.borderRadius=`${this.styles.size}px`,e.style.border="solid 1px",e.style.borderColor=`${this.styles.backgroundColor} ${this.styles.backgroundColor} ${this.styles.color} ${this.styles.color}`,e.style.margin="0 auto",e.style.position="absolute",e.style.left="0",e.style.right="0",e.style.top="50%",e.style.transform="translateY(-50%) rotate(0deg)",e.style.transformStyle="preserve-3d",e.style.animation=`${gd} 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)`,e}setStyleAttribute(e,t){Object.keys(t).forEach(n=>{e.style.setProperty(n,t[n])})}defineAnimation(){var e;if(document.getElementById(gd))return;const t=document.createElement("style");t.id=gd,null===(e=document.head)||void 0===e||e.appendChild(t),t.sheet instanceof CSSStyleSheet&&t.sheet.insertRule(`\n @keyframes ${gd} {\n 0% { transform: translateY(-50%) rotate(0deg); }\n 100% { transform: translateY(-50%) rotate(360deg); }\n }\n `,0)}}class fd{constructor(e){this._decimalPlaces=e}toInteger(e){return Math.round(e*Math.pow(10,this._decimalPlaces))}}const Sd=["AC","AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CV","CW","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MK","ML","MM","MN","MO","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SZ","TA","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","US","UY","UZ","VA","VC","VE","VG","VN","VU","WF","WS","XK","YE","YT","ZA","ZM","ZW","ZZ"];var _d=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class wd{constructor(e,t,n,i){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n,this.loadingIndicator=i}initialize(e){return _d(this,void 0,void 0,function*(){const{stripeocs:t}=e||{};if(!t)throw new fi('Unable to proceed because "options" argument is not provided.');const{gatewayId:n,container:i}=t;if(!i||!n)throw new ri(ei.PaymentNotInitialized);const r=this._getMethodId(n),o=yield this.paymentIntegrationService.loadPaymentMethod(n,{params:{method:r}}),a=o.getPaymentMethodOrThrow(r,n),{loadingContainerId:s,buttonHeight:d,onComplete:c}=t;if(this._loadingIndicatorContainer=s,this._onComplete=c,!dd(a))throw new ti(Xn.MissingPaymentMethod);const{initializationData:l}=a,{captureMethod:u}=l,h=this.stripeIntegrationService.getStripeJsVersion(l);this._captureMethod=u,this._stripeClient=yield this.scriptLoader.getStripeClient(l,o.getCartLocale(),h),yield this._mountExpressCheckoutElement(i,this._stripeClient,d),this._initializeEvents(r)})}signIn(){return Promise.resolve()}signOut(){return Promise.resolve()}executePaymentMethodCheckout(){return Promise.resolve()}deinitialize(){return Promise.resolve()}_mountExpressCheckoutElement(e,t,n=40){return _d(this,void 0,void 0,function*(){const i=this._shouldRequireShippingAddress(),r=Object.assign(Object.assign(Object.assign({shippingAddressRequired:i},i?{allowedShippingCountries:yield this._getAvailableCountries()}:{}),i?{shippingRates:[{id:"_",amount:0,displayName:"Pending rates"}]}:{}),{billingAddressRequired:!0,emailRequired:!0,phoneNumberRequired:!0,paymentMethods:{link:Ta.AUTO,applePay:Ta.NEVER,googlePay:Ta.NEVER,amazonPay:Ta.NEVER,paypal:Ta.NEVER,klarna:Ta.NEVER},buttonHeight:n}),{cartAmount:o}=this.paymentIntegrationService.getState().getCartOrThrow(),a=Object.assign({mode:"payment",amount:this._toCents(o),currency:this._getCurrency()},this._captureMethod?{captureMethod:this._captureMethod}:{});return this._stripeElements=t.elements(a),this._linkV2Element=this._stripeElements.create(Da.EXPRESS_CHECKOUT,r),this._linkV2Element.mount(`#${e}`),this._linkV2Element})}_initializeEvents(e){this._linkV2Element&&(this._shouldRequireShippingAddress()&&(this._linkV2Element.on(za.SHIPPING_ADDRESS_CHANGE,e=>_d(this,void 0,void 0,function*(){return this._onShippingAddressChange(e)})),this._linkV2Element.on(za.SHIPPING_RATE_CHANGE,e=>_d(this,void 0,void 0,function*(){return this._onShippingRateChange(e)}))),this._linkV2Element.on(za.CONFIRM,t=>_d(this,void 0,void 0,function*(){return this._onConfirm(t,e)})),this._linkV2Element.on(za.CANCEL,this._onCancel))}_onShippingAddressChange(e){return _d(this,void 0,void 0,function*(){if(!("address"in e))return;const t=e.address,n={firstName:"",lastName:"",phone:"",company:"",address1:"",address2:"",city:(null==t?void 0:t.city)||"",countryCode:(null==t?void 0:t.country)||"",postalCode:(null==t?void 0:t.postal_code)||"",stateOrProvince:(null==t?void 0:t.state)||"",stateOrProvinceCode:(null==t?void 0:t.state)||"",customFields:[]};yield this.paymentIntegrationService.updateShippingAddress(n);const i=yield this._getAvailableShippingOptions();yield this._updateDisplayedPrice(),(null==i?void 0:i.length)?e.resolve({shippingRates:i}):e.reject()})}_onCancel(){throw new Wi}_onShippingRateChange(e){return _d(this,void 0,void 0,function*(){if("shippingRate"in e){const{shippingRate:t}=e;yield this._handleShippingOptionChange(null==t?void 0:t.id),yield this._updateDisplayedPrice(),e.resolve({})}})}_onConfirm(e,t){return _d(this,void 0,void 0,function*(){if("billingDetails"in e&&"shippingAddress"in e&&this._stripeClient&&this._stripeElements){yield this._updateShippingAndBillingAddress(e),yield this.paymentIntegrationService.submitOrder();const n=this._getPaymentPayload(t);try{yield this.paymentIntegrationService.submitPayment(n)}catch(e){yield this._processAdditionalAction(e,t)}}return Promise.resolve()})}_updateShippingAndBillingAddress(e){var t,n,i,r,o,a,s,d;return _d(this,void 0,void 0,function*(){const c=this._shouldRequireShippingAddress(),l=(null===(n=null===(t=e.shippingAddress)||void 0===t?void 0:t.name)||void 0===n?void 0:n.split(" ")[0])||(null===(r=null===(i=e.billingDetails)||void 0===i?void 0:i.name)||void 0===r?void 0:r.split(" ")[0])||"",u=(null===(a=null===(o=e.shippingAddress)||void 0===o?void 0:o.name)||void 0===a?void 0:a.split(" ")[1])||(null===(d=null===(s=e.billingDetails)||void 0===s?void 0:s.name)||void 0===d?void 0:d.split(" ")[1])||"";if(c){const t=this._mapShippingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateShippingAddress(t)}const h=this._mapBillingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateBillingAddress(h)})}_mapShippingAddress(e,t,n,i){var r,o,a,s,d,c,l;return{firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==e?void 0:e.address)||void 0===r?void 0:r.line1)||"",address2:(null===(o=null==e?void 0:e.address)||void 0===o?void 0:o.line2)||"",city:(null===(a=null==e?void 0:e.address)||void 0===a?void 0:a.city)||"",countryCode:(null===(s=null==e?void 0:e.address)||void 0===s?void 0:s.country)||"",postalCode:(null===(d=null==e?void 0:e.address)||void 0===d?void 0:d.postal_code)||"",stateOrProvince:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",stateOrProvinceCode:(null===(l=null==e?void 0:e.address)||void 0===l?void 0:l.state)||"",customFields:[]}}_mapBillingAddress(e,t,n,i){var r,o,a,s,d,c;return{email:(null==t?void 0:t.email)||"",firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==t?void 0:t.address)||void 0===r?void 0:r.line1)||"",address2:"",city:(null===(o=null==t?void 0:t.address)||void 0===o?void 0:o.city)||"",countryCode:(null===(a=null==t?void 0:t.address)||void 0===a?void 0:a.country)||"",postalCode:(null===(s=null==t?void 0:t.address)||void 0===s?void 0:s.postal_code)||"",stateOrProvince:(null===(d=null==t?void 0:t.address)||void 0===d?void 0:d.state)||"",stateOrProvinceCode:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",customFields:[]}}_processAdditionalAction(e,t){return _d(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeClient||!this._stripeElements)throw new ri(ei.PaymentNotInitialized);const{data:n}=e.body.additional_action_required,{token:i}=n,{paymentIntent:r}=yield this._confirmStripePaymentOrThrow(n,t),o=this._getPaymentPayload(t,(null==r?void 0:r.id)||i);try{this._toggleLoadingIndicator(!0),yield this.paymentIntegrationService.submitPayment(o),yield this._completeCheckoutFlow()}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}finally{this._toggleLoadingIndicator(!1)}})}_confirmStripePaymentOrThrow(e,t){var n,i,r;return _d(this,void 0,void 0,function*(){const{token:o,redirect_url:a}=e,s=this.stripeIntegrationService.mapStripePaymentData(this._stripeElements,a);let d;try{const e=(yield this.stripeIntegrationService.isPaymentCompleted(t,this._stripeClient))?yield null===(r=this._stripeClient)||void 0===r?void 0:r.retrievePaymentIntent(o||""):yield null===(n=this._stripeClient)||void 0===n?void 0:n.confirmPayment({elements:s.elements,clientSecret:o,redirect:Ta.IF_REQUIRED,confirmParams:{return_url:null===(i=s.confirmParams)||void 0===i?void 0:i.return_url}});if(d=null==e?void 0:e.error,d||!(null==e?void 0:e.paymentIntent))throw new Qr;return e}catch(e){return this.stripeIntegrationService.throwStripeError(d)}})}_completeCheckoutFlow(){return _d(this,void 0,void 0,function*(){return"function"==typeof this._onComplete?this._onComplete():(window.location.replace("/order-confirmation"),Promise.resolve())})}_getPaymentPayload(e,t){var n;const i=(null===(n=this.paymentIntegrationService.getState().getCart())||void 0===n?void 0:n.id)||"";return{methodId:e,paymentData:{formattedPayload:Object.assign(Object.assign({cart_id:i},t?{credit_card_token:{token:t}}:{}),{confirm:!1,method:Aa.Link})}}}_shouldRequireShippingAddress(){const{getCartOrThrow:e}=this.paymentIntegrationService.getState(),{lineItems:t}=e();return!!t.physicalItems.length}_updateDisplayedPrice(){return _d(this,void 0,void 0,function*(){this._stripeElements&&this._stripeElements.update({currency:this._getCurrency(),mode:"payment",amount:yield this._getTotalPrice()})})}_getCurrency(){if(!this._currencyCode){const{code:e}=this.paymentIntegrationService.getState().getCartOrThrow().currency;this._currencyCode=e.toLowerCase()}return this._currencyCode}_getTotalPrice(){return _d(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const{getCheckoutOrThrow:e,getCartOrThrow:t}=this.paymentIntegrationService.getState(),{decimalPlaces:n}=t().currency,i=ge(e().outstandingBalance,n).toFixed(n);return this._toCents(+i)})}_getAvailableCountries(){var e;return _d(this,void 0,void 0,function*(){const t=yield this.paymentIntegrationService.loadShippingCountries();return((null===(e=t.getShippingCountries())||void 0===e?void 0:e.map(e=>e.code))||[]).filter(e=>Sd.includes(e))})}_getAvailableShippingOptions(){var e,t,n;return _d(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getConsignments();if(!(null==i?void 0:i[0]))return;const r=i[0],o=(r.availableShippingOptions||[]).map(this._getStripeShippingOption.bind(this)),a=null===(e=r.availableShippingOptions)||void 0===e?void 0:e.find(e=>e.isRecommended),s=null===(t=r.selectedShippingOption)||void 0===t?void 0:t.id,d=null==a?void 0:a.id;return s?o.sort(e=>e.id===s?-1:0):d?(o.sort(e=>e.id===d?-1:0),yield this._handleShippingOptionChange(d)):yield this._handleShippingOptionChange(null===(n=o[0])||void 0===n?void 0:n.id),o.slice(0,9)})}_getStripeShippingOption({id:e,cost:t,description:n}){return{id:e,displayName:n,amount:this._toCents(t)}}_handleShippingOptionChange(e){return _d(this,void 0,void 0,function*(){if(e&&"shipping_option_unselected"!==e)return this.paymentIntegrationService.selectShippingOption(e)})}_getAmountTransformer(){if(this._amountTransformer)return this._amountTransformer;const{getCart:e}=this.paymentIntegrationService.getState(),{currency:t}=e()||{};return t?new fd(t.decimalPlaces):void 0}_toCents(e){const t=Math.round(100*e),n=this._getAmountTransformer();return n?n.toInteger(e):t}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this.loadingIndicator.show(this._loadingIndicatorContainer):this.loadingIndicator.hide()}_getMethodId(e){const{initializationData:{checkoutSessionEnabled:t}={}}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e);return t?Aa.CHECKOUT_SESSION:Aa.OCS}}const Id=vi(e=>{const t=new Ra(a()),n=new vd({containerStyles:yd});return new wd(e,t,new pd(e,t),n)},[{id:"stripeocs"}]);class Cd extends Qn{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}class bd{constructor(e){this._paymentIntegrationService=e}execute(e,t){return n=this,i=void 0,o=function*(){yield this._paymentIntegrationService.submitOrder(le(e,"payment"),t)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const Pd=vi(e=>new bd(e),[{id:"nopaymentdatarequired"}]);var Od,Ed,Ad,Td,kd,Dd,Md;class zd{constructor(e,t,n=window){this._scriptLoader=e,this._stylesheetLoader=t,this._window=n}load(e){var t,n,i,r,o,a;return i=this,r=void 0,a=function*(){if(yield Promise.all([this._stylesheetLoader.loadStylesheet(`https://checkoutshopper-${null!==(t=e.environment)&&void 0!==t?t:""}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.css`,{prepend:!1,attributes:{integrity:"sha384-8ofgICZZ/k5cC5N7xegqFZOA73H9RQ7H13439JfAZW8Gj3qjuKL2isaTD3GMIhDE",crossorigin:"anonymous"}}),this._scriptLoader.loadScript(`https://checkoutshopper-${null!==(n=e.environment)&&void 0!==n?n:""}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.js`,{async:!0,attributes:{integrity:"sha384-wG2z9zSQo61EIvyXmiFCo+zB3y0ZB4hsrXVcANmpP8HLthjoQJQPBh7tZKJSV8jA",crossorigin:"anonymous"}})]),!this._window.AdyenCheckout)throw new mi;return new this._window.AdyenCheckout(e)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}}function Nd(e){return"object"==typeof e&&"string"==typeof e.data.paymentMethod.encryptedSecurityCode||"string"==typeof e.data.paymentMethod.encryptedExpiryMonth}function xd(e){return Boolean(e.instrumentId)}!function(e){e.ThreeDS2Fingerprint="threeDS2Fingerprint",e.ThreeDS2="threeDS2",e.Redirect="redirect",e.QRCode="qrCode",e.Voucher="voucher",e.Sdk="sdk"}(Od||(Od={})),function(e){e.ThreeDS2Fingerprint="threeDS2Fingerprint",e.ThreeDS2Challenge="threeDS2Challenge",e.Redirect="redirect",e.QRCode="qrCode",e.Voucher="voucher"}(Ed||(Ed={})),function(e){e.SecuredFields="securedfields"}(Ad||(Ad={})),function(e){e.ACH="ach",e.AliPay="alipay",e.Bancontact="bcmc",e.CreditCard="scheme",e.Klarna="klarna",e.KlarnaPayNow="klarna_paynow",e.KlarnaAccount="klarna_account",e.IDEAL="ideal",e.GiroPay="giropay",e.GooglePay="paywithgoogle",e.SEPA="sepadirectdebit",e.Sofort="directEbanking",e.Vipps="vipps",e.WeChatPayQR="wechatpayQR"}(Td||(Td={})),function(e){e.POST="POST"}(kd||(kd={})),function(e){e.ChallengeShopper="ChallengeShopper",e.Error="Error",e.IdentifyShopper="IdentifyShopper"}(Dd||(Dd={})),function(e){e.CardNumber="encryptedCardNumber",e.SecurityCode="encryptedSecurityCode",e.ExpiryDate="encryptedExpiryDate"}(Md||(Md={}));var Rd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Fd{constructor(e,t){this._paymentIntegrationService=e,this._scriptLoader=t}initialize(e){return Rd(this,void 0,void 0,function*(){const{adyenv2:t}=e;if(!t)throw new fi('Unable to initialize payment because "options.adyenv2" argument is not provided.');this._paymentInitializeOptions=t;const n=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{originKey:i,clientKey:r,environment:o,paymentMethodsResponse:a}=n.initializationData||{},s={key:"",value:""};return i?(s.key="originKey",s.value=i):(s.key="clientKey",s.value=r||""),this._adyenClient=yield this._scriptLoader.load({environment:o,locale:this._paymentIntegrationService.getState().getLocale(),[s.key]:s.value,paymentMethodsResponse:a,translations:{es:{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-AR":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-ES":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-MX":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CL":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CO":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-PE":{"creditCard.expiryDateField.title":"Fecha de caducidad"}}}),this._paymentComponent=yield this._mountPaymentComponent(n),n.method!==Td.CreditCard&&n.method!==Td.Bancontact||(this._cardVerificationComponent=yield this._mountCardVerificationComponent()),Promise.resolve()})}execute(e,t){return Rd(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const{threeDS2ContainerId:i,additionalActionOptions:r}=this._getPaymentInitializeOptions(),{onBeforeLoad:o,containerId:a,onLoad:s,onComplete:d}=r,c=JSON.parse(e.action),l=this._getAdyenClient().createFromAction(c,{onAdditionalDetails:e=>{const n={methodId:c.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};d&&d(),t(n)},size:this._getThreeDS2ChallengeWidgetSize(),onError:e=>n(e)});o&&o(c.type===Ed.ThreeDS2Challenge||c.type===Ed.QRCode),l.mount(`#${a||i}`),s&&s(()=>{n(new Wi),l.unmount()})})}_mapAdyenPlaceholderData(e,t){if(!e)return{};const{firstName:n,lastName:i,address1:r,address2:o,postalCode:a,city:s,stateOrProvinceCode:d,countryCode:c}=e;return{holderName:t?`${n} ${i}`:"",billingAddress:{street:r,houseNumberOrName:o,postalCode:a,city:s,stateOrProvince:d,country:c}}}_mountCardVerificationComponent(){const e=this._getPaymentInitializeOptions(),t=this._getAdyenClient();let n;return new Promise((i,r)=>{var o,a,s;if(e.cardVerificationContainerId){n=t.create(Ad.SecuredFields,Object.assign(Object.assign({},e.options),{styles:Object.assign(Object.assign({},null===(o=e.options)||void 0===o?void 0:o.styles),{placeholder:Object.assign({color:"transparent",caretColor:"#000"},null===(s=null===(a=e.options)||void 0===a?void 0:a.styles)||void 0===s?void 0:s.placeholder)}),onChange:e=>this._updateComponentState(e),onError:t=>e.validateCardFields(t),onFieldValid:t=>e.validateCardFields(t)}));try{n.mount(`#${e.cardVerificationContainerId}`)}catch(e){r(new ri(ei.PaymentNotInitialized))}}i(n)})}_mountPaymentComponent(e){let t;const n=this._getPaymentInitializeOptions(),i=this._getAdyenClient();return new Promise((r,o)=>{switch(e.method){case Td.CreditCard:case Td.ACH:case Td.Bancontact:{const r=this._paymentIntegrationService.getState().getBillingAddress(),{prefillCardHolderName:a}=e.initializationData;t=i.create(e.method,Object.assign(Object.assign({},n.options),{onChange:e=>this._updateComponentState(e),data:this._mapAdyenPlaceholderData(r,a)}));try{t.mount(`#${n.containerId}`)}catch(e){o(new ri(ei.PaymentNotInitialized))}break}case Td.IDEAL:case Td.SEPA:if(n.hasVaultedInstruments)this._updateComponentState({data:{paymentMethod:{type:e.method}}});else{t=i.create(e.method,Object.assign(Object.assign({},n.options),{onChange:e=>this._updateComponentState(e)}));try{t.mount(`#${n.containerId}`)}catch(e){o(new ri(ei.PaymentNotInitialized))}}break;case Td.AliPay:case Td.GiroPay:case Td.Sofort:case Td.Klarna:case Td.KlarnaPayNow:case Td.KlarnaAccount:case Td.Vipps:case Td.WeChatPayQR:this._updateComponentState({data:{paymentMethod:{type:e.method}}})}r(t)})}_processAdditionalAction(e,t,n){return Rd(this,void 0,void 0,function*(){if(!pa(e)||!ve(e.body.errors,{code:"additional_action_required"}))throw e;const i=yield this._handleAction(e.body.provider_data);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:Object.assign(Object.assign({},i.paymentData),{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n})}))}catch(e){return this._processAdditionalAction(e,t,n)}})}_updateComponentState(e){this._componentState=e}_validateCardData(){var e,t;const n=this._getPaymentInitializeOptions().hasVaultedInstruments?this._cardVerificationComponent:this._paymentComponent;if((null===(e=null==n?void 0:n.componentRef)||void 0===e?void 0:e.showValidation)&&n.state&&(n.componentRef.showValidation(),0===Object.keys(n.state).length||!n.state.isValid&&!n.state.issuer||"sepadirectdebit"===(null===(t=n.props)||void 0===t?void 0:t.type)&&n.state.data&&Object.values(n.state.data).some(e=>0===e.toString().trim().length)))throw new lo(this._mapCardErrors(n.state.errors))}_mapCardErrors(e={}){const t={};return Object.keys(e).forEach(n=>{t[n]=[{message:e[n],type:n}]}),t}}const Ld=vi(e=>new Fd(e,new zd(a(),s())),[{gateway:"adyenv2"}]);class Bd{constructor(e,t,n=window){this._scriptLoader=e,this._stylesheetLoader=t,this._window=n}load(e){var t,n,i,r,o,a;return i=this,r=void 0,a=function*(){if(yield Promise.all([this._stylesheetLoader.loadStylesheet(`https://checkoutshopper-${null!==(t=e.environment)&&void 0!==t?t:""}.adyen.com/checkoutshopper/sdk/5.71.1/adyen.css`,{prepend:!1,attributes:{integrity:"sha384-5MvB4RnzvviA3VBT4KYABZ4HXNZG5LRqREEgd41xt/pf/QvKmsj2O9GuNuywRXx9",crossorigin:"anonymous"}}),this._scriptLoader.loadScript(`https://checkoutshopper-${null!==(n=e.environment)&&void 0!==n?n:""}.adyen.com/checkoutshopper/sdk/5.71.1/adyen.js`,{async:!0,attributes:{integrity:"sha384-yvY2yFNR4WqIjPqP9MzjI+gJimmaJnAvj4rLHKvgJbgFD5fMuf8zIJrFJOW8Lhhf",crossorigin:"anonymous"}})]),!this._window.AdyenCheckout)throw new mi;return yield this._window.AdyenCheckout(e)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}}function jd(e){return!("object"!=typeof e||null===e||void 0!==e.shouldSaveInstrument&&"boolean"!=typeof e.shouldSaveInstrument||void 0!==e.shouldSetAsDefaultInstrument&&"boolean"!=typeof e.shouldSetAsDefaultInstrument)}var Ud=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class qd{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){return Ud(this,void 0,void 0,function*(){const{adyenv3:t}=e;if(!t)throw new fi('Unable to initialize payment because "options.adyenv3" argument is not provided.');this.paymentInitializeOptions=t;const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{environment:i,clientKey:r,paymentMethodsResponse:o,installmentOptions:a}=n.initializationData||{};return this.adyenClient=yield this.scriptLoader.load({paymentMethodsConfiguration:Object.assign({klarna:{useKlarnaWidget:!0},klarna_account:{useKlarnaWidget:!0},klarna_paynow:{useKlarnaWidget:!0}},a?{card:{installmentOptions:Object.assign({showInstallmentAmounts:!0},a)}}:{}),environment:i,locale:this._getLocale(),clientKey:r,paymentMethodsResponse:o,showPayButton:!1,translations:{es:{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-AR":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-ES":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-MX":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CL":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CO":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-PE":{"creditCard.expiryDateField.title":"Fecha de caducidad"}}}),this.paymentComponent=yield this._mountPaymentComponent(n),n.method!==Td.CreditCard&&n.method!==Td.Bancontact||(this.cardVerificationComponent=yield this._mountCardVerificationComponent()),Promise.resolve()})}execute(e,t){var n;return Ud(this,void 0,void 0,function*(){const{payment:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const{additionalActionOptions:i}=this._getPaymentInitializeOptions(),{onBeforeLoad:r,containerId:o,onLoad:a,onComplete:s,widgetSize:d,onActionHandled:c}=i,l=JSON.parse(e.action),u=this._getAdyenClient().createFromAction(l,{onActionHandled:e=>{c&&"function"==typeof c&&"3DS2Fingerprint"!==e.componentType&&c()},onAdditionalDetails:e=>{const n={methodId:l.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};s&&"function"==typeof s&&s(),t(n)},challengeWindowSize:d||"05",onError:e=>n(e)});r&&"function"==typeof r&&r(l.type===Od.ThreeDS2||l.type===Od.QRCode||l.type===Od.Sdk),this._mountElement(u,o).then(()=>{a&&"function"==typeof a&&a(()=>{n(new Wi),u.unmount()})}).catch(n)})}_mapAdyenPlaceholderData(e,t){if(!e)return{};const{firstName:n,lastName:i,address1:r,address2:o,postalCode:a,city:s,stateOrProvinceCode:d,countryCode:c}=e;return{holderName:t?`${n} ${i}`:"",firstName:t?n:"",lastName:t?i:"",billingAddress:{street:r,houseNumberOrName:o,postalCode:a,city:s,stateOrProvince:d,country:c}}}_mountCardVerificationComponent(){var e,t,n;return Ud(this,void 0,void 0,function*(){const i=this._getPaymentInitializeOptions(),r=this._getAdyenClient();if(!i.cardVerificationContainerId)return;const o=r.create(Ad.SecuredFields,Object.assign(Object.assign({},i.options),{styles:Object.assign(Object.assign({},null===(e=i.options)||void 0===e?void 0:e.styles),{placeholder:Object.assign({color:"transparent",caretColor:"#000"},null===(n=null===(t=i.options)||void 0===t?void 0:t.styles)||void 0===n?void 0:n.placeholder)}),onChange:e=>this._updateComponentState(e),onError:e=>i.validateCardFields(e),onFieldValid:e=>i.validateCardFields(e)}));try{yield this._mountElement(o,i.cardVerificationContainerId)}catch(e){throw new ri(ei.PaymentNotInitialized)}return o})}_mountPaymentComponent(e){return Ud(this,void 0,void 0,function*(){const t=this._getPaymentInitializeOptions(),n=this._getAdyenClient(),i=this.paymentIntegrationService.getState().getBillingAddress(),{prefillCardHolderName:r}=e.initializationData,o=n.create(e.method,Object.assign(Object.assign(Object.assign(Object.assign({},this._isOneyPaymentMethod(e.method)?{visibility:{personalDetails:"hidden",billingAddress:"hidden",deliveryAddress:"hidden"}}:{}),t.options),{showBrandsUnderCardNumber:!1,billingAddressRequired:!1,showEmailAddress:!1,onChange:e=>this._updateComponentState(e),onSubmit:e=>this._updateComponentState(e)}),i?{data:this._mapAdyenPlaceholderData(i,r)}:{}));try{yield this._mountElement(o,t.containerId)}catch(e){throw new ri(ei.PaymentNotInitialized)}return o})}_isOneyPaymentMethod(e){return e.startsWith("facilypay")}_processAdditionalAction(e,t,n,i,r){return Ud(this,void 0,void 0,function*(){if(!pa(e)||!ve(e.body.errors,{code:"additional_action_required"}))throw e;const o=yield this._handleAction(e.body.provider_data);try{const e=Object.assign(Object.assign({},o.paymentData),{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n}),a=n&&!t?{instrumentId:i,formattedPayload:{bigpay_token:Object.assign(Object.assign({},r),{token:i})}}:{};yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},o),{paymentData:Object.assign(Object.assign({},e),a)}))}catch(e){return this._processAdditionalAction(e,t,n,i,r)}})}_validateCardData(){var e;const t=this._getPaymentInitializeOptions().hasVaultedInstruments?this.cardVerificationComponent:this.paymentComponent;if((null===(e=null==t?void 0:t.componentRef)||void 0===e?void 0:e.showValidation)&&t.state&&(t.componentRef.showValidation(),0===Object.keys(t.state).length||!t.state.isValid))throw new lo(this._mapCardErrors(t.state.errors))}_mapCardErrors(e={}){const t={};return Object.keys(e).forEach(n=>{t[n]=[{message:e[n],type:n}]}),t}_mountElement(e,t){return Ud(this,void 0,void 0,function*(){yield this._waitForMountContainer(t);try{e.mount(`#${t}`)}catch(e){throw new ri(ei.PaymentNotInitialized)}})}_waitForMountContainer(e){return Ud(this,void 0,void 0,function*(){const t=Math.ceil(qd.mountContainerMaxWaitMs/qd.mountContainerPollIntervalMs),n=qd.mountContainerPollIntervalMs;let i=0;const r=()=>Ud(this,void 0,void 0,function*(){if(i===t)throw new ri(ei.PaymentNotInitialized);document.getElementById(e)||(yield new Promise(e=>{setTimeout(e,n)}),i+=1,yield r())});yield r()})}}qd.mountContainerMaxWaitMs=5e3,qd.mountContainerPollIntervalMs=50;const Vd=vi(e=>new qd(e,new Bd(a(),s())),[{gateway:"adyenv3"}]);var Gd,Hd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Wd{constructor(e,t){this.paymentIntegrationService=e,this.affirmScriptLoader=t}initialize(e){return Hd(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadPaymentMethod(e.methodId);const t=this.paymentIntegrationService.getState(),{clientToken:n,config:{testMode:i}}=t.getPaymentMethodOrThrow(e.methodId);if(!n)throw new ti(Xn.MissingPaymentMethod);this.affirm=yield this.affirmScriptLoader.load(n,i)})}execute(e,t){var n;return Hd(this,void 0,void 0,function*(){const i=null===(n=e.payment)||void 0===n?void 0:n.methodId,{useStoreCredit:r}=e;if(!this.affirm)throw new ri(ei.PaymentNotInitialized);if(!i)throw new co(["payment.methodId"]);yield this.paymentIntegrationService.submitOrder({useStoreCredit:r},t);const o={methodId:i,paymentData:{nonce:(yield this.initializeAffirmCheckout()).checkout_token}};yield this.paymentIntegrationService.submitPayment(o)})}deinitialize(){return this.affirm&&(this.affirm=void 0),Promise.resolve()}finalize(){return Promise.reject(new Cd)}initializeAffirmCheckout(){var e;return null===(e=this.affirm)||void 0===e||e.checkout(this.getCheckoutInformation()),new Promise((e,t)=>{var n,i;null===(n=this.affirm)||void 0===n||n.checkout.open({onFail:e=>{"canceled"===e.reason?t(new Wi):t(new Xr)},onSuccess:t=>{e(t)}}),null===(i=this.affirm)||void 0===i||i.ui.error.on("close",()=>{t(new Wi)})})}getCheckoutInformation(){const e=this.paymentIntegrationService.getState(),t=e.getStoreConfig(),n=e.getConsignments(),i=e.getOrder(),r=e.getCart();if(!t)throw new ti(Xn.MissingCheckoutConfig);if(!i)throw new ti(Xn.MissingCheckout);const o=new fd(i.currency.decimalPlaces),a=this.getBillingAddress(),s=this.getShippingAddress(),d=jo(r,t)&&s?s:a;return{merchant:{user_confirmation_url:t.links.checkoutLink,user_cancel_url:t.links.checkoutLink,user_confirmation_url_action:"POST"},shipping:d,billing:a,items:this.getItems(o,i),metadata:{shipping_type:this.getShippingType(n),mode:"modal",platform_type:"BigCommerce",platform_version:"",platform_affirm:""},discounts:this.getDiscounts(o,i),order_id:i.orderId?i.orderId.toString():"",shipping_amount:o.toInteger(i.shippingCostTotal),tax_amount:o.toInteger(i.taxTotal),total:o.toInteger(i.orderAmount)}}getShippingType(e){if(!e)return"";const t=e[0];return(null==t?void 0:t.selectedShippingOption)?t.selectedShippingOption.type:""}getBillingAddress(){const e=this.paymentIntegrationService.getState().getBillingAddress();if(!e)throw new ti(Xn.MissingBillingAddress);return{name:{first:e.firstName,last:e.lastName,full:`${e.firstName} ${e.lastName}`},address:{line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,zipcode:e.postalCode,country:e.countryCode},phone_number:e.phone,email:e.email}}getShippingAddress(){const e=this.paymentIntegrationService.getState().getShippingAddress();if(e)return{name:{first:e.firstName,last:e.lastName,full:`${e.firstName} ${e.lastName}`},address:{line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,zipcode:e.postalCode,country:e.countryCode},phone_number:e.phone}}getItems(e,t){const n=[];return t.lineItems.physicalItems.forEach(t=>{n.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.salePrice),qty:t.quantity,item_image_url:t.imageUrl,item_url:t.url,categories:this.getCategories(t.categories)})}),t.lineItems.digitalItems.forEach(t=>{n.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.salePrice),qty:t.quantity,item_image_url:t.imageUrl,item_url:t.url,categories:this.getCategories(t.categories)})}),t.lineItems.giftCertificates.forEach(t=>{n.push({display_name:t.name,sku:"",unit_price:e.toInteger(t.amount),qty:1,item_image_url:"",item_url:""})}),t.lineItems.customItems&&t.lineItems.customItems.forEach(t=>{n.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.listPrice),qty:t.quantity,item_image_url:"",item_url:""})}),n}getDiscounts(e,t){const n={};return t.coupons.forEach(t=>{t.discountedAmount>0&&(n[t.code]={discount_amount:e.toInteger(t.discountedAmount),discount_display_name:t.displayName})}),t.discountAmount>0&&(n.DISCOUNTED_AMOUNT={discount_amount:e.toInteger(t.discountAmount),discount_display_name:"discount"}),n}getCategories(e){return e?e.map(e=>e.map(e=>e.name)):[[]]}}!function(e){e.PROD="//cdn1.affirm.com/js/v2/affirm.js",e.SANDBOX="//cdn1-sandbox.affirm.com/js/v2/affirm.js"}(Gd||(Gd={}));class $d{constructor(e=window){this.affirmWindow=e}load(e="",t){const n=t?Gd.SANDBOX:Gd.PROD;if(function(e,t,n,i,r,o,a){const s=e[n]||{},d=document.createElement(o),c=document.getElementsByTagName(o)[0],l=function(e,t,n){return function(){e[t]._.push([n,arguments])}};s[i]=l(s,i,"set");const u=s[i];s[r]={},s[r]._=[],u._=[],s._=[],s[r][a]=l(s,r,a),s.jsReady=function(){s._.push([a,arguments])};let h=0;for(const e="set add save post open empty reset on off trigger ready setProduct".split(" ");hnew Wd(e,new $d),[{id:"affirm"}]);class Kd extends Qn{constructor(e){super(e||"The current order could not be finalized successfully"),this.name="OrderFinalizationNotCompletedError",this.type="order_finalization_not_completed"}}var Jd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Zd{constructor(e,t){this._paymentIntegrationService=e,this._afterpayScriptLoader=t}initialize(e){var t;return Jd(this,void 0,void 0,function*(){const n=this._paymentIntegrationService.getState(),i=n.getPaymentMethod(e.methodId,e.gatewayId),r=(null===(t=n.getCart())||void 0===t?void 0:t.currency.code)||"",o=this._mapCurrencyToISO2(r),a=Ci(n.getStoreConfigOrThrow().checkoutSettings.features,"PI-4789.afterpay_script_use_https",!1);if(!i)throw new ti(Xn.MissingPaymentMethod);this._afterpaySdk=yield this._afterpayScriptLoader.load(i,o,a)})}deinitialize(){return this._afterpaySdk&&(this._afterpaySdk=void 0),Promise.resolve()}execute(e,t){var n;return Jd(this,void 0,void 0,function*(){if(!e.payment)throw new co(["payment.gatewayId","payment.methodId"]);const{gatewayId:i,methodId:r}=e.payment;if(!i||!r)throw new co(["payment.gatewayId","payment.methodId"]);const{useStoreCredit:o}=e;void 0!==o&&(yield this._paymentIntegrationService.applyStoreCredit(o)),yield this._loadPaymentMethod(i,r,t);const a=this._paymentIntegrationService.getState();yield this._paymentIntegrationService.validateCheckout(a.getCheckout(),t);const s=(null===(n=a.getCart())||void 0===n?void 0:n.currency.code)||"",d=this._mapCurrencyToISO2(s);return this._redirectToAfterpay(d,a.getPaymentMethod(r,i)),new Promise(()=>{})})}finalize(e){var t,n,i;return Jd(this,void 0,void 0,function*(){const r=this._paymentIntegrationService.getState(),o=r.getPaymentId(),a=r.getContextConfig();if(!o)throw new ti(Xn.MissingCheckout);if(!(null==a?void 0:a.payment.token))throw new ti(Xn.MissingCheckoutConfig);const s={methodId:o.providerId,paymentData:{nonce:a.payment.token}};yield this._paymentIntegrationService.submitOrder({},e);try{yield this._paymentIntegrationService.submitPayment(s)}catch(e){if(yield this._paymentIntegrationService.forgetCheckout(o.providerId),yield this._paymentIntegrationService.loadPaymentMethods(),pa(e))throw new Kd(null===(i=null===(n=null===(t=e.body)||void 0===t?void 0:t.errors)||void 0===n?void 0:n[0])||void 0===i?void 0:i.message)}})}_redirectToAfterpay(e,t){if(!this._afterpaySdk||!(null==t?void 0:t.clientToken))throw new ri(ei.PaymentNotInitialized);this._afterpaySdk.initialize({countryCode:e}),this._afterpaySdk.redirect({token:t.clientToken})}_mapCurrencyToISO2(e){return{AUD:"AU",NZD:"NZ",CAD:"CA",USD:"US"}[e]||"AU"}_loadPaymentMethod(e,t,n){var i;return Jd(this,void 0,void 0,function*(){try{return yield this._paymentIntegrationService.loadPaymentMethod(e,Object.assign(Object.assign({},n),{params:Object.assign(Object.assign({},null==n?void 0:n.params),{method:t})}))}catch(e){if(e instanceof nr&&422===(null===(i=e.body)||void 0===i?void 0:i.status))throw new fi("Afterpay can't process your payment for this order, please try another payment method");throw e}})}}var Qd,Xd;!function(e){e.PROD="//portal.afterpay.com/afterpay-async.js",e.SANDBOX="//portal.sandbox.afterpay.com/afterpay.js",e.HTTPS_PROD="https://portal.afterpay.com/afterpay-async.js",e.HTTPS_SANDBOX="https://portal.sandbox.afterpay.com/afterpay.js"}(Qd||(Qd={})),function(e){e.PROD="//portal.afterpay.com/afterpay-async.js",e.SANDBOX="//portal.sandbox.afterpay.com/afterpay.js",e.HTTPS_PROD="https://portal.afterpay.com/afterpay-async.js",e.HTTPS_SANDBOX="https://portal.sandbox.afterpay.com/afterpay.js"}(Xd||(Xd={}));class ec{constructor(e){this._scriptLoader=e}load(e,t,n=!1){return i=this,r=void 0,a=function*(){const i=e.config.testMode||!1,r=this._getScriptURI(t,i,n);return this._scriptLoader.loadScript(r).then(()=>{if(!function(e){return"AfterPay"in e}(window))throw new mi;return window.AfterPay})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a}_getScriptURI(e,t,n=!1){return"US"===e?n?t?Xd.HTTPS_SANDBOX:Xd.HTTPS_PROD:t?Xd.SANDBOX:Xd.PROD:n?t?Qd.HTTPS_SANDBOX:Qd.HTTPS_PROD:t?Qd.SANDBOX:Qd.PROD}}const tc=vi(e=>new Zd(e,new ec(o())),[{gateway:"afterpay"},{id:"afterpay"}]);var nc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ic{constructor(e,t){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t}initialize(e){return nc(this,void 0,void 0,function*(){const{methodId:t,amazonpay:n}=e;if(!t)throw new fi('Unable to proceed because "methodId" argument is not provided.');const i=this.paymentIntegrationService.getState(),{features:r}=i.getStoreConfigOrThrow().checkoutSettings,o=i.getPaymentMethodOrThrow(t),a=o.initializationData||{},{paymentToken:s="",region:d="",isButtonMicroTextDisabled:c}=a;if(yield this.amazonPayV2PaymentProcessor.initialize(o),this._isReadyToPay(s))(null==n?void 0:n.editButtonId)&&this._bindEditButton(n.editButtonId,s,"changePayment",this._isModalFlow(d));else{const{id:e}=this._createContainer();if(this._amazonPayButton=this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:i,containerId:e,decoupleCheckoutInitiation:this._isOneTimeTransaction(r,d.toUpperCase()),methodId:t,placement:si.Checkout,isButtonMicroTextDisabled:c}),!this._amazonPayButton)throw new fi("Unable to render the Amazon Pay button to an invalid HTML container element.")}})}execute(e,t){return nc(this,void 0,void 0,function*(){const{payment:n}=e;if(!n)throw new co(["payment"]);const{methodId:i}=n,r=this.paymentIntegrationService.getState(),{features:o}=r.getStoreConfigOrThrow().checkoutSettings,a=r.getPaymentMethodOrThrow(i).initializationData||{},{paymentToken:s="",region:d=""}=a;if(this._isReadyToPay(s)||this._isOneTimeTransaction(o,d.toUpperCase())){const n={methodId:i,paymentData:{nonce:s||"apb"}};yield this.paymentIntegrationService.submitOrder(e,t);try{return void(yield this.paymentIntegrationService.submitPayment(n))}catch(e){if(!(pa(e)&&(c=e.body,"object"==typeof c&&null!==c&&"status"in c&&"additional_action_required"in c&&"additional_action_required"===c.status&&"data"in c.additional_action_required&&"redirect_url"in c.additional_action_required.data&&"string"==typeof c.additional_action_required.data.redirect_url)))throw e;const{additional_action_required:t}=e.body,{redirect_url:n}=t.data;if(s)return new Promise(()=>window.location.assign(n));this.amazonPayV2PaymentProcessor.prepareCheckout(JSON.parse(n))}}var c;return this._getAmazonPayButton().click(),this._isModalFlow(d)?new Promise((e,t)=>{const n=()=>{window.removeEventListener("focus",n),t(new Wi("Shopper needs to login to Amazonpay to continue"))};window.addEventListener("focus",n)}):new Promise(ce)})}finalize(){return Promise.reject(new Cd)}deinitialize(){return nc(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize(),this._amazonPayButton=void 0})}_bindEditButton(e,t,n,i){const r=document.getElementById(e);if(r&&r.parentNode){if(!i){const e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener("click",()=>{this._showLoadingSpinner()})}this.amazonPayV2PaymentProcessor.bindButton(e,t,n)}}_isModalFlow(e){return"us"===e}_showLoadingSpinner(){return nc(this,void 0,void 0,function*(){yield this.paymentIntegrationService.widgetInteraction(()=>new Promise(ce))})}_createContainer(){let e=document.getElementById("AmazonPayButton");return e||(e=document.createElement("div"),e.id="AmazonPayButton",e.style.display="none",document.body.appendChild(e))}_getAmazonPayButton(){return ii(this._amazonPayButton,()=>new ri(ei.PaymentNotInitialized))}_isOneTimeTransaction(e,t){return this.amazonPayV2PaymentProcessor.isPh4Enabled(e,t)&&e["INT-6399.amazon_pay_apb"]}_isReadyToPay(e){return!!e}}const rc=vi(e=>new ic(e,gi()),[{id:"amazonpay"}]);var oc,ac=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.Shipping="Shipping",e.Subtotal="Subtotal",e.StoreCredit="Store Credit"}(oc||(oc={}));class sc{constructor(e,t,n,i,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._braintreeSdk=i,this._applePayScriptLoader=r,this._shippingLabel=oc.Shipping,this._subTotalLabel=oc.Subtotal,this._storeCreditLabel=oc.StoreCredit}initialize(e){var t,n,i,r;return ac(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new fi('Unable to submit payment because "options.methodId" argument is not provided.');const{methodId:o}=e;yield this._applePayScriptLoader.loadSdk(),this._shippingLabel=(null===(t=e.applepay)||void 0===t?void 0:t.shippingLabel)||oc.Shipping,this._subTotalLabel=(null===(n=e.applepay)||void 0===n?void 0:n.subtotalLabel)||oc.Subtotal,this._storeCreditLabel=(null===(i=e.applepay)||void 0===i?void 0:i.storeCreditLabel)||oc.StoreCredit;const a=(yield this._paymentIntegrationService.loadPaymentMethod(o)).getPaymentMethodOrThrow(o);(null===(r=a.initializationData)||void 0===r?void 0:r.gateway)===Vi.BRAINTREE&&a.clientToken&&this._braintreeSdk.initialize(a.clientToken)})}execute(e,t){return ac(this,void 0,void 0,function*(){const{payment:n}=e,i=this._paymentIntegrationService.getState();if(!n)throw new co(["payment"]);const{methodId:r}=n,o=i.getPaymentMethodOrThrow(r),a=this._getBaseRequest(i,o),s=this._sessionFactory.create(a);return yield this._paymentIntegrationService.submitOrder({useStoreCredit:e.useStoreCredit},t),s.begin(),new Promise((e,t)=>{this._handleApplePayEvents(s,o,{resolve:e,reject:t})})})}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_getBaseRequest(e,t){const n=e.getCheckoutOrThrow(),i=e.getCartOrThrow(),r=e.getStoreConfigOrThrow(),{storeProfile:{storeCountryCode:o,storeName:a}}=r,{currency:{code:s,decimalPlaces:d}}=i,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=t,{grandTotal:u,isStoreCreditApplied:h,outstandingBalance:p}=n,m=[{label:this._subTotalLabel,amount:`${n.subtotal.toFixed(d)}`}];if(n.taxes.forEach(e=>m.push({label:e.name,amount:`${e.amount.toFixed(d)}`})),m.push({label:this._shippingLabel,amount:`${n.shippingCostTotal.toFixed(d)}`}),h){const{storeCredit:t}=e.getCustomerOrThrow();m.push({label:this._storeCreditLabel,amount:`-${Math.min(u,t).toFixed(d)}`})}return{countryCode:o,currencyCode:s,merchantCapabilities:c,supportedNetworks:l,lineItems:m,total:{label:a,amount:`${p.toFixed(d)}`,type:"final"}}}_handleApplePayEvents(e,t,n){e.onvalidatemerchant=n=>ac(this,void 0,void 0,function*(){try{const{body:i}=yield this._onValidateMerchant(t,n);e.completeMerchantValidation(i)}catch(e){throw new Error("Merchant validation failed")}}),e.oncancel=()=>ac(this,void 0,void 0,function*(){return n.reject(new Wi("Continue with applepay"))}),e.onpaymentauthorized=i=>this._onPaymentAuthorized(i,e,t,n)}_onValidateMerchant(e,t){return ac(this,void 0,void 0,function*(){const n=[`validationUrl=${t.validationURL}`,`merchantIdentifier=${e.initializationData.merchantId}`,`displayName=${e.initializationData.storeName}`,`domainName=${window.location.hostname}`].join("&");return this._requestSender.post(`${e.initializationData.paymentsUrl}/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})})}_onPaymentAuthorized(e,t,n,i){var r;return ac(this,void 0,void 0,function*(){const{token:o}=e.payment;let a;(null===(r=n.initializationData)||void 0===r?void 0:r.gateway)===Vi.BRAINTREE&&(a=yield this._getBraintreeDeviceData());const s={methodId:n.id,paymentData:{deviceSessionId:a,formattedPayload:{apple_pay_token:{payment_data:o.paymentData,payment_method:o.paymentMethod,transaction_id:o.transactionIdentifier}}}};try{return yield this._paymentIntegrationService.submitPayment(s),t.completePayment(ApplePaySession.STATUS_SUCCESS),i.resolve()}catch(e){return t.completePayment(ApplePaySession.STATUS_FAILURE),i.reject(new ri(ei.PaymentNotInitialized))}})}_getBraintreeDeviceData(){return ac(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}const dc=vi(e=>{const{getHost:t}=e.getState(),i=new Ei(e);return new sc(n({host:t()}),e,new Zi,new Ui(new Hi(a(),window,i)),new Qi(new r))},[{id:"applepay"}]),cc={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},lc=function({styles:e}){const t={};return e.color&&(t.color=e.color),e.layout&&(t.layout=e.layout),(e["logo-type"]||e["logo-position"])&&(t.logo={},e["logo-type"]&&(t.logo.type=e["logo-type"]),e["logo-position"]&&(t.logo.position=e["logo-position"])),e.ratio&&(t.ratio=e.ratio),(e["text-color"]||e["text-size"])&&(t.text={},e["text-color"]&&(t.text.color=e["text-color"]),e["text-size"]&&(t.text.size=+e["text-size"])),t};function uc(e){return"object"==typeof e&&null!==e&&"bigpayToken"in e&&"defaultInstrument"in e&&"provider"in e&&"trustedShippingAddress"in e&&"method"in e&&"type"in e}var hc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.paypalSdkHelper=n,this.loadingIndicator=i}initialize(e){return hc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments:n}=e||{};if(this.bigcommerce_payments=n,!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(t),{container:o,bannerContainerId:a}=n,{orderId:s,paypalBNPLConfiguration:d=[],isPayPalCreditAvailable:c}=r.initializationData||{};if(void 0!==a){if(!document.getElementById(a))return void console.error("Unable to create banner without valid banner container ID.");const e=null==d?void 0:d.find(({id:e})=>"checkout"===e);if(c||!(null==e?void 0:e.status))return;const t=yield this.paypalSdkHelper.getPayPalMessages(r,i.getCartOrThrow().currency.code);return t&&"function"==typeof(null==t?void 0:t.Messages)?this.renderMessages(t,a,e):void console.error("[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK")}s?this.orderId=s:(this.loadingIndicatorContainer=null==o?void 0:o.split("#")[1],yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t),n.onInit&&"function"==typeof n.onInit&&n.onInit(()=>this.renderButton(t,n)),(void 0===n.shouldRenderPayPalButtonOnInitialization||n.shouldRenderPayPalButtonOnInitialization)&&this.renderButton(t,n))})}execute(e,t){return hc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{var i;this.bigcommerce_payments&&(null===(i=this.paypalButton)||void 0===i||i.close(),this.renderButton(n.methodId,this.bigcommerce_payments),this.handleError(new Error("INSTRUMENT_DECLINED"),r)),t()})),this.handleError(e,r),Promise.reject()}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}prepareVaultedInstrumentPaymentPayload(e,t,n){const{instrumentId:i,shouldSetAsDefaultInstrument:r}=n,o=!this.isTrustedVaultingFlow(n);return o?{methodId:e,paymentData:{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}:{methodId:e,paymentData:{instrumentId:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t},bigpay_token:{token:i}}}}}preparePaymentPayload(e,t,n){const{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:r=!1}=jd(n)?n:{};return{methodId:e,paymentData:{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}}renderButton(e,t){var n,i,r,o;const a=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:d}=s.initializationData||{},{checkoutPaymentButtonStyles:c}=d||{},{container:l,onError:u,onRenderButton:h,onValidate:p,submitForm:m}=t;if(!l)throw new fi('Unable to initialize payment because "container" argument is not provided.');const y=Object.assign(Object.assign({},this.isAppSwitchEnabled(e)&&{appSwitchWhenAvailable:!0}),{fundingSource:a.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(c),createOrder:()=>this.createOrder(),onClick:(e,t)=>this.handleClick(t,p),onApprove:e=>this.handleApprove(e,m),onError:e=>this.handleError(e,u),onCancel:()=>this.toggleLoadingIndicator(!1)});this.paypalButton=a.Buttons(y),this.paypalButton.isEligible()&&(h&&"function"==typeof h&&h(),(null===(i=(n=this.paypalButton).hasReturned)||void 0===i?void 0:i.call(n))&&this.isAppSwitchEnabled(e)?null===(o=(r=this.paypalButton).resume)||void 0===o||o.call(r):this.paypalButton.render(l))}handleClick(e,t){return hc(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;yield null==t?void 0:t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,null==t||t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createOrder(){return hc(this,void 0,void 0,function*(){const e=this.getFieldsValues();return this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_paymentscheckout",{shouldSaveInstrument:(null==e?void 0:e.shouldSaveInstrument)||!1})})}getFieldsValues(){const{getFieldsValues:e}=this.bigcommerce_payments||{};return"function"==typeof e?e():void 0}isTrustedVaultingFlow(e){if(e&&xd(e)){const t=this.paymentIntegrationService.getState().getInstruments(),n=null==t?void 0:t.find(t=>uc(t)&&t.bigpayToken===e.instrumentId);return!(uc(n)&&!n.trustedShippingAddress)}return!1}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isPayPalVaultedInstrumentPaymentData(e){return!!e&&xd(e)&&jd(e)}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:lc(n)};e.Messages(i).render(`#${t}`)}isProviderError(e){var t,n,i;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"INSTRUMENT_DECLINED"===(null===(i=null===(n=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===n?void 0:n.provider_error)||void 0===i?void 0:i.code)}isAppSwitchEnabled(e){var t,n;return null!==(n=null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)&&void 0!==n&&n}}const mc=vi(e=>new pc(e,_r(e),Rr(),new vd({containerStyles:cc})),[{id:"bigcommerce_payments"}]);function yc(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var gc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsRequestSender=t,this.bigCommercePaymentsSdk=n,this.bigCommercePaymentsFastlaneUtils=i}initialize(e){var t,n;return gc(this,void 0,void 0,function*(){const{methodId:i,bigcommerce_payments_fastlane:r}=e;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(this.methodId=i,!r)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_fastlane" argument is not provided.');if(this.bigcommerce_payments_fastlane=r,!r.onInit||"function"!=typeof r.onInit)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_fastlane.onInit" argument is not provided or it is not a function.');if(!r.onChange||"function"!=typeof r.onChange)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_fastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState(),a=o.getCartOrThrow(),s=o.getPaymentMethodOrThrow(i),{isDeveloperModeApplicable:d,isFastlaneStylingEnabled:c}=s.initializationData||{};this.threeDSVerificationMethod=null===(t=s.initializationData)||void 0===t?void 0:t.threeDSVerificationMethod,this.paypalFastlaneSdk=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(s,a.currency.code,a.id);const l=qr(c?null===(n=null==s?void 0:s.initializationData)||void 0===n?void 0:n.fastlaneStyles:{},null==r?void 0:r.styles);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(this.paypalFastlaneSdk,!!d,l),this.shouldRunAuthenticationFlow()&&(yield this.runPayPalAuthenticationFlowOrThrow(i)),yield this.initializePayPalPaymentComponent(),r.onInit(e=>this.renderPayPalPaymentComponent(e)),r.onChange(()=>this.handlePayPalStoredInstrumentChange(i))})}execute(e,t){return gc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const{getHost:t}=e.getState();return new vc(e,new vr(n({host:t()})),Rr(),jr())},[{id:"bigcommerce_payments_fastlane"}]);var Sc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class _c{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=n,this.paypalSdkHelper=i}initialize(e){return Sc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_paylater:n}=e||{};if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(t),{paypalBNPLConfiguration:o=[],orderId:a}=r.initializationData||{},{bannerContainerId:s,container:d}=n;if(void 0!==s){if(!document.getElementById(s))return void console.error("Unable to create banner without valid banner container ID.");const e=o&&o.find(({id:e})=>"checkout"===e);if(!(null==e?void 0:e.status))return;const t=yield this.paypalSdkHelper.getPayPalMessages(r,i.getCartOrThrow().currency.code);return this.renderMessages(t,s,e)}a?this.orderId=a:(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t),this.loadingIndicatorContainer=null==d?void 0:d.split("#")[1],this.renderButton(t,n))})}execute(e,t){return Sc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(h)return;const t={fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.bigCommercePaymentsButtons=n.Buttons(t),this.bigCommercePaymentsButtons.isEligible()||e!==n.FUNDING.PAYLATER){if(!this.bigCommercePaymentsButtons.isEligible()&&e===n.FUNDING.CREDIT)throw new Si(`BigCommercePayments ${e} is not available for your region. Please use BigCommercePayments Checkout instead.`);d&&"function"==typeof d&&d(),this.bigCommercePaymentsButtons.render(a),h=!0}})}handleClick(e,t){return Sc(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;t&&"function"==typeof t&&(yield t(()=>(this.toggleLoadingIndicator(!0),n()),i))})}handleApprove({orderID:e},t){this.orderId=e,t&&"function"==typeof t&&t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:lc(n)};e.Messages(i).render(`#${t}`)}}const wc=vi(e=>new _c(e,_r(e),new vd({containerStyles:cc}),Rr()),[{id:"bigcommerce_payments_paylater"}]);class Ic extends nr{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}var Cc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class bc{constructor(e,t,n,i=3e3,r=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=n,this.pollingInterval=i,this.maxPollingIntervalTime=r,this.pollingTimer=0,this.stopPolling=ce}initialize(e){return Cc(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,bigcommerce_payments_ratepay:i}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_ratepay" argument is not provided.');const{legalTextContainer:r,container:o,loadingContainerId:a}=i;if(!o)throw new fi('Unable to initialize payment because "options.container" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.legalTextContainer" argument is not provided.');if(!a)throw new fi('Unable to initialize payment because "options.loadingContainerId" argument is not provided.');this.loadingIndicatorContainer=a;const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t),{merchantId:d}=s.initializationData||{};if(!d)throw new fi("Unable to initialize payment because merchantId argument is not provided.");this.bigcommerce_payments_ratepay=i,yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n),this.createFraudNetScript(d,n,t),this.loadFraudnetConfig(),this.renderLegalText(r,o)})}execute(e,t){return Cc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.initializePollingMechanism(n.methodId,e,t,n.gatewayId)})}catch(e){return this.handleError(e),new Promise((e,t)=>t())}})}finalize(){return Promise.reject(new Cd)}deinitialize(){const{legalTextContainer:e}=this.bigcommerce_payments_ratepay||{},t=document.querySelectorAll('[data-id="fraudnetScript"]')[0],n=document.querySelectorAll('[data-id="fraudnetConfig"]')[0];if(this.deinitializePollingMechanism(),t.remove(),n.remove(),e){const t=document.getElementById(e);null==t||t.remove()}return Promise.resolve()}normalizeDate(e){const t=this.formatDate(e.getDate()),n=this.formatDate(e.getMonth()+1);return`${e.getFullYear()}-${n}-${t}`}formatDate(e){return`${e<10?0:""}${e}`}renderLegalText(e,t){const n=e,i=t.split("#")[1],r=document.getElementById(i),o=null==r?void 0:r.parentNode,a=document.createElement("div");a.style.marginBottom="20px",a.setAttribute("id",n),null==o||o.prepend(a);const s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=s.Legal({fundingSource:s.Legal.FUNDING.PAY_UPON_INVOICE});if(!document.getElementById(n))throw new fi('Unable to initialize payment because "legalTextContainerElement" argument is not found.');d.render(`#${n}`)}handleError(e){const{onError:t}=this.bigcommerce_payments_ratepay||{};this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createFraudNetScript(e,t,n){const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{testMode:r}=i.config,o=document.createElement("script");o.setAttribute("type","application/json"),o.setAttribute("fncls","fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99"),o.setAttribute("data-id","fraudnetScript"),this.guid=this.generateGUID();const a={f:this.guid,s:`${e}_checkout-page`,sandbox:r};o.innerHTML=JSON.stringify(a),document.body.appendChild(o)}generateGUID(){let e="";for(let t=0;t<32;t+=1)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(62*Math.random())];return e}loadFraudnetConfig(){const e=document.createElement("script");e.setAttribute("data-id","fraudnetConfig"),e.src="https://c.paypal.com/da/r/fb.js",document.body.appendChild(e)}reinitializeStrategy(e){return Cc(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}initializePollingMechanism(e,t,n,i){return Cc(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.bigCommercePaymentsIntegrationService.getOrderStatus("bigcommerce_payments_apms",{params:{useMetadata:!0}}),o=r===cr.PollingStop,a=r===cr.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimernew bc(e,_r(e),new vd({containerStyles:Object.assign(Object.assign({},cc),{position:"fixed"})})),[{gateway:"bigcommerce_payments_apms",id:"ratepay"}]);var Oc;!function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification",e.CardExpiryVerification="cardExpiryVerification"}(Oc||(Oc={}));const Ec=Oc;function Ac(e){return Ec.CardNumber in e&&Ec.CardName in e&&Ec.CardExpiry in e}function Tc(e){return Ec.CardNumberVerification in e&&Ec.CardCodeVerification in e&&Ec.CardExpiryVerification in e}var kc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Dc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdk=n,this.bigCommercePaymentsFastlaneUtils=i}initialize(e){return kc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_creditcards:n}=e,i=n,{form:r,onCreditCardFieldsRenderingError:o,onLoadComplete:a}=i||{};if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new fi('Unable to proceed because "options.bigcommerce_payments_creditcards.form" argument is not provided.');this.hostedFormOptions=r,this.isCreditCardForm=Ac(r.fields),this.isCreditCardVaultedForm=Tc(r.fields)&&!this.hasUndefinedValues(),yield this.paymentIntegrationService.loadPaymentMethod(t),yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t,void 0,!0,!0),(this.isCreditCardForm||this.isCreditCardVaultedForm)&&(yield this.initializeFields(r,o)),null==a||a(),this.shouldInitializePayPalFastlane(t)&&(yield this.initializePayPalFastlaneOrThrow(t))})}execute(e,t){return kc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(n===ir.No||n===ir.Unknown)throw new Error;return this.handleApprove({orderID:e,vaultSetupToken:t})},onError:()=>{throw new Qr},inputEvents:{onChange:t=>this.onChangeHandler(e,t),onFocus:t=>this.onFocusHandler(e,t),onBlur:t=>this.onBlurHandler(e,t),onInputSubmitRequest:t=>this.onInputSubmitRequest(e,t)}},o);if(this.cardFields=yield r.CardFields(a),!this.cardFields.isEligible())throw new ri(ei.PaymentNotInitialized);try{this.stylizeInputContainers(n),Ac(n)&&(yield this.renderFields(n)),Tc(n)&&(yield this.renderVaultedFields(n))}catch(e){"function"==typeof t&&t(e)}})}getExecuteCallback(e){return Tc(e)?this.createVaultSetupTokenCallback():this.createOrderCallback()}createVaultSetupTokenCallback(){return{createVaultSetupToken:()=>kc(this,void 0,void 0,function*(){const{setupToken:e}=(yield this.bigCommercePaymentsIntegrationService.createOrderCardFields("bigcommerce_payments_creditcardscheckout",Object.assign(Object.assign({},this.getInstrumentParams()),{setupToken:!0})))||{};return e})}}createOrderCallback(){return{createOrder:()=>kc(this,void 0,void 0,function*(){const{orderId:e}=(yield this.bigCommercePaymentsIntegrationService.createOrderCardFields("bigcommerce_payments_creditcardscheckout",this.getInstrumentParams()))||{};return e})}}handleApprove({orderID:e,vaultSetupToken:t}){e&&(this.returnedOrderId=e),t&&(this.returnedVaultedToken=t)}renderFields(e){var t,n,i,r;return kc(this,void 0,void 0,function*(){const o=this.getCardFieldsOrThrow();(null===(t=e.cardCode)||void 0===t?void 0:t.containerId)&&(this.cvvField=o.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCode.containerId}`)),(null===(n=e.cardExpiry)||void 0===n?void 0:n.containerId)&&(this.expiryField=o.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiry.containerId}`)),(null===(i=e.cardName)||void 0===i?void 0:i.containerId)&&(this.nameField=o.NameField({placeholder:""}),yield this.nameField.render(`#${e.cardName.containerId}`)),(null===(r=e.cardNumber)||void 0===r?void 0:r.containerId)&&(this.numberField=o.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumber.containerId}`))})}renderVaultedFields(e){var t,n,i;return kc(this,void 0,void 0,function*(){const r=this.getCardFieldsOrThrow();(null===(t=e.cardCodeVerification)||void 0===t?void 0:t.containerId)&&(this.cvvField=r.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCodeVerification.containerId}`)),(null===(n=e.cardExpiryVerification)||void 0===n?void 0:n.containerId)&&(this.expiryField=r.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiryVerification.containerId}`)),(null===(i=e.cardNumberVerification)||void 0===i?void 0:i.containerId)&&(this.numberField=r.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumberVerification.containerId}`))})}getInstrumentParams(){if(!this.executionPaymentData)return{};if(jd(this.executionPaymentData)){const{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}=this.executionPaymentData;return{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}}if(xd(this.executionPaymentData)){const{instrumentId:e}=this.executionPaymentData;return{instrumentId:e}}return{}}getFieldTypeByEmittedField({emittedBy:e}){return{fieldType:this.mapFieldType(e)}}submitHostedForm(){return kc(this,void 0,void 0,function*(){const e=this.getCardFieldsOrThrow(),t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),n={billingAddress:{company:t.company,addressLine1:t.address1,addressLine2:t.address2,adminArea1:t.stateOrProvinceCode,adminArea2:t.city,postalCode:t.postalCode,countryCode:t.countryCode}};try{this.isCreditCardVaultedForm?yield e.submit():yield e.submit(n)}catch(e){throw new Qr("Failed authentication. Please try to authorize again.")}})}validateHostedFormOrThrow(){var e,t;return kc(this,void 0,void 0,function*(){const n=this.getCardFieldsOrThrow(),i=yield n.getState().then(e=>e),r=this.getValidityData(i);if(!r.isValid)throw null===(t=null===(e=this.hostedFormOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,r),new lo(this.mapValidationErrors(r.errors))})}getValidityData({fields:e}){const t=Object.assign({},e);delete t.cardNameField;const n=Object.keys(t);return{isValid:n.every(e=>{var n;return null===(n=t[e])||void 0===n?void 0:n.isValid}),errors:n.reduce((e,n)=>{var i;const r=this.mapFieldType(n);return Object.assign(Object.assign({},e),{[r]:(null===(i=t[n])||void 0===i?void 0:i.isValid)?void 0:[this.getInvalidErrorByFieldType(r)]})},{})}}getInvalidErrorByFieldType(e){switch(e){case Ec.CardCode:case Ec.CardCodeVerification:return{fieldType:e,message:"Invalid card code",type:"invalid_card_code"};case Ec.CardNumber:case Ec.CardNumberVerification:return{fieldType:e,message:"Invalid card number",type:"invalid_card_number"};case Ec.CardExpiry:case Ec.CardExpiryVerification:return{fieldType:e,message:"Invalid card expiry",type:"invalid_card_expiry"};default:return{fieldType:e,message:"Invalid field",type:"invalid"}}}mapValidationErrors(e={}){const t={};return Object.keys(e).forEach(n=>{var i,r;t[n]=[{message:(null===(r=null===(i=e[n])||void 0===i?void 0:i[0])||void 0===r?void 0:r.message)||"",type:n}]}),t}mapFieldType(e){switch(e){case"name":return Ec.CardName;case"cardNumberField":case"number":return this.isCreditCardForm?Ec.CardNumber:Ec.CardNumberVerification;case"cardExpiryField":case"expiry":return this.isCreditCardForm?Ec.CardExpiry:Ec.CardExpiryVerification;case"cardCvvField":case"cvv":return this.isCreditCardForm?Ec.CardCode:Ec.CardCodeVerification;default:throw new Error("Unexpected field type")}}getCardFieldsOrThrow(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);return this.cardFields}getInputStyles(e){var t,n,i;const r={"font-size":(null===(t=null==e?void 0:e.default)||void 0===t?void 0:t.fontSize)||"1rem","font-family":(null===(n=null==e?void 0:e.default)||void 0===n?void 0:n.fontFamily)||"Montserrat, Arial, Helvetica, sans-serif","font-weight":(null===(i=null==e?void 0:e.default)||void 0===i?void 0:i.fontWeight)||"400",outline:"none",padding:"9px 13px"},o=Object.assign(Object.assign({},r),{color:"#333333"});return{input:o,".invalid":Object.assign(Object.assign({},r),{color:"red"}),".valid":o,":focus":o}}stylizeInputContainers(e){Object.values(e||{}).forEach(e=>{const t=document.getElementById(`${(null==e?void 0:e.containerId)||""}`);t&&(t.style.padding="0px",t.style.boxShadow="none",t.style.border="none",t.style.background="transparent",t.style.marginBottom="10px",t.style.marginLeft="-5px")})}hasUndefinedValues(){return!this.hostedFormOptions||Object.values(this.hostedFormOptions.fields).some(e=>void 0===e)}onChangeHandler(e,t){var n;null===(n=null==e?void 0:e.onValidate)||void 0===n||n.call(e,this.getValidityData(t))}onFocusHandler(e,t){var n;null===(n=null==e?void 0:e.onFocus)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onBlurHandler(e,t){var n;null===(n=null==e?void 0:e.onBlur)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onInputSubmitRequest(e,t){var n;null===(n=null==e?void 0:e.onEnter)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}shouldInitializePayPalFastlane(e){var t,n;const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(e),o=i.getPaymentProviderCustomer(),a=(s=o)&&("authenticationState"in s||"addresses"in s||"instruments"in s)?o:{};var s;return(null===(t=null==r?void 0:r.initializationData)||void 0===t?void 0:t.isAcceleratedCheckoutEnabled)&&(null===(n=null==r?void 0:r.initializationData)||void 0===n?void 0:n.isBigCommercePaymentsAnalyticsV2Enabled)&&!(null==a?void 0:a.authenticationState)}initializePayPalFastlaneOrThrow(e){return kc(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getPaymentMethodOrThrow(e),{initializationData:r}=i;if(!(null==r?void 0:r.connectClientToken))return;const o=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(i,n.currency.code,n.id);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(o,!!(null==r?void 0:r.isDeveloperModeApplicable))}catch(e){}})}}const Mc=vi(e=>new Dc(e,_r(e),Rr(),jr()),[{id:"bigcommerce_payments_creditcards"}]);var zc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Nc{constructor(e,t,n,i,r=3e3,o=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdkHelper=n,this.loadingIndicator=i,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.pollingTimer=0,this.stopPolling=ce,this.isPollingEnabled=!1}initialize(e){return zc(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,bigcommerce_payments_apms:i}=e;if(this.bigCommercePaymentsAlternativeMethods=i,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_apms" argument is not provided.');const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(n,t),{orderId:a,shouldRenderFields:s}=o.initializationData||{},d=r.getStoreConfigOrThrow().checkoutSettings.features;this.isPollingEnabled=Ci(d,"PAYPAL-5624.bcp_ideal_polling"),a?this.orderId=a:(this.paypalApms=yield this.bigCommercePaymentsSdkHelper.getPayPalApmsSdk(o,r.getCartOrThrow().currency.code),this.loadingIndicatorContainer=i.container.split("#")[1],this.renderButton(n,t,i),s&&this.renderFields(n,i))})}execute(e,t){return zc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.initializePollingMechanism(r,e,t,o)})),this.isNonInstantPaymentMethod(r)||(yield this.paymentIntegrationService.submitOrder(i,t)),yield this.bigCommercePaymentsIntegrationService.submitPayment(r,this.orderId,o)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,this.isPollingEnabled&&this.resetPollingMechanism(),null===(e=this.bigCommercePaymentsButton)||void 0===e||e.close(),Promise.resolve()}initializePollingMechanism(e,t,n,i){return zc(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.bigCommercePaymentsIntegrationService.getOrderStatus(i),o=r===cr.Approved,a=r===cr.PollingError;if(o)return this.deInitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimern.onInitButton(t),createOrder:()=>this.onCreateOrder(e,t,n),onApprove:e=>this.handleApprove(e,c),onCancel:()=>{this.toggleLoadingIndicator(!1),this.deInitializePollingMechanism()},onError:e=>{this.deInitializePollingMechanism(),this.handleFailure(e,s)},onClick:(e,t)=>zc(this,void 0,void 0,function*(){return n.onValidate(t.resolve,t.reject)})};this.bigCommercePaymentsButton=i.Buttons(l),this.bigCommercePaymentsButton.isEligible()&&(d&&"function"==typeof d&&d(),this.bigCommercePaymentsButton.render(a))}onCreateOrder(e,t,n){return zc(this,void 0,void 0,function*(){const{onValidate:i}=n;yield i(()=>(this.toggleLoadingIndicator(!0),()=>Promise.resolve()),ce);const r=yield this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apms");if(this.isNonInstantPaymentMethod(e)){const n={useStoreCredit:!1},i={params:{methodId:e,gatewayId:t}};yield this.paymentIntegrationService.submitOrder(n,i),yield this.bigCommercePaymentsIntegrationService.submitPayment(e,r,t)}return r})}handleApprove({orderID:e},t){this.orderId=e,t()}handleFailure(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderFields(e,t){const n=this.getPaypalAmpsSdkOrThrow(),i=this.paymentIntegrationService.getState(),{firstName:r,lastName:o,email:a}=i.getBillingAddressOrThrow(),{apmFieldsContainer:s,apmFieldsStyles:d}=t;if(!s)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_apms" argument should contain "apmFieldsContainer".');const c=document.querySelector(s);c&&(c.innerHTML="");const l={fundingSource:e,style:d||{},fields:{name:{value:`${r} ${o}`},email:{value:a}}};n.PaymentFields(l).render(s)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isNonInstantPaymentMethod(e){return e.toUpperCase()in dr}getPaypalAmpsSdkOrThrow(){if(!this.paypalApms)throw new mi;return this.paypalApms}}const xc=vi(e=>new Nc(e,_r(e),Rr(),new vd({containerStyles:cc})),[{gateway:"bigcommerce_payments_apms"}]);class Rc{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){const{gatewayId:t,methodId:n,bigcommerce_payments_apms:i}=e;if(this.bigCommercePaymentsAlternativeMethods=i,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');return Promise.resolve()}execute(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{window.location.replace(t),n()})}return this.handleError(e),Promise.reject(e)}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}handleError(e){const{onError:t}=this.bigCommercePaymentsAlternativeMethods||{};t&&"function"==typeof t&&t(e)}}const Fc=vi(e=>new Rc(e,_r(e)),[{gateway:"bigcommerce_payments_apms",id:"klarna"},{gateway:"bigcommerce_payments_apms",id:"afterpay"}]);var Lc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Bc{constructor(e,t,n){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=n}initialize(e){var t,n;return Lc(this,void 0,void 0,function*(){const{methodId:i,bigcommerce_payments_venmo:r}=e||{};if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i);(null===(t=o.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(n=o.initializationData)||void 0===n?void 0:n.orderId:(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i),this.loadingIndicatorContainer=r.container.split("#")[1],this.renderButton(i,r))})}execute(e,t){return Lc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rthis.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmocheckout"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=n.Buttons(u),!this.paypalButton.isEligible())throw new Si("Venmo is not available for your region. Please another payment method instead.");d&&"function"==typeof d&&d(),this.paypalButton.render(a)}handleClick(e,t){return Lc(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;yield t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,t(),this.toggleLoadingIndicator(!1)}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const jc=vi(e=>new Bc(e,_r(e),new vd({styles:{backgroundColor:"black"}})),[{id:"bigcommerce_payments_venmo"}]);class Uc{initialize(e){this._blueSnapSdk=e}initialize3ds(e,t){return n=this,i=void 0,o=function*(){const n=this._getBlueSnapSdk();return new Promise((i,r)=>{n.threeDsPaymentsSetup(e,e=>"1"===e.code?i(e.threeDSecure.threeDSecureReferenceId):r(new Qr)),n.threeDsPaymentsSubmitData(t)})},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_getBlueSnapSdk(){return ii(this._blueSnapSdk,()=>new ri(ei.PaymentNotInitialized))}}function qc(e){return Ec.CardNumber in e}function Vc(e){return Ec.CardCodeVerification in e||Ec.CardNumberVerification in e}var Gc,Hc,Wc,$c,Yc,Kc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Jc{constructor(e,t,n,i){this._scriptLoader=e,this._paymentIntegrationService=t,this._blueSnapDirectHostedForm=n,this._blueSnapDirect3ds=i}initialize(e){return Kc(this,void 0,void 0,function*(){const{methodId:t,gatewayId:n,creditCard:i}=e;if(!n||!i)throw new fi;const r=yield this._paymentIntegrationService.loadPaymentMethod(n,{params:{method:t,bigpayToken:i.bigpayToken}}),{config:{testMode:o,is3dsEnabled:a},clientToken:s}=r.getPaymentMethodOrThrow(t,n);if(this._blueSnapSdk=yield this._scriptLoader.load(o),this._paymentFieldsToken=s,this._shouldUseHostedFields=qc(i.form.fields)||Vc(i.form.fields)&&!!i.form.fields.cardNumberVerification,this._shouldUseHostedFields){this._blueSnapDirectHostedForm.initialize(this._blueSnapSdk,i.form.fields);try{yield this._blueSnapDirectHostedForm.attach(this._getPaymentFieldsToken(),i,a)}catch(e){if(e instanceof fi)return;throw e}}})}execute(e){return Kc(this,void 0,void 0,function*(){if(!e.payment)throw new co(["payment"]);if(!this._blueSnapSdk)throw new co(["payment"]);const{paymentData:t}=e.payment,{shouldSaveInstrument:n,shouldSetAsDefaultInstrument:i}=jd(t)?t:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},r=this._getPaymentFieldsToken();let o;const{is3dsEnabled:a}=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.payment.methodId,e.payment.gatewayId).config,s=this._shouldUseHostedFields?yield this._blueSnapDirectHostedForm.validate().submit(a?this._getBlueSnapDirectThreeDSecureData():void 0,!(jd(t)&&xd(t))):void 0;if(yield this._paymentIntegrationService.submitOrder(),jd(t)&&xd(t)&&this._paymentFieldsToken&&t.instrumentId){if(a){this._blueSnapDirect3ds.initialize(this._blueSnapSdk);const{last4:e,brand:n}=this._paymentIntegrationService.getState().getCardInstrumentOrThrow(t.instrumentId),i=Object.assign({last4Digits:e,ccType:n.toUpperCase()},this._getBlueSnapDirectThreeDSecureData());o=yield this._blueSnapDirect3ds.initialize3ds(this._paymentFieldsToken,i)}yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e.payment),{paymentData:Object.assign(Object.assign(Object.assign({instrumentId:t.instrumentId},this._shouldUseHostedFields?{nonce:r}:{}),o?{deviceSessionId:o}:{}),{shouldSetAsDefaultInstrument:!!i})}))}else yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e.payment),{paymentData:{formattedPayload:{credit_card_token:{token:JSON.stringify({pfToken:r,cardHolderName:s&&s.cardHolderName})},vault_payment_instrument:n,set_as_default_stored_instrument:i}}}))})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this._shouldUseHostedFields&&this._blueSnapDirectHostedForm.detach(),Promise.resolve()}_getBlueSnapDirectThreeDSecureData(){var e;const{getBillingAddress:t,getShippingAddress:n,getCustomer:i,getCheckoutOrThrow:r,getCartOrThrow:o}=this._paymentIntegrationService.getState(),a=t(),s=n(),d=(null===(e=i())||void 0===e?void 0:e.email)||(null==a?void 0:a.email),c=(null==a?void 0:a.phone)||(null==s?void 0:s.phone);return Object.assign(Object.assign(Object.assign(Object.assign({amount:r().outstandingBalance,currency:o().currency.code},d&&{email:d}),c&&{phone:c}),a&&{billingFirstName:a.firstName,billingLastName:a.lastName,billingCountry:a.countryCode,billingCity:a.city,billingAddress:`${a.address1} ${a.address2}`.trim(),billingZip:a.postalCode}),s&&{shippingFirstName:s.firstName,shippingLastName:s.lastName,shippingCountry:s.countryCode,shippingCity:s.city,shippingAddress:`${s.address1} ${s.address2}`.trim(),shippingZip:s.postalCode})}_getPaymentFieldsToken(){return ii(this._paymentFieldsToken,()=>new ti(Xn.MissingPaymentToken))}}!function(e){e.AMEX="american-express",e.CHINA_UNION_PAY="unionpay",e.DINERS="diners-club",e.DISCOVER="discover",e.JCB="jcb",e.MASTERCARD="mastercard",e.UNKNOWN="unknown",e.VISA="visa"}(Gc||(Gc={})),function(e){e.ON_BLUR="onBlur",e.ON_SUBMIT="onSubmit"}(Hc||(Hc={})),function(e){e.EMPTY="empty",e.INVALID="invalid",e.THREE_DS_NOT_ENABLED="3D Secure is not enabled"}(Wc||(Wc={})),function(e){e.CC_NOT_SUPORTED="22013",e.ERROR_403="403",e.ERROR_404="404",e.ERROR_500="500",e.INVALID_OR_EMPTY="10",e.SESSION_EXPIRED="400",e.THREE_DS_AUTH_FAILED="14101",e.THREE_DS_CLIENT_ERROR="14103",e.THREE_DS_MISSING_FIELDS="14102",e.THREE_DS_NOT_ENABLED="14100",e.TOKEN_EXPIRED="14040",e.TOKEN_NOT_ASSOCIATED="14042",e.TOKEN_NOT_FOUND="14041"}($c||($c={})),function(e){e.CardCode="cvv",e.CardExpiry="exp",e.CardName="noc",e.CardNumber="ccn"}(Yc||(Yc={}));const Zc={[Yc.CardNumber]:Ec.CardNumber,[Yc.CardExpiry]:Ec.CardExpiry,[Yc.CardName]:Ec.CardName,[Yc.CardCode]:Ec.CardCode},Qc={empty:{[Ec.CardNumber]:{fieldType:"cardNumber",message:"Credit card number is required",type:"required"},[Ec.CardNumberVerification]:{fieldType:"cardNumber",message:"Credit card number is required",type:"required"},[Ec.CardExpiry]:{fieldType:"cardExpiry",message:"Expiration date is required",type:"required"},[Ec.CardCode]:{fieldType:"cardCode",message:"CVV is required",type:"required"},[Ec.CardName]:{fieldType:"cardName",message:"Full name is required",type:"required"}},invalid:{[Ec.CardNumber]:{fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},[Ec.CardNumberVerification]:{fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},[Ec.CardExpiry]:{fieldType:"cardExpiry",message:"Expiration date must be a valid future date in MM / YY format",type:"invalid_card_expiry"},[Ec.CardCode]:{fieldType:"cardCode",message:"CVV must be valid",type:"invalid_card_code"},[Ec.CardName]:{fieldType:"cardName",message:"Full name is required",type:"required"}}};class Xc{constructor(e,t){this._nameOnCardInput=e,this._hostedInputValidator=t}initialize(e,t){this._blueSnapSdk=e,t&&(qc(t)?this._hostedInputValidator.initialize():Vc(t)&&t.cardNumberVerification&&this._hostedInputValidator.initializeValidationFields())}attach(e,t,n){var i,r,o,a,s=t.form,{fields:d}=s,c=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const r=this._getHostedPaymentFieldsOptions(e,d,c,i,n);t.hostedPaymentFieldsCreate(r),qc(d)&&this._nameOnCardInput.attach(r,d.cardName.accessibilityLabel,d.cardName.placeholder)})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}validate(){var e;const t=this._hostedInputValidator.validate();if(null===(e=this._onValidate)||void 0===e||e.call(this,t),!t.isValid){const e=Object.entries(t.errors).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n.map(({message:e,type:t})=>({message:e,type:t}))}),{});throw new lo(e)}return this}submit(e,t=!1){return new Promise((n,i)=>this._getBlueSnapSdk().hostedPaymentFieldsSubmitData(e=>this._isBlueSnapDirectCallbackError(e)?i(new Qr(e.statusCode===$c.THREE_DS_AUTH_FAILED?e.error[0].errorDescription:`Submission failed with status: ${e.statusCode} and errors: ${JSON.stringify(e.error)}`)):n(Object.assign(Object.assign({},e.cardData),t?{cardHolderName:this._nameOnCardInput.getValue()}:{})),e))}detach(){this._nameOnCardInput.detach()}_isBlueSnapDirectCallbackError(e){return"error"in e}_getHostedPaymentFieldsOptions(e,t,{onFocus:n,onBlur:i,onValidate:r,onCardTypeChange:o,onEnter:a,styles:s},d,c){var l;return Object.assign(Object.assign(Object.assign({token:e,onFieldEventHandler:{setupComplete:()=>d(),onFocus:this._usetUiEventCallback(n),onBlur:this._usetUiEventCallback(i),onError:this._handleError(r),onType:(e,t)=>null==o?void 0:o({cardType:Gc[t]}),onEnter:this._usetUiEventCallback(a),onValid:e=>null==r?void 0:r(this._hostedInputValidator.validate({tagId:e}))}},qc(t)&&{ccnPlaceHolder:t.cardNumber.placeholder||"",cvvPlaceHolder:(null===(l=t.cardCode)||void 0===l?void 0:l.placeholder)||"",expPlaceHolder:t.cardExpiry.placeholder||"MM / YY"}),s&&{style:this._mapStyles(s)}),{"3DS":c})}_mapStyles({default:e,error:t,focus:n}){return Object.entries(Object.assign(Object.assign(Object.assign({},e&&{input:e}),t&&{".invalid":t}),n&&{":focus":n})).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:Object.entries(n).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[te(t)]:n}),{})}),{})}_handleError(e){return(t,n,i,r)=>{if(n===$c.INVALID_OR_EMPTY&&t&&function(e){return void 0!==e&&[Wc.EMPTY,Wc.INVALID].includes(e)}(i))return null==e?void 0:e(this._hostedInputValidator.validate({tagId:t,errorDescription:i}));throw new Qr(`An unexpected error has occurred: ${JSON.stringify({tagId:t,errorCode:n,errorDescription:i,eventOrigin:r})}`)}}_usetUiEventCallback(e){return t=>{e&&e({fieldType:Zc[t]})}}_getBlueSnapSdk(){return ii(this._blueSnapSdk,()=>new ri(ei.PaymentNotInitialized))}_setCustomBlueSnapAttributes(e){const{cardNumber:t,cardExpiry:n,cardCode:i,cardName:r}=e,o=document.getElementById(t.containerId),a=document.getElementById(n.containerId),s=i&&document.getElementById(i.containerId),d=document.getElementById(r.containerId);if(!(o&&a&&s&&d))throw new fi("Unable to create hosted payment fields to invalid HTML container elements.");o.dataset.bluesnap=Yc.CardNumber,a.dataset.bluesnap=Yc.CardExpiry,s.dataset.bluesnap=Yc.CardCode,d.dataset.bluesnap=Yc.CardName}_setCustomStoredCardsBlueSnapAttributes(e){const{cardNumberVerification:t,cardCodeVerification:n}=e,i=t&&document.getElementById(t.containerId),r=n&&document.getElementById(n.containerId);(i||r)&&(i&&(i.dataset.bluesnap=Yc.CardNumber),r&&(r.dataset.bluesnap=Yc.CardCode))}}class el{constructor(){this._errors={}}initialize(){this._errors={cardNumber:[Qc.empty.cardNumber],cardExpiry:[Qc.empty.cardExpiry],cardCode:[Qc.empty.cardCode],cardName:[Qc.empty.cardName]}}initializeValidationFields(){this._errors={cardNumberVerification:[Qc.empty.cardNumber]}}validate(e){return e&&this._updateErrors(e.tagId,e.errorDescription),{isValid:Object.values(this._errors).every(e=>0===e.length),errors:this._errors}}_updateErrors(e,t){const n=this._errors.cardNumberVerification?Ec.CardNumberVerification:Zc[e];this._errors[n]=t?[Qc[t][n]]:[]}}class tl{attach({style:e,onFieldEventHandler:{onFocus:t,onBlur:n,onValid:i,onError:r,onEnter:o}={}},a,s){var d;this._style=e,this._create(),this._getInput().addEventListener("focus",this._handleFocus(t)),this._getInput().addEventListener("blur",this._handleBlur(n,i,r)),this._getInput().addEventListener("enter",this._handleEnter(o)),a&&this._getInput().setAttribute("aria-label",a),s&&(this._getInput().placeholder=s),null===(d=document.querySelector('[data-bluesnap="noc"]'))||void 0===d||d.appendChild(this._getInput())}getValue(){return this._getInput().value}detach(){this._input&&(this._input.remove(),this._input=void 0)}_handleFocus(e){return()=>{var t;this._applyStyles(null===(t=this._style)||void 0===t?void 0:t[":focus"]),null==e||e(Yc.CardName)}}_handleBlur(e,t,n){return({target:i})=>{var r,o;null==e||e(Yc.CardName),i instanceof HTMLInputElement&&(/\w{1,200}/.test(i.value)?(this._applyStyles(null===(r=this._style)||void 0===r?void 0:r.input),null==t||t(Yc.CardName)):(this._applyStyles(null===(o=this._style)||void 0===o?void 0:o[".invalid"]),null==n||n(Yc.CardName,$c.INVALID_OR_EMPTY,Wc.EMPTY,Hc.ON_BLUR)))}}_handleEnter(e){return()=>null==e?void 0:e(Yc.CardName)}_applyStyles(e={}){const t={color:e.color,fontFamily:e["font-family"],fontSize:e["font-size"],fontWeight:e["font-weight"]},n=Object.keys(t);n.every(e=>["color","fontFamily","fontSize","fontWeight"].includes(e))&&n.forEach(e=>{t[e]&&(this._getInput().style[e]=t[e]||"")})}_configureInput(){this._getInput().autocomplete="cc-name",this._getInput().id=Yc.CardName,this._getInput().inputMode="text",this._getInput().maxLength=200,this._getInput().style.backgroundColor="transparent",this._getInput().style.border="0",this._getInput().style.height="100%",this._getInput().style.margin="0",this._getInput().style.outline="none",this._getInput().style.padding="0",this._getInput().style.width="100%",this._getInput().type="text"}_getInput(){return ii(this._input,()=>new ri(ei.PaymentNotInitialized))}_create(){var e;this._input=document.createElement("input"),this._configureInput(),this._applyStyles(null===(e=this._style)||void 0===e?void 0:e.input)}}var nl;!function(e){e.PRODUCTION="https://pay.bluesnap.com/web-sdk/5/bluesnap.js",e.SANDBOX="https://sandpay.bluesnap.com/web-sdk/5/bluesnap.js"}(nl||(nl={}));class il{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e=!1){return t=this,n=void 0,r=function*(){if(this._window.bluesnap)return this._window.bluesnap;if(yield this._scriptLoader.loadScript(e?nl.SANDBOX:nl.PRODUCTION),!this._window.bluesnap)throw new mi;return this._window.bluesnap},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const rl=vi(e=>new Jc(new il(a()),e,new Xc(new tl,new el),new Uc),[{id:"credit_card",gateway:"bluesnapdirect"}]);class ol{constructor(e){this._paymentIntegrationService=e}execute(e){return t=this,n=void 0,r=function*(){const t=this._formatePaymentPayload(e);yield this._paymentIntegrationService.submitOrder();try{yield this._paymentIntegrationService.submitPayment(t)}catch(e){if(this._isBlueSnapDirectRedirectResponse(e)){const t=e.body.provider_data&&JSON.parse(e.body.provider_data);let n=e.body.additional_action_required.data.redirect_url;if(function(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!t.merchantid&&"string"==typeof t.merchantid}(t)){const e=new URLSearchParams(t).toString();n=`${n}&${e}`}return new Promise(()=>window.location.replace(n))}return Promise.reject(e)}},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}initialize(){return Promise.resolve()}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_formatePaymentPayload({payment:e}){if(!e)throw new co(["payment"]);return e.paymentData&&xd(e.paymentData)&&jd(e.paymentData)?Object.assign(Object.assign({},e),{paymentData:{instrumentId:e.paymentData.instrumentId,shouldSetAsDefaultInstrument:!!e.paymentData.shouldSetAsDefaultInstrument}}):(t=e.paymentData,Boolean("object"==typeof t&&null!==t&&"accountNumber"in t&&"accountType"in t&&"shopperPermission"in t&&"routingNumber"in t)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{ecp:Object.assign({account_number:e.paymentData.accountNumber,account_type:e.paymentData.accountType,shopper_permission:e.paymentData.shopperPermission,routing_number:e.paymentData.routingNumber},e.paymentData.companyName?{company_name:e.paymentData.companyName}:{}),vault_payment_instrument:e.paymentData.shouldSaveInstrument,set_as_default_stored_instrument:e.paymentData.shouldSetAsDefaultInstrument}}}):(n=e.paymentData,Boolean("object"==typeof n&&null!==n&&"iban"in n&&"firstName"in n&&"lastName"in n&&"shopperPermission"in n)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{sepa_direct_debit:{iban:e.paymentData.iban,first_name:e.paymentData.firstName,last_name:e.paymentData.lastName,shopper_permission:e.paymentData.shopperPermission},vault_payment_instrument:e.paymentData.shouldSaveInstrument,set_as_default_stored_instrument:e.paymentData.shouldSetAsDefaultInstrument}}}):function(e){return Boolean("object"==typeof e&&null!==e&&"bic"in e)}(e.paymentData)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{ideal:{bic:e.paymentData.bic}}}}):function(e){return Boolean("object"==typeof e&&null!==e&&"iban"in e&&!("firstName"in e)&&!("lastName"in e)&&!("shopperPermission"in e))}(e.paymentData)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{pay_by_bank:{iban:e.paymentData.iban}}}}):{methodId:e.methodId}));var t,n}_isBlueSnapDirectRedirectResponse(e){var t;if("object"!=typeof e||null===e)return!1;const n=e;if(!n.body)return!1;const i=n.body;return"additional_action_required"===i.status&&!!(null===(t=i.additional_action_required)||void 0===t?void 0:t.data.redirect_url)}}const al=vi(e=>new ol(e),[{gateway:"bluesnapdirect"}]);var sl;!function(e){e.ACKNOWLEDGE="ACKNOWLEDGE",e.FINALIZE="FINALIZE",e.INITIALIZE="INITIALIZE"}(sl||(sl={}));const dl=sl;var cl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ll{constructor(e){this._paymentIntegrationService=e}execute(e,t){return cl(this,void 0,void 0,function*(){const{payment:n}=e;if(!n)throw new co(["payment"]);if(!this._initializeOptions)throw new ri(ei.PaymentNotInitialized);const{onLoad:i,style:r}=this._initializeOptions,o=this._createIframe("bluesnapv2_hosted_payment_page",r),a=new En(new Promise(ce));i(o,()=>a.cancel(new Wi)),yield this._paymentIntegrationService.submitOrder(e,t),yield this._paymentIntegrationService.initializeOffsitePayment({methodId:n.methodId,gatewayId:n.gatewayId,shouldSaveInstrument:!1,target:o.name,promise:a.promise})})}finalize(e){return cl(this,void 0,void 0,function*(){const t=this._paymentIntegrationService.getState(),n=t.getOrder(),i=t.getPaymentStatus();if(!n||i!==dl.ACKNOWLEDGE&&i!==dl.FINALIZE)return Promise.reject(new Cd);yield this._paymentIntegrationService.finalizeOrder(e)})}initialize(e){return cl(this,void 0,void 0,function*(){this._initializeOptions=e&&e.bluesnapv2,yield Promise.resolve()})}deinitialize(){return Promise.resolve()}_createIframe(e,t){const n=document.createElement("iframe");if(n.setAttribute("sandbox","allow-top-navigation allow-scripts allow-forms allow-same-origin"),n.name=e,t){const{border:e,height:i,width:r}=t;n.style.border=null!=e?e:"",n.style.height=null!=i?i:"",n.style.width=null!=r?r:""}return n}}const ul=vi(e=>new ll(e),[{gateway:"bluesnapv2"}]);class hl{constructor(e){this.storage=e}saveExtraItemsData(e,t){const n=[...t.physicalItems,...t.digitalItems].reduce((e,t)=>(e[t.productId]={brand:t.brand?t.brand:"",category:t.categoryNames?t.categoryNames.join(", "):""},e),{});try{return this.storage.setItem(this.getStorageKey(e),JSON.stringify(n)),n}catch(e){return{}}}readExtraItemsData(e){try{const t=this.storage.getItem(this.getStorageKey(e));if(!t)return null;const n=JSON.parse(t);return function(e){if(!Z(e))return!1;const t=Object.values(e).some(e=>!Z(e)||!("brand"in e)||!("category"in e));return Boolean(!t)}(n)?n:null}catch(e){return null}}clearExtraItemData(e){try{this.storage.removeItem(this.getStorageKey(e))}catch(e){}}getStorageKey(e){return e?`ORDER_ITEMS_${e}`:""}}function pl(e){return Boolean(e.hasOwnProperty("analytics"))}function ml(e){return"object"==typeof e&&null!==e&&"shouldCreateAccount"in e}class yl extends Qn{constructor(e){super(),this.errorCode=e,this.name="BoltPaymentsFieldError",this.type="bolt_payments_field_error",this.body={errors:[yl.getError(e)]}}static getError(e){switch(e){case"1000":case"2000":case"3000":return{code:"invalid_number"};case"1001":case"2001":case"3001":return{code:"invalid_expiry_date"};case"1002":case"2002":return{code:"invalid_cvc"};case"1003":return{code:"invalid_zip"};case"2003":return{code:"incorrect_zip"};default:return{code:"general_error"}}}}var gl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vl{constructor(e,t,n){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.analyticsExtraItemsManager=n,this.useBoltClient=!1,this.useBoltEmbedded=!1}initialize(e){return gl(this,void 0,void 0,function*(){const{bolt:t,methodId:n}=e,{containerId:i,onPaymentSelect:r,useBigCommerceCheckout:o}=t||{};if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)return void(this.boltClient=yield this.boltScriptLoader.loadBoltClient());const a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{initializationData:s,config:d}=a,{publishableKey:c,developerConfig:l,embeddedOneClickEnabled:u}=s||{},{testMode:h}=d;if(!c)throw new ti(Xn.MissingPaymentMethod);if(this.boltClient=yield this.boltScriptLoader.loadBoltClient(c,h,l),this.useBoltClient=!u,this.useBoltEmbedded=!!u,this.useBoltEmbedded){if(!i)throw new fi('Unable to initialize payment because "options.bolt.containerId" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.bolt.onPaymentSelect" argument is not provided.');this.boltEmbedded=yield this.boltScriptLoader.loadBoltEmbedded(c,h,l),this.mountBoltEmbeddedField(i),r(yield this.hasBoltAccount())}})}deinitialize(){var e;return null===(e=this.embeddedField)||void 0===e||e.unmount(),this.boltClient=void 0,this.boltEmbedded=void 0,Promise.resolve()}finalize(){return Promise.reject(new Cd)}execute(e,t){return gl(this,void 0,void 0,function*(){this.setExtraItemsForAnalytics();const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const n={success:(n,i)=>{n.reference?e(n):t(new Qr("Unable to proceed because transaction reference is unavailable. Please try again later.")),i()},close:()=>{t(new Wi)}};s.configure({orderToken:r},{},n).open()});return{methodId:e,paymentData:{nonce:d.reference,shouldSaveInstrument:a}}})}getBoltEmbeddedPaymentPayload(e,t){var n;return gl(this,void 0,void 0,function*(){if(!ml(t))throw new ti(Xn.MissingPayment);const i=this.validateTokenizeResultOrThrow(yield null===(n=this.embeddedField)||void 0===n?void 0:n.tokenize());return{methodId:e,paymentData:{formattedPayload:{credit_card_token:{token:i.token,last_four_digits:i.last4,iin:i.bin,expiration_month:+i.expiration.split("-")[1],expiration_year:+i.expiration.split("-")[0]},provider_data:{create_account:!!t.shouldCreateAccount,embedded_checkout:!0}}}}})}getBoltFullCheckoutPaymentPayload(e,t){return gl(this,void 0,void 0,function*(){yield this.setBoltOrderId();const n=this.getBoltClientOrThrow(),i=yield n.getTransactionReference();if(!i)throw new Xr;return{methodId:e,paymentData:Object.assign(Object.assign({},t),{nonce:i})}})}getBoltClientOrThrow(){if(!this.boltClient)throw new ri(ei.PaymentNotInitialized);return this.boltClient}getBoltEmbeddedOrThrow(){if(!this.boltEmbedded)throw new ri(ei.PaymentNotInitialized);return this.boltEmbedded}hasBoltAccount(){return gl(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCustomer(),n=e.getBillingAddress(),i=(null==t?void 0:t.email)||(null==n?void 0:n.email)||"",r=this.getBoltClientOrThrow();try{return yield r.hasBoltAccount(i)}catch(e){throw new Xr}})}setBoltOrderId(){return gl(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getOrderOrThrow(),t=this.getBoltClientOrThrow();try{yield t.setOrderId(e.orderId)}catch(e){throw new Xr}})}mountBoltEmbeddedField(e){const t=this.getBoltEmbeddedOrThrow().create("payment_field",{styles:{backgroundColor:"#fff"},renderSeparateFields:!0});t.mount(`#${e}`),this.embeddedField=t}validateTokenizeResultOrThrow(e){if(!e)throw new Xr;if(e instanceof Error)throw new yl(e.message);const{token:t,last4:n,bin:i,expiration:r}=e,o=+n,a=+i,s=+`${r}`.split("-")[1],d=+`${r}`.split("-")[0];if(!t||Number.isNaN(o)||Number.isNaN(a)||Number.isNaN(s)||Number.isNaN(d))throw new co;return e}setExtraItemsForAnalytics(){const e=this.paymentIntegrationService.getState(),t=e.getStoreConfigOrThrow(),n=e.getCartOrThrow();if(t.checkoutSettings.isAnalyticsEnabled&&pl(window)){const{id:e,lineItems:t}=n;this.analyticsExtraItemsManager.saveExtraItemsData(e,t)}}}const fl=vi(e=>new vl(e,new ao(a()),new hl(Te)),[{id:"bolt"}]);function Sl(e){return!!e&&"accountNumber"in e&&"routingNumber"in e&&"ownershipType"in e&&"accountType"in e}var _l=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class wl{constructor(e,t){this.paymentIntegrationService=e,this.braintreeSdk=t}initialize(e){return _l(this,void 0,void 0,function*(){const{methodId:t,braintreeach:n}=e||{};if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');this.getMandateText=null==n?void 0:n.getMandateText,yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{clientToken:r,initializationData:o}=i;if(!r||!o)throw new ti(Xn.MissingPaymentMethod);this.braintreeSdk.initialize(r);try{this.usBankAccount=yield this.braintreeSdk.getUsBankAccount()}catch(e){this.handleBraintreeError(e)}})}execute(e,t){return _l(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew wl(e,(e=>{const t=new Ei(e),n=new Hi(a(),window,t);return new Ui(n)})(e)),[{id:"braintreeach"}]);class Cl{constructor(e){this.paymentIntegrationService=e,this.braintreeHostWindow=window}render(e,t,n){const i=t&&document.getElementById(t);if(this.braintreeHostWindow.paypal&&i){const r=this.paymentIntegrationService.getState(),o=r.getCartOrThrow(),a=r.getBillingAddressOrThrow(),s=r.getPaymentMethodOrThrow(e);if(!s.initializationData)return;const{paypalBNPLConfiguration:d=[]}=s.initializationData,c=n===fo.PAYMENT?"checkout":n,l=d&&d.find(({id:e})=>e===c);if(!l||!l.status)return;n===fo.CART&&(i.removeAttribute("data-pp-style-logo-type"),i.removeAttribute("data-pp-style-logo-position"),i.removeAttribute("data-pp-style-text-color"),i.removeAttribute("data-pp-style-text-size")),this.braintreeHostWindow.paypal.Messages({amount:o.cartAmount,buyerCountry:a.countryCode,placement:n,style:this.getPaypalMessagesStylesFromBNPLConfig(l)}).render(`#${t}`)}}getPaypalMessagesStylesFromBNPLConfig({styles:e}){const t={};return e.color&&(t.color=e.color),e.layout&&(t.layout=e.layout),(e["logo-type"]||e["logo-position"])&&(t.logo={},e["logo-type"]&&(t.logo.type=e["logo-type"]),e["logo-position"]&&(t.logo.position=e["logo-position"])),e.ratio&&(t.ratio=e.ratio),(e["text-color"]||e["text-size"])&&(t.text={},e["text-color"]&&(t.text.color=e["text-color"]),e["text-size"]&&(t.text.size=+e["text-size"])),t}}class bl{constructor(e){const{element:t,closeElement:n,mainElement:i}=this._createElements(e);this._element=t,this._closeElement=n,this._mainElement=i}show(e){this._mainElement.parentElement||(this._registerClick(e),document.body.appendChild(this._mainElement),setTimeout(()=>this._element.style.opacity="1"))}remove(){this._mainElement.parentElement&&(this._unregisterClick&&this._unregisterClick(),this._removeAfterTransition(),setTimeout(()=>this._element.style.opacity="0"))}_createElements(e){const t=document.createElement("div"),{background:n="rgba(0, 0, 0, 0.8)",id:i="checkoutOverlay",transitionDuration:r=400,hasCloseButton:o=!1,innerHtml:a=null}=e||{};let s,d,c,l,u=t;if(i&&(t.id=i),a){const e=document.createElement("div");l=`${i}--overlayText`,e.className=l,e.appendChild(a),t.appendChild(e)}return o&&(c=`${i}--close`,s=document.createElement("div"),s.className=c,d=`${i}--layout`,u=document.createElement("div"),u.className=d,u.appendChild(t),u.appendChild(s)),u.appendChild(function(e){const{id:t,background:n,transitionDuration:i,classLayout:r,classOverlayText:o,classClose:a}=e,s=document.createElement("style"),d=r?`, .${r}`:"";return s.id=`${t}--styles`,s.type="text/css",s.innerText=`\n #${t}${d} {\n display: block;\n height: 100%;\n width: 100%;\n left: 0;\n top: 0;\n position: fixed;\n z-index: 2147483647;\n }\n #${t} {\n transition: opacity ${i}ms ease-out;\n background: ${n};\n opacity: 0;\n }\n `,o&&(s.innerText+=`\n #${t} {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n #${t} .${o} {\n color: white;\n max-width: 330px;\n font-size: 1.2em;\n text-align: center;\n }\n `),a&&(s.innerText+=`\n #${t} {\n opacity: 1;\n }\n .${r} .${a} {\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 .${r} .${a}::after, .${r} .${a}::before {\n position: absolute;\n left: 8px;\n content: '';\n height: 16px;\n width: 2px;\n background-color: #fff;\n }\n .${r} .${a}::after {\n transform: rotate(-45deg);\n }\n .${r} .${a}::before {\n transform: rotate(45deg);\n }\n `),s}({id:i,background:n,transitionDuration:r,classLayout:d,classOverlayText:l,classClose:c})),{element:t,closeElement:s,mainElement:u}}_addEventListener(e,t){e&&t&&e.addEventListener("click",t)}_removeEventListener(e,t){e&&t&&e.removeEventListener("click",t)}_registerClick(e){if(this._unregisterClick&&this._unregisterClick(),e){const{onClick:t,onClickClose:n}=e;this._addEventListener(this._element,t),this._addEventListener(this._closeElement,n),this._unregisterClick=()=>{this._removeEventListener(this._element,t),this._removeEventListener(this._closeElement,n),this._unregisterClick=void 0}}}_removeAfterTransition(){const e=t=>{"opacity"===t.propertyName&&(this._mainElement.parentElement&&this._mainElement.remove(),this._element.removeEventListener("transitionend",e))};this._element.addEventListener("transitionend",e)}}const Pl={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"};function Ol(e){return"object"==typeof e&&null!==e&&"name"in e&&"BraintreeError"===e.name}function El(e){return{recipientName:`${e.firstName} ${e.lastName}`,line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,postalCode:e.postalCode,countryCode:e.countryCode,phone:e.phone}}var Al=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Tl{constructor(e,t,n,i){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeMessages=n,this.loadingIndicator=i,this.braintreeHostWindow=window}initialize(e){return Al(this,void 0,void 0,function*(){const{braintree:t,methodId:n}=e;if((null==t?void 0:t.containerId)&&(this.braintreeButtonOptions=t),this.paymentMethod&&this.paymentMethod.nonce||(this.paymentMethod=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n)),this.paymentMethod.clientToken&&(null==t?void 0:t.bannerContainerId))return yield this.loadPaypal(),this.loadPaypalCheckoutInstance(t);if(this.paymentMethod.clientToken)return this.loadPaypal();const i=yield this.paymentIntegrationService.loadPaymentMethod(n);if(this.paymentMethod=i.getPaymentMethodOrThrow(n),null==t?void 0:t.bannerContainerId)return this.loadPaypalCheckoutInstance(t);if(!this.paymentMethod.clientToken)throw new ti(Xn.MissingPaymentMethod);return this.loadPaypal()})}execute(e,t){var n;return Al(this,void 0,void 0,function*(){const{payment:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{o&&"function"==typeof o&&o(new Error("INSTRUMENT_DECLINED")),t()})),this.handleError(e)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.braintreeTokenizePayload=void 0,null===(e=this.paypalButtonRender)||void 0===e||e.close(),this.braintreeIntegrationService.teardown()}preparePaymentData(e,t){var n;return Al(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),r=i.getOutstandingBalance(t),o=i.getStoreConfig();if(!r)throw new ti(Xn.MissingCheckout);if(!o)throw new ti(Xn.MissingCheckoutConfig);if(!this.paymentMethod)throw new ri(ei.PaymentNotInitialized);const{currency:a,storeProfile:{storeLanguage:s}}=o,{nonce:d,config:{isVaultingEnabled:c}}=this.paymentMethod,{methodId:l,paymentData:u={}}=e,h=(null===(n=this.braintreeTokenizePayload)||void 0===n?void 0:n.nonce)||d;if(h){const t=yield this.paymentIntegrationService.loadPaymentMethod(l);return this.paymentMethod=t.getPaymentMethod(l),Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(h)})}if(xd(u)||(p=u,Boolean(p.instrumentId)&&!Object.prototype.hasOwnProperty.call(p,"ccNumber")&&!Object.prototype.hasOwnProperty.call(p,"ccCvv"))){if(!c)throw new fi("Vaulting is disabled but a vaulted instrument was being used for this transaction");return Promise.resolve(e)}var p;if(!jd(u))throw new ti(Xn.MissingPayment);const{shouldSaveInstrument:m,shouldSetAsDefaultInstrument:y}=u;if(m&&!c)throw new fi("Vaulting is disabled but shouldSaveInstrument is set to true");const g=i.getShippingAddress(),v=g?El(g):void 0;return Promise.all([this.braintreeIntegrationService.paypal({amount:r,locale:s,currency:a.code,offerCredit:"braintreepaypalcredit"===this.paymentMethod.id,shippingAddressOverride:v,shouldSaveInstrument:m||!1,shippingAddressEditable:!1}),this.braintreeIntegrationService.getSessionId()]).then(([{nonce:t,details:n}={},i])=>Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(t,n&&n.email,i,m,y)}))})}formattedPayload(e,t,n,i,r){return{formattedPayload:{vault_payment_instrument:i||null,set_as_default_stored_instrument:r||null,device_info:n||null,paypal_account:{token:e,email:t||null}}}}loadPaypalCheckoutInstance(e){return Al(this,void 0,void 0,function*(){const{clientToken:t,initializationData:n,id:i}=this.paymentMethod||{};if(!t)throw new ti(Xn.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(t);const r={currency:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,intent:null==n?void 0:n.intent,isCreditEnabled:null==n?void 0:n.isCreditEnabled},o="braintreepaypalcredit"===i||!(null==n?void 0:n.isCreditEnabled);yield this.braintreeIntegrationService.getPaypalCheckout(r,t=>{o&&i&&(null==e?void 0:e.bannerContainerId)&&this.renderPayPalMessages(i,e.bannerContainerId),this.renderPayPalButton(t,e)},this.handleError)}catch(e){this.handleError(e)}})}renderPayPalMessages(e,t){this.braintreeMessages.render(e,t,fo.PAYMENT)}renderPayPalButton(e,t){const{onPaymentError:n,submitForm:i,onRenderButton:r,containerId:o,onError:a}=t||{};if(!o)return;const s=this.getSmartButtonContainerId(o);if(!document.getElementById(s))throw new fi(`Unable to initialize payment because element with id ${o} does not exist.`);if(!this.paymentMethod)throw new ri(ei.PaymentNotInitialized);this.loadingIndicatorContainer=o.split("#")[1];const{id:d,config:{testMode:c}}=this.paymentMethod,{paypal:l}=this.braintreeHostWindow,u=null==l?void 0:l.FUNDING.PAYPAL;l&&u?(this.paypalButtonRender=l.Buttons({env:c?"sandbox":"production",commit:!1,fundingSource:u,onClick:()=>{this.toggleLoadingIndicator(!0)},createOrder:()=>this.setupPayment(e,d,n),onApprove:t=>Al(this,void 0,void 0,function*(){this.braintreeTokenizePayload=yield this.tokenizePaymentOrThrow(t,e),i&&"function"==typeof i&&i()}),onCancel:()=>{this.toggleLoadingIndicator(!1)},onError:e=>{this.toggleLoadingIndicator(!1),null==a||a(e)}}),r&&"function"==typeof r&&r(),this.paypalButtonRender.isEligible()&&this.paypalButtonRender.render(`${o}`)):this.removeElement(o.split("#")[1])}setupPayment(e,t,n){return Al(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState();try{const n=i.getCustomer(),r=i.getPaymentMethodOrThrow(t),o=i.getCheckoutOrThrow().outstandingBalance,a=i.getStoreConfigOrThrow().currency.code,s=i.getShippingAddress()||(null==n?void 0:n.addresses[0]),d=s?El(s):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:d,amount:o,currency:a,offerCredit:!1,intent:r.initializationData.intent})}catch(e){throw n&&(Ol(e)||e instanceof Qn)&&n(e),e}})}tokenizePaymentOrThrow(e,t,n){return Al(this,void 0,void 0,function*(){try{return yield t.tokenizePayment(e)}catch(e){throw n&&(Ol(e)||e instanceof Qn)&&n(e),e}})}loadPaypal(){return Al(this,void 0,void 0,function*(){const{clientToken:e,initializationData:t}=this.paymentMethod||{};if(!e||!t)throw new ti(Xn.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(e),yield this.braintreeIntegrationService.getPaypal()}catch(e){this.handleError(e)}return Promise.resolve()})}handleError(e){if(!Ol(e))throw e;if("PAYPAL_POPUP_CLOSED"===e.code)throw new Wi(e.message);throw new Qr(e.message)}isProviderError(e){var t,n,i;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"2046"===(null===(i=null===(n=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===n?void 0:n.provider_error)||void 0===i?void 0:i.code)}removeElement(e){const t=e&&document.getElementById(e);t&&t.remove()}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}getSmartButtonContainerId(e){var t;return null!==(t=e.split("#")[1])&&void 0!==t?t:e}}const kl=vi(e=>{const t=window,n=new bl,i=new Ei(e),r=new _o(new Hi(a(),t,i),t,n),o=new Cl(e);return new Tl(e,r,o,new vd({containerStyles:Pl}))},[{id:"braintreepaypal"},{id:"braintreepaypalcredit"}]);class Dl{constructor(e){this.requestSender=e}getOrderStatus(e="braintreelocalmethods",t){return n=this,i=void 0,o=function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}var Ml=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class zl{constructor(e,t,n,i,r=3e3,o=3e5){this.paymentIntegrationService=e,this.braintreeSdk=t,this.braintreeRequestSender=n,this.loadingIndicator=i,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.isLPMsUpdateExperimentEnabled=!1,this.pollingTimer=0,this.stopPolling=ce,this.isPollingEnabled=!1}initialize(e){return Ml(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,braintreelocalmethods:i}=e;if(this.gatewayId=t,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.braintreelocalmethods" argument is not provided.');this.braintreelocalmethods=i,this.loadingIndicatorContainer=i.container.split("#")[1],yield this.paymentIntegrationService.loadPaymentMethod(t);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(t),{clientToken:a,config:s,initializationData:d}=o,c=r.getStoreConfigOrThrow().checkoutSettings.features;if(this.isPollingEnabled=Ci(c,"PAYPAL-5258.braintree_local_methods_polling"),this.isLPMsUpdateExperimentEnabled=Ci(c,"PAYPAL-4853.add_new_payment_flow_for_braintree_lpms"),!a||!d||!s.merchantId)throw new ti(Xn.MissingPaymentMethod);try{this.braintreeSdk.initialize(a),this.isNonInstantPaymentMethod(n)||(this.braintreeLocalPayment=yield this.braintreeSdk.getBraintreeLocalPayment(s.merchantId))}catch(e){this.handleError(e)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return Ml(this,void 0,void 0,function*(){return this.toggleLoadingIndicator(!1),Promise.resolve()})}execute(e,t){return Ml(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{window.location.replace(t),this.toggleLoadingIndicator(!1),n()})}return this.handleError(e),Promise.reject(e)}})}executeWithInstantLPM(e,t,n){return Ml(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment)throw new Xr;yield new Promise((i,r)=>{var o;null===(o=this.braintreeLocalPayment)||void 0===o||o.startPayment(this.getInstantLPMConfig(e,t,n),this.getInstantLPMCallback(i,r,e,t,n))})})}getLPMsBasicPaymentData(){return Ml(this,void 0,void 0,function*(){const{deviceData:e}=yield this.braintreeSdk.getDataCollectorOrThrow();return{deviceSessionId:e}})}getInstantLPMConfig(e,t,n){const i=this.paymentIntegrationService.getState(),r=i.getCartOrThrow(),o=i.getBillingAddressOrThrow(),{firstName:a,lastName:s,countryCode:d}=o,{currency:c,email:l,lineItems:u}=r,h=u.physicalItems.length>0,p=i.getCheckoutOrThrow().outstandingBalance,m=i.getStoreConfigOrThrow().links.checkoutLink;return{paymentType:e,amount:p,fallback:{url:m,buttonText:"Complete Payment"},currencyCode:c.code,shippingAddressRequired:h,email:l,givenName:a,surname:s,address:{countryCode:d},onPaymentStart:(i,r)=>Ml(this,void 0,void 0,function*(){if(!this.isLPMsUpdateExperimentEnabled)return this.orderId=i.paymentId,void r();const o=yield this.getLPMsBasicPaymentData(),a=Object.assign(Object.assign({},o),{formattedPayload:{method:e,[`${e}_account`]:{order_id:i.paymentId}}});try{yield this.paymentIntegrationService.submitOrder(t,n),yield this.paymentIntegrationService.submitPayment({methodId:e,paymentData:a})}catch(t){if(this.isBraintreeOrderSavedResponse(t)&&t.body.additional_action_required.data.order_id_saved_successfully)return r(),this.isPollingEnabled?new Promise((t,n)=>{this.initializePollingMechanism(e,t,n,this.gatewayId)}):void 0;throw t}})}}getInstantLPMCallback(e,t,n,i,r){const o=this.paymentIntegrationService.getState().getCartOrThrow();return(a,s)=>Ml(this,void 0,void 0,function*(){if(a)return"LOCAL_PAYMENT_WINDOW_CLOSED"===a.code?(this.toggleLoadingIndicator(!1),this.resetPollingMechanism(),t()):(this.isPollingEnabled&&this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t(new Xr));const d=yield this.getLPMsBasicPaymentData(),c=Object.assign(Object.assign({},d),{formattedPayload:{method:n,[`${n}_account`]:Object.assign({email:o.email,token:s.nonce},this.isLPMsUpdateExperimentEnabled?{}:{order_id:this.orderId})}});try{return this.isLPMsUpdateExperimentEnabled||(yield this.paymentIntegrationService.submitOrder(i,r)),yield this.paymentIntegrationService.submitPayment({methodId:n,paymentData:c}),e(void 0)}catch(e){return this.handleError(e),t(e)}})}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}handleError(e){const{onError:t}=this.braintreelocalmethods||{};this.isPollingEnabled&&this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}isNonInstantPaymentMethod(e){return e.toUpperCase()in Di}isBraintreeRedirectError(e){var t;if("object"!=typeof e||null===e)return!1;const{body:n}=e;return!!n&&!!(null===(t=n.additional_action_required)||void 0===t?void 0:t.data.redirect_url)}isBraintreeOrderSavedResponse(e){var t;if("object"!=typeof e||null===e)return!1;const{body:n}=e;return!!n&&(null===(t=n.additional_action_required)||void 0===t?void 0:t.data.hasOwnProperty("order_id_saved_successfully"))}initializePollingMechanism(e,t,n,i){return Ml(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.braintreeRequestSender.getOrderStatus(i,{params:{useMetadata:!1}}),o=r.status===ki.Pending,a=r.status===ki.Completed,s=r.status===ki.Failed;if(a)return this.deinitializePollingMechanism(),t();if(s)return n();if(!a&&o&&this.pollingTimer{const t=window,i=new Ei(e),r=new Ui(new Hi(a(),t,i)),o=n(),s=new Dl(o);return new zl(e,r,s,new vd({styles:{backgroundColor:"black"}}))},[{gateway:"braintreelocalmethods"}]);function xl(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var Rl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Fl{constructor(e,t,n){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.braintreeSdk=n}initialize(e){var t;return Rl(this,void 0,void 0,function*(){const{methodId:n,braintreefastlane:i}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.braintreefastlane" argument is not provided.');if(!i.onInit||"function"!=typeof i.onInit)throw new fi('Unable to initialize payment because "options.braintreefastlane.onInit" argument is not provided or it is not a function.');if(!i.onChange||"function"!=typeof i.onChange)throw new fi('Unable to initialize payment because "options.braintreefastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(n);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(n),{initializationData:a,clientToken:s}=o||{},{isFastlaneStylingEnabled:d}=a||{},c=Ci(r.getStoreConfigOrThrow().checkoutSettings.features,"PROJECT-7080.braintree_fastlane_three_ds");this.is3DSEnabled=o.config.is3dsEnabled,s&&c&&this.braintreeSdk.initialize(s);const l=Ao(d?null===(t=o.initializationData)||void 0===t?void 0:t.fastlaneStyles:void 0,i.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(n,l),this.shouldRunAuthenticationFlow()&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow()),yield this.initializeCardComponent(),this.onError=i.onError,i.onInit(e=>this.renderBraintreeCardComponent(e)),i.onChange(()=>this.handleBraintreeStoredInstrumentChange(n))})}execute(e,t){return Rl(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{i.verifyCard({amount:null==r?void 0:r.orderAmount,nonce:e,bin:t,onLookupComplete:(e,t)=>{i.on("customer-canceled",()=>{"function"==typeof this.onError&&this.onError(new Wi),o(new Wi)}),t()}},(e,t)=>(e&&"THREEDS_VERIFY_CARD_CANCELED_BY_MERCHANT"===e.code&&("function"==typeof this.onError&&this.onError(new Wi),o(new Wi)),n(t.nonce)))})})}mapToPayPalAddress(e){return{streetAddress:(null==e?void 0:e.address1)||"",locality:(null==e?void 0:e.city)||"",region:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCodeAlpha2:(null==e?void 0:e.countryCode)||""}}shouldRunAuthenticationFlow(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getCustomerOrThrow(),i=e.getPaymentProviderCustomer(),r=xl(i)?i:{},o=this.braintreeFastlaneUtils.getSessionIdFromCookies();return!(!n.isGuest||(null==r?void 0:r.authenticationState)===Mi.CANCELED||(null==r?void 0:r.authenticationState)||o!==t.id)}getBraintreeCardComponentOrThrow(){if(!this.braintreeCardComponent)throw new mi;return this.braintreeCardComponent}getPayPalInstruments(){const e=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow();return(xl(e)?e:{}).instruments||[]}handleBraintreeStoredInstrumentChange(e){return Rl(this,void 0,void 0,function*(){const t=this.braintreeFastlaneUtils.getBraintreeFastlaneOrThrow(),{selectionChanged:n,selectedCard:i}=yield t.profile.showCardSelector();if(n){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),n=xl(t)?t:{},r=this.braintreeFastlaneUtils.mapPayPalToBcInstrument(e,[i]);if(r&&r.length>0)return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},n),{instruments:[...r]})),r[0]}})}}const Ll=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t),r=new Mo(e,i),o=new Hi(a(),t,n),s=new Ui(o);return new Fl(e,r,s)},[{id:"braintreeacceleratedcheckout"}]);var Bl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class jl{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n}initialize(e){return Bl(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:n}=e;if(!t)throw new fi('Unable to initialize payment because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState();this.paymentMethod=i.getPaymentMethodOrThrow(n);const r=i.getCheckoutOrThrow(),o=i.getStoreConfigOrThrow(),{clientToken:a,config:s}=this.paymentMethod||{};if(!a)throw new ti(Xn.MissingPaymentMethod);const{onError:d=ce,onPaymentSelect:c=ce}=t;this.braintreeSdk.initialize(a);const l=yield this.braintreeSdk.getBraintreeVisaCheckout(),u=yield this.braintreeSdk.getVisaCheckoutSdk(null==s?void 0:s.testMode),h=l.createInitOptions({settings:{locale:o.storeProfile.storeLanguage,shipping:{collectShipping:!1}},paymentRequest:{currencyCode:o.currency.code,subtotal:String(r.subtotal)}});yield u.init(h),u.on("payment.success",e=>this.tokenizePayment(l,e).then(()=>Promise.all([this.paymentIntegrationService.loadCheckout(),this.paymentIntegrationService.loadPaymentMethod(n)])).then(()=>c()).catch(e=>d(e))),u.on("payment.error",(e,t)=>d(t))})}execute(e,t){var n,i;return Bl(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const n=this.paymentIntegrationService.getState(),i=n.getShippingAddress(),r=n.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(i),billingAddress:a=this.mapToVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}mapToVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}postForm(e,t){const{userData:n,billingAddress:i,shippingAddress:r,details:o}=e,{userEmail:a}=n,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,i)),shipping_address:JSON.stringify(this.getAddress(a,r))})}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}handleError(e){if(e instanceof Error&&"BraintreeError"===e.name)throw new Qr(e.message);throw e}}const Ul=vi(e=>{const t=window,n=new Ei(e),i=new Ui(new Hi(a(),t,n));return new jl(e,Ee(),i)},[{id:"braintreevisacheckout"}]);var ql=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vl{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}initialize(e){return ql(this,void 0,void 0,function*(){const{methodId:t}=e;yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState();this.venmoOptions=e.braintreevenmo;const i=n.getPaymentMethodOrThrow(t);yield this.initializeBraintreeVenmo(i)})}execute(e){return ql(this,void 0,void 0,function*(){const{payment:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{var n;null===(n=this.braintreeVenmoCheckout)||void 0===n||n.tokenize((n,i)=>{if(n)return t(n);e(i)})})}}const Gl=vi(e=>{const t=window,n=a(),i=new Ei(e),r=new Hi(n,t,i),o=new _o(r,t);return new Vl(e,o)},[{id:"braintreevenmo"}]);var Hl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Wl{constructor(e,t,n){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeHostedForm=n}initialize(e){return Hl(this,void 0,void 0,function*(){const{methodId:t,gatewayId:n,braintree:i}=e;yield this.paymentIntegrationService.loadPaymentMethod(t);const r=this.paymentIntegrationService.getState();this.paymentMethod=r.getPaymentMethodOrThrow(t);const{clientToken:o}=this.paymentMethod;if(!o)throw new ti(Xn.MissingPaymentMethod);this.threeDSecure=null==i?void 0:i.threeDSecure,this.onPaymentError=null==i?void 0:i.onPaymentError;try{this.braintreeIntegrationService.initialize(o,this.threeDSecure),this.isHostedPaymentFormEnabled(t,n)&&(null==i?void 0:i.form)&&(yield this.braintreeHostedForm.initialize(i.form,i.unsupportedCardBrands,o),this.isHostedFormInitialized=this.braintreeHostedForm.isInitialized()),this.is3dsEnabled=this.paymentMethod.config.is3dsEnabled,this.deviceSessionId=yield this.braintreeIntegrationService.getSessionId(),this.shouldInitializeBraintreeFastlane()&&(yield this.initializeBraintreeFastlaneOrThrow(t))}catch(e){return this.handleError(e,t)}})}execute(e){return Hl(this,void 0,void 0,function*(){const{payment:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r"string"==typeof e));var n}var Kl,Jl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e[e.CreditCard=0]="CreditCard",e[e.StoredCardVerification=1]="StoredCardVerification"}(Kl||(Kl={}));class Zl{constructor(e,t){this.braintreeScriptLoader=e,this.braintreeSDKVersionManager=t,this.isInitializedHostedForm=!1,this.handleBlur=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onBlur)||void 0===n||n.call(t,{fieldType:this.mapFieldType(e.emittedBy),errors:this.mapErrors(e.fields)})},this.handleFocus=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onFocus)||void 0===n||n.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleCardTypeChange=e=>{var t,n;const i=1===e.cards.length?e.cards[0].type.replace(/^master-card$/,"mastercard"):void 0;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onCardTypeChange)||void 0===n||n.call(t,{cardType:i})},this.handleInputSubmitRequest=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onEnter)||void 0===n||n.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleValidityChange=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===n||n.call(t,{isValid:this.isValidForm(e),errors:this.mapValidationErrors(e.fields)})}}initialize(e,t,n){var i,r,o,a,s;return Jl(this,void 0,void 0,function*(){this.clientToken=n,this.formOptions=e,this.type=$l(e.fields)?Kl.CreditCard:Kl.StoredCardVerification;const d=this.mapFieldOptions(e.fields,t);$(d)?this.isInitializedHostedForm=!1:(this.cardFields=yield this.createHostedFields({fields:d,styles:e.styles&&this.mapStyleOptions(e.styles)}),null===(i=this.cardFields)||void 0===i||i.on("blur",this.handleBlur),null===(r=this.cardFields)||void 0===r||r.on("focus",this.handleFocus),null===(o=this.cardFields)||void 0===o||o.on("cardTypeChange",this.handleCardTypeChange),null===(a=this.cardFields)||void 0===a||a.on("validityChange",this.handleValidityChange),null===(s=this.cardFields)||void 0===s||s.on("inputSubmitRequest",this.handleInputSubmitRequest),this.isInitializedHostedForm=!0)})}isInitialized(){return!!this.isInitializedHostedForm}deinitialize(){var e;return Jl(this,void 0,void 0,function*(){this.isInitializedHostedForm&&(this.isInitializedHostedForm=!1,yield null===(e=this.cardFields)||void 0===e?void 0:e.teardown())})}validate(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);const e=this.cardFields.getState();if(!this.isValidForm(e)){this.handleValidityChange(e);const t=this.mapValidationErrors(e.fields);throw new lo(t)}}tokenize(e){var t,n,i,r,o;return Jl(this,void 0,void 0,function*(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);try{const r=yield this.cardFields.tokenize(ue({billingAddress:e&&this.mapBillingAddress(e)},J));return null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===n||n.call(t,{isValid:!0,errors:{}}),{nonce:r.nonce,bin:null===(i=r.details)||void 0===i?void 0:i.bin}}catch(e){if(Yl(e)){const t=this.mapTokenizeError(e);if(t)throw null===(o=null===(r=this.formOptions)||void 0===r?void 0:r.onValidate)||void 0===o||o.call(r,{isValid:!1,errors:t}),new lo(t)}throw e}})}tokenizeForStoredCardVerification(){var e,t,n,i,r;return Jl(this,void 0,void 0,function*(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);try{const i=yield this.cardFields.tokenize();return null===(t=null===(e=this.formOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,{isValid:!0,errors:{}}),{nonce:i.nonce,bin:null===(n=i.details)||void 0===n?void 0:n.bin}}catch(e){if(Yl(e)){const t=this.mapTokenizeError(e,!0);if(t)throw null===(r=null===(i=this.formOptions)||void 0===i?void 0:i.onValidate)||void 0===r||r.call(i,{isValid:!1,errors:t}),new lo(t)}throw e}})}createHostedFields(e){return Jl(this,void 0,void 0,function*(){const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadHostedFields(),i=this.braintreeSDKVersionManager.getSDKVersion()===bi?Object.assign(Object.assign({},e),{preventCursorJumps:!0}):e;return n.create(Object.assign(Object.assign({},i),{client:t}))})}getClient(){return Jl(this,void 0,void 0,function*(){if(!this.clientToken)throw new ri(ei.PaymentNotInitialized);if(!this.client){const e=yield this.braintreeScriptLoader.loadClient();this.client=e.create({authorization:this.clientToken})}return this.client})}mapBillingAddress(e){return{countryName:e.country,postalCode:e.postalCode,streetAddress:e.address2?`${e.address1} ${e.address2}`:e.address1}}mapFieldOptions(e,t){if($l(e)){const n={};return null==t||t.forEach(e=>{(e=>Object.values(xi).includes(e))(e)&&(n[e]=!1)}),ue({number:Object.assign({container:`#${e.cardNumber.containerId}`,placeholder:e.cardNumber.placeholder,internalLabel:e.cardNumber.accessibilityLabel},Object.keys(n).length>0?{supportedCardBrands:n}:{}),expirationDate:{container:`#${e.cardExpiry.containerId}`,placeholder:e.cardExpiry.placeholder,internalLabel:e.cardExpiry.accessibilityLabel},cvv:e.cardCode&&{container:`#${e.cardCode.containerId}`,placeholder:e.cardCode.placeholder,internalLabel:e.cardCode.accessibilityLabel},cardholderName:{container:`#${e.cardName.containerId}`,placeholder:e.cardName.placeholder,internalLabel:e.cardName.accessibilityLabel}},J)}return ue({number:e.cardNumberVerification&&{container:`#${e.cardNumberVerification.containerId}`,placeholder:e.cardNumberVerification.placeholder},cvv:e.cardCodeVerification&&{container:`#${e.cardCodeVerification.containerId}`,placeholder:e.cardCodeVerification.placeholder}},J)}mapStyleOptions(e){const t=(e={})=>ue({color:e.color,"font-family":e.fontFamily,"font-size":e.fontSize,"font-weight":e.fontWeight},J);return{input:t(e.default),".invalid":t(e.error),":focus":t(e.focus)}}mapFieldType(e){switch(e){case"number":return this.type===Kl.StoredCardVerification?Bi.CardNumberVerification:Bi.CardNumber;case"expirationDate":return Bi.CardExpiry;case"cvv":return this.type===Kl.StoredCardVerification?Bi.CardCodeVerification:Bi.CardCode;case"cardholderName":return Bi.CardName;default:throw new Error("Unexpected field type")}}mapErrors(e){const t={};if(e)for(const[n,i]of Object.entries(e))if(i&&this.isValidParam(n)){const{isValid:e,isEmpty:r,isPotentiallyValid:o}=i;t[n]={isValid:e,isEmpty:r,isPotentiallyValid:o}}return t}mapValidationErrors(e){return Object.keys(e).reduce((t,n)=>{var i;return Object.assign(Object.assign({},t),{[this.mapFieldType(n)]:(null===(i=e[n])||void 0===i?void 0:i.isValid)?void 0:[this.createInvalidError(this.mapFieldType(n))]})},{})}mapTokenizeError(e,t=!1){var n,i;if("HOSTED_FIELDS_FIELDS_EMPTY"===e.code){const e=[this.createRequiredError(this.mapFieldType("cvv"))];return t?{[this.mapFieldType("cvv")]:e}:{[this.mapFieldType("cvv")]:e,[this.mapFieldType("expirationDate")]:[this.createRequiredError(this.mapFieldType("expirationDate"))],[this.mapFieldType("number")]:[this.createRequiredError(this.mapFieldType("number"))],[this.mapFieldType("cardholderName")]:[this.createRequiredError(this.mapFieldType("cardholderName"))]}}return null===(i=null===(n=e.details)||void 0===n?void 0:n.invalidFieldKeys)||void 0===i?void 0:i.reduce((e,t)=>{const n=this.mapFieldType(t);return Object.assign(Object.assign({},e),{[n]:[this.createInvalidError(n)]})},{})}createRequiredError(e){var t;return{fieldType:e,message:null!==(t={[Bi.CardCode]:"CVV is required",[Bi.CardCodeVerification]:"CVV is required",[Bi.CardNumber]:"Credit card number is required",[Bi.CardNumberVerification]:"Credit card number is required",[Bi.CardExpiry]:"Expiration date is required",[Bi.CardName]:"Full name is required"}[e])&&void 0!==t?t:"Field is required",type:"required"}}createInvalidError(e){var t,n,i,r;const o={[Bi.CardCode]:{message:"Invalid card code",type:"invalid_card_code"},[Bi.CardCodeVerification]:{message:"Invalid card code",type:"invalid_card_code"},[Bi.CardNumber]:{message:"Invalid card number",type:"invalid_card_number"},[Bi.CardNumberVerification]:{message:"Invalid card number",type:"invalid_card_number"},[Bi.CardExpiry]:{message:"Invalid card expiry",type:"invalid_card_expiry"},[Bi.CardName]:{message:"Invalid card name",type:"invalid_card_name"}};return{fieldType:e,message:null!==(n=null===(t=o[e])||void 0===t?void 0:t.message)&&void 0!==n?n:"Invalid field",type:null!==(r=null===(i=o[e])||void 0===i?void 0:i.type)&&void 0!==r?r:"invalid"}}isValidForm(e){return Object.keys(e.fields).every(t=>{var n;return null===(n=e.fields[t])||void 0===n?void 0:n.isValid})}isValidParam(e){return["number","cvv","expirationDate","postalCode","cardholderName","cardType"].includes(e)}}const Ql=vi(e=>{const t=window,n=new Ei(e),i=new Hi(a(),t,n),r=new _o(i,t),o=new Zl(i,n);return new Wl(e,r,o)},[{id:"braintree"}]);var Xl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})},eu=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r(this._shouldRenderHostedForm=!0,this._hostedForm=r,Promise.resolve()))}deinitialize(){return this._hostedForm&&this._hostedForm.detach(),Promise.resolve()}finalize(){return Promise.reject(new Cd)}_executeWithoutHostedForm(e,t){return Xl(this,void 0,void 0,function*(){const{payment:n}=e,i=eu(e,["payment"]),r=n&&n.paymentData;if(!n||!r)throw new co(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(i,t),yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:r}))})}_executeWithHostedForm(e,t){return Xl(this,void 0,void 0,function*(){const{payment:n}=e,i=eu(e,["payment"]),r=this._hostedForm;if(!r)throw new ri(ei.PaymentNotInitialized);if(!n||!n.methodId)throw new co(["payment.methodId"]);yield this._paymentIntegrationService.submitOrder(i,t),yield r.validate().then(()=>r.submit(n))})}_isHostedPaymentFormEnabled(e,t){return!!e&&!0===this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t).config.isHostedFormEnabled}_isHostedFieldAvailable(e){return!Ce(e&&e.creditCard&&e.creditCard.form.fields).every(J)}}var nu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class iu extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this.cbaMGPSScriptLoader=t,this.sessionId=""}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return nu(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{methodId:n}=e;yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(n);if(!function(e){return"object"==typeof e&&null!==e&&"initializationData"in e&&"object"==typeof e.initializationData&&null!==e.initializationData&&"merchantId"in e.initializationData&&"string"==typeof e.initializationData.merchantId&&("boolean"==typeof e.initializationData.isTestModeFlagEnabled||void 0===e.initializationData.isTestModeFlagEnabled)}(r))throw new ti(Xn.MissingPaymentMethod);const{clientToken:o,initializationData:{isTestModeFlagEnabled:a=!1,merchantId:s},config:{is3dsEnabled:d}}=r;if(d){if(this.threeDSjs=yield this.cbaMGPSScriptLoader.load(a),!this.threeDSjs)throw new ri(ei.PaymentNotInitialized);if(!o||!s)throw new ti(Xn.MissingPaymentMethod);if(this.sessionId=o,this.locale=i.getLocale(),!this.locale)throw new ti(Xn.MissingCart);yield this.threeDSjs.configure({merchantId:s,sessionId:this.sessionId,callback:()=>{var e;if(null===(e=this.threeDSjs)||void 0===e?void 0:e.isConfigured())return this.paymentIntegrationService.getState();throw new Qr("Failed to configure 3DS API.")},configuration:{userLanguage:this.locale,wsVersion:62}})}return Promise.resolve()})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return nu(this,void 0,void 0,function*(){const{payment:i}=e,r=i&&i.paymentData;if(!i||!r)throw new co(["payment.paymentData"]);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i.methodId),{is3dsEnabled:a}=o.config;if(a){const t=Object.assign(Object.assign({},r),{threeDSecure:{token:this.sessionId}});e.payment&&(e.payment.paymentData=t)}return n.execute.call(this,e,t).catch(e=>{if(!a||!pa(e)||!ve(e.body.errors,{code:"three_d_secure_required"}))return Promise.reject(e);const t=this.paymentIntegrationService.getState(),n=t.getOrder(),{storeProfile:{storeId:i}}=t.getStoreConfigOrThrow();if(!n||!this.sessionId)throw new ti(Xn.MissingCheckout);const r=`${i}_${n.orderId}`;if("object"!=typeof(o=e.body)||null===o||!("three_ds_result"in o)||"object"!=typeof o.three_ds_result||null===o.three_ds_result||!("token"in o.three_ds_result)||"string"!=typeof o.three_ds_result.token)throw new nr;var o;const{three_ds_result:{token:s}}=e.body;return s?this.initiateAuthentication(r,s):Promise.reject(e)})})}finalize(e){return nu(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE?(yield this.paymentIntegrationService.finalizeOrder(e),Promise.resolve()):Promise.reject(new Cd)})}deinitialize(){return this.threeDSjs=void 0,this.sessionId="",super.deinitialize()}initiateAuthentication(e,t){return nu(this,void 0,void 0,function*(){const n=yield new Promise((n,i)=>{if(!this.threeDSjs)throw new ri(ei.PaymentNotInitialized);this.threeDSjs.initiateAuthentication(e,t,e=>{const t=e.error;return t?i(new Qr(t.msg)):this.threeDSjs&&"PROCEED"===e.gatewayRecommendation?n(e.restApiResponse):i(new Qr)})});if(n.transaction&&"AUTHENTICATION_AVAILABLE"===n.transaction.authenticationStatus)return this.authenticatePayer(e,t);throw new Qr})}authenticatePayer(e,t,n=1){return nu(this,void 0,void 0,function*(){return new Promise((i,r)=>{if(!this.threeDSjs)return r(new ri(ei.PaymentNotInitialized));this.threeDSjs.authenticatePayer(e,t,i=>nu(this,void 0,void 0,function*(){const o=i.error;return o?o.cause&&"SERVER_BUSY"===o.cause&&n<5?(yield new Promise(e=>setTimeout(e,3e3)),this.authenticatePayer(e,t,++n)):r(new Qr):new Promise(ce)}),{fullScreenRedirect:!0})})})}}class ru{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e){return t=this,n=void 0,r=function*(){if(yield this._scriptLoader.loadScript(`//${e?"test":"ap"}-gateway.mastercard.com/static/threeDS/1.3.0/three-ds.min.js`),!this._window.ThreeDS)throw new mi;return this._window.ThreeDS},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const ou=vi(e=>new iu(e,new ru(a())),[{id:"cba_mpgs"}]);var au;!function(e){e.OffsiteRedirect="offsite_redirect"}(au||(au={}));class su extends tu{constructor(e){super(e),this.paymentIntegrationService=e}finalize(e){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),Promise.reject(new Cd)}_executeWithHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{window.location.replace(e.data.redirect_url)})}}class du extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew du(e),[{gateway:"checkoutcom",id:"fawry"}]);function lu(e){return pa(e)&&ve(e.body.errors,{code:"three_d_secure_required"})}var uu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})},hu=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rthis.formPoster.postForm(t,{PaReq:n||null,TermUrl:i||null,MD:r||null}))}}const mu=vi(e=>new pu(e,Ee()),[{gateway:"checkoutcom",id:"credit_card"},{gateway:"checkoutcom",id:"card"}]);class yu extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew yu(e),[{gateway:"checkoutcom",id:"sepa"}]);class vu extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew vu(e),[{gateway:"checkoutcom",id:"ideal"}]);const Su=["boleto","oxxo","qpay","ideal"];class _u extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew _u(e),[{gateway:"checkoutcom"}]);var Iu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Cu{constructor(e,t){this._paymentIntegrationService=e,this._clearpayScriptLoader=t}initialize(e){return Iu(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:t}=this._paymentIntegrationService.getState(),n=t(e.methodId,e.gatewayId),i=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features;this._clearpaySdk=yield this._clearpayScriptLoader.load(n,i)})}deinitialize(){return this._clearpaySdk=void 0,Promise.resolve()}execute(e,t){return Iu(this,void 0,void 0,function*(){const{gatewayId:n,methodId:i}=e.payment||{};if(!n||!i)throw new co(["payment.gatewayId","payment.methodId"]);const r=this._paymentIntegrationService.getState(),{isStoreCreditApplied:o}=r.getCheckoutOrThrow();yield this._paymentIntegrationService.applyStoreCredit(o),yield this._paymentIntegrationService.validateCheckout(r.getCheckout(),t);const{countryCode:a}=r.getBillingAddressOrThrow();if(!this._isCountrySupported(a))throw new fi("Unable to proceed because billing country is not supported.");return yield this._loadPaymentMethod(n,i,t),yield this._redirectToClearpay(a,this._paymentIntegrationService.getState().getPaymentMethod(i,n)),new Promise(ce)})}finalize(e){var t,n,i;return Iu(this,void 0,void 0,function*(){const r=this._paymentIntegrationService.getState(),o=r.getPaymentId(),a=r.getContextConfig();if(!o)throw new ti(Xn.MissingCheckout);if(!a||!a.payment.token)throw new ti(Xn.MissingCheckoutConfig);const s={methodId:o.providerId,paymentData:{nonce:a.payment.token}};yield this._paymentIntegrationService.submitOrder({},e);try{yield this._paymentIntegrationService.submitPayment(s)}catch(e){if(yield this._paymentIntegrationService.forgetCheckout(o.providerId),yield this._paymentIntegrationService.loadPaymentMethods(),pa(e))throw new Kd(null===(i=null===(n=null===(t=e.body)||void 0===t?void 0:t.errors)||void 0===n?void 0:n[0])||void 0===i?void 0:i.message)}})}_redirectToClearpay(e,t){return Iu(this,void 0,void 0,function*(){if(!this._clearpaySdk||!t||!t.clientToken)throw new ri(ei.PaymentNotInitialized);return this._clearpaySdk.initialize({countryCode:e}),this._clearpaySdk.redirect({token:t.clientToken}),Promise.resolve()})}_isCountrySupported(e){return"GB"===e}_loadPaymentMethod(e,t,n){var i;return Iu(this,void 0,void 0,function*(){try{return yield this._paymentIntegrationService.loadPaymentMethod(e,Object.assign(Object.assign({},n),{params:Object.assign(Object.assign({},null==n?void 0:n.params),{method:t})}))}catch(e){if(e instanceof nr&&422===(null===(i=e.body)||void 0===i?void 0:i.status))throw new fi("Clearpay can't process your payment for this order, please try another payment method");throw e}})}}class bu{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e,t={}){return n=this,i=void 0,o=function*(){if(yield this._scriptLoader.loadScript(this._getScriptUrl(e.config.testMode,t)),!this._window.AfterPay)throw new mi;return this._window.AfterPay},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_getScriptUrl(e,t={}){const n=Ci(t,"PI-4555.clearpay_add_https_to_prod_script",!1);return e?n?"https://portal.sandbox.clearpay.co.uk/afterpay-async.js":"//portal.sandbox.clearpay.co.uk/afterpay-async.js":n?"https://portal.clearpay.co.uk/afterpay-async.js":"//portal.clearpay.co.uk/afterpay-async.js"}}const Pu=vi(e=>new Cu(e,new bu(a())),[{gateway:"clearpay"},{id:"clearpay"}]),Ou=vi(e=>new tu(e),[{default:!0}]);var Eu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Au{constructor(e,t){this._paymentIntegrationService=e,this._cardinalClient=t}prepare(e){return Eu(this,void 0,void 0,function*(){yield this._cardinalClient.load(e.id,e.config.testMode),yield this._cardinalClient.configure(yield this._getClientToken(e))})}start(e,t,n,i){return Eu(this,void 0,void 0,function*(){const{getCardInstrument:r,getPaymentMethodOrThrow:o}=this._paymentIntegrationService.getState(),{payment:{methodId:a="",paymentData:s={}}={}}=t,d=xd(s)&&r(s.instrumentId),c=d?d.iin:i&&i.getBin();c&&(yield this._cardinalClient.runBinProcess(c));try{return yield e(de(t,{payment:{paymentData:{threeDSecure:{token:o(a).clientToken}}}}),n)}catch(e){if(!pa(e)||!ve(e.body.errors,{code:"three_d_secure_required"}))throw e;const n=yield this._cardinalClient.getThreeDSecureData(e.body.three_ds_result,this._getOrderData());if(!i)return void(yield this._paymentIntegrationService.submitPayment(de(t.payment,{paymentData:{threeDSecure:n}})));yield i.submit(de(t.payment,{paymentData:{threeDSecure:n}}))}})}_getClientToken(e){return Eu(this,void 0,void 0,function*(){return e.clientToken?e.clientToken:(yield this._paymentIntegrationService.loadPaymentMethod(e.id),this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.id).clientToken||"")})}_getOrderData(){const e=this._paymentIntegrationService.getState(),t=e.getBillingAddressOrThrow(),n=e.getShippingAddress(),i=e.getCheckoutOrThrow(),r=e.getOrderOrThrow();return{billingAddress:t,shippingAddress:n,currencyCode:i.cart.currency.code,id:r.orderId.toString(),amount:i.cart.cartAmount}}}const Tu=[100004,1010,1011,1020];var ku,Du,Mu,zu,Nu,xu,Ru;!function(e){e.SetupCompleted="payments.setupComplete",e.Validated="payments.validated"}(ku||(ku={})),function(e){e.Init="init",e.Complete="complete",e.Confirm="confirm"}(Du||(Du={})),function(e){e.Success="SUCCESS",e.NoAction="NOACTION",e.Failure="FAILURE",e.Error="ERROR"}(Mu||(Mu={})),function(e){e.CCA="CCA",e.Paypal="Paypal",e.Wallet="Wallet",e.VisaCheckout="VisaCheckout",e.ApplePay="ApplePay",e.DiscoverWallet="DiscoverWallet"}(zu||(zu={})),function(e){e.BinProcess="bin.process"}(Nu||(Nu={})),function(e){e.CCA="cca"}(xu||(xu={})),function(e){e.Yes="Y",e.No="N"}(Ru||(Ru={}));class Fu{constructor(e){this._scriptLoader=e,this._provider="",this._testMode=!1,this._configurationToken=""}load(e,t=!1){return this._provider=e,this._testMode=t,this._sdk||(this._sdk=this._scriptLoader.load(e,t)),this._sdk.then(ce)}configure(e){if(this._configurationToken){if(this._configurationToken===e)return Promise.resolve();this._sdk=this._scriptLoader.load(`${this._provider}.${Date.now()}`,this._testMode)}return this._getClientSDK().then(t=>new Promise((n,i)=>{t.on(ku.SetupCompleted,()=>{t.off(ku.SetupCompleted),t.off(ku.Validated),this._configurationToken=e,n()}),t.on(ku.Validated,e=>{t.off(ku.SetupCompleted),t.off(ku.Validated),e.ActionCode===Mu.Error&&(H(Tu,e.ErrorNumber)&&i(new ti(Xn.MissingPaymentMethod)),i(new Qr(e.ErrorDescription)))}),t.setup(Du.Init,{jwt:e})}))}runBinProcess(e){return this._getClientSDK().then(t=>t.trigger(Nu.BinProcess,e).catch(ce)).then(e=>{if(!e||!e.Status)throw new ri(ei.PaymentNotInitialized)})}getThreeDSecureData(e,t){return this._getClientSDK().then(n=>new Promise((i,r)=>{n.on(ku.Validated,(e,t)=>{if(n.off(ku.Validated),!t)return r(new Qr(e.ErrorDescription?e.ErrorDescription:"An error was encountered while processing the transaction."));if(!e.ActionCode)return i({token:t});switch(e.ActionCode){case Mu.Success:return i({token:t});case Mu.NoAction:return e.ErrorNumber>0?r(new Qr(e.ErrorDescription)):e.Payment&&e.Payment.ExtendedData&&e.Payment.ExtendedData.SignatureVerification===Ru.Yes?i({token:t}):r(new Qr("Transaction signature could not be validated."));case Mu.Failure:return r(new Qr("User failed authentication or an error was encountered while processing the transaction."));case Mu.Error:return r(new Qr(e.ErrorDescription))}});const o={AcsUrl:e.acs_url,Payload:e.merchant_data},a=this._mapToPartialOrder(t,e.payer_auth_request);n.continue(xu.CCA,o,a)}))}_mapToPartialOrder(e,t){const n={BillingAddress:this._mapToCardinalAddress(e.billingAddress)};return e.paymentData&&(n.Account=this._mapToCardinalAccount(e.paymentData)),e.billingAddress.email&&(n.Email1=e.billingAddress.email),e.shippingAddress&&(n.ShippingAddress=this._mapToCardinalAddress(e.shippingAddress)),{Consumer:n,OrderDetails:{OrderNumber:e.id,Amount:e.amount,CurrencyCode:e.currencyCode,OrderChannel:"S",TransactionId:t}}}_mapToCardinalAccount(e){return{AccountNumber:Number(e.ccNumber),ExpirationMonth:Number(e.ccExpiry.month),ExpirationYear:Number(e.ccExpiry.year),NameOnAccount:e.ccName,CardCode:Number(e.ccCvv)}}_mapToCardinalAddress(e){const t={FirstName:e.firstName,LastName:e.lastName,Address1:e.address1,City:e.city,State:e.stateOrProvince,PostalCode:e.postalCode,CountryCode:e.countryCode};return e.address2&&(t.Address2=e.address2),e.phone&&(t.Phone1=e.phone),t}_getClientSDK(){if(!this._sdk)throw new ri(ei.PaymentNotInitialized);return this._sdk}}class Lu{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e,t){const n=t?"https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js":"https://static.client.cardinaltrusted.com/songbird/v2.0.0/songbird.js";return this._scriptLoader.loadScript(`${n}?v=${e}`).then(()=>{if(!this._window.Cardinal)throw new mi;return this._window.Cardinal})}}var Bu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ju extends tu{constructor(e,t){super(e),this._threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Bu(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),i=n(e.methodId);i.config.is3dsEnabled&&(yield this._threeDSecureFlow.prepare(i))})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return Bu(this,void 0,void 0,function*(){const{payment:{methodId:i=""}={}}=e,{getPaymentMethodOrThrow:r}=this._paymentIntegrationService.getState();return r(i).config.is3dsEnabled?this._threeDSecureFlow.start(n.execute.bind(this),e,t,this._hostedForm):n.execute.call(this,e,t)})}}const Uu=vi(e=>new ju(e,new Au(e,new Fu(new Lu(a())))),[{id:"cybersource"}]);var qu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vu{constructor(e,t){this._paymentIntegrationService=e,this._cardinalClient=t}prepare(e){return qu(this,void 0,void 0,function*(){yield this._cardinalClient.load(e.id,e.config.testMode)})}start(e,t,n,i){var r,o,a,s;return qu(this,void 0,void 0,function*(){const{getCardInstrument:d}=this._paymentIntegrationService.getState(),{payment:c={methodId:""}}=t,{paymentData:l={}}=c;try{return yield e(t,n)}catch(e){if(pa(e)&&"additional_action_required"===(null===(r=e.body)||void 0===r?void 0:r.status)){const t=null===(a=null===(o=e.body.additional_action_required)||void 0===o?void 0:o.data)||void 0===a?void 0:a.token,n=null===(s=e.body.three_ds_result)||void 0===s?void 0:s.payer_auth_request;yield this._cardinalClient.configure(t);const r=this._getBin(l,d,i);r&&(yield this._cardinalClient.runBinProcess(r));try{return yield this._submitPayment(c,{xid:n},i)}catch(e){if(pa(e)&&ve(e.body.errors,{code:"three_d_secure_required"})){const t=e.body.three_ds_result,n=null==t?void 0:t.payer_auth_request;return yield this._cardinalClient.getThreeDSecureData(t,this._getOrderData()),this._submitPayment(c,{token:n},i)}throw e}}throw e}})}_getOrderData(){const e=this._paymentIntegrationService.getState(),t=e.getBillingAddressOrThrow(),n=e.getShippingAddress(),{cart:{currency:{code:i},cartAmount:r}}=e.getCheckoutOrThrow();return{billingAddress:t,shippingAddress:n,currencyCode:i,id:e.getOrderOrThrow().orderId.toString(),amount:r}}_submitPayment(e,t,n){return qu(this,void 0,void 0,function*(){const i=de({},e,{paymentData:{threeDSecure:t}});n||(yield this._paymentIntegrationService.submitPayment(i)),yield null==n?void 0:n.submit(i)})}_getBin(e,t,n){const i=xd(e)&&t(e.instrumentId),r=function(e){const t=e;return!xd(t)&&"string"==typeof t.ccName&&"string"==typeof t.ccNumber&&"object"==typeof t.ccExpiry&&"string"==typeof t.ccExpiry.month&&"string"==typeof t.ccExpiry.year}(e)&&e.ccNumber,o=n?n.getBin():r;return(i?i.iin:o)||""}}var Gu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Hu extends tu{constructor(e,t){super(e),this._threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Gu(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),i=n(e.methodId);i.config.is3dsEnabled&&(yield this._threeDSecureFlow.prepare(i))})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return Gu(this,void 0,void 0,function*(){const{payment:{methodId:i=""}={}}=e,{getPaymentMethodOrThrow:r}=this._paymentIntegrationService.getState();return r(i).config.is3dsEnabled?this._threeDSecureFlow.start(n.execute.bind(this),e,t,this._hostedForm):n.execute.call(this,e,t)})}}const Wu=vi(e=>new Hu(e,new Vu(e,new Fu(new Lu(a())))),[{id:"cybersourcev2"},{id:"bnz"}]);function $u(e){return"object"==typeof e&&null!==e&&"errors"in e&&Array.isArray(e.errors)&&"code"in e.errors[0]&&"string"==typeof e.errors[0].code&&"provider_data"in e&&"object"==typeof e.provider_data}var Yu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ku extends ea{constructor(e,t){super("adyen",e),this._scriptLoader=t,this._service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Yu(this,void 0,void 0,function*(){yield i.initialize.call(this,e,t,n);const r=i.getPaymentMethod.call(this),o=this._service.getState().getStoreConfig();if(!o)throw new ti(Xn.MissingCheckoutConfig);return this._adyenClient=yield this._scriptLoader.load({environment:r.config.testMode?"test":"live",locale:o.storeProfile.storeLanguage}),Promise.resolve()})}getNonce(e){const t=Object.create(null,{getNonce:{get:()=>super.getNonce},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Yu(this,void 0,void 0,function*(){const n=yield t.getNonce.call(this,e),i=t.getPaymentMethod.call(this);return JSON.stringify({type:i.method,googlePayToken:n,browser_info:ss()})})}processAdditionalAction(e){return Yu(this,void 0,void 0,function*(){if(!pa(e)||!$u(e.body))throw e;const t=yield this._handleAction(e.body.provider_data);try{return yield this._service.submitPayment(t)}catch(e){return this.processAdditionalAction(e)}})}_handleAction(e){return new Promise((t,n)=>{const i=JSON.parse(e.action);this._getAdyenClient().createFromAction(i,{onAdditionalDetails:e=>{const n={methodId:i.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};t(n)},size:"05",onError:e=>n(e)}).mount("body"),n(new Wi)})}_getAdyenClient(){if(!this._adyenClient)throw new ri(ei.PaymentNotInitialized);return this._adyenClient}}var Ju=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Zu{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t,this._isDeinitializationBlocked=!1,this._loadingIndicator=new vd({containerStyles:yd})}initialize(e){var t,n;return Ju(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId)||!na(e.methodId))throw new fi('Unable to proceed because "methodId" is not a valid key.');this._methodId=e.methodId;const i=e[this._getMethodId()];if(!(null==i?void 0:i.walletButton))throw new fi("Unable to proceed without valid options.");const{walletButton:r,loadingContainerId:o}=i,a=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rs,this._getGooglePayClientOptions(null===(n=s.initializationData)||void 0===n?void 0:n.storeCountry)),this._addPaymentButton(r,a)})}execute({payment:e}){return Ju(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new co(["payment"]);yield this._paymentIntegrationService.submitOrder();const t=yield this._googlePayPaymentProcessor.getNonce(e.methodId),n=yield this._googlePayPaymentProcessor.extraPaymentData();try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:Object.assign({nonce:t},n)}))}catch(t){yield this._googlePayPaymentProcessor.processAdditionalAction(t,e.methodId)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this._isDeinitializationBlocked||(this._clickListener&&(null===(e=this._paymentButton)||void 0===e||e.removeEventListener("click",this._clickListener)),this._paymentButton=void 0,this._clickListener=void 0,this._methodId=void 0),Promise.resolve()}_addPaymentButton(e,t){if(this._paymentButton)return;const n=document.getElementById(e);if(!n)throw new fi("Unable to proceed without a walletButton.");this._paymentButton=n,this._clickListener=this._handleClick(t),this._paymentButton.addEventListener("click",this._clickListener)}_handleClick({onPaymentSelect:e,onError:t}){return n=>Ju(this,void 0,void 0,function*(){n.preventDefault();try{this._googlePayPaymentProcessor.setShouldRequestShipping(!1),yield this._googlePayPaymentProcessor.initializeWidget(),this._isDirectPayOnClickEnabled()?yield this._interactWithPaymentSheetAndPay():yield this._interactWithPaymentSheet()}catch(e){let n=e;if(this._toggleLoadingIndicator(!1),ta(e)){if("CANCELED"===e.statusCode)throw new Wi;n=new Qr(JSON.stringify(e))}throw null==t||t(new Qr("An error occurred while requesting your Google Pay payment details.")),n}finally{this._toggleBlockDeinitialization(!1)}null==e||e()})}_interactWithPaymentSheetAndPay(){return Ju(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet();this._toggleBlockDeinitialization(!0),this._toggleLoadingIndicator(!0);const t=this._getMethodId(),n=this._paymentIntegrationService.getState(),{features:i}=n.getStoreConfigOrThrow().checkoutSettings,r=Ci(i,"PI-5031.google_pay_dont_override_address"),o=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e);o&&!r&&(yield this._paymentIntegrationService.updateBillingAddress(o)),yield this._googlePayPaymentProcessor.setExternalCheckoutXhr(t,e),yield this._paymentIntegrationService.loadCheckout(),yield this._paymentIntegrationService.loadPaymentMethod(t);const a=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(t);yield this._googlePayPaymentProcessor.initialize(()=>a),yield this.execute({useStoreCredit:!1,payment:{methodId:t}}),this._completeCheckoutFlow()})}_completeCheckoutFlow(){window.location.replace("/checkout/order-confirmation"),this._toggleLoadingIndicator(!1),this._toggleBlockDeinitialization(!1)}_interactWithPaymentSheet(){return Ju(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet(),t=this._paymentIntegrationService.getState(),{features:n}=t.getStoreConfigOrThrow().checkoutSettings,i=Ci(n,"PI-5031.google_pay_dont_override_address");this._toggleBlockDeinitialization(!0),this._toggleLoadingIndicator(!0);const r=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e);r&&!i&&(yield this._paymentIntegrationService.updateBillingAddress(r)),yield this._googlePayPaymentProcessor.setExternalCheckoutXhr(this._getMethodId(),e),yield this._paymentIntegrationService.loadCheckout(),yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodId()),this._toggleLoadingIndicator(!1),this._toggleBlockDeinitialization(!1)})}_getMethodId(){return ii(this._methodId,()=>new ri(ei.PaymentNotInitialized))}_getIsSignedInOrThrow(){return Ju(this,void 0,void 0,function*(){try{return!!(yield this._googlePayPaymentProcessor.getNonce(this._getMethodId()))}catch(e){if(e instanceof ti&&e.subtype===Xn.MissingPaymentToken)return!1;throw e}})}_handleOfferTrigger(e){return Ju(this,void 0,void 0,function*(){let t=!1,n="Sign in to Google Pay first to apply or remove promo codes.";try{t=yield this._getIsSignedInOrThrow()}catch(e){e instanceof ti&&(n=e.message)}if(t){const{newOfferInfo:t,error:n}=yield this._googlePayPaymentProcessor.handleCoupons(e);return{newOfferInfo:t,error:n}}return{error:{reason:Ko.OFFER_INVALID,message:n,intent:Jo.OFFER}}})}_getGooglePayClientOptions(e){return this._googlePayPaymentProcessor.isWebViewWithRestrictions()?{}:{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:t,offerData:n})=>Ju(this,void 0,void 0,function*(){if(t!==Jo.INITIALIZE&&t!==Jo.OFFER)return;const{offerChangeTriggers:i}=this._googlePayPaymentProcessor.getCallbackTriggers(),{newOfferInfo:r,error:o}=i.includes(t)?yield this._handleOfferTrigger(n):{},a=o;yield this._paymentIntegrationService.loadCheckout();const{code:s}=this._paymentIntegrationService.getState().getCartOrThrow().currency,d=this._googlePayPaymentProcessor.getTotalPrice();return Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},e&&{countryCode:e}),{currencyCode:s,totalPriceStatus:Wo.FINAL,totalPrice:d})},r&&{newOfferInfo:r}),a&&{error:a})})}}}_isDirectPayOnClickEnabled(){const{features:e}=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings;return Ci(e,"PI-5111.google_pay_direct_pay_on_click")}_toggleBlockDeinitialization(e){this._isDeinitializationBlocked=e}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this._loadingIndicator.show(this._loadingIndicatorContainer):this._loadingIndicator.hide()}}const Qu=vi(e=>new Zu(e,new aa(da(),new Ku(e,new zd(a(),s())),n(),Ee())),[{id:"googlepayadyenv2"}]);var Xu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class eh extends ea{constructor(e,t){super("adyen",e),this._scriptLoader=t,this._service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Xu(this,void 0,void 0,function*(){yield i.initialize.call(this,e,t,n);const r=i.getPaymentMethod.call(this),o=this._service.getState().getStoreConfig();if(!o)throw new ti(Xn.MissingCheckoutConfig);return this._adyenClient=yield this._scriptLoader.load({environment:r.config.testMode?"test":"live",locale:o.storeProfile.storeLanguage}),Promise.resolve()})}processAdditionalAction(e){return Xu(this,void 0,void 0,function*(){if(!pa(e)||!$u(e.body))throw e;const t=yield this._handleAction(e.body.provider_data);try{return yield this._service.submitPayment(t)}catch(e){return this.processAdditionalAction(e)}})}getNonce(e){const t=Object.create(null,{getNonce:{get:()=>super.getNonce},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Xu(this,void 0,void 0,function*(){const n=yield t.getNonce.call(this,e),i=t.getPaymentMethod.call(this);return JSON.stringify({type:i.method,googlePayToken:n,browser_info:ss()})})}_handleAction(e){return new Promise((t,n)=>{const i=JSON.parse(e.action);this._getAdyenClient().createFromAction(i,{onAdditionalDetails:e=>{const n={methodId:i.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};t(n)},size:"05",onError:e=>n(e)}).mount("body"),n(new Wi)})}_getAdyenClient(){if(!this._adyenClient)throw new ri(ei.PaymentNotInitialized);return this._adyenClient}}const th=vi(e=>new Zu(e,new aa(da(),new eh(e,new Bd(a(),s())),n(),Ee())),[{id:"googlepayadyenv3"}]),nh=vi(e=>new Zu(e,new aa(da(),new ua(e),n(),Ee())),[{id:"googlepayauthorizenet"}]),ih=vi(e=>{const t=n();return new Zu(e,new aa(da(),new ga(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]),rh=vi(e=>new Zu(e,new aa(da(),new fa(e),n(),Ee())),[{id:"googlepaycybersourcev2"},{id:"googlepaybnz"}]),oh=vi(e=>new Zu(e,new aa(da(),new wa(e),n(),Ee())),[{id:"googlepayorbital"}]),ah=vi(e=>new Zu(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeupe"},{id:"googlepaystripeocs"}]),sh=vi(e=>new Zu(e,new aa(da(),new Ga(e),n(),Ee())),[{id:"googlepayworldpayaccess"}]),dh=vi(e=>{const t=n(),i=window,r=new Ei(e),o=new Ui(new Hi(a(),i,r));return new Zu(e,new aa(da(),new $a(e,o),t,Ee()))},[{id:"googlepaybraintree"}]);var ch,lh;!function(e){e.Approved="APPROVED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(ch||(ch={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(lh||(lh={}));var uh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class hh extends Zu{constructor(e,t,n,i){super(e,t),this._payPalCommerceSdk=n,this._requestSender=i}execute({payment:e}){return uh(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new co(["payment"]);const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow().id,{initializationData:i}=t.getPaymentMethodOrThrow(this._getMethodId()),{orderId:r}=yield this.getOrderId(n),{card_information:o}=i||{},a=yield this._googlePayPaymentProcessor.getNonce(e.methodId),s={tokenizationData:{type:"PAYMENT_GATEWAY",token:atob(a)},info:{cardNetwork:(null==o?void 0:o.type)||"",cardDetails:(null==o?void 0:o.number)||""},type:"CARD"};yield this.confirmOrder(r,s),yield this._paymentIntegrationService.submitOrder();try{const t={formattedPayload:{method_id:e.methodId,paypal_account:{order_id:r}}};yield this._paymentIntegrationService.submitPayment({methodId:e.methodId,paymentData:t})}catch(e){yield this._googlePayPaymentProcessor.processAdditionalAction(e)}})}confirmOrder(e,t){return uh(this,void 0,void 0,function*(){const n=this._paymentIntegrationService.getState(),i=n.getPaymentMethodOrThrow(this._getMethodId());if(!i.initializationData)throw new ti(Xn.MissingPaymentMethod);const r=n.getCartOrThrow().currency.code,o=yield this._payPalCommerceSdk.getPayPalGooglePaySdk(i,r,n.getLocale(),!0),{status:a}=yield o.Googlepay().confirmOrder({orderId:e,paymentMethodData:t});if(a===ch.PayerActionRequired)return yield o.Googlepay().initiatePayerAction({orderId:e}),Promise.resolve();if(a!==ch.Approved)throw new fi("Payment is not approved.");return Promise.resolve()})}getOrderId(e){return uh(this,void 0,void 0,function*(){const t={cartId:e,shouldSaveInstrument:!1},{body:n}=yield this._requestSender.post("/api/storefront/payments/googlepaypaypalcommercecheckout",{headers:Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr),body:t});return n})}}const ph=vi(e=>{const t=new Xa(a());return new hh(e,new aa(da(),new ns(e,t),n(),Ee()),t,n())},[{id:"googlepaypaypalcommerce"}]);var mh,yh;!function(e){e.Approved="APPROVED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(mh||(mh={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(yh||(yh={}));var gh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vh extends Zu{constructor(e,t,n,i){super(e,t),this._payPalSdkHelper=n,this._requestSender=i}execute({payment:e}){return gh(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new co(["payment"]);const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow().id,{initializationData:i}=t.getPaymentMethodOrThrow(this._getMethodId()),{orderId:r}=yield this.getOrderId(n),{card_information:o}=i||{},a=yield this._googlePayPaymentProcessor.getNonce(e.methodId),s={tokenizationData:{type:"PAYMENT_GATEWAY",token:atob(a)},info:{cardNetwork:(null==o?void 0:o.type)||"",cardDetails:(null==o?void 0:o.number)||""},type:"CARD"};yield this.confirmOrder(r,s),yield this._paymentIntegrationService.submitOrder();try{const t={formattedPayload:{method_id:e.methodId,paypal_account:{order_id:r}}};yield this._paymentIntegrationService.submitPayment({methodId:e.methodId,paymentData:t})}catch(e){yield this._googlePayPaymentProcessor.processAdditionalAction(e)}})}confirmOrder(e,t){return gh(this,void 0,void 0,function*(){const n=this._paymentIntegrationService.getState(),i=n.getPaymentMethodOrThrow(this._getMethodId());if(!i.initializationData)throw new ti(Xn.MissingPaymentMethod);const r=n.getCartOrThrow().currency.code,o=yield this._payPalSdkHelper.getPayPalGooglePaySdk(i,r,!0),{status:a}=yield o.Googlepay().confirmOrder({orderId:e,paymentMethodData:t});if(a===mh.PayerActionRequired)return yield o.Googlepay().initiatePayerAction({orderId:e}),Promise.resolve();if(a!==mh.Approved)throw new fi("Payment is not approved.");return Promise.resolve()})}getOrderId(e){return gh(this,void 0,void 0,function*(){const t={cartId:e,shouldSaveInstrument:!1},{body:n}=yield this._requestSender.post("/api/storefront/payments/googlepay_bigcommerce_paymentscheckout",{headers:Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr),body:t});return n})}}const fh=vi(e=>{const t=new xr(a());return new vh(e,new aa(da(),new os(e,t),n(),Ee()),t,n())},[{id:"googlepay_bigcommerce_payments"}]),Sh=vi(e=>new Zu(e,new aa(da(),new cs(e,Ee()),n(),Ee())),[{id:"googlepaytdonlinemart"}]);class _h extends Qn{constructor(e,t,n){super(n||"Payment cannot be processed for this order, please select another payment method"),this.type="custom_provider_execute_error",this.name=t,this.subtype=e}}class wh{constructor(e,t){this.paymentIntegrationService=e,this.formPoster=t}execute(e,t){var n,i,r,o,a;return i=this,r=void 0,a=function*(){const{payment:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.formPoster.postForm(t,JSON.parse(n),e)})}isOffsiteRedirectResponse(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!t.body)return!1;const n=t.body;return"additional_action_required"===n.status&&!!n.additional_action_required&&"offsite_redirect"===n.additional_action_required.type&&"string"==typeof n.provider_data}}const Ih=vi(e=>new wh(e,Ee()),[{id:"humm"}]),Ch=["AT","BE","CA","CH","CZ","DE","DK","ES","FI","FR","GB","GR","IE","IT","NL","NO","NZ","PL","PT","SE"],bh=["AU"];var Ph=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Oh{constructor(e,t){this.paymentIntegrationService=e,this.klarnaScriptLoader=t}initialize(e){return Ph(this,void 0,void 0,function*(){this.klarnaCredit=yield this.klarnaScriptLoader.load(),this.unsubscribe=this.paymentIntegrationService.subscribe(t=>{t.isPaymentMethodInitialized({methodId:e.methodId,gatewayId:e.gatewayId})&&this.loadWidget(e)},e=>{const t=e.getCheckout();return t&&t.outstandingBalance},e=>{const t=e.getCheckout();return t&&t.coupons}),yield this.loadWidget(e)})}deinitialize(){return this.unsubscribe&&this.unsubscribe(),Promise.resolve()}execute(e,t){return Ph(this,void 0,void 0,function*(){if(!e.payment)throw new fi('Unable to proceed because "payload.payment" argument is not provided.');const n=e.payment,{paymentData:i}=n,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const r=this.paymentIntegrationService.getState().getPaymentMethod(t);if(!r)throw new ti(Xn.MissingPaymentMethod);if(!this.klarnaCredit||!r.clientToken)throw new ri(ei.PaymentNotInitialized);this.klarnaCredit.init({client_token:r.clientToken}),this.klarnaCredit.load({container:n},t=>{i&&i(t),e(t)})})})}getUpdateSessionData(e,t){if(!H([...Ch,...bh],e.countryCode))return{};const n={billing_address:this.mapToKlarnaAddress(e,e.email)};return t&&(n.shipping_address=this.mapToKlarnaAddress(t,e.email)),n}needsStateCode(e){return H(bh,e)}mapToKlarnaAddress(e,t){const n={street_address:e.address1,city:e.city,country:e.countryCode,given_name:e.firstName,family_name:e.lastName,postal_code:e.postalCode,region:this.needsStateCode(e.countryCode)?e.stateOrProvinceCode:e.stateOrProvince,email:t};return e.address2&&(n.street_address2=e.address2),e.phone&&(n.phone=e.phone),n}authorize(){return new Promise((e,t)=>{const n=this.paymentIntegrationService.getState(),i=n.getBillingAddress(),r=n.getShippingAddress();if(!i)throw new ti(Xn.MissingBillingAddress);if(!this.klarnaCredit)throw new ri(ei.PaymentNotInitialized);const o=this.getUpdateSessionData(i,r);this.klarnaCredit.authorize(o,n=>n.approved?e(n):n.show_form?t(new Wi):void t(new Xr))})}}class Eh{constructor(e,t=window){this.scriptLoader=e,this.klarnaWindow=t}load(){var e,t,n,i,r,o;return n=this,i=void 0,o=function*(){if((null===(e=this.klarnaWindow.Klarna)||void 0===e?void 0:e.Credit)||(yield this.scriptLoader.loadScript("//credit.klarnacdn.net/lib/v1/api.js")),!(null===(t=this.klarnaWindow.Klarna)||void 0===t?void 0:t.Credit))throw new mi;return this.klarnaWindow.Klarna.Credit},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}}const Ah=vi(e=>new Oh(e,new Eh(a())),[{id:"klarna"}]);var Th=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class kh{constructor(e,t,n){this.paymentIntegrationService=e,this.klarnav2ScriptLoader=t,this.klarnav2TokenUpdater=n}initialize(e){return Th(this,void 0,void 0,function*(){this.klarnaPayments=yield this.klarnav2ScriptLoader.load(),this.unsubscribe=this.paymentIntegrationService.subscribe(t=>{t.isPaymentMethodInitialized({methodId:e.methodId,gatewayId:e.gatewayId})&&this.loadPaymentsWidget(e)},e=>{const t=e.getCheckout();return t&&t.outstandingBalance},e=>{const t=e.getCheckout();return t&&t.coupons}),yield this.loadPaymentsWidget(e)})}deinitialize(){return this.unsubscribe&&this.unsubscribe(),Promise.resolve()}execute(e,t){return Th(this,void 0,void 0,function*(){if(!e.payment)throw new fi('Unable to proceed because "payload.payment" argument is not provided.');const n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{throw new ti(Xn.MissingPaymentMethod)}),new Promise(e=>{const a=o.getPaymentMethodOrThrow(t),{klarnaMultipleRadioButton:s}=a.initializationData||{};if(!this.klarnaPayments||!a.clientToken)throw new ri(ei.PaymentNotInitialized);this.klarnaPayments.init({client_token:a.clientToken}),this.klarnaPayments.load({container:i,payment_method_category:this.isKlarnaMultipleRadioButtonEnabled(s,n,t)},t=>{r&&r(t),e(t)})})})}getUpdateSessionData(e,t,n){if(!H([...Ch,...bh],t.countryCode))return{};const i={billing_address:this.mapToKlarnaAddress(e,t,t.email)};return n&&(i.shipping_address=this.mapToKlarnaAddress(e,n,t.email)),i}needsStateCode(e){return H(bh,e)}isKlarnaMultipleRadioButtonEnabled(e,t,n){return e?n:t}mapToKlarnaAddress(e,t,n){const i=this.paymentIntegrationService.getState(),{checkoutSettings:r}=i.getStoreConfigOrThrow(),o=i.getPaymentMethodOrThrow(e),{enableBillie:a}=o.initializationData||{},s={street_address:t.address1,city:t.city,country:t.countryCode,given_name:t.firstName,family_name:t.lastName,postal_code:t.postalCode,region:this.needsStateCode(t.countryCode)?t.stateOrProvinceCode:t.stateOrProvince,email:n};return t.address2&&(s.street_address2=t.address2),t.phone&&(s.phone=t.phone),t.company&&a&&Ci(r.features,"PI-3915.b2b_payment_session_for_klarna")&&(s.organization_name=t.company),s}authorizeOrThrow(e,t){return Th(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const n=this.paymentIntegrationService.getState(),i=n.getBillingAddressOrThrow(),r=n.getShippingAddress(),o=this.getUpdateSessionData(t,i,r);return new Promise((t,n)=>{if(!this.klarnaPayments)return n(new ri(ei.PaymentNotInitialized));this.klarnaPayments.authorize({payment_method_category:e},o,e=>e.approved?t(e):e.show_form?n(new Wi):void n(new Xr))})})}}class Dh{constructor(e,t=window){this.scriptLoader=e,this.klarnaWindow=t}load(){var e,t,n,i,r,o;return n=this,i=void 0,o=function*(){if((null===(e=this.klarnaWindow.Klarna)||void 0===e?void 0:e.Payments)||(yield this.scriptLoader.loadScript("https://x.klarnacdn.net/kp/lib/v1/api.js")),!(null===(t=this.klarnaWindow.Klarna)||void 0===t?void 0:t.Payments))throw new mi;return this.klarnaWindow.Klarna.Payments},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}}class Mh{constructor(e){this.requestSender=e}updateClientToken(e,{timeout:t,params:n}={}){const i=`/api/storefront/payments/${e}`;return this.requestSender.get(i,{timeout:t,headers:Object.assign({Accept:mr.JsonV1,"X-API-INTERNAL":hr},yr),params:n})}klarnaOrderInitialization(e,t){return n=this,i=void 0,o=function*(){const n={headers:Object.assign({Accept:mr.JsonV1,"X-API-INTERNAL":hr},yr),body:{cartId:e,clientToken:t}};yield this.requestSender.put("/api/storefront/initialization/klarna",n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const zh=vi(e=>{const{getHost:t}=e.getState(),i=n({host:t()});return new kh(e,new Dh(a()),new Mh(i))},[{gateway:"klarna"}]);class Nh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return n=this,i=void 0,o=function*(){return yield this._paymentIntegrationService.submitOrder(e,t),Promise.resolve()},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const xh=vi(e=>new Nh(e),[{id:"testgateway"}]);var Rh,Fh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.CREDIT_CARD="credit_card"}(Rh||(Rh={}));const Lh=["klarnapaylater","klarnasliceit"];class Bh{constructor(e,t){this.mollieScriptLoader=e,this.paymentIntegrationService=t}initialize(e){return Fh(this,void 0,void 0,function*(){const{mollie:t,methodId:n,gatewayId:i}=e;if(!t)throw new fi('Unable to initialize payment because "options.mollie" argument is not provided.');if(!n||!i)throw new fi('Unable to initialize payment because "methodId" and/or "gatewayId" argument is not provided.');const r=document.querySelectorAll(".mollie-components-controller");F(r,e=>e.remove());const o=this.paymentIntegrationService.getState(),a=o.getStoreConfigOrThrow();this.initializeOptions=t;const s=o.getPaymentMethodOrThrow(n,i),{config:{merchantId:d,testMode:c}}=s;if(this.locale=o.getLocale(),!d)throw new ti(Xn.MissingPaymentMethod);return this.isCreditCard(n)&&t.form&&this.shouldShowTSVHostedForm(n,i)?this.hostedForm=yield this.mountCardVerificationfields(t.form):this.isCreditCard(n)&&(this.mollieClient=yield this.loadMollieJs(d,a.storeProfile.storeLanguage,c),this.mountElements()),this.unsubscribe=()=>{if(this.paymentIntegrationService.getState().isPaymentMethodInitialized({methodId:e.methodId,gatewayId:e.gatewayId})){const e=document.getElementById(`${i}-${n}-paragraph`);e&&e.remove(),t.disableButton(!1),this.loadPaymentMethodsAllowed(t,n,i)}},this.unsubscribe(),this.loadPaymentMethodsAllowed(t,n,i),Promise.resolve()})}execute(e,t){return Fh(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rFh(this,void 0,void 0,function*(){try{const n=this.paymentIntegrationService.getState().getStoreConfig(),i=null==n?void 0:n.paymentSettings.bigpayBaseUrl;if(!i)throw new ti(Xn.MissingCheckoutConfig);const r=this.paymentIntegrationService.createHostedForm(i,e);yield r.attach(),t(r)}catch(e){n(e)}}))}isHostedPaymentFormEnabled(e,t){const{getPaymentMethodOrThrow:n}=this.paymentIntegrationService.getState();return!0===n(e,t).config.isHostedFormEnabled}isHostedFieldAvailable(){var e;return!!(null===(e=this.getInitializeOptions().form)||void 0===e?void 0:e.fields)}processAdditionalAction(e){if(!pa(e))return Promise.reject(e);if(ve(e.body.errors,{code:"additional_action_required"})){const{additional_action_required:{data:{redirect_url:t}}}=e.body;return new Promise(()=>window.location.replace(t))}return Promise.reject(e)}getInitializeOptions(){if(!this.initializeOptions)throw new ri(ei.PaymentNotInitialized);return this.initializeOptions}loadMollieJs(e,t,n=!1){return this.mollieClient?Promise.resolve(this.mollieClient):this.mollieScriptLoader.load(e,t,n)}getMollieClient(){if(!this.mollieClient)throw new ri(ei.PaymentNotInitialized);return this.mollieClient}getShopperLocale(){if(!this.locale)throw new ri(ei.PaymentNotInitialized);return this.locale}mountElements(){const{containerId:e,cardNumberId:t,cardCvcId:n,cardExpiryId:i,cardHolderId:r,styles:o}=this.getInitializeOptions();let a;e&&(a=document.getElementById(e)),setTimeout(()=>{if(!e||"none"!==(null==a?void 0:a.style.display)){const e=this.getMollieClient();this.cardHolderElement=e.createComponent("cardHolder",{styles:o}),this.cardHolderElement.mount(`#${r}`),this.cardNumberElement=e.createComponent("cardNumber",{styles:o}),this.cardNumberElement.mount(`#${t}`),this.verificationCodeElement=e.createComponent("verificationCode",{styles:o}),this.verificationCodeElement.mount(`#${n}`),this.expiryDateElement=e.createComponent("expiryDate",{styles:o}),this.expiryDateElement.mount(`#${i}`)}},0)}loadPaymentMethodsAllowed(e,t,n){var i;if(Lh.includes(t)){const r=null===(i=this.paymentIntegrationService.getState().getCartOrThrow().lineItems)||void 0===i?void 0:i.digitalItems;if(r&&r.length>0){const{containerId:i}=this.getInitializeOptions();if(i){const r=document.getElementById(i);if(r){const i=document.createElement("p");i.setAttribute("id",`${n}-${t}-paragraph`),e.unsupportedMethodMessage&&(i.innerText=e.unsupportedMethodMessage,r.appendChild(i),e.disableButton(!0))}}}}}}class jh{constructor(e,t=window){this.scriptLoader=e,this.mollieHostWindow=t}load(e,t,n){return i=this,r=void 0,a=function*(){if(yield this.scriptLoader.loadScript("https://js.mollie.com/v1/mollie.js"),!function(e){return"Mollie"in e}(this.mollieHostWindow))throw new mi;return this.mollieHostWindow.Mollie(e,{locale:t,testmode:n})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a}}const Uh=vi(e=>new Bh(new jh(a()),e),[{gateway:"mollie"},{gateway:"mollie",id:"applepay"}]);var qh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const Vh="moneris-payment-iframe";class Gh{constructor(e){this.paymentIntegrationService=e}initialize(e){return qh(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),{moneris:n,methodId:i}=e;if(!i)throw new fi('Unable to initialize payment because "methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.moneris" argument is not provided.');this.initializeOptions=n;const{config:r,initializationData:o}=t.getPaymentMethodOrThrow(i);if(!(null==o?void 0:o.profileId))throw new ti(Xn.MissingPaymentMethod);return n.form&&this.shouldShowTSVHostedForm(i)&&(this.hostedForm=yield this.mountCardVerificationfields(n.form)),this.iframe||(this.iframe=this.createIframe(n.containerId,o,!!r.testMode)),Promise.resolve()})}execute(e,t){return qh(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(!this.iframe)throw new ri(ei.PaymentNotInitialized);const i=this.iframe.contentWindow;if(null===i)throw new ri(ei.PaymentNotInitialized);i.postMessage("tokenize",this.monerisURL(!!t)),this.windowEventListener=i=>{if("string"==typeof i.data&&i.origin===`https://${t?"esqa":"www3"}.moneris.com`)try{e(this.handleMonerisResponse(i))}catch(e){n(e)}},window.addEventListener("message",this.windowEventListener)});void 0!==a&&(yield this.paymentIntegrationService.submitPayment({methodId:e.methodId,paymentData:{nonce:a,shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o}}))})}executeWithVaulted(e){return qh(this,void 0,void 0,function*(){if(this.hostedForm){const t=this.hostedForm;return yield t.validate(),yield t.submit(e),this.paymentIntegrationService.loadCurrentOrder()}return this.paymentIntegrationService.submitPayment(e)})}shouldShowTSVHostedForm(e){return this.isHostedPaymentFormEnabled(e)&&this.isHostedFieldAvailable()}isHostedPaymentFormEnabled(e){const t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e);return Boolean(t.config.isHostedFormEnabled)}isHostedFieldAvailable(){var e;const t=this.getInitializeOptions(),n=ue(null===(e=t.form)||void 0===e?void 0:e.fields,$);return!$(n)}getInitializeOptions(){if(!this.initializeOptions)throw new ri(ei.PaymentNotInitialized);return this.initializeOptions}mountCardVerificationfields(e){var t;return qh(this,void 0,void 0,function*(){const n=null===(t=this.paymentIntegrationService.getState().getStoreConfig())||void 0===t?void 0:t.paymentSettings.bigpayBaseUrl;if(!n)throw new ti(Xn.MissingCheckoutConfig);const i=this.paymentIntegrationService.createHostedForm(n,e);return yield i.attach(),i})}createIframe(e,t,n,i){const r=document.getElementById(e);if(!r)throw new fi("Unable to create iframe without valid container ID.");const o=document.createElement("iframe"),a={id:t.profileId,pmmsg:!0,display_labels:1,enable_exp:1,enable_cvd:1,css_body:(null==i?void 0:i.cssBody)||"font-family: Arial, Helvetica,sans-serif;background: transparent;",css_textbox:(null==i?void 0:i.cssTextbox)||"border-radius:4px;border: 2px solid rgb(00,00,00);width: 100%;font-weight: 600;padding: 8px 8px;outline: 0;",css_textbox_pan:(null==i?void 0:i.cssTextboxCardNumber)||"width: 240px;",css_textbox_exp:(null==i?void 0:i.cssTextboxExpiryDate)||"margin-bottom: 0;width: calc(30% - 12px);",css_textbox_cvd:(null==i?void 0:i.cssTextboxCVV)||"margin-bottom: 0;width: calc(30% - 12px);",css_input_label:(null==i?void 0:i.cssInputLabel)||"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;",pan_label:t.creditCardLabel||"Credit Card Number",exp_label:t.expiryDateLabel||"Expiration",cvd_label:t.cvdLabel||"CVD"},s=oe(a,(e,t)=>`${t}=${e}`).join("&");return o.width="100%",o.height="100%",o.name=Vh,o.id=Vh,o.style.border="none",o.src=`${this.monerisURL(n)}?${s}`,o.allow="payment",r.appendChild(o),o}handleMonerisResponse(e){const t=JSON.parse(e.data);if("001"!==t.responseCode[0])throw new Error(t.errorMessage);return t.dataKey}monerisURL(e){return`https://${e?"esqa":"www3"}.moneris.com/HPPtoken/index.php`}}const Hh=vi(e=>new Gh(e),[{id:"moneris"}]);class Wh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return n=this,i=void 0,o=function*(){return console.log("payload =======1",e),yield this._paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:e.payment?Object.assign({methodId:e.payment.methodId},"purchaseorder"===e.payment.methodId&&{paymentData:e.payment.paymentData}):void 0}),t),Promise.resolve()},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const $h=vi(e=>new Wh(e),[{type:"PAYMENT_TYPE_OFFLINE"}]);var Yh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Kh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return Yh(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew Kh(e),[{type:"PAYMENT_TYPE_HOSTED"}]),Zh=function({styles:e}){const t={};return e.color&&(t.color=e.color),e.layout&&(t.layout=e.layout),(e["logo-type"]||e["logo-position"])&&(t.logo={},e["logo-type"]&&(t.logo.type=e["logo-type"]),e["logo-position"]&&(t.logo.position=e["logo-position"])),e.ratio&&(t.ratio=e.ratio),(e["text-color"]||e["text-size"])&&(t.text={},e["text-color"]&&(t.text.color=e["text-color"]),e["text-size"]&&(t.text.size=+e["text-size"])),t};var Qh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Xh{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.payPalSdkScriptLoader=n,this.loadingIndicator=i}initialize(e){var t;return Qh(this,void 0,void 0,function*(){const{methodId:n,paypalcommerce:i}=e||{};if(this.paypalcommerce=i,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(n),{container:a,bannerContainerId:s}=i,{orderId:d,paypalBNPLConfiguration:c=[],isPayPalCreditAvailable:l}=o.initializationData||{};if(void 0!==s){if(!document.getElementById(s))return void console.error("Unable to create banner without valid banner container ID.");const e=null==c?void 0:c.find(({id:e})=>"checkout"===e);if(l||!(null==e?void 0:e.status))return;const t=yield this.payPalSdkScriptLoader.getPayPalMessages(o,r.getCartOrThrow().currency.code,r.getLocale());return t&&"function"==typeof(null==t?void 0:t.Messages)?this.renderMessages(t,s,e):void console.error("[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK")}d?this.orderId=null===(t=o.initializationData)||void 0===t?void 0:t.orderId:(this.loadingIndicatorContainer=null==a?void 0:a.split("#")[1],yield this.paypalIntegrationService.loadPayPalSdk(n),i.onInit&&"function"==typeof i.onInit&&i.onInit(()=>this.renderButton(n,i)),(void 0===i.shouldRenderPayPalButtonOnInitialization||i.shouldRenderPayPalButtonOnInitialization)&&this.renderButton(n,i))})}execute(e,t){var n,i;return Qh(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rwindow.location.replace(t))}return this.isProviderError(e)&&(yield this.paypalIntegrationService.loadPayPalSdk(r.methodId),yield new Promise((e,t)=>{var n;this.paypalcommerce&&(null===(n=this.paypalButton)||void 0===n||n.close(),this.renderButton(r.methodId,this.paypalcommerce),this.handleError(new Error("INSTRUMENT_DECLINED"),a)),t()})),this.handleError(e,a),Promise.reject()}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}prepareVaultedInstrumentPaymentPayload(e,t,n){const{instrumentId:i,shouldSetAsDefaultInstrument:r}=n,o=!this.isTrustedVaultingFlow(n);return o?{methodId:e,paymentData:{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}:{methodId:e,paymentData:{instrumentId:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t},bigpay_token:{token:i}}}}}preparePaymentPayload(e,t,n){const{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:r=!1}=jd(n)?n:{};return{methodId:e,paymentData:{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}}renderButton(e,t){var n,i,r,o;const a=this.paypalIntegrationService.getPayPalSdkOrThrow(),s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:d}=s.initializationData||{},{checkoutPaymentButtonStyles:c}=d||{},{container:l,onError:u,onRenderButton:h,onValidate:p,submitForm:m}=t;if(!l)throw new fi('Unable to initialize payment because "container" argument is not provided.');const y=this.getSmartButtonContainerId(l);if(!document.getElementById(y))throw new fi(`Unable to initialize payment because element with id ${y} does not exist.`);const g=Object.assign(Object.assign({},this.isPaypalCommerceAppSwitchEnabled(e)&&{appSwitchWhenAvailable:!0}),{fundingSource:a.FUNDING.PAYPAL,style:this.paypalIntegrationService.getValidButtonStyle(c),createOrder:()=>this.createOrder(),onClick:(e,t)=>this.handleClick(t,p),onApprove:e=>this.handleApprove(e,m),onError:e=>this.handleError(e,u),onCancel:()=>this.toggleLoadingIndicator(!1)});this.paypalButton=a.Buttons(g),this.paypalButton.isEligible()&&(h&&"function"==typeof h&&h(),(null===(i=(n=this.paypalButton).hasReturned)||void 0===i?void 0:i.call(n))&&this.isPaypalCommerceAppSwitchEnabled(e)?null===(o=(r=this.paypalButton).resume)||void 0===o||o.call(r):this.paypalButton.render(l))}handleClick(e,t){return Qh(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;return null==t?void 0:t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,null==t||t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createOrder(){return Qh(this,void 0,void 0,function*(){const e=this.getFieldsValues();return this.paypalIntegrationService.createOrder("paypalcommercecheckout",{shouldSaveInstrument:(null==e?void 0:e.shouldSaveInstrument)||!1})})}getFieldsValues(){const{getFieldsValues:e}=this.paypalcommerce||{};return"function"==typeof e?e():void 0}isTrustedVaultingFlow(e){if(e&&xd(e)){const t=this.paymentIntegrationService.getState().getInstruments(),n=null==t?void 0:t.find(t=>uc(t)&&t.bigpayToken===e.instrumentId);return!(uc(n)&&!n.trustedShippingAddress)}return!1}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isPayPalVaultedInstrumentPaymentData(e){return!!e&&xd(e)&&jd(e)}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:Zh(n)};e.Messages(i).render(`#${t}`)}isProviderError(e){var t,n,i;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"INSTRUMENT_DECLINED"===(null===(i=null===(n=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===n?void 0:n.provider_error)||void 0===i?void 0:i.code)}isPaypalCommerceAppSwitchEnabled(e){var t;return(null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)||!1}getSmartButtonContainerId(e){var t;return null!==(t=e.split("#")[1])&&void 0!==t?t:e}}const ep=vi(e=>new Xh(e,As(e),new Is(a()),new vd({containerStyles:Ka})),[{id:"paypalcommerce"}]);var tp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class np{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.loadingIndicator=n,this.payPalSdkScriptLoader=i}initialize(e){return tp(this,void 0,void 0,function*(){const{methodId:t,paypalcommerce:n,paypalcommercecredit:i}=e||{},r=i||n;if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const o=this.paymentIntegrationService.getState(),a=o.getPaymentMethodOrThrow(t),{paypalBNPLConfiguration:s=[],orderId:d}=a.initializationData||{},{bannerContainerId:c,container:l}=r;if(void 0!==c){if(!document.getElementById(c))return void console.error("Unable to create banner without valid banner container ID.");const e=s&&s.find(({id:e})=>"checkout"===e);if(!(null==e?void 0:e.status))return;const t=yield this.payPalSdkScriptLoader.getPayPalMessages(a,o.getCartOrThrow().currency.code,o.getLocale());return this.renderMessages(t,c,e)}d?this.orderId=d:(yield this.paypalIntegrationService.loadPayPalSdk(t),this.loadingIndicatorContainer=null==l?void 0:l.split("#")[1],this.renderButton(t,r))})}execute(e,t){return tp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(h)return;const t={fundingSource:e,style:this.paypalIntegrationService.getValidButtonStyle(o),createOrder:()=>this.paypalIntegrationService.createOrder("paypalcommercecreditcheckout"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=n.Buttons(t),this.paypalButton.isEligible()||e!==n.FUNDING.PAYLATER){if(!this.paypalButton.isEligible()&&e===n.FUNDING.CREDIT)throw new Si(`PayPal ${e} is not available for your region. Please use PayPal Checkout instead.`);d&&"function"==typeof d&&d(),this.paypalButton.render(a),h=!0}})}handleClick(e,t){return tp(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;if(t&&"function"==typeof t)return t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,t&&"function"==typeof t&&t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:Zh(n)};e.Messages(i).render(`#${t}`)}}const ip=vi(e=>new np(e,As(e),new vd({containerStyles:Ka}),Cs()),[{id:"paypalcommercecredit"}]);var rp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class op{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.loadingIndicator=n}initialize(e){var t,n;return rp(this,void 0,void 0,function*(){const{methodId:i,paypalcommerce:r,paypalcommercevenmo:o}=e||{},a=o||r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!a)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i);(null===(t=s.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(n=s.initializationData)||void 0===n?void 0:n.orderId:(yield this.paypalIntegrationService.loadPayPalSdk(i),this.loadingIndicatorContainer=a.container.split("#")[1],this.renderButton(i,a))})}execute(e,t){return rp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rthis.paypalIntegrationService.createOrder("paypalcommercevenmocheckout"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=n.Buttons(u),!this.paypalButton.isEligible())throw new Si("PayPal Venmo is not available for your region. Please use PayPal Checkout instead.");d&&"function"==typeof d&&d(),this.paypalButton.render(a)}handleClick(e,t){return rp(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;return t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,t(),this.toggleLoadingIndicator(!1)}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const ap=vi(e=>new op(e,As(e),new vd({styles:{backgroundColor:"black"}})),[{id:"paypalcommercevenmo"}]),sp={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"};var dp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class cp{constructor(e,t,n,i,r=3e3,o=3e5){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.paypalSdkScriptLoader=n,this.loadingIndicator=i,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.pollingTimer=0,this.stopPolling=ce,this.isOrderApprovedProcessing=!1}initialize(e){return dp(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,paypalcommerce:i,paypalcommercealternativemethods:r}=e,o=r||i;if(this.paypalcommercealternativemethods=r,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!o)throw new fi('Unable to initialize payment because "options.paypalcommercealternativemethods" argument is not provided.');const a=this.paymentIntegrationService.getState(),s=a.getPaymentMethodOrThrow(n,t),{orderId:d,shouldRenderFields:c}=s.initializationData||{},l=a.getStoreConfigOrThrow().checkoutSettings.features;this.isOrderApprovedProcessing=Ci(l,"PAYPAL-5431.order_approved_processing",!1),d?this.orderId=d:(this.paypalApms=yield this.paypalSdkScriptLoader.getPayPalApmsSdk(s,a.getCartOrThrow().currency.code,a.getLocale()),this.loadingIndicatorContainer=o.container.split("#")[1],this.renderButton(n,t,o),c&&this.renderFields(n,o))})}execute(e,t){return dp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.initializePollingMechanism(r,e,t,o)})),this.isNonInstantPaymentMethod(r)&&(r!==Bs.IDEAL||this.isOrderApprovedProcessing)||(yield this.paymentIntegrationService.submitOrder(i,t)),yield this.paypalCommerceIntegrationService.submitPayment(r,this.orderId,o)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,this.isOrderApprovedProcessing||this.resetPollingMechanism(),null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}initializePollingMechanism(e,t,n,i){return dp(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.paypalCommerceIntegrationService.getOrderStatus(null!=i?i:"paypalcommerce"),o=r===js.Approved,a=r===js.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimern.onInitButton(t),createOrder:()=>this.onCreateOrder(e,t,n),onApprove:e=>this.handleApprove(e,c),onCancel:()=>{this.toggleLoadingIndicator(!1),this.deinitializePollingMechanism()},onError:e=>{this.deinitializePollingMechanism(),this.handleFailure(e,s)},onClick:(e,t)=>dp(this,void 0,void 0,function*(){return n.onValidate(t.resolve,t.reject)})};this.paypalButton=i.Buttons(l),this.paypalButton.isEligible()&&(d&&"function"==typeof d&&d(),this.paypalButton.render(a))}onCreateOrder(e,t,n){var i;return dp(this,void 0,void 0,function*(){const{onValidate:r}=n;yield r(()=>(this.toggleLoadingIndicator(!0),()=>Promise.resolve()),ce);const o=yield this.paypalCommerceIntegrationService.createOrder("paypalcommercealternativemethodscheckout");if(this.isNonInstantPaymentMethod(e)&&(e===Bs.IDEAL&&this.isOrderApprovedProcessing||e===Bs.OXXO)){const n={useStoreCredit:!1},r={params:{methodId:e,gatewayId:t}};if(yield this.paymentIntegrationService.submitOrder(n,r),e===Bs.IDEAL){const t=this.paymentIntegrationService.getState(),n=null===(i=t.getOrder())||void 0===i?void 0:i.orderId;yield this.paypalCommerceIntegrationService.updateOrder("paypalcommercealternativemethods",e,n)}yield this.paypalCommerceIntegrationService.submitPayment(e,o,t)}return o})}handleApprove({orderID:e},t){this.orderId=e,t()}handleFailure(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderFields(e,t){const n=this.getPaypalAmpsSdkOrThrow(),i=this.paymentIntegrationService.getState(),{firstName:r,lastName:o,email:a}=i.getBillingAddressOrThrow(),{apmFieldsContainer:s,apmFieldsStyles:d}=t;if(!s)throw new fi('Unable to initialize payment because "options.paypalcommercealternativemethods" argument should contain "apmFieldsContainer".');const c=document.querySelector(s);c&&(c.innerHTML="");const l={fundingSource:e,style:d||{},fields:{name:{value:`${r} ${o}`},email:{value:a}}};n.PaymentFields(l).render(s)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isNonInstantPaymentMethod(e){return e.toUpperCase()in Bs}getPaypalAmpsSdkOrThrow(){if(!this.paypalApms)throw new mi;return this.paypalApms}}const lp=vi(e=>new cp(e,As(e),Cs(),new vd({containerStyles:sp})),[{gateway:"paypalcommercealternativemethods"}]);var up=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class hp{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.paypalSdkScriptLoader=n,this.paypalFastlaneUtils=i}initialize(e){return up(this,void 0,void 0,function*(){const{methodId:t,paypalcommercecreditcards:n,paypalcommerce:i}=e,r=n||i,{form:o,onCreditCardFieldsRenderingError:a,onLoadComplete:s}=r||{};if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)throw new fi('Unable to proceed because "options.paypalcommercecreditcards.form" argument is not provided.');this.hostedFormOptions=o,this.isCreditCardForm=Ac(o.fields),this.isCreditCardVaultedForm=Tc(o.fields)&&!this.hasUndefinedValues(),yield this.paymentIntegrationService.loadPaymentMethod(t),yield this.paypalIntegrationService.loadPayPalSdk(t,void 0,!0,!0),(this.isCreditCardForm||this.isCreditCardVaultedForm)&&(yield this.initializeFields(o,a)),null==s||s(),this.shouldInitializePayPalFastlane(t)&&(yield this.initializePayPalFastlaneOrThrow(t))})}execute(e,t){return up(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(n===Ns.No||n===Ns.Unknown)throw new Error;return this.handleApprove({orderID:e,vaultSetupToken:t})},onError:()=>{throw new Qr},inputEvents:{onChange:t=>this.onChangeHandler(e,t),onFocus:t=>this.onFocusHandler(e,t),onBlur:t=>this.onBlurHandler(e,t),onInputSubmitRequest:t=>this.onInputSubmitRequest(e,t)}},o);if(this.cardFields=yield r.CardFields(a),!this.cardFields.isEligible())throw new ri(ei.PaymentNotInitialized);try{this.stylizeInputContainers(n),Ac(n)&&(yield this.renderFields(n)),Tc(n)&&(yield this.renderVaultedFields(n))}catch(e){"function"==typeof t&&t(e)}})}getExecuteCallback(e){return Tc(e)?this.createVaultSetupTokenCallback():this.createOrderCallback()}createVaultSetupTokenCallback(){return{createVaultSetupToken:()=>up(this,void 0,void 0,function*(){const{setupToken:e}=(yield this.paypalIntegrationService.createOrderCardFields("paypalcommercecreditcardscheckout",Object.assign(Object.assign({},this.getInstrumentParams()),{setupToken:!0})))||{};return e})}}createOrderCallback(){return{createOrder:()=>up(this,void 0,void 0,function*(){const{orderId:e}=(yield this.paypalIntegrationService.createOrderCardFields("paypalcommercecreditcardscheckout",this.getInstrumentParams()))||{};return e})}}handleApprove({orderID:e,vaultSetupToken:t}){e&&(this.returnedOrderId=e),t&&(this.returnedVaultedToken=t)}renderFields(e){var t,n,i,r;return up(this,void 0,void 0,function*(){const o=this.getCardFieldsOrThrow();(null===(t=e.cardCode)||void 0===t?void 0:t.containerId)&&(this.cvvField=o.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCode.containerId}`)),(null===(n=e.cardExpiry)||void 0===n?void 0:n.containerId)&&(this.expiryField=o.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiry.containerId}`)),(null===(i=e.cardName)||void 0===i?void 0:i.containerId)&&(this.nameField=o.NameField({placeholder:""}),yield this.nameField.render(`#${e.cardName.containerId}`)),(null===(r=e.cardNumber)||void 0===r?void 0:r.containerId)&&(this.numberField=o.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumber.containerId}`))})}renderVaultedFields(e){var t,n,i;return up(this,void 0,void 0,function*(){const r=this.getCardFieldsOrThrow();(null===(t=e.cardCodeVerification)||void 0===t?void 0:t.containerId)&&(this.cvvField=r.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCodeVerification.containerId}`)),(null===(n=e.cardExpiryVerification)||void 0===n?void 0:n.containerId)&&(this.expiryField=r.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiryVerification.containerId}`)),(null===(i=e.cardNumberVerification)||void 0===i?void 0:i.containerId)&&(this.numberField=r.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumberVerification.containerId}`))})}getInstrumentParams(){if(!this.executionPaymentData)return{};if(jd(this.executionPaymentData)){const{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}=this.executionPaymentData;return{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}}if(xd(this.executionPaymentData)){const{instrumentId:e}=this.executionPaymentData;return{instrumentId:e}}return{}}getFieldTypeByEmittedField({emittedBy:e}){return{fieldType:this.mapFieldType(e)}}submitHostedForm(){return up(this,void 0,void 0,function*(){const e=this.getCardFieldsOrThrow(),t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),n={billingAddress:{company:t.company,addressLine1:t.address1,addressLine2:t.address2,adminArea1:t.stateOrProvinceCode,adminArea2:t.city,postalCode:t.postalCode,countryCode:t.countryCode}};try{this.isCreditCardVaultedForm?yield e.submit():yield e.submit(n)}catch(e){throw new Qr("Failed authentication. Please try to authorize again.")}})}validateHostedFormOrThrow(){var e,t;return up(this,void 0,void 0,function*(){const n=this.getCardFieldsOrThrow(),i=yield n.getState().then(e=>e),r=this.getValidityData(i);if(!r.isValid)throw null===(t=null===(e=this.hostedFormOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,r),new lo(this.mapValidationErrors(r.errors))})}getValidityData({fields:e}){const t=Object.assign({},e);delete t.cardNameField;const n=Object.keys(t);return{isValid:n.every(e=>{var n;return null===(n=t[e])||void 0===n?void 0:n.isValid}),errors:n.reduce((e,n)=>{var i;const r=this.mapFieldType(n);return Object.assign(Object.assign({},e),{[r]:(null===(i=t[n])||void 0===i?void 0:i.isValid)?void 0:[this.getInvalidErrorByFieldType(r)]})},{})}}getInvalidErrorByFieldType(e){switch(e){case Ec.CardCode:case Ec.CardCodeVerification:return{fieldType:e,message:"Invalid card code",type:"invalid_card_code"};case Ec.CardNumber:case Ec.CardNumberVerification:return{fieldType:e,message:"Invalid card number",type:"invalid_card_number"};case Ec.CardExpiry:case Ec.CardExpiryVerification:return{fieldType:e,message:"Invalid card expiry",type:"invalid_card_expiry"};default:return{fieldType:e,message:"Invalid field",type:"invalid"}}}mapValidationErrors(e={}){const t={};return Object.keys(e).forEach(n=>{var i,r;t[n]=[{message:(null===(r=null===(i=e[n])||void 0===i?void 0:i[0])||void 0===r?void 0:r.message)||"",type:n}]}),t}mapFieldType(e){switch(e){case"name":return Ec.CardName;case"cardNumberField":case"number":return this.isCreditCardForm?Ec.CardNumber:Ec.CardNumberVerification;case"cardExpiryField":case"expiry":return this.isCreditCardForm?Ec.CardExpiry:Ec.CardExpiryVerification;case"cardCvvField":case"cvv":return this.isCreditCardForm?Ec.CardCode:Ec.CardCodeVerification;default:throw new Error("Unexpected field type")}}getCardFieldsOrThrow(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);return this.cardFields}getInputStyles(e){var t,n,i;const r={"font-size":(null===(t=null==e?void 0:e.default)||void 0===t?void 0:t.fontSize)||"1rem","font-family":(null===(n=null==e?void 0:e.default)||void 0===n?void 0:n.fontFamily)||"Montserrat, Arial, Helvetica, sans-serif","font-weight":(null===(i=null==e?void 0:e.default)||void 0===i?void 0:i.fontWeight)||"400",outline:"none",padding:"9px 13px"},o=Object.assign(Object.assign({},r),{color:"#333333"});return{input:o,".invalid":Object.assign(Object.assign({},r),{color:"red"}),".valid":o,":focus":o}}stylizeInputContainers(e){Object.values(e||{}).forEach(e=>{const t=document.getElementById(`${(null==e?void 0:e.containerId)||""}`);t&&(t.style.padding="0px",t.style.boxShadow="none",t.style.border="none",t.style.background="transparent",t.style.marginBottom="10px",t.style.marginLeft="-5px")})}hasUndefinedValues(){return!this.hostedFormOptions||Object.values(this.hostedFormOptions.fields).some(e=>void 0===e)}onChangeHandler(e,t){var n;null===(n=null==e?void 0:e.onValidate)||void 0===n||n.call(e,this.getValidityData(t))}onFocusHandler(e,t){var n;null===(n=null==e?void 0:e.onFocus)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onBlurHandler(e,t){var n;null===(n=null==e?void 0:e.onBlur)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onInputSubmitRequest(e,t){var n;null===(n=null==e?void 0:e.onEnter)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}shouldInitializePayPalFastlane(e){var t,n;const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(e),o=i.getPaymentProviderCustomer(),a=(s=o)&&("authenticationState"in s||"addresses"in s||"instruments"in s)?o:{};var s;return(null===(t=null==r?void 0:r.initializationData)||void 0===t?void 0:t.isAcceleratedCheckoutEnabled)&&(null===(n=null==r?void 0:r.initializationData)||void 0===n?void 0:n.isPayPalCommerceAnalyticsV2Enabled)&&!(null==a?void 0:a.authenticationState)}initializePayPalFastlaneOrThrow(e){return up(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getPaymentMethodOrThrow(e),{initializationData:r}=i;if(!(null==r?void 0:r.connectClientToken))return;const o=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(i,n.currency.code,n.id,t.getLocale());yield this.paypalFastlaneUtils.initializePayPalFastlane(o,!!(null==r?void 0:r.isDeveloperModeApplicable))}catch(e){}})}}const pp=vi(e=>new hp(e,As(e),Cs(),nd()),[{id:"paypalcommercecreditcards"}]);var mp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class yp{constructor(e,t,n,i=3e3,r=3e5){this.paymentIntegrationService=e,this.paypalCommerceService=t,this.loadingIndicator=n,this.pollingInterval=i,this.maxPollingIntervalTime=r,this.pollingTimer=0,this.stopPolling=ce}initialize(e){return mp(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,paypalcommerceratepay:i}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.paypalcommerceratepay" argument is not provided.');const{legalTextContainer:r,container:o,loadingContainerId:a}=i;if(!o)throw new fi('Unable to initialize payment because "options.container" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.legalTextContainer" argument is not provided.');if(!a)throw new fi('Unable to initialize payment because "options.loadingContainerId" argument is not provided.');this.loadingIndicatorContainer=a;const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t),{merchantId:d}=s.initializationData||{};if(!d)throw new fi("Unable to initialize payment because merchantId argument is not provided.");this.paypalcommerceratepay=i,yield this.paypalCommerceService.loadPayPalSdk(n),this.createFraudNetScript(d,n,t),this.loadFraudnetConfig(),this.renderLegalText(r,o)})}execute(e,t){return mp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.initializePollingMechanism(n.methodId,e,t,n.gatewayId)})}catch(e){return this.handleError(e),new Promise((e,t)=>t())}})}finalize(){return Promise.reject(new Cd)}deinitialize(){const{legalTextContainer:e}=this.paypalcommerceratepay||{},t=document.querySelectorAll('[data-id="fraudnetScript"]')[0],n=document.querySelectorAll('[data-id="fraudnetConfig"]')[0];if(this.deinitializePollingMechanism(),t.remove(),n.remove(),e){const t=document.getElementById(e);null==t||t.remove()}return Promise.resolve()}normalizeDate(e){const t=this.formatDate(e.getDate()),n=this.formatDate(e.getMonth()+1);return`${e.getFullYear()}-${n}-${t}`}formatDate(e){return`${e<10?0:""}${e}`}renderLegalText(e,t){const n=e,i=t.split("#")[1],r=document.getElementById(i),o=null==r?void 0:r.parentNode,a=document.createElement("div");a.style.marginBottom="20px",a.setAttribute("id",n),null==o||o.prepend(a);const s=this.paypalCommerceService.getPayPalSdkOrThrow(),d=s.Legal({fundingSource:s.Legal.FUNDING.PAY_UPON_INVOICE});if(!document.getElementById(n))throw new fi('Unable to initialize payment because "legalTextContainerElement" argument is not found.');d.render(`#${n}`)}handleError(e){const{onError:t}=this.paypalcommerceratepay||{};this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createFraudNetScript(e,t,n){const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{testMode:r}=i.config,o=document.createElement("script");o.setAttribute("type","application/json"),o.setAttribute("fncls","fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99"),o.setAttribute("data-id","fraudnetScript"),this.guid=this.generateGUID();const a={f:this.guid,s:`${e}_checkout-page`,sandbox:r};o.innerHTML=JSON.stringify(a),document.body.appendChild(o)}generateGUID(){let e="";for(let t=0;t<32;t+=1)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(62*Math.random())];return e}loadFraudnetConfig(){const e=document.createElement("script");e.setAttribute("data-id","fraudnetConfig"),e.src="https://c.paypal.com/da/r/fb.js",document.body.appendChild(e)}reinitializeStrategy(e){return mp(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}initializePollingMechanism(e,t,n,i){return mp(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.paypalCommerceService.getOrderStatus("paypalcommercealternativemethods",{params:{useMetadata:!0}}),o=r===_s.PollingStop,a=r===_s.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimernew yp(e,As(e),new vd({containerStyles:Object.assign(Object.assign({},Ka),{position:"fixed"})})),[{gateway:"paypalcommercealternativemethods",id:"ratepay"}]);function vp(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var fp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Sp{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalCommerceRequestSender=t,this.paypalSdkScriptLoader=n,this.paypalFastlaneUtils=i}initialize(e){var t,n;return fp(this,void 0,void 0,function*(){const{methodId:i,paypalcommercefastlane:r}=e;if(this.methodId=i,this.paypalcommercefastlane=r,!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.paypalcommercefastlane" argument is not provided.');if(!r.onInit||"function"!=typeof r.onInit)throw new fi('Unable to initialize payment because "options.paypalcommercefastlane.onInit" argument is not provided or it is not a function.');if(!r.onChange||"function"!=typeof r.onChange)throw new fi('Unable to initialize payment because "options.paypalcommercefastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState(),a=o.getCartOrThrow(),s=o.getPaymentMethodOrThrow(i),{isDeveloperModeApplicable:d,isFastlaneStylingEnabled:c}=s.initializationData||{};this.threeDSVerificationMethod=null===(t=s.initializationData)||void 0===t?void 0:t.threeDSVerificationMethod,this.paypalFastlaneSdk=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(s,a.currency.code,a.id,o.getLocale());const l=rd(c?null===(n=null==s?void 0:s.initializationData)||void 0===n?void 0:n.fastlaneStyles:{},null==r?void 0:r.styles);yield this.paypalFastlaneUtils.initializePayPalFastlane(this.paypalFastlaneSdk,!!d,l),this.shouldRunAuthenticationFlow()&&(yield this.runPayPalAuthenticationFlowOrThrow(i)),yield this.initializePayPalPaymentComponent(),r.onInit(e=>this.renderPayPalPaymentComponent(e)),r.onChange(()=>this.handlePayPalStoredInstrumentChange(i))})}execute(e,t){return fp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const{getHost:t}=e.getState();return new Sp(e,new Gs(n({host:t()})),Cs(),nd())},[{id:"paypalcommerceacceleratedcheckout"}]);var wp,Ip,Cp,bp,Pp,Op;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(wp||(wp={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(Ip||(Ip={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black"}(Cp||(Cp={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(bp||(bp={})),function(e){e.PILL="pill",e.RECT="rect"}(Pp||(Pp={})),function(e){e.ACKNOWLEDGE="ACKNOWLEDGE",e.FINALIZE="FINALIZE",e.INITIALIZE="INITIALIZE"}(Op||(Op={}));var Ep=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ap{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t,this.useRedirectFlow=!1,this.window=window}initialize(e){return Ep(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState();this.paymentMethod=t.getPaymentMethodOrThrow(e.methodId),this.useRedirectFlow=!0===(e.paypalexpress&&e.paypalexpress.useRedirectFlow);const n=this.paymentMethod.config.merchantId;if(!this.isInContextEnabled()||!n)throw new ti(Xn.MissingPaymentMethod);const i=yield this.scriptLoader.loadPaypalSDK();this.paypalSdk=i,this.paypalSdk.checkout.setup(n,{button:"paypal-button",environment:this.paymentMethod.config.testMode?"sandbox":"production"})})}deinitialize(){return this.isInContextEnabled()&&this.paypalSdk&&(this.paypalSdk.checkout.closeFlow(),this.paypalSdk=void 0),Promise.resolve()}execute(e,t){return Ep(this,void 0,void 0,function*(){let n,i;const r=this.paypalSdk;if(!this.isAcknowledgedOrFinalized()){if(!this.isInContextEnabled()||this.useRedirectFlow)return n=yield this.paymentIntegrationService.submitOrder(e,t),i=n.getPaymentRedirectUrl(),i&&this.window.top&&(this.window.top.location.href=i),new Promise(ce);if(!r)throw new ri(ei.PaymentNotInitialized);r.checkout.initXO();try{n=yield this.paymentIntegrationService.submitOrder(e,t)}catch(e){return r.checkout.closeFlow(),Promise.reject(e)}return i=n.getPaymentRedirectUrl(),i&&r.checkout.startFlow(i),new Promise(ce)}yield this.paymentIntegrationService.submitOrder(e,t)})}finalize(e){return Ep(this,void 0,void 0,function*(){return this.paymentIntegrationService.getState().getOrder()&&this.isAcknowledgedOrFinalized()?(yield this.paymentIntegrationService.finalizeOrder(e),Promise.resolve()):Promise.reject(new Cd)})}isAcknowledgedOrFinalized(){const e=this.paymentIntegrationService.getState();return e.getPaymentStatus()===Op.ACKNOWLEDGE||e.getPaymentStatus()===Op.FINALIZE}isInContextEnabled(){return!(!this.paymentMethod||!this.paymentMethod.config.merchantId)}}class Tp{constructor(e){this.scriptLoader=e,this.window=window}loadPaypalSDK(e=""){return t=this,n=void 0,r=function*(){const t=Object.assign({async:!0,attributes:{"data-merchant-id":e}},e&&{attributes:{"data-merchant-id":e}});if(yield this.scriptLoader.loadScript("//www.paypalobjects.com/api/checkout.min.js",t),!this.window.paypal)throw new mi;return this.window.paypal},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const kp=vi(e=>new Ap(e,new Tp(a())),[{id:"paypalexpress",type:"PAYMENT_TYPE_HOSTED"},{id:"paypalexpresscredit",type:"PAYMENT_TYPE_HOSTED"}]);var Dp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Mp extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this.threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Dp(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);n.config.is3dsEnabled&&(yield this.threeDSecureFlow.prepare(n))})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return Dp(this,void 0,void 0,function*(){const{payment:{methodId:i=""}={}}=e,r=this.paymentIntegrationService.getState();return r.getPaymentStatus()===dl.ACKNOWLEDGE?(yield this.paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:{methodId:i}}),t),Promise.resolve()):r.getPaymentMethodOrThrow(i).config.is3dsEnabled?this.threeDSecureFlow.start(n.execute.bind(this),e,t,this._hostedForm):n.execute.call(this,e,t)})}}const zp=vi(e=>new Mp(e,new Au(e,new Fu(new Lu(a())))),[{id:"paypal"}]);class Np extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this._formPoster=t}execute(e,t){const{payment:n}=e;if(!n)throw new ri(ei.PaymentNotInitialized);const{paymentData:i}=n;if(!i)throw new ti(Xn.MissingPayment);if(this._isThreeDSTwoExperimentOn()){const t=Object.assign(Object.assign({},i),{browser_info:ss()});e.payment&&(e.payment.paymentData=t)}return super.execute(e,t).catch(e=>pa(e)&&ve(e.body.errors,{code:"three_d_secure_required"})?new Promise(()=>{let t;t=this._isThreeDSTwoExperimentOn()&&!e.body.three_ds_result.merchant_data?{creq:e.body.three_ds_result.payer_auth_request}:{PaReq:e.body.three_ds_result.payer_auth_request,TermUrl:e.body.three_ds_result.callback_url,MD:e.body.three_ds_result.merchant_data},this._formPoster.postForm(e.body.three_ds_result.acs_url,t,void 0,"_top")}):Promise.reject(e))}finalize(e){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),super.finalize()}_isThreeDSTwoExperimentOn(){return!0===this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features["INT-4994.Opayo_3DS2"]}}const xp=vi(e=>new Np(e,Ee()),[{id:"sagepay"}]);class Rp{constructor(e,t){this._formPoster=e,this._paymentIntegrationService=t}execute(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.redirectUrl(t)})}var o},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}redirectUrl(e){return this._formPoster.postForm(e,{})}_isAdditionalActionRequired(e){const{additional_action_required:t,status:n}=e;return"additional_action_required"===n&&t&&"offsite_redirect"===t.type}}class Fp extends Rp{redirectUrl(e){window.location.replace(e)}}const Lp=vi(e=>new Fp(Ee(),e),[{id:"sezzle"}]);var Bp;!function(e){e.CHARGE="CHARGE",e.STORE="STORE"}(Bp||(Bp={}));var jp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Up{constructor(e,t){this._scriptLoader=e,this._paymentIntegrationService=t}initialize({testMode:e,applicationId:t,locationId:n}){return jp(this,void 0,void 0,function*(){const i=yield this._scriptLoader.load(e);this._payments=i.payments(t,n)})}deinitialize(){return jp(this,void 0,void 0,function*(){this._formValidationSubscription&&this._formValidationSubscription.unsubscribe(),this._card&&(yield this._card.destroy()),this._formValidationSubscription=void 0,this._card=void 0,this._payments=void 0})}initializeCard({containerId:e,style:t,onValidationChange:n}){return jp(this,void 0,void 0,function*(){const{postalCode:i}=this._paymentIntegrationService.getState().getBillingAddress()||{};this._card=yield this._getPayments().card(),yield this._card.attach(`#${e}`);try{yield this._card.configure({postalCode:i,style:t})}catch(e){}n&&(this._formValidationSubscription=this._subscribeToFormValidation(this._card,n))})}tokenize(){return jp(this,void 0,void 0,function*(){const e=yield this._getCard().tokenize();if("OK"!==e.status||!e.token){let t=`Tokenization failed with status: ${e.status}`;throw"errors"in e&&e.errors&&(t+=` and errors: ${JSON.stringify(e.errors)}`),new _h("payment.errors.card_error","SquareV2TokenizationError",t)}return e.token})}verifyBuyer(e,t){return jp(this,void 0,void 0,function*(){return t===Bp.CHARGE?this._chargeVerifyBuyer(e):this._storeVerifyBuyer(e)})}_getPayments(){return ii(this._payments,()=>new ri(ei.PaymentNotInitialized))}_subscribeToFormValidation(e,t){const n=["cardNumber","cvv"],i=new Set(n),r=["focusClassAdded","focusClassRemoved","errorClassAdded","errorClassRemoved","cardBrandChanged","postalCodeChanged"].map(t=>_(e,t));return w(...r).pipe(T(e=>{const{detail:{field:t,currentState:{isCompletelyValid:r}}}=e;return n.includes(t)&&i[r?"delete":"add"](t),0===i.size}),E()).subscribe(t)}_getCard(){return ii(this._card,()=>new ri(ei.PaymentNotInitialized))}_mapToSquareBillingContact({firstName:e,lastName:t,address1:n,address2:i,city:r,stateOrProvinceCode:o,postalCode:a,countryCode:s,email:d,phone:c}){return{givenName:e,familyName:t,addressLines:[n,i],city:r,state:o,postalCode:a,countryCode:s,email:d,phone:c}}_chargeVerifyBuyer(e){return jp(this,void 0,void 0,function*(){const{getCheckoutOrThrow:t,getBillingAddressOrThrow:n}=this._paymentIntegrationService.getState(),{outstandingBalance:i,cart:r}=t(),o={amount:i.toString(),billingContact:this._mapToSquareBillingContact(n()),currencyCode:r.currency.code,intent:Bp.CHARGE},a=yield this._getPayments().verifyBuyer(e,o);return a?a.token:""})}_storeVerifyBuyer(e){return jp(this,void 0,void 0,function*(){const{getBillingAddressOrThrow:t}=this._paymentIntegrationService.getState(),n={billingContact:this._mapToSquareBillingContact(t()),intent:Bp.STORE},i=yield this._getPayments().verifyBuyer(e,n);return i?i.token:""})}}var qp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vp{constructor(e,t){this._paymentIntegrationService=e,this._squareV2PaymentProcessor=t}initialize(e){var t;return qp(this,void 0,void 0,function*(){if(!(null===(t=null==e?void 0:e.squarev2)||void 0===t?void 0:t.containerId))throw new fi('Unable to proceed because "containerId" argument is not provided.');const{methodId:n,squarev2:i}=e,{config:{testMode:r},initializationData:o}=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(n),{applicationId:a,locationId:s}=o||{};if(!a)throw new Xr;yield this._squareV2PaymentProcessor.initialize({applicationId:a,locationId:s,testMode:r}),yield this._squareV2PaymentProcessor.initializeCard(i)})}execute({payment:e}){return qp(this,void 0,void 0,function*(){if(!e)throw new co(["payment"]);const{methodId:t,paymentData:n}=e,{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r}=jd(n)?n:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1};yield this._paymentIntegrationService.submitOrder();const o=n&&xd(n)?yield this._getVaultedInstrumentPayload(t,n):yield this._getCardPayload(t,i);yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:{formattedPayload:Object.assign(Object.assign({},o),{vault_payment_instrument:i||!1,set_as_default_stored_instrument:r||!1})}}))})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this._squareV2PaymentProcessor.deinitialize()}shouldVerify(){const{features:e}=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings;return e["PROJECT-3828.add_3ds_support_on_squarev2"]}_getCardPayload(e,t){return qp(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),{initializationData:i}=n(e),r=yield this._squareV2PaymentProcessor.tokenize();if(i&&"isSquareV2ApiV2Enabled"in i?!i.isSquareV2ApiV2Enabled:!this.shouldVerify())return{credit_card_token:{token:r}};let o={nonce:r,token:yield this._squareV2PaymentProcessor.verifyBuyer(r,Bp.CHARGE)};if(t){const e=yield this._squareV2PaymentProcessor.tokenize();o=Object.assign(Object.assign({},o),{store_card_nonce:e,store_card_token:yield this._squareV2PaymentProcessor.verifyBuyer(e,Bp.STORE)})}return{credit_card_token:{token:JSON.stringify(o)}}})}_getVaultedInstrumentPayload(e,t){return qp(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),{initializationData:i}=n(e),{instrumentId:r}=t,o=(i&&"isSquareV2ApiV2Enabled"in i?i.isSquareV2ApiV2Enabled:this.shouldVerify())?yield this._squareV2PaymentProcessor.verifyBuyer(yield this._getSquareCardIdOrThrow(e,r),Bp.CHARGE):void 0;return{bigpay_token:Object.assign({token:r},o&&{three_d_secure:{token:o}})}})}_getSquareCardIdOrThrow(e,t){return qp(this,void 0,void 0,function*(){const n=yield this._paymentIntegrationService.loadPaymentMethod(e,{params:{method:e,bigpayToken:t}}),{initializationData:i}=n.getPaymentMethodOrThrow(e),{cardId:r}=i||{};if(!r)throw new co(["cardId"]);return r})}}var Gp;!function(e){e.LIVE="https://web.squarecdn.com/v1/square.js",e.SANDBOX="https://sandbox.web.squarecdn.com/v1/square.js"}(Gp||(Gp={}));class Hp{constructor(e){this._scriptLoader=e}load(e=!1){return t=this,n=void 0,r=function*(){return yield this._scriptLoader.loadScript(e?Gp.SANDBOX:Gp.LIVE),function(e){if(!function(e){return"Square"in e}(e))throw new mi}(window),window.Square},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const Wp=vi(e=>new Vp(e,new Up(new Hp(a()),e)),[{id:"squarev2"}]);function $p(e){return null!==e&&"object"==typeof e&&"cardNumberElementOptions"in e&&"cardCvcElementOptions"in e&&"cardExpiryElementOptions"in e&&void 0!==e.cardNumberElementOptions&&void 0!==e.cardCvcElementOptions&&void 0!==e.cardExpiryElementOptions}var Yp,Kp,Jp,Zp;!function(e){e.Solid="solid",e.Default="default"}(Yp||(Yp={})),function(e){e.Alipay="alipay",e.CardCvc="cardCvc",e.CardExpiry="cardExpiry",e.CardNumber="cardNumber",e.CreditCard="card",e.IDEAL="idealBank",e.Sepa="iban"}(Kp||(Kp={})),function(e){e.Alipay="alipay",e.CreditCard="card",e.IDEAL="ideal",e.Sepa="sepa_debit"}(Jp||(Jp={})),function(e){e.AuthFailure="auth_failure"}(Zp||(Zp={}));class Qp extends Qn{constructor(e){super(e===Zp.AuthFailure?"User did not authenticate":"There was an error while processing your payment. Please try again or contact us."),this.type="stripev3_error",this.subtype=e}}var Xp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const em=[Kp.Alipay,Kp.IDEAL];class tm{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){return Xp(this,void 0,void 0,function*(){const{stripev3:t,methodId:n,gatewayId:i}=e;if(!i)throw new fi('Unable to initialize payment because "gatewayId" argument is not provided.');this.initializeOptions=t,this.isDeinitialize=!1;const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n),{initializationData:{stripePublishableKey:o,stripeConnectedAccount:a,useIndividualCardFields:s,allowRedisplayForStoredInstruments:d}}=r;this._allowRedisplayForStoredInstruments=d;const c=this.getInitializeOptions().form;this.useIndividualCardFields=s,this.stripeV3Client=yield this.loadStripeJs(o,a),this.isCreditCard(n)&&this.shouldShowTSVHostedForm(n,i)&&c?this.hostedForm=yield this.mountCardVerificationFields(c):this.stripeElement=yield this.mountCardFields(n)})}execute(e,t){var n,i;return Xp(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{switch(this.stripeElements||(this.stripeElements=this.getStripeJs().elements()),e){case Kp.CreditCard:if(this.useIndividualCardFields&&$p(t)){const{cardNumberElementOptions:e,cardExpiryElementOptions:n,cardCvcElementOptions:r}=t,a=this.stripeElements.getElement(Kp.CardNumber)||this.stripeElements.create(Kp.CardNumber,e),s=this.stripeElements.getElement(Kp.CardExpiry)||this.stripeElements.create(Kp.CardExpiry,n),d=this.stripeElements.getElement(Kp.CardCvc)||this.stripeElements.create(Kp.CardCvc,r);this.stripeCardElements=[a,s,d],i=this.stripeCardElements[0];try{a.mount(`#${e.containerId}`),s.mount(`#${n.containerId}`),d.mount(`#${r.containerId}`)}catch(e){this.isDeinitialize||o(new fi("Unable to mount Stripe component without valid container ID."))}}else{i=this.stripeElements.getElement(e)||this.stripeElements.create(e,t);try{i.mount(`#${n}`)}catch(e){this.isDeinitialize||o(new fi("Unable to mount Stripe component without valid container ID."))}}break;case Kp.IDEAL:case Kp.Sepa:i=this.stripeElements.getElement(e)||this.stripeElements.create(e,t);try{i.mount(`#${n}`)}catch(e){this.isDeinitialize||o(new fi("Unable to mount Stripe component without valid container ID."))}case Kp.Alipay:}r(i)})}mountCardVerificationFields(e){return Xp(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getStoreConfig();if(!t)throw new ti(Xn.MissingCheckoutConfig);const n=t.paymentSettings.bigpayBaseUrl,i=this.paymentIntegrationService.createHostedForm(n,e);return yield i.attach(),i})}processAdditionalAction(e,t,n=!1,i=!1){return Xp(this,void 0,void 0,function*(){if(!pa(e))throw e;const r=ve(e.body.errors,{code:"additional_action_required"}),o=ve(e.body.errors,{code:"three_d_secure_required"});if(r){const t=e.body.additional_action_required;if(t&&"redirect_to_url"===t.type)return new Promise(()=>{t.data.redirect_url&&window.location.replace(t.data.redirect_url)})}if(o){const r=e.body.three_ds_result.token,o=!1;let a,s=!1;try{a=yield this.getStripeJs().confirmCardPayment(r)}catch(e){s=!0}if(null==a?void 0:a.error){if(this.isCancellationError(a.error))throw new Wi;if(this.isAuthError(a.error))throw new Qp(Zp.AuthFailure);throw new Error(a.error.message)}const d={credit_card_token:{token:this.getPaymentToken(null==a?void 0:a.paymentIntent,r,s)},vault_payment_instrument:n,confirm:o},c=this.buildPaymentPayload(t,d,i);try{return yield this.paymentIntegrationService.submitPayment(c)}catch(e){throw this.handleEmptyPaymentIntentError(e,null==a?void 0:a.error)}}throw e})}getPaymentToken(e,t,n){return!e||n?t:e.id}shouldShowTSVHostedForm(e,t){return this.isHostedFieldAvailable()&&this.isHostedPaymentFormEnabled(e,t)}unmountElement(){this.stripeElement&&(this.stripeElement.unmount(),this.stripeElement=void 0)}}class nm{constructor(e,t=window){this.scriptLoader=e,this.stripeWindow=t}load(e,t,n){return this.scriptLoader.loadScript("https://js.stripe.com/v3/").then(()=>{if(!this.stripeWindow.Stripe)throw new mi;return this.stripeWindow.Stripe(e,{stripeAccount:t,locale:n,betas:["payment_intent_beta_3","alipay_pm_beta_1"],apiVersion:"2020-03-02;alipay_beta=v1"})})}}const im=vi(e=>new tm(e,new nm(a())),[{gateway:"stripev3"}]),rm={ar:["ar"],bg:["bg"],cs:["cs"],da:["da"],de:["de"],el:["el"],en:["en","en-GB"],es:["es","es-419"],et:["et"],fi:["fi"],fil:["fil"],fr:["fr","fr-CA"],he:["he"],hr:["hr"],hu:["hu"],id:["id"],it:["it"],ja:["ja"],ko:["ko"],lt:["lt"],lv:["lv"],ms:["ms"],mt:["mt"],nb:["nb"],nl:["nl"],pl:["pl"],pt:["pt","pt-BR"],ro:["ro"],ru:["ru"],sk:["sk"],sl:["sl"],sv:["sv"],th:["th"],tr:["tr"],vi:["vi"],zh:["zh","zh-HK","zh-TW"]};function om(e){const[t,n]=e.replace(/_/g,"-").toLowerCase().split("-"),i=rm[t];if(!i)return"auto";const r=n?`${t}-${n.toUpperCase()}`:t;return i.indexOf(r)>-1?r:i[0]}var am=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class sm{constructor(e,t,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n}initialize(e){return am(this,void 0,void 0,function*(){const{stripeupe:t,methodId:n,gatewayId:i}=e;if(!(null==t?void 0:t.containerId))throw new ri(ei.PaymentNotInitialized);if(!i)throw new fi('Unable to initialize payment because "gatewayId" argument is not provided.');return this._loadStripeElement(t,i,n).catch(e=>{var n;return null===(n=t.onError)||void 0===n?void 0:n.call(t,e)}),this.stripeIntegrationService.initCheckoutEventsSubscription(i,n,t,this._stripeElements),Promise.resolve()})}execute(e,t){return am(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{o()}),f.on(za.CHANGE,e=>{(null==e?void 0:e.value)&&"type"in e.value&&this._updateStripeLinkStateByElementType(e.value.type)}),this._isStripeElementUpdateEnabled&&(null==a||a(this._updateStripeElement.bind(this)))})}_processAdditionalActionWithStripeConfirmation(e,t,n,i=!1,r=!1){return am(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new ri(ei.PaymentNotInitialized);const{data:o}=e.body.additional_action_required,{token:a}=o,{paymentIntent:s,error:d}=yield this._confirmStripePaymentOrThrow(t,o),c=this._getPaymentPayload(t,(null==s?void 0:s.id)||a,i,r);if(d||!s){const{initializationData:e}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{sendSecondPaymentRequestOnStripeError:i}=e||{};if(i)try{const e=de({},c,{paymentData:{formattedPayload:{client_side_error:!0}}});yield this.paymentIntegrationService.submitPayment(e)}catch(e){}this.stripeIntegrationService.throwStripeError(d)}try{yield this.paymentIntegrationService.submitPayment(c)}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}})}_confirmStripePaymentOrThrow(e,t){return am(this,void 0,void 0,function*(){if(!this._stripeUPEClient)throw new ri(ei.PaymentNotInitialized);const{token:n,redirect_url:i}=t,r=this.stripeIntegrationService.mapStripePaymentData(this._stripeElements,i,!!this._allowRedisplayForStoredInstruments);return(yield this.stripeIntegrationService.isPaymentCompleted(e,this._stripeUPEClient))?this._stripeUPEClient.retrievePaymentIntent(n||""):this._stripeUPEClient.confirmPayment(r)})}_processVaultedAdditionalAction(e,t,n=!1){var i;return am(this,void 0,void 0,function*(){if(!t||!pa(e)||!ve(e.body.errors,{code:"three_d_secure_required"}))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new ri(ei.PaymentNotInitialized);const r=e.body.three_ds_result.token;let o,a=!1;try{o=yield this._stripeUPEClient.confirmCardPayment(r)}catch(e){try{o=yield this._stripeUPEClient.retrievePaymentIntent(r)}catch(e){a=!0}}if((null==o?void 0:o.error)&&this.stripeIntegrationService.throwStripeError(o.error),!(null==o?void 0:o.paymentIntent)&&!a)throw new nr;const s=this._getPaymentPayload(t,a?r:null===(i=null==o?void 0:o.paymentIntent)||void 0===i?void 0:i.id,!1,n);return this.paymentIntegrationService.submitPayment(s)})}_loadStripeJs(e){return am(this,void 0,void 0,function*(){if(this._stripeUPEClient)return this._stripeUPEClient;const t=this.paymentIntegrationService.getState();return this.scriptLoader.getStripeClient(e,t.getCartLocale(),ka.V3,Fa,La)})}_getPaymentPayload(e,t,n=!1,i=!1){var r;return{methodId:e,paymentData:{formattedPayload:{cart_id:(null===(r=this.paymentIntegrationService.getState().getCart())||void 0===r?void 0:r.id)||"",credit_card_token:{token:t},confirm:!1,vault_payment_instrument:n,set_as_default_stored_instrument:i}}}}_updateStripeElement({shouldShowTerms:e}){var t;const n=null===(t=this._stripeElements)||void 0===t?void 0:t.getElement(Da.PAYMENT);null==n||n.update(Object.assign({},this._getStripeElementTerms(e)))}_getStripeElementTerms(e){let t=Ta.AUTO;return this._isStripeElementUpdateEnabled&&(t=e?Ta.AUTO:Ta.NEVER),{terms:{card:t}}}_updateStripeLinkStateByElementType(e){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow(),n=e===Aa.Link;!cd(t)&&n&&this.paymentIntegrationService.updatePaymentProviderCustomer({stripeLinkAuthenticationState:n})}}const dm=vi(e=>{const t=new Ra(a());return new sm(e,t,new pd(e,t))},[{gateway:"stripeupe"},{gateway:"stripeupe",id:"klarna"}]),cm=e=>"object"==typeof e&&null!==e&&"value"in e&&"collapsed"in e;var lm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class um{constructor(e,t,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n}initialize(e){var t;return lm(this,void 0,void 0,function*(){const{stripeocs:n,methodId:i,gatewayId:r}=e;if(!(null==n?void 0:n.containerId))throw new ri(ei.PaymentNotInitialized);if(!r)throw new fi('Unable to initialize payment because "gatewayId" argument is not provided.');try{yield this._initializeStripeElement(n,r,i)}catch(e){e instanceof Error&&(null===(t=n.onError)||void 0===t||t.call(n,e))}this.stripeIntegrationService.initCheckoutEventsSubscription(r,i,n,this.stripeElements)})}execute(e,t){return lm(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{null==y||y(!1)}),_.on(za.READY,()=>{h()}),_.on(za.CHANGE,e=>{this._onStripeElementChange(e,t,n,p)}),null==m||m(this._collapseStripeElement.bind(this))})}_loadStripeJs(e){return lm(this,void 0,void 0,function*(){if(this.stripeClient)return this.stripeClient;const t=this.paymentIntegrationService.getState(),n=this.stripeIntegrationService.getStripeJsVersion(e);return this.scriptLoader.getStripeClient(e,t.getCartLocale(),n)})}_collapseStripeElement(){var e;const t=null===(e=this.stripeElements)||void 0===e?void 0:e.getElement(Da.PAYMENT);null==t||t.collapse()}_getPaymentPayload(e,t,n){var i;const r=(null===(i=this.paymentIntegrationService.getState().getCart())||void 0===i?void 0:i.id)||"",{card:o,us_bank_account:a}=n||{},s=this._shouldSaveInstrument(o)||this._shouldSaveInstrument(a),d=this._getTokenizedOptions(t,n);return{methodId:e,paymentData:{formattedPayload:Object.assign({cart_id:r,confirm:!1,method:this.selectedMethodId,vault_payment_instrument:s},d)}}}_processAdditionalAction(e,t,n){return lm(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this.stripeClient||!this.stripeElements)throw new ri(ei.PaymentNotInitialized);const{data:i}=e.body.additional_action_required,{token:r}=i,{paymentIntent:o,error:a}=yield this._confirmStripePaymentOrThrow(t,i),{client_secret:s,payment_method_options:d}=o||{},c=this._getPaymentPayload(t,s||r,d);if(a||!o){const{initializationData:e}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{sendSecondPaymentRequestOnStripeError:i}=e||{};if(i)try{const e=de({},c,{paymentData:{formattedPayload:{client_side_error:!0}}});yield this.paymentIntegrationService.submitPayment(e)}catch(e){}this.stripeIntegrationService.throwStripeError(a)}try{return yield this.paymentIntegrationService.submitPayment(c)}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}})}_confirmStripePaymentOrThrow(e,t){return lm(this,void 0,void 0,function*(){if(!this.stripeClient)throw new ri(ei.PaymentNotInitialized);const{token:n,redirect_url:i}=t,r=this.stripeIntegrationService.mapStripePaymentData(this.stripeElements,i);return(yield this.stripeIntegrationService.isPaymentCompleted(e,this.stripeClient))?this.stripeClient.retrievePaymentIntent(n||""):this.stripeClient.confirmPayment(r)})}_onStripeElementChange(e,t,n,i){cm(e)&&!e.collapsed&&(this.selectedMethodId=e.value.type,null==i||i(`${t}-${n}`))}_shouldSaveInstrument(e){const t=null==e?void 0:e.setup_future_usage;return t===Na.ON_SESSION||t===Na.OFF_SESSION}_getTokenizedOptions(e,t){return this._shouldSaveInstrument(null==t?void 0:t.us_bank_account)?{tokenized_ach:{token:e}}:{credit_card_token:{token:e}}}}const hm=vi(e=>{const t=new Ra(a());return new um(e,t,new pd(e,t))},[{gateway:"stripeocs",id:"optimized_checkout"}]);var pm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class mm{constructor(e,t,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n}initialize(e){var t;return pm(this,void 0,void 0,function*(){const{stripeocs:n,methodId:i,gatewayId:r}=e;if(!(null==n?void 0:n.containerId)||!r)throw new ri(ei.PaymentNotInitialized);let o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,r);(null==o?void 0:o.clientToken)||(yield this.paymentIntegrationService.loadPaymentMethod(r,{params:{method:i}}),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,r));try{yield this._initStripeCheckoutSession(n,o),yield this._updateStripeShopperData(),this._initializePaymentElement(n,o),this._initializeAdaptivePricingElement(n,o)}catch(e){e instanceof Error&&(null===(t=n.onError)||void 0===t||t.call(n,e))}})}execute(e,t){return pm(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{null==u||u(!1)}),h.on(za.READY,()=>{d()}),h.on(za.CHANGE,e=>{this._onStripeElementChange(e,r,i,c)}),null==l||l(this._collapseStripeElement.bind(this))}_loadStripeJs(e){return pm(this,void 0,void 0,function*(){if(this.stripeClient)return this.stripeClient;const t=this.paymentIntegrationService.getState();return this.scriptLoader.getStripeClient(e,t.getCartLocale(),ka.CLOVER)})}_getStripeActionsOrThrow(){return pm(this,void 0,void 0,function*(){if(!this.stripeCheckout)throw new ri(ei.PaymentNotInitialized);const{actions:e,error:t}=yield this.stripeCheckout.loadActions();if(!e||t)throw new Qr(null==t?void 0:t.message);return e})}_getStripeElement(e){var t,n;return(null===(t=this.stripeCheckout)||void 0===t?void 0:t.getPaymentElement())||(null===(n=this.stripeCheckout)||void 0===n?void 0:n.createPaymentElement(e))}_onStripeElementChange(e,t,n,i){cm(e)&&!e.collapsed&&(this.selectedMethodId=e.value.type,null==i||i(`${t}-${n}`))}_collapseStripeElement(){var e;const t=null===(e=this.stripeCheckout)||void 0===e?void 0:e.getPaymentElement();null==t||t.collapse()}_updateCheckoutSessionData(e,t){return pm(this,void 0,void 0,function*(){yield this._updateStripeShopperData(),yield this.paymentIntegrationService.loadPaymentMethod(e,{params:{method:t}})})}_getPaymentPayload(e,t,n){var i;const r=(null===(i=this.paymentIntegrationService.getState().getCart())||void 0===i?void 0:i.id)||"",o=this._getTokenizedOptions(t,n);return{methodId:e,paymentData:{formattedPayload:Object.assign({cart_id:r,confirm:!1,method:this.selectedMethodId,vault_payment_instrument:!!n},o)}}}_processAdditionalAction(e,t,n){var i;return pm(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;const{data:r}=(null===(i=e.body)||void 0===i?void 0:i.additional_action_required)||{},{token:o}=r||{},a=yield this._getStripeSavedPaymentMethodsOrThrow(),{session:s,error:d}=yield this._confirmStripePayment(r),c=yield this._getStripeSavedPaymentMethodsOrThrow(s),{id:l,status:u}=s||{},h=this._getNewVaultedStripeInstrument(a,c),p=this._getPaymentPayload(n,l||o,h),{initializationData:m}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t),{sendSecondPaymentRequestOnStripeError:y}=m||{};if(d||!s){if(y)try{const e=de({},p,{paymentData:{formattedPayload:{client_side_error:!0}}});yield this.paymentIntegrationService.submitPayment(e)}catch(e){}throw new Qr(null==d?void 0:d.message)}try{return yield this.paymentIntegrationService.submitPayment(p)}catch(e){throw(null==u?void 0:u.paymentStatus)===Oa.Paid&&this.stripeIntegrationService.throwPaymentConfirmationProceedMessage(),e}})}_confirmStripePayment(e){return pm(this,void 0,void 0,function*(){const{redirect_url:t}=e||{};if(!this.stripeCheckout)throw new ri(ei.PaymentNotInitialized);return(yield this._getStripeActionsOrThrow()).confirm({redirect:Ta.IF_REQUIRED,returnUrl:t})})}_updateStripeShopperData(){return pm(this,void 0,void 0,function*(){const e=yield this._getStripeActionsOrThrow();yield this._updateStripeEmail(e),yield this._updateStripeShippingAddress(e),yield this._updateStripeBillingAddress(e)})}_updateStripeEmail(e){return pm(this,void 0,void 0,function*(){if((yield e.getSession()).email)return;const{getBillingAddress:t}=this.paymentIntegrationService.getState(),n=t();yield e.updateEmail((null==n?void 0:n.email)||"")})}_updateStripeShippingAddress(e){return pm(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getShippingAddress();t&&(yield e.updateShippingAddress({name:this.stripeIntegrationService.getShopperFullName(t),address:this.stripeIntegrationService.mapStripeAddress(t)}))})}_updateStripeBillingAddress(e){return pm(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getBillingAddress();t&&(yield e.updateBillingAddress({name:this.stripeIntegrationService.getShopperFullName(t),address:this.stripeIntegrationService.mapStripeAddress(t)}))})}_getStripeSavedPaymentMethodsOrThrow(e){return pm(this,void 0,void 0,function*(){if(null==e?void 0:e.savedPaymentMethods)return e.savedPaymentMethods;const t=yield this._getStripeActionsOrThrow(),{savedPaymentMethods:n}=yield t.getSession();return n||[]})}_getNewVaultedStripeInstrument(e,t){return t.find(t=>!e.some(e=>e.id===t.id))}_getTokenizedOptions(e,t){return(null==t?void 0:t.type)===Aa.ACH?{tokenized_ach:{token:e}}:{credit_card_token:{token:e}}}_initializeAdaptivePricingElement(e,t){const{initializationData:n}=t,{currencySelectorContainerId:i}=e;if(!(null==n?void 0:n.adaptivePricingEnabled))return;if(!i)throw new ri(ei.PaymentNotInitialized);const r=this._getCurrencySelectorElement();r&&(r.mount(`#${i}`),this._initAdaptivePricingEvents(r))}_getCurrencySelectorElement(){var e,t;return(null===(e=this.stripeCheckout)||void 0===e?void 0:e.getCurrencySelectorElement())||(null===(t=this.stripeCheckout)||void 0===t?void 0:t.createCurrencySelectorElement())}_initAdaptivePricingEvents(e){e.on(za.CHANGE,e=>pm(this,void 0,void 0,function*(){if(!e.value||!("currency"in e.value))return;const{currency:t}=this.paymentIntegrationService.getState().getCartOrThrow(),n=t.code.toLowerCase(),i=e.value.currency.toLowerCase();yield this.paymentIntegrationService.updatePaymentProviderCustomer({isCustomerCurrencySelected:n!==i,customerCurrency:i})}))}}const ym=vi(e=>{const t=new Ra(a());return new mm(e,t,new pd(e,t))},[{gateway:"stripeocs",id:"checkout_session"}]);var gm;!function(e){e.CARD_NUMBER="card-number",e.CVV="cvv",e.EXPIRY="expiry"}(gm||(gm={}));var vm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class fm{constructor(e,t,n){this.paymentIntegrationService=e,this.tdOnlineMartScriptLoader=t,this.formPoster=n,this.tdInputs=[{id:"ccNumber",fieldType:gm.CARD_NUMBER},{id:"ccCvv",fieldType:gm.CVV},{id:"ccExpiry",fieldType:gm.EXPIRY}]}initialize(e){return vm(this,void 0,void 0,function*(){const{methodId:t}=e;if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');this.tdOnlineMartClient=yield this.loadTDOnlineMartJs(),this.mountHostedFields(t)})}execute(e,t){return vm(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{null==e||e.unmount()}),Promise.resolve()}getPaymentPayloadOrThrow(e){return vm(this,void 0,void 0,function*(){const{methodId:t,paymentData:n}=e,{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:r=!1}=jd(n)?n:{},o={browser_info:ss(),shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r};if(jd(n)&&xd(n)&&n.instrumentId){const e=!!this.paymentIntegrationService.getState().getCartOrThrow().lineItems.digitalItems.length,i=!this.isTrustedVaultingInstrument(n.instrumentId)||e;return{methodId:t,paymentData:Object.assign(Object.assign(Object.assign({},o),{instrumentId:n.instrumentId}),i?{nonce:n.instrumentId}:{})}}let a;try{a=yield this.getTokenOrThrow()}catch(e){this.throwTokenizationError(e)}return{methodId:t,paymentData:Object.assign(Object.assign({},o),{nonce:a})}})}mountHostedFields(e){const t=this.getHostedFieldsOptions(),n=this.getTDOnlineMartClientOrThrow();this.tdInputs.forEach(i=>{const r=`${e}-${i.id}`;document.getElementById(r)&&(i.inputElement=n.create(i.fieldType,t),i.inputElement.mount(`#${r}`))})}loadTDOnlineMartJs(){return vm(this,void 0,void 0,function*(){return this.tdOnlineMartClient?this.tdOnlineMartClient:this.tdOnlineMartScriptLoader.load()})}getTokenOrThrow(){return new Promise((e,t)=>{this.getTDOnlineMartClientOrThrow().createToken(n=>{const{error:i,token:r}=n;if(i||!r)return t(i);e(r)})})}getTDOnlineMartClientOrThrow(){if(!this.tdOnlineMartClient)throw new ri(ei.PaymentNotInitialized);return this.tdOnlineMartClient}processWithAdditionalAction(e){return vm(this,void 0,void 0,function*(){if(!function(e){return pa(e)&&(t=e.body,Z(t)&&"object"==typeof t&&"errors"in t&&"three_ds_result"in t&&W(t.errors)&&ve(t.errors,{code:"three_d_secure_required"}));var t}(e))throw e;const{three_ds_result:t}=e.body,{acs_url:n,payer_auth_request:i,merchant_data:r}=t||{};if(!n||!i||!r)throw new co(["formUrl","threeDSSessionData","creq"]);return new Promise(e=>{this.formPoster.postForm(n,{threeDSSessionData:i,creq:r},e,"_top")})})}throwTokenizationError(e){if(!function(e){return"object"==typeof e&&null!==e&&"field"in e&&"type"in e&&"message"in e}(e))throw new ti(Xn.MissingPaymentToken);throw new Error(e.message)}getHostedFieldsOptions(){return{style:{error:{color:"#d14343"}},classes:{error:"form-input--error"}}}isTrustedVaultingInstrument(e){const t=this.paymentIntegrationService.getState().getInstruments(),n=null==t?void 0:t.find(t=>uc(t)&&t.bigpayToken===e);return!(uc(n)&&!n.trustedShippingAddress)}}class Sm{constructor(e,t=window){this.scriptLoader=e,this.tdOnlineMartWindow=t}load(){return e=this,t=void 0,i=function*(){if(this.tdOnlineMartWindow.customcheckout||(yield this.scriptLoader.loadScript("https://libs.na.bambora.com/customcheckout/1/customcheckout.js")),!this.tdOnlineMartWindow.customcheckout)throw new mi;return this.tdOnlineMartWindow.customcheckout()},new((n=void 0)||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())});var e,t,n,i}}const _m=vi(e=>new fm(e,new Sm(a()),Ee()),[{id:"tdonlinemart"}]);var wm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const Im="Payment cannot continue";let Cm;class bm extends tu{initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return wm(this,void 0,void 0,function*(){if(this._initializeOptions=e&&e.worldpay,!this._initializeOptions)throw new ri(ei.PaymentNotInitialized);return t.initialize.call(this,e)})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return wm(this,void 0,void 0,function*(){const{payment:i}=e;if(Cm=this._submitAdditionalAction(),!i)throw new co(["payment"]);try{return yield n.execute.call(this,e,t)}catch(e){return this._processAdditionalAction(e,i)}})}_processAdditionalAction(e,t){return wm(this,void 0,void 0,function*(){return pa(e)&&ve(e.body.errors,{code:"additional_action_required"})?new Promise((n,i)=>{const r=e=>wm(this,void 0,void 0,function*(){if(-1===e.origin.indexOf("cardinalcommerce.com"))return;if("string"!=typeof e.data||!this._isValidJsonWithSessionId(e.data))return i(new Error(Im));window.removeEventListener("message",r),o.remove();const a=JSON.parse(e.data),s=de({},t,{paymentData:{threeDSecure:{token:a.SessionId}}});try{n(yield Cm(s))}catch(e){if(!pa(e)||!ve(e.body.errors,{code:"three_d_secure_required"}))return i(e);if(!this._initializeOptions)return i(new ri(ei.PaymentNotInitialized));const{onLoad:t}=this._initializeOptions,n=this._createIframe(e.body.three_ds_result);try{t(n,()=>i(new Error("Payment was cancelled")))}catch(e){i(new Error(Im))}}});let o;window.addEventListener("message",r);try{o=this._createHiddenIframe(e.body)}catch(e){throw window.removeEventListener("message",r),new Error(Im)}}):Promise.reject(e)})}_createHiddenIframe(e){const t=document.createElement("iframe");if(document.body.appendChild(t),!t.contentWindow)throw new Error;t.id="worldpay_hosted_hidden_payment_page",t.height="0px",t.width="0px";const n=document.createElement("form"),i="collectionForm";n.id=i,n.name="devicedata",n.method="post";const r=e.additional_action_required.data.redirect_url;n.action=r;const o=document.createElement("input");o.name="Bin",o.type="hidden",o.value=e.provider_data.source_id,n.appendChild(o);const a=document.createElement("input");a.name="JWT",a.type="hidden",a.value=e.provider_data.data,n.appendChild(a);const s=document.createElement("button");s.type="submit",s.id="btnsubmit",n.appendChild(s),navigator.userAgent.match("Firefox")?t.srcdoc=n.outerHTML:t.contentWindow.document.body.appendChild(n);const d=document.createElement("script");return d.innerHTML=`\n document.getElementById('${i}').submit();\n `,t.contentWindow.document.body.appendChild(d),t}_createIframe(e){const t=document.createElement("form");t.id="challengeForm",t.method="POST",t.action=e.acs_url;const n=document.createElement("input");n.name="JWT",n.type="hidden",n.value=e.payer_auth_request,t.appendChild(n);const i=document.createElement("input");i.name="MD",i.type="hidden",i.value=`merchantSessionId=${e.merchant_data}`,t.appendChild(i);const r=document.createElement("script");r.type="text/javascript",r.innerHTML="window.onload = function() { document.getElementById('challengeForm').submit(); }";const o=document.createElement("iframe");return o.name="worldpay_hosted_payment_page",o.height="400",o.width="100%",o.srcdoc=`${t.outerHTML} ${r.outerHTML}`,o}_submitAdditionalAction(){if(this._shouldRenderHostedForm){if(!this._hostedForm)throw new ri(ei.PaymentNotInitialized);const e=this._hostedForm;return t=>wm(this,void 0,void 0,function*(){yield e.submit(t)})}return e=>wm(this,void 0,void 0,function*(){yield this._paymentIntegrationService.submitPayment(e)})}_isValidJsonWithSessionId(e){try{const t=JSON.parse(e);return!(!t.SessionId||!t.Status)}catch(e){return!1}}}const Pm=vi(e=>new bm(e),[{gateway:"worldpayaccess",id:"credit_card"},{id:"worldpayaccess"}]);class Om{constructor(e){this._paymentIntegrationService=e}execute({payment:e}){return t=this,n=void 0,r=function*(){if(!e)throw new co(["payment"]);yield this._paymentIntegrationService.submitOrder();try{yield this._paymentIntegrationService.submitPayment(this._buildOpenBankingSubmitPayment(e))}catch(e){if(this._isWorldpayAccessRedirectResponse(e)){const t=e.body.additional_action_required.data.redirect_url;return new Promise(()=>window.location.replace(t))}return Promise.reject(e)}},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}initialize(){return Promise.resolve()}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_buildOpenBankingSubmitPayment(e){const{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n}=jd(e.paymentData)?e.paymentData:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1};return Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{open_banking:{},vault_payment_instrument:t||!1,set_as_default_stored_instrument:n||!1}}})}_isWorldpayAccessRedirectResponse(e){var t,n;if("object"!=typeof e||null===e)return!1;const i=e;if(!i.body)return!1;const r=i.body;return"additional_action_required"===r.status&&!!(null===(n=null===(t=r.additional_action_required)||void 0===t?void 0:t.data)||void 0===n?void 0:n.redirect_url)}}const Em=vi(e=>new Om(e),[{id:"open_banking",gateway:"worldpayaccess"}]);class Am{constructor(e){this._requestSender=e}saveExternalId(e,t){return n=this,i=void 0,o=function*(){const n=`/api/storefront/payment/${e}/save-external-id`,i={headers:Object.assign({Accept:mr.JsonV1,"X-API-INTERNAL":hr},yr),body:{externalId:t,provider:e}};yield this._requestSender.post(n,i)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}class Tm{constructor(e,t){this.paymentIntegrationService=e,this.storefrontPaymentRequestSender=t}initialize(){return Promise.resolve()}execute(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rwindow.location.replace(d));throw e}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_prepareForReferredRegistration(e,t){return this.storefrontPaymentRequestSender.saveExternalId(e,t)}}const km=vi(e=>{const{getHost:t}=e.getState(),i=n({host:t()}),r=new Am(i);return new Tm(e,r)},[{id:"zip"},{id:"quadpay"}]);var Dm,Mm;!function(e){e.LoadCountriesRequested="LOAD_COUNTRIES_REQUESTED",e.LoadCountriesSucceeded="LOAD_COUNTRIES_SUCCEEDED",e.LoadCountriesFailed="LOAD_COUNTRIES_FAILED"}(Dm||(Dm={}));class zm{constructor(e){this._countryRequestSender=e}loadCountries(e){return m.create(t=>{t.next(l(Dm.LoadCountriesRequested)),this._countryRequestSender.loadCountries(e).then(e=>{t.next(l(Dm.LoadCountriesSucceeded,e.body.data)),t.complete()}).catch(e=>{t.error(h(Dm.LoadCountriesFailed,e))})})}}class Nm{constructor(e,t){this._requestSender=e,this._config=t}loadCountries({timeout:e}={}){const t=Object.assign({"Accept-Language":this._config.locale},Xe);return this._requestSender.get("/internalapi/v1/store/countries",{headers:t,timeout:e})}}class xm extends it{constructor(e){super(e||"Your checkout could not be processed because some details have changed. Please review your order and try again."),this.name="CartConsistencyError",this.type="cart_consistency"}}class Rm extends it{constructor(e,t){super(t||"At least one item changed stock position. Please review your cart and try again."),this.name="CartStockPositionsChangedError",this.type="cart_stock_positions_changed",this.changedItemIds=e}}class Fm extends it{constructor(e){super(e||"The tax provider is unavailable."),this.name="OrderTaxProviderUnavailableError",this.type="tax_provider_unavailable"}}class Lm extends it{constructor(e){super(e),this.name="MissingShippingMethodError",this.type="missing_shipping_method"}}class Bm extends it{constructor(e){super(e),this.name="InvalidShippingAddressError",this.type="invalid_shipping_address"}}class jm{constructor(e){this._requestSender=e}loadOrder(e,{timeout:t}={}){const n=`/api/storefront/orders/${e}`,i=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.get(n,{params:{include:Ft(["payments","lineItems.physicalItems.socialMedia","lineItems.physicalItems.options","lineItems.physicalItems.categories","lineItems.digitalItems.socialMedia","lineItems.digitalItems.options","lineItems.digitalItems.categories"])},headers:i,timeout:t})}submitOrder(e,{headers:t,timeout:n}={}){return this._requestSender.post("/internalapi/v1/checkout/order",{body:e,headers:ue(Object.assign({"X-Checkout-Variant":t&&t.checkoutVariant},Xe),J),timeout:n}).catch(e=>{var t,n;if("tax_provider_unavailable"===e.body.type)throw new Fm;if("cart_has_changed"===e.body.type)throw new xm;if("cart_stock_positions_changed"===e.body.type){const i=null!==(n=null===(t=e.body.errors)||void 0===t?void 0:t.changedItemIds)&&void 0!==n?n:[];throw new Rm(i)}if("missing_shipping_method"===e.body.type)throw new Lm(e.body.detail);if("invalid_shipping_address"===e.body.type)throw new Bm(e.body.detail);if("empty_cart"===e.body.type)throw new dt;throw e})}finalizeOrder(e,{timeout:t}={}){const n=`/internalapi/v1/checkout/order/${e}`;return this._requestSender.post(n,{timeout:t,headers:Xe})}}class Um extends it{constructor(){super("You haven't complete our spam check. Please try again."),this.name="SpamProtectionNotCompletedError",this.type="spam_protection_not_completed"}}!function(e){e.LoadOrderRequested="LOAD_ORDER_REQUESTED",e.LoadOrderSucceeded="LOAD_ORDER_SUCCEEDED",e.LoadOrderFailed="LOAD_ORDER_FAILED",e.LoadOrderPaymentsRequested="LOAD_ORDER_PAYMENTS_REQUESTED",e.LoadOrderPaymentsSucceeded="LOAD_ORDER_PAYMENTS_SUCCEEDED",e.LoadOrderPaymentsFailed="LOAD_ORDER_PAYMENTS_FAILED",e.SubmitOrderRequested="SUBMIT_ORDER_REQUESTED",e.SubmitOrderSucceeded="SUBMIT_ORDER_SUCCEEDED",e.SubmitOrderFailed="SUBMIT_ORDER_FAILED",e.FinalizeOrderRequested="FINALIZE_ORDER_REQUESTED",e.FinalizeOrderSucceeded="FINALIZE_ORDER_SUCCEEDED",e.FinalizeOrderFailed="FINALIZE_ORDER_FAILED"}(Mm||(Mm={}));var qm;class Vm{constructor(e,t){this._orderRequestSender=e,this._checkoutValidator=t}loadOrder(e,t){return new m(n=>{n.next(l(Mm.LoadOrderRequested)),this._orderRequestSender.loadOrder(e,t).then(e=>{n.next(l(Mm.LoadOrderSucceeded,e.body)),n.complete()}).catch(e=>{n.error(h(Mm.LoadOrderFailed,e))})})}loadOrderPayments(e,t){return new m(n=>{n.next(l(Mm.LoadOrderPaymentsRequested)),this._orderRequestSender.loadOrder(e,t).then(e=>{n.next(l(Mm.LoadOrderPaymentsSucceeded,e.body)),n.complete()}).catch(e=>{n.error(h(Mm.LoadOrderPaymentsFailed,e))})})}loadCurrentOrder(e){return t=>v(()=>{const n=this._getCurrentOrderId(t.getState());if(!n)throw new rt(et.MissingOrderId);return this.loadOrder(n,e)})}submitOrder(e,t){return n=>g(C(l(Mm.SubmitOrderRequested)),v(()=>{const i=n.getState(),r=i.config.getExternalSource(),o=i.config.getVariantIdentificationToken(),a=i.checkout.getCheckout();if(!a)throw new rt(et.MissingCheckout);if(a.shouldExecuteSpamCheck)throw new Um;return S(this._checkoutValidator.validate(a,t).then(()=>this._orderRequestSender.submitOrder(this._mapToOrderRequestBody(null!=e?e:{},a.id,a.customerMessage,r),Object.assign(Object.assign({},t),{headers:{checkoutVariant:o}})))).pipe(M(e=>g(this.loadOrder(e.body.data.order.orderId,t),C(l(Mm.SubmitOrderSucceeded,e.body.data,Object.assign(Object.assign({},e.body.meta),{token:e.headers.token}))))))}).pipe(P(e=>Je(Mm.SubmitOrderFailed,e))))}finalizeOrder(e,t){return g(C(l(Mm.FinalizeOrderRequested)),S(this._orderRequestSender.finalizeOrder(e,t)).pipe(M(n=>g(this.loadOrder(e,t),C(l(Mm.FinalizeOrderSucceeded,n.body.data)))))).pipe(P(e=>Je(Mm.FinalizeOrderFailed,e)))}_getCurrentOrderId(e){const t=e.order.getOrder(),n=e.checkout.getCheckout();return t&&t.orderId||n&&n.orderId}_mapToOrderRequestBody(e,t,n,i){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const n=e.config.getStoreConfig();n&&t.setHost(n.paymentSettings.bigpayBaseUrl)},e=>e.config.getStoreConfig()),t}!function(e){e.LoadPaymentMethodRequested="LOAD_PAYMENT_METHOD_REQUESTED",e.LoadPaymentMethodSucceeded="LOAD_PAYMENT_METHOD_SUCCEEDED",e.LoadPaymentMethodFailed="LOAD_PAYMENT_METHOD_FAILED",e.LoadPaymentMethodsRequested="LOAD_PAYMENT_METHODS_REQUESTED",e.LoadPaymentMethodsSucceeded="LOAD_PAYMENT_METHODS_SUCCEEDED",e.LoadPaymentMethodsFailed="LOAD_PAYMENT_METHODS_FAILED"}(qm||(qm={}));const Hm=e=>!!e;class Wm{constructor(e){this._requestSender=e}loadPaymentMethodsById(e,t){return n=>new m(i=>{var r;const o=null===(r=n.getState().cart.getCart())||void 0===r?void 0:r.id,a=o?Object.assign(Object.assign({},null==t?void 0:t.params),{cartId:o}):Object.assign({},null==t?void 0:t.params);i.next(l(qm.LoadPaymentMethodsRequested)),Promise.all(e.map(e=>{return n=this,i=void 0,o=function*(){try{return(yield this._requestSender.loadPaymentMethod(e,Object.assign(Object.assign({},t),{params:a}))).body}catch(e){return}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).then(e=>{const t=e.filter(Hm);i.next(l(qm.LoadPaymentMethodsSucceeded,t)),i.complete()}).catch(e=>{i.next(l(qm.LoadPaymentMethodsFailed,e)),i.complete()})})}loadPaymentMethods(e){return t=>m.create(n=>{const i=t.getState().cart.getCartOrThrow();n.next(l(qm.LoadPaymentMethodsRequested)),this._requestSender.loadPaymentMethods(Object.assign(Object.assign({},e),{params:Object.assign(Object.assign({},null==e?void 0:e.params),{cartId:i.id})})).then(e=>{const t={deviceSessionId:e.headers["x-device-session-id"],sessionHash:e.headers["x-session-hash"]},i=e.body;n.next(l(qm.LoadPaymentMethodsSucceeded,i,t)),n.complete()}).catch(e=>{n.error(h(qm.LoadPaymentMethodsFailed,e))})})}loadPaymentMethod(e,t){return n=>m.create(i=>{var r;const o=null===(r=n.getState().cart.getCart())||void 0===r?void 0:r.id,a=o?Object.assign(Object.assign({},null==t?void 0:t.params),{cartId:o}):Object.assign({},null==t?void 0:t.params);i.next(l(qm.LoadPaymentMethodRequested,void 0,{methodId:e})),this._requestSender.loadPaymentMethod(e,Object.assign(Object.assign({},t),{params:a})).then(t=>{i.next(l(qm.LoadPaymentMethodSucceeded,t.body,{methodId:e})),i.complete()}).catch(t=>{i.error(h(qm.LoadPaymentMethodFailed,t,{methodId:e}))})})}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([It],Wm.prototype,"loadPaymentMethod",null);class $m{constructor(e){this._requestSender=e}loadPaymentMethods({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/payments",{timeout:e,headers:Object.assign({Accept:ct.JsonV1,"X-API-INTERNAL":At},Xe),params:t})}loadPaymentMethod(e,{timeout:t,params:n}={}){const i=`/api/storefront/payments/${e}`;return this._requestSender.get(i,{timeout:t,headers:Object.assign({Accept:ct.JsonV1,"X-API-INTERNAL":At},Xe),params:n})}}class Ym extends it{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}var Km,Jm;!function(e){e.ExecuteFailed="PAYMENT_STRATEGY_EXECUTE_FAILED",e.ExecuteRequested="PAYMENT_STRATEGY_EXECUTE_REQUESTED",e.ExecuteSucceeded="PAYMENT_STRATEGY_EXECUTE_SUCCEEDED",e.FinalizeFailed="PAYMENT_STRATEGY_FINALIZE_FAILED",e.FinalizeRequested="PAYMENT_STRATEGY_FINALIZE_REQUESTED",e.FinalizeSucceeded="PAYMENT_STRATEGY_FINALIZE_SUCCEEDED",e.InitializeFailed="PAYMENT_STRATEGY_INITIALIZE_FAILED",e.InitializeRequested="PAYMENT_STRATEGY_INITIALIZE_REQUESTED",e.InitializeSucceeded="PAYMENT_STRATEGY_INITIALIZE_SUCCEEDED",e.DeinitializeFailed="PAYMENT_STRATEGY_DEINITIALIZE_FAILED",e.DeinitializeRequested="PAYMENT_STRATEGY_DEINITIALIZE_REQUESTED",e.DeinitializeSucceeded="PAYMENT_STRATEGY_DEINITIALIZE_SUCCEEDED",e.WidgetInteractionStarted="PAYMENT_STRATEGY_WIDGET_INTERACTION_STARTED",e.WidgetInteractionFinished="PAYMENT_STRATEGY_WIDGET_INTERACTION_FINISHED",e.WidgetInteractionFailed="PAYMENT_STRATEGY_WIDGET_INTERACTION_FAILED"}(Km||(Km={})),function(e){e.ADYENV2="adyenv2",e.ADYENV2_GOOGLEPAY="googlepayadyenv2",e.ADYENV3="adyenv3",e.ADYENV3_GOOGLEPAY="googlepayadyenv3",e.AFFIRM="affirm",e.AFTERPAY="afterpay",e.AUTHORIZENET_GOOGLE_PAY="googlepayauthorizenet",e.AMAZONPAY="amazonpay",e.APPLEPAY="applepay",e.BLUESNAPV2="bluesnapv2",e.BOLT="bolt",e.CBA_MPGS="cba_mpgs",e.CHECKOUTCOM="checkoutcom",e.CHECKOUTCOM_APM="checkoutcomapm",e.CHECKOUTCOM_FAWRY="checkoutcomfawry",e.CHECKOUTCOM_SEPA="checkoutcomsepa",e.CHECKOUTCOM_IDEAL="checkoutcomideal",e.CREDIT_CARD="creditcard",e.CHECKOUTCOM_GOOGLE_PAY="googlepaycheckoutcom",e.CLEARPAY="clearpay",e.CONVERGE="converge",e.CYBERSOURCE="cybersource",e.CYBERSOURCEV2="cybersourcev2",e.BNZ="bnz",e.BNZ_GOOGLEPAY="googlepaybnz",e.CYBERSOURCEV2_GOOGLE_PAY="googlepaycybersourcev2",e.HUMM="humm",e.KLARNA="klarna",e.KLARNAV2="klarnav2",e.LEGACY="legacy",e.MOLLIE="mollie",e.MONERIS="moneris",e.NO_PAYMENT_DATA_REQUIRED="nopaymentdatarequired",e.OFFLINE="offline",e.OFFSITE="offsite",e.ORBITAL_GOOGLE_PAY="googlepayorbital",e.PAYPAL_EXPRESS="paypalexpress",e.PAYPAL_EXPRESS_CREDIT="paypalexpresscredit",e.PAYPAL_COMMERCE="paypalcommerce",e.PAYPAL_COMMERCE_CREDIT="paypalcommercecredit",e.PAYPAL_COMMERCE_CREDIT_CARD="paypalcommercecreditcards",e.PAYPAL_COMMERCE_ALTERNATIVE_METHODS="paypalcommercealternativemethods",e.PAYPAL_COMMERCE_VENMO="paypalcommercevenmo",e.PPSDK="PAYMENT_TYPE_SDK",e.QUADPAY="quadpay",e.SAGE_PAY="sagepay",e.SQUARE="squarev2",e.STRIPEV3="stripev3",e.STRIPE_UPE="stripeupe",e.STRIPE_UPE_GOOGLE_PAY="googlepaystripeupe",e.BRAINTREE="braintree",e.BRAINTREE_PAYPAL="braintreepaypal",e.BRAINTREE_VENMO="braintreevenmo",e.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",e.BRAINTREE_VISA_CHECKOUT="braintreevisacheckout",e.BRAINTREE_GOOGLE_PAY="googlepaybraintree",e.WORLDPAYACCESS="worldpayaccess",e.WORLDPAYACCESS_GOOGLE_PAY="googlepayworldpayaccess",e.STRIPE_GOOGLE_PAY="googlepaystripe",e.SEZZLE="sezzle",e.ZIP="zip"}(Jm||(Jm={}));const Zm=Jm;class Qm{widgetInteraction(e,t){const n={methodId:t&&t.methodId};return g(C(l(Km.WidgetInteractionStarted,void 0,n)),v(()=>e().then(()=>l(Km.WidgetInteractionFinished,void 0,n)))).pipe(P(e=>Je(Km.WidgetInteractionFailed,e,n)))}}class Xm{constructor(e,t,n,i,r){this._strategyRegistry=e,this._strategyRegistryV2=t,this._orderActionCreator=n,this._spamProtectionActionCreator=i,this._paymentIntegrationService=r,this._paymentStrategyWidgetActionCreator=new Qm}execute(e,t){const{payment:n={},useStoreCredit:i}=e,r={methodId:n.methodId};return o=>{const{checkout:a}=o.getState(),{shouldExecuteSpamCheck:s}=a.getCheckoutOrThrow();return g(s?this._spamProtectionActionCreator.verifyCheckoutSpamProtection()(o):f(),C(l(Km.ExecuteRequested,void 0,r)),v(()=>{const a=o.getState();let s;if(a.payment.isPaymentDataRequired(i)){const e=a.paymentMethods.getPaymentMethod(n.methodId,n.gatewayId);if(!e)throw new rt(et.MissingPaymentMethod);s=this._getStrategy(e)}else s=this._strategyRegistryV2.get({id:Zm.NO_PAYMENT_DATA_REQUIRED});return s.execute(e,Object.assign(Object.assign({},t),{methodId:n.methodId,gatewayId:n.gatewayId})).then(()=>l(Km.ExecuteSucceeded,void 0,r))})).pipe(P(e=>Je(Km.ExecuteFailed,e,r)))}}finalize(e){const{integrations:t}=null!=e?e:{};return n=>g(C(l(Km.FinalizeRequested)),this._loadOrderPaymentsIfNeeded(n,e),v(()=>{return i=this,r=void 0,a=function*(){const i=n.getState(),{providerId:r="",gatewayId:o=""}=i.payment.getPaymentId()||{},a=i.paymentMethods.getPaymentMethod(r,o);if(!a)throw new Ym;let s;Zt(this._strategyRegistryV2,null!=t?t:[],this._paymentIntegrationService);try{s=this._getStrategy(a)}catch(e){throw new Ym}return yield s.finalize(Object.assign(Object.assign({},e),{methodId:a.id,gatewayId:a.gateway})),l(Km.FinalizeSucceeded,void 0,{methodId:a.id})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a})).pipe(P(e=>{const t=n.getState().payment.getPaymentId();return Je(Km.FinalizeFailed,e,{methodId:t&&t.providerId})}))}initialize(e){const{methodId:t,gatewayId:n,integrations:i}=e;return r=>v(()=>{const o=r.getState(),a=o.paymentMethods.getPaymentMethod(t,n);if(!a)throw new rt(et.MissingPaymentMethod);if(t&&o.paymentStrategies.isInitialized({methodId:t,gatewayId:n}))return f();Zt(this._strategyRegistryV2,null!=i?i:[],this._paymentIntegrationService);const s=this._getStrategy(a).initialize(Object.assign(Object.assign({},e),{methodId:t,gatewayId:n}));return g(C(l(Km.InitializeRequested,void 0,{methodId:t,gatewayId:n})),s.then(()=>l(Km.InitializeSucceeded,void 0,{methodId:t,gatewayId:n})))}).pipe(P(e=>Je(Km.InitializeFailed,e,{methodId:t,gatewayId:n})))}deinitialize(e){const{methodId:t,gatewayId:n}=e;return i=>v(()=>{const r=i.getState(),o=r.paymentMethods.getPaymentMethod(t,n);if(!o)throw new rt(et.MissingPaymentMethod);if(t&&!r.paymentStrategies.isInitialized({methodId:t,gatewayId:n}))return f();const a=this._getStrategy(o).deinitialize(Object.assign(Object.assign({},e),{methodId:t,gatewayId:n}));return g(C(l(Km.DeinitializeRequested,void 0,{methodId:t,gatewayId:n})),a.then(()=>l(Km.DeinitializeSucceeded,void 0,{methodId:t,gatewayId:n})))}).pipe(P(e=>Je(Km.DeinitializeFailed,e,{methodId:t,gatewayId:n})))}widgetInteraction(e,t){return this._paymentStrategyWidgetActionCreator.widgetInteraction(e,t)}_getStrategy(e){let t;try{t=this._strategyRegistry.getByMethod(e)}catch(n){try{t=this._strategyRegistryV2.get({id:e.id,gateway:e.gateway,type:e.type})}catch(t){throw wt().error(`[PaymentStrategyActionCreator] Unable to resolve V2 strategy for id: ${e.id}, gateway: ${e.gateway}, type: ${e.type}`),t}}return t}_loadOrderPaymentsIfNeeded(e,t){const n=e.getState().checkout.getCheckout();return n&&n.orderId?this._orderActionCreator.loadOrderPayments(n.orderId,t):f()}}class ey{isEqual(e,t){return Y(this._normalize(e),this._normalize(t))}_normalize(e){return{cartAmount:e.cartAmount,currency:e.currency,id:e.id,lineItems:{digitalItems:e.lineItems.digitalItems.slice().sort((e,t)=>`${e.productId}${e.variantId}`.localeCompare(`${t.productId}${t.variantId}`)).map(e=>({extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId})),giftCertificates:e.lineItems.giftCertificates.slice().sort((e,t)=>`${e.id}`.localeCompare(`${t.id}`)).map(e=>({amount:e.amount,recipient:e.recipient})),physicalItems:e.lineItems.physicalItems.slice().sort((e,t)=>`${e.productId}${e.variantId}`.localeCompare(`${t.productId}${t.variantId}`)).map(e=>({extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId,giftWrapping:e.giftWrapping}))}}}}class ty extends it{constructor(e,t){super("An update to your shopping cart has been detected and your available shipping costs have been updated."),this.name="CartChangedError",this.type="cart_changed",this.data={previous:e,updated:t}}}class ny{constructor(e){this._checkoutRequestSender=e}validate(e,t){if(!e)throw new rt(et.MissingCheckout);return this._checkoutRequestSender.loadCheckout(e.id,t).then(t=>{const n=new ey;if(!(e.outstandingBalance===t.body.outstandingBalance&&this._compareCoupons(e.coupons,t.body.coupons)&&this._compareGiftCertificates(e.giftCertificates,t.body.giftCertificates)&&n.isEqual(e.cart,t.body.cart)))throw new ty(this._getComparableCheckout(e),this._getComparableCheckout(t.body))})}_compareCoupons(e,t){return Y(oe(e,"code"),oe(t,"code"))}_compareGiftCertificates(e,t){return Y(oe(e,"code"),oe(t,"code"))}_getComparableCheckout(e){const{cart:t,coupons:n,giftCertificates:i,outstandingBalance:r}=e;return{cart:{cartAmount:t.cartAmount,currency:t.currency,lineItems:t.lineItems},coupons:n,giftCertificates:i,outstandingBalance:r}}}class iy{constructor(e){this._namespace=e}getItem(e){const t=Te.getItem(this.withNamespace(e));if(null===t)return null;try{return JSON.parse(t)}catch(t){return this.removeItem(this.withNamespace(e)),null}}getItemOnce(e){const t=this.getItem(e);return this.removeItem(e),t}setItem(e,t){return Te.setItem(this.withNamespace(e),JSON.stringify(t))}removeItem(e){return Te.removeItem(this.withNamespace(e))}withNamespace(e){return`${this._namespace}.${e}`}}class ry extends it{constructor(){super("Please complete our human verification challenge and try again."),this.name="CardingProtectionChallengeNotCompletedError",this.type="carding_protection_challenge_not_completed"}}class oy extends it{constructor(){super("We were not able to verify that you are not a robot. Please try again."),this.name="CardingProtectionFailedError",this.type="carding_protection_failed"}}var ay,sy,dy=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class cy{constructor(e){this._googleRecaptcha=e}handle(e,t){return dy(this,void 0,void 0,function*(){return"string"==typeof e?this.handleWithRecaptchaSitekey(e,t):this.handleWithPaymentHumanVerificationRequestError(e)})}handleWithPaymentHumanVerificationRequestError(e){return dy(this,void 0,void 0,function*(){if(!this._isPaymentHumanVerificationRequest(e))throw e;return yield this._initialize(e.body.additional_action_required.data.key),this._performRecaptcha()})}handleWithRecaptchaSitekey(e,t){return dy(this,void 0,void 0,function*(){if("recaptcha_v2"!==e)throw Error("Human verification method is not supported.");if(!t)throw Error("Recaptcha site key is missing.");return yield this._initialize(t),this._performRecaptcha()})}_performRecaptcha(){return this._googleRecaptcha.execute().pipe(z(1)).pipe(M(({error:e,token:t})=>dy(this,void 0,void 0,function*(){if(e instanceof sn)throw new ry;if(e||!t)throw new oy;return{type:"recaptcha_v2_verification",data:{human_verification_token:t}}}))).toPromise()}_initialize(e){const t="cardingProtectionContainer";let n=document.getElementById(t);return n&&n.parentNode&&n.parentNode.removeChild(n),n=document.createElement("div"),n.setAttribute("id",t),document.body.appendChild(n),this._googleRecaptcha.load(t,e)}_isPaymentHumanVerificationRequest(e){const{additional_action_required:t,status:n}=e.body||{};return"additional_action_required"===n&&t&&"recaptcha_v2_verification"===t.type}}function ly(e,t){const{body:n}=e,{errors:i=[]}=n;return new Ot(e,{message:uy(i)||t,errors:i})}function uy(e){if(Array.isArray(e))return e.reduce((e,t)=>t&&t.message?[...e,t.message]:e,[]).join(" ")}class hy extends it{constructor(e){super(e||"Unable to proceed due to invalid configuration provided for the hosted payment form."),this.name="InvalidHostedFormConfigError",this.type="invalid_hosted_form_config"}}class py extends it{constructor(e){super(e||"Unable to proceed due to an unknown error with the hosted payment form."),this.name="InvalidHostedFormError",this.type="invalid_hosted_form"}}class my extends it{constructor(e){super(["Unable to proceed due to invalid user input values",...U(Ce(e),e=>oe(e,({message:e})=>e))].join(". ")),this.errors=e,this.name="InvalidHostedFormValueError",this.type="invalid_hosted_form_value"}}!function(e){e.AttachRequested="HOSTED_FIELD:ATTACH_REQUESTED",e.SubmitRequested="HOSTED_FIELD:SUBMITTED_REQUESTED",e.ValidateRequested="HOSTED_FIELD:VALIDATE_REQUESTED",e.StoredCardRequested="HOSTED_FIELD:STORED_CARD_REQUESTED"}(ay||(ay={})),function(e){e.AttachSucceeded="HOSTED_INPUT:ATTACH_SUCCEEDED",e.AttachFailed="HOSTED_INPUT:ATTACH_FAILED",e.BinChanged="HOSTED_INPUT:BIN_CHANGED",e.Blurred="HOSTED_INPUT:BLURRED",e.Changed="HOSTED_INPUT:CHANGED",e.CardTypeChanged="HOSTED_INPUT:CARD_TYPE_CHANGED",e.Entered="HOSTED_INPUT:ENTERED",e.Focused="HOSTED_INPUT:FOCUSED",e.SubmitSucceeded="HOSTED_INPUT:SUBMIT_SUCCEEDED",e.SubmitFailed="HOSTED_INPUT:SUBMIT_FAILED",e.Validated="HOSTED_INPUT:VALIDATED",e.StoredCardSucceeded="HOSTED_INPUT:STORED_CARD_SUCCEEDED",e.StoredCardFailed="HOSTED_INPUT:STORED_CARD_FAILED"}(sy||(sy={}));var yy=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class gy{constructor(e,t,n,i,r,o,a,s,d,c){this._type=e,this._containerId=t,this._placeholder=n,this._accessibilityLabel=i,this._styles=r,this._eventPoster=o,this._eventListener=a,this._detachmentObserver=s,this._checkoutId=d,this._cardInstrument=c,this._iframe=document.createElement("iframe");const l=this._checkoutId?`/checkout/payment/hosted-field?version=1.909.5&checkoutId=${this._checkoutId}`:"/checkout/payment/hosted-field?version=1.909.5";this._iframe.src=l,this._iframe.style.border="none",this._iframe.style.height="100%",this._iframe.style.overflow="hidden",this._iframe.style.width="100%"}getType(){return this._type}attach(){return yy(this,void 0,void 0,function*(){const e=document.getElementById(this._containerId);if(!e)throw new hy("Unable to proceed because the provided container ID is not valid.");e.appendChild(this._iframe),this._eventListener.listen();const t=_(this._iframe,"load").pipe(M(({target:e})=>yy(this,void 0,void 0,function*(){const t=e&&e.contentWindow;if(!t)throw new Error("The content window of the iframe cannot be accessed.");this._eventPoster.setTarget(t),yield this._eventPoster.post({type:ay.AttachRequested,payload:{accessibilityLabel:this._accessibilityLabel,cardInstrument:this._cardInstrument,fontUrls:this._getFontUrls(),placeholder:this._placeholder,styles:this._styles,origin:document.location.origin,type:this._type}},{successType:sy.AttachSucceeded,errorType:sy.AttachFailed})})),z(1)).toPromise();yield this._detachmentObserver.ensurePresence([this._iframe],t)})}detach(){this._iframe.parentElement&&(this._iframe.parentElement.removeChild(this._iframe),this._eventListener.stopListen())}submitForm(e,t){return yy(this,void 0,void 0,function*(){try{const n=this._eventPoster.post({type:ay.SubmitRequested,payload:{fields:e,data:t}},{successType:sy.SubmitSucceeded,errorType:sy.SubmitFailed});return yield this._detachmentObserver.ensurePresence([this._iframe],n)}catch(e){if(this._isSubmitErrorEvent(e)){if("hosted_form_error"===e.payload.error.code)throw new py(e.payload.error.message);if(e.payload.response)throw ly(e.payload.response);throw new Error(e.payload.error.message)}throw e}})}submitStoredCardForm(e,t){return yy(this,void 0,void 0,function*(){const n=this._eventPoster.post({type:ay.StoredCardRequested,payload:{fields:e,data:t}},{successType:sy.StoredCardSucceeded,errorType:sy.StoredCardFailed});return this._detachmentObserver.ensurePresence([this._iframe],n)})}validateForm(){return yy(this,void 0,void 0,function*(){const e=this._eventPoster.post({type:ay.ValidateRequested},{successType:sy.Validated}),{payload:t}=yield this._detachmentObserver.ensurePresence([this._iframe],e);if(!t.isValid)throw new my(t.errors)})}_getFontUrls(){const e="fonts.googleapis.com",t=document.querySelectorAll(`link[href*='${e}'][rel='stylesheet']`);return Array.prototype.slice.call(t).filter(t=>In(t.href).hostname===e).filter(e=>Ce(this._styles).map(e=>e&&e.fontFamily).filter(e=>"string"==typeof e).some(t=>t.split(/,\s/).some(t=>-1!==e.href.indexOf(t.replace(" ","+"))))).map(e=>e.href)}_isSubmitErrorEvent(e){return e.type===sy.SubmitFailed}}var vy,fy=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Sy{constructor(e,t,n,i,r){this._fields=e,this._eventListener=t,this._payloadTransformer=n,this._eventCallbacks=i,this._paymentHumanVerificationHandler=r,this._handleEnter=({payload:e})=>fy(this,void 0,void 0,function*(){try{yield this.validate()}catch(e){if(e instanceof Error&&"InvalidHostedFormValueError"!==e.name)throw e}const{onEnter:t=ce}=this._eventCallbacks;t(e)});const{onBlur:o=ce,onCardTypeChange:a=ce,onFocus:s=ce,onValidate:d=ce}=this._eventCallbacks;this._eventListener.addListener(sy.Blurred,({payload:e})=>o(e)),this._eventListener.addListener(sy.CardTypeChanged,({payload:e})=>a(e)),this._eventListener.addListener(sy.Focused,({payload:e})=>s(e)),this._eventListener.addListener(sy.Validated,({payload:e})=>d(e)),this._eventListener.addListener(sy.Entered,this._handleEnter),this._eventListener.addListener(sy.CardTypeChanged,({payload:e})=>this._cardType=e.cardType),this._eventListener.addListener(sy.BinChanged,({payload:e})=>this._bin=e.bin)}getBin(){return this._bin}getCardType(){return this._cardType}attach(){return fy(this,void 0,void 0,function*(){this._eventListener.listen();const e=this._getFirstField(),t=be(this._fields,e);yield e.attach(),yield Promise.all(t.map(e=>e.attach()))})}detach(){this._eventListener.stopListen(),this._fields.forEach(e=>{e.detach()})}submit(e,t){return fy(this,void 0,void 0,function*(){try{return yield this._getFirstField().submitForm(this._fields.map(e=>e.getType()),this._payloadTransformer.transform(e,t))}catch(t){const n=yield this._paymentHumanVerificationHandler.handle(t);return yield this._getFirstField().submitForm(this._fields.map(e=>e.getType()),this._payloadTransformer.transform(e,n))}})}submitStoredCard(e){return fy(this,void 0,void 0,function*(){return this._getFirstField().submitStoredCardForm(e.fields,e.data)})}validate(){return fy(this,void 0,void 0,function*(){return this._getFirstField().validateForm()})}_getFirstField(){const e=this._fields[0];if(!e)throw new hy("Unable to proceed because the payment form has no field defined.");return e}}function _y(e){return Boolean(e.instrumentId)}class wy{constructor(e){this._store=e}transform(e,t){const n=this._store.getState(),i=n.checkout.getCheckout(),r=n.config.getConfig(),o=n.instruments.getInstrumentsMeta(),a=n.order.getOrder(),s=n.order.getOrderMeta(),d=le(e.paymentData,"ccExpiry","ccName","ccNumber","ccCvv");let c=n.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId);"worldpayaccess"===(null==c?void 0:c.gateway)&&"credit_card"===(null==c?void 0:c.id)&&(c=Object.assign(Object.assign({},c),{id:"worldpayaccess",method:"credit-card"}));const l=n.paymentMethods.getPaymentMethodsMeta(),u=o&&d&&_y(d)?`${n.payment.getPaymentToken()}, ${o.vaultAccessToken}`:n.payment.getPaymentToken();if(!u)throw new rt(et.MissingPaymentToken);return{additionalAction:t,authToken:u,checkout:i,config:r,order:a,orderMeta:s,payment:d,paymentMethod:c,paymentMethodMeta:l}}}class Iy{constructor(e){this._store=e}create(e,t,n){const i=Object.keys(t.fields).reduce((i,r)=>{const o=t.fields[r];return o?[...i,new gy(r,o.containerId,o.placeholder||"",o.accessibilityLabel||"",t.styles||{},new Pn(e),new Yn(e),new kn(new mn),n,"instrumentId"in o?this._getCardInstrument(o.instrumentId):void 0)]:i},[]);return new Sy(i,new Yn(e),new wy(this._store),pe(t,"onBlur","onEnter","onFocus","onCardTypeChange","onValidate"),new cy(Sn(o())))}_getCardInstrument(e){const{instruments:{getCardInstrument:t}}=this._store.getState(),n=t(e);if(!n)throw new rt(et.MissingPaymentInstrument);return n}}!function(e){e.SubmitPaymentRequested="SUBMIT_PAYMENT_REQUESTED",e.SubmitPaymentSucceeded="SUBMIT_PAYMENT_SUCCEEDED",e.SubmitPaymentFailed="SUBMIT_PAYMENT_FAILED",e.InitializeOffsitePaymentRequested="INITIALIZE_OFFSITE_PAYMENT_REQUESTED",e.InitializeOffsitePaymentSucceeded="INITIALIZE_OFFSITE_PAYMENT_SUCCEEDED",e.InitializeOffsitePaymentFailed="INITIALIZE_OFFSITE_PAYMENT_FAILED"}(vy||(vy={}));class Cy{constructor(e,t,n,i){this._paymentRequestSender=e,this._orderActionCreator=t,this._paymentRequestTransformer=n,this._paymentHumanVerificationHandler=i,this.initializeOffsitePayment=({methodId:e,gatewayId:t,instrumentId:n,target:i,promise:r,shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a})=>s=>{let d;n?d={formattedPayload:{bigpay_token:n}}:o&&(d={formattedPayload:{vault_payment_instrument:o,set_as_default_stored_instrument:a||null}});const c=this._paymentRequestTransformer.transform({gatewayId:t,methodId:e,paymentData:d},s.getState());return g(C(l(vy.InitializeOffsitePaymentRequested)),Promise.race([this._paymentRequestSender.initializeOffsitePayment(c,i),r].filter(Boolean)).then(()=>l(vy.InitializeOffsitePaymentSucceeded))).pipe(P(e=>Je(vy.InitializeOffsitePaymentFailed,e)))}}submitPayment(e){return t=>g(C(l(vy.SubmitPaymentRequested)),v(()=>{return n=this,i=void 0,o=function*(){try{return yield this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(e,t.getState()))}catch(n){const i=yield this._paymentHumanVerificationHandler.handle(n);return yield this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(Object.assign(Object.assign({},e),{additionalAction:i}),t.getState()))}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}).pipe(M(({body:e})=>g(this._orderActionCreator.loadCurrentOrder()(t),C(l(vy.SubmitPaymentSucceeded,e)))))).pipe(P(e=>Je(vy.SubmitPaymentFailed,e)))}}class by{constructor(e){this._client=e}submitPayment(e){return new Promise((t,n)=>{this._client.submitPayment(e,(e,i)=>{e?n(this._transformResponse(e)):t(this._transformResponse(i))})})}initializeOffsitePayment(e,t){return new Promise(()=>{this._client.initializeOffsitePayment(e,null,t)})}_transformResponse(e){return{headers:e.headers,body:e.data,status:e.status,statusText:e.statusText}}}function Py(e,t){let n;return function(e){return void 0!==e.id}(e)?n=e.id:t&&t.length&&(n=t[0].id),{id:n,firstName:e.firstName,lastName:e.lastName,company:e.company,addressLine1:e.address1,addressLine2:e.address2,city:e.city,province:e.stateOrProvince,provinceCode:e.stateOrProvinceCode,postCode:e.postalCode,country:e.country,countryCode:e.countryCode,phone:e.phone,customFields:e.customFields}}const Oy=["per_item_discount","percentage_discount","per_total_discount","shipping_discount","free_shipping"];function Ey(e){return{code:e.code,discount:e.displayName,discountType:Oy.indexOf(e.couponType)}}function Ay(e){return{code:e.code,discountedAmount:e.used,remainingBalance:e.remaining,giftCertificate:{balance:e.balance,code:e.code,purchaseDate:e.purchaseDate}}}function Ty(e){const t=[];return(e||[]).forEach(e=>{(e.banners||[]).forEach(e=>{t.push({placeholders:[],discountType:null,message:"",messageHtml:e.text})})}),t}function ky(e,t,n="id"){return Object.keys(e).reduce((i,r)=>[...i,...e[r].map(e=>"giftCertificates"===r?function(e,t){const n=new fd(t);return{id:e.id,imageUrl:"",name:e.name,amount:e.amount,amountAfterDiscount:e.amount,discount:0,integerAmount:n.toInteger(e.amount),integerAmountAfterDiscount:n.toInteger(e.amount),integerUnitPrice:n.toInteger(e.amount),integerUnitPriceAfterDiscount:n.toInteger(e.amount),integerDiscount:0,quantity:1,sender:e.sender,recipient:e.recipient,type:"ItemGiftCertificateEntity",attributes:[],variantId:null}}(e,t):function(e,t,n,i="id"){const r=new fd(n);return{id:e[i],imageUrl:e.imageUrl,amount:e.extendedListPrice,amountAfterDiscount:e.extendedSalePrice,discount:e.discountAmount,integerAmount:r.toInteger(e.extendedListPrice),integerAmountAfterDiscount:r.toInteger(e.extendedSalePrice),integerDiscount:r.toInteger(e.discountAmount),integerUnitPrice:r.toInteger(e.listPrice),integerUnitPriceAfterDiscount:r.toInteger(e.salePrice),downloadsPageUrl:e.downloadPageUrl,name:e.name,quantity:e.quantity,brand:e.brand,sku:e.sku,categoryNames:e.categoryNames,variantId:e.variantId,productId:e.productId,attributes:(e.options||[]).map(e=>({name:e.name,value:e.value})),addedByPromotion:e.addedByPromotion,type:t}}(e,function(e){switch(e){case"physicalItems":return"ItemPhysicalEntity";case"digitalItems":return"ItemDigitalEntity";case"giftCertificates":return"ItemGiftCertificateEntity";default:return""}}(r),t,n))],[])}function Dy(e){const t=e.cart.currency.decimalPlaces,n=new fd(t);return{id:e.cart.id,items:ky(e.cart.lineItems,t),currency:e.cart.currency.code,coupon:{discountedAmount:ye(e.cart.coupons,(e,t)=>e+t.discountedAmount,0),coupons:e.cart.coupons.map(Ey)},discount:{amount:e.cart.discountAmount,integerAmount:n.toInteger(e.cart.discountAmount)},discountNotifications:Ty(e.promotions),giftCertificate:{totalDiscountedAmount:ye(e.giftCertificates,(e,t)=>e+t.used,0),appliedGiftCertificates:ne(e.giftCertificates.map(Ay),"code")},shipping:{amount:e.shippingCostTotal,integerAmount:n.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:n.toInteger(e.shippingCostBeforeDiscount),required:ve(e.cart.lineItems.physicalItems,e=>e.isShippingRequired)},subtotal:{amount:e.subtotal,integerAmount:n.toInteger(e.subtotal)},storeCredit:{amount:e.customer?e.customer.storeCredit:0},taxSubtotal:{amount:e.taxTotal,integerAmount:n.toInteger(e.taxTotal)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:n.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:n.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.grandTotal,integerAmount:n.toInteger(e.grandTotal)}}}var My;!function(e){e.APPLEPAY="applepay",e.AMAZON_PAY_V2="amazonpay",e.BRAINTREE_PAYPAL="braintreepaypal",e.BRAINTREE_VENMO="braintreevenmo",e.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",e.GOOGLEPAY_ADYENV2="googlepayadyenv2",e.GOOGLEPAY_ADYENV3="googlepayadyenv3",e.GOOGLEPAY_AUTHORIZENET="googlepayauthorizenet",e.GOOGLEPAY_BNZ="googlepaybnz",e.GOOGLEPAY_BRAINTREE="googlepaybraintree",e.GOOGLEPAY_CHECKOUTCOM="googlepaycheckoutcom",e.GOOGLEPAY_CYBERSOURCEV2="googlepaycybersourcev2",e.GOOGLEPAY_ORBITAL="googlepayorbital",e.GOOGLEPAY_STRIPE="googlepaystripe",e.GOOGLEPAY_STRIPEUPE="googlepaystripeupe",e.GOOGLEPAY_WORLDPAYACCESS="googlepayworldpayaccess",e.PAYPALEXPRESS="paypalexpress"}(My||(My={}));const zy=My;function Ny(e,t){const n=e.firstName||t.firstName||"",i=e.lastName||t.lastName||"";return{addresses:(e.addresses||[]).map(e=>Py(e)),customerId:e.id,isGuest:e.isGuest,storeCredit:e.storeCredit,email:e.email||t.email||"",firstName:n,lastName:i,name:e.fullName||[n,i].join(" "),customerGroupName:e.customerGroup&&e.customerGroup.name}}class xy{format(e){const[t="",n=""]=e.split(new RegExp("\\s*/\\s*")),i=t.slice(0,2),r=4===n.length?n.slice(-2):n?n.slice(0,2):t.slice(2);return e.length<2?t:e.length>3&&!r?i:`${i} / ${r}`}toObject(e){const[t="",n=""]=e.split(new RegExp("\\s*/\\s*"));return/^\d+$/.test(t)&&/^\d+$/.test(n)?{month:1===t.length?`0${t}`:t.slice(0,2),year:2===n.length?`20${n}`:n.slice(0,4)}:{month:"",year:""}}}class Ry{format(e){const{card:t}=Me(e);if(!t)return e;const n=ae(De(e).map(e=>ae(e.lengths))),i=this.unformat(e).slice(0,n);return t.gaps.filter(e=>i.length>e).reduce((e,t,n)=>[e.slice(0,t+n),e.slice(t+n)].join(" "),i)}unformat(e){const{card:t}=Me(e);return t?e.replace(new RegExp(" ","g"),""):e}}function Fy(e,t={}){const n=e.currency.decimalPlaces,i=new fd(n);return{id:e.orderId,items:ky(e.lineItems,e.currency.decimalPlaces,"productId"),orderId:e.orderId,currency:e.currency.code,customerCanBeCreated:e.customerCanBeCreated,payment:jy(e.payments,t.payment),subtotal:{amount:e.baseAmount,integerAmount:i.toInteger(e.baseAmount)},coupon:{discountedAmount:ye(e.coupons,(e,t)=>e+t.discountedAmount,0),coupons:e.coupons.map(Ey)},discount:{amount:e.discountAmount,integerAmount:i.toInteger(e.discountAmount)},token:t.orderToken,callbackUrl:t.callbackUrl,discountNotifications:[],giftCertificate:By(e.payments),socialData:qy(e),status:e.status,hasDigitalItems:e.hasDigitalItems,isDownloadable:e.isDownloadable,isComplete:e.isComplete,shipping:{amount:e.shippingCostTotal,integerAmount:i.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:i.toInteger(e.shippingCostBeforeDiscount)},storeCredit:{amount:Ly(e.payments)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:i.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:i.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.orderAmount,integerAmount:e.orderAmountAsInteger}}}function Ly(e){const t=B(e,{providerId:"storecredit"});return t?t.amount:0}function By(e){const t=L(e,{providerId:"giftcertificate"});return{totalDiscountedAmount:ye(t,(e,t)=>t.amount+e,0),appliedGiftCertificates:ne(t.map(e=>({code:e.detail.code,discountedAmount:e.amount,remainingBalance:e.detail.remaining,giftCertificate:{balance:e.amount+e.detail.remaining,code:e.detail.code,purchaseDate:""}})),"code")}}function jy(e,t={}){const n=B(e,Uy);return n?{id:n.providerId,status:(i=n.detail.step,`PAYMENT_STATUS_${i}`),helpText:n.detail.instructions,returnUrl:t.returnUrl}:{};var i}function Uy(e){return"giftcertificate"!==e.providerId&&"storecredit"!==e.providerId}function qy(e){const t={};return[...e.lineItems.physicalItems,...e.lineItems.digitalItems].forEach(e=>{var n;t[e.id]=(n=e,["fb","tw","gp"].reduce((e,t)=>{const i=n.socialMedia&&B(n.socialMedia,e=>e.code===t);return i?(e[t]={name:n.name,description:n.name,image:n.imageUrl,url:i.link,shareText:i.text,sharingLink:i.link,channelName:i.channel,channelCode:i.code},e):e},{}))}),t}function Vy(e,t){return{description:e.description,module:e.type,price:e.cost,id:e.id,selected:t,isRecommended:e.isRecommended,imageUrl:e.imageUrl,transitTime:e.transitTime}}class Gy{constructor(){this._cardExpiryFormatter=new xy,this._cardNumberFormatter=new Ry}transform(e,t){const n=t.billingAddress.getBillingAddress(),i=t.checkout.getCheckout(),r=t.customer.getCustomer(),o=t.order.getOrder(),a=t.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId),s=this._mapShippingAddress(t,a),d=t.consignments.getConsignments(),c=t.consignments.getShippingOption(),l=t.config.getStoreConfig(),u=t.config.getContextConfig(),h=t.instruments.getInstrumentsMeta(),p=t.paymentMethods.getPaymentMethodsMeta(),m=t.order.getOrderMeta(),y=r&&n&&Ny(r,n),g=h&&e.paymentData&&(_y(e.paymentData)||function(e){const t=e.formattedPayload;return!!t&&("string"==typeof t.bigpay_token||Boolean(t.bigpay_token&&t.bigpay_token.token))}(e.paymentData))?`${t.payment.getPaymentToken()}, ${h.vaultAccessToken}`:t.payment.getPaymentToken();if(!g)throw new rt(et.MissingPaymentToken);return{additionalAction:e.additionalAction,authToken:g,customer:y,billingAddress:n&&Py(n),shippingAddress:s&&Py(s,d),shippingOption:c&&Vy(c,!0),cart:i&&Dy(i),order:o&&Fy(o,m),orderMeta:m,payment:e.paymentData,paymentMethod:a&&this._transformPaymentMethod(a),quoteMeta:{request:Object.assign(Object.assign({},p),{geoCountryCode:u&&u.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:pe(l&&l.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}}transformWithHostedFormData(e,t,n){const{additionalAction:i,authToken:r,checkout:o,config:a,order:s,orderMeta:d,payment:c={},paymentMethod:l,paymentMethodMeta:u}=t,h=o&&o.consignments[0],p=h&&h.shippingAddress,m=h&&h.selectedShippingOption;return{additionalAction:i,authToken:r,paymentMethod:l&&this._transformPaymentMethod(l),customer:s&&s.billingAddress&&o&&Ny(o.customer,s.billingAddress),billingAddress:s&&s.billingAddress&&Py(s.billingAddress),shippingAddress:p&&o&&Py(p,o.consignments),shippingOption:m&&Vy(m,!0),cart:o&&Dy(o),order:s&&Fy(s,d),orderMeta:d,payment:this._transformHostedInputValues(e,c,n),quoteMeta:{request:Object.assign(Object.assign({},u),{geoCountryCode:a&&a.context.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:a&&pe(a.storeConfig.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}}_transformPaymentMethod(e){if("multi-option"===e.method&&!e.gateway)return Object.assign(Object.assign({},e),{gateway:e.id});if(e.initializationData&&e.initializationData.gateway)return Object.assign(Object.assign({},e),{id:e.initializationData.gateway});if("worldpayaccess"===e.gateway){if("credit_card"===e.id)return Object.assign(Object.assign({},e),{id:"worldpayaccess",method:"credit-card"});if("open_banking"===e.id)return Object.assign(Object.assign({},e),{id:"worldpayaccess",method:"open_banking"})}return e.id===zy.BRAINTREE_VENMO?Object.assign(Object.assign({},e),{id:zy.BRAINTREE_PAYPAL}):e}_transformHostedInputValues(e,t,n){return"instrumentId"in t?Object.assign(Object.assign({},t),{ccCvv:e.cardCodeVerification,ccNumber:e.cardNumberVerification&&this._cardNumberFormatter.unformat(e.cardNumberVerification),hostedFormNonce:n}):Object.assign(Object.assign({},t),{ccCvv:e.cardCode,ccExpiry:this._cardExpiryFormatter.toObject(e.cardExpiry||""),ccName:e.cardName||"",ccNumber:this._cardNumberFormatter.unformat(e.cardNumber||""),hostedFormNonce:n})}_mapShippingAddress(e,t){var n,i,r,o;if(t){const a=null===(i=null===(n=t.initializationData)||void 0===n?void 0:n.bopis)||void 0===i?void 0:i.enabled,s=null===(o=null===(r=t.initializationData)||void 0===r?void 0:r.bopis)||void 0===o?void 0:o.requiredAddress,d=e.consignments.getConsignments(),c=null==d?void 0:d.every(e=>e.selectedPickupOption);if(a&&c&&"none"===s)return}return e.shippingAddress.getShippingAddress()}}const Hy=e=>{const{type:t,initializationStrategy:n}=e;return t===Zm.PPSDK&&"string"==typeof(null==n?void 0:n.type)};class Wy extends Vt{getByMethod(e){if(!e)return this.get();const t=this._getToken(e),n=[e.gateway,e.id].filter(e=>null!=e).join("-");return this.get(t,n)}_getToken(e){if(Hy(e))return Zm.PPSDK;if("klarna"===e.gateway)return Zm.KLARNAV2;const t=e.gateway||e.id;if(this._hasFactoryForMethod(t))return t;if("PAYMENT_TYPE_OFFLINE"===e.type)return Zm.OFFLINE;throw new qt(`'${t}' is not registered.`)}_hasFactoryForMethod(e){return this._hasFactory(e)}}const $y="FINALIZE";class Yy extends qt{constructor(e){let t="Unable to submit payment for the order because the payload is invalid.";e&&(t=`${t} Make sure the following fields are provided correctly: ${e.join(", ")}.`),super(t),this.name="PaymentArgumentInvalidError"}}var Ky=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r(this._shouldRenderHostedForm=!0,this._hostedForm=r,this._store.getState()))}deinitialize(e){return this._hostedForm&&this._hostedForm.detach(),Promise.resolve(this._store.getState())}_executeWithoutHostedForm(e,t){const{payment:n}=e,i=Ky(e,["payment"]),r=n&&n.paymentData;if(!n||!r)throw new Yy(["payment.paymentData"]);return this._store.dispatch(this._orderActionCreator.submitOrder(i,t)).then(()=>this._store.dispatch(this._paymentActionCreator.submitPayment(Object.assign(Object.assign({},n),{paymentData:r}))))}_executeWithHostedForm(e,t){const{payment:n}=e,i=Ky(e,["payment"]),r=this._hostedForm;if(!r)throw new yn(cn.PaymentNotInitialized);if(!n||!n.methodId)throw new Yy(["payment.methodId"]);return r.validate().then(()=>this._store.dispatch(this._orderActionCreator.submitOrder(i,t))).then(()=>r.submit(n)).then(()=>this._store.dispatch(this._orderActionCreator.loadCurrentOrder()))}_isHostedPaymentFormEnabled(e,t){if(!e)return!1;const{paymentMethods:{getPaymentMethodOrThrow:n}}=this._store.getState();return!0===n(e,t).config.isHostedFormEnabled}_isHostedFieldAvailable(e){return!Ce(e&&e.creditCard&&e.creditCard.form.fields).every(J)}}class Zy extends Jy{constructor(e,t,n,i,r){super(e,t,n,i),this._formPoster=r}execute(e,t){return super.execute(e,t).catch(e=>e instanceof Ot&&ve(e.body.errors,{code:"three_d_secure_required"})?new Promise(()=>{this._formPoster.postForm(e.body.three_ds_result.acs_url,{PaReq:e.body.three_ds_result.payer_auth_request,TermUrl:e.body.three_ds_result.callback_url,MD:e.body.three_ds_result.merchant_data})}):Promise.reject(e))}finalize(e){const t=this._store.getState(),n=t.order.getOrder();return n&&t.payment.getPaymentStatus()===$y?this._store.dispatch(this._orderActionCreator.finalizeOrder(n.orderId,e)):Promise.reject(new Ym)}}class Qy extends it{constructor(e){super(e||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}const Xy="redirecting";class eg{constructor(){this._isRedirecting=this.currentUrlHasRedirectingParam()}isRedirecting(){return this._isRedirecting}setRedirecting(e){e?this.setRedirectingParamOnUrl():this.removeRedirectingParamFromUrl(),this._isRedirecting=e}currentUrlHasRedirectingParam(){return Xy in this.getCurrentUrl().query}getCurrentUrl(){return Ne(window.location.href)}replaceCurrentUrl(e){window.history.replaceState(null,"",e)}setRedirectingParamOnUrl(){if(this.currentUrlHasRedirectingParam())return;const e=this.getCurrentUrl(),t=Object.assign(Object.assign({},e),{query:Object.assign(Object.assign({},e.query),{[Xy]:"true"})});this.replaceCurrentUrl(xe(t))}removeRedirectingParamFromUrl(){this.currentUrlHasRedirectingParam()&&this.replaceCurrentUrl(ze(window.location.href,[Xy]))}}const tg=he([e=>"continue"===V(e,"type")&&"redirect"===V(e,"code")&&(e=>{const t=V(e,"form_fields");return X(V(e,"url"))&&(ee(t)||Z(t))})(V(e,"parameters")),e=>"continue"===V(e,"type")&&"resubmit_with_human_verification"===V(e,"code")&&(e=>{const t=V(e,"available_methods");return W(t)})(V(e,"parameters"))]);class ng{constructor(e,t){this._formPoster=e,this._humanVerificationHandler=t}handle(e,t){switch(e.code){case"redirect":return(({url:e,form_fields:t},n)=>{const i=new eg;return i.isRedirecting()?(i.setRedirecting(!1),Promise.reject(new Qy)):(i.setRedirecting(!0),t?n.postForm(e,t):window.location.assign(e),new Promise(ce))})(e.parameters,this._formPoster);case"resubmit_with_human_verification":return(({available_methods:e},t,n)=>{return i=void 0,r=void 0,a=function*(){if(!n)throw new Error("PPSDK human verification callback function is missing.");if(!t)throw new Error("PPSDK human verification handler is missing.");if(0===e.length)throw Error("Human verification method is missing.");const{id:i,parameters:r}=e[0],o=yield t.handle(i,r.key);return n(o)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a})(e.parameters,this._humanVerificationHandler,null==t?void 0:t.humanVerification)}}}class ig{constructor(e){this._continueHandler=e}handle(e,t){const{body:n}=e;return(e=>"success"===V(e,"type"))(n)?Promise.resolve():(e=>tg(e))(n)?this._continueHandler.handle(n,null==t?void 0:t.continue):(e=>"failure"===V(e.body,"type")&&X(V(e.body,"code")))(e)?(e=>{return Promise.reject(new Ot((t=e,Object.assign(Object.assign({},t),{body:{errors:[{code:t.body.code}]}}))));var t})(e):((e=>{V(e.body,"type")})(e),(e=>Promise.reject(new Ot(e)))(e))}}const rg="completed-payments";class og{constructor(e){this._browserStorage=e}isCompleted(e){return this.getCompletedPayments().indexOf(e)>=0}setCompleted(e){const t=this.getCompletedPayments();t.push(e),this.setCompletedPayments(t)}getCompletedPayments(){return this._browserStorage.getItem(rg)||[]}setCompletedPayments(e){this._browserStorage.setItem(rg,e)}}var ag,sg=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class dg{constructor(e,t,n,i,r){this._store=e,this._orderActionCreator=t,this._subStrategyRegistry=n,this._paymentResumer=i,this._completedPayments=new og(r)}execute(e,t){var n;return sg(this,void 0,void 0,function*(){const{bigpayBaseUrl:i}=this._store.getState().config.getStoreConfigOrThrow().paymentSettings;if(!(null==t?void 0:t.methodId))throw new qt('Unable to submit payment because "options.methodId" argument is not provided.');const{methodId:r}=t,{payment:o}=e,a=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{throw this._completedPayments.setCompleted(i),e}),this._store.getState()})}initialize(e){return sg(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new qt('Unable to submit payment because "options.methodId" argument is not provided.');const t=((e,t)=>{const n=e.getState().paymentMethods.getPaymentMethod(t);if(n&&Hy(n))return n})(this._store,e.methodId);if(!t)throw new yn(cn.PaymentNotInitialized);if(this._subStrategy=this._subStrategyRegistry.getByMethod(t),!this._subStrategy)throw new yn(cn.PaymentNotInitialized);return yield this._subStrategy.initialize(e),this._store.getState()})}deinitialize(e){var t;return sg(this,void 0,void 0,function*(){return null===(t=this._subStrategy)||void 0===t||t.deinitialize(),this._store.getState()})}}!function(e){e.CARD="card_ui",e.NONE="none",e.UNSUPPORTED="unsupported"}(ag||(ag={}));const cg=N([[e=>"card_ui"===e.type,x(ag.CARD)],[e=>"none"===e.type,x(ag.NONE)],[fe,x(ag.UNSUPPORTED)]]);class lg extends Vt{getByMethod(e){const t=cg(e.initializationStrategy);return this.get(t)}}var ug=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class hg{constructor(e,t,n,i){this._store=e,this._orderActionCreator=t,this._hostedFormFactory=n,this._ppsdkStepHandler=i}execute(e){return ug(this,void 0,void 0,function*(){const t=this._hostedForm;if(!t)throw new yn(cn.PaymentNotInitialized);const{additionalAction:n,payment:i}=e;if(!i||!i.methodId)throw new Yy(["payment.methodId"]);yield t.validate();const{payload:r}=yield t.submit(i,n),{response:o}=r;yield this._ppsdkStepHandler.handle(o,{continue:{humanVerification:t=>ug(this,void 0,void 0,function*(){return this.execute(Object.assign({additionalAction:t},e))})}}),yield this._store.dispatch(this._orderActionCreator.loadCurrentOrder())})}initialize(e){return ug(this,void 0,void 0,function*(){const t=e&&e.creditCard&&e.creditCard.form,{config:n,checkout:i}=this._store.getState(),{paymentSettings:{bigpayBaseUrl:r=""}={}}=n.getStoreConfig()||{},o=i.getCheckoutOrThrow().id;if(!t)throw new qt;const a=t&&this._hostedFormFactory.create(r,t,o);yield a.attach(),this._hostedForm=a})}deinitialize(){this._hostedForm&&this._hostedForm.detach()}}class pg{constructor(e,t){this._requestSender=e,this._stepHandler=t}execute({methodId:e,bigpayBaseUrl:t,token:n}){const i={credentials:!1,body:{payment_method_id:e},headers:{authorization:n,"X-XSRF-TOKEN":null}};return this._requestSender.post(`${t}/payments`,i).then(e=>this._stepHandler.handle(e))}initialize(){return Promise.resolve()}deinitialize(){}}var mg,yg,gg=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vg{constructor(e,t){this._requestSender=e,this._stepHandler=t}resume({paymentId:e,bigpayBaseUrl:t,orderId:n}){return gg(this,void 0,void 0,function*(){const i={credentials:!1,headers:{authorization:yield this._getToken(n).catch(()=>{throw new Ym}),"X-XSRF-TOKEN":null}};return this._requestSender.get(`${t}/payments/${e}`,i).then(e=>this._stepHandler.handle(e))})}_getToken(e){return gg(this,void 0,void 0,function*(){const t={params:{order_id:e}};return this._requestSender.get("/api/storefront/payments/auth-token",t).then(({body:e})=>e.auth_token)})}}class fg{constructor(e){this._requestSender=e}createBuyNowCart(e,{timeout:t}={}){const n=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post("/api/storefront/carts",{body:e,headers:n,timeout:t})}}!function(e){e.UpdatePaymentProviderCustomer="UPDATE_PAYMENT_PROVIDER_CUSTOMER"}(mg||(mg={}));class Sg{updatePaymentProviderCustomer(e){return C(l(mg.UpdatePaymentProviderCustomer,e))}}!function(e){e.ForgetCheckoutRemoteCustomerRequested="FORGET_CHECKOUT_REMOTE_CUSTOMER_REQUESTED",e.ForgetCheckoutRemoteCustomerSucceeded="FORGET_CHECKOUT_REMOTE_CUSTOMER_SUCCEEDED",e.ForgetCheckoutRemoteCustomerFailed="FORGET_CHECKOUT_REMOTE_CUSTOMER_FAILED",e.InitializeRemoteBillingRequested="INITIALIZE_REMOTE_BILLING_REQUESTED",e.InitializeRemoteBillingSucceeded="INITIALIZE_REMOTE_BILLING_SUCCEEDED",e.InitializeRemoteBillingFailed="INITIALIZE_REMOTE_BILLING_FAILED",e.InitializeRemoteShippingRequested="INITIALIZE_REMOTE_SHIPPING_REQUESTED",e.InitializeRemoteShippingSucceeded="INITIALIZE_REMOTE_SHIPPING_SUCCEEDED",e.InitializeRemoteShippingFailed="INITIALIZE_REMOTE_SHIPPING_FAILED",e.InitializeRemotePaymentRequested="INITIALIZE_REMOTE_PAYMENT_REQUESTED",e.InitializeRemotePaymentSucceeded="INITIALIZE_REMOTE_PAYMENT_SUCCEEDED",e.InitializeRemotePaymentFailed="INITIALIZE_REMOTE_PAYMENT_FAILED",e.LoadRemoteSettingsRequested="LOAD_REMOTE_SETTINGS_REQUESTED",e.LoadRemoteSettingsSucceeded="LOAD_REMOTE_SETTINGS_SUCCEEDED",e.LoadRemoteSettingsFailed="LOAD_REMOTE_SETTINGS_FAILED",e.SignOutRemoteCustomerRequested="SIGN_OUT_REMOTE_CUSTOMER_REQUESTED",e.SignOutRemoteCustomerSucceeded="SIGN_OUT_REMOTE_CUSTOMER_SUCCEEDED",e.SignOutRemoteCustomerFailed="SIGN_OUT_REMOTE_CUSTOMER_FAILED",e.UpdateRemoteCheckout="UPDATE_REMOTE_CHECKOUT"}(yg||(yg={}));var _g;class wg{constructor(e,t){this._remoteCheckoutRequestSender=e,this._checkoutActionCreator=t}initializeBilling(e,t,n){return m.create(i=>{i.next(l(yg.InitializeRemoteBillingRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializeBilling(e,t,n).then(({body:t={}})=>{i.next(l(yg.InitializeRemoteBillingSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(yg.InitializeRemoteBillingFailed,t,{methodId:e}))})})}initializeShipping(e,t,n){return m.create(i=>{i.next(l(yg.InitializeRemoteShippingRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializeShipping(e,t,n).then(({body:t={}})=>{i.next(l(yg.InitializeRemoteShippingSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(yg.InitializeRemoteShippingFailed,t,{methodId:e}))})})}initializePayment(e,t,n){return m.create(i=>{i.next(l(yg.InitializeRemotePaymentRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializePayment(e,t,n).then(({body:t={}})=>{i.next(l(yg.InitializeRemotePaymentSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(yg.InitializeRemotePaymentFailed,t,{methodId:e}))})})}loadSettings(e,t){return m.create(n=>{n.next(l(yg.LoadRemoteSettingsRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.loadSettings(e,t).then(({body:t})=>{n.next(l(yg.LoadRemoteSettingsSucceeded,t,{methodId:e})),n.complete()}).catch(t=>{n.error(h(yg.LoadRemoteSettingsFailed,t,{methodId:e}))})})}signOut(e,t){return m.create(n=>{n.next(l(yg.SignOutRemoteCustomerRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.signOut(e,t).then(()=>{n.next(l(yg.SignOutRemoteCustomerSucceeded,void 0,{methodId:e})),n.complete()}).catch(t=>{n.error(h(yg.SignOutRemoteCustomerFailed,t,{methodId:e}))})})}forgetCheckout(e,t){return g(C(l(yg.ForgetCheckoutRemoteCustomerRequested,void 0,{methodId:e})),v(()=>{return n=this,i=void 0,o=function*(){return yield this._remoteCheckoutRequestSender.forgetCheckout(t),yield this._checkoutActionCreator.loadCurrentCheckout(),l(yg.ForgetCheckoutRemoteCustomerSucceeded,void 0,{methodId:e})},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(t=>Je(yg.ForgetCheckoutRemoteCustomerFailed,t,{methodId:e})))}updateCheckout(e,t){return l(yg.UpdateRemoteCheckout,t,{methodId:e})}}class Ig{constructor(e){this._requestSender=e}initializeBilling(e,t,{timeout:n}={}){const i=`/remote-checkout/${e}/billing`;return this._requestSender.get(i,{params:t,timeout:n,headers:Xe})}initializeShipping(e,t,{timeout:n}={}){const i=`/remote-checkout/${e}/shipping`;return this._requestSender.get(i,{params:t,timeout:n,headers:Xe})}initializePayment(e,t,{timeout:n}={}){const i=`/remote-checkout/${e}/payment`;return this._requestSender.get(i,{params:t,timeout:n,headers:Xe})}loadSettings(e,{timeout:t}={}){const n=`/remote-checkout/${e}/settings`;return this._requestSender.get(n,{timeout:t,headers:Xe})}signOut(e,{timeout:t}={}){const n=`/remote-checkout/${e}/signout`;return this._requestSender.get(n,{timeout:t,headers:Xe})}generateToken({timeout:e}={}){return this._requestSender.get("/remote-checkout-token",{timeout:e,headers:Xe})}trackAuthorizationEvent({timeout:e}={}){return this._requestSender.post("/remote-checkout/events/shopper-checkout-service-provider-authorization-requested",{timeout:e,headers:Xe})}forgetCheckout({timeout:e}={}){return this._requestSender.post("/remote-checkout/forget-checkout",{timeout:e,headers:Xe})}}!function(e){e.CreateConsignmentsRequested="CREATE_CONSIGNMENTS_REQUESTED",e.CreateConsignmentsSucceeded="CREATE_CONSIGNMENTS_SUCCEEDED",e.CreateConsignmentsFailed="CREATE_CONSIGNMENTS_FAILED",e.UpdateConsignmentRequested="UPDATE_CONSIGNMENT_REQUESTED",e.UpdateConsignmentSucceeded="UPDATE_CONSIGNMENT_SUCCEEDED",e.UpdateConsignmentFailed="UPDATE_CONSIGNMENT_FAILED",e.DeleteConsignmentRequested="DELETE_CONSIGNMENT_REQUESTED",e.DeleteConsignmentSucceeded="DELETE_CONSIGNMENT_SUCCEEDED",e.DeleteConsignmentFailed="DELETE_CONSIGNMENT_FAILED",e.UpdateShippingOptionRequested="UPDATE_SHIPPING_OPTION_REQUESTED",e.UpdateShippingOptionSucceeded="UPDATE_SHIPPING_OPTION_SUCCEEDED",e.UpdateShippingOptionFailed="UPDATE_SHIPPING_OPTION_FAILED",e.LoadShippingOptionsRequested="LOAD_SHIPPING_OPTIONS_REQUESTED",e.LoadShippingOptionsSucceeded="LOAD_SHIPPING_OPTIONS_SUCCEEDED",e.LoadShippingOptionsFailed="LOAD_SHIPPING_OPTIONS_FAILED"}(_g||(_g={}));class Cg{constructor(e,t){this._consignmentRequestSender=e,this._checkoutRequestSender=t}unassignItemsByAddress(e,t){return n=>{const i=n.getState();if(!i.checkout.getCheckout())throw new rt(et.MissingCheckout);const r=this._consignmentHasAddress(e)?e.address:e.shippingAddress,o=i.consignments.getConsignmentByAddress(r);if(!o)throw new qt("No consignment found for the specified address");const a=this._removeLineItems(e.lineItems,o,i.cart.getCart());return a.length?this.updateConsignment({id:o.id,address:r,lineItems:a},t)(n):this.deleteConsignment(o.id,t)(n)}}assignItemsByAddress(e,t){return n=>{const i=n.getState(),r=this._consignmentHasAddress(e)?e.address:e.shippingAddress,o=i.consignments.getConsignmentByAddress(r);return this._createOrUpdateConsignment({id:o&&o.id,address:r,lineItems:this._addLineItems(e.lineItems,o,i.cart.getCart())},t)(n)}}selectShippingOption(e,t){return n=>m.create(i=>{const r=n.getState(),o=r.checkout.getCheckout(),a=r.consignments.getConsignments();if(!o)throw new rt(et.MissingCheckout);if(!a||!a.length)throw new rt(et.MissingConsignments);const s={id:a[0].id,shippingOptionId:e},d={id:a[0].id};i.next(l(_g.UpdateShippingOptionRequested,void 0,d)),this._consignmentRequestSender.updateConsignment(o.id,s,t).then(({body:e})=>{i.next(l(_g.UpdateShippingOptionSucceeded,e,d)),i.complete()}).catch(e=>{i.error(h(_g.UpdateShippingOptionFailed,e,d))})})}loadShippingOptions(e){return t=>m.create(n=>{const i=t.getState().checkout.getCheckout();if(!i)throw new rt(et.MissingCheckout);n.next(l(_g.LoadShippingOptionsRequested)),this._checkoutRequestSender.loadCheckout(i.id,Object.assign(Object.assign({},e),{params:{include:[zt.AvailableShippingOptions]}})).then(({body:e})=>{n.next(l(_g.LoadShippingOptionsSucceeded,e)),n.complete()}).catch(e=>{n.error(h(_g.LoadShippingOptionsFailed,e))})})}updateAddress(e,t){return n=>{const i=this._getUpdateAddressRequestBody(e,n),r=n.getState().consignments.getConsignments();return r&&r.length&&(i.id=r[0].id),this._createOrUpdateConsignment(i,t)(n)}}createConsignments(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r||!r.id)throw new rt(et.MissingCheckout);i.next(l(_g.CreateConsignmentsRequested)),this._consignmentRequestSender.createConsignments(r.id,e,t).then(({body:e})=>{i.next(l(_g.CreateConsignmentsSucceeded,e)),i.complete()}).catch(e=>{i.error(h(_g.CreateConsignmentsFailed,e))})})}updateConsignment(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r||!r.id)throw new rt(et.MissingCheckout);const o={id:e.id};i.next(l(_g.UpdateConsignmentRequested,void 0,o)),this._consignmentRequestSender.updateConsignment(r.id,e,t).then(({body:e})=>{i.next(l(_g.UpdateConsignmentSucceeded,e,o)),i.complete()}).catch(e=>{i.error(h(_g.UpdateConsignmentFailed,e,o))})})}deleteConsignment(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout(),o={id:e};if(!r||!r.id)throw new rt(et.MissingCheckout);i.next(l(_g.DeleteConsignmentRequested,void 0,o)),this._consignmentRequestSender.deleteConsignment(r.id,e,t).then(({body:e})=>{i.next(l(_g.DeleteConsignmentSucceeded,e,o)),i.complete()}).catch(e=>{i.error(h(_g.DeleteConsignmentFailed,e,o))})})}updateShippingOption(e,t){return n=>m.create(i=>{var r;const o=n.getState().checkout.getCheckout(),a=n.getState().consignments.getConsignmentById(e.id);if((null===(r=null==a?void 0:a.selectedShippingOption)||void 0===r?void 0:r.id)===e.shippingOptionId)return void i.complete();if(!o||!o.id)throw new rt(et.MissingCheckout);const s={id:e.id};i.next(l(_g.UpdateShippingOptionRequested,void 0,s)),this._consignmentRequestSender.updateConsignment(o.id,e,t).then(({body:e})=>{i.next(l(_g.UpdateShippingOptionSucceeded,e,s)),i.complete()}).catch(e=>{i.error(h(_g.UpdateShippingOptionFailed,e,s))})})}_createOrUpdateConsignment(e,t){return n=>{const i=n.getState().checkout.getCheckout();if(!i||!i.id)throw new rt(et.MissingCheckout);return this._isUpdateConsignmentRequest(e)?this.updateConsignment(e,t)(n):this.createConsignments([e],t)(n)}}_getUpdateAddressRequestBody(e,t){const n=t.getState().cart.getCart();if(!n)throw new rt(et.MissingCart);const{physicalItems:i,customItems:r=[]}=n.lineItems;return{address:e,lineItems:[...i,...r].map(e=>({itemId:e.id,quantity:e.quantity}))}}_removeLineItems(e,t,n){if(!n)throw new rt(et.MissingCart);return this._hydrateLineItems(t.lineItemIds,n).map(t=>{const n=B(e,e=>e.itemId===t.itemId);return Object.assign(Object.assign({},t),{quantity:n?t.quantity-n.quantity:t.quantity})}).filter(e=>e.quantity>0)}_addLineItems(e,t,n){if(!t)return e;if(!n)throw new rt(et.MissingCart);return e.concat(this._hydrateLineItems(t.lineItemIds,n)).filter(e=>e.quantity>0)}_hydrateLineItems(e,t){return e.map(e=>{const n=B(t.lineItems.physicalItems,t=>t.id===e);return{itemId:e,quantity:n?n.quantity:0}})}_isUpdateConsignmentRequest(e){return!!e.id}_consignmentHasAddress(e){return"object"==typeof e&&"address"in e}}const bg=["consignments.availableShippingOptions","cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","promotions.banners"];class Pg{constructor(e){this._requestSender=e}createConsignments(e,t,{timeout:n,params:{include:i}={}}={}){const r=`/api/storefront/checkouts/${e}/consignments`,o=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(r,{body:t,params:{include:Xt(bg,i)},headers:o,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}updateConsignment(e,t,{timeout:n,params:{include:i}={}}={}){const{id:r}=t,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if("empty_cart"===e.body.type)throw new dt;throw e})}deleteConsignment(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/consignments/${t}`,r=Object.assign({Accept:ct.JsonV1},Xe),o=Ft(bg);return this._requestSender.delete(i,{params:{include:o},headers:r,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}var Og,Eg;!function(e){e.LoadShippingCountriesRequested="LOAD_SHIPPING_COUNTRIES_REQUESTED",e.LoadShippingCountriesSucceeded="LOAD_SHIPPING_COUNTRIES_SUCCEEDED",e.LoadShippingCountriesFailed="LOAD_SHIPPING_COUNTRIES_FAILED"}(Og||(Og={}));class Ag{constructor(e,t){this._shippingCountryRequestSender=e,this._store=t}loadCountries(e){const{checkout:t}=this._store.getState(),n=t.getCheckout(),i=n?n.channelId:null;return m.create(t=>{t.next(l(Og.LoadShippingCountriesRequested)),this._shippingCountryRequestSender.loadCountries(i,e).then(e=>{t.next(l(Og.LoadShippingCountriesSucceeded,e.body.data)),t.complete()}).catch(e=>{t.error(h(Og.LoadShippingCountriesFailed,e))})})}}class Tg{constructor(e,t){this._requestSender=e,this._config=t}loadCountries(e,{timeout:t}={}){const n="/internalapi/v1/shipping/countries"+(e?`?channel_id=${e}`:""),i=Object.assign({"Accept-Language":this._config.locale},Xe);return this._requestSender.get(n,{headers:i,timeout:t})}}!function(e){e.ApplyStoreCreditRequested="APPLY_STORE_CREDIT_REQUESTED",e.ApplyStoreCreditSucceeded="APPLY_STORE_CREDIT_SUCCEEDED",e.ApplyStoreCreditFailed="APPLY_STORE_CREDIT_FAILED"}(Eg||(Eg={}));var kg;class Dg{constructor(e){this._storeCreditRequestSender=e}applyStoreCredit(e,t){return n=>g(C(l(Eg.ApplyStoreCreditRequested)),v(()=>{return i=this,r=void 0,a=function*(){var i;const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);const{id:o}=r,a=null!==(i=null==t?void 0:t.version)&&void 0!==i?i:r.version,{body:s}=yield e?this._storeCreditRequestSender.applyStoreCredit(o,Object.assign(Object.assign({},t),{version:a})):this._storeCreditRequestSender.removeStoreCredit(o,Object.assign(Object.assign({},t),{version:a}));return l(Eg.ApplyStoreCreditSucceeded,s)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a})).pipe(P(e=>Je(Eg.ApplyStoreCreditFailed,e)))}}class Mg{constructor(e){this._requestSender=e}applyStoreCredit(e,{timeout:t,version:n}={}){const i=`/api/storefront/checkouts/${e}/store-credit`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{headers:r,timeout:t,params:{include:Ft(Mt)},body:{version:n}})}removeStoreCredit(e,{timeout:t,version:n}={}){const i=`/api/storefront/checkouts/${e}/store-credit`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.delete(i,{headers:r,timeout:t,params:{include:Ft(Mt)},body:{version:n}})}}!function(e){e.UpdateSubscriptionsRequested="UPDATE_SUBSCRIPTIONS_REQUESTED",e.UpdateSubscriptionsSucceeded="UPDATE_SUBSCRIPTIONS_SUCCEEDED",e.UpdateSubscriptionsFailed="UPDATE_SUBSCRIPTIONS_FAILED"}(kg||(kg={}));class zg extends Ot{constructor(e){super(e),this.name="UpdateSubscriptionsError",this.type="update_subscriptions"}}class Ng{constructor(e){this._subscriptionsRequestSender=e}updateSubscriptions(e,t){return g(C(l(kg.UpdateSubscriptionsRequested)),v(()=>{return n=this,i=void 0,o=function*(){const{body:n}=yield this._subscriptionsRequestSender.updateSubscriptions(e,t);return l(kg.UpdateSubscriptionsSucceeded,n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Je(kg.UpdateSubscriptionsFailed,new zg(e))))}}class xg{constructor(e){this._requestSender=e}updateSubscriptions(e,{timeout:t}={}){const n=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post("/api/storefront/subscriptions",{body:e,headers:n,timeout:t})}}function Rg(e){return Q(e)}const Fg=se(e=>Array.isArray(e)?e.map(e=>Lg(e)):Rg(e)?Object.keys(e).reduce((t,n)=>Object.assign(Object.assign({},t),{[n]:Lg(e[n])}),{}):e);Fg.cache=new WeakMap;const Lg=e=>"object"==typeof e&&null!==e?Fg(e):e;function Bg(e){return(...t)=>Lg(e(...t))}function jg({billingAddress:{getBillingAddress:e,getBillingAddressOrThrow:t},cart:{getCart:n,getCartOrThrow:i,getLocale:r},checkout:{getCheckout:o,getCheckoutOrThrow:a,getOutstandingBalance:s},config:{getContextConfig:d,getHost:c,getLocale:l,getStoreConfig:u,getStoreConfigOrThrow:h,getConfig:p},consignments:{getConsignments:m,getConsignmentsOrThrow:y},countries:{getCountries:g},customer:{getCustomer:v,getCustomerOrThrow:f},instruments:{getCardInstrument:S,getCardInstrumentOrThrow:_,getInstruments:w,getInstrumentsMeta:I},order:{getOrder:C,getOrderOrThrow:b,getOrderMeta:P},payment:{getPaymentToken:O,getPaymentTokenOrThrow:E,getPaymentId:A,getPaymentIdOrThrow:T,getPaymentStatus:k,getPaymentStatusOrThrow:D,getPaymentRedirectUrl:M,getPaymentRedirectUrlOrThrow:z,isPaymentDataRequired:N},paymentMethods:{getPaymentMethod:x,getPaymentMethodOrThrow:R,getPaymentMethodsMeta:F},paymentProviderCustomer:{getPaymentProviderCustomer:L,getPaymentProviderCustomerOrThrow:B},paymentStrategies:{isInitialized:j},shippingAddress:{getShippingAddress:U,getShippingAddressOrThrow:q,getShippingAddresses:V,getShippingAddressesOrThrow:G},shippingCountries:{getShippingCountries:H}}){return{getHost:Bg(c),getLocale:Bg(l),getCartLocale:Bg(r),getBillingAddress:Bg(e),getBillingAddressOrThrow:Bg(t),getCart:Bg(n),getCartOrThrow:Bg(i),getCheckout:Bg(o),getCheckoutOrThrow:Bg(a),getCountries:Bg(g),getStoreConfig:Bg(u),getStoreConfigOrThrow:Bg(h),getConfig:Bg(p),getConsignments:Bg(m),getConsignmentsOrThrow:Bg(y),getContextConfig:Bg(d),getCustomer:Bg(v),getCustomerOrThrow:Bg(f),getCardInstrument:Bg(S),getInstruments:Bg(w),getCardInstrumentOrThrow:Bg(_),getOrder:Bg(C),getOrderOrThrow:Bg(b),getOrderMeta:Bg(P),getInstrumentsMeta:Bg(I),getPaymentToken:O,getPaymentTokenOrThrow:E,getPaymentId:A,getPaymentIdOrThrow:T,getPaymentStatus:k,getPaymentStatusOrThrow:D,getPaymentRedirectUrl:M,getPaymentRedirectUrlOrThrow:z,getPaymentMethod:Bg(x),getPaymentMethodOrThrow:Bg(R),getPaymentMethodsMeta:Bg(F),getPaymentProviderCustomer:Bg(L),getPaymentProviderCustomerOrThrow:Bg(B),getShippingAddress:Bg(U),getShippingAddressOrThrow:Bg(q),getShippingAddresses:Bg(V),getShippingAddressesOrThrow:Bg(G),getShippingCountries:Bg(H),getOutstandingBalance:Bg(s),isPaymentDataRequired:N,isPaymentMethodInitialized:j}}var Ug,qg=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vg{constructor(e,t,n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S){this._store=e,this._storeProjectionFactory=t,this._checkoutActionCreator=n,this._checkoutValidator=i,this._hostedFormFactory=r,this._orderActionCreator=o,this._billingAddressActionCreator=a,this._consignmentActionCreator=s,this._paymentMethodActionCreator=d,this._paymentActionCreator=c,this._paymentHumanVerificationHandler=l,this._customerActionCreator=u,this._cartRequestSender=h,this._storeCreditActionCreator=p,this._couponActionCreator=m,this._spamProtectionActionCreator=y,this._paymentProviderCustomerActionCreator=g,this._shippingCountryActionCreator=v,this._remoteCheckoutActionCreator=f,this._paymentStrategyWidgetActionCreator=S,this._storeProjection=this._storeProjectionFactory.create(this._store)}createHostedForm(e,t){const n=this._storeProjection.getState().getCheckoutOrThrow().id;return this._hostedFormFactory.create(e,t,n)}subscribe(e,...t){return this._storeProjection.subscribe(e,...t)}getState(){return this._storeProjection.getState()}initializeOffsitePayment(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentActionCreator.initializeOffsitePayment(e)),this._storeProjection.getState()})}loadCheckout(e){return qg(this,void 0,void 0,function*(){return e?yield this._store.dispatch(this._checkoutActionCreator.loadCheckout(e)):yield this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),this._storeProjection.getState()})}loadDefaultCheckout(){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()),this._storeProjection.getState()})}loadPaymentMethod(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e,t)),this._storeProjection.getState()})}loadPaymentMethods(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethods(e)),this._storeProjection.getState()})}submitOrder(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._orderActionCreator.submitOrder(e,t)),this._storeProjection.getState()})}submitPayment(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentActionCreator.submitPayment(e)),this._storeProjection.getState()})}finalizeOrder(e){return qg(this,void 0,void 0,function*(){const{order:{getOrderOrThrow:t}}=this._store.getState();return yield this._store.dispatch(this._orderActionCreator.finalizeOrder(t().orderId,e)),this._storeProjection.getState()})}updateBillingAddress(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(e)),this._storeProjection.getState()})}updateShippingAddress(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.updateAddress(e)),this._storeProjection.getState()})}selectShippingOption(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t)),this._storeProjection.getState()})}signInCustomer(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._customerActionCreator.signInCustomer(e,t)),this._storeProjection.getState()})}signOutCustomer(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._customerActionCreator.signOutCustomer(e)),this._storeProjection.getState()})}createBuyNowCart(e,t){return qg(this,void 0,void 0,function*(){const{body:n}=yield this._cartRequestSender.createBuyNowCart(e,t);return n})}applyStoreCredit(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(e,t)),this._storeProjection.getState()})}applyCoupon(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._couponActionCreator.applyCoupon(e,t)),this._storeProjection.getState()})}removeCoupon(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._couponActionCreator.removeCoupon(e,t)),this._storeProjection.getState()})}verifyCheckoutSpamProtection(){return qg(this,void 0,void 0,function*(){const{checkout:e}=this._store.getState(),{shouldExecuteSpamCheck:t}=e.getCheckoutOrThrow();return t&&(yield this._store.dispatch(this._spamProtectionActionCreator.verifyCheckoutSpamProtection())),this._storeProjection.getState()})}loadCurrentOrder(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._orderActionCreator.loadCurrentOrder(e)),this._storeProjection.getState()})}updatePaymentProviderCustomer(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(e)),this._storeProjection.getState()})}loadShippingCountries(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._shippingCountryActionCreator.loadCountries(e)),this._storeProjection.getState()})}deleteConsignment(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.deleteConsignment(e,t)),this._storeProjection.getState()})}initializePayment(e,t,n){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.initializePayment(e,t,n)),this._storeProjection.getState()})}forgetCheckout(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.forgetCheckout(e,t)),this._storeProjection.getState()})}remoteCheckoutSignOut(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.signOut(e,t)),this._storeProjection.getState()})}validateCheckout(e,t){return qg(this,void 0,void 0,function*(){yield this._checkoutValidator.validate(e,t)})}handlePaymentHumanVerification(e,t){return qg(this,void 0,void 0,function*(){return"string"==typeof e?this._paymentHumanVerificationHandler.handle(e,null!=t?t:""):this._paymentHumanVerificationHandler.handle(e)})}widgetInteraction(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentStrategyWidgetActionCreator.widgetInteraction(e),{queueId:"widgetInteraction"}),this._storeProjection.getState()})}}class Gg{constructor(e){this._transformSelectors=e}create(e){return mt(e,this._transformSelectors)}}function Hg(e,t){const{config:{getHost:i,getLocale:r}}=e.getState();t||(t=n({host:i()}));const a=new Gg(jg),s=new nn(new en(t),new bt(new Tt(t)),new on(new an(t))),d=new ny(new en(t)),c=new Iy(e),l=new Vm(new jm(t),new ny(new en(t))),u=new st(new ut(t),new Ng(new xg(t))),h=new Cg(new Pg(t),new en(t)),p=new Wm(new $m(t)),m=new Cy(new by(Gm(e)),l,new Gy,new cy(Sn(o()))),y=new cy(Sn(o())),g=new Kt(new Jt(t),s,new pn(Sn(o()),new _n(t))),v=new Dg(new Mg(t)),f=new Dt(new Lt(t)),S=Sn(o()),_=new _n(t),w=new pn(S,_),I=new fg(t),C=new Sg,b=new Ag(new Tg(t,{locale:r()}),e),P=new wg(new Ig(t),s),O=new Qm;return new Vg(e,a,s,d,c,l,u,h,p,m,y,g,I,v,f,w,C,b,P,O)}!function(e){e.LoadInstrumentsRequested="LOAD_INSTRUMENTS_REQUESTED",e.LoadInstrumentsSucceeded="LOAD_INSTRUMENTS_SUCCEEDED",e.LoadInstrumentsFailed="LOAD_INSTRUMENTS_FAILED",e.DeleteInstrumentRequested="DELETE_INSTRUMENT_REQUESTED",e.DeleteInstrumentSucceeded="DELETE_INSTRUMENT_SUCCEEDED",e.DeleteInstrumentFailed="DELETE_INSTRUMENT_FAILED"}(Ug||(Ug={}));class Wg{constructor(e){this._instrumentRequestSender=e}loadInstruments(){return e=>m.create(t=>{t.next(l(Ug.LoadInstrumentsRequested));const n=this._getSessionContext(e),i=this._getCurrentAccessToken(e),r=this._getShippingAddress(e);return this._getValidAccessToken(i).then(e=>this._instrumentRequestSender.loadInstruments(Object.assign(Object.assign({},n),{authToken:e.vaultAccessToken}),r).then(({body:n})=>{t.next(l(Ug.LoadInstrumentsSucceeded,n,e)),t.complete()})).catch(e=>{t.error(h(Ug.LoadInstrumentsFailed,e))})})}deleteInstrument(e){return t=>m.create(n=>{n.next(l(Ug.DeleteInstrumentRequested,void 0,{instrumentId:e}));const i=this._getSessionContext(t),r=this._getCurrentAccessToken(t);return this._getValidAccessToken(r).then(t=>this._instrumentRequestSender.deleteInstrument(Object.assign(Object.assign({},i),{authToken:t.vaultAccessToken}),e).then(({body:i})=>{n.next(l(Ug.DeleteInstrumentSucceeded,i,Object.assign({instrumentId:e},t))),n.complete()})).catch(t=>{n.error(h(Ug.DeleteInstrumentFailed,t,{instrumentId:e}))})})}_isValidVaultAccessToken(e){if(!e||!e.vaultAccessToken)return!1;return function(e){const t=new Date(e.getTime());return t.setMinutes(e.getMinutes()+2),t}(new Date(e.vaultAccessExpiry)).valueOf()>Date.now()}_getCurrentAccessToken(e){const{instruments:t}=e.getState(),n=t.getInstrumentsMeta();if(n)return{vaultAccessToken:n.vaultAccessToken,vaultAccessExpiry:n.vaultAccessExpiry}}_getValidAccessToken(e){return e&&this._isValidVaultAccessToken(e)?Promise.resolve(e):this._instrumentRequestSender.getVaultAccessToken().then(({body:e})=>e)}_getShippingAddress(e){const t=e.getState(),n=t.shippingAddress.getShippingAddresses();return n.length>1?n:t.shippingAddress.getShippingAddress()}_getSessionContext(e){const t=e.getState(),n=t.config.getStoreConfig(),i=t.cart.getCart();if(!n)throw new rt(et.MissingCheckoutConfig);if(!i)throw new rt(et.MissingCart);const{customerId:r}=i,{storeId:o}=n.storeProfile,{code:a}=n.shopperCurrency.isTransactional?n.shopperCurrency:n.currency;return{customerId:r,storeId:o,currencyCode:a}}}var $g,Yg,Kg=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rthis._isPayPalInstrument(e)?function(e){return{bigpayToken:e.bigpay_token,defaultInstrument:e.default_instrument,provider:e.provider,externalId:e.external_id,trustedShippingAddress:e.trusted_shipping_address,method:"paypal",type:"account"}}(e):this._isBankInstrument(e)?function(e){return{bigpayToken:e.bigpay_token,defaultInstrument:e.default_instrument,provider:e.provider,trustedShippingAddress:e.trusted_shipping_address,accountNumber:e.account_number,issuer:e.issuer,iban:e.iban,method:e.method,type:"bank"}}(e):function(e){return{bigpayToken:e.bigpay_token,defaultInstrument:e.default_instrument,provider:e.provider,iin:e.iin,last4:e.last_4,expiryMonth:e.expiry_month,expiryYear:e.expiry_year,brand:e.brand,trustedShippingAddress:e.trusted_shipping_address,untrustedShippingCardVerificationMode:e.untrusted_shipping_address_card_verification_mode,method:e.method,type:"card"}}(e))}_isPayPalInstrument(e){return"paypal"===e.method_type}_isBankInstrument(e){return"bank"===e.method_type}_transformResponse(e){const{data:t}=e,n=Kg(e,["data"]);return Object.assign(Object.assign({},n),{body:t})}}class Zg{constructor(e,t){this._client=e,this._requestSender=t,this._transformer=new Jg}getVaultAccessToken({timeout:e}={}){return this._requestSender.get("/internalapi/v1/checkout/payments/vault-access-token",{timeout:e}).then(e=>Object.assign(Object.assign({},e),{body:{vaultAccessToken:e.body.data.token,vaultAccessExpiry:e.body.data.expires_at}}))}loadInstruments(e,t){return t?this._loadInstrumentsWithAddress(e,t):this._loadInstruments(e)}deleteInstrument(e,t){const n=Object.assign(Object.assign({},e),{instrumentId:t});return new Promise((e,t)=>{this._client.deleteShopperInstrument(n,(n,i)=>n?t(this._transformer.transformErrorResponse(n)):e(this._transformer.transformResponse(i)))})}_loadInstruments(e){return new Promise((t,n)=>{this._client.loadInstruments(e,(e,i)=>e?n(this._transformer.transformErrorResponse(e)):t(this._transformer.transformResponse(i)))})}_loadInstrumentsWithAddress(e,t){const n=Object.assign(Object.assign({},e),{shippingAddress:Array.isArray(t)?t.map(e=>Py(e)):Py(t)});return new Promise((e,t)=>{this._client.loadInstrumentsWithAddress(n,(n,i)=>n?t(this._transformer.transformErrorResponse(n)):e(this._transformer.transformResponse(i)))})}}!function(e){e.LoadPickupOptionsRequested="LOAD_PICKUP_OPTIONS_REQUESTED",e.LoadPickupOptionsSucceeded="LOAD_PICKUP_OPTIONS_SUCCEEDED",e.LoadPickupOptionsFailed="LOAD_PICKUP_OPTIONS_FAILED"}($g||($g={}));class Qg{constructor(e){this._pickupOptionRequestSender=e}loadPickupOptions(e){return t=>new m(n=>{const i=this._hydrateApiQuery(t,e);n.next(l($g.LoadPickupOptionsRequested)),this._pickupOptionRequestSender.fetchPickupOptions(i).then(t=>{n.next(l($g.LoadPickupOptionsSucceeded,t.body.results,e)),n.complete()}).catch(e=>{n.error(h($g.LoadPickupOptionsFailed,e))})})}_hydrateApiQuery(e,t){const n=e.getState(),i=n.cart.getCartOrThrow();if(!i)throw new rt(et.MissingCart);const r=n.consignments.getConsignmentById(t.consignmentId);if(!r)throw new rt(et.MissingConsignments);const o=r.lineItemIds,a=i.lineItems.physicalItems.filter(e=>H(o,e.id)).map(e=>({variantId:e.variantId,quantity:e.quantity}));return{searchArea:t.searchArea,items:a}}}class Xg{constructor(e){this._requestSender=e}fetchPickupOptions(e){return this._requestSender.post("/api/storefront/pickup-options",{headers:Object.assign({Accept:ct.Json},Xe),body:e})}}!function(e){e.UpdateAddressFailed="SHIPPING_STRATEGY_UPDATE_ADDRESS_FAILED",e.UpdateAddressRequested="SHIPPING_STRATEGY_UPDATE_ADDRESS_REQUESTED",e.UpdateAddressSucceeded="SHIPPING_STRATEGY_UPDATE_ADDRESS_SUCCEEDED",e.SelectOptionFailed="SHIPPING_STRATEGY_SELECT_OPTION_FAILED",e.SelectOptionRequested="SHIPPING_STRATEGY_SELECT_OPTION_REQUESTED",e.SelectOptionSucceeded="SHIPPING_STRATEGY_SELECT_OPTION_SUCCEEDED",e.InitializeFailed="SHIPPING_STRATEGY_INITIALIZE_FAILED",e.InitializeRequested="SHIPPING_STRATEGY_INITIALIZE_REQUESTED",e.InitializeSucceeded="SHIPPING_STRATEGY_INITIALIZE_SUCCEEDED",e.DeinitializeFailed="SHIPPING_STRATEGY_DEINITIALIZE_FAILED",e.DeinitializeRequested="SHIPPING_STRATEGY_DEINITIALIZE_REQUESTED",e.DeinitializeSucceeded="SHIPPING_STRATEGY_DEINITIALIZE_SUCCEEDED",e.WidgetInteractionStarted="SHIPPING_STRATEGY_WIDGET_INTERACTION_STARTED",e.WidgetInteractionFinished="SHIPPING_STRATEGY_WIDGET_INTERACTION_FINISHED",e.WidgetInteractionFailed="SHIPPING_STRATEGY_WIDGET_INTERACTION_FAILED"}(Yg||(Yg={}));class ev{constructor(e){this._strategyRegistry=e}updateAddress(e,t){return n=>m.create(i=>{const r=n.getState().payment.getPaymentId(),o=t&&t.methodId||r&&r.providerId;i.next(l(Yg.UpdateAddressRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).updateAddress(e,Object.assign(Object.assign({},t),{methodId:o})).then(()=>{i.next(l(Yg.UpdateAddressSucceeded,void 0,{methodId:o})),i.complete()}).catch(e=>{i.error(h(Yg.UpdateAddressFailed,e,{methodId:o}))})})}selectOption(e,t){return n=>m.create(i=>{const r=n.getState().payment.getPaymentId(),o=t&&t.methodId||r&&r.providerId;i.next(l(Yg.SelectOptionRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).selectOption(e,Object.assign(Object.assign({},t),{methodId:o})).then(()=>{i.next(l(Yg.SelectOptionSucceeded,void 0,{methodId:o})),i.complete()}).catch(e=>{i.error(h(Yg.SelectOptionFailed,e,{methodId:o}))})})}initialize(e){return t=>m.create(n=>{const i=t.getState(),r=i.payment.getPaymentId(),o=e&&e.methodId||r&&r.providerId,a=Object.assign(Object.assign({},e),{methodId:o});if(o&&i.shippingStrategies.isInitialized(o))return n.complete();n.next(l(Yg.InitializeRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).initialize(a).then(()=>{n.next(l(Yg.InitializeSucceeded,void 0,{methodId:o})),n.complete()}).catch(e=>{n.error(h(Yg.InitializeFailed,e,{methodId:o}))})})}deinitialize(e){return t=>m.create(n=>{const i=t.getState(),r=i.payment.getPaymentId(),o=e&&e.methodId||r&&r.providerId;if(o&&!i.shippingStrategies.isInitialized(o))return n.complete();n.next(l(Yg.DeinitializeRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).deinitialize(Object.assign(Object.assign({},e),{methodId:o})).then(()=>{n.next(l(Yg.DeinitializeSucceeded,void 0,{methodId:o})),n.complete()}).catch(e=>{n.error(h(Yg.DeinitializeFailed,e,{methodId:o}))})})}widgetInteraction(e,t){return m.create(n=>{const i={methodId:t&&t.methodId};n.next(l(Yg.WidgetInteractionStarted,void 0,i)),e().then(()=>{n.next(l(Yg.WidgetInteractionFinished,void 0,i)),n.complete()}).catch(e=>{n.error(h(Yg.WidgetInteractionFailed,e,i))})})}}var tv,nv=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class iv{constructor(e,t,n,i,r){this._store=e,this._consignmentActionCreator=t,this._paymentMethodActionCreator=n,this._amazonPayV2PaymentProcessor=i,this._shippingStrategyActionCreator=r}updateAddress(e,t){const n=this._store.getState().shippingAddress.getShippingAddress();if(!n)throw new rt(et.MissingShippingAddress);const i=Object.assign(Object.assign({},n),{customFields:e.customFields});return this._store.dispatch(this._consignmentActionCreator.updateAddress(i,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(e){return nv(this,void 0,void 0,function*(){const{amazonpay:t,methodId:n}=e;if(!t||!n)throw new qt('Unable to proceed because "options.amazonpay" argument is not provided.');const i=(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n))).paymentMethods.getPaymentMethodOrThrow(n);yield this._amazonPayV2PaymentProcessor.initialize(i);const{paymentToken:r,region:o}=i.initializationData,a=t.editAddressButtonId;if(r&&a){const e=this._shouldShowLoadingSpinner(o);this._bindEditButton(a,r,"changeAddress",e)}return this._store.getState()})}deinitialize(){return nv(this,void 0,void 0,function*(){return yield this._amazonPayV2PaymentProcessor.deinitialize(),Promise.resolve(this._store.getState())})}_bindEditButton(e,t,n,i){const r=document.getElementById(e);if(r&&r.parentNode){if(i){const e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener("click",()=>this._showLoadingSpinner())}this._amazonPayV2PaymentProcessor.bindButton(e,t,n)}}_showLoadingSpinner(){return this._store.dispatch(this._shippingStrategyActionCreator.widgetInteraction(()=>new Promise(I)),{queueId:"widgetInteraction"})}_shouldShowLoadingSpinner(e){return"us"!==e}}!function(e){e.CVV="cvv",e.PAN="pan"}(tv||(tv={}));var rv=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ov{constructor(e,t,n,i,r,o){this._store=e,this._billingAddressActionCreator=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=i,this._paymentProviderCustomerActionCreator=r,this._braintreeIntegrationService=o}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}deinitialize(){return Promise.resolve(this._store.getState())}initialize(e){var t;return rv(this,void 0,void 0,function*(){const{methodId:n,braintreefastlane:i,fastlane:r}=e||{},o=r||i,{onPayPalFastlaneAddressChange:a}=o||{};if(!n)throw new qt('Unable to proceed because "methodId" argument is not provided.');const s=this._store.getState();if(!s.customer.getCustomerOrThrow().isGuest)return Promise.resolve(this._store.getState());try{if(this._shouldRunAuthenticationFlow()){const e=s.paymentMethods.getPaymentMethod(n),{clientToken:i,isFastlaneStylingEnabled:r}=(null==e?void 0:e.initializationData)||{};i||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n)));const a=Ao(r?null===(t=null==e?void 0:e.initializationData)||void 0===t?void 0:t.fastlaneStyles:void 0,null==o?void 0:o.styles);yield this._runAuthenticationFlowOrThrow(n,a)}"function"==typeof a&&(yield this._shouldUseBraintreeFastlaneShippingComponent(n))&&a(()=>this._handleBraintreeFastlaneShippingAddressChange())}catch(e){}return Promise.resolve(this._store.getState())})}_shouldRunAuthenticationFlow(){var e;const t=this._store.getState(),n=null===(e=t.cart.getCart())||void 0===e?void 0:e.id,i=Fr.get("bc-fastlane-sessionId")||"",r=t.paymentProviderCustomer.getPaymentProviderCustomer(),o=xl(r)?r:{};return(null==o?void 0:o.authenticationState)!==Mi.CANCELED&&!(null==o?void 0:o.authenticationState)&&i===n}_runAuthenticationFlowOrThrow(e,t){var n,i;return rv(this,void 0,void 0,function*(){const r=this._store.getState(),o=r.cart.getCartOrThrow(),a=r.countries.getCountries()||[],s=r.paymentMethods.getPaymentMethodOrThrow(e),{clientToken:d,config:c}=s;if(!d)throw new rt(et.MissingPaymentMethod);this._braintreeIntegrationService.initialize(d);const l=yield this._braintreeIntegrationService.getBraintreeFastlane(null==o?void 0:o.id,null==c?void 0:c.testMode,t),u=(null===(n=r.customer.getCustomer())||void 0===n?void 0:n.email)||(null===(i=r.billingAddress.getBillingAddress())||void 0===i?void 0:i.email);if(!u)return;const{lookupCustomerByEmail:h,triggerAuthenticationFlow:p}=l.identity,{customerContextId:m}=yield h(u);if(!m)return;const{authenticationState:y,profileData:g}=yield p(m);if(y===Mi.CANCELED)return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:y,addresses:[],instruments:[]})),void Fr.remove("bc-fastlane-sessionId");const v=this._getPayPalBillingAddress(g),f=g.shippingAddress,S=g.shippingAddress.phoneNumber,_=this._mapPayPalToBcAddress(f,a,S),w=this._mapPayPalToBcAddress(v,a,S);if(w&&_){const t=this._mergeShippingAndBillingAddresses(_,w),n=this._mapPayPalToBcInstrument(e,g.card),i=n?[n]:[];yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:y,addresses:t,instruments:i})),w&&(yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(Object.assign(Object.assign({},w),{id:String(w.id)})))),_&&o.lineItems.physicalItems.length>0&&(yield this._store.dispatch(this._consignmentActionCreator.updateAddress(_)))}})}_getPayPalBillingAddress(e){const{name:t,card:n}=e,i=n.paymentSource.card.billingAddress;return Object.assign(Object.assign({},i),{firstName:i.firstName||(null==t?void 0:t.firstName),lastName:i.lastName||(null==t?void 0:t.lastName)})}_getCountryNameByCountryCode(e,t){const n=t.find(t=>t.code===e);return(null==n?void 0:n.name)||""}_mapPayPalToBcAddress(e,t,n,i){return{id:Number(Date.now()),type:"paypal-address",firstName:e.firstName||"",lastName:e.lastName||"",company:e.company||"",address1:e.streetAddress,address2:e.extendedAddress||"",city:e.locality,stateOrProvince:e.region,stateOrProvinceCode:e.region,country:this._getCountryNameByCountryCode(e.countryCodeAlpha2,t),countryCode:e.countryCodeAlpha2,postalCode:e.postalCode,phone:n||"",customFields:i||[]}}_normalizeAddress(e){return le(e,["id"])}_mergeShippingAndBillingAddresses(e,t){return Y(this._normalizeAddress(e),this._normalizeAddress(t))?[e]:[e,t]}_mapPayPalToBcInstrument(e,t){if(!t)return;const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a}=i.card,[s,d]=o.split("-");return{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:tv.CVV,type:"card"}}_handleBraintreeFastlaneShippingAddressChange(){var e;return rv(this,void 0,void 0,function*(){const t=this._store.getState().countries.getCountries()||[],n=yield this._braintreeIntegrationService.getBraintreeFastlane(),{selectionChanged:i,selectedAddress:r}=yield n.profile.showShippingAddressSelector();if(i){const n=this._store.getState(),i=n.shippingAddress.getShippingAddressesOrThrow(),o=n.paymentProviderCustomer.getPaymentProviderCustomer(),a=xl(o)?o:{},s=this._mapPayPalToBcAddress(r,t,r.phoneNumber,null===(e=i[0])||void 0===e?void 0:e.customFields);if(s){const e=this._filterAddresses([s,...a.addresses||[]]);return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(Object.assign(Object.assign({},a),{addresses:e}))),yield this._store.dispatch(this._consignmentActionCreator.updateAddress(s)),s}}})}_filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this._isEqualAddresses(e,t))?e:[...e,t]:e,[])}_isEqualAddresses(e,t){return Y(this._normalizeAddress(e),this._normalizeAddress(t))}_shouldUseBraintreeFastlaneShippingComponent(e){var t;return rv(this,void 0,void 0,function*(){const n=this._store.getState().paymentProviderCustomer.getPaymentProviderCustomer(),i=xl(n)?n:{};if(i&&(null==i?void 0:i.authenticationState)!==Mi.CANCELED){const n=yield this._getBraintreePaymentMethodOrThrow(e);return!!(null===(t=null==n?void 0:n.initializationData)||void 0===t?void 0:t.isFastlaneEnabled)}return!1})}_getBraintreePaymentMethodOrThrow(e){return rv(this,void 0,void 0,function*(){const t=this._store.getState().paymentMethods.getPaymentMethod(e);return t||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e))).paymentMethods.getPaymentMethodOrThrow(e)})}}class av{constructor(e,t){this._store=e,this._consignmentActionCreator=t}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(){return Promise.resolve(this._store.getState())}deinitialize(){return Promise.resolve(this._store.getState())}}var sv=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class dv{constructor(e,t,n,i,r,o,a){this._store=e,this._billingAddressActionCreator=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=i,this._paymentProviderCustomerActionCreator=r,this._paypalSdkScriptLoader=o,this._paypalCommerceFastlaneUtils=a}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}deinitialize(){return Promise.resolve(this._store.getState())}initialize(e){return sv(this,void 0,void 0,function*(){const{methodId:t,paypalcommercefastlane:n,fastlane:i}=e||{},r=i||n,{onPayPalFastlaneAddressChange:o,styles:a}=r||{};if(!t)throw new qt('Unable to proceed because "methodId" argument is not provided.');const s=this._store.getState().customer.getCustomerOrThrow();if(!(null==s?void 0:s.isGuest))return Promise.resolve(this._store.getState());try{this._shouldAuthenticateUserWithFastlane()&&(yield this._initializePayPalSdk(t,a),yield this._authenticateUserWithFastlaneOtp(t)),"function"==typeof o&&this._shouldUsePayPalFastlaneShippingComponent()&&(yield this._initializePayPalSdk(t,a),o(()=>this._handlePayPalShippingAddressChange()))}catch(e){}return Promise.resolve(this._store.getState())})}_getPayPalPaymentMethodOrThrow(e){return sv(this,void 0,void 0,function*(){const t=this._store.getState().paymentMethods.getPaymentMethod(e);return t||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e))).paymentMethods.getPaymentMethodOrThrow(e)})}_getPayPalCustomerAuthenticationState(){const e=this._store.getState().paymentProviderCustomer.getPaymentProviderCustomerOrThrow();var t;return((t=e)&&("authenticationState"in t||"addresses"in t||"instruments"in t)?e:{}).authenticationState}_shouldAuthenticateUserWithFastlane(){const e=this._store.getState().cart.getCartOrThrow(),t=this._paypalCommerceFastlaneUtils.getStorageSessionId();return!this._getPayPalCustomerAuthenticationState()&&t===e.id}_shouldUsePayPalFastlaneShippingComponent(){const e=this._getPayPalCustomerAuthenticationState();return!!e&&e!==fs.CANCELED}_initializePayPalSdk(e,t){var n;return sv(this,void 0,void 0,function*(){const i=this._store.getState().cart.getCartOrThrow(),r=yield this._getPayPalPaymentMethodOrThrow(e),{isDeveloperModeApplicable:o,isFastlaneStylingEnabled:a}=(null==r?void 0:r.initializationData)||{},s=!!o,d=rd(a?null===(n=null==r?void 0:r.initializationData)||void 0===n?void 0:n.fastlaneStyles:{},t),c=yield this._paypalSdkScriptLoader.getPayPalFastlaneSdk(r,i.currency.code,i.id,i.locale);yield this._paypalCommerceFastlaneUtils.initializePayPalFastlane(c,s,d)})}_authenticateUserWithFastlaneOtp(e){var t,n;return sv(this,void 0,void 0,function*(){const i=this._store.getState(),r=i.cart.getCartOrThrow(),o=null===(t=i.customer.getCustomer())||void 0===t?void 0:t.email,a=null===(n=i.billingAddress.getBillingAddress())||void 0===n?void 0:n.email,s=o||a||"",{customerContextId:d}=yield this._paypalCommerceFastlaneUtils.lookupCustomerOrThrow(s),c=yield this._paypalCommerceFastlaneUtils.triggerAuthenticationFlowOrThrow(d),{authenticationState:l,addresses:u,billingAddress:h,shippingAddress:p,instruments:m}=this._paypalCommerceFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,c);yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:l,addresses:u,instruments:m})),c.authenticationState===fs.CANCELED?this._paypalCommerceFastlaneUtils.removeStorageSessionId():this._paypalCommerceFastlaneUtils.updateStorageSessionId(r.id),h&&(yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(Object.assign(Object.assign({},h),{id:String(h.id)})))),p&&r.lineItems.physicalItems.length>0&&(yield this._store.dispatch(this._consignmentActionCreator.updateAddress(p)))})}_handlePayPalShippingAddressChange(){var e;return sv(this,void 0,void 0,function*(){const t=this._paypalCommerceFastlaneUtils.getPayPalFastlaneOrThrow(),{selectionChanged:n,selectedAddress:i}=yield t.profile.showShippingAddressSelector();if(n){const t=this._store.getState(),n=t.shippingAddress.getShippingAddressesOrThrow(),r=t.paymentProviderCustomer.getPaymentProviderCustomer(),o=vp(r)?r:{},a=this._paypalCommerceFastlaneUtils.mapPayPalToBcAddress(i.address,i.name,i.phoneNumber,null===(e=n[0])||void 0===e?void 0:e.customFields),s=this._paypalCommerceFastlaneUtils.filterAddresses([a,...o.addresses||[]]);return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(Object.assign(Object.assign({},o),{addresses:s}))),yield this._store.dispatch(this._consignmentActionCreator.updateAddress(a)),a}})}}var cv;class lv{constructor(e,t,n,i){this._store=e,this._stripeScriptLoader=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=i}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(e){return t=this,n=void 0,r=function*(){if(!e.stripeupe)throw new qt('Unable to proceed because "options" argument is not provided.');const{container:t,gatewayId:n,methodId:i,onChangeShipping:r,getStyles:o,availableCountries:a,getStripeState:s}=e.stripeupe;Object.entries(e.stripeupe).forEach(([e,t])=>{if(!t)throw new qt(`Unable to proceed because "${e}" argument is not provided.`)});const d=yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n,{params:{method:i}})),c=d.paymentMethods.getPaymentMethodOrThrow(i,n),{initializationData:l}=c;if(!c||!c.initializationData.stripePublishableKey||!c.clientToken)throw new rt(et.MissingPaymentMethod);let u;this._stripeUPEClient=yield this._stripeScriptLoader.getStripeClient(l,d.cart.getLocale(),ka.V3,Fa,La);const h=o&&o(),{form:{getShippingAddressFields:p},shippingAddress:{getShippingAddress:m}}=this._store.getState(),y=p([],"");u=h?{variables:{colorPrimary:h.fieldInnerShadow,colorBackground:h.fieldBackground,colorText:h.labelText,colorDanger:h.fieldErrorText,colorTextSecondary:h.labelText,colorTextPlaceholder:h.fieldPlaceholderText,spacingUnit:"4px",borderRadius:"4px"},rules:{".Input":{borderColor:h.fieldBorder,color:h.fieldText,boxShadow:h.fieldInnerShadow}}}:{variables:{spacingUnit:"4px",borderRadius:"4px"}},this._stripeElements=yield this._stripeScriptLoader.getElements(this._stripeUPEClient,{clientSecret:c.clientToken,appearance:u});const g=m(),v=y.find(e=>"phone"===e.name);let f={mode:Ca.SHIPPING,allowedCountries:[a],fields:{phone:"always"},validation:{phone:{required:v&&v.required?"always":"never"}},display:{name:ba.SPLIT}};if(g){const{stateOrProvinceCode:e,countryCode:t,lastName:n,firstName:i,phone:r,address1:o,address2:a,city:d,postalCode:c}=g,l=e&&t?s(t,e):e;f=Object.assign(Object.assign({},f),{defaultValues:{firstName:i,lastName:n,phone:r,address:{line1:o,line2:a,city:d,state:l,postal_code:c,country:t}}})}let S=this._stripeElements.getElement(Da.SHIPPING);return S&&S.destroy(),S=this._stripeElements.create(Da.SHIPPING,f),S.on(za.CHANGE,e=>{if(!("isNewAddress"in e))throw new rt(et.MissingShippingAddress);(e.complete||e.isNewAddress)&&(this.sendData&&clearTimeout(this.sendData),this.sendData=setTimeout(()=>{r(Object.assign(Object.assign({},e),{phoneFieldRequired:!!v&&v.required}))},1e3))}),S.mount(`#${t}`),Promise.resolve(this._store.getState())},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}deinitialize(){return Promise.resolve(this._store.getState())}}!function(e){e.SendSignInEmailRequested="SEND_SIGNIN_EMAIL_REQUESTED",e.SendSignInEmailSucceeded="SEND_SIGNIN_EMAIL_SUCCEEDED",e.SendSignInEmailFailed="SEND_SIGNIN_EMAIL_FAILED"}(cv||(cv={}));class uv{constructor(e){this._requestSender=e}sendSignInEmail(e,t){return g(C(l(cv.SendSignInEmailRequested)),v(()=>{return n=this,i=void 0,o=function*(){const{body:n}=yield this._requestSender.sendSignInEmail(e,t);return l(cv.SendSignInEmailSucceeded,n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Je(cv.SendSignInEmailFailed,e)))}}class hv{constructor(e){this._requestSender=e}sendSignInEmail({email:e,redirectUrl:t},{timeout:n}={}){const i=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post("/login.php?action=passwordless_login",{body:{email:e,redirect_url:t||In(window.top?window.top.location.href:"").pathname},headers:i,timeout:n})}}class pv{constructor(e){this._messageCustomizer=e}transform(e){var t;return e.message=(t=this._messageCustomizer(e))?t.split(/(?:\r\n|\n|\r)/).map(e=>e.replace(/^\s+/gm,"")).join(" ").trim():"",e}}let mv=class{constructor(e,t,n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,_,w,I,C,b,P,O,E,A){this._store=e,this._storeProjection=t,this._extensionMessenger=n,this._extensionEventBroadcaster=i,this._b2bTokenActionCreator=r,this._billingAddressActionCreator=o,this._checkoutActionCreator=a,this._configActionCreator=s,this._customerActionCreator=d,this._consignmentActionCreator=c,this._countryActionCreator=l,this._couponActionCreator=u,this._customerStrategyActionCreator=h,this._errorActionCreator=p,this._giftCertificateActionCreator=m,this._instrumentActionCreator=y,this._orderActionCreator=g,this._paymentMethodActionCreator=v,this._paymentStrategyActionCreator=f,this._pickupOptionActionCreator=S,this._shippingCountryActionCreator=_,this._shippingStrategyActionCreator=w,this._signInEmailActionCreator=I,this._spamProtectionActionCreator=C,this._storeCreditActionCreator=b,this._subscriptionsActionCreator=P,this._formFieldsActionCreator=O,this._extensionActionCreator=E,this._workerExtensionMessenger=A,this._errorTransformer=function(e="development"===vt()){return new pv(t=>{if(!e||!function(e){return!(!e.subtype&&!e.type)}(t))return t.message;switch(t.subtype||t.type){case et.MissingConsignments:return`\n ${t.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 `;case et.MissingCart:case et.MissingCheckout:return`\n ${t.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 `;case et.MissingCheckoutConfig:return`\n ${t.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 `;case et.MissingOrder:return`\n ${t.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 `;case et.MissingOrderId:return`\n ${t.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 `;case et.MissingPaymentMethod:return`\n ${t.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 `;case cn.CustomerNotInitialized: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 ";case cn.PaymentNotInitialized:return`\n ${t.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 `;case cn.ShippingNotInitialized:return`\n ${t.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 `;default:return t.message}})}()}getState(){return this._storeProjection.getState()}notifyState(){this._storeProjection.notifyState()}subscribe(e,...t){return this._storeProjection.subscribe(e,...t)}hydrateInitialState(e){return this._dispatch(this._checkoutActionCreator.hydrateInitialState(e))}loadCheckout(e,t){return this._dispatch(e?this._checkoutActionCreator.loadCheckout(e,t):this._checkoutActionCreator.loadDefaultCheckout(t))}updateCheckout(e,t){const n=this._checkoutActionCreator.updateCheckout(e,t);return this._dispatch(n)}loadOrder(e,t){const n=this._orderActionCreator.loadOrder(e,t),i=this._formFieldsActionCreator.loadFormFields(t),r=this._configActionCreator.loadConfig(t);return Promise.all([this._dispatch(n),this._dispatch(r,{queueId:"config"}),this._dispatch(i,{queueId:"formFields"})]).then(()=>this.getState())}submitOrder(e,t){const n=this._paymentStrategyActionCreator.execute(e,t);return this._dispatch(n,{queueId:"paymentStrategy"})}finalizeOrderIfNeeded(e){const t=this._paymentStrategyActionCreator.finalize(e);return this._dispatch(t,{queueId:"paymentStrategy"})}loadPaymentMethods(e){const t=this._paymentMethodActionCreator.loadPaymentMethods(e);return this._dispatch(t,{queueId:"paymentMethods"})}loadPaymentMethodByIds(e,t){const n=this._paymentMethodActionCreator.loadPaymentMethodsById(e,t);return this._dispatch(n,{queueId:"paymentMethods"})}loadPaymentMethod(e,t){const n=this._paymentMethodActionCreator.loadPaymentMethod(e,t);return this._dispatch(n,{queueId:"paymentMethods"})}initializePayment(e){const t=this._paymentStrategyActionCreator.initialize(e);return this._dispatch(t,{queueId:"paymentStrategy"})}deinitializePayment(e){const t=this._paymentStrategyActionCreator.deinitialize(e);return this._dispatch(t,{queueId:"paymentStrategy"})}loadBillingCountries(e){const t=this._countryActionCreator.loadCountries(e);return this._dispatch(t,{queueId:"billingCountries"})}loadShippingCountries(e){const t=this._shippingCountryActionCreator.loadCountries(e);return this._dispatch(t,{queueId:"shippingCountries"})}loadPickupOptions(e){const t=this._pickupOptionActionCreator.loadPickupOptions(e);return this._dispatch(t,{queueId:"pickupOptions"})}loadBillingAddressFields(e){return this.loadBillingCountries(e)}loadShippingAddressFields(e){return this.loadShippingCountries(e)}initializeCustomer(e){const t=this._customerStrategyActionCreator.initialize(e);return this._dispatch(t,{queueId:"customerStrategy"})}deinitializeCustomer(e){const t=this._customerStrategyActionCreator.deinitialize(e);return this._dispatch(t,{queueId:"customerStrategy"})}sendSignInEmail(e,t){const n=this._signInEmailActionCreator.sendSignInEmail(e,t);return this._dispatch(n,{queueId:"signInEmail"})}getB2BToken(e){const t=this._b2bTokenActionCreator.loadB2BToken(e);return this._dispatch(t,{queueId:"b2bToken"})}createCustomerAccount(e,t){const n=this._customerActionCreator.createCustomer(e,t);return this._dispatch(n)}createCustomerAddress(e,t){const n=this._customerActionCreator.createAddress(e,t);return this._dispatch(n)}updateSubscriptions(e,t){const n=this._subscriptionsActionCreator.updateSubscriptions(e,t);return this._dispatch(n,{queueId:"subscriptions"})}continueAsGuest(e,t){const n=this._billingAddressActionCreator.continueAsGuest(e,t);return this._dispatch(n)}signInCustomer(e,t){const n=this._customerStrategyActionCreator.signIn(e,t);return this._dispatch(n,{queueId:"customerStrategy"})}signOutCustomer(e){const t=this._customerStrategyActionCreator.signOut(e);return this._dispatch(t,{queueId:"customerStrategy"})}executePaymentMethodCheckout(e){const t=this._customerStrategyActionCreator.executePaymentMethodCheckout(e);return this._dispatch(t,{queueId:"customerStrategy"})}loadShippingOptions(e){const t=this._consignmentActionCreator.loadShippingOptions(e);return this._dispatch(t)}initializeShipping(e){const t=this._shippingStrategyActionCreator.initialize(e);return this._dispatch(t,{queueId:"shippingStrategy"})}deinitializeShipping(e){const t=this._shippingStrategyActionCreator.deinitialize(e);return this._dispatch(t,{queueId:"shippingStrategy"})}selectShippingOption(e,t){const n=this._shippingStrategyActionCreator.selectOption(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}updateShippingAddress(e,t){const n=this._shippingStrategyActionCreator.updateAddress(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}createConsignments(e,t){const n=this._consignmentActionCreator.createConsignments(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}deleteConsignment(e,t){const n=this._consignmentActionCreator.deleteConsignment(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}updateConsignment(e,t){const n=this._consignmentActionCreator.updateConsignment(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}assignItemsToAddress(e,t){const n=this._consignmentActionCreator.assignItemsByAddress(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}unassignItemsToAddress(e,t){const n=this._consignmentActionCreator.unassignItemsByAddress(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}selectConsignmentShippingOption(e,t,n){const i=this._consignmentActionCreator.updateShippingOption({id:e,shippingOptionId:t},n);return this._dispatch(i,{queueId:"shippingStrategy"})}updateBillingAddress(e,t={}){const n=this._billingAddressActionCreator.updateAddress(e,t);return this._dispatch(n)}applyStoreCredit(e,t){const n=this._storeCreditActionCreator.applyStoreCredit(e,t);return this._dispatch(n)}applyCoupon(e,t){const n=this._couponActionCreator.applyCoupon(e,t);return this._dispatch(n)}removeCoupon(e,t){const n=this._couponActionCreator.removeCoupon(e,t);return this._dispatch(n)}applyGiftCertificate(e,t){const n=this._giftCertificateActionCreator.applyGiftCertificate(e,t);return this._dispatch(n)}removeGiftCertificate(e,t){const n=this._giftCertificateActionCreator.removeGiftCertificate(e,t);return this._dispatch(n)}loadInstruments(){const e=this._instrumentActionCreator.loadInstruments();return this._dispatch(e)}deleteInstrument(e){const t=this._instrumentActionCreator.deleteInstrument(e);return this._dispatch(t).then(()=>this.loadInstruments())}clearError(e){const t=this._errorActionCreator.clearError(e);return this._dispatch(t)}initializeSpamProtection(e){const t=this._spamProtectionActionCreator.initialize(e);return this._dispatch(t,{queueId:"spamProtection"})}executeSpamCheck(){const e=this._spamProtectionActionCreator.verifyCheckoutSpamProtection();return this._dispatch(e,{queueId:"spamProtection"})}loadExtensions(e){const t=this._extensionActionCreator.loadExtensions(e);return this._dispatch(t,{queueId:"extensions"})}renderExtension(e,t){return n=this,i=void 0,o=function*(){const n=this._extensionActionCreator.renderExtension(e,t,this._workerExtensionMessenger),i=yield this._dispatch(n,{queueId:"extensions"});return this._extensionEventBroadcaster.listen(),i},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}clearExtensionCache(e){this._extensionMessenger.clearCacheByRegion(e)}postMessageToExtension(e,t){this._extensionMessenger.post(e,t)}handleExtensionCommand(e,t,n){return this._extensionMessenger.listenForCommand(e,t,n)}handleExtensionQuery(e,t,n){return this._extensionMessenger.listenForQuery(e,t,n)}_dispatch(e,t){return this._store.dispatch(e,t).then(()=>this.getState()).catch(e=>{throw this._errorTransformer.transform(e)})}};mv=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],mv);const yv=mv;function gv(e){return(...t)=>{const n=t.pop();return e(...t,(...e)=>{const t=n(...e);return"function"==typeof t?Pe(t):t})}}const vv=gv(Re),fv=gv(Fe(Le,(e,t)=>Be(e,t)));class Sv extends Ot{constructor(e,t){super(e,{message:t||"An unexpected error has occurred. The checkout process cannot continue as a result."}),this.name="UnrecoverableError",this.type="unrecoverable"}}function _v(e){return e.reduce((e,t)=>t?[...e,t]:e,[]).join(" ")}class wv extends Ot{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}class Iv{constructor(){this._factoryMethods={},this.register("default",(e,t)=>new Ot(e,{message:t})),this.register("internal",(e,t)=>function(e,t){const{body:n}=e,{errors:i=[]}=n;return new Ot(e,{message:_v(i)||n.detail||n.title||t,errors:i.length?i.map(e=>({code:n.type,message:e})):[{code:n.type,message:n.detail||n.title}]})}(e,t)),this.register("storefront",(e,t)=>function(e,t){const{body:n}=e;return new Ot(e,{message:t||n.detail||n.title,errors:[{code:n.code||n.type,message:n.detail||n.title}]})}(e,t)),this.register("payment",(e,t)=>ly(e,t)),this.register("timeout",e=>new wv(e))}register(e,t){this._factoryMethods[e]=t}createError(e,t){return(this._factoryMethods[this._getType(e)]||this._factoryMethods.default)(e,t)}_getType(e){if(0===e.status)return"timeout";if(this._isStorefrontErrorResponseBody(e.body))return"storefront";if(this._isInternalErrorResponseBody(e.body)){const t=re(e.body.type.split("/"));return t&&this._factoryMethods[t]?t:"internal"}const t=re(e.body&&e.body.errors);return t&&t.code&&this._factoryMethods[t.code]?t.code:"payment"}_isStorefrontErrorResponseBody(e){const t=e;return!this._isInternalErrorResponseBody(e)&&"string"==typeof t.title&&"string"==typeof t.type&&"number"==typeof t.status&&"string"==typeof t.detail}_isInternalErrorResponseBody(e){const t=e;return"object"==typeof t.errors&&"string"==typeof t.title&&"string"==typeof t.type&&"number"==typeof t.status}}function Cv(e,t){return Array.isArray(e)?e.map(e=>Cv(e,t)):Q(e)?Se(ue(e,t),(e,n,i)=>{e[i]=Cv(n,t)},{}):e}function bv(e,t){return function(e){return e.type===pt.ClearError}(t)?Cv(e,e=>e===t.payload):e}function Pv(e,t,n){return e===t||(e&&t&&"object"==typeof e&&"object"==typeof t?Array.isArray(e)&&Array.isArray(t)?function(e,t,n){if(e.length!==t.length)return!1;for(let i=0,r=e.length;ivoid 0!==e.id&&e.id===t.id}=i||{};if(!t)return n;if(!n||t===n)return t;let o=0,a=0;const s=(e,t,n)=>(o+=e===t?1:0,a+=e===n?1:0,e),d=n.map((n,i)=>{const o=t&&t[i];return Rg(o)&&Rg(n)?r(o,n)?s(Bv(o,n),o,n):s(Mv(o,n),o,n):W(o)&&W(n)?s(e(o,n),o,n):s(Mv(o,n),o,n)});return o===n.length&&t&&t.length===n.length?t:a===n.length?n:d},Bv=function e(t,n){return t?n&&t!==n?Object.keys(n).reduce((t,i)=>{const r=t[i],o=n[i];return Rg(r)&&Rg(o)?Ov(t,i,e(r,o)):W(r)&&W(o)?Ov(t,i,Lv(r,o)):Ov(t,i,o)},t):t:n},jv={errors:{},statuses:{}};function Uv(e=jv,t){return d({data:qv,errors:c(Gv,bv),statuses:Vv})(e,t)}function qv(e,t){var n,i;switch(t.type){case tt.UpdateBillingAddressSucceeded:case $t.LoadCheckoutSucceeded:case _g.CreateConsignmentsSucceeded:case _g.DeleteConsignmentSucceeded:case _g.UpdateConsignmentSucceeded:case _g.UpdateShippingOptionSucceeded:case _g.LoadShippingOptionsSucceeded:case kt.ApplyCouponSucceeded:case kt.RemoveCouponSucceeded:case Nt.ApplyGiftCertificateSucceeded:case Nt.RemoveGiftCertificateSucceeded:return Bv(e,t.payload&&t.payload.cart);case Yt.HydrateInitialState:return Bv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.cart);default:return e}}function Vv(e=jv.statuses,t){switch(t.type){case $t.LoadCheckoutRequested:return Ov(e,"isLoading",!0);case $t.LoadCheckoutFailed:case $t.LoadCheckoutSucceeded:return Ov(e,"isLoading",!1);default:return e}}function Gv(e=jv.errors,t){switch(t.type){case $t.LoadCheckoutRequested:case $t.LoadCheckoutSucceeded:return Ov(e,"loadError",void 0);case $t.LoadCheckoutFailed:return Ov(e,"loadError",t.payload);default:return e}}var Hv;!function(e){e.InitializeButtonFailed="INITIALIZE_BUTTON_FAILED",e.InitializeButtonRequested="INITIALIZE_BUTTON_REQUESTED",e.InitializeButtonSucceeded="INITIALIZE_BUTTON_SUCCEEDED",e.DeinitializeButtonFailed="DEINITIALIZE_BUTTON_FAILED",e.DeinitializeButtonRequested="DEINITIALIZE_BUTTON_REQUESTED",e.DeinitializeButtonSucceeded="DEINITIALIZE_BUTTON_SUCCEEDED"}(Hv||(Hv={}));const Wv={data:{},errors:{},statuses:{}},$v={initializedContainers:{}},Yv={},Kv={};function Jv(e=Wv,t){return t.meta&&t.meta.methodId?d({data:d({[t.meta.methodId]:Zv}),errors:d({[t.meta.methodId]:Qv}),statuses:d({[t.meta.methodId]:Xv})})(e,t):e}function Zv(e=$v,t){switch(t.type){case Hv.InitializeButtonSucceeded:return t.meta&&t.meta.containerId?Bv(e,{initializedContainers:{[t.meta.containerId]:!0}}):e;case Hv.DeinitializeButtonSucceeded:return Ov(e,"initializedContainers",{})}return e}function Qv(e=Yv,t){switch(t.type){case Hv.InitializeButtonRequested:case Hv.InitializeButtonSucceeded:return Ov(e,"initializeError",void 0);case Hv.InitializeButtonFailed:return Ov(e,"initializeError",t.payload);case Hv.DeinitializeButtonRequested:case Hv.DeinitializeButtonSucceeded:return Ov(e,"deinitializeError",void 0);case Hv.DeinitializeButtonFailed:return Ov(e,"deinitializeError",t.payload);default:return e}}function Xv(e=Kv,t){switch(t.type){case Hv.InitializeButtonRequested:return Ov(e,"isInitializing",!0);case Hv.InitializeButtonFailed:case Hv.InitializeButtonSucceeded:return Ov(e,"isInitializing",!1);case Hv.DeinitializeButtonRequested:return Ov(e,"isDeinitializing",!0);case Hv.DeinitializeButtonFailed:case Hv.DeinitializeButtonSucceeded:return Ov(e,"isDeinitializing",!1);default:return e}}const ef={meta:{},errors:{},statuses:{}};function tf(e=ef,t){return d({data:nf,errors:c(rf,bv),statuses:of})(e,t)}function nf(e,t){var n,i;switch(t.type){case Ct.LoadConfigSucceeded:return Bv(e,t.payload);case Yt.HydrateInitialState:{const r=Bv(e,null===(n=t.payload)||void 0===n?void 0:n.config);return r&&(null===(i=t.payload)||void 0===i?void 0:i.b2bApiSettings)?Object.assign(Object.assign({},r),{storeConfig:Object.assign(Object.assign({},r.storeConfig),{b2bApiSettings:t.payload.b2bApiSettings})}):r}default:return e}}function rf(e=ef.errors,t){switch(t.type){case Ct.LoadConfigSucceeded:return Ov(e,"loadError",void 0);case Ct.LoadConfigFailed:return Ov(e,"loadError",t.payload);default:return e}}function of(e=ef.statuses,t){switch(t.type){case Ct.LoadConfigRequested:return Ov(e,"isLoading",!0);case Ct.LoadConfigSucceeded:case Ct.LoadConfigFailed:return Ov(e,"isLoading",!1);default:return e}}const af={errors:{},statuses:{}};function sf(e=af,t){return d({data:df,errors:c(cf,bv),statuses:lf})(e,t)}function df(e,t){var n,i;switch(t.type){case $t.LoadCheckoutSucceeded:case kt.ApplyCouponSucceeded:case _g.UpdateShippingOptionSucceeded:case kt.RemoveCouponSucceeded:case Mm.LoadOrderSucceeded:return Lv(e,t.payload&&t.payload.coupons);case Yt.HydrateInitialState:return Lv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.coupons);default:return e}}function cf(e={},t){switch(t.type){case kt.ApplyCouponRequested:case kt.ApplyCouponSucceeded:return Ov(e,"applyCouponError",void 0);case kt.ApplyCouponFailed:return Ov(e,"applyCouponError",t.payload);case kt.RemoveCouponRequested:case kt.RemoveCouponSucceeded:return Ov(e,"removeCouponError",void 0);case kt.RemoveCouponFailed:return Ov(e,"removeCouponError",t.payload);default:return e}}function lf(e={},t){switch(t.type){case kt.ApplyCouponRequested:return Ov(e,"isApplyingCoupon",!0);case kt.ApplyCouponSucceeded:case kt.ApplyCouponFailed:return Ov(e,"isApplyingCoupon",!1);case kt.RemoveCouponRequested:return Ov(e,"isRemovingCoupon",!0);case kt.RemoveCouponSucceeded:case kt.RemoveCouponFailed:return Ov(e,"isRemovingCoupon",!1);default:return e}}const uf={errors:{},statuses:{}};function hf(e=uf,t){return d({data:pf,errors:c(mf,bv),statuses:yf})(e,t)}function pf(e,t){var n,i;switch(t.type){case $t.LoadCheckoutSucceeded:case _g.CreateConsignmentsSucceeded:case _g.UpdateConsignmentSucceeded:case _g.DeleteConsignmentSucceeded:case _g.UpdateShippingOptionSucceeded:case kt.ApplyCouponSucceeded:case kt.RemoveCouponSucceeded:case Nt.ApplyGiftCertificateSucceeded:case Nt.RemoveGiftCertificateSucceeded:return Lv(e,t.payload&&t.payload.giftCertificates);case Yt.HydrateInitialState:return Lv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.giftCertificates);default:return e}}function mf(e=uf.errors,t){switch(t.type){case Nt.ApplyGiftCertificateRequested:case Nt.ApplyGiftCertificateSucceeded:return Ov(e,"applyGiftCertificateError",void 0);case Nt.ApplyGiftCertificateFailed:return Ov(e,"applyGiftCertificateError",t.payload);case Nt.RemoveGiftCertificateRequested:case Nt.RemoveGiftCertificateSucceeded:return Ov(e,"removeGiftCertificateError",void 0);case Nt.RemoveGiftCertificateFailed:return Ov(e,"removeGiftCertificateError",t.payload);default:return e}}function yf(e=uf.statuses,t){switch(t.type){case Nt.ApplyGiftCertificateRequested:return Ov(e,"isApplyingGiftCertificate",!0);case Nt.ApplyGiftCertificateSucceeded:case Nt.ApplyGiftCertificateFailed:return Ov(e,"isApplyingGiftCertificate",!1);case Nt.RemoveGiftCertificateRequested:return Ov(e,"isRemovingGiftCertificate",!0);case Nt.RemoveGiftCertificateSucceeded:case Nt.RemoveGiftCertificateFailed:return Ov(e,"isRemovingGiftCertificate",!1);default:return e}}const gf={errors:{},statuses:{}};function vf(e=gf,t){return d({data:ff,errors:c(Sf,bv),statuses:_f})(e,t)}function ff(e,t){var n,i;switch(t.type){case tt.ContinueAsGuestSucceeded:case $t.LoadCheckoutSucceeded:return Bv(e,t.payload&&t.payload.customer);case Rt.CreateCustomerAddressSucceeded:return Bv(e,t.payload);case Yt.HydrateInitialState:return Bv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.customer);default:return e}}function Sf(e=gf.errors,t){switch(t.type){case Rt.CreateCustomerRequested:case Rt.CreateCustomerSucceeded:return Ov(e,"createError",void 0);case Rt.CreateCustomerFailed:return Ov(e,"createError",t.payload);case Rt.CreateCustomerAddressRequested:case Rt.CreateCustomerAddressSucceeded:return Ov(e,"createAddressError",void 0);case Rt.CreateCustomerAddressFailed:return Ov(e,"createAddressError",t.payload);default:return e}}function _f(e=gf.statuses,t){switch(t.type){case Rt.CreateCustomerRequested:return Ov(e,"isCreating",!0);case Rt.CreateCustomerFailed:case Rt.CreateCustomerSucceeded:return Ov(e,"isCreating",!1);case Rt.CreateCustomerAddressRequested:return Ov(e,"isCreatingAddress",!0);case Rt.CreateCustomerAddressFailed:case Rt.CreateCustomerAddressSucceeded:return Ov(e,"isCreatingAddress",!1);default:return e}}const wf={data:{},errors:{},statuses:{}};function If(e=wf,t){return d({data:Cf,errors:c(bf,bv),statuses:Pf})(e,t)}function Cf(e=wf.data,t){switch(t.type){case Wt.InitializeSucceeded:return Bv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!0}});case Wt.DeinitializeSucceeded:return Bv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!1}})}return e}function bf(e=wf.errors,t){switch(t.type){case Wt.InitializeRequested:case Wt.InitializeSucceeded:return Bv(e,{initializeErrors:Object.assign({},e.initializeErrors),initializeMethodId:e.initializeMethodId?e.initializeMethodId:void 0});case Wt.InitializeFailed:return Bv(e,{initializeErrors:Object.assign(Object.assign({},e.initializeErrors),{[t.meta&&t.meta.methodId]:t.payload}),initializeMethodId:t.meta&&t.meta.methodId});case Wt.DeinitializeRequested:case Wt.DeinitializeSucceeded:return Bv(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Wt.DeinitializeFailed:return Bv(e,{deinitializeError:t.payload,deinitializeMethodId:t.meta&&t.meta.methodId});case Wt.SignInRequested:case Wt.SignInSucceeded:return Bv(e,{signInError:void 0,signInMethodId:void 0});case Wt.SignInFailed:return Bv(e,{signInError:t.payload,signInMethodId:t.meta&&t.meta.methodId});case Wt.SignOutRequested:case Wt.SignOutSucceeded:return Bv(e,{signOutError:void 0,signOutMethodId:void 0});case Wt.SignOutFailed:return Bv(e,{signOutError:t.payload,signOutMethodId:t.meta&&t.meta.methodId});case Wt.ExecutePaymentMethodCheckoutRequested:case Wt.ExecutePaymentMethodCheckoutSucceeded:return Bv(e,{executePaymentMethodCheckoutError:void 0,executePaymentMethodCheckoutMethodId:void 0});case Wt.ExecutePaymentMethodCheckoutFailed:return Bv(e,{executePaymentMethodCheckoutError:t.payload,executePaymentMethodCheckoutMethodId:t.meta&&t.meta.methodId});case Wt.WidgetInteractionStarted:case Wt.WidgetInteractionFinished:return Bv(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Wt.WidgetInteractionFailed:return Bv(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta.methodId});default:return e}}function Pf(e=wf.statuses,t){switch(t.type){case Wt.InitializeRequested:return Bv(e,{isInitializing:!0,initializeMethodId:t.meta&&t.meta.methodId});case Wt.InitializeFailed:case Wt.InitializeSucceeded:return Bv(e,{isInitializing:!1,initializeMethodId:void 0});case Wt.DeinitializeRequested:return Bv(e,{isDeinitializing:!0,deinitializeMethodId:t.meta&&t.meta.methodId});case Wt.DeinitializeFailed:case Wt.DeinitializeSucceeded:return Bv(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Wt.SignInRequested:return Bv(e,{isSigningIn:!0,signInMethodId:t.meta&&t.meta.methodId});case Wt.SignInFailed:case Wt.SignInSucceeded:return Bv(e,{isSigningIn:!1,signInMethodId:void 0});case Wt.SignOutRequested:return Bv(e,{isSigningOut:!0,signOutMethodId:t.meta&&t.meta.methodId});case Wt.SignOutFailed:case Wt.SignOutSucceeded:return Bv(e,{isSigningOut:!1,signOutMethodId:void 0});case Wt.ExecutePaymentMethodCheckoutRequested:return Bv(e,{isExecutingPaymentMethodCheckout:!0,executePaymentMethodCheckoutMethodId:t.meta&&t.meta.methodId});case Wt.ExecutePaymentMethodCheckoutFailed:case Wt.ExecutePaymentMethodCheckoutSucceeded:return Bv(e,{isExecutingPaymentMethodCheckout:!1,executePaymentMethodCheckoutMethodId:void 0});case Wt.WidgetInteractionStarted:return Bv(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta.methodId});case Wt.WidgetInteractionFinished:case Wt.WidgetInteractionFailed:return Bv(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const Of={errors:{},statuses:{}};function Ef(e=Of,t){return d({data:Af,errors:c(Tf,bv),statuses:kf})(e,t)}function Af(e,t){var n;return t.type===ln.LoadExtensionsSucceeded?Lv(e,t.payload):t.type===Yt.HydrateInitialState?Lv(e,null===(n=t.payload)||void 0===n?void 0:n.extensions):e}function Tf(e=Of.errors,t){switch(t.type){case ln.LoadExtensionsRequested:case ln.LoadExtensionsSucceeded:return Ov(e,"loadError",void 0);case ln.RenderExtensionRequested:case ln.RenderExtensionSucceeded:return Ov(e,"renderError",void 0);case ln.LoadExtensionsFailed:return Ov(e,"loadError",t.payload);case ln.RenderExtensionFailed:return Ov(e,"renderError",t.payload);default:return e}}function kf(e=Of.statuses,t){switch(t.type){case ln.LoadExtensionsRequested:return Ov(e,"isLoading",!0);case ln.LoadExtensionsSucceeded:case ln.LoadExtensionsFailed:return Ov(e,"isLoading",!1);default:return e}}const Df={errors:{},statuses:{}};function Mf(e=Df,t){return d({data:zf,extraFields:Nf,errors:c(xf,bv),statuses:Rf})(e,t)}function zf(e,t){var n;switch(t.type){case tn.LoadFormFieldsSucceeded:return Bv(e,t.payload);case Yt.HydrateInitialState:return Bv(e,null===(n=t.payload)||void 0===n?void 0:n.formFields);default:return e}}function Nf(e,t){var n,i;return t.type===Yt.HydrateInitialState&&null!==(i=null===(n=t.payload)||void 0===n?void 0:n.extraFields)&&void 0!==i?i:e}function xf(e=Df.errors,t){switch(t.type){case tn.LoadFormFieldsSucceeded:return Ov(e,"loadError",void 0);case tn.LoadFormFieldsFailed:return Ov(e,"loadError",t.payload);default:return e}}function Rf(e=Df.statuses,t){switch(t.type){case tn.LoadFormFieldsRequested:return Ov(e,"isLoading",!0);case tn.LoadFormFieldsSucceeded:case tn.LoadFormFieldsFailed:return Ov(e,"isLoading",!1);default:return e}}const Ff={errors:{},statuses:{}};function Lf(e=Ff,t){return d({data:Bf,errors:c(jf,bv),statuses:Uf})(e,t)}function Bf(e,t){return t.type===Dm.LoadCountriesSucceeded?Lv(e,t.payload):e}function jf(e=Ff.errors,t){switch(t.type){case Dm.LoadCountriesRequested:case Dm.LoadCountriesSucceeded:return Ov(e,"loadError",void 0);case Dm.LoadCountriesFailed:return Ov(e,"loadError",t.payload);default:return e}}function Uf(e=Ff.statuses,t){switch(t.type){case Dm.LoadCountriesRequested:return Ov(e,"isLoading",!0);case Dm.LoadCountriesSucceeded:case Dm.LoadCountriesFailed:return Ov(e,"isLoading",!1);default:return e}}const qf={errors:{},meta:{},statuses:{}};function Vf(e=qf,t){return d({data:Gf,errors:c(Wf,bv),meta:Hf,statuses:$f})(e,t)}function Gf(e,t){switch(t.type){case Mm.LoadOrderSucceeded:case Mm.LoadOrderPaymentsSucceeded:return Bv(e,le(t.payload,["billingAddress","coupons"]));default:return e}}function Hf(e,t){switch(t.type){case Mm.FinalizeOrderSucceeded:case Mm.SubmitOrderSucceeded:return Bv(e,Object.assign(Object.assign({},t.meta),{callbackUrl:t.payload&&t.payload.order.callbackUrl,orderToken:t.payload&&t.payload.order.token,payment:t.payload&&t.payload.order&&t.payload.order.payment}));default:return e}}function Wf(e=qf.errors,t){switch(t.type){case Mm.LoadOrderRequested:case Mm.LoadOrderSucceeded:case Mm.LoadOrderPaymentsSucceeded:case Mm.LoadOrderPaymentsRequested:return Ov(e,"loadError",void 0);case Mm.LoadOrderFailed:case Mm.LoadOrderPaymentsFailed:return Ov(e,"loadError",t.payload);default:return e}}function $f(e=qf.statuses,t){switch(t.type){case Mm.LoadOrderRequested:case Mm.LoadOrderPaymentsRequested:return Ov(e,"isLoading",!0);case Mm.LoadOrderSucceeded:case Mm.LoadOrderFailed:case Mm.LoadOrderPaymentsSucceeded:case Mm.LoadOrderPaymentsFailed:return Ov(e,"isLoading",!1);default:return e}}const Yf={};function Kf(e=Yf,t){return d({data:Jf})(e,t)}function Jf(e,t){switch(t.type){case Mm.LoadOrderPaymentsSucceeded:case Mm.LoadOrderSucceeded:return Mv(e,t.payload&&t.payload.billingAddress);default:return e}}function Zf(e={},t){return d({data:Qf})(e,t)}function Qf(e,t){return t.type===vy.SubmitPaymentSucceeded?t.payload:e}const Xf={errors:{},statuses:{}};function eS(e=Xf,t){return d({data:tS,errors:c(iS,bv),meta:nS,statuses:rS})(e,t)}function tS(e,t){switch(t.type){case qm.LoadPaymentMethodSucceeded:return function(e,t,n){if(!t)return e;const i=pe(t,"id"),r="object"==typeof n?me(n):n||i,o=j(e,r),a=[...e];if(-1===o)a.push(t);else{const n=e[o];a[o]=Rg(n)&&Rg(t)?Bv(n,t):t}return a}(e||[],t.payload,t.payload&&{id:t.payload.id,gateway:t.payload.gateway});case qm.LoadPaymentMethodsSucceeded:return Lv(e,t.payload,{matchObject:(e,t)=>e.id===t.id&&e.gateway===t.gateway});default:return e}}function nS(e,t){return t.type===qm.LoadPaymentMethodsSucceeded?Bv(e,t.meta):e}function iS(e=Xf.errors,t){switch(t.type){case qm.LoadPaymentMethodsRequested:case qm.LoadPaymentMethodsSucceeded:return Ov(e,"loadError",void 0);case qm.LoadPaymentMethodsFailed:return Ov(e,"loadError",t.payload);case qm.LoadPaymentMethodRequested:case qm.LoadPaymentMethodSucceeded:return Bv(e,{loadMethodId:void 0,loadMethodError:void 0});case qm.LoadPaymentMethodFailed:return Bv(e,{loadMethodId:t.meta.methodId,loadMethodError:t.payload});default:return e}}function rS(e=Xf.statuses,t){switch(t.type){case qm.LoadPaymentMethodsRequested:return Ov(e,"isLoading",!0);case qm.LoadPaymentMethodsSucceeded:case qm.LoadPaymentMethodsFailed:return Ov(e,"isLoading",!1);case qm.LoadPaymentMethodRequested:return Bv(e,{isLoadingMethod:!0,loadMethodId:t.meta.methodId});case qm.LoadPaymentMethodSucceeded:case qm.LoadPaymentMethodFailed:return Bv(e,{isLoadingMethod:!1,loadMethodId:void 0});default:return e}}const oS={data:{},errors:{},statuses:{}};function aS(e=oS,t){return d({data:sS,errors:c(dS,bv),statuses:cS})(e,t)}function sS(e=oS.data,t){switch(t.type){case Km.InitializeSucceeded:if(t.meta){const{methodId:n,gatewayId:i}=t.meta,r=i?`${n}.${i}`:n;return Bv(e,{[r]:{isInitialized:!0}})}break;case Km.DeinitializeSucceeded:if(t.meta){const{methodId:n,gatewayId:i}=t.meta,r=i?`${n}.${i}`:n;return Bv(e,{[r]:{isInitialized:!1}})}}return e}function dS(e=oS.errors,t){switch(t.type){case Km.InitializeRequested:case Km.InitializeSucceeded:return Bv(e,{initializeError:void 0,initializeMethodId:void 0});case Km.InitializeFailed:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return Bv(e,{initializeError:t.payload,initializeMethodId:n})}case Km.DeinitializeRequested:case Km.DeinitializeSucceeded:return Bv(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Km.DeinitializeFailed:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return Bv(e,{deinitializeError:t.payload,deinitializeMethodId:n})}case Km.ExecuteRequested:case Km.ExecuteSucceeded:return Bv(e,{executeError:void 0,executeMethodId:void 0});case Km.ExecuteFailed:return Bv(e,{executeError:t.payload,executeMethodId:t.meta&&t.meta.methodId});case Km.FinalizeRequested:case Km.FinalizeSucceeded:return Bv(e,{finalizeError:void 0,finalizeMethodId:void 0});case Km.FinalizeFailed:return Bv(e,{finalizeError:t.payload,finalizeMethodId:t.meta&&t.meta.methodId});case Km.WidgetInteractionStarted:case Km.WidgetInteractionFinished:return Bv(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Km.WidgetInteractionFailed:return Bv(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta.methodId});default:return e}}function cS(e=oS.statuses,t){switch(t.type){case Km.InitializeRequested:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return Bv(e,{isInitializing:!0,initializeMethodId:n})}case Km.InitializeFailed:case Km.InitializeSucceeded:return Bv(e,{isInitializing:!1,initializeMethodId:void 0});case Km.DeinitializeRequested:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return Bv(e,{isDeinitializing:!0,deinitializeMethodId:n})}case Km.DeinitializeFailed:case Km.DeinitializeSucceeded:return Bv(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Km.ExecuteRequested:return Bv(e,{isExecuting:!0,executeMethodId:t.meta&&t.meta.methodId});case Km.ExecuteFailed:case Km.ExecuteSucceeded:return Bv(e,{isExecuting:!1,executeMethodId:void 0});case Km.FinalizeRequested:return Bv(e,{isFinalizing:!0,finalizeMethodId:t.meta&&t.meta.methodId});case Km.FinalizeFailed:case Km.FinalizeSucceeded:return Bv(e,{isFinalizing:!1,finalizeMethodId:void 0});case Km.WidgetInteractionStarted:return Bv(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta.methodId});case Km.WidgetInteractionFinished:case Km.WidgetInteractionFailed:return Bv(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const lS={data:{}};function uS(e=lS,t){return d({data:hS})(e,t)}function hS(e=lS.data,t){return t.type===mg.UpdatePaymentProviderCustomer?Bv(e,t.payload):e}const pS={data:[],errors:{},statuses:{}};function mS(e=pS,t){return d({data:yS,errors:c(vS,bv),meta:gS,statuses:fS})(e,t)}function yS(e=pS.data,t){return t.type===Ug.LoadInstrumentsSucceeded?Lv(e,t.payload&&t.payload.vaultedInstruments||[]):e}function gS(e,t){switch(t.type){case Ug.LoadInstrumentsSucceeded:case Ug.DeleteInstrumentSucceeded:return Bv(e,t.meta);default:return e}}function vS(e=pS.errors,t){switch(t.type){case Ug.LoadInstrumentsRequested:case Ug.LoadInstrumentsSucceeded:return Ov(e,"loadError",void 0);case Ug.DeleteInstrumentRequested:case Ug.DeleteInstrumentSucceeded:return Bv(e,{deleteError:void 0,failedInstrument:void 0});case Ug.LoadInstrumentsFailed:return Ov(e,"loadError",t.payload);case Ug.DeleteInstrumentFailed:return Bv(e,{deleteError:t.payload,failedInstrument:t.meta.instrumentId});default:return e}}function fS(e=pS.statuses,t){switch(t.type){case Ug.LoadInstrumentsRequested:return Ov(e,"isLoading",!0);case Ug.DeleteInstrumentRequested:return Bv(e,{isDeleting:!0,deletingInstrument:t.meta.instrumentId});case Ug.LoadInstrumentsSucceeded:case Ug.LoadInstrumentsFailed:return Ov(e,"isLoading",!1);case Ug.DeleteInstrumentSucceeded:case Ug.DeleteInstrumentFailed:return Bv(e,{isDeleting:!1,deletingInstrument:void 0});default:return e}}const SS={data:{}};function _S(e=SS,t){return t.meta&&t.meta.methodId?d({data:d({[t.meta.methodId]:wS})})(e,t):e}function wS(e,t){switch(t.type){case yg.InitializeRemoteBillingSucceeded:return Ov(e,"billing",t.payload&&t.payload.billing);case yg.InitializeRemoteShippingSucceeded:return Ov(e,"shipping",t.payload&&t.payload.shipping);case yg.LoadRemoteSettingsSucceeded:return Ov(e,"settings",t.payload);case yg.UpdateRemoteCheckout:return Bv(e,t.payload);default:return e}}const IS={errors:{updateShippingOptionError:{},updateError:{},deleteError:{}},statuses:{isUpdating:{},isUpdatingShippingOption:{},isDeleting:{}}};function CS(e=IS,t){return d({data:bS,errors:c(PS,bv),statuses:OS})(e,t)}function bS(e,t){var n,i;switch(t.type){case $t.LoadCheckoutSucceeded:case _g.LoadShippingOptionsSucceeded:case _g.CreateConsignmentsSucceeded:case _g.UpdateConsignmentSucceeded:case _g.DeleteConsignmentSucceeded:case _g.UpdateShippingOptionSucceeded:case kt.ApplyCouponSucceeded:case kt.RemoveCouponSucceeded:return Lv(e,t.payload&&t.payload.consignments);case Rt.SignOutCustomerSucceeded:return Lv(e,[]);case Yt.HydrateInitialState:return Lv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.consignments);default:return e}}function PS(e=IS.errors,t){switch(t.type){case $t.LoadCheckoutRequested:case $t.LoadCheckoutSucceeded:case _g.LoadShippingOptionsSucceeded:case _g.LoadShippingOptionsRequested:return Ov(e,"loadError",void 0);case $t.LoadCheckoutFailed:case _g.LoadShippingOptionsFailed:return Ov(e,"loadError",t.payload);case _g.CreateConsignmentsRequested:case _g.CreateConsignmentsSucceeded:return Ov(e,"createError",void 0);case _g.CreateConsignmentsFailed:return Ov(e,"createError",t.payload);case _g.UpdateConsignmentSucceeded:case _g.UpdateConsignmentRequested:return t.meta?Bv(e,{updateError:{[t.meta.id]:void 0}}):e;case _g.UpdateConsignmentFailed:return t.meta?Bv(e,{updateError:{[t.meta.id]:t.payload}}):e;case _g.DeleteConsignmentSucceeded:case _g.DeleteConsignmentRequested:return t.meta?Bv(e,{deleteError:{[t.meta.id]:void 0}}):e;case _g.DeleteConsignmentFailed:return t.meta?Bv(e,{deleteError:{[t.meta.id]:t.payload}}):e;case _g.UpdateShippingOptionRequested:case _g.UpdateShippingOptionSucceeded:return t.meta?Bv(e,{updateShippingOptionError:{[t.meta.id]:void 0}}):e;case _g.UpdateShippingOptionFailed:return t.meta?Bv(e,{updateShippingOptionError:{[t.meta.id]:t.payload}}):e;default:return e}}function OS(e=IS.statuses,t){switch(t.type){case $t.LoadCheckoutRequested:return Ov(e,"isLoading",!0);case _g.LoadShippingOptionsRequested:return Ov(e,"isLoadingShippingOptions",!0);case $t.LoadCheckoutSucceeded:case $t.LoadCheckoutFailed:return Ov(e,"isLoading",!1);case _g.LoadShippingOptionsSucceeded:case _g.LoadShippingOptionsFailed:return Ov(e,"isLoadingShippingOptions",!1);case _g.CreateConsignmentsRequested:return Ov(e,"isCreating",!0);case _g.CreateConsignmentsSucceeded:case _g.CreateConsignmentsFailed:return Ov(e,"isCreating",!1);case _g.UpdateConsignmentRequested:return t.meta?Bv(e,{isUpdating:{[t.meta.id]:!0}}):e;case _g.UpdateConsignmentSucceeded:case _g.UpdateConsignmentFailed:return t.meta?Bv(e,{isUpdating:{[t.meta.id]:!1}}):e;case _g.DeleteConsignmentRequested:return t.meta?Bv(e,{isDeleting:{[t.meta.id]:!0}}):e;case _g.DeleteConsignmentSucceeded:case _g.DeleteConsignmentFailed:return t.meta?Bv(e,{isDeleting:{[t.meta.id]:!1}}):e;case _g.UpdateShippingOptionRequested:return t.meta?Bv(e,{isUpdatingShippingOption:{[t.meta.id]:!0}}):e;case _g.UpdateShippingOptionSucceeded:case _g.UpdateShippingOptionFailed:return t.meta?Bv(e,{isUpdatingShippingOption:{[t.meta.id]:!1}}):e;default:return e}}function ES(e,t){const n={};return Object.keys(e).forEach(i=>{const r=e[i],o=t?`${t}.${i}`:i;"object"==typeof r?Object.assign(n,ES(r,o)):n[o]=r}),n}function AS(e){return Object.keys(e).sort().reduce((t,n)=>Object.assign(Object.assign({},t),{[n]:e[n]}),{})}const TS={errors:{},statuses:{}};function kS(e=TS,t){return d({data:DS,errors:c(MS,bv),statuses:zS})(e,t)}function DS(e,t){if(t.type!==$g.LoadPickupOptionsSucceeded)return e;if(t.meta){const n=AS(ES({consignmentId:t.meta.consignmentId,searchArea:t.meta.searchArea}));return Ov(e,btoa(`${JSON.stringify(n)}`),t.payload)}}function MS(e=TS.errors,t){switch(t.type){case $g.LoadPickupOptionsRequested:case $g.LoadPickupOptionsSucceeded:return Ov(e,"loadError",void 0);case $g.LoadPickupOptionsFailed:return Ov(e,"loadError",t.payload);default:return e}}function zS(e=TS.statuses,t){switch(t.type){case $g.LoadPickupOptionsRequested:return Ov(e,"isLoading",!0);case $g.LoadPickupOptionsSucceeded:case $g.LoadPickupOptionsFailed:return Ov(e,"isLoading",!1);default:return e}}const NS={errors:{},statuses:{}};function xS(e=NS,t){return d({data:RS,errors:c(FS,bv),statuses:LS})(e,t)}function RS(e,t){return t.type===Og.LoadShippingCountriesSucceeded?Lv(e,t.payload):e}function FS(e=NS.errors,t){switch(t.type){case Og.LoadShippingCountriesRequested:case Og.LoadShippingCountriesSucceeded:return Ov(e,"loadError",void 0);case Og.LoadShippingCountriesFailed:return Ov(e,"loadError",t.payload);default:return e}}function LS(e=NS.statuses,t){switch(t.type){case Og.LoadShippingCountriesRequested:return Ov(e,"isLoading",!0);case Og.LoadShippingCountriesSucceeded:case Og.LoadShippingCountriesFailed:return Ov(e,"isLoading",!1);default:return e}}const BS={data:{},errors:{},statuses:{}};function jS(e=BS,t){return d({data:US,errors:c(qS,bv),statuses:VS})(e,t)}function US(e=BS.data,t){switch(t.type){case Yg.InitializeSucceeded:return Bv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!0}});case Yg.DeinitializeSucceeded:return Bv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!1}})}return e}function qS(e=BS.errors,t){switch(t.type){case Yg.InitializeRequested:case Yg.InitializeSucceeded:return Bv(e,{initializeError:void 0,initializeMethodId:void 0});case Yg.InitializeFailed:return Bv(e,{initializeError:t.payload,initializeMethodId:t.meta&&t.meta.methodId});case Yg.DeinitializeRequested:case Yg.DeinitializeSucceeded:return Bv(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Yg.DeinitializeFailed:return Bv(e,{deinitializeError:t.payload,deinitializeMethodId:t.meta&&t.meta.methodId});case Yg.UpdateAddressRequested:case Yg.UpdateAddressSucceeded:return Bv(e,{updateAddressError:void 0,updateAddressMethodId:void 0});case Yg.UpdateAddressFailed:return Bv(e,{updateAddressError:t.payload,updateAddressMethodId:t.meta&&t.meta.methodId});case Yg.SelectOptionRequested:case Yg.SelectOptionSucceeded:return Bv(e,{selectOptionError:void 0,selectOptionMethodId:void 0});case Yg.SelectOptionFailed:return Bv(e,{selectOptionError:t.payload,selectOptionMethodId:t.meta&&t.meta.methodId});case Yg.WidgetInteractionStarted:case Yg.WidgetInteractionFinished:return Bv(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Yg.WidgetInteractionFailed:return Bv(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta&&t.meta.methodId});default:return e}}function VS(e=BS.statuses,t){switch(t.type){case Yg.InitializeRequested:return Bv(e,{isInitializing:!0,initializeMethodId:t.meta&&t.meta.methodId});case Yg.InitializeFailed:case Yg.InitializeSucceeded:return Bv(e,{isInitializing:!1,initializeMethodId:void 0});case Yg.DeinitializeRequested:return Bv(e,{isDeinitializing:!0,deinitializeMethodId:t.meta&&t.meta.methodId});case Yg.DeinitializeFailed:case Yg.DeinitializeSucceeded:return Bv(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Yg.UpdateAddressRequested:return Bv(e,{isUpdatingAddress:!0,updateAddressMethodId:t.meta&&t.meta.methodId});case Yg.UpdateAddressFailed:case Yg.UpdateAddressSucceeded:return Bv(e,{isUpdatingAddress:!1,updateAddressMethodId:void 0});case Yg.SelectOptionRequested:return Bv(e,{isSelectingOption:!0,selectOptionMethodId:t.meta&&t.meta.methodId});case Yg.SelectOptionFailed:case Yg.SelectOptionSucceeded:return Bv(e,{isSelectingOption:!1,selectOptionMethodId:void 0});case Yg.WidgetInteractionStarted:return Bv(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta&&t.meta.methodId});case Yg.WidgetInteractionFinished:case Yg.WidgetInteractionFailed:return Bv(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const GS={errors:{},statuses:{}};function HS(e=GS,t){return d({data:WS,errors:c($S,bv),statuses:YS})(e,t)}function WS(e,t){return t.type===cv.SendSignInEmailSucceeded?Bv(e,t.payload):e}function $S(e=GS.errors,t){switch(t.type){case cv.SendSignInEmailRequested:case cv.SendSignInEmailSucceeded:return Ov(e,"sendError",void 0);case cv.SendSignInEmailFailed:return Ov(e,"sendError",t.payload);default:return e}}function YS(e=GS.statuses,t){switch(t.type){case cv.SendSignInEmailRequested:return Ov(e,"isSending",!0);case cv.SendSignInEmailFailed:case cv.SendSignInEmailSucceeded:return Ov(e,"isSending",!1);default:return e}}const KS={errors:{},statuses:{}};function JS(e=KS,t){return d({errors:c(ZS,bv),statuses:QS})(e,t)}function ZS(e=KS.errors,t){switch(t.type){case Eg.ApplyStoreCreditRequested:case Eg.ApplyStoreCreditSucceeded:return Ov(e,"applyError",void 0);case Eg.ApplyStoreCreditFailed:return Ov(e,"applyError",t.payload);default:return e}}function QS(e=KS.statuses,t){switch(t.type){case Eg.ApplyStoreCreditRequested:return Ov(e,"isApplying",!0);case Eg.ApplyStoreCreditSucceeded:case Eg.ApplyStoreCreditFailed:return Ov(e,"isApplying",!1);default:return e}}const XS={errors:{},statuses:{}};function e_(e=XS,t){return d({errors:c(t_,bv),statuses:n_})(e,t)}function t_(e=XS.errors,t){switch(t.type){case kg.UpdateSubscriptionsRequested:case kg.UpdateSubscriptionsSucceeded:return Ov(e,"updateError",void 0);case kg.UpdateSubscriptionsFailed:return Ov(e,"updateError",t.payload);default:return e}}function n_(e=XS.statuses,t){switch(t.type){case kg.UpdateSubscriptionsRequested:return Ov(e,"isUpdating",!0);case kg.UpdateSubscriptionsFailed:case kg.UpdateSubscriptionsSucceeded:return Ov(e,"isUpdating",!1);default:return e}}const i_={errors:{},statuses:{}};function r_(e=i_,t){return d({data:o_,errors:c(a_,bv),statuses:s_})(e,t)}function o_(e,t){var n;switch(t.type){case $t.LoadCheckoutSucceeded:case $t.UpdateCheckoutSucceeded:case Eg.ApplyStoreCreditSucceeded:case tt.UpdateBillingAddressSucceeded:case kt.ApplyCouponSucceeded:case kt.RemoveCouponSucceeded:case _g.CreateConsignmentsSucceeded:case _g.UpdateConsignmentSucceeded:case _g.DeleteConsignmentSucceeded:case _g.UpdateShippingOptionSucceeded:case _g.LoadShippingOptionsSucceeded:case Nt.ApplyGiftCertificateSucceeded:case Nt.RemoveGiftCertificateSucceeded:case rn.VerifyCheckoutSucceeded:return Bv(e,le(t.payload,["billingAddress","cart","consignments","customer","coupons","giftCertificates"]));case Mm.SubmitOrderSucceeded:return Ov(e,"orderId",t.payload&&t.payload.order.orderId);case Yt.HydrateInitialState:return Bv(e,le(null===(n=t.payload)||void 0===n?void 0:n.checkout,["billingAddress","cart","consignments","customer","coupons","giftCertificates"]));default:return e}}function a_(e=i_.errors,t){switch(t.type){case $t.LoadCheckoutRequested:case $t.LoadCheckoutSucceeded:return Ov(e,"loadError",void 0);case $t.LoadCheckoutFailed:return Ov(e,"loadError",t.payload);case $t.UpdateCheckoutRequested:case $t.UpdateCheckoutSucceeded:return Ov(e,"updateError",void 0);case $t.UpdateCheckoutFailed:return Ov(e,"updateError",t.payload);default:return e}}function s_(e=i_.statuses,t){switch(t.type){case $t.LoadCheckoutRequested:return Ov(e,"isLoading",!0);case $t.LoadCheckoutFailed:case $t.LoadCheckoutSucceeded:return Ov(e,"isLoading",!1);case $t.UpdateCheckoutRequested:return Ov(e,"isUpdating",!0);case $t.UpdateCheckoutFailed:case $t.UpdateCheckoutSucceeded:return Ov(e,"isUpdating",!1);case rn.ExecuteRequested:return Ov(e,"isExecutingSpamCheck",!0);case rn.ExecuteFailed:case rn.ExecuteSucceeded:return Ov(e,"isExecutingSpamCheck",!1);default:return e}}function d_(e,t){if(null==e)throw t?t():new Error("An unexpected error has occurred.");return e}function c_(e){return function(e){const t=Object.create(e);return function(e,t){let n=Object.getPrototypeOf(e);for(;n;)t(n),n=Object.getPrototypeOf(n)}(e,n=>{Object.getOwnPropertyNames(n).forEach(n=>{"constructor"!==n&&"function"==typeof t[n]&&"_"!==n.charAt(0)&&(t[n]=((e,t)=>(...n)=>p(e[t].call(e,...n)))(e,n))})}),t}(e)}const l_={"mollie.credit_card":{provider:"mollie",method:"credit_card"},"adyenv2.scheme":{provider:"adyenv2",method:"scheme"},"adyenv3.scheme":{provider:"adyenv3",method:"scheme"},"adyenv2.bcmc":{provider:"adyenv2",method:"bcmc"},"adyenv2.ideal":{provider:"adyenv2",method:"ideal"},"adyenv2.sepadirectdebit":{provider:"adyenv2",method:"sepadirectdebit"},"adyenv2.directEbanking":{provider:"adyenv2",method:"directEbanking"},"adyenv2.giropay":{provider:"adyenv2",method:"giropay"},braintree:{provider:"braintree",method:"credit_card"},braintreepaypal:{provider:"braintree",method:"paypal"},braintreeach:{provider:"braintree",method:"ach"},authorizenet:{provider:"authorizenet",method:"credit_card"},elavon:{provider:"elavon",method:"credit_card"},checkoutcom:{provider:"checkoutcom",method:"credit_card"},"checkoutcom.credit_card":{provider:"checkoutcom",method:"credit_card"},"checkoutcom.card":{provider:"checkoutcom",method:"card"},sagepay:{provider:"sagepay",method:"credit_card"},stripe:{provider:"stripe",method:"credit_card"},"stripev3.card":{provider:"stripev3",method:"card"},"stripeupe.card":{provider:"stripeupe",method:"card"},cybersource:{provider:"cybersource",method:"credit_card"},cybersourcev2:{provider:"cybersourcev2",method:"credit_card"},bnz:{provider:"bnz",method:"credit_card"},converge:{provider:"converge",method:"credit_card"},bluesnapv2:{provider:"bluesnapv2",method:"credit_card"},"bluesnapdirect.credit_card":{provider:"bluesnapdirect",method:"credit_card"},"bluesnapdirect.ecp":{provider:"bluesnapdirect",method:"ecp"},"bluesnapdirect.sepa_direct_debit":{provider:"bluesnapdirect",method:"sepa_direct_debit"},orbital:{provider:"orbital",method:"credit_card"},paymetric:{provider:"paymetric",method:"credit_card"},bolt:{provider:"bolt",method:"credit_card"},"barclaycard.credit_card":{provider:"barclaycard",method:"credit_card"},moneris:{provider:"moneris",method:"credit_card"},cba_mpgs:{provider:"cba_mpgs",method:"credit_card"},worldpayaccess:{provider:"worldpayaccess",method:"credit_card"},"worldpayaccess.credit_card":{provider:"worldpayaccess",method:"credit_card"},squarev2:{provider:"squarev2",method:"credit_card"},paypalcommercecreditcards:{provider:"paypalcommerce",method:"credit_card"},paypalcommerce:{provider:"paypalcommerce",method:"paypal"},bigcommerce_payments_creditcards:{provider:"bigcommerce_payments",method:"credit_card"},bigcommerce_payments:{provider:"bigcommerce_payments",method:"paypal"},tdonlinemart:{provider:"tdonlinemart",method:"credit_card"}};function u_(e){return me({firstName:e.firstName,lastName:e.lastName,company:e.company,address1:e.address1,address2:e.address2,city:e.city,stateOrProvince:e.stateOrProvince,countryCode:e.countryCode,postalCode:e.postalCode,phone:e.phone,customFields:e.customFields},G)}const h_={errors:{},statuses:{}};function p_(){const e=function(){const e=vv(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.token},e=>()=>e),t=vv(e=>e.errors.loadError,e=>()=>e),n=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((i=Ev)=>({getToken:e(i),getLoadError:t(i),isLoading:n(i)}))}(),t=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingBillingAddress))),n=vv(e=>e.errors.updateError,e=>()=>e),i=vv(e=>e.errors.continueAsGuestError,e=>()=>e),r=vv(e=>e.errors.loadError,e=>()=>e),o=vv(e=>!!e.statuses.isUpdating,e=>()=>e),a=vv(e=>!!e.statuses.isContinuingAsGuest,e=>()=>e),s=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((d=zv)=>({getBillingAddress:e(d),getBillingAddressOrThrow:t(d),getUpdateError:n(d),getContinueAsGuestError:i(d),getLoadError:r(d),isUpdating:o(d),isContinuingAsGuest:a(d),isLoading:s(d)}))}(),n=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingCart))),n=vv(e=>e.errors.loadError,e=>()=>e),i=vv(e=>!!e.statuses.isLoading,e=>()=>e),r=vv(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.locale},e=>()=>e);return Oe((o=jv)=>({getCart:e(o),getCartOrThrow:t(o),getLoadError:n(o),isLoading:i(o),getLocale:r(o)}))}(),i=function(){const e=vv(e=>e,e=>()=>e),t=vv(e=>e.statuses,e=>Pe(t=>{if(t){const n=e[t];return!0===(n&&n.isInitializing)}return ve(e,{isInitializing:!0})})),n=vv(e=>e.data,e=>Pe((t,n)=>{const i=e[t];return!!i&&(n?!0===i.initializedContainers[n]:ve(i.initializedContainers,e=>!0===e))})),i=vv(e=>e.statuses,e=>Pe(t=>{if(t){const n=e[t];return!0===(n&&n.isDeinitializing)}return ve(e,{isDeinitializing:!0})})),r=vv(e=>e.errors,e=>Pe(t=>{const n=t?e[t]:B(Ce(e),e=>!(!e||!e.initializeError));return n&&n.initializeError})),o=vv(e=>e.errors,e=>Pe(t=>{const n=t?e[t]:B(Ce(e),e=>!(!e||!e.deinitializeError));return n&&n.deinitializeError}));return Oe((a=Wv)=>({getState:e(a),isInitializing:t(a),isInitialized:n(a),isDeinitializing:i(a),getInitializeError:r(a),getDeinitializeError:o(a)}))}(),r=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.data,e=>t=>{if(!e)return;const{flashMessages:n}=e.context;return n?void 0!==t?n.filter(({type:e})=>t===e):n:void 0}),n=vv(e=>e.data,(e,{formState:t})=>t&&t.data,(e,t={customerAccount:[],shippingAddress:[],billingAddress:[]})=>()=>e?Object.assign(Object.assign({},e.storeConfig),{formFields:t}):void 0),i=vv(n,e=>()=>d_(e(),()=>new rt(et.MissingCheckoutConfig))),r=vv(e=>e.data&&e.data.context,e=>()=>e),o=vv(e=>e.meta&&e.meta.externalSource,e=>()=>e),a=vv(e=>{var t;return null===(t=e.meta)||void 0===t?void 0:t.host},e=>()=>e),s=vv(e=>{var t;return null===(t=e.meta)||void 0===t?void 0:t.locale},e=>()=>e),d=vv(e=>e.meta&&e.meta.variantIdentificationToken,e=>()=>e),c=vv(e=>e.errors.loadError,e=>()=>e),l=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((u=ef,h)=>({getConfig:e(u),getFlashMessages:t(u),getStoreConfig:n(u,{formState:h}),getStoreConfigOrThrow:i(u,{formState:h}),getContextConfig:r(u),getExternalSource:o(u),getHost:a(u),getLocale:s(u),getVariantIdentificationToken:d(u),getLoadError:c(u),isLoading:l(u)}))}(),o=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.loadError,e=>()=>e),n=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((i=Ff)=>({getCountries:e(i),getLoadError:t(i),isLoading:n(i)}))}(),a=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.removeCouponError,e=>()=>e),n=vv(e=>e.errors.applyCouponError,e=>()=>e),i=vv(e=>!!e.statuses.isApplyingCoupon,e=>()=>e),r=vv(e=>!!e.statuses.isRemovingCoupon,e=>()=>e);return Oe((o=af)=>({getCoupons:e(o),getRemoveError:t(o),getApplyError:n(o),isApplying:i(o),isRemoving:r(o)}))}(),s=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingCustomer))),n=vv(e=>e.errors.createError,e=>()=>e),i=vv(e=>!!e.statuses.isCreating,e=>()=>e),r=vv(e=>e.errors.createAddressError,e=>()=>e),o=vv(e=>!!e.statuses.isCreatingAddress,e=>()=>e);return Oe((a=gf)=>({getCustomer:e(a),getCustomerOrThrow:t(a),getCreateAccountError:n(a),isCreatingCustomerAccount:i(a),getCreateAddressError:r(a),isCreatingCustomerAddress:o(a)}))}(),d=function(){const e=vv(e=>e.errors.signInMethodId,e=>e.errors.signInError,(e,t)=>n=>{if(!n||e===n)return t}),t=vv(e=>e.errors.signOutMethodId,e=>e.errors.signOutError,(e,t)=>n=>{if(!n||e===n)return t}),n=vv(e=>e.errors.executePaymentMethodCheckoutMethodId,e=>e.errors.executePaymentMethodCheckoutError,(e,t)=>n=>{if(!n||e===n)return t}),i=vv(e=>e.errors.initializeMethodId,e=>e.errors.initializeErrors,(e,t)=>n=>{if(e&&t)return n?t[n]:t[e]}),r=vv(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>n=>{if(!n||e===n)return t}),o=vv(e=>e.statuses.signInMethodId,e=>e.statuses.isSigningIn,(e,t)=>n=>!(n&&e!==n||!t)),a=vv(e=>e.statuses.signOutMethodId,e=>e.statuses.isSigningOut,(e,t)=>n=>!(n&&e!==n||!t)),s=vv(e=>e.statuses.executePaymentMethodCheckoutMethodId,e=>e.statuses.isExecutingPaymentMethodCheckout,(e,t)=>n=>!(n&&e!==n||!t)),d=vv(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>n=>!(n&&e!==n||!t)),c=vv(e=>e.data,e=>t=>!(!e[t]||!e[t].isInitialized)),l=vv(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((u=wf)=>({getSignInError:e(u),getSignOutError:t(u),getExecutePaymentMethodCheckoutError:n(u),getInitializeError:i(u),getWidgetInteractionError:r(u),isSigningIn:o(u),isSigningOut:a(u),isExecutingPaymentMethodCheckout:s(u),isInitializing:d(u),isInitialized:c(u),isWidgetInteracting:l(u)}))}(),c=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.removeGiftCertificateError,e=>()=>e),n=vv(e=>e.errors.applyGiftCertificateError,e=>()=>e),i=vv(e=>!!e.statuses.isApplyingGiftCertificate,e=>()=>e),r=vv(e=>!!e.statuses.isRemovingGiftCertificate,e=>()=>e);return Oe((o=uf)=>({getGiftCertificates:e(o),getRemoveError:t(o),getApplyError:n(o),isApplying:i(o),isRemoving:r(o)}))}(),l=function(){const e=vv(e=>e.data,e=>t=>{if(!e)return;const n=t.gateway?`${t.gateway}.${t.id}`:t.id,i=l_[n];return i?L(e,i):[]}),t=vv(e=>e.data,(e=[])=>t=>{const n=Ce(l_);return e.find(e=>e.bigpayToken===t&&"card"===e.type&&n.some(t=>K(e,t)))}),n=vv(t,e=>t=>d_(e(t),()=>new rt(et.MissingPaymentInstrument))),i=vv(e=>e.data,e=>()=>{if(e)return U(l_,t=>L(e,e=>K(e,t)))}),r=vv(e=>e.meta,e=>()=>e),o=vv(e=>e.errors.loadError,e=>()=>e),a=vv(e=>e.errors.failedInstrument,e=>e.errors.deleteError,(e,t)=>n=>{if(!n||e===n)return t}),s=vv(e=>e.statuses.isLoading,e=>()=>!!e),d=vv(e=>e.statuses.deletingInstrument,e=>e.statuses.isDeleting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((c=pS)=>({getCardInstrument:t(c),getCardInstrumentOrThrow:n(c),getInstruments:i(c),getInstrumentsByPaymentMethod:e(c),getInstrumentsMeta:r(c),getLoadError:o(c),getDeleteError:a(c),isLoading:s(c),isDeleting:d(c)}))}(),u=function(){const e=vv(e=>e.data,e=>(t=[],n)=>{const i=B(t,{code:n});return(e?e.shippingAddress:[]).map(e=>a(e,t,i))}),t=vv(e=>e.data,e=>(t=[],n)=>{const i=B(t,{code:n});return(e?e.billingAddress:[]).map(e=>a(e,t,i))}),n=vv(e=>e.data,e=>()=>e?e.customerAccount:[]),i=vv(e=>e.extraFields,e=>()=>e&&e.address.length?e.address.map(Ke):[]),r=vv(e=>e.errors.loadError,e=>()=>e),o=vv(e=>!!e.statuses.isLoading,e=>()=>e);function a(e,t,n){return"countryCode"===e.name?function(e,t=[],n){if(!t.length)return e;const{code:i=""}=n||{},r=t.map(({code:e,name:t})=>({value:e,label:t}));return Object.assign(Object.assign({},e),{options:{items:r},default:i,type:"array",fieldType:"dropdown",itemtype:"string"})}(e,t,n):"stateOrProvince"===e.name?function(e,t){const{subdivisions:n=[],requiresState:i}=t||{};if(!n.length)return Object.assign(Object.assign({},e),{required:null!=i&&i});const r=n.map(({code:e,name:t})=>({value:e,label:t}));return Object.assign(Object.assign({},e),{name:"stateOrProvinceCode",options:{items:r},required:null==i||i,type:"array",fieldType:"dropdown",itemtype:"string"})}(e,n):"postalCode"===e.name?function(e,t){const{hasPostalCodes:n=[]}=t||{};return void 0===n?e:Object.assign(Object.assign({},e),{required:Boolean(n)})}(e,n):e}return Oe((a=Df)=>({getShippingAddressFields:e(a),getBillingAddressFields:t(a),getCustomerAccountFields:n(a),getAddressExtraFields:i(a),getLoadError:r(a),isLoading:o(a)}))}(),h=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.meta,e=>()=>e),n=vv(e=>e.data,e=>(t,n)=>B(e,n?{id:t,gateway:n}:{id:t})),i=vv(n,e=>(t,n)=>d_(e(t,n),()=>new rt(et.MissingPaymentMethod))),r=vv(e=>e.errors.loadError,e=>()=>e),o=vv(e=>e.errors.loadMethodId,e=>e.errors.loadMethodError,(e,t)=>n=>{if(!n||e===n)return t}),a=vv(e=>e.statuses.isLoading,e=>()=>!!e),s=vv(e=>e.statuses.loadMethodId,e=>e.statuses.isLoadingMethod,(e,t)=>n=>!(n&&e!==n||!t));return Oe((d=Xf)=>({getPaymentMethods:e(d),getPaymentMethodsMeta:t(d),getPaymentMethod:n(d),getPaymentMethodOrThrow:i(d),getLoadError:r(d),getLoadMethodError:o(d),isLoading:a(d),isLoadingMethod:s(d)}))}(),p=function(){const e=vv(e=>e.errors.initializeMethodId,e=>e.errors.initializeError,(e,t)=>n=>{if(!n||e===n)return t}),t=vv(e=>e.errors.executeMethodId,e=>e.errors.executeError,(e,t)=>n=>{if(!n||e===n)return t}),n=vv(e=>e.errors.finalizeMethodId,e=>e.errors.finalizeError,(e,t)=>n=>{if(!n||e===n)return t}),i=vv(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>n=>{if(!n||e===n)return t}),r=vv(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>n=>!(n&&e!==n||!t)),o=vv(e=>e.data,e=>t=>{const n=t.gatewayId?`${t.methodId}.${t.gatewayId}`:t.methodId;return!(!e[n]||!e[n].isInitialized)}),a=vv(e=>e.statuses.executeMethodId,e=>e.statuses.isExecuting,(e,t)=>n=>!(n&&e!==n||!t)),s=vv(e=>e.statuses.finalizeMethodId,e=>e.statuses.isFinalizing,(e,t)=>n=>!(n&&e!==n||!t)),d=vv(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((c=oS)=>({getInitializeError:e(c),getExecuteError:t(c),getFinalizeError:n(c),getWidgetInteractingError:i(c),isInitializing:r(c),isInitialized:o(c),isExecuting:a(c),isFinalizing:s(c),isWidgetInteracting:d(c)}))}(),m=function(){const e=vv(e=>e.data,e=>(t,n)=>{if(!e)return;const i=AS(ES({consignmentId:t,searchArea:n})),r=btoa(`${JSON.stringify(i)}`);return e[r]}),t=vv(e=>e.errors.loadError,e=>()=>e),n=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((i=TS)=>({getPickupOptions:e(i),getLoadError:t(i),isLoading:n(i)}))}(),y=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingPaymentProviderCustomer)));return Oe((n=lS)=>({getPaymentProviderCustomer:e(n),getPaymentProviderCustomerOrThrow:t(n)}))}(),g=function(){const e=vv(e=>e.data,e=>t=>e[t]);return Oe((t=SS)=>({getCheckout:e(t)}))}(),v=function(){const e=vv(e=>e.data,e=>()=>{const t=null==e?void 0:e.find(e=>!e.selectedPickupOption);return null==t?void 0:t.shippingAddress}),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingShippingAddress))),n=vv(e=>e.data,e=>()=>{const t=null==e?void 0:e.filter(e=>!e.selectedPickupOption);return t?t.map(e=>e.shippingAddress):[]}),i=vv(n,e=>()=>d_(e(),()=>new rt(et.MissingShippingAddress)));return Oe((r=IS)=>({getShippingAddress:e(r),getShippingAddressOrThrow:t(r),getShippingAddresses:n(r),getShippingAddressesOrThrow:i(r)}))}(),f=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.loadError,e=>()=>e),n=vv(e=>e.statuses.isLoading,e=>()=>!!e);return Oe((i=NS)=>({getShippingCountries:e(i),getLoadError:t(i),isLoading:n(i)}))}(),S=function(){const e=vv(e=>e.errors.updateAddressMethodId,e=>e.errors.updateAddressError,(e,t)=>n=>{if(!n||e===n)return t}),t=vv(e=>e.errors.selectOptionMethodId,e=>e.errors.selectOptionError,(e,t)=>n=>{if(!n||e===n)return t}),n=vv(e=>e.errors.initializeMethodId,e=>e.errors.initializeError,(e,t)=>n=>{if(!n||e===n)return t}),i=vv(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>n=>{if(!n||e===n)return t}),r=vv(e=>e.statuses.updateAddressMethodId,e=>e.statuses.isUpdatingAddress,(e,t)=>n=>!(n&&e!==n||!t)),o=vv(e=>e.statuses.selectOptionMethodId,e=>e.statuses.isSelectingOption,(e,t)=>n=>!(n&&e!==n||!t)),a=vv(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>n=>!(n&&e!==n||!t)),s=vv(e=>e.data,e=>t=>!(!e[t]||!e[t].isInitialized)),d=vv(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((c=BS)=>({getUpdateAddressError:e(c),getSelectOptionError:t(c),getInitializeError:n(c),getWidgetInteractionError:i(c),isUpdatingAddress:r(c),isSelectingOption:o(c),isInitializing:a(c),isInitialized:s(c),isWidgetInteracting:d(c)}))}(),_=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingConsignments))),n=vv(e=>e.data,e=>t=>{if(e&&e.length)return B(e,{id:t})}),i=vv(e=>e.data,e=>t=>{if(e&&e.length)return B(e,e=>{return n=e.shippingAddress,i=t,Y(u_(n),u_(i));var n,i})}),r=vv(e=>e.data,e=>()=>{if(e&&e.length)return e[0].selectedShippingOption}),o=vv(e=>e.errors.loadError,e=>()=>e),a=vv(e=>e.errors.createError,e=>()=>e),s=vv(e=>e.errors.loadShippingOptionsError,e=>()=>e),d=vv(e,(e,{cart:t})=>t.getCart,(e,t)=>()=>{const n=t();if(!n)return[];const i=(e()||[]).reduce((e,t)=>e.concat(t.lineItemIds),[]);return(n.lineItems.physicalItems||[]).filter(e=>i.indexOf(e.id)<0)}),c=vv(e=>e.errors.updateError,e=>t=>t?e[t]:B(e)),l=vv(e=>e.errors.deleteError,e=>t=>t?e[t]:B(e)),u=vv(i,c,a,(e,t,n)=>i=>{const r=e(i);return r?t(r.id):n()}),h=vv(e=>e.errors.updateShippingOptionError,e=>t=>t?e[t]:B(e)),p=vv(e=>e.statuses.isLoading,e=>()=>!0===e),m=vv(e=>e.statuses.isLoadingShippingOptions,e=>()=>!0===e),y=vv(e=>e.statuses.isCreating,e=>()=>!0===e),g=vv(e=>e.statuses.isUpdating,e=>t=>t?!0===e[t]:!0===B(e)),v=vv(e=>e.statuses.isDeleting,e=>t=>t?!0===e[t]:!0===B(e)),f=vv(i,g,y,(e,t,n)=>i=>{const r=e(i);return r?t(r.id):n()}),S=vv(e=>e.statuses.isUpdatingShippingOption,e=>t=>t?!0===e[t]:!0===B(e));return Oe((_=IS,w)=>({getConsignments:e(_),getConsignmentsOrThrow:t(_),getConsignmentById:n(_),getConsignmentByAddress:i(_),getShippingOption:r(_),getLoadError:o(_),getCreateError:a(_),getLoadShippingOptionsError:s(_),getUnassignedItems:d(_,{cart:w}),getUpdateError:c(_),getDeleteError:l(_),getItemAssignmentError:u(_),getUpdateShippingOptionError:h(_),isLoading:p(_),isLoadingShippingOptions:m(_),isCreating:y(_),isUpdating:g(_),isDeleting:v(_),isAssigningItems:f(_),isUpdatingShippingOption:S(_)}))}(),w=function(){const e=vv(e=>e.data,(e,{billingAddress:t})=>t.getBillingAddress,(e,{cart:t})=>t.getCart,(e,{customer:t})=>t.getCustomer,(e,{consignments:t})=>t.getConsignments,(e,{coupons:t})=>t.getCoupons,(e,{giftCertificates:t})=>t.getGiftCertificates,(e,t,n,i,r,o,a)=>()=>{const s=t(),d=n(),c=i(),l=r()||[],u=o()||[],h=a()||[];if(e&&d&&c)return Object.assign(Object.assign({},e),{billingAddress:s,cart:d,customer:c,consignments:l,coupons:u,giftCertificates:h})}),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingCheckout))),n=vv(e,e=>t=>{const n=e();if(!n)return;const i=n.grandTotal||0,r=n.customer.storeCredit||0;return t?Math.max(i-r,0):n.outstandingBalance}),i=vv(e=>e.errors.loadError,e=>()=>e),r=vv(e=>e.errors.updateError,e=>()=>e),o=vv(e=>e.statuses.isExecutingSpamCheck,e=>()=>!0===e),a=vv(e=>e.statuses.isLoading,e=>()=>!0===e),s=vv(e=>e.statuses.isUpdating,e=>()=>!0===e);return Oe((d=i_,c,l,u,h,p,m)=>({getCheckout:e(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getCheckoutOrThrow:t(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getOutstandingBalance:n(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getLoadError:i(d),getUpdateError:r(d),isExecutingSpamCheck:o(d),isLoading:a(d),isUpdating:s(d)}))}(),I=function(){const e=vv(e=>e.data,(e,{billingAddress:t})=>t.getOrderBillingAddress(),(e,{coupons:t})=>t.getCoupons(),(e,t,n=[])=>()=>{if(e&&t)return Object.assign(Object.assign({},e),{billingAddress:t,coupons:n})}),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingOrder))),n=vv(e=>e.meta,e=>()=>e),i=vv(e=>e.errors.loadError,e=>()=>e),r=vv(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.payments},(e=[])=>t=>{const n=e.find(({providerId:e})=>e===t);return null==n?void 0:n.paymentId}),o=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((a=qf,s,d)=>({getOrder:e(a,{billingAddress:s,coupons:d}),getOrderOrThrow:t(a,{billingAddress:s,coupons:d}),getOrderMeta:n(a),getLoadError:i(a),getPaymentId:r(a),isLoading:o(a)}))}(),C=function(){const e=vv(e=>e.data,e=>()=>e);return Oe((t=Yf)=>({getOrderBillingAddress:e(t)}))}(),b=function(){const e=vv(({order:e})=>e.getOrderMeta,e=>()=>{const t=e();return t&&t.payment}),t=vv(({order:e})=>e.getOrder,e=>()=>{const t=e();return B(t&&t.payments,({providerId:e})=>"giftcertificate"!==e&&"storecredit"!==e)}),n=vv(({checkout:e})=>e.getCheckout,e=>()=>{const t=e();return B(t&&t.payments,({providerType:e})=>"PAYMENT_TYPE_HOSTED"===e)}),i=vv(e,n,t,(e,t,n)=>()=>{const i=e();if(i&&i.id)return{providerId:i.id,gatewayId:i.gateway};const r=t()||n();return r&&r.providerId?{providerId:r.providerId,gatewayId:r.gatewayId}:void 0}),r=vv(i,e=>()=>d_(e(),()=>new rt(et.MissingPaymentId))),o=vv(e,n,t,(e,t,n)=>()=>{const i=e();if(i&&i.status)return i.status.replace("PAYMENT_STATUS_","");const r=t()||n();return r?r.detail.step:void 0}),a=vv(o,e=>()=>d_(e(),()=>new rt(et.MissingPaymentStatus))),s=vv(({order:e})=>e.getOrderMeta,e=>()=>{const t=e();return t&&t.token}),d=vv(s,e=>()=>d_(e(),()=>new rt(et.MissingPaymentToken))),c=vv(e,e=>()=>{const t=e();return t&&t.redirectUrl}),l=vv(c,e=>()=>d_(e(),()=>new rt(et.MissingPaymentRedirectUrl))),u=vv(({checkout:e})=>e.getOutstandingBalance,e=>(t=!1)=>{const n=e(t);return!!n&&n>0}),h=vv(o,e=>t=>!(!t||!t.nonce)||"ACKNOWLEDGE"===e()||e()===$y);return Oe((e,t)=>({getPaymentId:i({checkout:e,order:t}),getPaymentIdOrThrow:r({checkout:e,order:t}),getPaymentStatus:o({checkout:e,order:t}),getPaymentStatusOrThrow:a({checkout:e,order:t}),getPaymentToken:s({checkout:e,order:t}),getPaymentTokenOrThrow:d({checkout:e,order:t}),getPaymentRedirectUrl:c({checkout:e,order:t}),getPaymentRedirectUrlOrThrow:l({checkout:e,order:t}),isPaymentDataRequired:u({checkout:e,order:t}),isPaymentDataSubmitted:h({checkout:e,order:t})}))}(),P=function(){const e=vv(e=>e.errors.applyError,e=>()=>e),t=vv(e=>!!e.statuses.isApplying,e=>()=>e);return Oe((n=h_)=>({getApplyError:e(n),isApplying:t(n)}))}(),O=function(){const e=vv(e=>e.errors.updateError,e=>()=>e),t=vv(e=>!!e.statuses.isUpdating,e=>()=>e);return Oe((n=XS)=>({getUpdateError:e(n),isUpdating:t(n)}))}(),E=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.sendError,e=>()=>e),n=vv(e=>!!e.statuses.isSending,e=>()=>e);return Oe((i=GS)=>({getEmail:e(i),getSendError:t(i),isSending:n(i)}))}(),A=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.data,e=>t=>null==e?void 0:e.find(e=>e.region===t)),n=vv(e=>e.errors.loadError,e=>()=>e),i=vv(e=>e.statuses.isLoading,e=>()=>!!e);return Oe((r=Of)=>({getExtensions:e(r),getExtensionByRegion:t(r),getLoadError:n(r),isLoading:i(r)}))}();return(T,k={})=>{const D=e(T.b2bToken),M=t(T.billingAddress),z=n(T.cart),N=i(T.checkoutButton),x=o(T.countries),R=a(T.coupons),F=s(T.customer),L=d(T.customerStrategies),B=A(T.extensions),j=u(T.formFields),U=c(T.giftCertificates),q=l(T.instruments),V=C(T.orderBillingAddress),G=h(T.paymentMethods),H=y(T.paymentProviderCustomer),W=p(T.paymentStrategies),$=m(T.pickupOptions),Y=g(T.remoteCheckout),K=v(T.consignments),J=f(T.shippingCountries),Z=S(T.shippingStrategies),Q=O(T.subscriptions),X=P(T.storeCredit),ee=E(T.signInEmail),te=_(T.consignments,z),ne=w(T.checkout,M,z,te,R,F,U),ie=I(T.order,V,R),re=b(ne,ie),oe={b2bToken:D,billingAddress:M,cart:z,checkout:ne,checkoutButton:N,config:r(T.config,T.formFields),consignments:te,countries:x,coupons:R,customer:F,customerStrategies:L,extensions:B,form:j,giftCertificates:U,instruments:q,order:ie,orderBillingAddress:V,payment:re,paymentMethods:G,paymentProviderCustomer:H,paymentStrategies:W,pickupOptions:$,remoteCheckout:Y,shippingAddress:K,shippingCountries:J,shippingStrategies:Z,signInEmail:ee,subscriptions:Q,storeCredit:X};return k.shouldWarnMutation?(ae=oe,Object.keys(ae).reduce((e,t)=>(e[t]=c_(ae[t]),e),{})):oe;var ae}}function m_(e={},t){const n=(o=function(){const e=new Iv;return["catalog_only","empty_cart","invalid_order_id","invalid_order_token","missing_order_token","missing_provider_token","missing_shipping_method","order_completion_error","order_could_not_be_finalized_error","order_create_failed","provider_fatal_error","provider_setup_error","stock_too_low"].forEach(t=>{e.register(t,(e,t)=>new Sv(e,t))}),e.register("invalid_payment_provider",e=>new Xr(e)),e.register("payment_config_not_found",e=>new Xr(e)),e}(),e=>S(e).pipe(P(e=>{if(e instanceof Error||e.payload instanceof Error)throw e;if((t=e.payload)&&"object"==typeof t&&["body","headers","status","statusText"].every(e=>Object.prototype.hasOwnProperty.call(t,e))){const t=e.payload.body&&e.payload.body.detail;throw Object.assign(Object.assign({},e),{payload:o.createError(e.payload,t)})}var t;throw e}))),i=p_(),r=d({b2bToken:Av,billingAddress:Nv,cart:Uv,checkout:r_,checkoutButton:Jv,config:tf,consignments:CS,countries:Lf,coupons:sf,customer:vf,customerStrategies:If,extensions:Ef,formFields:Mf,giftCertificates:hf,instruments:mS,orderBillingAddress:Kf,order:Vf,payment:Zf,paymentMethods:eS,paymentStrategies:aS,pickupOptions:kS,paymentProviderCustomer:uS,remoteCheckout:_S,shippingCountries:xS,shippingStrategies:jS,signInEmail:HS,subscriptions:e_,storeCredit:JS});var o;return u(r,e,Object.assign({actionTransformer:n,stateTransformer:e=>i(e)},t))}function y_(e){"https:"!==document.location.protocol&&wt().warn("The BigCommerce Checkout SDK should not be used on a non-HTTPS page"),"production"!==vt()&&wt().warn("Note that the development build is not optimized. To create a production build, set process​.env.NODE_ENV to `production`.");const t={meta:{externalSource:e&&e.externalSource,host:null==e?void 0:e.host,locale:null==e?void 0:e.locale,variantIdentificationToken:window.checkoutVariantIdentificationToken},errors:{},statuses:{}},{locale:i="",shouldWarnMutation:r=!0}=e||{},s=n({host:e&&e.host}),d=m_({config:t},{shouldWarnMutation:r}),c=new gt(s,{getBasePath:()=>{var e,t;return null!==(t=null===(e=d.getState().config.getStoreConfig())||void 0===e?void 0:e.links.baseUrl)&&void 0!==t?t:void 0},getFeatures:()=>{var e,t,n;return null!==(n=null===(t=null===(e=d.getState().config.getStoreConfig())||void 0===e?void 0:e.checkoutSettings)||void 0===t?void 0:t.features)&&void 0!==n?n:{}}}),l=Gm(d),u=new jm(c),h=new en(c),p=new bt(new Tt(s)),m=Sn(o()),y=new _n(c),g=new pn(m,y),v=new Vm(u,new ny(h)),f=new Ng(new xg(c)),S=new on(new an(c)),_=new nn(h,p,S),w=Hg(d,c),I=function(e,t,n={useFallback:!1}){const{useFallback:i}=n,r=new Gt(i);for(const[,n]of Object.entries(t))if(Ut(n))for(const t of n.resolveIds)r.register(t,()=>n(e));return r}(w,He,{useFallback:!0}),C=function(e,t){const n=new Gt;for(const[,i]of Object.entries(t))if(Ut(i))for(const t of i.resolveIds)n.register(t,()=>i(e));return n}(w,Ge),b=new xn(new Rn(c)),P=new Hn,O=new Kn(d,P),E=mt(d,function(){const e=function(){const e=vv(({checkout:e})=>e.getCheckout,e=>Bg(e)),t=vv(({order:e})=>e.getOrder,e=>Bg(e)),n=vv(({config:e})=>e.getStoreConfig,e=>Bg(e)),i=vv(({shippingAddress:e})=>e.getShippingAddress,({config:e})=>e.getContextConfig,(e,t)=>Bg(()=>{const n=e(),i=t();if(!n){if(!i||!i.geoCountryCode)return;return{firstName:"",lastName:"",company:"",address1:"",address2:"",city:"",stateOrProvince:"",stateOrProvinceCode:"",postalCode:"",country:"",phone:"",customFields:[],countryCode:i.geoCountryCode}}return n})),r=vv(({consignments:e})=>e.getConsignments,e=>Bg(()=>{const t=e(),n=null==t?void 0:t.find(e=>!e.selectedPickupOption);return null==n?void 0:n.availableShippingOptions})),o=vv(({consignments:e})=>e.getConsignments,e=>Bg(e)),a=vv(({consignments:e})=>e.getConsignments,e=>Bg(()=>{const t=e(),n=null==t?void 0:t.find(e=>!e.selectedPickupOption);return null==n?void 0:n.selectedShippingOption})),s=vv(({shippingCountries:e})=>e.getShippingCountries,e=>Bg(e)),d=vv(({billingAddress:e})=>e.getBillingAddress,({config:e})=>e.getContextConfig,(e,t)=>Bg(()=>{const n=e(),i=t();return(!n||Ce(le(n,"shouldSaveAddress","email","id")).every(e=>!e||!e.length))&&i&&i.geoCountryCode?{id:n?n.id:"",firstName:"",lastName:"",company:"",address1:"",address2:"",city:"",email:n?n.email:"",stateOrProvince:"",stateOrProvinceCode:"",postalCode:"",country:"",phone:"",customFields:[],countryCode:i.geoCountryCode}:n})),c=vv(({countries:e})=>e.getCountries,e=>Bg(e)),l=vv(({paymentMethods:e})=>e.getPaymentMethods,e=>Bg(e)),u=vv(({paymentMethods:e})=>e.getPaymentMethod,e=>Bg(e)),h=vv(({payment:e})=>e.getPaymentId,({paymentMethods:e})=>e.getPaymentMethod,(e,t)=>Bg(()=>{const n=e();return n&&t(n.providerId,n.gatewayId)})),p=vv(({cart:e})=>e.getCart,e=>Bg(e)),m=vv(({coupons:e})=>e.getCoupons,e=>Bg(e)),y=vv(({giftCertificates:e})=>e.getGiftCertificates,e=>Bg(e)),g=vv(({customer:e})=>e.getCustomer,e=>Bg(e)),v=vv(({signInEmail:e})=>e.getEmail,e=>Bg(e)),f=vv(({b2bToken:e})=>e.getToken,e=>Bg(e)),S=vv(({payment:e})=>e.isPaymentDataRequired,e=>Bg(e)),_=vv(({payment:e})=>e.isPaymentDataSubmitted,({paymentMethods:e})=>e.getPaymentMethod,(e,t)=>Bg((n,i)=>e(t(n,i)))),w=vv(({instruments:e})=>e.getInstruments,({instruments:e})=>e.getInstrumentsByPaymentMethod,(e,t)=>Bg(function(n){return n?t(n):e()})),I=vv(({form:e})=>e.getCustomerAccountFields,e=>Bg(e)),C=vv(({form:e})=>e.getBillingAddressFields,({countries:e})=>e.getCountries,(e,t)=>Bg(n=>e(t(),n))),b=vv(({form:e})=>e.getShippingAddressFields,({shippingCountries:e})=>e.getShippingCountries,(e,t)=>Bg(n=>e(t(),n))),P=vv(({form:e})=>e.getAddressExtraFields,e=>Bg(e)),O=vv(({config:e})=>e.getFlashMessages,e=>Bg(e)),E=vv(({pickupOptions:e})=>e.getPickupOptions,e=>Bg(e)),A=vv(({config:e})=>e.getStoreConfig,e=>Bg(()=>{const t=e();if(t)return t.checkoutSettings.checkoutUserExperienceSettings})),T=vv(({extensions:e})=>e.getExtensions,e=>Bg(e)),k=vv(({paymentProviderCustomer:e})=>e.getPaymentProviderCustomer,e=>Bg(e)),D=vv(({extensions:e})=>e.getExtensionByRegion,e=>Bg(e));return Oe(M=>({getCheckout:e(M),getOrder:t(M),getConfig:n(M),getExtensions:T(M),getExtensionByRegion:D(M),getFlashMessages:O(M),getShippingAddress:i(M),getShippingOptions:r(M),getConsignments:o(M),getSelectedShippingOption:a(M),getShippingCountries:s(M),getBillingAddress:d(M),getBillingCountries:c(M),getPaymentMethods:l(M),getPaymentMethod:u(M),getSelectedPaymentMethod:h(M),getCart:p(M),getCoupons:m(M),getGiftCertificates:y(M),getCustomer:g(M),isPaymentDataRequired:S(M),isPaymentDataSubmitted:_(M),getSignInEmail:v(M),getB2BToken:f(M),getInstruments:w(M),getCustomerAccountFields:I(M),getBillingAddressFields:C(M),getShippingAddressFields:b(M),getAddressExtraFields:P(M),getPickupOptions:E(M),getUserExperienceSettings:A(M),getPaymentProviderCustomer:k(M)}))}(),t=function(){const e=fv(e=>e,e=>()=>{for(const t of Object.keys(e)){const n=e[t]();if(n)return n}}),t=vv(({shippingStrategies:e})=>e.getSelectOptionError,({consignments:e})=>e.getUpdateShippingOptionError,(e,t)=>n=>e()||t(n));return Oe(n=>{const i={getLoadCheckoutError:n.checkout.getLoadError,getUpdateCheckoutError:n.checkout.getUpdateError,getSubmitOrderError:n.paymentStrategies.getExecuteError,getFinalizeOrderError:n.paymentStrategies.getFinalizeError,getLoadOrderError:n.order.getLoadError,getLoadCartError:n.cart.getLoadError,getLoadBillingCountriesError:n.countries.getLoadError,getLoadShippingCountriesError:n.shippingCountries.getLoadError,getLoadPaymentMethodsError:n.paymentMethods.getLoadError,getLoadPaymentMethodError:n.paymentMethods.getLoadMethodError,getInitializePaymentError:n.paymentStrategies.getInitializeError,getSignInError:n.customerStrategies.getSignInError,getSignOutError:n.customerStrategies.getSignOutError,getInitializeCustomerError:n.customerStrategies.getInitializeError,getLoadShippingOptionsError:n.consignments.getLoadShippingOptionsError,getSelectShippingOptionError:t(n),getContinueAsGuestError:n.billingAddress.getContinueAsGuestError,getUpdateBillingAddressError:n.billingAddress.getUpdateError,getUpdateSubscriptionsError:n.subscriptions.getUpdateError,getUpdateShippingAddressError:n.shippingStrategies.getUpdateAddressError,getDeleteConsignmentError:n.consignments.getDeleteError,getUpdateConsignmentError:n.consignments.getUpdateError,getCreateConsignmentsError:n.consignments.getCreateError,getInitializeShippingError:n.shippingStrategies.getInitializeError,getApplyStoreCreditError:n.storeCredit.getApplyError,getApplyCouponError:n.coupons.getApplyError,getRemoveCouponError:n.coupons.getRemoveError,getApplyGiftCertificateError:n.giftCertificates.getApplyError,getRemoveGiftCertificateError:n.giftCertificates.getRemoveError,getLoadInstrumentsError:n.instruments.getLoadError,getDeleteInstrumentError:n.instruments.getDeleteError,getLoadConfigError:n.config.getLoadError,getSignInEmailError:n.signInEmail.getSendError,getLoadB2BTokenError:n.b2bToken.getLoadError,getCreateCustomerAccountError:n.customer.getCreateAccountError,getCreateCustomerAddressError:n.customer.getCreateAddressError,getPickupOptionsError:n.pickupOptions.getLoadError,getLoadExtensionsError:n.extensions.getLoadError};return Object.assign({getError:e(i)},i)})}(),n=function(){const e=fv(e=>e,e=>()=>Object.keys(e).some(t=>e[t]())),t=vv(({shippingStrategies:e})=>e.isSelectingOption,({consignments:e})=>e.isUpdatingShippingOption,(e,t)=>n=>e()||t(n)),n=vv(({customerStrategies:e})=>e.isInitializing,({customerStrategies:e})=>e.isSigningIn,({customerStrategies:e})=>e.isSigningOut,({customerStrategies:e})=>e.isExecutingPaymentMethodCheckout,({customerStrategies:e})=>e.isWidgetInteracting,(e,t,n,i,r)=>o=>e(o)||t(o)||n(o)||i(o)||r(o)),i=vv(({shippingStrategies:e})=>e.isInitializing,({shippingStrategies:e})=>e.isUpdatingAddress,({shippingStrategies:e})=>e.isSelectingOption,({shippingStrategies:e})=>e.isWidgetInteracting,(e,t,n,i)=>r=>e(r)||t(r)||n(r)||i(r)),r=vv(({paymentStrategies:e})=>e.isInitializing,({paymentStrategies:e})=>e.isExecuting,({paymentStrategies:e})=>e.isFinalizing,({paymentStrategies:e})=>e.isWidgetInteracting,(e,t,n,i)=>r=>e(r)||t(r)||n(r)||i(r)),o=vv(({paymentStrategies:e})=>e.isExecuting,({checkout:e})=>e.isExecutingSpamCheck,(e,t)=>n=>e(n)||t());return Oe(a=>{const s={isLoadingCheckout:a.checkout.isLoading,isUpdatingCheckout:a.checkout.isUpdating,isExecutingSpamCheck:a.checkout.isExecutingSpamCheck,isSubmittingOrder:o(a),isFinalizingOrder:a.paymentStrategies.isFinalizing,isLoadingOrder:a.order.isLoading,isLoadingCart:a.cart.isLoading,isLoadingBillingCountries:a.countries.isLoading,isLoadingShippingCountries:a.shippingCountries.isLoading,isLoadingPaymentMethods:a.paymentMethods.isLoading,isLoadingPaymentMethod:a.paymentMethods.isLoadingMethod,isInitializingPayment:a.paymentStrategies.isInitializing,isSigningIn:a.customerStrategies.isSigningIn,isSigningOut:a.customerStrategies.isSigningOut,isExecutingPaymentMethodCheckout:a.customerStrategies.isExecutingPaymentMethodCheckout,isInitializingCustomer:a.customerStrategies.isInitializing,isInitializedCustomer:a.customerStrategies.isInitialized,isLoadingShippingOptions:a.consignments.isLoadingShippingOptions,isSelectingShippingOption:t(a),isUpdatingBillingAddress:a.billingAddress.isUpdating,isUpdatingSubscriptions:a.subscriptions.isUpdating,isCreatingCustomerAccount:a.customer.isCreatingCustomerAccount,isCreatingCustomerAddress:a.customer.isCreatingCustomerAddress,isContinuingAsGuest:a.billingAddress.isContinuingAsGuest,isUpdatingShippingAddress:a.shippingStrategies.isUpdatingAddress,isUpdatingConsignment:a.consignments.isUpdating,isDeletingConsignment:a.consignments.isDeleting,isCreatingConsignments:a.consignments.isCreating,isInitializingShipping:a.shippingStrategies.isInitializing,isApplyingStoreCredit:a.storeCredit.isApplying,isApplyingCoupon:a.coupons.isApplying,isRemovingCoupon:a.coupons.isRemoving,isApplyingGiftCertificate:a.giftCertificates.isApplying,isRemovingGiftCertificate:a.giftCertificates.isRemoving,isLoadingInstruments:a.instruments.isLoading,isDeletingInstrument:a.instruments.isDeleting,isLoadingConfig:a.config.isLoading,isSendingSignInEmail:a.signInEmail.isSending,isLoadingB2BToken:a.b2bToken.isLoading,isCustomerStepPending:n(a),isShippingStepPending:i(a),isPaymentStepPending:r(a),isLoadingPickupOptions:a.pickupOptions.isLoading};return Object.assign({isPending:e(s)},s)})}();return i=>({data:e(i),errors:t(i),statuses:n(i)})}());return new yv(d,E,O,function(e,t){const n={[$n.ConsignmentsChanged]:Zn};return new Jn(e,t,n)}(E,O),new Qe(new nt(s)),new st(new ut(c),f),_,p,new Kt(new Jt(c),_,g),new Cg(new Pg(c),h),new zm(new Nm(c,{locale:i})),new Dt(new Lt(c)),new Qt(function(e,t){const n=new Vt,i=a(),r=new en(t),o=new nn(r,new bt(new Tt(t)),new on(new an(t))),s=new pn(Sn(i),new _n(t)),d=new Kt(new Jt(t),o,s);return n.register("default",()=>new wn(e,d)),n}(d,c),C,w),new yt,new Bt(new jt(c)),new Wg(new Zg(l,c)),v,new Wm(new $m(c)),new Xm(function(e,t,n){const i=new Wy({defaultToken:Zm.CREDIT_CARD}),r=new Gy,a=new by(t),s=new en(n),d=new ny(s),c=new Vm(new jm(n),d),l=new cy(Sn(o())),u=new Cy(a,c,r,l),h=Ee(),p=((e,t)=>new ig(new ng(e,t)))(h,l),m=new Iy(e);return i.register(Zm.CONVERGE,()=>new Zy(e,c,u,m,h)),i.register(Zm.PPSDK,()=>new dg(e,c,((e,t,n,i,r)=>{const o=new lg;return o.register(ag.CARD,()=>new hg(e,t,r,i)),o.register(ag.NONE,()=>new pg(n,i)),o.register(ag.UNSUPPORTED,()=>{}),o})(e,c,n,p,m),new vg(n,p),new iy("PPSDK"))),i}(d,l,c),I,v,g,w),new Qg(new Xg(c)),new Ag(new Tg(c,{locale:i}),d),new ev(function(e,t){const n=new Vt,i=Hg(e),r=new en(t),o=new Pg(t),s=new Cg(o,r),d=new Wm(new $m(t)),c=a(),l=new Ng(new xg(t)),u=new st(new ut(t),l),h=window,p=new Ei(i);return n.register("amazonpay",()=>new iv(e,s,new Wm(new $m(t)),gi(),new ev(n))),n.register("stripeupe",()=>new lv(e,new Ra(c),s,d)),n.register("braintreeacceleratedcheckout",()=>new ov(e,u,s,d,new Sg,new _o(new Hi(a(),h,p),h))),n.register("paypalcommerceacceleratedcheckout",()=>new dv(e,u,s,d,new Sg,Cs(),nd())),n.register("default",()=>new av(e,s)),n}(d,c)),new uv(new hv(c)),g,new Dg(new Mg(c)),f,S,b,P)}class g_ extends Qn{constructor(e){super(e||"An unexpected error has occurred during config creation process. Please try again later."),this.name="AmazonPayV2ConfigCreationError",this.type="amazon_pay_v2_config_creation_error"}}function v_(e){return e instanceof Object&&"buyNowInitializeOptions"in e}var f_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class S_{constructor(e,t,n){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t,this.amazonPayV2ConfigRequestSender=n}initialize(e){var t;return f_(this,void 0,void 0,function*(){const{methodId:n,containerId:i,amazonpay:r}=e,{buttonColor:o}=r||{};if(!n||!i)throw new fi('Unable to proceed because "methodId" or "containerId" argument is not provided.');const{getPaymentMethodOrThrow:a}=this.paymentIntegrationService.getState(),s=a(n),{initializationData:d}=s;yield this.amazonPayV2PaymentProcessor.initialize(s),r||(yield this.paymentIntegrationService.loadDefaultCheckout());const c=v_(r)?void 0:r;v_(r)&&"function"==typeof(null===(t=r.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody)&&(this._buyNowInitializeOptions=r.buyNowInitializeOptions,this.amazonPayV2PaymentProcessor.updateBuyNowFlowFlag(!0)),this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:this.paymentIntegrationService.getState(),containerId:i,methodId:n,options:c,placement:si.Cart,buttonColor:o,isButtonMicroTextDisabled:null==d?void 0:d.isButtonMicroTextDisabled}),this._buyNowInitializeOptions&&this.amazonPayV2PaymentProcessor.prepareCheckoutWithCreationRequestConfig(this._getCheckoutCreationRequestConfig.bind(this))})}deinitialize(){return this.amazonPayV2PaymentProcessor.deinitialize()}_createBuyNowCartOrThrow(){var e,t;return f_(this,void 0,void 0,function*(){const n=null===(t=null===(e=this._buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody)||void 0===t?void 0:t.call(e);if(!n)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(n)}catch(e){throw new er}})}_createCheckoutConfig(e){return f_(this,void 0,void 0,function*(){try{const t=(yield this.amazonPayV2ConfigRequestSender.createCheckoutConfig(e)).body,{payload:n,public_key:i}=t,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const t=n(),i=new __(t),r=gi();return new S_(e,r,i)},[{id:"amazonpay"}]);var I_,C_,b_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}(I_||(I_={})),function(e){e.Black="black",e.White="white",e.WhiteBorder="white-border"}(C_||(C_={}));class P_{constructor(e,t,n,i,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._braintreeSdk=i,this._applePayScriptLoader=r,this._onAuthorizeCallback=ce,this._subTotalLabel=I_.Subtotal,this._shippingLabel=I_.Shipping}initialize(e){var t,n;return b_(this,void 0,void 0,function*(){const{methodId:i,containerId:r,applepay:o}=e;if(!i||!o)throw new ti(Xn.MissingPaymentMethod);yield this._applePayScriptLoader.loadSdk();const{onPaymentAuthorize:a,buyNowInitializeOptions:s,requiresShipping:d}=o;this._requiresShipping=d,this._buyNowInitializeOptions=s,this._onAuthorizeCallback=a,s||(yield this._paymentIntegrationService.loadDefaultCheckout()),yield this._paymentIntegrationService.loadPaymentMethod(i);const c=this._paymentIntegrationService.getState();return this._paymentMethod=c.getPaymentMethodOrThrow(i),c.getCart()&&(yield this._paymentIntegrationService.verifyCheckoutSpamProtection()),(null===(t=this._paymentMethod.initializationData)||void 0===t?void 0:t.gateway)===Vi.BRAINTREE&&this._paymentMethod.clientToken&&this._braintreeSdk.initialize(this._paymentMethod.clientToken),this._applePayButton=this._createButton(r,null===(n=this._paymentMethod.initializationData)||void 0===n?void 0:n.styleOption),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),Promise.resolve()})}deinitialize(){return Promise.resolve()}_createButton(e,t){const n=document.getElementById(e);if(!n)throw new fi("Unable to create wallet button without valid container ID.");const i=this._createApplePayButtonElement(t);return n.appendChild(i),i}_createApplePayButtonElement(e){const t=document.createElement("apple-pay-button");return t.setAttribute("buttonstyle",(e=>{switch(e){case C_.White:return"white";case C_.WhiteBorder:return"white-outline";case C_.Black:default:return"black"}})(e)),t.setAttribute("type","plain"),t.setAttribute("style","--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;"),t}_handleWalletButtonClick(e){var t;return b_(this,void 0,void 0,function*(){if(e.preventDefault(),!this._paymentMethod||!this._paymentMethod.initializationData)throw new ti(Xn.MissingPaymentMethod);if(this._buyNowInitializeOptions&&"function"==typeof this._buyNowInitializeOptions.getBuyNowCartRequestBody){const{countryCode:e,currencyCode:n,merchantCapabilities:i,supportedNetworks:r,storeName:o}=this._paymentMethod.initializationData,a=this._getRequestWithEmptyTotal(e,n,r,i);this._requiresShipping&&(null===(t=a.requiredShippingContactFields)||void 0===t||t.push("postalAddress"));const s=this._sessionFactory.create(a);this._handleApplePayEvents(s,this._paymentMethod,o),s.begin()}else{const e=this._paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getStoreConfigOrThrow(),i=e.getCheckoutOrThrow(),r=this._getBaseRequest(t,i,n,this._paymentMethod),o=this._sessionFactory.create(r);this._handleApplePayEvents(o,this._paymentMethod,n.storeProfile.storeName),o.begin()}})}_getRequestWithEmptyTotal(e,t,n,i){return{countryCode:e,currencyCode:t,supportedNetworks:n,merchantCapabilities:i,total:{label:"",amount:"0",type:"pending"},requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"]}}_getBaseRequest(e,t,n,i){var r;const{storeProfile:{storeCountryCode:o,storeName:a}}=n,{currency:{code:s,decimalPlaces:d}}=e,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=i,u=e.lineItems.physicalItems.length>0,h={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:o,currencyCode:s,merchantCapabilities:c,supportedNetworks:l,lineItems:[],total:u?{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"pending"}:{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"final"}};if(u)null===(r=h.requiredShippingContactFields)||void 0===r||r.push("postalAddress");else{const e=[{label:this._subTotalLabel,amount:`${t.subtotal.toFixed(d)}`}];t.taxes.forEach(t=>e.push({label:t.name,amount:`${t.amount.toFixed(d)}`})),h.lineItems=e}return h}_handleApplePayEvents(e,t,n){e.onvalidatemerchant=n=>b_(this,void 0,void 0,function*(){try{const{body:i}=yield this._onValidateMerchant(t,n);e.completeMerchantValidation(i)}catch(e){throw new Error("Merchant validation failed")}}),this._buyNowInitializeOptions&&!this._requiresShipping&&(e.onpaymentmethodselected=()=>b_(this,void 0,void 0,function*(){yield this._createBuyNowCart(),this._handlePaymentMethodSelected(e)})),e.onshippingcontactselected=t=>b_(this,void 0,void 0,function*(){this._buyNowInitializeOptions&&this._requiresShipping&&(yield this._createBuyNowCart()),yield this._handleShippingContactSelected(e,n,t)}),e.onshippingmethodselected=t=>b_(this,void 0,void 0,function*(){yield this._handleShippingMethodSelected(e,n,t)}),e.oncancel=()=>b_(this,void 0,void 0,function*(){try{const e=`/remote-checkout/${t.id}/signout`;return yield this._requestSender.get(e),yield this._paymentIntegrationService.loadCheckout()}catch(e){throw new Wi}}),e.onpaymentauthorized=n=>b_(this,void 0,void 0,function*(){return this._onPaymentAuthorized(n,e,t)})}_createBuyNowCart(){var e,t;return b_(this,void 0,void 0,function*(){try{const n=null===(t=null===(e=this._buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody)||void 0===t?void 0:t.call(e);if(!n)throw new ti(Xn.MissingCart);const i=yield this._paymentIntegrationService.createBuyNowCart(n);yield this._paymentIntegrationService.loadCheckout(i.id);const r=this._paymentIntegrationService.getState(),{shouldExecuteSpamCheck:o}=r.getCheckoutOrThrow();o&&(yield this._paymentIntegrationService.verifyCheckoutSpamProtection())}catch(e){throw new er}})}_handlePaymentMethodSelected(e){const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getStoreConfigOrThrow(),r=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new ti(Xn.MissingPaymentMethod);const o=this._getBaseRequest(n,r,i,this._paymentMethod);delete o.total.type,e.completePaymentMethodSelection({newTotal:o.total,newLineItems:o.lineItems})}_handleShippingContactSelected(e,t,n){var i;return b_(this,void 0,void 0,function*(){const r=this._transformContactToAddress(n.shippingContact);try{yield this._paymentIntegrationService.updateShippingAddress(r)}catch(t){throw e.abort(),new Error("Shipping address update failed")}let o=this._paymentIntegrationService.getState();const{currency:{decimalPlaces:a}}=o.getCartOrThrow();let s=o.getCheckoutOrThrow();const d=null===(i=s.consignments[0].selectedShippingOption)||void 0===i?void 0:i.id,c=s.consignments[0].availableShippingOptions,l=null==c?void 0:c.find(({id:e})=>e===d),u=null==c?void 0:c.filter(e=>e.id!==d),h=l?[{label:l.description,amount:`${l.cost.toFixed(a)}`,detail:l.additionalDescription,identifier:l.id}]:[];if(u&&[...u.filter(e=>e.isRecommended),...u.filter(e=>!e.isRecommended)].forEach(e=>h.push({label:e.description,amount:`${e.cost.toFixed(a)}`,detail:e.additionalDescription,identifier:e.id})),!(c instanceof Array))throw new Error("Shipping options not available.");if(0===c.length)return void e.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:t,amount:`${s.grandTotal.toFixed(a)}`},[]);const p=c.find(e=>e.isRecommended),m=p?p.id:c[0].id,y=l?l.id:m;try{yield this._updateShippingOption(y)}catch(e){throw new Error("Shipping options update failed")}o=this._paymentIntegrationService.getState(),s=o.getCheckoutOrThrow(),e.completeShippingContactSelection({newShippingMethods:h,newTotal:{type:"final",label:t,amount:`${s.grandTotal.toFixed(a)}`},newLineItems:this._getUpdatedLineItems(s,a)})})}_handleShippingMethodSelected(e,t,n){return b_(this,void 0,void 0,function*(){const{shippingMethod:{identifier:i}}=n;try{yield this._updateShippingOption(i)}catch(t){throw e.abort(),new Error("Shipping option selection update failed.")}const r=this._paymentIntegrationService.getState(),{currency:{decimalPlaces:o}}=r.getCartOrThrow(),a=r.getCheckoutOrThrow();e.completeShippingMethodSelection({newTotal:{type:"final",label:t,amount:`${a.grandTotal.toFixed(o)}`},newLineItems:this._getUpdatedLineItems(a,o)})})}_getUpdatedLineItems(e,t){const n=[{label:this._subTotalLabel,amount:`${e.subtotal.toFixed(t)}`}];return e.taxes.forEach(e=>n.push({label:e.name,amount:`${e.amount.toFixed(t)}`})),n.push({label:this._shippingLabel,amount:`${e.shippingCostTotal.toFixed(t)}`}),n}_updateShippingOption(e){return b_(this,void 0,void 0,function*(){return this._paymentIntegrationService.selectShippingOption(e)})}_onValidateMerchant(e,t){return b_(this,void 0,void 0,function*(){const n=[`validationUrl=${t.validationURL}`,`merchantIdentifier=${e.initializationData.merchantId}`,`displayName=${e.initializationData.storeName}`,`domainName=${window.location.hostname}`].join("&");return this._requestSender.post(`${e.initializationData.paymentsUrl}/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})})}_onPaymentAuthorized(e,t,n){var i;return b_(this,void 0,void 0,function*(){const{token:r,billingContact:o,shippingContact:a}=e.payment,s=this._paymentIntegrationService.getState().getCartOrThrow().lineItems.physicalItems.length>0;let d;(null===(i=n.initializationData)||void 0===i?void 0:i.gateway)===Vi.BRAINTREE&&(d=yield this._getBraintreeDeviceData());const c={methodId:n.id,paymentData:{deviceSessionId:d,formattedPayload:{apple_pay_token:{payment_data:r.paymentData,payment_method:r.paymentMethod,transaction_id:r.transactionIdentifier}}}},l=this._transformContactToAddress(o),u=this._transformContactToAddress(a),h=null==a?void 0:a.emailAddress,p=(null==a?void 0:a.phoneNumber)||"";try{return yield this._paymentIntegrationService.updateBillingAddress(Object.assign(Object.assign({},l),{email:h,phone:p})),s&&(yield this._paymentIntegrationService.updateShippingAddress(u)),yield this._paymentIntegrationService.submitOrder({useStoreCredit:!1}),yield this._paymentIntegrationService.submitPayment(c),t.completePayment(ApplePaySession.STATUS_SUCCESS),this._onAuthorizeCallback()}catch(e){throw t.completePayment(ApplePaySession.STATUS_FAILURE),new Error("Payment cannot complete")}})}_transformContactToAddress(e){return{firstName:(null==e?void 0:e.givenName)||"",lastName:(null==e?void 0:e.familyName)||"",city:(null==e?void 0:e.locality)||"",company:"",address1:(null==e?void 0:e.addressLines)&&e.addressLines[0]||"",address2:(null==e?void 0:e.addressLines)&&e.addressLines[1]||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||"",phone:(null==e?void 0:e.phoneNumber)||"",stateOrProvince:(null==e?void 0:e.administrativeArea)||"",stateOrProvinceCode:(null==e?void 0:e.administrativeArea)||"",customFields:[]}}_getBraintreeDeviceData(){return b_(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}const O_=vi(e=>{const{getHost:t}=e.getState(),i=new Ei(e);return new P_(n({host:t()}),e,new Zi,new Ui(new Hi(a(),window,i)),new Qi(new r))},[{id:"applepay"}]);var E_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class A_{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){var t;return E_(this,void 0,void 0,function*(){const{bigcommerce_payments:n,containerId:i,methodId:r}=e,o=Boolean(null==n?void 0:n.buyNowInitializeOptions);if(!r)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');if(o&&!n.currencyCode)throw new fi('Unable to initialize payment because "options.bigcommerce_payments.currencyCode" argument is not provided.');if(o&&"function"!=typeof(null===(t=n.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.bigcommerce_payments.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');o||(yield this.paymentIntegrationService.loadDefaultCheckout());const a=o?n.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(r,a,!1),this.renderButton(i,r,n,o)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n,i){var r,o;const{buyNowInitializeOptions:a,style:s,onComplete:d,onEligibilityFailure:c}=n,l=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),u=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:h,isAppSwitchEnabled:p}=u.initializationData||{},m=Object.assign(Object.assign({},!i&&this.isPaypalCommerceAppSwitchEnabled(t)&&{appSwitchWhenAvailable:!0}),{createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)}),y={onClick:()=>this.handleClick(a),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},g=Object.assign(Object.assign({},!p&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(e,n)=>this.onHostedCheckoutApprove(e,n,t,d)}),v=Object.assign(Object.assign(Object.assign({fundingSource:l.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(s)},m),a&&y),h&&g),f=l.Buttons(v);f.isEligible()?(null===(r=f.hasReturned)||void 0===r?void 0:r.call(f))&&this.isPaypalCommerceAppSwitchEnabled(t)?null===(o=f.resume)||void 0===o||o.call(f):f.render(`#${e}`):c&&"function"==typeof c?c():this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return E_(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,n,i){return E_(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return E_(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return E_(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}isPaypalCommerceAppSwitchEnabled(e){var t,n;return null!==(n=null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)&&void 0!==n&&n}}const T_=vi(e=>new A_(e,_r(e)),[{id:"bigcommerce_payments"}]);var k_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class D_{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return k_(this,void 0,void 0,function*(){const{bigcommerce_payments_paylater:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');if(a&&!o)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=this.paymentIntegrationService.getState(),d=a?o:s.getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i,d,!1),this.renderButton(n,i,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){const{buyNowInitializeOptions:i,style:r,onComplete:o,onEligibilityFailure:a}=n,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:c}=d.initializationData||{},l={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},u={onClick:()=>this.handleClick(i),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},h={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(e,n)=>this.onHostedCheckoutApprove(e,n,t,o)},p=[s.FUNDING.PAYLATER,s.FUNDING.CREDIT];let m=!1;p.forEach(t=>{if(!m){const n=Object.assign(Object.assign(Object.assign({fundingSource:t,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(r)},l),i&&u),c&&h),o=s.Buttons(n);o.isEligible()?(o.render(`#${e}`),m=!0):a&&"function"==typeof a&&a()}}),m||this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return k_(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,n,i){return k_(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return k_(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return k_(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}}const M_=vi(e=>new D_(e,_r(e)),[{id:"bigcommerce_payments_paylater"}]);var z_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class N_{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return z_(this,void 0,void 0,function*(){const{bigcommerce_payments_venmo:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');if(a&&!o)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=a?o:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i,s,!1),this.renderButton(n,i,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){const{buyNowInitializeOptions:i,style:r,onEligibilityFailure:o}=n,a=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),s=a.FUNDING.VENMO,d={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},c={onClick:()=>this.handleClick(i),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},l=Object.assign(Object.assign({fundingSource:s,style:this.getValidVenmoButtonStyles(r)},d),i&&c),u=a.Buttons(l);u.isEligible()?u.render(`#${e}`):o&&"function"==typeof o?o():this.bigCommercePaymentsIntegrationService.removeElement(e)}getValidVenmoButtonStyles(e){const t=this.bigCommercePaymentsIntegrationService.getValidButtonStyle(e);return t.color===ar.gold?Object.assign(Object.assign({},t),{color:void 0}):t}handleClick(e){return z_(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const x_=vi(e=>new N_(e,_r(e)),[{id:"bigcommerce_payments_venmo"}]);class R_{constructor(e,t,n=window){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=n}initialize(e){return t=this,n=void 0,r=function*(){const{bolt:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,style:o}=t||{};if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bolt" argument is not provided.');if(!Boolean(r))throw new Si("Only buy now flow is implemented for Bolt button");if(!(null==r?void 0:r.storefrontApiToken)||"string"!=typeof r.storefrontApiToken)throw new fi('Unable to initialize payment because "options.storefrontApiToken" argument is not provided.');const a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i),{initializationData:s,config:d}=a,{publishableKey:c,developerConfig:l}=s||{};yield this.boltScriptLoader.loadBoltClient(c,d.testMode,l,"BigCommerce",r.storefrontApiToken),this.renderButton(n,a,o)},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}deinitialize(){return Promise.resolve()}renderButton(e,t,n){var i;"function"==typeof(null===(i=this.boltHostWindow.BoltConnect)||void 0===i?void 0:i.setupProductPageCheckout)&&(this.addButtonContainer(e,t,n),this.boltHostWindow.BoltConnect.setupProductPageCheckout())}addButtonContainer(e,t,n){const i=document.getElementById(e);if(!i)return;const r=document.createElement("div"),o=document.createElement("object");r.setAttribute("id","product-page-checkout-wrapper"),r.setAttribute("class","bolt-button-wrapper"),r.setAttribute("style","display:none"),r.setAttribute("data-tid","product-page-checkout-wrapper"),o.setAttribute("data",this.getBoltObjectData(t,n)),o.setAttribute("class","bolt-product-checkout-button"),r.append(o),i.innerHTML="",i.append(r)}getBoltObjectData(e,t){const{initializationData:n,config:i}=e,{publishableKey:r,developerConfig:o}=n||{},a=this.boltScriptLoader.getDomainURL(!!i.testMode,o),s=this.getButtonHeight(null==t?void 0:t.size),d=this.getButtonBorderRadius(null==t?void 0:t.shape,s);return xe({url:`https://${a}/v1/checkout_button`,query:{publishable_key:r,variant:"ppc",height:s,border_radius:d}})}getButtonHeight(e){if(e)switch(e){case to.Small:return 25;case to.Large:return 45;case to.Medium:default:return 40}}getButtonBorderRadius(e,t){if(e)switch(e){case no.Pill:return t?Math.round(t/2):void 0;case no.Rect:default:return 4}}}const F_=vi(e=>new R_(e,new ao(a())),[{id:"bolt"}]);function L_(e){const{color:t,fundingicons:n,height:i=40,layout:r,shape:o,size:a,tagline:s}=e||{},d={color:t,fundingicons:n,height:B_(i),layout:r,shape:o||"rect",size:a,tagline:s};return ue(d,J)}function B_(e){const t=Number(e);return!t||Number.isNaN(t)?40:t>55?55:t<25?25:t}var j_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class U_{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return j_(this,void 0,void 0,function*(){const{braintreepaypal:t,containerId:n,methodId:i}=e;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');let r,o=this.paymentIntegrationService.getState();if(t.buyNowInitializeOptions){if(!t.currencyCode)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');r=t.currencyCode}else yield this.paymentIntegrationService.loadDefaultCheckout(),o=this.paymentIntegrationService.getState(),r=o.getCartOrThrow().currency.code;const a=o.getPaymentMethodOrThrow(i),{clientToken:s,config:d,initializationData:c}=a;if(!s||!c)throw new ti(Xn.MissingPaymentMethod);const l={currency:r,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(l,e=>{this.renderPayPalButton(e,t,n,i,!!d.testMode)},e=>this.handleError(e,n,t.onError))})}deinitialize(){return j_(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}renderPayPalButton(e,t,n,i,r){const{style:o,shouldProcessPayment:a,onAuthorizeError:s,onEligibilityFailure:d}=t,{paypal:c}=this.braintreeHostWindow;if(c){const l=c.Buttons({env:r?"sandbox":"production",fundingSource:c.FUNDING.PAYPAL,style:L_(o),createOrder:()=>this.setupPayment(e,t,i),onApprove:t=>this.tokenizePayment(t,e,i,a,s)});l.isEligible()?l.render(`#${n}`):d&&"function"==typeof d&&d()}else this.braintreeIntegrationService.removeElement(n)}setupPayment(e,t,n){var i;return j_(this,void 0,void 0,function*(){const{onPaymentError:r,shippingAddress:o,buyNowInitializeOptions:a}=t;try{const r="function"==typeof(null==a?void 0:a.getBuyNowCartRequestBody)?yield this.createBuyNowCart(a.getBuyNowCartRequestBody()):void 0;this.buyNowCartId=null==r?void 0:r.id;const s=this.paymentIntegrationService.getState(),d=s.getCustomer(),c=s.getPaymentMethodOrThrow(n),l=r?r.cartAmount:s.getCartOrThrow().cartAmount,u=r?t.currencyCode:s.getCartOrThrow().currency.code,h=o||(null==d?void 0:d.addresses[0]),p=h?El(h):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:p,amount:l,currency:u,offerCredit:!1,intent:null===(i=c.initializationData)||void 0===i?void 0:i.intent})}catch(e){throw r&&(Ri(e)||e instanceof Qn)&&r(e),e}})}tokenizePayment(e,t,n,i,r){return j_(this,void 0,void 0,function*(){try{const{deviceData:r}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),o=yield t.tokenizePayment(e),{details:a,nonce:s}=o,d=this.braintreeIntegrationService.mapToLegacyBillingAddress(a),c=this.braintreeIntegrationService.mapToLegacyShippingAddress(a);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",provider:n,action:i?"process_payment":"set_external_checkout",nonce:s,device_data:r,billing_address:JSON.stringify(d),shipping_address:JSON.stringify(c)},this.buyNowCartId&&{cart_id:this.buyNowCartId})),o}catch(e){throw r&&(Ri(e)||e instanceof Qn)&&r(e),e}})}createBuyNowCart(e){return j_(this,void 0,void 0,function*(){if(!e)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(e)}catch(e){throw new er}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const q_=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t);return new U_(e,Ee(),i,t)},[{id:"braintreepaypal"}]);var V_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class G_{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return V_(this,void 0,void 0,function*(){const{braintreepaypalcredit:t,containerId:n,methodId:i}=e;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');let r,o=this.paymentIntegrationService.getState();if(t.buyNowInitializeOptions){if(!t.currencyCode)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');r=t.currencyCode}else yield this.paymentIntegrationService.loadDefaultCheckout(),o=this.paymentIntegrationService.getState(),r=o.getCartOrThrow().currency.code;const a=o.getPaymentMethodOrThrow(i),{clientToken:s,config:d,initializationData:c}=a;if(!s||!c)throw new ti(Xn.MissingPaymentMethod);const l={currency:r,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(l,e=>{this.renderPayPalButton(e,t,n,i,!!d.testMode)},e=>this.handleError(e,n,t.onError))})}deinitialize(){return V_(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}renderPayPalButton(e,t,n,i,r){const{style:o,shouldProcessPayment:a,onAuthorizeError:s,onEligibilityFailure:d}=t,{paypal:c}=this.braintreeHostWindow;let l=!1;c&&[c.FUNDING.PAYLATER,c.FUNDING.CREDIT].forEach(u=>{const h=u===c.FUNDING.CREDIT?Object.assign({label:go.CREDIT},L_(o)):L_(o);if(!l){const o=c.Buttons({env:r?"sandbox":"production",fundingSource:u,style:h,createOrder:()=>this.setupPayment(e,t,i),onApprove:t=>this.tokenizePayment(t,e,i,a,s)});o.isEligible()?(o.render(`#${n}`),l=!0):c.FUNDING.CREDIT&&d&&"function"==typeof d&&d()}}),c&&l||this.braintreeIntegrationService.removeElement(n)}setupPayment(e,t,n){var i;return V_(this,void 0,void 0,function*(){const{onPaymentError:r,shippingAddress:o,buyNowInitializeOptions:a}=t;try{const r="function"==typeof(null==a?void 0:a.getBuyNowCartRequestBody)?yield this.createBuyNowCart(a.getBuyNowCartRequestBody()):void 0;this.buyNowCartId=null==r?void 0:r.id;const s=this.paymentIntegrationService.getState(),d=s.getCustomer(),c=s.getPaymentMethodOrThrow(n),l=r?r.cartAmount:s.getCartOrThrow().cartAmount,u=r?t.currencyCode:s.getCartOrThrow().currency.code,h=o||(null==d?void 0:d.addresses[0]),p=h?El(h):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:p,amount:l,currency:u,offerCredit:!0,intent:null===(i=c.initializationData)||void 0===i?void 0:i.intent})}catch(e){throw r&&(Ri(e)||e instanceof Qn)&&r(e),e}})}tokenizePayment(e,t,n,i,r){return V_(this,void 0,void 0,function*(){try{const{deviceData:r}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),o=yield t.tokenizePayment(e),{details:a,nonce:s}=o,d=this.braintreeIntegrationService.mapToLegacyBillingAddress(a),c=this.braintreeIntegrationService.mapToLegacyShippingAddress(a);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",provider:n,action:i?"process_payment":"set_external_checkout",nonce:s,device_data:r,billing_address:JSON.stringify(d),shipping_address:JSON.stringify(c)},this.buyNowCartId&&{cart_id:this.buyNowCartId})),o}catch(e){throw r&&(Ri(e)||e instanceof Qn)&&r(e),e}})}createBuyNowCart(e){return V_(this,void 0,void 0,function*(){if(!e)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(e)}catch(e){throw new er}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const H_=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t);return new G_(e,Ee(),i,t)},[{id:"braintreepaypalcredit"}]);var W_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class $_{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n}initialize(e){return W_(this,void 0,void 0,function*(){const{containerId:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState(),{clientToken:r,initializationData:o,config:a}=i.getPaymentMethodOrThrow(n);if(!r||!o)throw new ti(Xn.MissingPaymentMethod);this.braintreeSdk.initialize(r);const s=yield this.braintreeSdk.getBraintreeVisaCheckout(),{currency:{code:d},cartAmount:c}=i.getCartOrThrow(),l=yield this.braintreeSdk.getVisaCheckoutSdk(a.testMode),u=s.createInitOptions({paymentRequest:{currencyCode:d,subtotal:String(c)},settings:{shipping:{collectShipping:!0}}});this.createSignInButton(t),yield l.init(u),l.on("payment.success",e=>W_(this,void 0,void 0,function*(){yield this.paymentSuccess(s,e)}))})}deinitialize(){return Promise.resolve()}paymentSuccess(e,t){return W_(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const n=this.paymentIntegrationService.getState(),i=n.getShippingAddress(),r=n.getBillingAddress(),{shippingAddress:o=this.toVisaCheckoutAddress(i),billingAddress:a=this.toVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}postForm(e,t){const{userData:n,billingAddress:i,shippingAddress:r,details:o}=e,{userEmail:a}=n,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,i)),shipping_address:JSON.stringify(this.getAddress(a,r))})}toVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}createSignInButton(e){const t=document.querySelector(`#${e}`);if(!t)throw new Error("Need a container to place the button");return this.insertVisaCheckoutButton(t)}insertVisaCheckoutButton(e){const t=document.createElement("div");return t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="flex-end",t.innerHTML='\n \n Tell Me More',e.appendChild(t),t}}const Y_=vi(e=>{const t=window,n=new Ei(e),i=new Ui(new Hi(a(),t,n));return new $_(e,Ee(),i)},[{id:"braintreevisacheckout"}]);function K_(e){const{billingAddress:t,email:n,firstName:i,lastName:r,phone:o,shippingAddress:a}=e,s=t||a;return{email:n,first_name:i,last_name:r,phone_number:o,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 J_(e){const{email:t,phone:n,shippingAddress:i}=e,r=(null==i?void 0:i.recipientName)||"",[o,a]=r.split(" ");return{email:t,first_name:o||"",last_name:a||"",phone_number:n,address_line_1:null==i?void 0:i.line1,address_line_2:null==i?void 0:i.line2,city:null==i?void 0:i.city,state:null==i?void 0:i.state,country_code:null==i?void 0:i.countryCode,postal_code:null==i?void 0:i.postalCode}}var Z_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const Q_=e=>{const{color:t,height:n}=e;return{backgroundColor:(i=t||"",i===yo.WHITE?"#FFFFFF":"#3D95CE"),backgroundPosition:"50% 50%",backgroundSize:"80px auto",backgroundImage:`url("/app/assets/img/payment-providers/venmo-logo-${t===yo.WHITE?yo.BLUE:yo.WHITE}.svg")`,backgroundRepeat:"no-repeat",borderRadius:"4px",cursor:"pointer",transition:"0.2s ease",minHeight:`${n||40}px`,minWidth:"150px",height:"100%",width:"100%",border:t===yo.WHITE?"1px solid black":"none"};var i};class X_{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n,this.onError=ce}initialize(e){return Z_(this,void 0,void 0,function*(){const{braintreevenmo:t,containerId:n,methodId:i}=e;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i),{clientToken:o,initializationData:a}=r,{paymentButtonStyles:s}=a,{cartButtonStyles:d}=s||{},c=(null==t?void 0:t.style)||d;if(!o||!a)throw new ti(Xn.MissingPaymentMethod);if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');yield this.paymentIntegrationService.loadDefaultCheckout(),this.onError=(null==t?void 0:t.onError)||this.handleError,this.braintreeSdk.initialize(o);try{const e=yield this.braintreeSdk.getVenmoCheckoutOrThrow();this.renderVenmoButton(e,n,null==t?void 0:t.buyNowInitializeOptions,c)}catch(e){(Ol(e)||function(e){return e instanceof Ai}(e))&&this.handleInitializationVenmoError(e,n)}})}deinitialize(){return Z_(this,void 0,void 0,function*(){return yield this.braintreeSdk.deinitialize(),Promise.resolve()})}handleError(e){throw new Error(e.message)}createBuyNowCart(e){return Z_(this,void 0,void 0,function*(){if("function"==typeof(null==e?void 0:e.getBuyNowCartRequestBody)){const t=null==e?void 0:e.getBuyNowCartRequestBody();if(!t)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}}})}handleInitializationVenmoError(e,t){return this.removeVenmoContainer(t),this.onError(e)}removeVenmoContainer(e){const t=document.getElementById(e);t&&t.remove()}renderVenmoButton(e,t,n,i){const r=document.getElementById(t),{color:o}=i||{};if(!r)throw new fi("Unable to create wallet button without valid container ID.");r.setAttribute("aria-label","Venmo"),Object.assign(r.style,Q_(i||{})),r.addEventListener("click",()=>Z_(this,void 0,void 0,function*(){r.setAttribute("disabled","true");const t=yield this.createBuyNowCart(n);e.tokenize&&e.tokenize((e,n)=>Z_(this,void 0,void 0,function*(){r.removeAttribute("disabled"),e&&this.onError(e),yield this.handlePostForm(n,null==t?void 0:t.id)}))})),o===yo.BLUE&&(r.addEventListener("mouseenter",()=>{r.style.backgroundColor="#0a7fc2"}),r.addEventListener("mouseleave",()=>{r.style.backgroundColor=Q_(i||{}).backgroundColor}))}handlePostForm(e,t){return Z_(this,void 0,void 0,function*(){const{deviceData:n}=yield this.braintreeSdk.getDataCollectorOrThrow(),{nonce:i,details:r}=e;this.formPoster.postForm("/checkout.php",Object.assign({nonce:i,provider:"braintreevenmo",payment_type:"paypal",device_data:n,action:"set_external_checkout",billing_address:JSON.stringify(K_(r)),shipping_address:JSON.stringify(J_(r))},t&&{cart_id:t}))})}}const ew=vi(e=>{const t=window,n=a(),i=new Ei(e),r=new Hi(n,t,i),o=new Ui(r);return new X_(e,Ee(),o)},[{id:"braintreevenmo"}]);var tw=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class nw{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t}initialize(e){var t,n,i;return tw(this,void 0,void 0,function*(){if(!e.methodId||!na(e.methodId))throw new fi('Unable to proceed because "methodId" is not a valid key.');if(this._methodId=e.methodId,!e.containerId)throw new fi('Unable to proceed because "containerId" is not a valid key.');const r=e[this._getMethodOrThrow()];if(!r)throw new fi("Unable to proceed without valid options.");const{buyNowInitializeOptions:o,currencyCode:a,buttonColor:s,buttonType:d,onError:c}=r;let l,u=this._paymentIntegrationService.getState();try{l=u.getPaymentMethodOrThrow(this._getMethodOrThrow())}catch(e){u=yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodOrThrow()),l=u.getPaymentMethodOrThrow(this._getMethodOrThrow())}if(this._countryCode=null===(t=l.initializationData)||void 0===t?void 0:t.storeCountry,this._googlePayPaymentProcessor.setIsWebViewExperimentOn(!!(null===(n=l.initializationData)||void 0===n?void 0:n.isWebViewExperimentOn)),o){if(!a)throw new fi('Unable to initialize payment because "options.currencyCode" argument is not provided.');this._currencyCode=a,this._buyNowInitializeOptions=o,yield this._googlePayPaymentProcessor.initialize(()=>l,this._getGooglePayClientOptions(),!!o,a)}else yield this._paymentIntegrationService.loadDefaultCheckout(),yield this._googlePayPaymentProcessor.initialize(()=>l,this._getGooglePayClientOptions());this._paymentButton=null!==(i=this._paymentButton)&&void 0!==i?i:this._googlePayPaymentProcessor.addPaymentButton(e.containerId,{buttonColor:null!=s?s:"default",buttonType:null!=d?d:"plain",onClick:this._handleClick(c)})})}deinitialize(){var e;return null===(e=this._paymentButton)||void 0===e||e.remove(),this._paymentButton=void 0,this._methodId=void 0,Promise.resolve()}_handleClick(e){return t=>tw(this,void 0,void 0,function*(){t.preventDefault();try{this._buyNowInitializeOptions?yield this._createBuyNowCartOrThrow(this._buyNowInitializeOptions):yield this._paymentIntegrationService.loadDefaultCheckout(),yield this._googlePayPaymentProcessor.initializeWidget(),yield this._interactWithPaymentSheet()}catch(t){let n=t;if(ta(t)){if("CANCELED"===t.statusCode)throw new Wi;n=new Qr(JSON.stringify(t))}throw null==e||e(new Qr("An error occurred while requesting your Google Pay payment details.")),n}})}_interactWithPaymentSheet(){var e;return tw(this,void 0,void 0,function*(){const t=yield this._googlePayPaymentProcessor.showPaymentSheet(),n=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(t),i=this._googlePayPaymentProcessor.mapToShippingAddressRequestBody(t),r="/embedded-checkout"===window.location.pathname?this._paymentIntegrationService.getState().getStoreConfigOrThrow().links.siteLink:void 0;n&&(yield this._paymentIntegrationService.updateBillingAddress(n)),i&&!(null===(e=this._buyNowCart)||void 0===e?void 0:e.lineItems.digitalItems.length)&&(yield this._paymentIntegrationService.updateShippingAddress(i)),yield this._googlePayPaymentProcessor.setExternalCheckoutForm(this._getMethodOrThrow(),t,r)})}_getGooglePayClientOptions(){return this._googlePayPaymentProcessor.isWebViewWithRestrictions()?{}:{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:e,shippingAddress:t,shippingOptionData:n,offerData:i})=>tw(this,void 0,void 0,function*(){const{availableTriggers:r,addressChangeTriggers:o,shippingOptionsChangeTriggers:a,offerChangeTriggers:s}=this._googlePayPaymentProcessor.getCallbackTriggers();if(!r.includes(e))return;const d=o.includes(e)?yield this._googlePayPaymentProcessor.handleShippingAddressChange(t):void 0;a.includes(e)&&(yield this._googlePayPaymentProcessor.handleShippingOptionChange(n.id));const{newOfferInfo:c,error:l}=s.includes(e)?yield this._googlePayPaymentProcessor.handleCoupons(i):{},u=l;return this._buyNowInitializeOptions?this._getBuyNowTransactionInfo(d,c,u):this._getTransactionInfo(d,c,u)})}}}_createBuyNowCartOrThrow(e){return tw(this,void 0,void 0,function*(){if("function"==typeof(null==e?void 0:e.getBuyNowCartRequestBody)){const t=e.getBuyNowCartRequestBody();try{this._buyNowCart=yield this._paymentIntegrationService.createBuyNowCart(t),yield this._paymentIntegrationService.loadCheckout(this._buyNowCart.id)}catch(e){if("string"==typeof e)throw new er(e);throw e}}})}_getBuyNowTransactionInfo(e,t,n){if(!this._buyNowCart)return;const{cartAmount:i}=this._buyNowCart,r=this._googlePayPaymentProcessor.getTotalPrice();return Object.assign(Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},this._countryCode&&{countryCode:this._countryCode}),{currencyCode:this._getCurrencyCodeOrThrow(),totalPrice:r||String(i),totalPriceStatus:Wo.FINAL})},e&&{newShippingOptionParameters:e}),t&&{newOfferInfo:t}),n&&{error:n})}_getTransactionInfo(e,t,n){return tw(this,void 0,void 0,function*(){yield this._paymentIntegrationService.loadCheckout();const i=this._googlePayPaymentProcessor.getTotalPrice(),{code:r}=this._paymentIntegrationService.getState().getCartOrThrow().currency;return Object.assign(Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},this._countryCode&&{countryCode:this._countryCode}),{currencyCode:r,totalPriceStatus:Wo.FINAL,totalPrice:i})},e&&{newShippingOptionParameters:e}),t&&{newOfferInfo:t}),n&&{error:n})})}_getMethodOrThrow(){return ii(this._methodId,()=>new ri(ei.PaymentNotInitialized))}_getCurrencyCodeOrThrow(){return ii(this._currencyCode,()=>new fi('Unable to initialize payment because "options.currencyCode" argument is not provided.'))}}const iw=vi(e=>{const t=n(),i=window,r=new Ei(e),o=new Ui(new Hi(a(),i,r));return new nw(e,new aa(da(),new $a(e,o),t,Ee()))},[{id:"googlepaybraintree"}]),rw=vi(e=>new nw(e,new aa(da(),new ns(e,new Xa(a())),n(),Ee())),[{id:"googlepaypaypalcommerce"}]),ow=vi(e=>new nw(e,new aa(da(),new os(e,new xr(a())),n(),Ee())),[{id:"googlepay_bigcommerce_payments"}]),aw=vi(e=>{const t=n();return new nw(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv2"}]),sw=vi(e=>{const t=n();return new nw(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv3"}]),dw=vi(e=>new nw(e,new aa(da(),new ua(e),n(),Ee())),[{id:"googlepayauthorizenet"}]),cw=vi(e=>{const t=n();return new nw(e,new aa(da(),new ga(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]),lw=vi(e=>new nw(e,new aa(da(),new fa(e),n(),Ee())),[{id:"googlepaycybersourcev2"},{id:"googlepaybnz"}]),uw=vi(e=>new nw(e,new aa(da(),new wa(e),n(),Ee())),[{id:"googlepayorbital"}]),hw=vi(e=>new nw(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeupe"},{id:"googlepaystripeocs"}]),pw=vi(e=>new nw(e,new aa(da(),new Ga(e),n(),Ee())),[{id:"googlepayworldpayaccess"}]),mw=vi(e=>new nw(e,new aa(da(),new cs(e,Ee()),n(),Ee())),[{id:"googlepaytdonlinemart"}]);class yw{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.paypalButtonCreationService=n}initialize(e){var t,n,i,r,o;return n=this,i=void 0,o=function*(){const{paypalcommerce:n,containerId:i,methodId:r}=e,o=Boolean(null==n?void 0:n.buyNowInitializeOptions);if(!r)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(o&&!n.currencyCode)throw new fi('Unable to initialize payment because "options.paypalcommerce.currencyCode" argument is not provided.');if(o&&"function"!=typeof(null===(t=n.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.paypalcommerce.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');o||(yield this.paymentIntegrationService.loadDefaultCheckout());const a=o?n.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.paypalIntegrationService.loadPayPalSdk(r,a,!1),this.renderButton(i,r,n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){var i,r;const{buyNowInitializeOptions:o,style:a,onComplete:s,onEligibilityFailure:d}=n,c=this.paypalIntegrationService.getPayPalSdkOrThrow(),l=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:u,isAppSwitchEnabled:h}=l.initializationData||{},p={onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},m=Object.assign(Object.assign({fundingSource:c.FUNDING.PAYPAL,style:this.paypalIntegrationService.getValidButtonStyle(a),isAppSwitchEnabled:h,isHostedCheckoutEnabled:u},o&&p),u&&s&&{onPaymentComplete:()=>s()}),y=this.paypalButtonCreationService.createPayPalButton("paypalcommerce",t,m,o);y.isEligible()?(null===(i=y.hasReturned)||void 0===i?void 0:i.call(y))&&h?null===(r=y.resume)||void 0===r||r.call(y):y.render(`#${e}`):d&&"function"==typeof d?d():this.paypalIntegrationService.removeElement(e)}}const gw=vi(e=>{const t=As(e),n=new ks(e,t);return new yw(e,t,n)},[{id:"paypalcommerce"}]);var vw=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class fw{constructor(e,t){this.paymentIntegrationService=e,this.paypalIntegrationService=t}initialize(e){return vw(this,void 0,void 0,function*(){const{paypalcommercecredit:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(a&&!o)throw new fi('Unable to initialize payment because "options.paypalcommercecredit.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.paypalcommercecredit.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=this.paymentIntegrationService.getState(),d=a?o:s.getCartOrThrow().currency.code;yield this.paypalIntegrationService.loadPayPalSdk(i,d,!1),this.renderButton(n,i,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){const{buyNowInitializeOptions:i,style:r,onComplete:o,onEligibilityFailure:a}=n,s=this.paypalIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:c,isAppSwitchEnabled:l}=d.initializationData||{},u={createOrder:()=>this.paypalIntegrationService.createOrder("paypalcommercecredit"),onApprove:({orderID:e})=>this.paypalIntegrationService.tokenizePayment(t,e)},h={onClick:()=>this.handleClick(i),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},p=Object.assign(Object.assign({},!l&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(e,n)=>this.onHostedCheckoutApprove(e,n,t,o)}),m=[s.FUNDING.PAYLATER,s.FUNDING.CREDIT];let y=!1;m.forEach(t=>{if(!y){const n=Object.assign(Object.assign(Object.assign({fundingSource:t,style:this.paypalIntegrationService.getValidButtonStyle(r)},u),i&&h),c&&p),o=s.Buttons(n);o.isEligible()?(o.render(`#${e}`),y=!0):a&&"function"==typeof a&&a()}}),y||this.paypalIntegrationService.removeElement(e)}handleClick(e){return vw(this,void 0,void 0,function*(){if(e){const t=yield this.paypalIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,n,i){return vw(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.paypalIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.paypalIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.paypalIntegrationService.updateOrder("paypalcommerce")}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.paypalIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return vw(this,void 0,void 0,function*(){const t=this.paypalIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.paypalIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.paypalIntegrationService.updateOrder("paypalcommerce")}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return vw(this,void 0,void 0,function*(){const t=this.paypalIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.paypalIntegrationService.updateOrder("paypalcommerce")}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}}const Sw=vi(e=>new fw(e,As(e)),[{id:"paypalcommercecredit"}]);var _w=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ww{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}initialize(e){return _w(this,void 0,void 0,function*(){const{paypalcommercevenmo:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(a&&!o)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.paypalcommercevenmo.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=a?o:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.paypalCommerceIntegrationService.loadPayPalSdk(i,s,!1),this.renderButton(n,i,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){const{buyNowInitializeOptions:i,style:r,onEligibilityFailure:o}=n,a=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),s=a.FUNDING.VENMO,d={createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo"),onApprove:({orderID:e})=>this.paypalCommerceIntegrationService.tokenizePayment(t,e)},c={onClick:()=>this.handleClick(i),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},l=Object.assign(Object.assign({fundingSource:s,style:this.getValidVenmoButtonStyles(r)},d),i&&c),u=a.Buttons(l);u.isEligible()?u.render(`#${e}`):o&&"function"==typeof o?o():this.paypalCommerceIntegrationService.removeElement(e)}getValidVenmoButtonStyles(e){const t=this.paypalCommerceIntegrationService.getValidButtonStyle(e);return t.color===Fs.gold?Object.assign(Object.assign({},t),{color:void 0}):t}handleClick(e){return _w(this,void 0,void 0,function*(){if(e){const t=yield this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const Iw=vi(e=>new ww(e,$s(e)),[{id:"paypalcommercevenmo"}]);var Cw=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class bw{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalExpressScriptLoader=t,this.formPoster=n}initialize(e){return Cw(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);if(!e.paypal)throw new fi;if(!t.config.merchantId)throw new ti(Xn.MissingPaymentMethod);const n=yield this.paypalExpressScriptLoader.loadPaypalSDK(t.config.merchantId);this.renderButton(e,n)})}deinitialize(){return Promise.resolve()}renderButton(e,t){const{containerId:n,methodId:i,paypal:r}=e,{allowCredit:o,clientId:a,onPaymentError:s,shouldProcessPayment:d,style:c}=r,l=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);if(!l.config.merchantId)throw new ti(Xn.MissingPaymentMethod);const u=l.config.merchantId,h=l.config.testMode?"sandbox":"production",p={[h]:a},m=t.FUNDING.CREDIT||"credit",y=o?[m]:[],g=o?[]:[m];return t.Button.render({env:h,client:p,commit:d,funding:{allowed:y,disallowed:g},style:this.getStyle(c),payment:(e,t)=>this.setupPayment(u,t,s),onAuthorize:(e,t)=>this.tokenizePayment(e,i,t,d)},n)}getStyle(e){const{color:t,fundingicons:n,label:i,layout:r,shape:o,size:a,tagline:s}=e||{};return{color:t,fundingicons:n,label:i,layout:r,shape:o||Pp.RECT,size:"small"===a?Ip.RESPONSIVE:a,tagline:s}}setupPayment(e,t,n){return Cw(this,void 0,void 0,function*(){if(!t)throw new ri(ei.CheckoutButtonNotInitialized);try{const n=yield this.paymentIntegrationService.loadDefaultCheckout(),{id:i}=n.getCartOrThrow(),r=n.getHost()||"";return(yield t.request.post(`${r}/api/storefront/payment/paypalexpress`,{merchantId:e,cartId:i},{headers:Object.assign({"X-API-INTERNAL":hr},yr)})).id}catch(e){throw n&&e instanceof Qn&&n(e),e}})}tokenizePayment(e,t,n,i){return Cw(this,void 0,void 0,function*(){if(!n)throw new ri(ei.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new ti(Xn.MissingPayment);const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),o=yield n.payment.get(e.paymentID);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:r.id,action:i?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(o.payer.payer_info)})})}}const Pw=vi(e=>new bw(e,new Tp(a()),Ee()),[{id:"paypalexpress"}]);var Ow=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ew{constructor(e,t,n,i){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n,this.loadingIndicator=i}initialize(e){return Ow(this,void 0,void 0,function*(){const{stripeocs:t,containerId:n}=e||{};if(!t||!n)throw new ri(ei.PaymentNotInitialized);const{gatewayId:i}=t;if(!i)throw new ti(Xn.MissingPaymentMethod);const r=this._getMethodId(i),o=yield this.paymentIntegrationService.loadPaymentMethod(i,{params:{method:r}}),a=o.getPaymentMethodOrThrow(r,i),{loadingContainerId:s,buttonHeight:d,onComplete:c}=t;if(this._loadingIndicatorContainer=s,this._onComplete=c,!dd(a))throw new ti(Xn.MissingPaymentMethod);const{initializationData:l}=a,{captureMethod:u}=l,h=this.stripeIntegrationService.getStripeJsVersion(l);this._captureMethod=u,this._stripeClient=yield this.scriptLoader.getStripeClient(l,o.getCartLocale(),h),yield this.paymentIntegrationService.loadDefaultCheckout(),yield this._mountExpressCheckoutElement(n,this._stripeClient,d),this._initializeEvents(r)})}signIn(){return Promise.resolve()}signOut(){return Promise.resolve()}executePaymentMethodCheckout(){return Promise.resolve()}deinitialize(){return Promise.resolve()}_mountExpressCheckoutElement(e,t,n=40){return Ow(this,void 0,void 0,function*(){const i=this._shouldRequireShippingAddress(),r=Object.assign(Object.assign(Object.assign({shippingAddressRequired:i},i?{allowedShippingCountries:yield this._getAvailableCountries()}:{}),i?{shippingRates:[{id:"_",amount:0,displayName:"Pending rates"}]}:{}),{billingAddressRequired:!0,emailRequired:!0,phoneNumberRequired:!0,paymentMethods:{link:Ta.AUTO,applePay:Ta.NEVER,googlePay:Ta.NEVER,amazonPay:Ta.NEVER,paypal:Ta.NEVER,klarna:Ta.NEVER},buttonHeight:n}),{cartAmount:o=1}=this.paymentIntegrationService.getState().getCart()||{},a=Object.assign({mode:"payment",amount:this._toCents(o),currency:this._getCurrency()},this._captureMethod?{captureMethod:this._captureMethod}:{});this._stripeElements=t.elements(a),this._linkV2Element=this._stripeElements.create(Da.EXPRESS_CHECKOUT,r),this._linkV2Element.mount(`#${e}`)})}_initializeEvents(e){this._linkV2Element&&(this._shouldRequireShippingAddress()&&(this._linkV2Element.on(za.SHIPPING_ADDRESS_CHANGE,e=>Ow(this,void 0,void 0,function*(){return this._onShippingAddressChange(e)})),this._linkV2Element.on(za.SHIPPING_RATE_CHANGE,e=>Ow(this,void 0,void 0,function*(){return this._onShippingRateChange(e)}))),this._linkV2Element.on(za.CONFIRM,t=>Ow(this,void 0,void 0,function*(){return this._onConfirm(t,e)})),this._linkV2Element.on(za.CANCEL,this._onCancel))}_onShippingAddressChange(e){return Ow(this,void 0,void 0,function*(){if(!("address"in e))return;const t=e.address,n={firstName:"",lastName:"",phone:"",company:"",address1:"",address2:"",city:(null==t?void 0:t.city)||"",countryCode:(null==t?void 0:t.country)||"",postalCode:(null==t?void 0:t.postal_code)||"",stateOrProvince:(null==t?void 0:t.state)||"",stateOrProvinceCode:(null==t?void 0:t.state)||"",customFields:[]};yield this.paymentIntegrationService.updateShippingAddress(n);const i=yield this._getAvailableShippingOptions();yield this._updateDisplayedPrice(),(null==i?void 0:i.length)?e.resolve({shippingRates:i}):e.reject()})}_onCancel(){throw new Wi}_onShippingRateChange(e){return Ow(this,void 0,void 0,function*(){if("shippingRate"in e){const{shippingRate:t}=e;yield this._handleShippingOptionChange(null==t?void 0:t.id),yield this._updateDisplayedPrice(),e.resolve({})}})}_onConfirm(e,t){return Ow(this,void 0,void 0,function*(){if("billingDetails"in e&&"shippingAddress"in e&&this._stripeClient&&this._stripeElements){yield this._updateShippingAndBillingAddress(e),yield this.paymentIntegrationService.submitOrder();const n=this._getPaymentPayload(t);try{yield this.paymentIntegrationService.submitPayment(n)}catch(e){yield this._processAdditionalAction(e,t)}}return Promise.resolve()})}_updateShippingAndBillingAddress(e){var t,n,i,r,o,a,s,d;return Ow(this,void 0,void 0,function*(){const c=this._shouldRequireShippingAddress(),l=(null===(n=null===(t=e.shippingAddress)||void 0===t?void 0:t.name)||void 0===n?void 0:n.split(" ")[0])||(null===(r=null===(i=e.billingDetails)||void 0===i?void 0:i.name)||void 0===r?void 0:r.split(" ")[0])||"",u=(null===(a=null===(o=e.shippingAddress)||void 0===o?void 0:o.name)||void 0===a?void 0:a.split(" ")[1])||(null===(d=null===(s=e.billingDetails)||void 0===s?void 0:s.name)||void 0===d?void 0:d.split(" ")[1])||"";if(c){const t=this._mapShippingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateShippingAddress(t)}const h=this._mapBillingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateBillingAddress(h)})}_mapShippingAddress(e,t,n,i){var r,o,a,s,d,c,l;return{firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==e?void 0:e.address)||void 0===r?void 0:r.line1)||"",address2:(null===(o=null==e?void 0:e.address)||void 0===o?void 0:o.line2)||"",city:(null===(a=null==e?void 0:e.address)||void 0===a?void 0:a.city)||"",countryCode:(null===(s=null==e?void 0:e.address)||void 0===s?void 0:s.country)||"",postalCode:(null===(d=null==e?void 0:e.address)||void 0===d?void 0:d.postal_code)||"",stateOrProvince:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",stateOrProvinceCode:(null===(l=null==e?void 0:e.address)||void 0===l?void 0:l.state)||"",customFields:[]}}_mapBillingAddress(e,t,n,i){var r,o,a,s,d,c;return{email:(null==t?void 0:t.email)||"",firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==t?void 0:t.address)||void 0===r?void 0:r.line1)||"",address2:"",city:(null===(o=null==t?void 0:t.address)||void 0===o?void 0:o.city)||"",countryCode:(null===(a=null==t?void 0:t.address)||void 0===a?void 0:a.country)||"",postalCode:(null===(s=null==t?void 0:t.address)||void 0===s?void 0:s.postal_code)||"",stateOrProvince:(null===(d=null==t?void 0:t.address)||void 0===d?void 0:d.state)||"",stateOrProvinceCode:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",customFields:[]}}_processAdditionalAction(e,t){return Ow(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeClient||!this._stripeElements)throw new ri(ei.PaymentNotInitialized);const{data:n}=e.body.additional_action_required,{token:i}=n,{paymentIntent:r}=yield this._confirmStripePaymentOrThrow(n,t),o=this._getPaymentPayload(t,(null==r?void 0:r.id)||i);try{this._toggleLoadingIndicator(!0),yield this.paymentIntegrationService.submitPayment(o),yield this._completeCheckoutFlow()}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}finally{this._toggleLoadingIndicator(!1)}})}_confirmStripePaymentOrThrow(e,t){var n,i,r;return Ow(this,void 0,void 0,function*(){const{token:o,redirect_url:a}=e,s=this.stripeIntegrationService.mapStripePaymentData(this._stripeElements,a);let d;try{const e=(yield this.stripeIntegrationService.isPaymentCompleted(t,this._stripeClient))?yield null===(r=this._stripeClient)||void 0===r?void 0:r.retrievePaymentIntent(o||""):yield null===(n=this._stripeClient)||void 0===n?void 0:n.confirmPayment({elements:s.elements,clientSecret:o,redirect:Ta.IF_REQUIRED,confirmParams:{return_url:null===(i=s.confirmParams)||void 0===i?void 0:i.return_url}});if(d=null==e?void 0:e.error,d||!(null==e?void 0:e.paymentIntent))throw new Qr;return e}catch(e){return this.stripeIntegrationService.throwStripeError(d)}})}_completeCheckoutFlow(){return Ow(this,void 0,void 0,function*(){return"function"==typeof this._onComplete?this._onComplete():(window.location.replace("/checkout/order-confirmation"),Promise.resolve())})}_getPaymentPayload(e,t){var n;const i=(null===(n=this.paymentIntegrationService.getState().getCart())||void 0===n?void 0:n.id)||"";return{methodId:e,paymentData:{formattedPayload:Object.assign(Object.assign({cart_id:i},t?{credit_card_token:{token:t}}:{}),{confirm:!1,method:Aa.Link})}}}_shouldRequireShippingAddress(){const{getCart:e}=this.paymentIntegrationService.getState(),{lineItems:t}=e()||{};return!!(null==t?void 0:t.physicalItems.length)}_updateDisplayedPrice(){return Ow(this,void 0,void 0,function*(){this._stripeElements&&this._stripeElements.update({currency:this._getCurrency(),mode:"payment",amount:yield this._getTotalPrice()})})}_getCurrency(){var e;if(!this._currencyCode){const t=null===(e=this.paymentIntegrationService.getState().getCart())||void 0===e?void 0:e.currency;t&&(this._currencyCode=t.code.toLowerCase())}return this._currencyCode}_getTotalPrice(){var e;return Ow(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const{getCheckoutOrThrow:t,getCart:n}=this.paymentIntegrationService.getState(),{decimalPlaces:i}=(null===(e=n())||void 0===e?void 0:e.currency)||{},r=ge(t().outstandingBalance,i).toFixed(i);return this._toCents(+r)})}_getAvailableCountries(){var e;return Ow(this,void 0,void 0,function*(){const t=yield this.paymentIntegrationService.loadShippingCountries();return((null===(e=t.getShippingCountries())||void 0===e?void 0:e.map(e=>e.code))||[]).filter(e=>Sd.includes(e))})}_getAvailableShippingOptions(){var e,t,n;return Ow(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getConsignments();if(!(null==i?void 0:i[0]))return;const r=i[0],o=(r.availableShippingOptions||[]).map(this._getStripeShippingOption.bind(this)),a=null===(e=r.availableShippingOptions)||void 0===e?void 0:e.find(e=>e.isRecommended),s=null===(t=r.selectedShippingOption)||void 0===t?void 0:t.id,d=null==a?void 0:a.id;return s?o.sort(e=>e.id===s?-1:0):d?(o.sort(e=>e.id===d?-1:0),yield this._handleShippingOptionChange(d)):yield this._handleShippingOptionChange(null===(n=o[0])||void 0===n?void 0:n.id),o.slice(0,9)})}_getStripeShippingOption({id:e,cost:t,description:n}){return{id:e,displayName:n,amount:this._toCents(t)}}_handleShippingOptionChange(e){return Ow(this,void 0,void 0,function*(){if(e&&"shipping_option_unselected"!==e)return this.paymentIntegrationService.selectShippingOption(e)})}_getAmountTransformer(){if(this._amountTransformer)return this._amountTransformer;const{getCart:e}=this.paymentIntegrationService.getState(),{currency:t}=e()||{};return t?new fd(t.decimalPlaces):void 0}_toCents(e){const t=Math.round(100*e),n=this._getAmountTransformer();return n?n.toInteger(e):t}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this.loadingIndicator.show(this._loadingIndicatorContainer):this.loadingIndicator.hide()}_getMethodId(e){const{initializationData:{checkoutSessionEnabled:t}={}}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e);return t?Aa.CHECKOUT_SESSION:Aa.OCS}}const Aw=vi(e=>{const t=new Ra(a()),n=new vd({containerStyles:yd});return new Ew(e,t,new pd(e,t),n)},[{id:"stripeocs"}]),Tw=e=>{const t=Ie(e);return document.getElementById(t)?Tw(e):t};function kw(e){return Object.prototype.hasOwnProperty.call(e,"cacheKey")}class Dw{constructor(e){this._lastId=0,this._map={maps:[]},this._usedMaps=[],this._options=Object.assign({maxSize:0,isEqual:Be,onExpire:ce},e)}getKey(...e){const t=this._resolveMap(...e),{index:n,parentMap:i}=t;let{map:r}=t;return r&&r.cacheKey?r.usedCount++:r=this._generateMap(i,e.slice(n)),this._removeLeastUsedMap(r),r.cacheKey}getUsedCount(...e){const{map:t}=this._resolveMap(...e);return t?t.usedCount:0}_resolveMap(...e){let t=0,n=this._map;for(;n.maps.length;){let i=!1;for(let r=0;r{const i=Object.getOwnPropertyDescriptor(e.prototype,n);i&&"constructor"!==n&&Object.defineProperty(t.prototype,n,function(e,t,n){if("function"!=typeof n.value)return n;let i=new Dw,r=n.value,o=Pe(r);return Fn(e,t,{get(){const e=(...e)=>{const t=o.call(this,...e);if(1===i.getUsedCount(...e))return t;const n=r.call(this,...e);return Pv(n,t,{keyFilter:e=>!function(e){return 0===`${e}`.indexOf("$$")||0===`${e}`.indexOf("_")}(e)})?t:(o.cache.set(i.getKey(...e),n),n)};return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e},set(e){i=new Dw,r=e,o=Pe(r)}})}(e.prototype,n,i))}),t}let zw=class{constructor(e){this._checkoutButton=e.checkoutButton}getInitializeButtonError(e){return this._checkoutButton.getInitializeError(e)}getDeinitializeButtonError(e){return this._checkoutButton.getDeinitializeError(e)}};zw=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Mw],zw);const Nw=zw;let xw=class{constructor(e){this._checkoutButton=e.checkoutButton}isInitializingButton(e){return this._checkoutButton.isInitializing(e)}isDeinitializingButton(e){return this._checkoutButton.isDeinitializing(e)}};xw=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Mw],xw);const Rw=xw;function Fw(e){return{errors:new Nw(e),statuses:new Rw(e)}}let Lw=class{constructor(e,t){this._store=e,this._buttonStrategyActionCreator=t,this._state=Fw(this._store.getState()),this._store.subscribe(e=>{this._state=Fw(e)})}getState(){return this._state}subscribe(e,...t){return this._store.subscribe(()=>e(this.getState()),e=>e.checkoutButton.getState(),...t.map(e=>t=>e(Fw(t))))}initializeButton(e){const t=(n=e.containerId,/^\w[\w\-\:\.]*$/.test(n)?[e.containerId]:function(e,t){const n=document.querySelectorAll(e);if(!n.length)throw new qt(`Unable to find any element with the specified selector: ${e}`);return Array.prototype.slice.call(n).map(e=>(e.id||(e.id=Tw(t)),e.id))}(e.containerId,`${e.methodId}-container`));var n;return Promise.all(t.map(t=>{const n=this._buttonStrategyActionCreator.initialize(Object.assign(Object.assign({},e),{containerId:t})),i=`checkoutButtonStrategy:${e.methodId}:${t}`;return this._store.dispatch(n,{queueId:i})})).then(()=>this.getState())}deinitializeButton(e){const t=this._buttonStrategyActionCreator.deinitialize(e),n=`checkoutButtonStrategy:${e.methodId}`;return this._store.dispatch(t,{queueId:n}).then(()=>this.getState())}};Lw=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],Lw);const Bw=Lw;class jw{constructor(e,t,n){this._registry=e,this._registryV2=t,this._paymentMethodActionCreator=n}initialize(e){return t=>{const n={methodId:e.methodId,containerId:e.containerId};if(t.getState().checkoutButton.isInitialized(e.methodId,e.containerId))return f();const i=e.currencyCode?{params:{currencyCode:e.currencyCode}}:{},r=Object.assign(Object.assign({},i),{timeout:e.timeout,useCache:!0});return g(C(l(Hv.InitializeButtonRequested,void 0,n)),this._paymentMethodActionCreator.loadPaymentMethod(e.methodId,r)(t),v(()=>this._getStrategy(e.methodId).initialize(e).then(()=>l(Hv.InitializeButtonSucceeded,void 0,n)))).pipe(P(e=>Je(Hv.InitializeButtonFailed,e,n)))}}deinitialize(e){return t=>{const n={methodId:e.methodId};return t.getState().checkoutButton.isInitialized(e.methodId)?g(C(l(Hv.DeinitializeButtonRequested,void 0,n)),v(()=>this._getStrategy(e.methodId).deinitialize().then(()=>l(Hv.DeinitializeButtonSucceeded,void 0,n)))).pipe(P(e=>Je(Hv.DeinitializeButtonFailed,e,n))):f()}}_getStrategy(e){let t;try{t=this._registryV2.get({id:e})}catch(n){t=this._registry.get(e)}return t}}class Uw extends it{constructor(e){super(e||"Unable to proceed because the client library of a payment method is not loaded or ready to be used."),this.name="PaymentMethodClientUnavailableError",this.type="payment_method_client_unavailable"}}var qw,Vw,Gw,Hw,Ww,$w,Yw,Kw;class Jw{constructor(e){this._scriptLoader=e,this._window=window}loadPaypal(e=""){return t=this,n=void 0,r=function*(){const t="//www.paypalobjects.com/api/checkout.min.js",n={async:!0,attributes:{"data-merchant-id":e}};if(e?yield this._scriptLoader.loadScript(t,n):yield this._scriptLoader.loadScript(t),!this._window.paypal)throw new Uw;return this._window.paypal},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(qw||(qw={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(Vw||(Vw={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black",e.WHITE="white"}(Gw||(Gw={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(Hw||(Hw={})),function(e){e.PILL="pill",e.RECT="rect"}(Ww||(Ww={}));class Zw{constructor(e,t,n,i,r=""){this._store=e,this._checkoutActionCreator=t,this._paypalScriptLoader=n,this._formPoster=i,this._host=r}initialize(e){const t=e.paypal,n=this._store.getState(),i=this._paymentMethod=n.paymentMethods.getPaymentMethod(e.methodId);if(!t)throw new qt;if(!i)throw new rt(et.MissingPaymentMethod);return this._paypalScriptLoader.loadPaypal(i.config.merchantId).then(n=>{var r,o;if(!i||!i.config.merchantId)throw new rt(et.MissingPaymentMethod);const a=i.config.merchantId,s=i.config.testMode?"sandbox":"production",d={[s]:t.clientId},c=n.FUNDING.CREDIT||"credit",l=t.allowCredit?[c]:[],u=t.allowCredit?[]:[c];return n.Button.render({env:s,client:d,commit:t.shouldProcessPayment,funding:{allowed:l,disallowed:u},style:Object.assign(Object.assign({shape:Ww.RECT},pe(t.style,"layout","color","label","shape","tagline","fundingicons")),{size:"paypalexpress"===i.id&&"small"===(null===(r=t.style)||void 0===r?void 0:r.size)?Vw.RESPONSIVE:null===(o=t.style)||void 0===o?void 0:o.size}),payment:(e,n)=>this._setupPayment(a,n,t.onPaymentError),onAuthorize:(e,n)=>this._tokenizePayment(e,n,t.shouldProcessPayment,t.onAuthorizeError)},e.containerId)})}deinitialize(){return this._paymentMethod=void 0,Promise.resolve()}_setupPayment(e,t,n){if(!t)throw new yn(cn.CheckoutButtonNotInitialized);return this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then(n=>{const i=n.cart.getCart(),r=i?i.id:"";return t.request.post(`${this._host}/api/storefront/payment/paypalexpress`,{merchantId:e,cartId:r},{headers:Object.assign({"X-API-INTERNAL":At},Xe)})}).then(e=>e.id).catch(e=>{throw n&&n(e),e})}_tokenizePayment(e,t,n,i){if(!this._paymentMethod)throw new yn(cn.CheckoutButtonNotInitialized);if(!t)throw new yn(cn.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new rt(et.MissingPayment);const r=this._paymentMethod.id;return t.payment.get(e.paymentID).then(t=>{this._formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:r,action:n?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(t.payer.payer_info)})})}}function Qw(e){const{host:t}=null!=e?e:{},i=m_({config:{meta:{host:null==e?void 0:e.host,locale:null==e?void 0:e.locale},errors:{},statuses:{}}}),r=n({host:t}),o=Ee({host:t}),s=function(e,t){const n=new Gt;for(const[,i]of Object.entries(t))if(Ut(i))for(const t of i.resolveIds)n.register(t,()=>i(e));return n}(Hg(i),We);return new Bw(i,new jw(function(e,t,n,i){const r=new Vt,o=a(),s=new en(t),d=new nn(s,new bt(new Tt(t)),new on(new an(t)));return r.register(zy.PAYPALEXPRESS,()=>new Zw(e,d,new Jw(o),n,i)),r}(i,r,o,t),s,new Wm(new $m(r))))}!function(e){e.CheckoutComplete="CHECKOUT_COMPLETE",e.CheckoutError="CHECKOUT_ERROR",e.CheckoutLoaded="CHECKOUT_LOADED",e.FrameError="FRAME_ERROR",e.FrameLoaded="FRAME_LOADED",e.SignedOut="SIGNED_OUT"}($w||($w={}));class Xw extends Ot{constructor(e){super(e,{message:e.body.title}),this.name="InvalidLoginTokenError",this.type="invalid_login_token"}}!function(e){e.MissingContainer="missing_container",e.MissingContent="missing_content",e.UnknownError="unknown_error"}(Yw||(Yw={}));class eI extends it{constructor(e,t=Yw.UnknownError){super(e||"Unable to embed the checkout form."),this.subtype=t,this.name="NotEmbeddableError",this.type="not_embeddable"}}!function(e){e.StyleConfigured="STYLE_CONFIGURED"}(Kw||(Kw={}));const tI="isCookieAllowed",nI="lastAllowCookieAttempt";let iI=class{constructor(e,t,n,i,r,o,a,s){this._iframeCreator=e,this._messageListener=t,this._messagePoster=n,this._loadingIndicator=i,this._requestSender=r,this._storage=o,this._location=a,this._options=s,this._isAttached=!1,this._options.onComplete&&this._messageListener.addListener($w.CheckoutComplete,this._options.onComplete),this._options.onError&&this._messageListener.addListener($w.CheckoutError,this._options.onError),this._options.onLoad&&this._messageListener.addListener($w.CheckoutLoaded,this._options.onLoad),this._options.onFrameLoad&&this._messageListener.addListener($w.FrameLoaded,this._options.onFrameLoad),this._options.onSignOut&&this._messageListener.addListener($w.SignedOut,this._options.onSignOut),this._messageListener.addListener($w.FrameLoaded,()=>this._configureStyles())}attach(){return this._isAttached?Promise.resolve(this):(this._isAttached=!0,this._messageListener.listen(),this._loadingIndicator.show(this._options.containerId),this._allowCookie().then(()=>this._attemptLogin()).then(e=>this._iframeCreator.createFrame(e,this._options.containerId)).then(e=>{this._iframe=e,this._configureStyles(),this._loadingIndicator.hide()}).catch(e=>(this._isAttached=!1,this._retryAllowCookie(e).catch(()=>{throw this._messageListener.trigger({type:$w.FrameError,payload:e}),this._loadingIndicator.hide(),e}))).then(()=>this))}detach(){this._isAttached&&(this._isAttached=!1,this._messageListener.stopListen(),this._iframe&&this._iframe.parentNode&&(this._iframe.parentNode.removeChild(this._iframe),this._iframe.iFrameResizer.close()))}_configureStyles(){this._iframe&&this._iframe.contentWindow&&this._options.styles&&(this._messagePoster.setTarget(this._iframe.contentWindow),this._messagePoster.post({type:Kw.StyleConfigured,payload:this._options.styles}))}_attemptLogin(){return/^\/login\/token/.test(In(this._options.url).pathname)?this._requestSender.post(this._options.url).then(({body:{redirectUrl:e}})=>e).catch(e=>Promise.reject(new Xw(e))):Promise.resolve(this._options.url)}_allowCookie(){if(this._storage.getItem(tI))return Promise.resolve();this._storage.setItem(tI,!0),this._storage.setItem(nI,Date.now());const{origin:e}=In(this._options.url),t=`${e}/embedded-checkout/allow-cookie?returnUrl=${encodeURIComponent(this._location.href)}`;return document.body.style.visibility="hidden",this._location.replace(t),new Promise(()=>{})}_retryAllowCookie(e){const t=Number(this._storage.getItem(nI));return(!t||Date.now()-t>6e5)&&e instanceof eI&&e.subtype===Yw.MissingContent?(this._storage.removeItem(nI),this._storage.removeItem(tI),this._allowCookie()):Promise.reject()}};iI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],iI);const rI=iI;class oI{constructor(e){this._options=e}createFrame(e,t){const n=document.getElementById(t),{timeout:i=6e4}=this._options||{};if(!n)throw new eI("Unable to embed the iframe because the container element could not be found.",Yw.MissingContainer);const r=document.createElement("iframe");return r.src=e,r.style.border="none",r.style.display="none",r.style.width="100%",r.allowPaymentRequest=!0,r.allow="payment",n.appendChild(r),this._toResizableFrame(r,i).catch(e=>{throw n.removeChild(r),e})}_toResizableFrame(e,t){return new Promise((n,i)=>{const r=window.setTimeout(()=>{i(new eI("Unable to embed the iframe because the content could not be loaded."))},t),o=t=>{if((t.origin===In(e.src).origin||t.origin===Wn(In(e.src)).origin)&&(bn(t.data,$w.FrameError)&&(a(),i(new eI(t.data.payload.message,Yw.MissingContent))),bn(t.data,$w.FrameLoaded))){e.style.display="";const i=Dn({scrolling:!1,sizeWidth:!1,heightCalculationMethod:t.data.payload&&t.data.payload.contentId?"taggedElement":"lowestElement"},e);a(),n(i[i.length-1])}},a=()=>{window.removeEventListener("message",o),window.clearTimeout(r)};window.addEventListener("message",o)})}}function aI(e){const t=In(e.url).origin;return new rI(new oI,new Yn(t),new Pn(t),new vd({styles:e.styles&&e.styles.loadingIndicator}),n(),new iy("BigCommerce.EmbeddedCheckout"),window.location,e).attach()}function sI(e){if(!e.payload||!e.payload.contentId)return;const t=document.getElementById(e.payload.contentId);t&&!t.hasAttribute("data-iframe-height")&&t.setAttribute("data-iframe-height","")}function dI(e){return"object"==typeof e&&null!==e&&"message"in e&&"type"in e}let cI=class{constructor(e,t,n,i={}){this._messageListener=e,this._messagePoster=t,this._untargetedMessagePoster=n,this._messageHandlers=i,this._messageListener.listen()}postComplete(){const e={type:$w.CheckoutComplete};this._postMessage(e)}postError(e){const t={type:$w.CheckoutError,payload:this._transformError(e)};this._postMessage(t)}postFrameError(e){const t={type:$w.FrameError,payload:this._transformError(e)};this._postMessage(t,{untargeted:!0})}postFrameLoaded(e){const t={type:$w.FrameLoaded,payload:e};this._postMessage(t)}postLoaded(){const e={type:$w.CheckoutLoaded};this._postMessage(e)}postSignedOut(){const e={type:$w.SignedOut};this._postMessage(e)}receiveStyles(e){this._messageListener.addListener(Kw.StyleConfigured,({payload:t})=>{e(t)})}_postMessage(e,t){if(this._notifyMessageHandlers(e),t&&t.untargeted)return this._untargetedMessagePoster.post(e);this._messagePoster.post(e)}_notifyMessageHandlers(e){Object.keys(this._messageHandlers).forEach(t=>{if(e.type!==t)return;const n=this._messageHandlers[t];n&&n.call(null,e)})}_transformError(e){return{message:e.message,type:dI(e)?e.type:void 0,subtype:dI(e)?e.subtype:void 0}}};cI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],cI);const lI=cI;let uI=class{postComplete(){}postError(){}postFrameError(){}postFrameLoaded(){}postLoaded(){}postSignedOut(){}receiveStyles(){}};uI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],uI);const hI=uI;function pI(e){Ve(939);const t=e.parentWindow||window.parent;return window===t?new hI:new lI(new Yn(e.parentOrigin),new Pn(e.parentOrigin,t),new Pn("*",t),{[$w.FrameLoaded]:sI})}const mI="en",yI="optimized_checkout";let gI=class{constructor(e,t){this._logger=t;const{locale:n,locales:i,translations:r}=this._transformConfig(e);this._locale=n,this._locales=i,this._translations=r,this._formatters={}}mapKeys(e){Object.keys(e).forEach(t=>{const n=`${yI}.${e[t]}`;this._translations[`${yI}.${t}`]=this._translations[n]})}getLocale(){return this._hasTranslations()?this._locale:mI}translate(e,t={}){var n;const i=`${yI}.${e}`;if("string"!=typeof this._translations[i])return this._logger.warn(`Translation key "${i}" is missing`),i;this._formatters[i]||(this._formatters[i]=new je(this._escapeSpecialCharacters(this._translations[i]||""),this._locales[i],void 0,{ignoreTag:!0}));try{return this._formatters[i].format(this._transformData(t))}catch(e){if(this._isFormatError(e))return null!==(n=e.originalMessage)&&void 0!==n?n:"";throw e}}_transformConfig(e={}){const t={defaultLocale:"",defaultTranslations:{},translations:{},locales:{},locale:e.locale||mI},n=e.locales||{},i=this._flattenObject(e.translations||{}),r=this._flattenObject(e.defaultTranslations||{}),o=this._flattenObject(e.fallbackTranslations||{});return _e(Object.keys(o),Object.keys(r),Object.keys(i)).forEach(a=>{var s,d;i&&i[a]?(t.translations[a]=i[a],t.locales[a]=n[a]||t.locale):r[a]?(t.translations[a]=r[a],t.locales[a]=null!==(s=e.defaultLocale)&&void 0!==s?s:mI):(t.translations[a]=o[a],t.locales[a]=null!==(d=e.fallbackLocale)&&void 0!==d?d:mI)}),t}_flattenObject(e,t={},n=""){try{Object.keys(e).forEach(i=>{const r=e[i],o=n?`${n}.${i}`:i;if(Z(r))return this._flattenObject(r,t,o);t[o]=r})}catch(e){this._logger.warn(`Unable to parse object: ${e}`)}return t}_transformData(e){return Object.keys(e).reduce((t,n)=>{const i=e[n];return t[n]=null==i?"":i,t},{})}_hasTranslations(){return Object.keys(this._locales).map(e=>this._locales[e]).filter(e=>e.split("-")[0]===this._locale.split("-")[0]).length>0}_isFormatError(e){return"object"==typeof e&&null!==e&&"originalMessage"in e}_escapeSpecialCharacters(e){return e.replace(/(\w+)='([^']*)'/g,"$1=''$2''")}};gI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],gI);const vI=gI;function fI(e={}){return new vI(e,wt())}let SI=class{constructor(e){this._storeConfig=e,this._customerFormatter=new Fo(this._storeConfig.shopperCurrency),this._storeFormatter=new Fo(this._storeConfig.currency)}toCustomerCurrency(e){const t=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(e*t)}toStoreCurrency(e){return this._storeFormatter.format(e)}};SI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],SI);const _I=SI;function wI(e){return new _I(e)}function II(e){return e&&"ga"in e&&"function"==typeof e.ga}function CI(e,t){II(window)&&window.ga("send",e,Object.assign(Object.assign({},t),{nonInteraction:!1}))}function bI(e){return PI(e).length>=8096}function PI(e){return Object.keys(e).reduce((t,n)=>{const i=typeof e[n];return"string"===i||"number"===i?[...t,`${n}=${e[n]}`]:"object"===i&&null!==e[n]?[...t,PI(e[n])]:t},[]).join("&")}var OI;!function(e){e[e.CUSTOMER=1]="CUSTOMER",e[e.SHIPPING=2]="SHIPPING",e[e.BILLING=3]="BILLING",e[e.PAYMENT=4]="PAYMENT"}(OI||(OI={}));const EI={customer:OI.CUSTOMER,shipping:OI.SHIPPING,billing:OI.BILLING,payment:OI.PAYMENT};class AI{constructor(e,t,n,{checkoutSteps:i}={}){if(this.checkoutService=e,this.analyticsExtraItemsManager=t,this.analytics=n,this._checkoutStarted=!1,this._completedSteps={},this._viewedSteps={},this._analyticStepOrder=["customer","shipping","billing","payment"],void 0!==i){if(i.some(e=>!(e in EI)))throw new qt(`Invalid checkout steps provided. Valid values are: ${ie(EI).join(", ")}.`);this._analyticStepOrder=i}}trackCheckoutStarted(){if(this._checkoutStarted)return;const e=this.getCheckout();if(!e)return;const{coupons:t,grandTotal:n,shippingCostTotal:i,taxTotal:r,cart:{lineItems:o,discountAmount:a,id:s}}=e,d=this.analyticsExtraItemsManager.saveExtraItemsData(s,o);this.analytics.track("Checkout Started",this.getTrackingPayload({revenue:n,shipping:i,tax:r,discount:a,coupons:t,lineItems:o,extraItemsData:d})),this._checkoutStarted=!0}trackOrderComplete(){var e;const t=this.getOrder();if(!t)return;const{isComplete:n,orderId:i,orderAmount:r,shippingCostTotal:o,taxTotal:a,discountAmount:s,coupons:d,lineItems:c,cartId:l}=t;if(!n)return;const u=this.analyticsExtraItemsManager.readExtraItemsData(l);if(null===u)return;const h=null===(e=this.checkoutService.getState().data.getConfig())||void 0===e?void 0:e.checkoutSettings.features["DATA-6891.missing_orders_within_GA"],p=this.getTrackingPayload({orderId:i,revenue:r,shipping:o,tax:a,discount:s,coupons:d,extraItemsData:u,lineItems:c});if(h&&pl(window)&&II(window)&&bI(p))return CI("transaction",{"&ti":p.order_id,"&ta":p.affiliation,"&tr":p.revenue,"&ts":p.shipping,"&tt":p.tax,"&tcc":p.coupon,"&cu":p.currency}),p.products.forEach(e=>{CI("item",{"&ti":p.order_id,"&in":e.name,"&ic":e.sku,"&iv":`${e.category}`,"&ip":e.price,"&iq":e.quantity})}),this.analyticsExtraItemsManager.clearExtraItemData(l);this.analytics.track("Order Completed",p),this.analyticsExtraItemsManager.clearExtraItemData(l)}trackStepViewed(e){const t=this.getIdFromStep(e);t&&!this.hasStepViewed(t)&&(this.trackViewed(t),this.backfill(t))}trackStepCompleted(e){const t=this.getIdFromStep(e);t&&!this.hasStepCompleted(t)&&(this.backfill(t),this.trackCompleted(t))}backfill(e){for(const t of this._analyticStepOrder){const n=this.getIdFromStep(t);if(!n)break;if(this.hasStepViewed(n)||this.trackViewed(n),n===e)break;this.hasStepCompleted(n)||this.trackCompleted(n)}}trackCompleted(e){const t=this.getSelectedShippingOption(),{code:n=""}=this.getShopperCurrency()||{},i=this.getPaymentMethodName(),r={step:e,currency:n};t&&(r.shipping_method=t.description),i&&(r.payment_method=i),r.shipping_method||r.payment_method||(r.shipping_method=" "),this.analytics.track("Checkout Step Completed",r);const o=t?t.id:"",a=e===OI.SHIPPING?`${e}-${o}`:e;this._completedSteps[a]=!0}getTrackingPayload({orderId:e,revenue:t,shipping:n,tax:i,discount:r,coupons:o,extraItemsData:a,lineItems:s}){const{code:d=""}=this.getShopperCurrency()||{},{storeName:c=""}=this.getStoreProfile()||{};return{order_id:String(e),affiliation:c,revenue:this.toShopperCurrency(t),shipping:this.toShopperCurrency(n),tax:this.toShopperCurrency(i),discount:this.toShopperCurrency(r),coupon:(o||[]).map(e=>e.code.toUpperCase()).join(","),currency:d,products:this.getProducts(a,s)}}hasStepCompleted(e){const t=this.getSelectedShippingOption(),n=t?t.id:"";return Object.prototype.hasOwnProperty.call(this._completedSteps,e)||e===OI.SHIPPING&&Object.prototype.hasOwnProperty.call(this._completedSteps,`${e}-${n}`)}hasStepViewed(e){return!!this._viewedSteps[e]}getIdFromStep(e){const t=e.split(".");return EI[t[0]]||null}trackViewed(e){const t=this.getShopperCurrency();this.analytics.track("Checkout Step Viewed",{step:e,currency:t?t.code:""}),this._viewedSteps[e]=!0}getOrder(){const{data:{getOrder:e}}=this.checkoutService.getState();return e()}getCheckout(){const{data:{getCheckout:e}}=this.checkoutService.getState();return e()}getShopperCurrency(){const{data:{getConfig:e}}=this.checkoutService.getState(),t=e();return t&&t.shopperCurrency}getStoreProfile(){const{data:{getConfig:e}}=this.checkoutService.getState(),t=e();return t&&t.storeProfile}toShopperCurrency(e){const{exchangeRate:t=1}=this.getShopperCurrency()||{};return Math.round(e*t*100)/100}getSelectedShippingOption(){const{data:e}=this.checkoutService.getState(),t=e.getSelectedShippingOption();return t&&t.id&&t.description?t:null}getPaymentMethodName(){const{data:e}=this.checkoutService.getState(),t=e.getSelectedPaymentMethod();return t&&t.config&&t.config.displayName||""}getProducts(e,t){const n=(t.customItems||[]).map(e=>({product_id:e.id,sku:e.sku,price:e.listPrice,quantity:e.quantity,name:e.name})),i=t.giftCertificates.map(e=>({product_id:e.id,price:this.toShopperCurrency(e.amount),name:e.name,quantity:1}));return[...n,...[...t.physicalItems,...t.digitalItems].map(t=>{let n;t.options&&t.options.length&&(n=t.options.map(e=>`${e.name}:${e.value}`),n.sort());const i=Array.isArray(n)&&n.length?n.join(", "):"single-product-option",r=e[t.productId]&&e[t.productId].brand;return Object.assign({product_id:String(t.productId),sku:t.sku,price:t.salePrice,image_url:t.imageUrl,name:t.name,quantity:t.quantity,category:e[t.productId]?e[t.productId].category:"",variant:i},r&&{brand:r})}),...i]}}class TI{trackCheckoutStarted(){}trackOrderComplete(){}trackStepViewed(){}trackStepCompleted(){}}function kI(e,t){const{data:n}=e.getState(),i=n.getConfig();if(!i)throw new rt(et.MissingCheckoutConfig);const{isAnalyticsEnabled:r}=i.checkoutSettings;return r&&pl(window)?new AI(e,new hl(Te),window.analytics,t):new TI}function DI(e){return Boolean(e.hasOwnProperty("braintreeFastlane"))}class MI{constructor(e){this.checkoutService=e,this._selectedPaymentMethodId=""}customerPaymentMethodExecuted(){this._shouldTrackFastlaneEvent()&&this._trackEmailSubmitted()}paymentComplete(){this._shouldTrackFastlaneEvent()&&this._trackOrderPlaced(this._selectedPaymentMethodId)}selectedPaymentMethod(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!1))}walletButtonClick(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!0))}_shouldTrackFastlaneEvent(){const e=this.checkoutService.getState(),t=e.data.getPaymentMethod("braintree")||e.data.getPaymentMethod("braintreeacceleratedcheckout"),n=null==t?void 0:t.initializationData.isBraintreeAnalyticsV2Enabled,i=DI(window)&&window.braintreeFastlane.events;return n&&i}_getBraintreeEventsOrThrow(){if(DI(window))return window.braintreeFastlane.events;throw new mi}_trackEmailSubmitted(){const{emailSubmitted:e}=this._getBraintreeEventsOrThrow();e(this._getEmailSubmittedEventOptions())}_trackApmSelected(e,t){const{apmSelected:n}=this._getBraintreeEventsOrThrow();n(this._getApmSelectedEventOptions(e,t))}_trackOrderPlaced(e){const{orderPlaced:t}=this._getBraintreeEventsOrThrow();t(this._getOrderPlacedEventOptions(e))}_getEventCommonOptions(){var e,t;const n=this.checkoutService.getState(),i=n.data.getCart(),r=null===(e=n.data.getConfig())||void 0===e?void 0:e.storeProfile,o=null===(t=n.data.getCustomer())||void 0===t?void 0:t.isGuest,a=n.data.getPaymentMethod("braintreeacceleratedcheckout"),s=[{treatment_group:!n.errors.getLoadPaymentMethodError("braintreeacceleratedcheckout")&&(null==a?void 0:a.initializationData.shouldRunAcceleratedCheckout)?"test":"control"}];return{context_type:"cs_id",context_id:(null==i?void 0:i.id)||"",page_type:"checkout_page",page_name:window.document.title,partner_name:"bigc",user_type:o?"store_guest":"store_member",store_id:(null==r?void 0:r.storeId)||"",merchant_name:(null==r?void 0:r.storeName)||"",experiment:JSON.stringify(s)}}_getEmailSubmittedEventOptions(){const e=(this.checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{user_email_saved:!1,apm_shown:e.length>1?"1":"0",apm_list:e.join(",")})}_getApmSelectedEventOptions(e,t){const n=(this.checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{apm_shown:n.length>1?"1":"0",apm_list:n.join(","),apm_selected:e,apm_location:t?"pre-email section":"payment section"})}_getOrderPlacedEventOptions(e){const t=this.checkoutService.getState().data.getCart();return Object.assign(Object.assign({},this._getEventCommonOptions()),{selected_payment_method:e,currency_code:(null==t?void 0:t.currency.code)||""})}}function zI(e){return new MI(e)}class NI{constructor(e){this._checkoutService=e,this._selectedPaymentMethodId=""}customerPaymentMethodExecuted(){this._shouldTrackFastlaneEvent()&&this._trackEmailSubmitted()}paymentComplete(){this._shouldTrackFastlaneEvent()&&this._trackOrderPlaced(this._selectedPaymentMethodId)}selectedPaymentMethod(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!1))}walletButtonClick(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!0))}_shouldTrackFastlaneEvent(){const e=this._checkoutService.getState().data.getPaymentMethod("paypalcommerce"),t=((null==e?void 0:e.initializationData)||{}).isPayPalCommerceAnalyticsV2Enabled,n=window,i=!!n.paypalFastlane&&!!n.paypalFastlane.events;return t&&i}_getPayPalEventsOrThrow(){const e=window;if(e.paypalFastlane&&e.paypalFastlane.events)return e.paypalFastlane.events;throw new mi}_trackEmailSubmitted(){const{emailSubmitted:e}=this._getPayPalEventsOrThrow();e(this._getEmailSubmittedEventOptions())}_trackApmSelected(e,t){const{apmSelected:n}=this._getPayPalEventsOrThrow();n(this._getApmSelectedEventOptions(e,t))}_trackOrderPlaced(e){const{orderPlaced:t}=this._getPayPalEventsOrThrow();t(this._getOrderPlacedEventOptions(e))}_getEventCommonOptions(){var e,t;const n=this._checkoutService.getState(),i=n.data.getCart(),r=null===(e=n.data.getConfig())||void 0===e?void 0:e.storeProfile,o=null===(t=n.data.getCustomer())||void 0===t?void 0:t.isGuest,a="paypalcommerceacceleratedcheckout",s=n.data.getPaymentMethod(a),d=[{treatment_group:!n.errors.getLoadPaymentMethodError(a)&&(null==s?void 0:s.initializationData.shouldRunAcceleratedCheckout)?"test":"control"}];return{context_type:"cs_id",context_id:(null==i?void 0:i.id.replace(/-/g,""))||"",page_type:"checkout_page",page_name:window.document.title,partner_name:"bigc",user_type:o?"store_guest":"store_member",store_id:(null==r?void 0:r.storeId)||"",merchant_name:(null==r?void 0:r.storeName)||"",experiment:JSON.stringify(d)}}_getEmailSubmittedEventOptions(){const e=(this._checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{user_email_saved:!1,apm_shown:e.length>1?"1":"0",apm_list:e.join(",")})}_getApmSelectedEventOptions(e,t){const n=(this._checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{apm_shown:n.length>1?"1":"0",apm_list:n.join(","),apm_selected:e,apm_location:t?"pre-email section":"payment section"})}_getOrderPlacedEventOptions(e){const t=this._checkoutService.getState().data.getCart();return Object.assign(Object.assign({},this._getEventCommonOptions()),{selected_payment_method:e,currency_code:(null==t?void 0:t.currency.code)||""})}}function xI(e){return new NI(e)}var RI;class FI{constructor(e,t){this._host=e,this._hostedFormFactory=t}submitStoredCard(e,t){return n=this,i=void 0,o=function*(){const n=this._hostedForm;if(!n)throw new yn(cn.PaymentNotInitialized);yield n.validate().then(()=>n.submitStoredCard({fields:e,data:t}))},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}initialize(e){const t=this._hostedFormFactory.create(this._host,e);return t.attach().then(()=>{this._hostedForm=t})}deinitialize(){this._hostedForm&&this._hostedForm.detach()}}function LI(e){const t=m_();return new FI(e,new Iy(t))}!function(e){e.CUSTOMER="customer",e.SHIPPING="shipping",e.BILLING="billing",e.PAYMENT="payment"}(RI||(RI={}));const BI=[RI.CUSTOMER,RI.SHIPPING,RI.BILLING,RI.PAYMENT];class jI{constructor(e,t){this.subscribe=e,this.bodlEvents=t,this._checkoutStarted=!1,this._emailEntryBegan=!1,this._shippingOptionsShown=!1,this._completedSteps={},this.subscribe(e=>{var t;if(this.setState(e.data),!(null===(t=this.state)||void 0===t?void 0:t.getConfig()))throw new rt(et.MissingCheckoutConfig)})}setState(e){this.state=e}checkoutBegin(){const e=this._getCommonCheckoutData();!this._checkoutStarted&&e&&(this.bodlEvents.emitCheckoutBeginEvent(e),this._checkoutStarted=!0)}orderPurchased(){var e;const t=null===(e=this.state)||void 0===e?void 0:e.getOrder();if(!t)return;const{currency:n,isComplete:i,orderId:r,orderAmount:o,shippingCostTotal:a,lineItems:s,cartId:d,coupons:c,channelId:l,taxTotal:u}=t;i&&this.bodlEvents.emitOrderPurchasedEvent({event_id:d,currency:n.code,order_id:r,tax:u,channel_id:l,cart_value:o,coupon_codes:c.map(e=>e.code.toUpperCase()),shipping_cost:a,line_items:this._getProducts(s,n.code)})}stepCompleted(e){e&&BI.some(t=>(this._hasStepCompleted(t)||this._trackCompletedStep(t),t===e))}customerEmailEntry(e){!this._emailEntryBegan&&(null==e?void 0:e.length)&&(this._emailEntryBegan=!0,this.bodlEvents.emit("bodl_checkout_email_entry_began"))}customerSuggestionInit(e){this.bodlEvents.emit("bodl_checkout_customer_suggestion_initialization",e)}customerSuggestionExecute(){this.bodlEvents.emit("bodl_checkout_customer_suggestion_execute")}customerPaymentMethodExecuted(e){this.bodlEvents.emit("bodl_checkout_customer_payment_method_executed",e)}showShippingMethods(){this._shippingOptionsShown||(this._shippingOptionsShown=!0,this.bodlEvents.emit("bodl_checkout_show_shipping_options"))}selectedPaymentMethod(e){const t=this._getCommonCheckoutData();t&&e&&this.bodlEvents.emitPaymentDetailsProvidedEvent(Object.assign(Object.assign({},t),{payment_type:e}))}clickPayButton(e){this.bodlEvents.emit("bodl_checkout_click_pay_button",e)}paymentRejected(){this.bodlEvents.emit("bodl_checkout_payment_rejected")}paymentComplete(){this.bodlEvents.emit("bodl_checkout_payment_complete")}exitCheckout(){this.bodlEvents.emit("bodl_checkout_exit")}_trackCompletedStep(e){this._completedSteps[e]=!0;const t={[RI.SHIPPING]:this._trackShippingStepCompleted.bind(this)}[e];t?t():this.bodlEvents.emit("bodl_checkout_step_completed",{step:e})}_trackShippingStepCompleted(){var e,t;const n=null===(t=null===(e=this.state)||void 0===e?void 0:e.getSelectedShippingOption())||void 0===t?void 0:t.description,i=this._getCommonCheckoutData();i&&n&&this.bodlEvents.emitShippingDetailsProvidedEvent(Object.assign(Object.assign({},i),{shipping_method:n}))}_getCommonCheckoutData(){var e;const t=null===(e=this.state)||void 0===e?void 0:e.getCheckout();if(!t)return null;const{cart:{cartAmount:n,currency:i,lineItems:r,id:o,coupons:a},channelId:s}=t;return{event_id:o,currency:i.code,cart_value:n,coupon_codes:a.map(e=>e.code.toUpperCase()),line_items:this._getProducts(r,i.code),channel_id:s}}_getProducts(e,t){const n=(e.customItems||[]).map(e=>({product_id:e.id,sku:e.sku,base_price:e.listPrice,sale_price:e.listPrice,purchase_price:e.listPrice,quantity:e.quantity,product_name:e.name,currency:t})),i=e.giftCertificates.map(e=>({product_id:e.id,gift_certificate_id:e.id,base_price:e.amount,sale_price:e.amount,purchase_price:e.amount,product_name:e.name,gift_certificate_name:e.name,gift_certificate_theme:e.theme,quantity:1,currency:t}));return[...n,...[...e.physicalItems,...e.digitalItems].map(e=>{let n;return e.options&&e.options.length&&(n=e.options.map(e=>`${e.name}:${e.value}`),n.sort()),{product_id:e.productId,quantity:e.quantity,product_name:e.name,base_price:e.listPrice,sale_price:e.salePrice,purchase_price:e.salePrice>0?e.salePrice:e.listPrice,sku:e.sku,variant_id:e.variantId,discount:e.discountAmount,coupon_amount:e.couponAmount,brand_name:e.brand,currency:t,category_names:(i=e,Array.isArray(i.categoryNames)?i.categoryNames:Array.isArray(i.categories)?q(i.categories).map(({name:e})=>e):[]),retail_price:e.retailPrice};var i}),...i].map(e=>Object.assign(Object.assign({},e),{product_id:String(e.product_id)}))}_hasStepCompleted(e){return this._completedSteps[e]}}class UI{checkoutBegin(){}orderPurchased(){}stepCompleted(){}customerEmailEntry(){}customerSuggestionInit(){}customerSuggestionExecute(){}customerPaymentMethodExecuted(){}showShippingMethods(){}selectedPaymentMethod(){}clickPayButton(){}paymentRejected(){}paymentComplete(){}exitCheckout(){}}function qI(e){return function(e){return"bodlEvents"in e}(window)?new jI(e,window.bodlEvents.checkout):new UI}export{Bn as ExtensionCommandType,jn as ExtensionQueryType,qI as createBodlService,zI as createBraintreeAnalyticTracker,Qw as createCheckoutButtonInitializer,y_ as createCheckoutService,wI as createCurrencyService,pI as createEmbeddedCheckoutMessenger,fI as createLanguageService,xI as createPayPalCommerceAnalyticTracker,kI as createStepTracker,LI as createStoredCardHostedFormService,i as createTimeout,aI as embedCheckout,Ye as isExtraField}; //# sourceMappingURL=checkout-sdk.js.map \ No newline at end of file diff --git a/dist/esm/checkout-sdk.js.map b/dist/esm/checkout-sdk.js.map index cb7984bfff..3d376e8bd9 100644 --- a/dist/esm/checkout-sdk.js.map +++ b/dist/esm/checkout-sdk.js.map @@ -1 +1 @@ -{"version":3,"file":"checkout-sdk.js","mappings":"k+DAAA,IAAAA,EACAC,EAGAC,EAAAC,SAJAH,EAIA,CAAqBI,cAAA,IAAAC,EAAA,eAHrBJ,EAAA,GAAaK,EAAAC,EAAAN,EAAAD,GAA6BC,WCD1CC,EAAAC,QAAAK,ICCAC,GAAA,GAGA,SAAAH,GAAAI,GAEA,IAAAC,EAAAF,GAAAC,GACA,QAAAE,IAAAD,EACA,OAAAA,EAAAR,QAGA,IAAAD,EAAAO,GAAAC,GAAA,CAGAP,QAAA,IAOA,OAHAU,GAAAH,GAAAR,EAAAA,EAAAC,QAAAG,IAGAJ,EAAAC,OACA,CCrBAG,GAAAC,EAAA,CAAAJ,EAAAW,KACA,QAAAC,KAAAD,EACAR,GAAAU,EAAAF,EAAAC,KAAAT,GAAAU,EAAAb,EAAAY,IACAE,OAAAC,eAAAf,EAAAY,EAAA,CAAyCI,YAAA,EAAAC,IAAAN,EAAAC,MCJzCT,GAAAU,EAAA,CAAAK,EAAAC,IAAAL,OAAAM,UAAAC,eAAAC,KAAAJ,EAAAC,GCCAhB,GAAAoB,EAAAvB,IACA,oBAAAwB,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D,MAAMy1B,EAAgB1F,IAEhBjK,EAA2C7e,OAC3C8e,EAA6B,IAAI1F,GAA2BrgB,GAC5Di0C,EAAe,IAAIvyB,GACrB,IAAImE,GACA7G,IACA8G,EACAC,IAIR,OAAO,IAAIm6B,GACPlgD,EACA,IAAI4hD,GACA8C,KACA,IAAIwG,GAA0BlrD,EAA2Bi0C,GACzDxe,EACAyC,QAK+D,CACvE,CAAE1uC,GAAI,wBC/CG0iE,GAA2B,CACpC,mBAAoB,qBACpB,UAAW,QAOFC,GAA+B,CACxC,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,SC3mBW,SAASC,GACpBxX,GAEA,IAAKA,EACD,OAGJ,IAAID,EAEJ,GAAIC,EAAcj8C,SAAS,KAAM,CAC7B,MAAO0zD,EAAUj7C,GAAUwjC,EAAcngB,MAAM,KAE/CkgB,EAAS,GAAG0X,KAAYj7C,EAAOk7C,qBAE/B3X,EAAS,GAAGC,KAAiBA,EAAc0X,gBAG/C,OAAOH,GAA6BxzD,SAASg8C,GAAUA,OAAS3tD,CACpE,wSCPe,MAAMulE,GAGjB,WAAAxhE,CAAoBsf,GAAApf,KAAAof,aAAAA,EAChBpf,KAAKgc,OAASA,MAClB,CAEM,oBAAA2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,QAAb9uE,EAAA2c,SAAS4zD,YAAI,IAAAvwE,GAAAA,EAAEid,YAAYmD,GAEvBA,EAAMowD,iBAAiBC,eAGvBrwD,EAAMowD,MAAME,WACR,gCACa5B,wLAKb,EAGZ,EChJW,MAAM6B,GACjB,WAAA7uE,CAAoB0rD,GAAAxrD,KAAAwrD,eAAAA,CAAyB,CAE7C,SAAAojB,CAAU77C,GACN,OAAOpB,KAAKg7B,MAAM55B,EAASpB,KAAAk9C,IAAA,GAAM7uE,KAAKwrD,gBAC1C,ECLG,MAAMsjB,GAAqC,CAC9C,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA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WjvL,UAGxD,IAAIkyL,EACf","sources":["webpack://@bigcommerce/checkout-sdk/external module \"iframe-resizer\"","webpack://@bigcommerce/checkout-sdk/external module \"iframe-resizer/js/iframeResizer.contentWindow\"","webpack://@bigcommerce/checkout-sdk/webpack/bootstrap","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/./packages/core/src/form/map-extra-field-to-form-field.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/throw-error-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/b2b-token/b2b-token-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/b2b-token/b2b-token-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/sdk-version-headers.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/b2b-token/b2b-token-request-sender.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/billing/errors/unable-to-continue-as-guest-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/content-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/empty-cart-error.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/http-request/experiment-aware-request-sender.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/./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-actions.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/coupon/gift-certificate-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/cart/cart-source.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-actions.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-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/core/src/spam-protection/is-spam-protection-succeeded-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-hydrate-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/payment-integration/register-integrations.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/form/form-fields-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/spam-protection-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/spam-protection/errors/spam-protection-challenge-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-failed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/not-initialized-error.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/spam-protection/spam-protection-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/mutation-observer.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/spam-protection/spam-protection-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/default/default-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/parse-url.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/extension-not-found-error.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/extension/create-extension-event-poster.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/cancellable-promise/cancellable-promise.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/errors/unexpected-detachment-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-internal-commands.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/detachment-observer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-resizer.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-iframe.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/create-extension-web-worker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/bind-decorator/bind-decorator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-commands.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-queries.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/worker/worker-event-listener.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/worker/worker-event-poster.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/unsupported-extension-command-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/unsupported-extension-query-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/worker-extension-messenger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/append-www.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-listener.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-messenger.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/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/missing-data-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/not-initialized-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/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/invalid-argument-error.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/utility/src/is-experiment-enabled/is-experiment-enabled.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk-verison.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk-version-manager.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.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk-scripts-integrity.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/isManageableBraintreeSDKVersion.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-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-session-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/is-apple-pay-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/is-apple-pay-sdk-window.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/buy-now-cart-creation-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/internal-api-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/content-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/sdk-version-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/create-bigcommerce-payments-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/checkout-buttons/default-checkout-button-height.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/bigcommerce-payments-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/create-bigcommerce-payments-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/bigcommerce-payments-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/paypal-sdk-helper.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/create-bigcommerce-payments-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/storage/src/cookie-storage.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/bigcommerce-payments-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/create-bigcommerce-payments-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/get-fastlane-styles.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-fastlane/bigcommerce-payments-fastlane-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-fastlane/create-bigcommerce-payments-fastlane-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/bigcommerce-payments-paylater-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/create-bigcommerce-payments-paylater-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/bigcommerce-payments-venmo-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/create-bigcommerce-payments-venmo-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/payment-method-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt.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-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/create-bolt-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-argument-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-invalid-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/load-paypal-sdk-once.ts","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/braintree-utils/src/utils/is-credit-card-instrument-like.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/./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/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/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/utility/src/is-web-view/is-web-view.ts","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/is-react-native-window/is-react-native-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/is-opera-window/is-opera-window.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/google-pay-payment-initialize-options.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/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/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/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/stripe-utils/src/stripe.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/stripe-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/stripe-upe/stripe-upe-constants.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/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/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/paypal-utils/src/paypal-commerce-constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/utils/transform-locale-to-paypal-format.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/paypal-commerce-sdk.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-gateway.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/google-pay-integration/src/google-pay-bigcommerce-payments/google-pay-bigcommerce-payments-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-bigcommerce-payments/create-google-pay-bigcommerce-payments-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/paypal-utils/src/paypal-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/paypal-sdk-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/create-paypal-sdk-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/paypal-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/paypal-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/create-paypal-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/paypal-button-creation-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-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-integration-service.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-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-utils/src/paypal-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/create-paypal-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-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-utils/src/is-stripe-payment-method-like.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/stripe-upe-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/create-stripe-upe-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/stripe-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/is-stripe-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/ui/src/loading-indicator/loading-indicator.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/utility/amount-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/stripe-link-v2-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/create-stripe-link-v2-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/order-finalization-not-required-error.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/adyen-utils/src/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-utils/src/adyenv2/adyenv2-script-loader.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/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.ts","webpack://@bigcommerce/checkout-sdk/./packages/affirm-integration/src/affirm-payment-strategy.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/bigcommerce-payments-integration/src/bigcommerce-payments-constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/get-paypal-messages-styles-from-bnpl-config.ts","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/is-base-instrument/is-base-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/bigcommerce-payments-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-bigcommerce-payments-provider-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/create-bigcommerce-payments-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-paypal-fastlane-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-fastlane/bigcommerce-payments-fastlane-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-bigcommerce-fastlane-request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-fastlane/create-bigcommerce-payments-fastlane-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/bigcommerce-payments-paylater-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/create-bigcommerce-payments-paylater-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/timeout-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-ratepay/bigcommerce-payments-ratepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-ratepay/create-bigcommerce-payments-ratepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/hosted-form/hosted-field-type.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/bigcommerce-payments-integration/src/bigcommerce-payments-credit-cards/bigcommerce-payments-credit-cards-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-bigcommerce-payments-fastlane-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-credit-cards/create-bigcommerce-payments-credit-cards-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-alternative-methods/bigcommerce-payments-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-alternative-methods/create-bigcommerce-payments-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-redirect-alternative-methods/bigcomemrce-payments-redirect-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-redirect-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-redirect-alternative-methods/create-bigcommerce-payments-redirect-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/bigcommerce-payments-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/create-bigcommerce-payments-venmo-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/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/types.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/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/braintree-utils/src/braintree-messages.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/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-request-sender.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/braintree-integration/src/braintree-visa-checkout/braintree-visa-checkout-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-visa-checkout/create-braintree-visa-checkout-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-venmo/braintree-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-venmo/create-braintree-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-credit-card/braintree-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-payment-request-3ds-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-form-fields-map.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-hosted-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-hosted-form/braintree-hosted-form.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-supported-card-brand.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-credit-card/create-braintree-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/credit-card-integration/src/credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/cba-mpgs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/is-cba-mpgs-payment-method-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/cba-mpgs.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/cba-mpgs-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/create-cba-mpgs-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/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/google-pay-bigcommerce-payments/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-bigcommerce-payments/google-pay-bigcommerce-payments-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-bigcommerce-payments/create-google-pay-bigcommerce-payments-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/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-utils/src/utils/get-paypal-messages-styles-from-bnpl-config.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/paypal-commerce-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/utils/is-redirect-action-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/utils/is-paypal-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-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-constants.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/paypal-commerce-integration/src/paypal-commerce-credit-card/paypal-commerce-credit-cards-payment-strategy.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/create-paypal-commerce-credit-cards-payment-strategy.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-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-utils/src/utils/is-paypal-fastlane-request-error.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-express-integration/src/paypal-express-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/paypal-express-payment-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-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/external-integration/src/external-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/external-integration/src/is-additional-action.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-utils/src/stripe-supported-locales.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/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-utils/src/is-stripe-payment-event.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/stripe-ocs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/create-stripe-ocs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-cs/stripe-cs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-cs/create-stripe-cs-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/worldpayaccess-integration/src/worldpayaccess-open-banking-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/worldpayaccess-integration/src/create-worldpayaccess-open-banking-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/order/order-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/cart/errors/cart-consistency-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/cart-stock-positions-changed-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/errors/missing-shipping-method-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/errors/invalid-shipping-address-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/create-payment-client.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-request-sender.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-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-widget-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-action-creator.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/storage/browser-storage.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/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/spam-protection/payment-human-verification-handler.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.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-actions.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/payment/payment-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-request-sender.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/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/promotion/map-to-discount-notifications.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/generated/checkout-button-method-type.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/./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/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/payment-status-types.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/converge/converge-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-method-cancelled-error.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/redirect/redirect.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/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-sub-strategy-type.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-provider-customer/payment-provider-customer-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-payment-resumer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-provider-customer/payment-provider-customer-actions-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-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-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/store-credit/store-credit-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/subscription/subscriptions-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/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/instrument/instrument-actions.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/payment/instrument/instrument-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/date-time/add-minutes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/date-time/is-future.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-actions.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-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-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument.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/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/paypal-utils/src/utils/is-paypal-accelerated-checkout-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-actions.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-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/./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/./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/object-set.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/b2b-token/b2b-token-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/b2b-token/b2b-token-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/replace.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/cart/cart-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-actions.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/b2b-token/b2b-token-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-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/coupon/coupon-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-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/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/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/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/store-credit/store-credit-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-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/checkout/create-action-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/create-request-error-factory.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/payment/create-payment-strategy-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/create-customer-strategy-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-selectors.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/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/ppsdk/create-ppsdk-sub-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/create-shipping-strategy-registry.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/bigcommerce-payments-integration/src/bigcommerce-payments/bigcommerce-payments-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/create-bigcommerce-payments-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/bigcommerce-payments-paylater-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/create-bigcommerce-payments-paylater-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/bigcommerce-payments-venmo-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/create-bigcommerce-payments-venmo-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/get-valid-button-style.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/braintree-paypal-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/create-braintree-paypal-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal-credit/braintree-paypal-credit-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal-credit/create-braintree-paypal-credit-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/google-pay-bigcommerce-payments/create-google-pay-bigcommerce-payments-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-express-integration/src/paypal-express-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/create-paypal-express-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/stripe-link-v2-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/create-stripe-link-v2-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/set-unique-element-id.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/checkout-buttons/checkout-button-strategy-action-creator.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/paypal/paypal-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/embedded-checkout-events.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/payment/strategies/paypal/paypal-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/paypal/paypal-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/errors/invalid-login-token-error.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/./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/bodl/analytics-steps.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/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":["var x = (y) => {\n\tvar x = {}; __webpack_require__.d(x, y); return x\n} \nvar y = (x) => (() => (x))\nmodule.exports = x({ [\"iframeResizer\"]: () => (__WEBPACK_EXTERNAL_MODULE_iframe_resizer_1512d797__.iframeResizer) });","module.exports = __WEBPACK_EXTERNAL_MODULE_iframe_resizer_js_iframeResizer_contentWindow_a6cfc03f__;","// 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","// 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};","import { ExtraField, ExtraFieldType } from './extra-field';\nimport FormField, { FormFieldFieldType, FormFieldType } from './form-field';\n\nexport const B2B_EXTRA_FIELD_PREFIX = 'b2bExtraField_';\n\nexport function isExtraField(field: FormField): boolean {\n return field.name.startsWith(B2B_EXTRA_FIELD_PREFIX);\n}\n\nexport default function mapExtraFieldToFormField(extraField: ExtraField): FormField {\n const { fieldType, type } = getFieldTypeInfo(extraField.type);\n\n let options: FormField['options'];\n\n if (extraField.config.numberOfRows) {\n options = { rows: extraField.config.numberOfRows };\n }\n\n if (extraField.config.options?.length) {\n options = {\n ...options,\n items: extraField.config.options.map((val) => ({\n value: val,\n label: val,\n })),\n };\n }\n\n return {\n id: `${B2B_EXTRA_FIELD_PREFIX}${extraField.id}`,\n name: `${B2B_EXTRA_FIELD_PREFIX}${extraField.id}`,\n custom: false,\n label: extraField.name,\n hidden: !extraField.visibleToStorefront,\n required: extraField.isRequired,\n default:\n extraField.config.defaultValue != null\n ? String(extraField.config.defaultValue)\n : undefined,\n fieldType,\n type,\n maxLength: extraField.config.maxLength,\n max: extraField.config.maxValue,\n options,\n };\n}\n\nfunction getFieldTypeInfo(extraFieldType: ExtraFieldType): {\n fieldType: FormFieldFieldType;\n type: FormFieldType;\n} {\n switch (extraFieldType) {\n case 'multiline_text':\n return { fieldType: 'multiline', type: 'string' };\n\n case 'number':\n return { fieldType: 'text', type: 'integer' };\n\n case 'dropdown':\n return { fieldType: 'dropdown', type: 'array' };\n\n case 'text':\n default:\n return { fieldType: 'text', type: 'string' };\n }\n}\n","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 { Action } from '@bigcommerce/data-store';\n\nimport { B2BToken } from './b2b-token-state';\n\nexport enum B2BTokenActionType {\n LoadB2BTokenRequested = 'LOAD_B2B_TOKEN_REQUESTED',\n LoadB2BTokenSucceeded = 'LOAD_B2B_TOKEN_SUCCEEDED',\n LoadB2BTokenFailed = 'LOAD_B2B_TOKEN_FAILED',\n}\n\nexport type LoadB2BTokenAction =\n | LoadB2BTokenRequestedAction\n | LoadB2BTokenSucceededAction\n | LoadB2BTokenFailedAction;\n\nexport interface LoadB2BTokenRequestedAction extends Action {\n type: B2BTokenActionType.LoadB2BTokenRequested;\n}\n\nexport interface LoadB2BTokenSucceededAction extends Action {\n type: B2BTokenActionType.LoadB2BTokenSucceeded;\n}\n\nexport interface LoadB2BTokenFailedAction extends Action {\n type: B2BTokenActionType.LoadB2BTokenFailed;\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 { RequestOptions } from '../common/http-request';\n\nimport { B2BTokenActionType, LoadB2BTokenAction } from './b2b-token-actions';\nimport B2BTokenRequestSender from './b2b-token-request-sender';\n\nexport default class B2BTokenActionCreator {\n constructor(private _requestSender: B2BTokenRequestSender) {}\n\n loadB2BToken(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const storeConfig = state.config.getStoreConfigOrThrow();\n const { storeHash } = storeConfig.storeProfile;\n const { baseUrl: b2bBaseUrl = '', clientId: b2bClientId = '' } =\n storeConfig.b2bApiSettings ?? {};\n const { id: customerId } = state.customer.getCustomerOrThrow();\n const { channelId } = state.checkout.getCheckoutOrThrow();\n\n return concat(\n of(createAction(B2BTokenActionType.LoadB2BTokenRequested)),\n defer(async () => {\n const { body } = await this._requestSender.getB2BToken(\n b2bClientId,\n customerId,\n storeHash,\n channelId,\n b2bBaseUrl,\n options,\n );\n\n return createAction(B2BTokenActionType.LoadB2BTokenSucceeded, {\n token: body.data.token,\n });\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(B2BTokenActionType.LoadB2BTokenFailed, error),\n ),\n );\n };\n }\n}\n","export const SDK_VERSION_HEADERS = { 'X-Checkout-SDK-Version': LIBRARY_VERSION };\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 { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nexport interface B2BTokenResponseBody {\n code: number;\n data: {\n token: string;\n };\n}\n\nexport default class B2BTokenRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n async getB2BToken(\n appClientId: string,\n customerId: number,\n storeHash: string,\n channelId: number,\n b2bBaseUrl: string,\n options?: RequestOptions,\n ): Promise> {\n const { body: jwtBody } = await this._requestSender.get<{ token: string }>(\n '/customer/current.jwt',\n {\n timeout: options?.timeout,\n params: { app_client_id: appClientId },\n headers: SDK_VERSION_HEADERS,\n },\n );\n\n return this._requestSender.post(`${b2bBaseUrl}/api/v2/login`, {\n timeout: options?.timeout,\n credentials: false,\n headers: { 'Content-Type': 'application/json' },\n body: {\n bcToken: jwtBody.token,\n customerId,\n storeHash,\n channelId,\n },\n });\n }\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 '../../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","enum ContentType {\n Json = 'application/json',\n JsonV1 = 'application/vnd.bc.v1+json',\n}\n\nexport default ContentType;\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\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 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\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 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 hasBillingAddress: boolean,\n options?: RequestOptions,\n ): Promise> {\n if (!hasBillingAddress) {\n return this._requestSender.createAddress(checkoutId, address, options);\n }\n\n return this._requestSender.updateAddress(checkoutId, address, options);\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error is thrown when cart is removed or empty.\n */\nexport default class EmptyCartError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Your checkout could not be processed because your cart is empty. Please add items to your cart and try again.',\n );\n\n this.name = 'EmptyCartError';\n this.type = 'empty_cart';\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { AddressRequestBody } from '../address';\nimport { EmptyCartError } from '../cart/errors';\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.physicalItems.stockPosition',\n 'cart.lineItems.digitalItems.options',\n 'cart.lineItems.digitalItems.stockPosition',\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\n .post(url, {\n body: address,\n params: DEFAULT_PARAMS,\n headers,\n timeout,\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .put(url, { params: DEFAULT_PARAMS, body, headers, timeout })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\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","import { RequestOptions, RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { StoreConfig } from '../../config';\n\nexport interface ExperimentConfig {\n getBasePath: () => string | undefined;\n getFeatures: () => StoreConfig['checkoutSettings']['features'];\n}\n\nexport default class ExperimentAwareRequestSender {\n constructor(private _requestSender: RequestSender, private _config: ExperimentConfig) {}\n\n sendRequest(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.sendRequest(url, options);\n }\n\n get(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.get(url, options);\n }\n\n post(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.post(this._prefixed(url), options);\n }\n\n put(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.put(this._prefixed(url), options);\n }\n\n patch(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.patch(this._prefixed(url), options);\n }\n\n delete(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.delete(this._prefixed(url), options);\n }\n\n private _prefixed(url: string): string {\n const basePath = this._config.getBasePath();\n\n const isExperimentEnabled =\n this._config.getFeatures()['CHECKOUT-9950.update_sf_checkout_url_for_subfolder'];\n\n if (\n !isExperimentEnabled ||\n !basePath ||\n basePath.endsWith('/checkout') ||\n /^https?:\\/\\//.test(url)\n ) {\n return url;\n }\n\n return `${basePath}${url}`;\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","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 { 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 { 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 | object;\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.physicalItems.stockPosition',\n 'cart.lineItems.digitalItems.options',\n 'cart.lineItems.digitalItems.stockPosition',\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 { 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","export enum CartSource {\n BuyNow = 'BUY_NOW',\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 { 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 { EmptyCartError } from '../cart/errors';\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\n .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 .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes([\n ...CHECKOUT_DEFAULT_INCLUDES,\n CheckoutIncludes.AvailableShippingOptions,\n ]),\n },\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\n }\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 { EmptyCartError } from '../cart/errors';\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\n .post(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n body: { giftCertificateCode },\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\n }\n}\n","import ResolvableModule from './resolvable-module';\n\nexport default function isResolvableModule(\n module: TModule,\n): module is ResolvableModule {\n return module && '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: (\n token: string,\n registeredTokens: string[],\n exactMatch?: boolean,\n ) => 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 getFactory(token: string, exactMatch?: boolean): Factory | undefined {\n const resolvedToken = this._tokenResolver(token, Object.keys(this._factories), exactMatch);\n const factory = resolvedToken ? this._factories[resolvedToken] : undefined;\n\n return factory;\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 factory = this.getFactory(token);\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 defaultToken: this._encodeToken({ default: true } as unknown as TToken),\n useFallback: this._useFallback,\n });\n }\n\n get(resolveId: TToken): TType {\n return this._registry.get(this._encodeToken(resolveId));\n }\n\n getFactory(resolveId: TToken, exactMatch?: boolean): Factory | undefined {\n try {\n return this._registry.getFactory(this._encodeToken(resolveId), exactMatch);\n } catch (error) {\n return undefined;\n }\n }\n\n getUseFallback(): boolean {\n return this._useFallback;\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(\n token: string,\n registeredTokens: string[],\n exactMatch?: boolean,\n ): string | undefined {\n const query = this._decodeToken(token);\n\n const results: Array<{\n token: string;\n matches: number;\n default: boolean;\n totalKeys: number;\n }> = [];\n\n registeredTokens.forEach((registeredToken) => {\n const resolverId = this._decodeToken(registeredToken);\n\n const result = {\n token: registeredToken,\n matches: 0,\n default: false,\n totalKeys: Object.keys(resolverId).length,\n };\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 queryKeyCount = Object.keys(query).length;\n\n if (exactMatch) {\n const exactResult = matchedResults.find(\n (result) => result.matches === queryKeyCount && result.matches === result.totalKeys,\n );\n\n if (!exactResult) {\n throw new Error(\n `Unable to resolve to a registered token with the provided token for ${JSON.stringify(\n query,\n )} with exact match.`,\n );\n }\n\n return exactResult.token;\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(\n `Unable to resolve to a registered token with the provided token for ${JSON.stringify(\n query,\n )}.`,\n );\n }\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\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 { 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 { Action } from '@bigcommerce/data-store';\n\nimport CheckoutInitialState from './checkout-initial-state';\n\nexport enum CheckoutHydrateActionType {\n HydrateInitialState = 'HYDRATE_INITIAL_STATE',\n}\n\nexport interface CheckoutHydrateAction extends Action {\n type: CheckoutHydrateActionType.HydrateInitialState;\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 { CartSource } from '@bigcommerce/checkout-sdk/payment-integration-api';\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 const checkout = store.getState().checkout.getCheckoutOrThrow();\n const cartId = checkout.cart.source === CartSource.BuyNow ? checkout.id : undefined;\n\n return concat(\n of(createAction(CustomerActionType.SignInCustomerRequested)),\n from(\n this._customerRequestSender.signInCustomer({ ...credentials, cartId }, options),\n ).pipe(\n switchMap(({ body }) => {\n if (body.data.persistentCartRetrievalInformation) {\n return concat(\n this._checkoutActionCreator.loadCheckout(\n body.data.persistentCartRetrievalInformation.id,\n options,\n )(store),\n of(\n createAction(\n CustomerActionType.SignInCustomerSucceeded,\n body.data,\n ),\n ),\n );\n }\n\n return 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\n signOutCustomer(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const checkout = store.getState().checkout.getCheckoutOrThrow();\n const cartId = checkout.cart.source === CartSource.BuyNow ? checkout.id : undefined;\n\n return concat(\n of(createAction(CustomerActionType.SignOutCustomerRequested)),\n from(this._customerRequestSender.signOutCustomer(options, cartId)).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}\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(\n { timeout }: RequestOptions = {},\n cartId?: string,\n ): Promise> {\n const url = '/internalapi/v1/checkout/customer';\n\n return this._requestSender.delete(url, {\n timeout,\n headers: SDK_VERSION_HEADERS,\n ...(cartId && { body: { cartId } }),\n });\n }\n}\n","import {\n isResolvableModule,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\n\nexport type StrategyFactory = (\n paymentIntegrationService: PaymentIntegrationService,\n) => TStrategy;\n\nexport function registerIntegrations(\n registry: ResolveIdRegistry,\n integrations: Array>,\n paymentIntegrationService: PaymentIntegrationService,\n): void {\n integrations.forEach((factory) => {\n if (!isResolvableModule, TResolveId>(factory)) {\n return;\n }\n\n factory.resolveIds.forEach((resolveId) => {\n if (registry.getFactory(resolveId, true)) {\n return;\n }\n\n registry.register(resolveId, () => factory(paymentIntegrationService));\n });\n });\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport {\n CustomerStrategy as CustomerStrategyV2,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { registerIntegrations } from '../payment-integration';\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 private _paymentIntegrationService: PaymentIntegrationService,\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 registerIntegrations(\n this._strategyRegistryV2,\n options?.integrations ?? [],\n this._paymentIntegrationService,\n );\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 { EmptyCartError } from '../cart/errors';\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\n .put(url, {\n params: {\n include: joinOrMergeIncludes(CHECKOUT_DEFAULT_INCLUDES, include),\n },\n body,\n headers,\n timeout,\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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 { Action, 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 } from '../config';\nimport { FormFieldsActionCreator } from '../form';\n\nimport Checkout, { CheckoutRequestBody } from './checkout';\nimport { CheckoutActionType, LoadCheckoutAction, UpdateCheckoutAction } from './checkout-actions';\nimport { CheckoutHydrateActionType } from './checkout-hydrate-actions';\nimport CheckoutInitialState from './checkout-initial-state';\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 () => {\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._transformCustomerAddresses(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._transformCustomerAddresses(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 hydrateInitialState(state: CheckoutInitialState): Action {\n return {\n type: CheckoutHydrateActionType.HydrateInitialState,\n payload: state,\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 { 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 } 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 { 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 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 './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 { 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 { 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 return concat(\n of(createAction(SpamProtectionActionType.InitializeRequested, undefined)),\n defer(async () => {\n const spamProtectionElementId = options\n ? options.containerId\n : 'spamProtectionContainer';\n\n const element = document.getElementById(spamProtectionElementId);\n\n if (element) {\n this._googleRecaptcha.reset(spamProtectionElementId);\n }\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\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","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 { 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\n .load()\n .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 .catch((err) => {\n throw err;\n });\n }\n\n reset(containerId: string): void {\n const element = document.getElementById(containerId);\n\n element?.remove();\n this._recaptcha?.reset(this._widgetId);\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 { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { EmptyCartError } from '../cart/errors';\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\n .post(url, { body: { token }, headers, timeout })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\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","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 { 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 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 { 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","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 { 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 { 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 { 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","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 { 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","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 { createExtensionWebWorker } from './create-extension-web-worker';\nimport { ExtensionNotFoundError } from './errors';\nimport { ExtensionRegion, ExtensionType } from './extension';\nimport { ExtensionAction, ExtensionActionType } from './extension-actions';\nimport { ExtensionIframe } from './extension-iframe';\nimport { ExtensionRequestSender } from './extension-request-sender';\nimport { WorkerExtensionMessenger } from './worker-extension-messenger';\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 workerExtensionMessenger: WorkerExtensionMessenger,\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 } = state.config.getStoreConfigOrThrow();\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 if (extension.type === ExtensionType.Worker) {\n const worker = createExtensionWebWorker(extension.url);\n\n workerExtensionMessenger.add(extension.id, worker);\n } else {\n const iframe = new ExtensionIframe(container, extension, {\n cartId,\n parentOrigin: parseUrl(checkoutLink).origin,\n });\n\n await iframe.attach();\n }\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","export function createExtensionWebWorker(url: string): Worker {\n if (!window.Worker) {\n throw new Error(\n `Unable to load the extension's web worker: your browser does not support Web Workers.`,\n );\n }\n\n try {\n const blob = URL.createObjectURL(\n new Blob(\n [\n `importScripts=((i)=>(...a)=>i(...a.map((u)=>''+new URL(u,\"${url}\"))))(importScripts);importScripts(\"${url}\")`,\n ],\n { type: 'text/javascript' },\n ),\n );\n\n return new Worker(blob);\n } catch (error) {\n throw new Error(`Unable to load the extension's web worker`);\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","/**\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","export type ExtensionCommand =\n | ReloadCheckoutCommand\n | ShowLoadingIndicatorCommand\n | SetIframeStyleCommand\n | ReRenderShippingForm\n | ReRenderShippingStep;\n\nexport enum ExtensionCommandType {\n ReloadCheckout = 'EXTENSION:RELOAD_CHECKOUT',\n ShowLoadingIndicator = 'EXTENSION:SHOW_LOADING_INDICATOR',\n SetIframeStyle = 'EXTENSION:SET_IFRAME_STYLE',\n ReRenderShippingForm = 'EXTENSION:RE_RENDER_SHIPPING_FORM',\n ReRenderShippingStep = 'EXTENSION:RE_RENDER_SHIPPING_STEP',\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 ReRenderShippingForm {\n type: ExtensionCommandType.ReRenderShippingForm;\n}\n\nexport interface ReRenderShippingStep {\n type: ExtensionCommandType.ReRenderShippingStep;\n}\nexport interface ExtensionCommandMap {\n [ExtensionCommandType.ReloadCheckout]: ReloadCheckoutCommand;\n [ExtensionCommandType.ShowLoadingIndicator]: ShowLoadingIndicatorCommand;\n [ExtensionCommandType.SetIframeStyle]: SetIframeStyleCommand;\n [ExtensionCommandType.ReRenderShippingForm]: ReRenderShippingForm;\n [ExtensionCommandType.ReRenderShippingStep]: ReRenderShippingStep;\n}\n","export type ExtensionQuery = GetConsignmentsQuery;\n\nexport enum ExtensionQueryType {\n GetConsignments = 'EXTENSION:GET_CONSIGNMENTS',\n}\n\nexport interface GetConsignmentsQuery {\n type: ExtensionQueryType.GetConsignments;\n payload?: {\n useCache?: boolean;\n };\n}\n\nexport interface ExtensionQueryMap {\n [ExtensionQueryType.GetConsignments]: GetConsignmentsQuery;\n}\n","import { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { WorkerEventListeners, WorkerEventMap } from './WorkerEvent';\n\nexport class WorkerEventListener<\n TEventMap extends WorkerEventMap,\n TContext = undefined,\n> {\n private _isListening: boolean;\n private _listeners: WorkerEventListeners;\n\n constructor(private _worker: Worker) {\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 this._worker.addEventListener('message', this._handleMessage);\n }\n\n stopListen(): void {\n if (!this._isListening) {\n return;\n }\n\n this._isListening = false;\n this._worker.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 const { context, ...event } = messageEvent.data;\n\n this.trigger(event, context);\n }\n}\n","export class WorkerEventPoster {\n constructor(private _worker: Worker, private _context: TContext) {}\n\n post(event: TEvent): void {\n if (!this._worker) {\n throw new Error(\n 'WorkerPoster: Worker is not initialized or creation failed. Cannot post message.',\n );\n }\n\n this._worker.postMessage({ ...event, context: this._context });\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 { StandardError } from '../../common/error/errors';\n\nexport class UnsupportedExtensionQueryError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unable to proceed due to unsupported extension query.');\n\n this.name = 'UnsupportedExtensionQueryError';\n this.type = 'unsupported_extension_query_error';\n }\n}\n","import { WorkerEventListener, WorkerEventPoster } from '../common/worker';\n\nimport {\n ExtensionNotFoundError,\n UnsupportedExtensionCommandError,\n UnsupportedExtensionQueryError,\n} from './errors';\nimport { ExtensionCommandMap, ExtensionCommandType } from './extension-commands';\nimport { ExtensionCommandOrQueryContext, ExtensionMessage } from './extension-message';\nimport { ExtensionQueryMap, ExtensionQueryType } from './extension-queries';\n\nexport class WorkerExtensionMessenger {\n constructor(\n private _workers: { [extensionId: string]: Worker } = {},\n private _commandListeners: {\n [extensionId: string]: WorkerEventListener;\n } = {},\n private _queryListeners: {\n [extensionId: string]: WorkerEventListener;\n } = {},\n ) {}\n\n add(extensionId: string, worker: Worker): void {\n this._workers[extensionId] = worker;\n }\n\n listenForCommand(\n extensionId: string,\n command: T,\n commandHandler: (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => Promise | void,\n ): () => void {\n const worker = this._getWorkerById(extensionId);\n\n if (!this._commandListeners[extensionId]) {\n this._commandListeners[extensionId] = new WorkerEventListener(worker);\n }\n\n const listener = this._commandListeners[extensionId];\n\n listener.listen();\n\n const validCommandType = this._validateCommand(command);\n\n const commandHandlerProxy = (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandOrQueryContext,\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 listenForQuery(\n extensionId: string,\n query: T,\n queryHandler: (\n query: ExtensionQueryMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => Promise | void,\n ): () => void {\n const worker = this._getWorkerById(extensionId);\n\n if (!this._queryListeners[extensionId]) {\n this._queryListeners[extensionId] = new WorkerEventListener(worker);\n }\n\n const listener = this._queryListeners[extensionId];\n\n listener.listen();\n\n const validQueryType = this._validateQuery(query);\n\n const queryHandlerProxy = (\n query: ExtensionQueryMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => {\n if (context?.extensionId === extensionId) {\n queryHandler(query, context);\n }\n };\n\n listener.addListener(validQueryType, queryHandlerProxy);\n\n return () => {\n listener.removeListener(validQueryType, queryHandlerProxy);\n };\n }\n\n stopListen(extensionId: string): void {\n if (this._commandListeners[extensionId]) {\n this._commandListeners[extensionId].stopListen();\n }\n\n if (this._queryListeners[extensionId]) {\n this._queryListeners[extensionId].stopListen();\n }\n }\n\n post(extensionId: string, message: ExtensionMessage): void {\n if (!this._workers[extensionId]) {\n throw new Error(`Worker with extensionId ${extensionId} not found`);\n }\n\n const workerPoster = new WorkerEventPoster(this._workers[extensionId], extensionId);\n\n workerPoster.post(message);\n }\n\n clearCacheById(extensionId: string): void {\n delete this._workers[extensionId];\n }\n\n private _getWorkerById(extensionId: string): Worker {\n const worker = this._workers[extensionId];\n\n if (!worker) {\n throw new ExtensionNotFoundError(`Worker with extensionId ${extensionId} not found`);\n }\n\n return worker;\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 private _validateQuery(query: T): T {\n if (Object.values(ExtensionQueryType).includes(query)) {\n return query;\n }\n\n throw new UnsupportedExtensionQueryError();\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 { 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 { 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\nexport type EventListeners = {\n [key in keyof TEventMap]?: Array<(event: TEventMap[key], context?: TContext) => void>;\n};\n","import { ReadableCheckoutStore } from '../checkout';\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\n\nimport { createExtensionEventPoster } from './create-extension-event-poster';\nimport {\n ExtensionNotFoundError,\n UnsupportedExtensionCommandError,\n UnsupportedExtensionQueryError,\n} from './errors';\nimport { Extension, ExtensionType } from './extension';\nimport { ExtensionCommandMap, ExtensionCommandType } from './extension-commands';\nimport { ExtensionCommandOrQueryContext, ExtensionMessage } from './extension-message';\nimport { ExtensionQueryMap, ExtensionQueryType } from './extension-queries';\nimport { WorkerExtensionMessenger } from './worker-extension-messenger';\n\nexport class ExtensionMessenger {\n private _extensions: Extension[] | undefined;\n\n constructor(\n private _store: ReadableCheckoutStore,\n private _workerExtensionMessenger: WorkerExtensionMessenger,\n private _commandListeners: {\n [extensionId: string]: IframeEventListener;\n } = {},\n private _queryListeners: {\n [extensionId: string]: IframeEventListener;\n } = {},\n private _posters: { [extensionId: string]: IframeEventPoster } = {},\n ) {}\n\n clearCacheByRegion(region: string): void {\n const extension = this._getExtensionByRegion(region);\n\n if (extension.type === ExtensionType.Worker) {\n this._workerExtensionMessenger.clearCacheById(extension.id);\n\n return;\n }\n\n this.clearCacheById(extension.id);\n }\n\n clearCacheById(extensionId: string): void {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n this._workerExtensionMessenger.clearCacheById(extension.id);\n\n return;\n }\n\n if (this._commandListeners[extensionId]) {\n delete this._commandListeners[extensionId];\n }\n\n if (this._queryListeners[extensionId]) {\n delete this._queryListeners[extensionId];\n }\n\n if (this._posters[extensionId]) {\n delete this._posters[extensionId];\n }\n }\n\n listenForCommand(\n extensionId: string,\n command: T,\n commandHandler: (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => Promise | void,\n ): () => void {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n return this._workerExtensionMessenger.listenForCommand(\n extensionId,\n command,\n commandHandler,\n );\n }\n\n if (!this._commandListeners[extensionId]) {\n this._commandListeners[extensionId] = new IframeEventListener(extension.url);\n }\n\n const listener = this._commandListeners[extensionId];\n\n listener.listen();\n\n const validCommandType = this._validateCommand(command);\n\n const commandHandlerProxy = (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandOrQueryContext,\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 listenForQuery(\n extensionId: string,\n query: T,\n queryHandler: (\n query: ExtensionQueryMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => Promise | void,\n ): () => void {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n return this._workerExtensionMessenger.listenForQuery(extensionId, query, queryHandler);\n }\n\n if (!this._queryListeners[extensionId]) {\n this._queryListeners[extensionId] = new IframeEventListener(extension.url);\n }\n\n const listener = this._queryListeners[extensionId];\n\n listener.listen();\n\n const validQueryType = this._validateQuery(query);\n\n const queryHandlerProxy = (\n query: ExtensionQueryMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => {\n if (context?.extensionId === extensionId) {\n queryHandler(query, context);\n }\n };\n\n listener.addListener(validQueryType, queryHandlerProxy);\n\n return () => {\n listener.removeListener(validQueryType, queryHandlerProxy);\n };\n }\n\n stopListen(extensionId: string): void {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n this._workerExtensionMessenger.stopListen(extensionId);\n\n return;\n }\n\n if (this._commandListeners[extensionId]) {\n this._commandListeners[extensionId].stopListen();\n }\n\n if (this._queryListeners[extensionId]) {\n this._queryListeners[extensionId].stopListen();\n }\n }\n\n post(extensionId: string, message: ExtensionMessage): void {\n try {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n this._workerExtensionMessenger.post(extensionId, message);\n\n return;\n }\n\n if (!this._posters[extensionId]) {\n this._posters[extensionId] =\n createExtensionEventPoster(extension);\n }\n\n this._posters[extensionId].post(message);\n } catch (error) {\n this.clearCacheById(extensionId);\n // eslint-disable-next-line no-console\n console.log(\n `Unable to post event to extension(${extensionId}) because extension iframe is not mounted.\\nThe event that could not be delivered:`,\n message,\n );\n }\n }\n\n private _getExtensionById(extensionId: string): Extension {\n this._getExtensions();\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 _getExtensionByRegion(region: string): Extension {\n this._getExtensions();\n\n const extension = this._extensions?.find((e) => e.region === region);\n\n if (!extension) {\n throw new ExtensionNotFoundError(\n `Unable to proceed due to no extension found for region: ${region}.`,\n );\n }\n\n return extension;\n }\n\n private _getExtensions(): void {\n if (this._extensions) {\n return;\n }\n\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\n private _validateCommand(command: T): T {\n if (Object.values(ExtensionCommandType).includes(command)) {\n return command;\n }\n\n throw new UnsupportedExtensionCommandError();\n }\n private _validateQuery(query: T): T {\n if (Object.values(ExtensionQueryType).includes(query)) {\n return query;\n }\n\n throw new UnsupportedExtensionQueryError();\n }\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 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\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 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 { 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: number, 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 {\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 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 | undefined {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n return;\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) {\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 if (!createCheckoutSessionConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\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: `${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 * 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\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 let paymentMethod: PaymentMethod;\n\n try {\n paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n } catch (_e) {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n paymentMethod = this.paymentIntegrationService\n .getState()\n .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","export interface Features {\n [featureName: string]: boolean | undefined;\n}\n\nexport default function isExperimentEnabled(\n features: Features,\n experimentName: string,\n fallbackValue = true,\n): boolean {\n return features[experimentName] ?? fallbackValue;\n}\n","export const BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION = '3.128.0';\nexport const BRAINTREE_SDK_DEFAULT_VERSION = '3.123.2';\nexport const BRAINTREE_SDK_STABLE_VERSION = '3.106.0';\n","import { find } from 'lodash';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport { BraintreeHostWindow } from './braintree';\nimport {\n BRAINTREE_SDK_DEFAULT_VERSION,\n BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION,\n BRAINTREE_SDK_STABLE_VERSION,\n} from './braintree-sdk-verison';\n\nexport default class BraintreeSDKVersionManager {\n private braintreeWindow: BraintreeHostWindow = window;\n\n constructor(private paymentIntegrationService: PaymentIntegrationService) {}\n\n getSDKVersion() {\n const state = this.paymentIntegrationService.getState();\n const storeConfig = state.getStoreConfig();\n const features = storeConfig?.checkoutSettings.features || {};\n\n const preloadedVersion = this.getPreloadedSDKVersion();\n\n if (preloadedVersion) {\n return preloadedVersion;\n }\n\n if (isExperimentEnabled(features, 'PAYPAL-5809.braintree_hosted_fields_fix_version')) {\n return BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION;\n }\n\n if (isExperimentEnabled(features, 'PAYPAL-5636.update_braintree_sdk_version')) {\n return BRAINTREE_SDK_DEFAULT_VERSION;\n }\n\n return BRAINTREE_SDK_STABLE_VERSION;\n }\n\n private getPreloadedSDKVersion(): void | string {\n const braintree = this.braintreeWindow.braintree;\n\n if (braintree) {\n const preloadedVersion = find<{ VERSION?: string }>(\n Object.values(braintree),\n (module) => !!module.VERSION,\n );\n\n return preloadedVersion?.VERSION;\n }\n }\n}\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","import { Address } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport * 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(\n options: BraintreeThreeDSecureOptions,\n callback?: Braintree3DSVerifyCardCallback,\n ): Promise;\n cancelVerifyCard(): Promise;\n on(\n event: K,\n handler: BraintreeThreeDSecureEventMap[K],\n ): void;\n}\n\nexport type Braintree3DSVerifyCardCallback = (\n verifyError: Braintree3DSVerifyCardError,\n payload: Braintree3DSVerifyCardPayload,\n) => void;\n\nexport interface BraintreeThreeDSecureEventMap {\n 'customer-canceled': () => void;\n}\n\nexport interface Braintree3DSVerifyCardError {\n code: string;\n}\n\nexport interface Braintree3DSVerifyCardPayload {\n nonce: string;\n}\n\nexport interface BraintreeThreeDSecureCreatorConfig extends BraintreeModuleCreatorConfig {\n version?: number;\n}\n\nexport interface BraintreeThreeDSecureOptions {\n nonce: string;\n amount: number | string;\n challengeRequested?: boolean;\n showLoader?: boolean;\n bin?: string;\n additionalInformation?: {\n acsWindowSize?: '01' | '02' | '03' | '04' | '05';\n };\n collectDeviceData?: boolean;\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\nexport enum BraintreeOrderStatus {\n Completed = 'COMPLETED',\n Pending = 'PENDING',\n Failed = 'FAILED',\n}\n\nexport interface BraintreeOrderStatusData {\n status: BraintreeOrderStatus;\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 non-instant payment methods\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 BraintreeOrderSavedResponse {\n body: {\n additional_action_required: {\n data: {\n order_id_saved_successfully: string;\n };\n };\n };\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 binDetails?: {\n bin: string;\n };\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\nexport interface BraintreeRedirectError {\n body: {\n additional_action_required: {\n data: {\n redirect_url: string;\n };\n };\n };\n}\n\nexport default interface BillingAddress extends Address {\n id: string;\n email?: string;\n}\n\nexport enum BraintreeSupportedCardBrands {\n Visa = 'visa',\n Mastercard = 'mastercard',\n AmericanExpress = 'american-express',\n DinersClub = 'diners-club',\n Discover = 'discover',\n Jcb = 'jcb',\n UnionPay = 'union-pay',\n Maestro = 'maestro',\n Elo = 'elo',\n Mir = 'mir',\n Hiper = 'hiper',\n Hipercard = 'hipercard',\n}\n\nexport 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 interface BraintreeRequestData {\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","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 { 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 enableCheckoutPaywallBanner?: boolean;\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 paypalBNPLConfiguration?: PayPalBNPLConfigurationItem[] | null;\n nonce?: string;\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 preventCursorJumps?: boolean;\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: (err: null | undefined | BraintreeError) => 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 BNPL Configurator related types\n *\n */\nexport interface PayPalBNPLConfigurationItem {\n id: string;\n name: string;\n status: boolean;\n styles: Record;\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 {\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 { BraintreeModuleName } from './braintree';\nimport {\n BRAINTREE_SDK_DEFAULT_VERSION,\n BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION,\n BRAINTREE_SDK_STABLE_VERSION,\n} from './braintree-sdk-verison';\n\nexport const BRAINTREE_SDK_SCRIPTS_INTEGRITY = {\n [BRAINTREE_SDK_STABLE_VERSION]: {\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 [BRAINTREE_SDK_DEFAULT_VERSION]: {\n [BraintreeModuleName.Client]:\n 'sha384-o+nbQGcwNNxIBeXeu3+XmbSq+Cg8R3EN3N0l5hXCgMMU2RGY0t1z0LroSEIAbfAO',\n [BraintreeModuleName.PaypalCheckout]:\n 'sha384-WrfbWPBS4mH86GAoycPSgiH8hQ8KH7A67C93Hjhunv/xhNk2YpBn3wbFA4Fhg9U/',\n [BraintreeModuleName.Paypal]:\n 'sha384-VF389nvvrRUgDsTXMxTYORDtVegB9IQa3Cxr//DyJnLYnz8/X8VCzEvck2c+Megt',\n [BraintreeModuleName.LocalPayment]:\n 'sha384-tZKx2rEQbfmZpoPSY5VPmJEhaq4X75dLvwHMs3VE9U+C8lPyw+hWTIL1+GPvWCIH',\n [BraintreeModuleName.DataCollector]:\n 'sha384-E6k3wOpP7syCDDwaRDLF06942Y00NkbwJvWi2OQXwwKzGwG5fd3E7RFUvCCecfvO',\n [BraintreeModuleName.UsBankAccount]:\n 'sha384-258FON8LZGG0W9Qaz4Jij83pZHu30YnKjJA7gNulLBh6CclkucgF+tHDQuYFRYfW',\n [BraintreeModuleName.GooglePayment]:\n 'sha384-taJ2p/0+n0VH328POAoBiuEbL3tnHUTE9S42hK1V+Txs3X+QYjZOyKW35JgHRFfO',\n [BraintreeModuleName.ThreeDSecure]:\n 'sha384-+NSZH4Zj3sO5bdWvPKhU5N16QDxeueTVTnUVeleeESkhLSaz4Ob1hh/5myecc9Ym',\n [BraintreeModuleName.VisaCheckout]:\n 'sha384-66DiBjghxk1OmBj8aksN8gbQ+CwoQcx1vPfiXUN08g1iQVM+BwewF0p7toM3i7SS',\n [BraintreeModuleName.Venmo]:\n 'sha384-B5UwY42kE4RoLoWbQ7YpqosUlUad2/DlGWiw0HhoZbSPk30CQAaSA10ohyLDTkDU',\n [BraintreeModuleName.HostedFields]:\n 'sha384-Aw9EesSaUeWxe36PqEHiOyOyOq8M6CIb1gw7/yHNVPRzGtFXXcd2OQ8qXrIlOj2P',\n [BraintreeModuleName.Fastlane]:\n 'sha384-rhBL1hpZ71JqG+2TsT0Dih47mbjx8cjJCpeZjk9tw3df1gFMKfCTmMyZunhr7H4Y',\n },\n [BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION]: {\n [BraintreeModuleName.Client]:\n 'sha384-0WNxksIpRP+fYZiIdr12g6DBUQfLDzYCQJZtR/C8KkcwSGhPHfcFp3tTaGcMyFTq',\n [BraintreeModuleName.PaypalCheckout]:\n 'sha384-lWM1jk4BOxoDNV6Kop7tVNvQgINlmEVz0c/OwM+HNHK3QC8xqwd54Ovrt2QRDTjh',\n [BraintreeModuleName.Paypal]:\n 'sha384-fXUmVxC2EMZBDXZ7eTHSTL/LFBrHej/MSXT/vTBXvra4lzgLNGvREAp+x0GYObuH',\n [BraintreeModuleName.LocalPayment]:\n 'sha384-pha1xGuGSkmZH5x9aqHvRaO4xLea7rmQ/79PFj9zxNzxuFcOWZg7gOP7FibygOEC',\n [BraintreeModuleName.DataCollector]:\n 'sha384-Q6PI2F9eekWbAxhroybl+aEcvqhdowN/EQlGwBUyJOzPFn9982u9xl6SU6XfGKzc',\n [BraintreeModuleName.UsBankAccount]:\n 'sha384-W3RLQSKJL1tQ3+Y7mP6tmkamtZ8bV4Yw/XxL9Jj5JtXHraD8loMF8hAIG5m2zK7F',\n [BraintreeModuleName.GooglePayment]:\n 'sha384-TITQMsFWA3elDNGP2mWz2oKBo4qjt+TlqzovcaPoeBiAh/wPBi6nae50ADdgU1/i',\n [BraintreeModuleName.ThreeDSecure]:\n 'sha384-YiycYN89ZlL/Evcaq4y1ajW1mhd7JYfZBDuOwHtIn4/Jnm20GL+/XCM+zYAwWD8D',\n [BraintreeModuleName.VisaCheckout]:\n 'sha384-/OdaTv9qrkKzjObtUe6yzfDhHozFW/+uXlrSl736sOZRJpjGQETvpYXqMFFg69xv',\n [BraintreeModuleName.Venmo]:\n 'sha384-dA+ojdW9vbJS4JavcXyOs9d5uZHJg5dNtYupoPSH2zsXIiYDVS5amLb/u8qmQ6oz',\n [BraintreeModuleName.HostedFields]:\n 'sha384-31ZkS58+iaWsW06ftW52zzVZFp43WPd7pNYRiddYynSNg6Oh7WGbSFGorAUH6T1z',\n [BraintreeModuleName.Fastlane]:\n 'sha384-jlbrwNvL3HvLAUCtLSmrnQ2GH1udCUrRS/bVmReAS5fuIVvcW8Pko/Gkg82tlgtr',\n },\n};\n","export enum ApplePayGatewayType {\n BRAINTREE = 'braintree',\n BRAINTREE_FASTLANE = 'braintreeacceleratedcheckout',\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 BraintreeSDKVersionManager from './braintree-sdk-version-manager';\nimport isManageableBraintreeSDKVersion from './isManageableBraintreeSDKVersion';\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 constructor(\n private scriptLoader: ScriptLoader,\n private braintreeHostWindow: BraintreeHostWindow,\n private braintreeSDKVersionManager: BraintreeSDKVersionManager,\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 braintreeSdkVersion = this.braintreeSDKVersionManager.getSDKVersion();\n\n const scriptPath = `//js.braintreegateway.com/web/${braintreeSdkVersion}/js/${fileName}`;\n\n const integrity = isManageableBraintreeSDKVersion(braintreeSdkVersion)\n ? this.getIntegrityValuesByModuleName(braintreeModuleName, braintreeSdkVersion)\n : undefined;\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(\n moduleName: BraintreeModuleName,\n version: keyof typeof BRAINTREE_SDK_SCRIPTS_INTEGRITY,\n ): string {\n const integrity = BRAINTREE_SDK_SCRIPTS_INTEGRITY[version][moduleName];\n\n if (!integrity) {\n throw new Error('Unexpected fileName value');\n }\n\n return integrity;\n }\n}\n","import { BRAINTREE_SDK_SCRIPTS_INTEGRITY } from './braintree-sdk-scripts-integrity';\n\nfunction isManageableBraintreeSDKVersion(\n version: string,\n): version is keyof typeof BRAINTREE_SDK_SCRIPTS_INTEGRITY {\n return version in BRAINTREE_SDK_SCRIPTS_INTEGRITY;\n}\n\nexport default isManageableBraintreeSDKVersion;\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","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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory 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 private _applePayScriptLoader: ApplePayScriptLoader,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithApplePayCustomerInitializeOptions,\n ): Promise {\n const { methodId, applepay } = options;\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 await this._applePayScriptLoader.loadSdk();\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 (\n this._paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE &&\n this._paymentMethod.clientToken\n ) {\n this._braintreeSdk.initialize(this._paymentMethod.clientToken);\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 applePayButton = this._createApplePayButtonElement();\n\n container.appendChild(applePayButton);\n\n return applePayButton;\n }\n\n private _createApplePayButtonElement(): HTMLElement {\n const applePayButton = document.createElement('apple-pay-button');\n\n applePayButton.setAttribute('buttonstyle', 'black');\n applePayButton.setAttribute('type', 'plain');\n applePayButton.setAttribute(\n 'style',\n '--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;',\n );\n\n return applePayButton;\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","import ApplePayWindow from './apple-pay-window';\nimport isApplePayWindow from './is-apple-pay-window';\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 ApplePayWindow from './apple-pay-window';\n\nexport default function isApplePayWindow(window: Window): window is ApplePayWindow {\n return 'ApplePaySession' in window;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { assertApplePayWindow } from './apple-pay-session-factory';\nimport isApplePaySdkWindow from './is-apple-pay-sdk-window';\n\nexport default class ApplePayScriptLoader {\n private sdkVersion = '1.latest';\n\n constructor(private scriptLoader: ScriptLoader) {}\n\n async loadSdk() {\n if (isApplePaySdkWindow(window)) {\n return;\n }\n\n await this.scriptLoader.loadScript(\n `https://applepay.cdn-apple.com/jsapi/${this.sdkVersion}/apple-pay-sdk.js`,\n );\n\n assertApplePayWindow(window);\n }\n}\n","interface ApplePaySdkWindow extends Window {\n ApplePaySDK?: {\n origin: string;\n publicPath: string;\n token: string | undefined;\n };\n}\n\nexport default function isApplePaySdkWindow(window: Window): window is ApplePaySdkWindow {\n return 'ApplePaySDK' in window;\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\n} 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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayCustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n\n return new ApplePayCustomerStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), window, braintreeSDKVersionManager),\n ),\n new ApplePayScriptLoader(new ScriptLoader()),\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 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 { 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 | object;\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 { PayPalBNPLConfigurationItem } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n BuyNowCartRequestBody,\n HostedInstrument,\n ShippingOption,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n/**\n *\n * BigCommerce Payments Funding sources\n *\n */\nexport type FundingType = string;\n// TODO: rename BigCommercePaymentsSDKFunding to PayPalSDKFunding\nexport interface BigCommercePaymentsSDKFunding {\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 * BigCommerce Payments SDK\n *\n */\n\nexport interface BigCommercePaymentsCardFieldsConfig {\n inputEvents: {\n onChange(data: BigCommercePaymentsCardFieldsState): void;\n onFocus(data: BigCommercePaymentsCardFieldsState): void;\n onBlur(data: BigCommercePaymentsCardFieldsState): void;\n onInputSubmitRequest(data: BigCommercePaymentsCardFieldsState): void;\n };\n createVaultSetupToken?: (data: BigCommercePaymentsCardFieldsState) => void;\n createOrder?: () => Promise;\n style: BigCommercePaymentsHostedFieldsRenderOptions['styles'];\n onApprove(data: BigCommercePaymentsCardFieldsOnApproveData): void;\n onError(): void;\n}\n\nexport interface BigCommercePaymentsCardFieldsOnApproveData {\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 BigCommercePaymentsCardFieldsFieldData {\n isFocused: boolean;\n isEmpty: boolean;\n isValid: boolean;\n isPotentiallyValid: boolean;\n}\n\ntype BigCommercePaymentsCardFieldsCard = BigCommercePaymentsHostedFieldsCard;\n\nexport interface BigCommercePaymentsCardFieldsState {\n cards: BigCommercePaymentsCardFieldsCard[];\n emittedBy: string;\n isFormValid: boolean;\n errors: string[];\n fields: {\n cardCvvField: BigCommercePaymentsCardFieldsFieldData;\n cardNumberField: BigCommercePaymentsCardFieldsFieldData;\n cardNameField?: BigCommercePaymentsCardFieldsFieldData;\n cardExpiryField: BigCommercePaymentsCardFieldsFieldData;\n };\n}\n\nexport interface BigCommercePaymentsFields {\n render(container: HTMLElement | string): Promise;\n clear(): void;\n removeClass(className: string): Promise;\n close(): Promise;\n}\n\ninterface BigCommercePaymentsFieldsInitializationData {\n placeholder?: string;\n}\n\nexport interface BigCommercePaymentsCardFields {\n isEligible(): boolean;\n CVVField(config?: BigCommercePaymentsFieldsInitializationData): BigCommercePaymentsFields;\n ExpiryField(config?: BigCommercePaymentsFieldsInitializationData): BigCommercePaymentsFields;\n NameField(config?: BigCommercePaymentsFieldsInitializationData): BigCommercePaymentsFields;\n NumberField(config?: BigCommercePaymentsFieldsInitializationData): BigCommercePaymentsFields;\n submit(config?: BigCommercePaymentsCardFieldsSubmitConfig): Promise;\n getState(): Promise;\n}\n\nexport interface BigCommercePaymentsCardFieldsSubmitConfig {\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: (\n data: BigCommercePaymentsCardFieldsConfig,\n ) => 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: BigCommercePaymentsSDKFunding;\n HostedFields: {\n isEligible(): boolean;\n render(\n data: BigCommercePaymentsHostedFieldsRenderOptions,\n ): Promise;\n };\n Legal: PayPalLegal & LegalFunding;\n Buttons(options: BigCommercePaymentsButtonsOptions): BigCommercePaymentsButtons;\n PaymentFields(\n options: BigCommercePaymentsPaymentFieldsOptions,\n ): BigCommercePaymentsPaymentFields;\n Messages(options: BigCommercePaymentsMessagesOptions): BigCommercePaymentsMessages;\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 BigCommercePaymentsScriptParams {\n options: {\n 'client-id'?: string;\n 'merchant-id'?: string;\n 'buyer-country'?: string;\n 'disable-funding'?: FundingType[];\n 'enable-funding'?: FundingType[];\n currency?: string;\n commit?: boolean;\n intent?: BigCommercePaymentsIntent;\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 'data-namespace'?: string;\n };\n}\n\nexport enum BigCommercePaymentsIntent {\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 BigCommercePaymentsHostWindow extends Window {\n bigCommercePaymentsPayPalSDK?: PayPalSDK;\n}\n\n/**\n *\n * BigCommerce Payments Initialization Data\n *\n */\nexport interface BigCommercePaymentsInitializationData {\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?: BigCommercePaymentsIntent;\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 isAppSwitchEnabled?: boolean;\n paypalBNPLConfiguration?: PayPalBNPLConfigurationItem[];\n}\n\n/**\n *\n * BigCommerce Payments BuyNow\n *\n */\nexport interface PayPalBuyNowInitializeOptions {\n getBuyNowCartRequestBody(): BuyNowCartRequestBody;\n}\n\n/**\n *\n * BigCommerce Payments Hosted Fields\n *\n */\nexport interface BigCommercePaymentsHostedFieldsRenderOptions {\n fields?: {\n number?: BigCommercePaymentsHostedFieldOption;\n cvv?: BigCommercePaymentsHostedFieldOption;\n expirationDate?: BigCommercePaymentsHostedFieldOption;\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 BigCommercePaymentsHostedFieldOption {\n selector: string;\n placeholder?: string;\n}\n\nexport interface BigCommercePaymentsHostedFields {\n submit(\n options?: BigCommercePaymentsHostedFieldsSubmitOptions,\n ): Promise;\n getState(): BigCommercePaymentsHostedFieldsState;\n on(eventName: string, callback: (event: BigCommercePaymentsHostedFieldsState) => void): void;\n}\n\nexport interface BigCommercePaymentsHostedFieldsSubmitOptions {\n contingencies?: Array<'3D_SECURE'>;\n cardholderName?: string;\n}\n\nexport interface BigCommercePaymentsHostedFieldsApprove {\n orderId: string;\n liabilityShift?: 'POSSIBLE' | 'NO' | 'UNKNOWN';\n}\n\nexport interface BigCommercePaymentsHostedFieldsState {\n cards: BigCommercePaymentsHostedFieldsCard[];\n emittedBy: string;\n fields: {\n number?: BigCommercePaymentsHostedFieldsFieldData;\n expirationDate?: BigCommercePaymentsHostedFieldsFieldData;\n expirationMonth?: BigCommercePaymentsHostedFieldsFieldData;\n expirationYear?: BigCommercePaymentsHostedFieldsFieldData;\n cvv?: BigCommercePaymentsHostedFieldsFieldData;\n postalCode?: BigCommercePaymentsHostedFieldsFieldData;\n };\n}\n\nexport interface BigCommercePaymentsHostedFieldsCard {\n type: string;\n niceType: string;\n code: {\n name: string;\n size: number;\n };\n}\n\nexport interface BigCommercePaymentsHostedFieldsFieldData {\n container: HTMLElement;\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\n/**\n *\n * BigCommerce Payments Buttons\n *\n */\nexport interface BigCommercePaymentsButtons {\n render(id: string): void;\n close(): void;\n isEligible(): boolean;\n hasReturned?(): boolean;\n resume?(): void;\n}\n\nexport interface BigCommercePaymentsButtonsOptions {\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 phone?: {\n phone_number: {\n national_number: string;\n };\n };\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 * BigCommerce Payments Payment fields\n *\n */\nexport interface BigCommercePaymentsPaymentFields {\n render(id: string): void;\n}\n\nexport interface BigCommercePaymentsPaymentFieldsOptions {\n style?: BigCommercePaymentsFieldsStyleOptions;\n fundingSource: string;\n fields: {\n name?: {\n value?: string;\n };\n email?: {\n value?: string;\n };\n };\n}\n\nexport interface BigCommercePaymentsFieldsStyleOptions {\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 * BigCommercePayments Messages\n */\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface BigCommercePaymentsMessages {\n render(id: string): void;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface BigCommercePaymentsMessagesOptions {\n amount: number;\n placement: string;\n style?: BigCommercePaymentsMessagesStyleOptions;\n fundingSource?: string;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface BigCommercePaymentsMessagesStyleOptions {\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 fastlaneToken?: string;\n methodId?: string;\n gatewayId?: string;\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 BigCommercePaymentsRequestSender from './bigcommerce-payments-request-sender';\nimport BigCommercePaymentsScriptLoader from './bigcommerce-payments-script-loader';\nimport {\n BigCommercePaymentsInitializationData,\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n PayPalCreateOrderCardFieldsResponse,\n PayPalCreateOrderRequestBody,\n PayPalOrderDetails,\n PayPalOrderStatus,\n PayPalSDK,\n StyleButtonColor,\n StyleButtonLabel,\n StyleButtonShape,\n} from './bigcommerce-payments-types';\n\nexport default class BigCommercePaymentsIntegrationService {\n private paypalSdk?: PayPalSDK;\n\n constructor(\n private formPoster: FormPoster,\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsRequestSender: BigCommercePaymentsRequestSender,\n private bigCommercePaymentsScriptLoader: BigCommercePaymentsScriptLoader,\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.bigCommercePaymentsScriptLoader.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.bigCommercePaymentsRequestSender.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.bigCommercePaymentsRequestSender.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.bigCommercePaymentsRequestSender.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.bigCommercePaymentsRequestSender.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: address?.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 phone: payer.phone?.phone_number?.national_number,\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","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 } 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 './bigcommerce-payments-types';\n\nexport default class BigCommercePaymentsRequestSender {\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/bigcommerce_payments`;\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 = 'bigcommerce_payments',\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 BigCommercePaymentsHostWindow,\n BigCommercePaymentsInitializationData,\n BigCommercePaymentsScriptParams,\n ComponentsScriptType,\n FundingType,\n PayPalSDK,\n} from './bigcommerce-payments-types';\n\nexport default class BigCommercePaymentsScriptLoader {\n private window: BigCommercePaymentsHostWindow;\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: BigCommercePaymentsScriptParams,\n forceLoad = false,\n ): Promise {\n if (!this.window.bigCommercePaymentsPayPalSDK || 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.bigCommercePaymentsPayPalSDK) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.bigCommercePaymentsPayPalSDK;\n }\n\n private getPayPalSdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage = true,\n ): BigCommercePaymentsScriptParams {\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 === 'bigcommerce_payments_creditcards';\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 enableVenmoFunding = isVenmoEnabled ? ['venmo'] : [];\n const disableVenmoFunding = !isVenmoEnabled ? ['venmo'] : [];\n const disableAPMsFunding = availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n );\n const googlePayComponent: ComponentsScriptType = isGooglePayEnabled ? ['googlepay'] : [];\n const cardFieldsComponent: ComponentsScriptType = initializesOnCheckoutPage\n ? ['card-fields']\n : [];\n const disableFunding: FundingType[] = this.filterFundingOptions([\n ...disableCardFunding,\n ...disableCreditFunding,\n ...disableVenmoFunding,\n ...disableAPMsFunding,\n ]);\n const enableFunding: FundingType[] = this.filterFundingOptions([\n ...enableCardFunding,\n ...enableCreditFunding,\n ...enableVenmoFunding,\n ...enabledAlternativePaymentMethods,\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 'data-namespace': 'bigCommercePaymentsPayPalSDK',\n },\n };\n }\n\n private filterFundingOptions(fundingOptions: FundingType[] | undefined): FundingType[] {\n const fundingTypesToBeFiltered = ['klarna', 'afterpay'];\n\n if (!fundingOptions) {\n return [];\n }\n\n return fundingOptions.filter(\n (fundingOption: FundingType) => !fundingTypesToBeFiltered.includes(fundingOption),\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 BigCommercePaymentsIntegrationService,\n BigCommercePaymentsRequestSender,\n BigCommercePaymentsScriptLoader,\n} from './index';\n\nconst createBigCommercePaymentsIntegrationService = (\n paymentIntegrationService: PaymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new BigCommercePaymentsIntegrationService(\n createFormPoster(),\n paymentIntegrationService,\n new BigCommercePaymentsRequestSender(createRequestSender({ host: getHost() })),\n new BigCommercePaymentsScriptLoader(getScriptLoader()),\n );\n};\n\nexport default createBigCommercePaymentsIntegrationService;\n","const DefaultCheckoutButtonHeight = 40;\n\nexport default DefaultCheckoutButtonHeight;\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsCustomerInitializeOptions, {\n WithBigCommercePaymentsCustomerInitializeOptions,\n} from './bigcommerce-payments-customer-initialize-options';\n\nexport default class BigCommercePaymentsCustomerStrategy implements CustomerStrategy {\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBigCommercePaymentsCustomerInitializeOptions,\n ): Promise {\n const { bigcommerce_payments, 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 (!bigcommerce_payments) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments\" argument is not provided.',\n );\n }\n\n if (!bigcommerce_payments.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments.container\" argument is not provided.',\n );\n }\n\n if (bigcommerce_payments.onClick && typeof bigcommerce_payments.onClick !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments.onClick\" argument is not a function.',\n );\n }\n\n this.onError = bigcommerce_payments.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 const paypalSdk = await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n // eslint-disable-next-line no-console\n console.error(\n '[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n this.renderButton(methodId, bigcommerce_payments);\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 bigcommerce_payments: BigCommercePaymentsCustomerInitializeOptions,\n ): void {\n const { container, onClick, onComplete } = bigcommerce_payments;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const {\n isHostedCheckoutEnabled,\n paymentButtonStyles,\n isAppSwitchEnabled = false,\n } = paymentMethod.initializationData || {};\n const { checkoutTopButtonStyles } = paymentButtonStyles || {};\n\n const defaultCallbacks = {\n ...(isAppSwitchEnabled && {\n appSwitchWhenAvailable: true,\n }),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder('bigcommerce_payments'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.tokenizePayment(methodId, orderID),\n ...(onClick && { onClick: () => onClick() }),\n };\n\n const hostedCheckoutCallbacks = {\n ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n }),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const buttonRenderOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.bigCommercePaymentsIntegrationService.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 if (paypalButton.hasReturned?.() && isAppSwitchEnabled) {\n paypalButton.resume?.();\n } else {\n paypalButton.render(`#${container}`);\n }\n } else {\n this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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 =\n this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsCustomerStrategy from './bigcommerce-payments-customer-strategy';\n\nconst createBigCommercePaymentsCustomerStrategy: CustomerStrategyFactory<\n BigCommercePaymentsCustomerStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsCustomerStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsCustomerStrategy, [\n { id: 'bigcommerce_payments' },\n]);\n","import { HostedInstrument, NonceInstrument } from './payment';\n\ntype PaymentInstrument = CardInstrument | AccountInstrument | HostedInstrument | NonceInstrument;\n\nexport default PaymentInstrument;\n\nexport interface 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 { CardInstrument, CustomerAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n/**\n *\n * BigCommerce Payments Funding sources\n *\n */\nexport type FundingType = string;\n\n/**\n *\n * BigCommerce Payments Initialization Data\n *\n */\nexport interface BigCommercePaymentsInitializationData {\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 BCP Fastlane A/B test will be finished\n enabledAlternativePaymentMethods: FundingType[];\n isDeveloperModeApplicable?: boolean;\n intent?: BigCommercePaymentsIntent;\n isAcceleratedCheckoutEnabled?: boolean; // PayPal Fastlane related\n isFastlaneShippingOptionAutoSelectEnabled?: boolean; // PayPal Fastlane related\n isFastlaneStylingEnabled?: boolean;\n isHostedCheckoutEnabled?: boolean;\n isBigCommercePaymentsAnalyticsV2Enabled?: 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 BCP Fastlane A/B test will be finished\n paymentButtonStyles?: Record;\n paypalBNPLConfiguration?: PayPalBNPLConfigurationItem[];\n threeDSVerificationMethod?: string;\n}\n\n/**\n *\n * PayPalHostWindow contains different\n * PayPal Sdk instances for different purposes\n *\n */\nexport interface PayPalHostWindow extends Window {\n bigCommercePaymentsFastlane?: PayPalFastlane;\n bigCommercePaymentsFastlaneSdk?: PayPalFastlaneSdk;\n bigCommercePaymentsMessages?: PayPalMessagesSdk;\n bigCommercePaymentsApms?: PayPalApmSdk;\n bigCommercePaymentsGooglePay?: PayPalGooglePaySdk;\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'?: FundingType[];\n 'disable-funding'?: FundingType[];\n currency?: string;\n commit?: boolean;\n intent?: BigCommercePaymentsIntent;\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 'data-sdk-client-token'?: string;\n };\n}\n\nexport enum BigCommercePaymentsIntent {\n AUTHORIZE = 'authorize',\n CAPTURE = 'capture',\n}\n\nexport type PayPalSdkComponents = Array<\n 'fastlane' | 'messages' | 'buttons' | 'payment-fields' | 'googlepay' | 'three-domain-secure'\n>;\n\n/**\n *\n * PayPal Sdk instances\n *\n */\nexport enum LiabilityShiftEnum {\n Possible = 'POSSIBLE',\n No = 'NO',\n Unknown = 'UNKNOWN',\n Yes = 'YES',\n}\n\nexport interface threeDSecureParameters {\n amount: string;\n currency: string;\n nonce: string;\n threeDSRequested: boolean;\n transactionContext: {\n experience_context: {\n brand_name?: string;\n locale: string;\n return_url: string;\n cancel_url: string;\n };\n };\n}\n\nexport interface PayPalFastlaneSdk {\n ThreeDomainSecureClient: {\n isEligible(params: threeDSecureParameters): Promise;\n show(): Promise;\n };\n Fastlane(options?: PayPalFastlaneOptions): Promise;\n}\n\ninterface ThreeDomainSecureClientShowResponse {\n liabilityShift: LiabilityShiftEnum;\n authenticationState: TDSecureAuthenticationState;\n nonce: string; // Enriched nonce or the original nonce\n}\n\nexport interface PayPalMessagesSdk {\n Messages(options: MessagingOptions): MessagingRender;\n}\n\nexport interface PayPalApmSdk {\n Buttons(options: BigCommercePaymentsButtonsOptions): BigCommercePaymentsButtons;\n PaymentFields(\n options: BigCommercePaymentsPaymentFieldsOptions,\n ): BigCommercePaymentsPaymentFields;\n}\n\nexport interface PayPalGooglePaySdk {\n Googlepay(): GooglePay;\n}\n\nexport enum TDSecureVerificationMethod {\n Always = 'SCA_ALWAYS',\n}\n\nexport enum TDSecureAuthenticationState {\n Succeeded = 'succeeded',\n Cancelled = 'cancelled',\n Errored = 'errored',\n}\n\n/**\n *\n * Google Pay related types\n *\n */\n\ninterface GooglePay {\n config: () => Promise;\n confirmOrder: (confirmOrderConfig: ConfirmOrderConfig) => Promise<{ status: string }>;\n initiatePayerAction: (payerActionConfig: PayerActionConfig) => Promise;\n}\n\ninterface ConfirmOrderConfig {\n orderId: string;\n paymentMethodData: ConfirmOrderData;\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\ninterface PayerActionConfig {\n orderId: 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\n/**\n *\n * BigCommerce Payments Buttons\n *\n */\nexport interface BigCommercePaymentsButtons {\n render(id: string): void;\n close(): void;\n isEligible(): boolean;\n}\n\nexport interface BigCommercePaymentsButtonsOptions {\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 * BigCommerce Payments PaymentFields fields\n *\n */\nexport interface BigCommercePaymentsPaymentFields {\n render(id: string): void;\n}\n\nexport interface BigCommercePaymentsPaymentFieldsOptions {\n style?: BigCommercePaymentsFieldsStyleOptions;\n fundingSource: string;\n fields: {\n name?: {\n value?: string;\n };\n email?: {\n value?: string;\n };\n };\n}\n\nexport interface BigCommercePaymentsFieldsStyleOptions {\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 = 'canceled',\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\nexport interface RedirectError {\n body: {\n additional_action_required: {\n data: {\n redirect_url: string;\n };\n };\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 BigCommercePaymentsInitializationData,\n FundingType,\n PayPalFastlaneSdk,\n PayPalGooglePaySdk,\n PayPalHostWindow,\n PayPalMessagesSdk,\n PayPalSdkConfig,\n} from './bigcommerce-payments-types';\n\nexport default class PayPalSdkHelper {\n private window: PayPalHostWindow;\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.bigCommercePaymentsFastlaneSdk) {\n const config = this.getPayPalFastlaneSdkConfiguration(\n paymentMethod,\n currencyCode,\n sessionId,\n );\n\n await this.loadPayPalSdk(config);\n\n if (!this.window.bigCommercePaymentsFastlaneSdk) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.window.bigCommercePaymentsFastlaneSdk;\n }\n\n async getPayPalGooglePaySdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n if (!this.window.bigCommercePaymentsGooglePay || forceLoad) {\n const paypalSdkScriptConfig = this.getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n initializesOnCheckoutPage,\n );\n\n await this.loadPayPalSdk(paypalSdkScriptConfig);\n }\n\n if (!this.window.bigCommercePaymentsGooglePay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.bigCommercePaymentsGooglePay;\n }\n\n async getPayPalApmsSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n ) {\n if (!this.window.bigCommercePaymentsApms) {\n const config = this.getPayPalApmSdkConfiguration(paymentMethod, currencyCode);\n\n await this.loadPayPalSdk(config);\n\n if (!this.window.bigCommercePaymentsApms) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.window.bigCommercePaymentsApms;\n }\n\n async getPayPalMessages(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n ): Promise {\n if (!this.window.bigCommercePaymentsMessages) {\n const paypalSdkMessagesConfig = this.getPayPalSdkMessagesConfiguration(\n paymentMethod,\n currencyCode,\n );\n\n await this.loadPayPalSdk(paypalSdkMessagesConfig);\n }\n\n if (!this.window.bigCommercePaymentsMessages) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.bigCommercePaymentsMessages;\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 { intent, clientId, merchantId, attributionId } = initializationData;\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit: true,\n components: ['fastlane', 'three-domain-secure'],\n currency: currencyCode,\n intent,\n },\n attributes: {\n 'data-client-metadata-id': sessionId.replace(/-/g, ''),\n 'data-namespace': 'bigCommercePaymentsFastlaneSdk',\n 'data-partner-attribution-id': attributionId,\n 'data-sdk-client-token': clientToken,\n },\n };\n }\n\n private getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage = true,\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 buyerCountry,\n attributionId,\n isHostedCheckoutEnabled,\n isDeveloperModeApplicable,\n } = initializationData;\n\n const commit = isHostedCheckoutEnabled || initializesOnCheckoutPage;\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit,\n components: ['googlepay'],\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 'data-namespace': 'bigCommercePaymentsGooglePay',\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 = this.filterFundingOptions(enabledAlternativePaymentMethods);\n const disableAPMsFunding = this.filterFundingOptions(\n availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n ),\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': 'bigCommercePaymentsApms',\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': 'bigCommercePaymentsMessages',\n 'data-partner-attribution-id': attributionId,\n },\n };\n }\n\n /**\n *\n * Utils methods\n *\n */\n private filterFundingOptions(fundingOptions: FundingType[] | undefined): FundingType[] {\n const fundingTypesToBeFiltered = ['klarna', 'afterpay'];\n\n if (!fundingOptions) {\n return [];\n }\n\n return fundingOptions.filter(\n (fundingOption: FundingType) => !fundingTypesToBeFiltered.includes(fundingOption),\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 { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport PayPalSdkHelper from './paypal-sdk-helper';\n\nexport default function createBigCommercePaymentsSdk(): PayPalSdkHelper {\n return new PayPalSdkHelper(createScriptLoader());\n}\n","interface CookieOptions {\n expires?: Date;\n path?: string;\n domain?: string;\n secure?: boolean;\n}\n\nexport default class CookieStorage {\n static get(name: string): string | null {\n const cookieKey = `${encodeURIComponent(`${name}`)}=`;\n const cookie = document.cookie;\n\n let value = null;\n\n const firstIndex = cookie.indexOf(cookieKey);\n\n if (firstIndex > -1) {\n let lastIndex = cookie.indexOf(';', firstIndex);\n\n if (lastIndex === -1) {\n lastIndex = cookie.length;\n }\n\n value = decodeURIComponent(cookie.substring(firstIndex + cookieKey.length, lastIndex));\n }\n\n return value;\n }\n\n static set(name: string, value: string, options: CookieOptions = { secure: true }) {\n let cookieText = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;\n\n const { expires, path, domain, secure } = options;\n\n if (expires) {\n cookieText += `; expires=${expires.toUTCString()}`;\n } else {\n const now = new Date();\n // info: default cookie expiration time after setup\n const minutes = 60;\n\n now.setTime(now.getTime() + minutes * 60 * 1000);\n\n cookieText += `; expires=${now.toUTCString()}`;\n }\n\n if (path) {\n cookieText += `; path=${path}`;\n }\n\n if (domain) {\n cookieText += `; domain=${domain}`;\n }\n\n if (secure) {\n cookieText += '; secure';\n }\n\n document.cookie = cookieText;\n }\n\n static remove(name: string, options?: CookieOptions) {\n CookieStorage.set(name, '', { expires: new Date(0), ...options });\n }\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 { CookieStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport {\n PayPalFastlane,\n PayPalFastlaneAddress,\n PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneLookupCustomerByEmailResult,\n PayPalFastlaneProfileCard,\n PayPalFastlaneProfileName,\n PayPalFastlaneProfilePhone,\n PayPalFastlaneProfileToBcCustomerDataMappingResult,\n PayPalFastlaneSdk,\n PayPalFastlaneStylesOption,\n PayPalHostWindow,\n} from './bigcommerce-payments-types';\n\nexport default class BigCommercePaymentsFastlaneUtils {\n private window: PayPalHostWindow;\n\n constructor() {\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.bigCommercePaymentsFastlane) {\n const defaultStyles = {\n root: {\n backgroundColorPrimary: 'transparent',\n },\n };\n\n this.window.bigCommercePaymentsFastlane = await paypalFastlaneSdk.Fastlane({\n styles: styles || defaultStyles,\n });\n }\n\n return this.window.bigCommercePaymentsFastlane;\n }\n\n getPayPalFastlaneOrThrow(): PayPalFastlane {\n if (!this.window.bigCommercePaymentsFastlane) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.bigCommercePaymentsFastlane;\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 *\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(sessionId: string): void {\n const expires = new Date();\n\n expires.setDate(expires.getDate() + 14); // 2 weeks expiry\n\n const cookiesOption = {\n expires,\n secure: true,\n };\n\n CookieStorage.set('bc-fastlane-sessionId', sessionId, cookiesOption);\n }\n\n removeStorageSessionId(): void {\n CookieStorage.remove('bc-fastlane-sessionId');\n }\n\n getStorageSessionId(): string {\n return CookieStorage.get('bc-fastlane-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 BigCommercePaymentsFastlaneUtils from './bigcommerce-payments-fastlane-utils';\n\nexport default function createBigCommercePaymentsFastlaneUtils(): BigCommercePaymentsFastlaneUtils {\n return new BigCommercePaymentsFastlaneUtils();\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 BigCommercePaymentsFastlaneUtils,\n BigCommercePaymentsInitializationData,\n getFastlaneStyles,\n PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneStylesOption,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsFastlaneCustomerInitializeOptions, {\n WithBigCommercePaymentsFastlaneCustomerInitializeOptions,\n} from './bigcommerce-payments-fastlane-customer-initialize-options';\n\nexport default class BigCommercePaymentsFastlaneCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsSdk: PayPalSdkHelper,\n private bigCommercePaymentsFastlaneUtils: BigCommercePaymentsFastlaneUtils,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions &\n WithBigCommercePaymentsFastlaneCustomerInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_fastlane } = 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.bigCommercePaymentsSdk.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n );\n\n await this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(\n paypalFastlaneSdk,\n isTestModeEnabled,\n this.getFastlaneStyles(methodId, bigcommerce_payments_fastlane),\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 await this.paymentIntegrationService.updatePaymentProviderCustomer({\n authenticationState: undefined,\n addresses: undefined,\n instruments: undefined,\n });\n\n this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId();\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 } =\n await this.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(customerEmail);\n\n const authenticationResult =\n await this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(\n customerContextId,\n );\n\n const isAuthenticationFlowCanceled =\n authenticationResult.authenticationState === PayPalFastlaneAuthenticationState.CANCELED;\n\n await this.updateCustomerDataState(methodId, authenticationResult);\n\n if (isAuthenticationFlowCanceled) {\n this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId();\n } else {\n this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(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.bigCommercePaymentsFastlaneUtils.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(\n methodId,\n );\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 bigcommerce_payments_fastlane:\n | BigCommercePaymentsFastlaneCustomerInitializeOptions\n | 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 bigcommerce_payments_fastlane?.styles,\n );\n }\n}\n","import {\n createBigCommercePaymentsFastlaneUtils,\n createBigCommercePaymentsSdk,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsFastlaneCustomerStrategy from './bigcommerce-payments-fastlane-customer-strategy';\n\nconst createBigCommercePaymentsFastlaneCustomerStrategy: CustomerStrategyFactory<\n BigCommercePaymentsFastlaneCustomerStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsFastlaneCustomerStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsSdk(),\n createBigCommercePaymentsFastlaneUtils(),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsFastlaneCustomerStrategy, [\n { id: 'bigcommerce_payments_fastlane' }, // this method id will be provided for users from test group\n { id: 'bigcommerce_payments_creditcards' }, // this method id will be provided for users from control group\n]);\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsPayLaterCustomerInitializeOptions, {\n WithBigCommercePaymentsPayLaterCustomerInitializeOptions,\n} from './bigcommerce-payments-paylater-customer-initialize-options';\n\nexport default class BigCommercePaymentsPayLaterCustomerStrategy implements CustomerStrategy {\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions &\n WithBigCommercePaymentsPayLaterCustomerInitializeOptions,\n ): Promise {\n const { bigcommerce_payments_paylater, 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 (!bigcommerce_payments_paylater) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_paylater\" argument is not provided.',\n );\n }\n\n if (!bigcommerce_payments_paylater.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_paylater.container\" argument is not provided.',\n );\n }\n\n if (\n bigcommerce_payments_paylater.onClick &&\n typeof bigcommerce_payments_paylater.onClick !== 'function'\n ) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_paylater.onClick\" argument is not a function.',\n );\n }\n\n this.onError = bigcommerce_payments_paylater.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 const paypalSdk = await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n // eslint-disable-next-line no-console\n console.error(\n '[BC BigCommercePayments PayLater]: button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n this.renderButton(methodId, bigcommerce_payments_paylater);\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 bigCommercePaymentsPayLater: BigCommercePaymentsPayLaterCustomerInitializeOptions,\n ): void {\n const { container, onComplete, onClick } = bigCommercePaymentsPayLater;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_paylater',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.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: BigCommercePaymentsButtonsOptions = {\n fundingSource,\n style: this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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 =\n this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsPayLaterCustomerStrategy from './bigcommerce-payments-paylater-customer-strategy';\n\nconst createBigCommercePaymentsPayLaterCustomerStrategy: CustomerStrategyFactory<\n BigCommercePaymentsPayLaterCustomerStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsPayLaterCustomerStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsPayLaterCustomerStrategy, [\n { id: 'bigcommerce_payments_paylater' },\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsVenmoCustomerInitializeOptions, {\n WithBigCommercePaymentsVenmoCustomerInitializeOptions,\n} from './bigcommerce-payments-venmo-customer-initialize-options';\n\nexport default class BigCommercePaymentsVenmoCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBigCommercePaymentsVenmoCustomerInitializeOptions,\n ): Promise {\n const { bigcommerce_payments_venmo, 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 (!bigcommerce_payments_venmo) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_venmo\" argument is not provided.',\n );\n }\n\n if (!bigcommerce_payments_venmo.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_venmo.container\" argument is not provided.',\n );\n }\n\n if (\n bigcommerce_payments_venmo.onClick &&\n typeof bigcommerce_payments_venmo.onClick !== 'function'\n ) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_venmo.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 const paypalSdk = await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n // eslint-disable-next-line no-console\n console.error(\n '[BC Payments Venmo]: Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n this.renderButton(methodId, bigcommerce_payments_venmo);\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 bigcommerce_payments_venmo: BigCommercePaymentsVenmoCustomerInitializeOptions,\n ): void {\n const { container, onClick } = bigcommerce_payments_venmo;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.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: BigCommercePaymentsButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle({\n ...checkoutTopButtonStyles,\n height: DefaultCheckoutButtonHeight,\n }),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_venmo',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.removeElement(container);\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsVenmoCustomerStrategy from './bigcommerce-payments-venmo-customer-strategy';\n\nconst createBigCommercePaymentsVenmoCustomerStrategy: CustomerStrategyFactory<\n BigCommercePaymentsVenmoCustomerStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsVenmoCustomerStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsVenmoCustomerStrategy, [\n { id: 'bigcommerce_payments_venmo' },\n]);\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 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 {\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 { 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 { 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","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 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 { BraintreePaypalCheckout, BraintreePaypalSdkCreatorConfig } from './braintree';\nimport { BraintreeError } from './types';\n\nlet paypalSdkPromise: Promise | null = null;\n\nexport default function loadPayPalSDKOnce(\n paypalCheckout: BraintreePaypalCheckout,\n config: BraintreePaypalSdkCreatorConfig,\n): Promise {\n if (!paypalSdkPromise) {\n paypalSdkPromise = new Promise((resolve, reject) => {\n paypalCheckout.loadPayPalSDK(config, (err: null | undefined | BraintreeError) => {\n if (err) {\n paypalSdkPromise = null;\n\n reject(err);\n } else {\n resolve(paypalCheckout);\n }\n });\n });\n }\n\n return paypalSdkPromise;\n}\n\n// for testing purposes\nexport function resetLoadPayPalSDKOncePromise() {\n paypalSdkPromise = null;\n}\n","// 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 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 enum MessagingPlacements {\n CART = 'cart',\n HOME = 'homepage',\n PAYMENT = 'payment',\n PRODUCT = 'product',\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 | string;\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';\nimport { isEmpty } from 'lodash';\n\nimport {\n Address,\n CancellablePromise,\n CreditCardInstrument,\n LegacyAddress,\n NonceInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethodCancelledError,\n UnsupportedBrowserError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { Overlay } from '@bigcommerce/checkout-sdk/ui';\n\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport loadPayPalSDKOnce from './load-paypal-sdk-once';\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 BraintreeRequestData,\n BraintreeShippingAddressOverride,\n BraintreeThreeDSecure,\n BraintreeThreeDSecureOptions,\n BraintreeTokenizationDetails,\n BraintreeTokenizePayload,\n BraintreeVenmoCheckout,\n BraintreeVenmoCreatorConfig,\n BraintreeVerifyPayload,\n PAYPAL_COMPONENTS,\n TokenizationPayload,\n} from './types';\nimport isBraintreeError from './utils/is-braintree-error';\nimport isCreditCardInstrumentLike from './utils/is-credit-card-instrument-like';\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 private threeDSecureOptions?: BraintreeThreeDSecureOptions;\n private threeDS?: Promise;\n private venmoCheckout?: BraintreeVenmoCheckout;\n\n constructor(\n private braintreeScriptLoader: BraintreeScriptLoader,\n private braintreeHostWindow: BraintreeHostWindow,\n private overlay?: Overlay,\n ) {}\n\n initialize(clientToken: string, threeDSecureOptions?: BraintreeThreeDSecureOptions) {\n this.clientToken = clientToken;\n this.threeDSecureOptions = threeDSecureOptions;\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 void loadPayPalSDKOnce(braintreePaypalCheckout, paypalSdkLoadConfig).then(\n paypalSdkLoadCallback,\n );\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 async get3DS(): Promise {\n if (!this.threeDS) {\n this.threeDS = Promise.all([\n this.getClient(),\n this.braintreeScriptLoader.load3DS(),\n ]).then(([client, threeDSecure]) => threeDSecure.create({ client, version: 2 }));\n }\n\n return this.threeDS;\n }\n\n async getVenmoCheckout(\n venmoConfig?: BraintreeVenmoCreatorConfig,\n ): Promise {\n if (!this.venmoCheckout) {\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 ...(venmoConfig || {}),\n };\n\n this.venmoCheckout = await new Promise((resolve, reject) => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n venmoCheckout.create(\n venmoCheckoutConfig,\n (error: BraintreeError, braintreeVenmoCheckout: BraintreeVenmoCheckout) => {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (error) {\n return reject(error);\n }\n\n if (!braintreeVenmoCheckout.isBrowserSupported()) {\n return reject(new UnsupportedBrowserError());\n }\n\n resolve(braintreeVenmoCheckout);\n },\n );\n });\n }\n\n return this.venmoCheckout;\n }\n\n /*\n Braintree Credit Card and Braintree Hosted Form\n */\n async verifyCard(\n payment: Payment,\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 async tokenizeCard(payment: Payment, billingAddress: Address): 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.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 challenge3DSVerification(\n tokenizationPayload: TokenizationPayload,\n amount: number,\n ): Promise {\n const threeDSecure = await this.get3DS();\n\n return this.present3DSChallenge(threeDSecure, amount, tokenizationPayload);\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 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 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\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 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 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 // eslint-disable-next-line @typescript-eslint/no-use-before-define\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 if (addFrame) {\n addFrame(error, iframe, cancelVerifyCard);\n }\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","import { CreditCardInstrument } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isCreditCardInstrumentLike(\n instrument: unknown,\n): instrument is CreditCardInstrument {\n if (typeof instrument !== 'object' || instrument === null) {\n return false;\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const creditCardInstrument = instrument as Partial>;\n\n return (\n typeof creditCardInstrument.ccExpiry === 'object' &&\n creditCardInstrument.ccExpiry !== null &&\n typeof creditCardInstrument.ccNumber === 'string' &&\n typeof creditCardInstrument.ccName === 'string'\n );\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 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\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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-initialize-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\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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","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","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 { CookieStorage } 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 ) {}\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.saveSessionIdToCookies(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.removeSessionIdFromCookies();\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.saveSessionIdToCookies(cart.id);\n\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 * Session id management\n *\n */\n getSessionIdFromCookies(): string {\n return CookieStorage.get('bc-fastlane-sessionId') || '';\n }\n\n saveSessionIdToCookies(sessionId: string): void {\n const expires = new Date();\n\n expires.setDate(expires.getDate() + 14); // 2 weeks expiry\n\n CookieStorage.set('bc-fastlane-sessionId', sessionId, {\n expires,\n secure: true,\n });\n }\n\n removeSessionIdFromCookies(): void {\n CookieStorage.remove('bc-fastlane-sessionId');\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, binDetails } = 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: binDetails?.bin || '',\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 BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n );\n const braintreeFastlaneUtils = new BraintreeFastlaneUtils(\n paymentIntegrationService,\n braintreeIntegrationService,\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), hostWindow, braintreeSDKVersionManager),\n );\n\n return new BraintreeVisaCheckoutCustomerStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeSdk,\n );\n};\n\nexport default toResolvableModule(createBraintreeVisaCheckoutCustomerStrategy, [\n { id: 'braintreevisacheckout' },\n]);\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 { isOperaWindow } from '../is-opera-window';\nimport { isReactNativeWindow } from '../is-react-native-window';\n\nexport function isWebView(): boolean {\n if (typeof window === 'undefined') {\n return false;\n }\n\n if (isReactNativeWindow(window)) {\n return true;\n }\n\n const userAgent =\n navigator.userAgent || navigator.vendor || (isOperaWindow(window) ? window.opera : '');\n\n const isAndroidWebView = /android.+; wv/i.test(userAgent);\n const isIOSWebView =\n /iPhone|iPod|iPad/i.test(userAgent) &&\n /AppleWebKit/i.test(userAgent) &&\n !/Safari/i.test(userAgent);\n\n return isAndroidWebView || isIOSWebView;\n}\n","interface ReactNativeWindow extends Window {\n ReactNativeWebView: {\n postMessage(msg: string): void;\n };\n}\n\nexport function isReactNativeWindow(window: Window): window is ReactNativeWindow {\n return 'ReactNativeWebView' in window;\n}\n","interface OperaWindow extends Window {\n opera: string;\n}\n\nexport function isOperaWindow(window: Window): window is OperaWindow {\n return 'opera' in window;\n}\n","import { BigCommercePaymentsIntent } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 offerInfo?: Offers;\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 NewOfferInfo {\n newOfferInfo?: Offers;\n}\n\nexport interface Offers {\n offers: OfferInfoItem[];\n}\n\nexport interface GooglePayError {\n message: string;\n reason: ErrorReasonType;\n intent: CallbackTriggerType;\n}\n\nexport enum ErrorReasonType {\n OFFER_INVALID = 'OFFER_INVALID',\n PAYMENT_DATA_INVALID = 'PAYMENT_DATA_INVALID',\n SHIPPING_ADDRESS_INVALID = 'SHIPPING_ADDRESS_INVALID',\n SHIPPING_ADDRESS_UNSERVICEABLE = 'SHIPPING_ADDRESS_UNSERVICEABLE',\n SHIPPING_OPTION_INVALID = 'SHIPPING_OPTION_INVALID',\n OTHER_ERROR = 'OTHER_ERROR',\n}\n\nexport interface OfferInfoItem {\n redemptionCode: string;\n description: string;\n}\n\nexport interface HandleCouponsOut {\n newOfferInfo: GooglePayPaymentDataRequest['offerInfo'];\n error?: GooglePayError;\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 offerData: {\n redemptionCodes: string[];\n };\n}\n\nexport interface GooglePayPaymentOptions {\n paymentDataCallbacks?: {\n onPaymentDataChanged(\n intermediatePaymentData: IntermediatePaymentData,\n ): onPaymentDataChangedOut;\n };\n}\n\nexport type onPaymentDataChangedOut = Promise<\n | (NewTransactionInfo & NewShippingOptionParameters & NewOfferInfo & { error?: GooglePayError })\n | void\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) => Promise;\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 isWebViewExperimentOn?: boolean;\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 GooglePayBigCommercePaymentsInitializationData\n 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?: BigCommercePaymentsIntent;\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 shopperLanguage: string;\n useNewStripeJsVersion?: boolean;\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 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 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 | GooglePayBigCommercePaymentsInitializationData;\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","/**\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 * A container for loading spinner.\n */\n loadingContainerId?: string;\n\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 BIGCOMMERCE_PAYMENTS = 'googlepay_bigcommerce_payments',\n CHECKOUT_COM = 'googlepaycheckoutcom',\n CYBERSOURCE_V2 = 'googlepaycybersourcev2',\n ORBITAL = 'googlepayorbital',\n STRIPE = 'googlepaystripe',\n STRIPE_UPE = 'googlepaystripeupe',\n STRIPE_OCS = 'googlepaystripeocs',\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 { 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';\nimport { isExperimentEnabled, isWebView } from '@bigcommerce/checkout-sdk/utility';\n\nimport isGooglePayCardNetworkKey from '../guards/is-google-pay-card-network-key';\nimport {\n CallbackIntentsType,\n CallbackTriggerType,\n ErrorReasonType,\n ExtraPaymentData,\n GooglePayCardDataResponse,\n GooglePayCardNetwork,\n GooglePayCardParameters,\n GooglePayError,\n GooglePayFullBillingAddress,\n GooglePayGatewayParameters,\n GooglePayInitializationData,\n GooglePayMerchantInfo,\n GooglePayPaymentDataRequest,\n GooglePayRequiredPaymentData,\n GooglePaySetExternalCheckoutData,\n GooglePayTransactionInfo,\n HandleCouponsOut,\n IntermediatePaymentData,\n ShippingOptionParameters,\n TotalPriceStatusType,\n} from '../types';\n\nexport default class GooglePayGateway {\n private _getPaymentMethodFn?: () => PaymentMethod;\n private _isBuyNowFlow = false;\n private _shouldRequestShipping = true;\n private _currencyCode?: string;\n private _currencyService?: CurrencyService;\n private _isWebViewExperimentOn: null | boolean = null;\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 customFields = [],\n } = this._paymentIntegrationService.getState().getBillingAddress() || {};\n\n return {\n ...this._mapToAddressRequestBody(billingAddress, company, phone, customFields),\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 if (!nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\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 CallbackTriggerType.OFFER,\n ];\n\n const initializationTrigger = [CallbackTriggerType.INITIALIZE];\n const addressChangeTriggers = [\n CallbackTriggerType.INITIALIZE,\n CallbackTriggerType.SHIPPING_ADDRESS,\n ];\n const shippingOptionsChangeTriggers = [CallbackTriggerType.SHIPPING_OPTION];\n const offerChangeTriggers = [CallbackTriggerType.OFFER];\n\n return {\n availableTriggers,\n initializationTrigger,\n addressChangeTriggers,\n shippingOptionsChangeTriggers,\n offerChangeTriggers,\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 const { getCartOrThrow } = this._paymentIntegrationService.getState();\n\n if (this._isBuyNowFlow) {\n currencyCode = this._getCurrencyCodeOrThrow();\n } else {\n currencyCode = getCartOrThrow().currency.code;\n }\n\n const countryCode = this.getGooglePayInitializationData().storeCountry;\n\n if (this.isWebViewWithRestrictions()) {\n const totalPrice = this.getTotalPrice();\n\n return {\n ...(countryCode && { countryCode }),\n currencyCode,\n totalPrice,\n totalPriceStatus: TotalPriceStatusType.ESTIMATED,\n };\n }\n\n return {\n ...(countryCode && { countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.ESTIMATED,\n totalPrice: '0',\n };\n }\n\n isWebViewWithRestrictions(): boolean {\n if (this._isWebViewExperimentOn !== null) {\n return this._isWebViewExperimentOn && isWebView();\n }\n\n return isWebView();\n }\n\n setIsWebViewExperimentOn(isWebViewExperimentOn: boolean): void {\n this._isWebViewExperimentOn = isWebViewExperimentOn;\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, getStoreConfigOrThrow } =\n this._paymentIntegrationService.getState();\n const { decimalPlaces } = getCartOrThrow().currency;\n const isRoundingExperimentOn = isExperimentEnabled(\n getStoreConfigOrThrow().checkoutSettings.features,\n 'PI-5075.google_pay_round_total_price_to_max_2_decimal_places',\n );\n const maxDecimalPlaces = isRoundingExperimentOn\n ? Math.min(decimalPlaces, 2)\n : decimalPlaces;\n const totalPrice = round(getCheckoutOrThrow().outstandingBalance, maxDecimalPlaces).toFixed(\n maxDecimalPlaces,\n );\n\n return totalPrice;\n }\n\n async handleCoupons(\n offerData: IntermediatePaymentData['offerData'],\n ): Promise {\n const { redemptionCodes: newCouponsState = [] } = offerData;\n const { offers: appliedCoupons } = this.getAppliedCoupons() || {};\n let error;\n\n await newCouponsState.reduce(async (promise, code) => {\n await promise;\n\n const exists = (appliedCoupons || []).some(\n ({ redemptionCode }) => redemptionCode === code,\n );\n\n if (exists) {\n return;\n }\n\n const appliedCouponError = await this.applyCoupon(code);\n\n if (appliedCouponError) {\n error = appliedCouponError;\n }\n }, Promise.resolve());\n\n await (appliedCoupons || []).reduce(async (promise, coupon) => {\n await promise;\n\n const stillExists = newCouponsState.includes(coupon.redemptionCode);\n\n if (!stillExists) {\n await this._paymentIntegrationService.removeCoupon(coupon.redemptionCode);\n }\n }, Promise.resolve());\n\n return {\n newOfferInfo: this.getAppliedCoupons(),\n error,\n };\n }\n\n getAppliedCoupons(): GooglePayPaymentDataRequest['offerInfo'] {\n const state = this._paymentIntegrationService.getState();\n const { coupons } = state.getCheckout() || {};\n\n const offers = (coupons || []).map((coupon) => {\n const { displayName, code } = coupon;\n\n return {\n redemptionCode: code,\n description: displayName,\n };\n });\n\n return {\n offers,\n };\n }\n\n async applyCoupon(code: string): Promise {\n let error: GooglePayError | undefined;\n\n try {\n await this._paymentIntegrationService.applyCoupon(code);\n } catch (e) {\n if (e instanceof Error) {\n error = {\n reason: ErrorReasonType.OFFER_INVALID,\n message: e.message,\n intent: CallbackTriggerType.OFFER,\n };\n }\n\n return error;\n }\n }\n\n setShouldRequestShipping(isRequired: boolean): void {\n this._shouldRequestShipping = isRequired;\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, getStoreConfigOrThrow, getShippingAddress } =\n this._paymentIntegrationService.getState();\n const storeConfig = getStoreConfigOrThrow();\n const features = storeConfig.checkoutSettings.features;\n const checkWithExperiment = isExperimentEnabled(\n features,\n 'PI-4290.google_pay_require_shipping_address',\n );\n\n let shippingContextRequiresCheck: boolean;\n\n if (checkWithExperiment) {\n shippingContextRequiresCheck = this._shouldRequestShipping;\n } else {\n shippingContextRequiresCheck = getShippingAddress() === undefined;\n }\n\n return shippingContextRequiresCheck && itemsRequireShipping(getCartOrThrow(), storeConfig);\n }\n\n private _mapToAddressRequestBody(\n address: GooglePayFullBillingAddress,\n company: string,\n phone: string,\n customFields?: AddressRequestBody['customFields'],\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: 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({\n id,\n cost,\n description,\n additionalDescription,\n }: ShippingOption) {\n const formattedCost = this._currencyService?.toCustomerCurrency(cost);\n\n return {\n id,\n label: `${formattedCost || cost} ${description}`,\n description: additionalDescription,\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","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 GooglePayError,\n GooglePayInitializationData,\n GooglePayPaymentOptions,\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 this._googlePayPaymentProcessor.setIsWebViewExperimentOn(\n !!paymentMethod.initializationData?.isWebViewExperimentOn,\n );\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 if (this._googlePayPaymentProcessor.isWebViewWithRestrictions()) {\n return {};\n }\n\n return {\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({\n callbackTrigger,\n shippingAddress,\n shippingOptionData,\n offerData,\n }) => {\n const {\n availableTriggers,\n addressChangeTriggers,\n shippingOptionsChangeTriggers,\n offerChangeTriggers,\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 const { newOfferInfo = undefined, error: couponsError = undefined } =\n offerChangeTriggers.includes(callbackTrigger)\n ? await this._googlePayPaymentProcessor.handleCoupons(offerData)\n : {};\n\n // We can add another errors if needed 'couponsError || shippingError || anotherError'\n const error: GooglePayError | undefined = couponsError;\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 ...(newOfferInfo && {\n newOfferInfo,\n }),\n ...(error && {\n error,\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) => Promise {\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\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","import { FormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\n\nimport {\n AddressRequestBody,\n BillingAddressRequestBody,\n guard,\n NotInitializedError,\n NotInitializedErrorType,\n Omit,\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 HandleCouponsOut,\n IntermediatePaymentData,\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 | undefined {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n return;\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 setShouldRequestShipping(isRequired: boolean): void {\n return this._gateway.setShouldRequestShipping(isRequired);\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 async handleCoupons(\n offerData: IntermediatePaymentData['offerData'],\n ): Promise {\n return this._gateway.handleCoupons(offerData);\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 isWebViewWithRestrictions(): boolean {\n return this._gateway.isWebViewWithRestrictions();\n }\n\n setIsWebViewExperimentOn(isWebViewExperimentOn: boolean): void {\n return this._gateway.setIsWebViewExperimentOn(isWebViewExperimentOn);\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\n const isWebViewLogic = this._gateway.isWebViewWithRestrictions()\n ? {\n shippingOptionRequired: false,\n }\n : {\n callbackIntents: this._gateway.getCallbackIntents(),\n offerInfo: this._gateway.getAppliedCoupons(),\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 ...isWebViewLogic,\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","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 { PaymentMethod } from '@bigcommerce/checkout-sdk/payment-integration-api';\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\n/**\n * The PaymentIntent object.\n */\nexport interface PaymentIntent {\n /**\n * Unique identifier for the object.\n */\n id: string;\n\n /**\n * The client secret of the PaymentIntent. Used for client-side retrieval using a publishable key.\n */\n client_secret?: 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 payment_method_options?: StripePIPaymentMethodOptions;\n}\n\nexport interface StripePIPaymentMethodSavingOptions {\n setup_future_usage?: StripeInstrumentSetupFutureUsage;\n verification_method?: string;\n}\n\nexport interface StripePIPaymentMethodOptions {\n card?: StripePIPaymentMethodSavingOptions;\n us_bank_account?: StripePIPaymentMethodSavingOptions;\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 * 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 StripeCustomFont = CssFontSource | CustomFontSource;\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 StripeCheckoutSessionConfirmationError {\n code?: string;\n message: string;\n paymentFailed?: {\n declineCode?: string;\n };\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: StripeElementEvent, 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\nexport interface StripeCurrencyEvent extends StripeEvent {\n value: {\n currency: string;\n };\n}\n\nexport interface 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 =\n | StripeCurrencyEvent\n | StripeShippingEvent\n | StripeCustomerEvent\n | StripePaymentEvent\n | StripeLinkV2Event;\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
& { country: string };\n\nexport interface StripeAddressValues {\n name?: string;\n address?: AddressOptions;\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 allow_redisplay?: 'always' | 'limited' | 'unspecified';\n}\n\n/**\n * Parameters that will be passed on to the Stripe API to confirm the PaymentIntent.\n */\nexport interface StripeConfirmParams {\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?: StripeConfirmParams;\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 clientSecret?: string;\n}\n\nexport interface StripeCheckoutSessionConfirmPaymentData {\n redirect?: StripeStringConstants.ALWAYS | StripeStringConstants.IF_REQUIRED;\n returnUrl?: string;\n}\n\nexport interface FieldsOptions {\n billingDetails?: AutoOrNever | BillingDetailsProperties;\n phone?: string;\n}\n\nexport interface WalletOptions {\n applePay?: AutoOrNever;\n googlePay?: AutoOrNever;\n link?: AutoOrNever;\n}\n\nexport interface TermOptions {\n card?: AutoOrNever;\n}\n\nexport interface StripeLayoutOptions {\n type?: 'accordion' | 'tabs';\n linkInAccordion?: boolean;\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 | PaymentDefaultValues;\n validation?: validationElement;\n display?: { name: StripeDisplayName };\n terms?: TermOptions;\n layout?: StripeLayoutOptions;\n paymentMethodOrder?: string[];\n // Link v2 options\n lineItems?: LineItem[];\n allowedShippingCountries?: string[];\n shippingAddressRequired?: boolean;\n shippingRates?: StripeLinkV2ShippingRate[];\n billingAddressRequired?: boolean;\n emailRequired?: boolean;\n phoneNumberRequired?: boolean;\n paymentMethods?: {\n link: StripeStringConstants.AUTO;\n applePay: StripeStringConstants.NEVER;\n googlePay: StripeStringConstants.NEVER;\n amazonPay: StripeStringConstants.NEVER;\n paypal: StripeStringConstants.NEVER;\n klarna: StripeStringConstants.NEVER;\n };\n buttonHeight?: number;\n savePaymentMethod?: StripeSavePaymentMethod;\n}\n\ninterface validationElement {\n phone?: validationRequiredElement;\n}\n\ninterface validationRequiredElement {\n required?: string;\n}\n\ninterface PaymentDefaultValues {\n savePaymentMethod?: boolean;\n billingDetails?: BillingDetailsOptions;\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 StripeDisplayName {\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: StripeDisplayName;\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\nexport enum StripeCheckoutSessionStatusType {\n Open = 'open',\n Expired = 'expired',\n Complete = 'complete',\n}\n\nexport enum StripeCheckoutSessionPaymentStatus {\n Paid = 'paid',\n UnPaid = 'unpaid',\n NoPaymentRequired = 'no_payment_required',\n}\n\nexport interface StripeCheckoutSessionStatus {\n type: StripeCheckoutSessionStatusType;\n paymentStatus: StripeCheckoutSessionPaymentStatus;\n}\n\nexport interface StripeCheckoutSessionAmount {\n minorUnitsAmount: number;\n amount: string;\n}\n\nexport interface StripeCheckoutSessionTotal {\n appliedBalance: StripeCheckoutSessionAmount;\n balanceAppliedToNextInvoice: boolean;\n discount: StripeCheckoutSessionAmount;\n shippingRate: StripeCheckoutSessionAmount;\n subtotal: StripeCheckoutSessionAmount;\n taxExclusive: StripeCheckoutSessionAmount;\n taxInclusive: StripeCheckoutSessionAmount;\n total: StripeCheckoutSessionAmount;\n}\n\nexport interface StripeCheckoutSession {\n id: string;\n savedPaymentMethods?: StripeSavedPaymentMethod[];\n billingAddress: StripeAddressValues;\n businessName: string;\n canConfirm: boolean;\n currency: string;\n email: string;\n phoneNumber: string;\n shipping: unknown;\n shippingAddress: StripeAddressValues;\n shippingOptions: unknown;\n status: StripeCheckoutSessionStatus;\n tax: unknown;\n taxAmounts: unknown;\n total: StripeCheckoutSessionTotal;\n}\n\nexport interface StripeCheckoutInstance {\n loadActions(): Promise;\n createPaymentElement(options?: StripeElementsCreateOptions): StripeElement;\n getPaymentElement(): StripeElement | null;\n getCurrencySelectorElement(): StripeElement | null;\n createCurrencySelectorElement(): StripeElement;\n}\n\nexport enum StripeLoadActionsResultType {\n SUCCESS = 'success',\n ERROR = 'error',\n}\n\nexport interface StripeLoadActionsResult {\n type: StripeLoadActionsResultType;\n error?: { message: string };\n actions?: StripeCheckoutSessionActions;\n}\n\nexport interface StripeCheckoutSessionActionResult {\n type: StripeLoadActionsResultType;\n error?: StripeCheckoutSessionConfirmationError;\n session?: StripeCheckoutSession;\n}\n\nexport interface StripeCheckoutSessionActions {\n updateEmail(email: string): Promise;\n updateShippingAddress(\n shippingAddress: StripeAddressValues,\n ): Promise;\n updateBillingAddress(\n billingAddress: StripeAddressValues,\n ): Promise;\n getSession(): Promise;\n confirm(\n options: StripeCheckoutSessionConfirmPaymentData,\n ): Promise;\n}\n\nexport interface StripeSavedPaymentMethod {\n id: string;\n type: string;\n billingDetails: BillingDetailsOptions;\n card?: StripeCardDetails;\n usBankAccount?: StripeUsBankAccountDetails;\n}\n\nexport interface StripeCardDetails {\n brand: string;\n last4: string;\n expMonth: number;\n expYear: number;\n}\n\nexport interface StripeUsBankAccountDetails {\n accountHolderType: string;\n accountType: string;\n bankName: string;\n last4: string;\n}\n\n/**\n * All available options are here https://stripe.com/docs/stripe-js/appearance-api#supported-css-properties\n */\nexport interface StripeAppearanceOptions {\n variables?: Record;\n\n rules?: Record>;\n}\n\nexport type StripeAppearanceValues = string | string[] | number | undefined;\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?: StripeCustomFont[];\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 * A token that represents the Stripe customer session.\n * Stripe documentation: https://docs.stripe.com/api/checkout/sessions\n */\n customerSessionClientSecret?: 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?: StripeAppearanceOptions;\n\n mode?: string;\n amount?: number;\n currency?: string;\n paymentMethodTypes?: string[];\n}\n\nexport interface StripeInitCheckoutOptions {\n clientSecret: string;\n elementsOptions?: StripeCheckoutSessionElementOptions;\n adaptivePricing?: {\n allowed: boolean;\n };\n defaultValues?: StripeCheckoutSessionDefaultValues;\n wallets?: any;\n}\n\nexport interface StripeCheckoutSessionElementOptions {\n appearance?: StripeAppearanceOptions;\n loader?: StripeStringConstants;\n fonts?: StripeCustomFont[];\n savedPaymentMethod?: {\n enableRedisplay?: StripeStringConstants;\n enableSave?: StripeStringConstants;\n };\n}\n\nexport interface StripeCheckoutSessionDefaultValues {\n billingAddress?: StripeAddressValues;\n shippingAddress?: StripeAddressValues;\n email?: string;\n phoneNumber?: 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?: StripeAppearanceOptions;\n mode?: string;\n amount?: number;\n currency?: string;\n}\n\nexport interface StripeClient {\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 initCheckout(options: StripeInitCheckoutOptions): Promise;\n}\n\nexport interface StripeResult {\n paymentIntent?: PaymentIntent;\n error?: StripeError;\n}\n\nexport interface StripeHostWindow extends Window {\n bcStripeClient?: StripeClient;\n bcStripeElements?: StripeElements;\n bcStripeCheckout?: StripeCheckoutInstance;\n Stripe?(\n stripePublishableKey: string,\n options?: StripeConfigurationOptions,\n ): T;\n}\n\nexport enum StripePaymentMethodType {\n CreditCard = 'card',\n ACH = 'us_bank_account',\n Link = 'link',\n EPS = 'eps',\n GRABPAY = 'grabpay',\n BANCONTACT = 'bancontact',\n IDEAL = 'ideal',\n ALIPAY = 'alipay',\n KLARNA = 'klarna',\n OCS = 'optimized_checkout',\n CHECKOUT_SESSION = 'checkout_session',\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 StripeJsVersion {\n V3 = 'v3',\n ACACIA = 'acacia',\n BASIL = 'basil',\n CLOVER = 'clover',\n}\n\nexport enum StripeElementType {\n PAYMENT = 'payment',\n AUTHENTICATION = 'linkAuthentication',\n SHIPPING = 'address',\n EXPRESS_CHECKOUT = 'expressCheckout',\n}\n\nexport enum StripePaymentIntentStatus {\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 StripePaymentMethod extends PaymentMethod {\n initializationData: StripeInitializationData;\n}\n\nexport interface StripeInitializationData {\n stripePublishableKey: string;\n stripeConnectedAccount: string;\n shopperLanguage: string;\n customerSessionToken?: string;\n enableLink?: boolean;\n allowRedisplayForStoredInstruments?: boolean;\n captureMethod?: 'automatic' | 'manual';\n useNewStripeJsVersion?: boolean;\n checkoutSessionEnabled?: boolean;\n sendSecondPaymentRequestOnStripeError?: boolean;\n adaptivePricingEnabled?: boolean;\n hasSectionOnTopOfPaymentsList?: 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\nexport enum StripeElementEvent {\n CLICK = 'click',\n CHANGE = 'change',\n READY = 'ready',\n SHIPPING_ADDRESS_CHANGE = 'shippingaddresschange',\n SHIPPING_RATE_CHANGE = 'shippingratechange',\n CONFIRM = 'confirm',\n CANCEL = 'cancel',\n LOADER_START = 'loaderstart',\n}\n\nexport interface LineItem {\n name: string;\n amount: number;\n}\n\nexport interface StripeSavePaymentMethod {\n maxVisiblePaymentMethods?: number;\n}\n\nexport enum StripeInstrumentSetupFutureUsage {\n ON_SESSION = 'on_session',\n OFF_SESSION = 'off_session',\n}\n\nexport interface StripeLinkV2Event {\n value?: null;\n billingDetails?: {\n name?: string;\n email?: string;\n phone?: string;\n address?: {\n line1?: string;\n city?: string;\n country?: string;\n postal_code?: string;\n state?: string;\n };\n };\n shippingAddress?: {\n name?: string;\n address?: {\n line1?: string;\n line2?: string;\n city?: string;\n country?: string;\n postal_code?: string;\n state?: string;\n };\n };\n address?: {\n line1?: string;\n city?: string;\n country?: string;\n postal_code?: string;\n state?: string;\n };\n shippingRate?: StripeLinkV2ShippingRate;\n elementType: string;\n expressPaymentType: string;\n resolve(data: StripeLinkV2EventResolveData): void;\n reject(): void;\n}\n\nexport interface StripeLinkV2EventResolveData {\n lineItems?: LineItem[];\n allowedShippingCountries?: string[];\n shippingAddressRequired?: boolean;\n shippingRates?: StripeLinkV2ShippingRate[];\n billingAddressRequired?: boolean;\n emailRequired?: boolean;\n phoneNumberRequired?: boolean;\n}\n\nexport interface StripeLinkV2ShippingRate {\n id: string;\n amount: number;\n displayName: string;\n}\n\nexport interface StripeLinkV2Options {\n clientSecret?: string;\n mode?: string;\n currency?: string;\n captureMethod?: 'automatic' | 'manual';\n amount?: number;\n}\n\nexport interface StripeFormattedPaymentPayload {\n cart_id: string;\n confirm: boolean;\n method?: string;\n credit_card_token?: { token: string };\n tokenized_ach?: { token: string };\n vault_payment_instrument?: boolean;\n set_as_default_stored_instrument?: boolean;\n client_side_error?: boolean;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n StripeCheckoutInstance,\n StripeClient,\n StripeElements,\n StripeElementsOptions,\n StripeHostWindow,\n StripeInitCheckoutOptions,\n StripeInitializationData,\n StripeJsVersion,\n} from './stripe';\n\nexport default class StripeScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private stripeWindow: StripeHostWindow = window,\n ) {}\n\n async getStripeClient(\n initializationData: StripeInitializationData,\n locale?: string,\n stripeJsVersion?: string,\n betas?: string[],\n apiVersion?: string,\n ): Promise {\n if (this.stripeWindow.bcStripeClient) {\n return this.stripeWindow.bcStripeClient;\n }\n\n const stripe = await this.load(stripeJsVersion);\n const { stripePublishableKey, stripeConnectedAccount } = initializationData;\n const options = {\n ...(stripeConnectedAccount ? { stripeAccount: stripeConnectedAccount } : {}),\n ...(locale ? { locale } : {}),\n ...(betas ? { betas } : {}),\n ...(apiVersion ? { apiVersion } : {}),\n };\n\n const stripeClient = stripe(stripePublishableKey, options);\n\n Object.assign(this.stripeWindow, { bcStripeClient: stripeClient });\n\n return stripeClient;\n }\n\n async getElements(\n stripeClient: StripeClient,\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 async getStripeCheckout(\n stripeClient: StripeClient,\n options: StripeInitCheckoutOptions,\n ): Promise {\n let stripeCheckout = await this.getStoredStripeCheckout(options);\n\n if (!stripeCheckout) {\n stripeCheckout = await stripeClient.initCheckout(options);\n\n Object.assign(this.stripeWindow, { bcStripeCheckout: stripeCheckout });\n }\n\n return stripeCheckout;\n }\n\n private async load(stripeJsVersion?: string) {\n if (!this.stripeWindow.Stripe) {\n await this.scriptLoader.loadScript(this.getScriptUrl(stripeJsVersion));\n\n if (!this.stripeWindow.Stripe) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.stripeWindow.Stripe;\n }\n\n private getScriptUrl(stripeJsVersion?: string) {\n if (!stripeJsVersion || stripeJsVersion === StripeJsVersion.V3) {\n return 'https://js.stripe.com/v3/';\n }\n\n return `https://js.stripe.com/${stripeJsVersion}/stripe.js`;\n }\n\n private async getStoredStripeCheckout(\n options: StripeInitCheckoutOptions,\n ): Promise {\n const stripeCheckout = this.stripeWindow.bcStripeCheckout;\n\n if (!stripeCheckout) {\n return undefined;\n }\n\n try {\n const { actions, error } = await stripeCheckout.loadActions();\n\n if (error || !actions) {\n this.logErrorToConsole(error);\n\n return undefined;\n }\n\n const stripeCheckoutSession = await actions.getSession();\n const stripeSessionIdFromOptions = options.clientSecret.split('_secret_')[0];\n\n if (stripeCheckoutSession.id === stripeSessionIdFromOptions) {\n return stripeCheckout;\n }\n } catch (error) {\n this.logErrorToConsole(error);\n\n return undefined;\n }\n\n return undefined;\n }\n\n private logErrorToConsole(error?: unknown) {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n error\n ? console.error(error)\n : console.error('No stripe checkout actions available on loadActions().');\n }\n}\n","export const STRIPE_UPE_CLIENT_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\nexport const STRIPE_UPE_CLIENT_API_VERSION = '2020-03-02;alipay_beta=v1;link_beta=v1';\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';\nimport {\n STRIPE_UPE_CLIENT_API_VERSION,\n STRIPE_UPE_CLIENT_BETAS,\n StripeJsVersion,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\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 GooglePayStripeInitializationData,\n} from '../types';\n\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: StripeScriptLoader,\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 shouldTrigger3DS = some(error.body.errors, { code: 'three_d_secure_required' });\n\n if (shouldTrigger3DS) {\n const initialization = this.getGooglePayInitializationData();\n\n assertsIsGooglePayStripeInitializationData(initialization);\n\n this.stripeUPEClient = await this.loadStripeJs(initialization, methodId);\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 initializationData: GooglePayStripeInitializationData,\n methodId: string,\n ): Promise {\n if (this.stripeUPEClient) {\n return this.stripeUPEClient;\n }\n\n const locale = this.paymentIntegrationService.getState().getCartLocale();\n\n if (methodId === 'googlepaystripeocs' && !!initializationData.useNewStripeJsVersion) {\n return this.scriptLoader.getStripeClient(\n initializationData,\n locale,\n StripeJsVersion.CLOVER,\n );\n }\n\n return this.scriptLoader.getStripeClient(\n initializationData,\n locale,\n StripeJsVersion.V3,\n STRIPE_UPE_CLIENT_BETAS,\n STRIPE_UPE_CLIENT_API_VERSION,\n );\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 { 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';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\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';\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 StripeScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayStripeCustomerStrategy, [\n { id: 'googlepaystripe' },\n { id: 'googlepaystripeocs' },\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';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\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';\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 StripeScriptLoader(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","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 { GooglePayKey } from '../google-pay-payment-initialize-options';\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 private _methodId = GooglePayKey.BRAINTREE;\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 let paymentMethod = super.getPaymentMethod();\n\n if (!paymentMethod.clientToken) {\n const state = await this._service.loadPaymentMethod(this._methodId);\n\n paymentMethod = state.getPaymentMethodOrThrow(this._methodId);\n }\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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","export const LOADING_INDICATOR_STYLES = {\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\n};\n\n/**\n * PayPal SDK supported locales\n * https://developer.paypal.com/sdk/js/configuration/#link-locale\n */\nexport const PAYPAL_SDK_SUPPORTED_LOCALES = [\n 'ar_BH',\n 'ar_DZ',\n 'ar_EG',\n 'ar_JO',\n 'ar_KW',\n 'ar_MA',\n 'ar_OM',\n 'ar_QA',\n 'ar_SA',\n 'ar_TN',\n 'ar_YE',\n 'ar_AE',\n 'bg_BG',\n 'cs_CZ',\n 'da_DK',\n 'da_FO',\n 'da_GL',\n 'de_AT',\n 'de_CH',\n 'de_DE',\n 'de_LU',\n 'el_GR',\n 'en_AD',\n 'en_AE',\n 'en_AG',\n 'en_AI',\n 'en_AL',\n 'en_AM',\n 'en_AN',\n 'en_AO',\n 'en_AT',\n 'en_AU',\n 'en_AW',\n 'en_AZ',\n 'en_BB',\n 'en_BE',\n 'en_BH',\n 'en_BJ',\n 'en_BM',\n 'en_BN',\n 'en_BS',\n 'en_BT',\n 'en_BW',\n 'en_BY',\n 'en_BZ',\n 'en_C2',\n 'en_CA',\n 'en_CD',\n 'en_CG',\n 'en_CH',\n 'en_CI',\n 'en_CK',\n 'en_CL',\n 'en_CM',\n 'en_CN',\n 'en_CO',\n 'en_CR',\n 'en_CV',\n 'en_CY',\n 'en_CZ',\n 'en_DE',\n 'en_DJ',\n 'en_DK',\n 'en_DM',\n 'en_DO',\n 'en_DZ',\n 'en_EC',\n 'en_EE',\n 'en_EG',\n 'en_ER',\n 'en_ES',\n 'en_ET',\n 'en_FI',\n 'en_FJ',\n 'en_FK',\n 'en_FM',\n 'en_FO',\n 'en_FR',\n 'en_GA',\n 'en_GB',\n 'en_GD',\n 'en_GE',\n 'en_GF',\n 'en_GI',\n 'en_GL',\n 'en_GM',\n 'en_GN',\n 'en_GP',\n 'en_GR',\n 'en_GT',\n 'en_GW',\n 'en_GY',\n 'en_HK',\n 'en_HN',\n 'en_HR',\n 'en_HU',\n 'en_ID',\n 'en_IE',\n 'en_IL',\n 'en_IN',\n 'en_IS',\n 'en_IT',\n 'en_JM',\n 'en_JO',\n 'en_JP',\n 'en_KE',\n 'en_KG',\n 'en_KH',\n 'en_KI',\n 'en_KM',\n 'en_KN',\n 'en_KR',\n 'en_KW',\n 'en_KY',\n 'en_KZ',\n 'en_LA',\n 'en_LC',\n 'en_LI',\n 'en_LK',\n 'en_LS',\n 'en_LT',\n 'en_LU',\n 'en_LV',\n 'en_MA',\n 'en_MC',\n 'en_MD',\n 'en_ME',\n 'en_MG',\n 'en_MH',\n 'en_MK',\n 'en_ML',\n 'en_MN',\n 'en_MQ',\n 'en_MR',\n 'en_MS',\n 'en_MT',\n 'en_MU',\n 'en_MV',\n 'en_MW',\n 'en_MY',\n 'en_MZ',\n 'en_NA',\n 'en_NC',\n 'en_NE',\n 'en_NF',\n 'en_NG',\n 'en_NI',\n 'en_NL',\n 'en_NO',\n 'en_NP',\n 'en_NR',\n 'en_NU',\n 'en_NZ',\n 'en_OM',\n 'en_PA',\n 'en_PE',\n 'en_PF',\n 'en_PG',\n 'en_PH',\n 'en_PL',\n 'en_PM',\n 'en_PN',\n 'en_PT',\n 'en_PW',\n 'en_PY',\n 'en_QA',\n 'en_RE',\n 'en_RO',\n 'en_RS',\n 'en_RU',\n 'en_RW',\n 'en_SA',\n 'en_SB',\n 'en_SC',\n 'en_SE',\n 'en_SG',\n 'en_SH',\n 'en_SI',\n 'en_SJ',\n 'en_SK',\n 'en_SL',\n 'en_SM',\n 'en_SN',\n 'en_SO',\n 'en_SR',\n 'en_ST',\n 'en_SV',\n 'en_SZ',\n 'en_TC',\n 'en_TD',\n 'en_TG',\n 'en_TH',\n 'en_TJ',\n 'en_TM',\n 'en_TN',\n 'en_TO',\n 'en_TR',\n 'en_TT',\n 'en_TV',\n 'en_TW',\n 'en_TZ',\n 'en_UA',\n 'en_UG',\n 'en_US',\n 'en_UY',\n 'en_VA',\n 'en_VC',\n 'en_VE',\n 'en_VG',\n 'en_VN',\n 'en_VU',\n 'en_WF',\n 'en_WS',\n 'en_YE',\n 'en_YT',\n 'en_ZA',\n 'en_ZM',\n 'en_ZW',\n 'es_AD',\n 'es_AI',\n 'es_AO',\n 'es_AR',\n 'es_AW',\n 'es_BB',\n 'es_BJ',\n 'es_BM',\n 'es_BO',\n 'es_BS',\n 'es_BZ',\n 'es_CD',\n 'es_CG',\n 'es_CK',\n 'es_CL',\n 'es_CO',\n 'es_CR',\n 'es_CV',\n 'es_DJ',\n 'es_DM',\n 'es_DO',\n 'es_DZ',\n 'es_EC',\n 'es_EG',\n 'es_ER',\n 'es_ES',\n 'es_ET',\n 'es_FJ',\n 'es_FK',\n 'es_FO',\n 'es_GA',\n 'es_GD',\n 'es_GE',\n 'es_GI',\n 'es_GL',\n 'es_GM',\n 'es_GN',\n 'es_GT',\n 'es_GW',\n 'es_GY',\n 'es_HN',\n 'es_IE',\n 'es_JM',\n 'es_JO',\n 'es_KE',\n 'es_KG',\n 'es_KI',\n 'es_KM',\n 'es_KN',\n 'es_KW',\n 'es_KY',\n 'es_KZ',\n 'es_LC',\n 'es_LI',\n 'es_LS',\n 'es_LU',\n 'es_MA',\n 'es_MG',\n 'es_MH',\n 'es_ML',\n 'es_MR',\n 'es_MS',\n 'es_MU',\n 'es_MW',\n 'es_MX',\n 'es_MZ',\n 'es_NA',\n 'es_NC',\n 'es_NE',\n 'es_NF',\n 'es_NI',\n 'es_NR',\n 'es_NU',\n 'es_NZ',\n 'es_OM',\n 'es_PA',\n 'es_PE',\n 'es_PF',\n 'es_PG',\n 'es_PM',\n 'es_PN',\n 'es_PW',\n 'es_PY',\n 'es_QA',\n 'es_RS',\n 'es_RW',\n 'es_SA',\n 'es_SB',\n 'es_SC',\n 'es_SH',\n 'es_SJ',\n 'es_SL',\n 'es_SM',\n 'es_SN',\n 'es_SO',\n 'es_SR',\n 'es_ST',\n 'es_SV',\n 'es_SZ',\n 'es_TC',\n 'es_TD',\n 'es_TG',\n 'es_TJ',\n 'es_TM',\n 'es_TN',\n 'es_TT',\n 'es_TV',\n 'es_UA',\n 'es_UG',\n 'es_US',\n 'es_UY',\n 'es_VA',\n 'es_VC',\n 'es_VE',\n 'es_VG',\n 'es_VU',\n 'es_WF',\n 'es_YE',\n 'es_ZM',\n 'et_EE',\n 'fi_FI',\n 'fr_AD',\n 'fr_AE',\n 'fr_AI',\n 'fr_AM',\n 'fr_AO',\n 'fr_AW',\n 'fr_AZ',\n 'fr_BB',\n 'fr_BE',\n 'fr_BF',\n 'fr_BI',\n 'fr_BJ',\n 'fr_BM',\n 'fr_BS',\n 'fr_BZ',\n 'fr_CA',\n 'fr_CD',\n 'fr_CG',\n 'fr_CH',\n 'fr_CI',\n 'fr_CK',\n 'fr_CM',\n 'fr_CV',\n 'fr_DJ',\n 'fr_DM',\n 'fr_DO',\n 'fr_DZ',\n 'fr_EC',\n 'fr_ER',\n 'fr_ET',\n 'fr_FJ',\n 'fr_FK',\n 'fr_FO',\n 'fr_FR',\n 'fr_GA',\n 'fr_GD',\n 'fr_GE',\n 'fr_GF',\n 'fr_GI',\n 'fr_GL',\n 'fr_GM',\n 'fr_GN',\n 'fr_GP',\n 'fr_GT',\n 'fr_GW',\n 'fr_GY',\n 'fr_HN',\n 'fr_IE',\n 'fr_JM',\n 'fr_JO',\n 'fr_KE',\n 'fr_KG',\n 'fr_KI',\n 'fr_KM',\n 'fr_KN',\n 'fr_KW',\n 'fr_KY',\n 'fr_KZ',\n 'fr_LC',\n 'fr_LI',\n 'fr_LS',\n 'fr_LU',\n 'fr_MA',\n 'fr_MC',\n 'fr_MG',\n 'fr_MH',\n 'fr_ML',\n 'fr_MQ',\n 'fr_MR',\n 'fr_MS',\n 'fr_MU',\n 'fr_MW',\n 'fr_MZ',\n 'fr_NA',\n 'fr_NC',\n 'fr_NE',\n 'fr_NF',\n 'fr_NI',\n 'fr_NR',\n 'fr_NU',\n 'fr_NZ',\n 'fr_OM',\n 'fr_PA',\n 'fr_PE',\n 'fr_PF',\n 'fr_PG',\n 'fr_PM',\n 'fr_PN',\n 'fr_PW',\n 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'zh_GD',\n 'zh_GE',\n 'zh_GI',\n 'zh_GL',\n 'zh_GM',\n 'zh_GN',\n 'zh_GT',\n 'zh_GW',\n 'zh_GY',\n 'zh_HN',\n 'zh_IE',\n 'zh_JM',\n 'zh_JO',\n 'zh_KE',\n 'zh_KG',\n 'zh_KI',\n 'zh_KM',\n 'zh_KN',\n 'zh_KW',\n 'zh_KY',\n 'zh_KZ',\n 'zh_LC',\n 'zh_LI',\n 'zh_LS',\n 'zh_LT',\n 'zh_LU',\n 'zh_MA',\n 'zh_MG',\n 'zh_MH',\n 'zh_ML',\n 'zh_MR',\n 'zh_MS',\n 'zh_MU',\n 'zh_MW',\n 'zh_MZ',\n 'zh_NA',\n 'zh_NC',\n 'zh_NE',\n 'zh_NF',\n 'zh_NI',\n 'zh_NR',\n 'zh_NU',\n 'zh_NZ',\n 'zh_OM',\n 'zh_PA',\n 'zh_PE',\n 'zh_PF',\n 'zh_PG',\n 'zh_PM',\n 'zh_PN',\n 'zh_PW',\n 'zh_QA',\n 'zh_RS',\n 'zh_RW',\n 'zh_SA',\n 'zh_SB',\n 'zh_SC',\n 'zh_SH',\n 'zh_SJ',\n 'zh_SL',\n 'zh_SM',\n 'zh_SN',\n 'zh_SO',\n 'zh_SR',\n 'zh_ST',\n 'zh_SV',\n 'zh_SZ',\n 'zh_TC',\n 'zh_TD',\n 'zh_TG',\n 'zh_TJ',\n 'zh_TM',\n 'zh_TN',\n 'zh_TT',\n 'zh_TV',\n 'zh_UA',\n 'zh_UG',\n 'zh_US',\n 'zh_UY',\n 'zh_VA',\n 'zh_VC',\n 'zh_VE',\n 'zh_VG',\n 'zh_VU',\n 'zh_WF',\n 'zh_YE',\n 'zh_ZA',\n 'zh_ZM',\n];\n","import { PAYPAL_SDK_SUPPORTED_LOCALES } from '../paypal-commerce-constants';\n\n/**\n * Transforms store language to PayPal SDK locale format.\n * PayPal SDK expects locale in format 'en_US' (underscore separator).\n * Returns undefined if the locale is not supported by PayPal SDK.\n * Examples: 'fr-CA' -> 'fr_CA', 'fr' -> 'fr_FR'\n */\nexport default function transformLocaleToPayPalFormat(\n storeLanguage: string | undefined,\n): string | undefined {\n if (!storeLanguage) {\n return undefined;\n }\n\n let locale: string;\n\n if (storeLanguage.includes('-')) {\n const [language, region] = storeLanguage.split('-');\n\n locale = `${language}_${region.toUpperCase()}`;\n } else {\n locale = `${storeLanguage}_${storeLanguage.toUpperCase()}`;\n }\n\n return PAYPAL_SDK_SUPPORTED_LOCALES.includes(locale) ? locale : undefined;\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';\nimport { transformLocaleToPayPalFormat } from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport {\n PayPalCommerceHostWindow,\n PayPalCommerceInitializationData,\n PayPalFastlaneSdk,\n PayPalGooglePaySdk,\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 storeLanguage: string | undefined,\n ): Promise {\n if (!this.window.paypalFastlaneSdk) {\n const config = this.getPayPalFastlaneSdkConfiguration(\n paymentMethod,\n currencyCode,\n sessionId,\n storeLanguage,\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 getPayPalGooglePaySdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n if (!this.window.paypalGooglePay || forceLoad) {\n const paypalSdkScriptConfig = this.getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n storeLanguage,\n initializesOnCheckoutPage,\n );\n\n await this.loadPayPalSdk(paypalSdkScriptConfig);\n }\n\n if (!this.window.paypalGooglePay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypalGooglePay;\n }\n\n async getPayPalApmsSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n ) {\n if (!this.window.paypalApms) {\n const config = this.getPayPalApmSdkConfiguration(\n paymentMethod,\n currencyCode,\n storeLanguage,\n );\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 storeLanguage: string | undefined,\n ): Promise {\n if (!this.window.paypalMessages) {\n const paypalSdkMessagesConfig = this.getPayPalSdkMessagesConfiguration(\n paymentMethod,\n currencyCode,\n storeLanguage,\n );\n\n await this.loadPayPalSdk(paypalSdkMessagesConfig);\n }\n\n if (!this.window.paypalMessages) {\n throw new PaymentMethodClientUnavailableError();\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 storeLanguage: string | undefined,\n ): PayPalSdkConfig {\n const { clientToken, initializationData } = paymentMethod;\n\n if (!initializationData || !initializationData.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { intent, clientId, merchantId, attributionId } = initializationData;\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit: true,\n components: [\n 'fastlane',\n 'buttons',\n 'payment-fields',\n 'hosted-fields',\n 'three-domain-secure',\n ],\n currency: currencyCode,\n intent,\n ...(locale && { locale }),\n },\n attributes: {\n 'data-client-metadata-id': sessionId.replace(/-/g, ''),\n 'data-namespace': 'paypalFastlaneSdk',\n 'data-partner-attribution-id': attributionId,\n 'data-sdk-client-token': clientToken,\n },\n };\n }\n\n private getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage = true,\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 buyerCountry,\n attributionId,\n isHostedCheckoutEnabled,\n isDeveloperModeApplicable,\n } = initializationData;\n\n const commit = isHostedCheckoutEnabled || initializesOnCheckoutPage;\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit,\n components: ['googlepay'],\n currency: currencyCode,\n intent,\n ...(isDeveloperModeApplicable && { 'buyer-country': buyerCountry }),\n ...(locale && { locale }),\n },\n attributes: {\n 'data-partner-attribution-id': attributionId,\n 'data-client-token': clientToken,\n 'data-namespace': 'paypalGooglePay',\n },\n };\n }\n\n private getPayPalApmSdkConfiguration(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\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 const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 storeLanguage: string | undefined,\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 const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 {\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 {\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\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 { GooglePayConfig } from './types';\n\nexport default class GooglePayPaypalCommerceGateway extends GooglePayGateway {\n private googlepayConfig?: GooglePayConfig;\n private service: PaymentIntegrationService;\n\n constructor(service: PaymentIntegrationService, private payPalCommerceSdk: PayPalCommerceSdk) {\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 state = this.service.getState();\n const currency = state.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 const googlePaySdk = await this.payPalCommerceSdk.getPayPalGooglePaySdk(\n paymentMethod,\n currency,\n state.getLocale(),\n );\n\n this.googlepayConfig = await googlePaySdk.Googlepay().config();\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 { 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';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\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';\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 PayPalCommerceSdk(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayPayPalCommerceCustomerStrategy, [\n { id: 'googlepaypaypalcommerce' },\n]);\n","import {\n BigCommercePaymentsInitializationData,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 GooglePayConfig,\n GooglePayPayPalCommerceGatewayParameters,\n GooglePayPayPalCommerceInitializationData,\n GooglePaySetExternalCheckoutData,\n} from '../types';\n\nexport default class GooglePayBigCommercePaymentsGateway extends GooglePayGateway {\n private googlepayConfig?: GooglePayConfig;\n private service: PaymentIntegrationService;\n\n constructor(service: PaymentIntegrationService, private payPalSdkHelper: PayPalSdkHelper) {\n super('googlepay_bigcommerce_payments', 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 const googlePaySdk = await this.payPalSdkHelper.getPayPalGooglePaySdk(\n paymentMethod as PaymentMethod,\n currency,\n );\n\n this.googlepayConfig = await googlePaySdk.Googlepay().config();\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 { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PayPalSdkHelper } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\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 GooglePayBigCommercePaymentsGateway from './google-pay-bigcommerce-payments-gateway';\n\nconst createGooglePayBigCommercePaymentsCustomerStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayBigCommercePaymentsGateway(\n paymentIntegrationService,\n new PayPalSdkHelper(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayBigCommercePaymentsCustomerStrategy, [\n { id: 'googlepay_bigcommerce_payments' },\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 {\n BuyNowCartRequestBody,\n CardInstrument,\n CustomerAddress,\n HostedInstrument,\n ShippingOption,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n/**\n *\n * PayPal 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 BuyNow\n *\n */\nexport interface PayPalBuyNowInitializeOptions {\n getBuyNowCartRequestBody(): BuyNowCartRequestBody;\n}\n\n/**\n *\n * PayPal Initialization Data\n *\n */\nexport interface PayPalInitializationData {\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?: PayPalIntent;\n isAcceleratedCheckoutEnabled?: boolean; // PayPal Fastlane related\n isFastlaneShippingOptionAutoSelectEnabled?: boolean; // PayPal Fastlane related\n isFastlaneStylingEnabled?: boolean;\n isHostedCheckoutEnabled?: boolean;\n isPayPalAnalyticsV2Enabled?: boolean; // PayPal Fastlane related\n isPayPalCreditAvailable?: boolean;\n isPayPalCommerceAnalyticsV2Enabled?: boolean; // PayPal Fastlane related\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 threeDSVerificationMethod?: string;\n isAppSwitchEnabled?: boolean;\n}\n\n/**\n *\n * PayPalHostWindow contains different\n * PayPal Sdk instances for different purposes\n *\n */\nexport interface PayPalHostWindow extends Window {\n paypal?: PayPalSDK;\n paypalFastlane?: PayPalFastlane;\n paypalFastlaneSdk?: PayPalFastlaneSdk;\n paypalMessages?: PayPalMessagesSdk;\n paypalApms?: PayPalApmSdk;\n paypalGooglePay?: PayPalGooglePaySdk;\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?: PayPalIntent;\n components?: PayPalSdkComponents;\n locale?: string;\n };\n attributes: {\n 'data-client-metadata-id'?: string;\n 'data-partner-attribution-id'?: string;\n 'data-sdk-client-token'?: string;\n 'data-namespace'?: string;\n 'data-client-token'?: string;\n };\n}\n\nexport enum PayPalIntent {\n AUTHORIZE = 'authorize',\n CAPTURE = 'capture',\n}\n\nexport type PayPalSdkComponents = Array<\n | 'fastlane'\n | 'three-domain-secure'\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 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\n/**\n *\n * PayPal Sdk instances\n *\n */\nexport interface PayPalSDK {\n CardFields: (data: PaypalCardFieldsConfig) => 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: PayPalHostedFieldsRenderOptions): Promise;\n };\n Legal: PayPalLegal & LegalFunding;\n Buttons(options: PayPalButtonsOptions): PayPalButtons;\n PaymentFields(options: PayPalPaymentFieldsOptions): PayPalPaymentFields;\n Messages(options: PayPalMessagesOptions): PayPalMessages;\n}\n\nexport interface PaypalCardFieldsConfig {\n inputEvents: {\n onChange(data: PayPalCardFieldsState): void;\n onFocus(data: PayPalCardFieldsState): void;\n onBlur(data: PayPalCardFieldsState): void;\n onInputSubmitRequest(data: PayPalCardFieldsState): void;\n };\n createVaultSetupToken?: (data: PayPalCardFieldsState) => void;\n createOrder?: () => Promise;\n style: PayPalHostedFieldsRenderOptions['styles'];\n onApprove(data: PayPalCardFieldsOnApproveData): void;\n onError(): void;\n}\n\ninterface PayPalFieldsInitializationData {\n placeholder?: string;\n}\n\nexport interface PayPalCardFields {\n isEligible(): boolean;\n CVVField(config?: PayPalFieldsInitializationData): PayPalFields;\n ExpiryField(config?: PayPalFieldsInitializationData): PayPalFields;\n NameField(config?: PayPalFieldsInitializationData): PayPalFields;\n NumberField(config?: PayPalFieldsInitializationData): PayPalFields;\n submit(config?: PayPalCardFieldsSubmitConfig): Promise;\n getState(): Promise;\n}\n\nexport interface PayPalCardFieldsSubmitConfig {\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 PayPalCardFieldsOnApproveData {\n vaultSetupToken?: string;\n orderID: string;\n liabilityShift?: LiabilityShiftEnum;\n}\n\ninterface PayPalCardFieldsFieldData {\n isFocused: boolean;\n isEmpty: boolean;\n isValid: boolean;\n isPotentiallyValid: boolean;\n}\n\ntype PayPalCardFieldsCard = PayPalHostedFieldsCard;\n\nexport interface PayPalCardFieldsState {\n cards: PayPalCardFieldsCard[];\n emittedBy: string;\n isFormValid: boolean;\n errors: string[];\n fields: {\n cardCvvField: PayPalCardFieldsFieldData;\n cardNumberField: PayPalCardFieldsFieldData;\n cardNameField?: PayPalCardFieldsFieldData;\n cardExpiryField: PayPalCardFieldsFieldData;\n };\n}\n\nexport interface PayPalFields {\n render(container: HTMLElement | string): Promise;\n clear(): void;\n removeClass(className: string): Promise;\n close(): Promise;\n}\n\nexport interface PayPalFastlaneSdk {\n ThreeDomainSecureClient: {\n isEligible(params: threeDSecureParameters): Promise;\n show(): Promise;\n };\n Fastlane(options?: PayPalFastlaneOptions): Promise;\n}\n\ninterface ThreeDomainSecureClientShowResponse {\n liabilityShift: LiabilityShiftEnum;\n authenticationState: TDSecureAuthenticationState;\n nonce: string; // Enriched nonce or the original nonce\n}\n\nexport enum TDSecureVerificationMethod {\n Always = 'SCA_ALWAYS',\n}\n\nexport enum TDSecureAuthenticationState {\n Succeeded = 'succeeded',\n Cancelled = 'cancelled',\n Errored = 'errored',\n}\n\nexport enum LiabilityShiftEnum {\n Possible = 'POSSIBLE',\n No = 'NO',\n Unknown = 'UNKNOWN',\n Yes = 'YES',\n}\n\nexport interface threeDSecureParameters {\n amount: string;\n currency: string;\n nonce: string;\n threeDSRequested: boolean;\n transactionContext: {\n experience_context: {\n brand_name?: string;\n locale: string;\n return_url: string;\n cancel_url: string;\n };\n };\n}\n\nexport interface PayPalMessagesSdk {\n Messages(options: MessagingOptions): MessagingRender;\n}\n\nexport interface PayPalApmSdk {\n Buttons(options: PayPalButtonsOptions): PayPalButtons;\n PaymentFields(options: PayPalPaymentFieldsOptions): PayPalPaymentFields;\n}\n\nexport interface PayPalGooglePaySdk {\n Googlepay(): GooglePay;\n}\n\n/**\n *\n * PayPal Payments Hosted Fields\n *\n */\nexport interface PayPalHostedFieldsRenderOptions {\n fields?: {\n number?: PayPalHostedFieldOption;\n cvv?: PayPalHostedFieldOption;\n expirationDate?: PayPalHostedFieldOption;\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 PayPalHostedFieldOption {\n selector: string;\n placeholder?: string;\n}\n\nexport interface PayPalHostedFields {\n submit(options?: PayPalHostedFieldsSubmitOptions): Promise;\n getState(): PayPalHostedFieldsState;\n on(eventName: string, callback: (event: PayPalHostedFieldsState) => void): void;\n}\n\nexport interface PayPalHostedFieldsSubmitOptions {\n contingencies?: Array<'3D_SECURE'>;\n cardholderName?: string;\n}\n\nexport interface PayPalHostedFieldsApprove {\n orderId: string;\n liabilityShift?: 'POSSIBLE' | 'NO' | 'UNKNOWN';\n}\n\nexport interface PayPalHostedFieldsState {\n cards: PayPalHostedFieldsCard[];\n emittedBy: string;\n fields: {\n number?: PayPalHostedFieldsFieldData;\n expirationDate?: PayPalHostedFieldsFieldData;\n expirationMonth?: PayPalHostedFieldsFieldData;\n expirationYear?: PayPalHostedFieldsFieldData;\n cvv?: PayPalHostedFieldsFieldData;\n postalCode?: PayPalHostedFieldsFieldData;\n };\n}\n\nexport interface PayPalHostedFieldsCard {\n type: string;\n niceType: string;\n code: {\n name: string;\n size: number;\n };\n}\n\nexport interface PayPalHostedFieldsFieldData {\n container: HTMLElement;\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\n/**\n *\n * PayPal Buttons\n *\n */\nexport interface PayPalButtons {\n render(id: string): void;\n close(): void;\n isEligible(): boolean;\n hasReturned?(): boolean;\n resume?(): void;\n}\n\nexport interface PayPalButtonsOptions {\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 phone?: {\n phone_number: {\n national_number: string;\n };\n };\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\nexport interface PayPalButtonOptions {\n fundingSource: string;\n style?: PayPalButtonStyleOptions;\n isAppSwitchEnabled?: boolean;\n isHostedCheckoutEnabled?: boolean;\n onClick?: () => void;\n onCancel?: () => void;\n onPaymentComplete?: () => void;\n onError?(error?: Error | unknown): void;\n}\n\n/**\n *\n * PayPal Messages\n */\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface PayPalMessages {\n render(id: string): void;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface PayPalMessagesOptions {\n amount: number;\n placement: string;\n style?: PayPalMessagesStyleOptions;\n fundingSource?: string;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface PayPalMessagesStyleOptions {\n layout?: string;\n}\n\n/**\n *\n * Google Pay related types\n *\n */\n\ninterface GooglePay {\n config: () => Promise;\n confirmOrder: (confirmOrderConfig: ConfirmOrderConfig) => Promise<{ status: string }>;\n initiatePayerAction: (payerActionConfig: PayerActionConfig) => Promise;\n}\n\ninterface ConfirmOrderConfig {\n orderId: string;\n paymentMethodData: ConfirmOrderData;\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\ninterface PayerActionConfig {\n orderId: 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\n/**\n *\n * PayPal Payment fields\n *\n */\nexport interface PayPalPaymentFields {\n render(id: string): void;\n}\n\nexport interface PayPalPaymentFieldsOptions {\n style?: PayPalFieldsStyleOptions;\n fundingSource: string;\n fields: {\n name?: {\n value?: string;\n };\n email?: {\n value?: string;\n };\n };\n}\n\nexport interface PayPalFieldsStyleOptions {\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 = 'canceled',\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\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 methodId?: string;\n orderId?: number;\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 fastlaneToken?: string;\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 { 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 FundingType,\n PayPalFastlaneSdk,\n PayPalGooglePaySdk,\n PayPalHostWindow,\n PayPalInitializationData,\n PayPalMessagesSdk,\n PayPalSDK,\n PayPalSdkComponents,\n PayPalSdkConfig,\n} from './paypal-types';\nimport { transformLocaleToPayPalFormat } from './utils';\n\nexport default class PayPalSdkScriptLoader {\n private window: PayPalHostWindow;\n\n constructor(private scriptLoader: ScriptLoader) {\n this.window = window;\n }\n\n async getPayPalSDK(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n if (!this.window.paypal || forceLoad) {\n const paypalSdkScriptConfig = this.getPayPalSdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n storeLanguage,\n initializesOnCheckoutPage,\n );\n\n await this.loadPayPalSdk(paypalSdkScriptConfig);\n\n if (!this.window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.window.paypal;\n }\n\n async getPayPalFastlaneSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n sessionId: string,\n storeLanguage: string | undefined,\n ): Promise {\n if (!this.window.paypalFastlaneSdk) {\n const config = this.getPayPalFastlaneSdkConfiguration(\n paymentMethod,\n currencyCode,\n sessionId,\n storeLanguage,\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 getPayPalGooglePaySdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n if (!this.window.paypalGooglePay || forceLoad) {\n const paypalSdkScriptConfig = this.getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n storeLanguage,\n initializesOnCheckoutPage,\n );\n\n await this.loadPayPalSdk(paypalSdkScriptConfig);\n }\n\n if (!this.window.paypalGooglePay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypalGooglePay;\n }\n\n async getPayPalApmsSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n ) {\n if (!this.window.paypalApms) {\n const config = this.getPayPalApmSdkConfiguration(\n paymentMethod,\n currencyCode,\n storeLanguage,\n );\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 storeLanguage: string | undefined,\n ): Promise {\n if (!this.window.paypalMessages) {\n const paypalSdkMessagesConfig = this.getPayPalSdkMessagesConfiguration(\n paymentMethod,\n currencyCode,\n storeLanguage,\n );\n\n await this.loadPayPalSdk(paypalSdkMessagesConfig);\n }\n\n if (!this.window.paypalMessages) {\n throw new PaymentMethodClientUnavailableError();\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 getPayPalSdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage = true,\n ): PayPalSdkConfig {\n const { id, 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 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 =\n id === 'paypalcommercecreditcards' || id === 'bigcommerce_payments_creditcards';\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 enableVenmoFunding = isVenmoEnabled ? ['venmo'] : [];\n const disableVenmoFunding = !isVenmoEnabled ? ['venmo'] : [];\n const disableAPMsFunding = availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n );\n const googlePayComponent: PayPalSdkComponents = isGooglePayEnabled ? ['googlepay'] : [];\n const cardFieldsComponent: PayPalSdkComponents = 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 ...enabledAlternativePaymentMethods,\n ];\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\n },\n attributes: {\n 'data-partner-attribution-id': attributionId,\n 'data-client-token': clientToken,\n },\n };\n }\n\n private getPayPalFastlaneSdkConfiguration(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n sessionId: string,\n storeLanguage: string | undefined,\n ): PayPalSdkConfig {\n const { clientToken, initializationData } = paymentMethod;\n\n if (!initializationData || !initializationData.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { intent, clientId, merchantId, attributionId } = initializationData;\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit: true,\n components: [\n 'fastlane',\n 'buttons',\n 'payment-fields',\n 'hosted-fields',\n 'three-domain-secure',\n ],\n currency: currencyCode,\n ...(locale && { locale }),\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-sdk-client-token': clientToken,\n },\n };\n }\n\n private getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage = true,\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 buyerCountry,\n attributionId,\n isHostedCheckoutEnabled,\n isDeveloperModeApplicable,\n } = initializationData;\n\n const commit = isHostedCheckoutEnabled || initializesOnCheckoutPage;\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit,\n components: ['googlepay'],\n currency: currencyCode,\n intent,\n ...(isDeveloperModeApplicable && { 'buyer-country': buyerCountry }),\n ...(locale && { locale }),\n },\n attributes: {\n 'data-partner-attribution-id': attributionId,\n 'data-client-token': clientToken,\n 'data-namespace': 'paypalGooglePay',\n },\n };\n }\n\n private getPayPalApmSdkConfiguration(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\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 const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 storeLanguage: string | undefined,\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 const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport PayPalSdkScriptLoader from './paypal-sdk-script-loader';\n\nexport default function createPayPalSdkScriptLoader(): PayPalSdkScriptLoader {\n return new PayPalSdkScriptLoader(getScriptLoader());\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 PayPalRequestSender from './paypal-request-sender';\nimport PayPalSdkScriptLoader from './paypal-sdk-script-loader';\nimport {\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n PayPalCreateOrderCardFieldsResponse,\n PayPalCreateOrderRequestBody,\n PayPalInitializationData,\n PayPalOrderDetails,\n PayPalOrderStatus,\n PayPalSDK,\n StyleButtonColor,\n StyleButtonLabel,\n StyleButtonShape,\n} from './paypal-types';\n\nexport default class PayPalIntegrationService {\n private paypalSdk?: PayPalSDK;\n\n constructor(\n private formPoster: FormPoster,\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalRequestSender: PayPalRequestSender,\n private paypalSdkLoader: PayPalSdkScriptLoader,\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 = state.getPaymentMethodOrThrow(methodId);\n const storeLanguage = state.getLocale();\n\n this.paypalSdk = await this.paypalSdkLoader.getPayPalSDK(\n paymentMethod,\n currencyCode,\n storeLanguage,\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.paypalRequestSender.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.paypalRequestSender.createOrder(providerId, {\n cartId,\n ...requestBody,\n });\n\n return { orderId, ...(setupToken ? { setupToken } : {}) };\n }\n\n async updateOrder(providerId: string, methodId?: string, orderId?: number): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const consignment = state.getConsignmentsOrThrow()[0];\n\n try {\n await this.paypalRequestSender.updateOrder(providerId, {\n availableShippingOptions: consignment.availableShippingOptions,\n cartId: cart.id,\n selectedShippingOption: consignment.selectedShippingOption,\n ...(methodId ? { methodId } : {}),\n ...(orderId ? { orderId } : {}),\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.paypalRequestSender.getOrderStatus(methodId, options);\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((option) => {\n if (consignment.selectedShippingOption) {\n const shippingOptionId = consignment.selectedShippingOption.id;\n\n return option.id === shippingOptionId;\n }\n\n return false;\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: address?.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 phone: payer.phone?.phone_number?.national_number,\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","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-types';\n\nexport default class PayPalRequestSender {\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 methodId: string,\n requestBody: PayPalUpdateOrderRequestBody,\n ): Promise {\n const url = `/api/storefront/initialization/${methodId}`;\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: string,\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 { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalSdkScriptLoader from './create-paypal-sdk-script-loader';\nimport PaypalIntegrationService from './paypal-integration-service';\nimport PaypalRequestSender from './paypal-request-sender';\n\nconst createPayPalIntegrationService = (paymentIntegrationService: PaymentIntegrationService) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new PaypalIntegrationService(\n createFormPoster(),\n paymentIntegrationService,\n new PaypalRequestSender(createRequestSender({ host: getHost() })),\n createPayPalSdkScriptLoader(),\n );\n};\n\nexport default createPayPalIntegrationService;\n","import {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalIntegrationService from './paypal-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalButtonOptions,\n PayPalButtons,\n PayPalBuyNowInitializeOptions,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from './paypal-types';\n\nclass PaypalButtonCreationService {\n private onError?: PayPalButtonOptions['onError'];\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\n ) {}\n\n createPayPalButton(\n providerId: string,\n methodId: string,\n buttonOptions: PayPalButtonOptions,\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): PayPalButtons {\n const {\n style,\n fundingSource,\n isAppSwitchEnabled,\n isHostedCheckoutEnabled,\n onClick,\n onCancel,\n onPaymentComplete,\n onError,\n } = buttonOptions;\n\n this.onError = onError;\n\n const paypalSdk = this.paypalIntegrationService.getPayPalSdkOrThrow();\n const isAvailableFundingSource = Object.values(paypalSdk.FUNDING).includes(fundingSource);\n\n if (!isAvailableFundingSource) {\n throw new InvalidArgumentError(\n `Unable to initialize PayPal button because \"fundingSource\" argument is not valid funding source.`,\n );\n }\n\n const hostedCheckoutCallbacks = {\n ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data, providerId),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data, providerId),\n }),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(\n data,\n actions,\n methodId,\n providerId,\n onPaymentComplete,\n ),\n };\n\n return paypalSdk.Buttons({\n fundingSource,\n style: this.paypalIntegrationService.getValidButtonStyle(style),\n ...(isAppSwitchEnabled && {\n appSwitchWhenAvailable: true,\n }),\n createOrder: async () => {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n\n return this.paypalIntegrationService.createOrder(providerId);\n },\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalIntegrationService.tokenizePayment(methodId, orderID),\n ...(onClick ? { onClick } : {}),\n ...(onCancel ? { onCancel } : {}),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n });\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n providerId: 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.paypalIntegrationService.getBillingAddressFromOrderDetails(orderDetails);\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalIntegrationService.getShippingAddressFromOrderDetails(orderDetails);\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalIntegrationService.updateOrder(providerId);\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalIntegrationService.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 providerId: string,\n ): Promise {\n const address = this.paypalIntegrationService.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.paypalIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalIntegrationService.updateOrder(providerId);\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n providerId: string,\n ): Promise {\n const shippingOption = this.paypalIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalIntegrationService.updateOrder(providerId);\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\nexport default PaypalButtonCreationService;\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';\nimport {\n PaypalButtonCreationService,\n PayPalButtonOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceCustomerInitializeOptions, {\n WithPayPalCommerceCustomerInitializeOptions,\n} from './paypal-commerce-customer-initialize-options';\n\nexport default class PayPalCommerceCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\n private paypalButtonCreationService: PaypalButtonCreationService,\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 const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethod(methodId);\n\n if (!paymentMethod) {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n }\n\n const paypalSdk = await this.paypalIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n console.error(\n '[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\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, onError } = paypalcommerce;\n\n const paypalSdk = this.paypalIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, paymentButtonStyles, isAppSwitchEnabled } =\n paymentMethod.initializationData || {};\n const { checkoutTopButtonStyles } = paymentButtonStyles || {};\n\n const buttonOptions: PayPalButtonOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n isAppSwitchEnabled,\n isHostedCheckoutEnabled,\n style: {\n ...checkoutTopButtonStyles,\n height: DefaultCheckoutButtonHeight,\n },\n ...(onClick && { onClick: () => onClick() }),\n ...(isHostedCheckoutEnabled && onComplete && { onPaymentComplete: () => onComplete() }),\n onError,\n };\n\n const paypalButton = this.paypalButtonCreationService.createPayPalButton(\n 'paypalcommerce',\n methodId,\n buttonOptions,\n );\n\n if (paypalButton.isEligible()) {\n if (paypalButton.hasReturned?.() && isAppSwitchEnabled) {\n paypalButton.resume?.();\n } else {\n paypalButton.render(`#${container}`);\n }\n } else {\n this.paypalIntegrationService.removeElement(container);\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalIntegrationService,\n PaypalButtonCreationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceCustomerStrategy from './paypal-commerce-customer-strategy';\n\nconst createPayPalCommerceCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceCustomerStrategy\n> = (paymentIntegrationService) => {\n const paypalIntegrationService = createPayPalIntegrationService(paymentIntegrationService);\n const paypalButtonCreationService = new PaypalButtonCreationService(\n paymentIntegrationService,\n paypalIntegrationService,\n );\n\n return new PayPalCommerceCustomerStrategy(\n paymentIntegrationService,\n paypalIntegrationService,\n paypalButtonCreationService,\n );\n};\n\nexport default toResolvableModule(createPayPalCommerceCustomerStrategy, [{ id: 'paypalcommerce' }]);\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 locale?: string;\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}\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 paypalBNPLConfiguration?: PayPalBNPLConfigurationItem[];\n isAppSwitchEnabled?: boolean;\n}\n\nexport interface PayPalBNPLConfigurationItem {\n id: string;\n name: string;\n status: boolean;\n styles: 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 hasReturned?(): boolean;\n resume?(): void;\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 phone?: {\n phone_number: {\n national_number: string;\n };\n };\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 IDEAL = 'ideal',\n}\n\nexport interface PayPalOrderData {\n orderId: string;\n setupToken?: string;\n approveUrl: string;\n fastlaneToken?: 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 fastlaneToken?: string;\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 state.getLocale(),\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: address?.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 phone: payer.phone?.phone_number?.national_number,\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","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';\nimport { transformLocaleToPayPalFormat } from '@bigcommerce/checkout-sdk/paypal-utils';\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 storeLanguage: string | undefined,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n const paypalSdkScriptConfig = this.getPayPalSdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n storeLanguage,\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 storeLanguage: string | undefined,\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 enableVenmoFunding = isVenmoEnabled ? ['venmo'] : [];\n const disableVenmoFunding = !isVenmoEnabled ? ['venmo'] : [];\n const disableAPMsFunding = availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n );\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 ...enabledAlternativePaymentMethods,\n ];\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 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 const paypalSdk = await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n console.error(\n '[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\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, isAppSwitchEnabled } =\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 ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n }),\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 const paypalSdk = await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n console.error(\n '[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\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 { 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 { CookieStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport {\n PayPalFastlane,\n PayPalFastlaneAddress,\n PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneLookupCustomerByEmailResult,\n PayPalFastlaneProfileCard,\n PayPalFastlaneProfileName,\n PayPalFastlaneProfilePhone,\n PayPalFastlaneProfileToBcCustomerDataMappingResult,\n PayPalFastlaneSdk,\n PayPalFastlaneStylesOption,\n PayPalHostWindow,\n} from './paypal-types';\n\nexport default class PaypalFastlaneUtils {\n private window: PayPalHostWindow;\n\n constructor() {\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 *\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(sessionId: string): void {\n const expires = new Date();\n\n expires.setDate(expires.getDate() + 14); // 2 weeks expiry\n\n const cookiesOption = {\n expires,\n secure: true,\n };\n\n CookieStorage.set('bc-fastlane-sessionId', sessionId, cookiesOption);\n }\n\n removeStorageSessionId(): void {\n CookieStorage.remove('bc-fastlane-sessionId');\n }\n\n getStorageSessionId(): string {\n return CookieStorage.get('bc-fastlane-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 PaypalFastlaneUtils from './paypal-fastlane-utils';\n\nexport default function createPaypalFastlaneUtils(): PaypalFastlaneUtils {\n return new PaypalFastlaneUtils();\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 PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneStylesOption,\n PayPalFastlaneUtils,\n PayPalInitializationData,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-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 paypalSdkScriptLoader: PayPalSdkScriptLoader,\n private paypalFastlaneUtils: PayPalFastlaneUtils,\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 = state.getPaymentMethodOrThrow(methodId);\n\n const isTestModeEnabled = !!paymentMethod.initializationData?.isDeveloperModeApplicable;\n\n const paypalFastlaneSdk = await this.paypalSdkScriptLoader.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n state.getLocale(),\n );\n\n await this.paypalFastlaneUtils.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 await this.paymentIntegrationService.updatePaymentProviderCustomer({\n authenticationState: undefined,\n addresses: undefined,\n instruments: undefined,\n });\n\n this.paypalFastlaneUtils.removeStorageSessionId();\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.paypalFastlaneUtils.lookupCustomerOrThrow(\n customerEmail,\n );\n\n const authenticationResult =\n await this.paypalFastlaneUtils.triggerAuthenticationFlowOrThrow(customerContextId);\n\n const isAuthenticationFlowCanceled =\n authenticationResult.authenticationState === PayPalFastlaneAuthenticationState.CANCELED;\n\n await this.updateCustomerDataState(methodId, authenticationResult);\n\n if (isAuthenticationFlowCanceled) {\n this.paypalFastlaneUtils.removeStorageSessionId();\n } else {\n this.paypalFastlaneUtils.updateStorageSessionId(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.paypalFastlaneUtils.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 = 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 createPayPalFastlaneUtils,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceFastlaneCustomerStrategy from './paypal-commerce-fastlane-customer-strategy';\n\nconst createPayPalCommerceFastlaneCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceFastlaneCustomerStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceFastlaneCustomerStrategy(\n paymentIntegrationService,\n createPayPalSdkScriptLoader(),\n createPayPalFastlaneUtils(),\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 { PaymentMethod } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { StripePaymentMethod } from './stripe';\n\nexport function isStripePaymentMethodLike(\n paymentMethod: PaymentMethod,\n): paymentMethod is StripePaymentMethod {\n return (\n typeof paymentMethod === 'object' &&\n paymentMethod !== null &&\n 'initializationData' in paymentMethod &&\n (paymentMethod as StripePaymentMethod).initializationData !== undefined &&\n (paymentMethod as StripePaymentMethod).initializationData !== null &&\n typeof (paymentMethod as StripePaymentMethod).initializationData === 'object' &&\n 'stripePublishableKey' in (paymentMethod as StripePaymentMethod).initializationData &&\n 'stripeConnectedAccount' in (paymentMethod as StripePaymentMethod).initializationData &&\n 'shopperLanguage' in (paymentMethod as StripePaymentMethod).initializationData &&\n typeof (paymentMethod as StripePaymentMethod).initializationData.stripePublishableKey !==\n 'undefined' &&\n typeof (paymentMethod as StripePaymentMethod).initializationData.stripeConnectedAccount !==\n 'undefined' &&\n typeof (paymentMethod as StripePaymentMethod).initializationData.shopperLanguage !==\n 'undefined'\n );\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 {\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';\nimport {\n isStripePaymentMethodLike,\n STRIPE_UPE_CLIENT_API_VERSION,\n STRIPE_UPE_CLIENT_BETAS,\n StripeAppearanceOptions,\n StripeClient,\n StripeElementEvent,\n StripeElements,\n StripeElementType,\n StripeEventType,\n StripeFormMode,\n StripeJsVersion,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport isStripeAcceleratedCheckoutCustomer from './is-stripe-accelerated-checkout-customer';\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: StripeScriptLoader,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithStripeUPECustomerInitializeOptions,\n ): Promise {\n let stripeUPEClient: StripeClient;\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 (!isStripePaymentMethodLike(paymentMethod) || !clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\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: StripeAppearanceOptions | 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 paymentMethod.initializationData,\n state.getCartLocale(),\n StripeJsVersion.V3,\n STRIPE_UPE_CLIENT_BETAS,\n STRIPE_UPE_CLIENT_API_VERSION,\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(StripeElementEvent.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 { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeUPECustomerStrategy from './stripe-upe-customer-strategy';\n\nconst createStripeUPECustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new StripeUPECustomerStrategy(\n paymentIntegrationService,\n new StripeScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createStripeUPECustomerStrategy, [{ id: 'stripeupe' }]);\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 StripeClient,\n StripeConfirmPaymentData,\n StripeElement,\n StripeElements,\n StripeElementType,\n StripeError,\n StripeInitializationData,\n StripeJsVersion,\n StripePaymentIntentStatus,\n StripeStringConstants,\n} from './stripe';\nimport StripePaymentInitializeOptions from './stripe-initialize-options';\nimport StripeScriptLoader from './stripe-script-loader';\n\nexport default class StripeIntegrationService {\n private isMounted = false;\n private checkoutEventsUnsubscribe?: () => void;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n ) {}\n\n deinitialize(): void {\n this.checkoutEventsUnsubscribe?.();\n this.isMounted = false;\n }\n\n initCheckoutEventsSubscription(\n gatewayId: string,\n methodId: string,\n stripeInitializationOptions: StripePaymentInitializeOptions,\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 stripeInitializationOptions.onError?.(error);\n }\n\n return;\n }\n\n if (!this.isMounted) {\n await stripeElements?.fetchUpdates();\n this.mountElement(paymentElement, stripeInitializationOptions.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(methodId: string, stripeUPEClient?: StripeClient): 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 === StripePaymentIntentStatus.SUCCEEDED;\n }\n\n mapStripePaymentData(\n stripeElements?: StripeElements,\n returnUrl?: string,\n shouldAllowRedisplay = false,\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 ...(shouldAllowRedisplay ? { allow_redisplay: 'always' } : {}),\n billing_details: {\n email,\n address,\n name: this.getShopperFullName(billingAddress),\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 // INFO: no need to update Stripe Element if client token is not present\n return;\n }\n\n this.scriptLoader.updateStripeElements({ clientSecret: clientToken });\n }\n\n getStripeJsVersion(initializationData: StripeInitializationData): StripeJsVersion {\n return initializationData.useNewStripeJsVersion\n ? StripeJsVersion.CLOVER\n : StripeJsVersion.V3;\n }\n\n mapStripeAddress(address?: Address): AddressOptions {\n if (address) {\n const {\n city,\n address1,\n address2,\n countryCode: country,\n postalCode,\n stateOrProvinceCode,\n } = address;\n\n return {\n city,\n country,\n postal_code: postalCode,\n line1: address1,\n line2: address2,\n ...(stateOrProvinceCode ? { state: stateOrProvinceCode } : {}),\n };\n }\n\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n getShopperFullName(address?: Address): string {\n const { firstName = '', lastName = '' } = address || {};\n\n return `${firstName} ${lastName}`.trim();\n }\n}\n","import { StripeError } from './stripe';\n\nexport function isStripeError(error: unknown): error is StripeError {\n return typeof error === 'object' && error !== null && 'type' in error;\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\nexport const DEFAULT_CONTAINER_STYLES = {\n position: 'fixed',\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\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 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","export const expressCheckoutAllowedCountryCodes = [\n 'AC',\n 'AD',\n 'AE',\n 'AF',\n 'AG',\n 'AI',\n 'AL',\n 'AM',\n 'AO',\n 'AQ',\n 'AR',\n 'AT',\n 'AU',\n 'AW',\n 'AX',\n 'AZ',\n 'BA',\n 'BB',\n 'BD',\n 'BE',\n 'BF',\n 'BG',\n 'BH',\n 'BI',\n 'BJ',\n 'BL',\n 'BM',\n 'BN',\n 'BO',\n 'BQ',\n 'BR',\n 'BS',\n 'BT',\n 'BV',\n 'BW',\n 'BY',\n 'BZ',\n 'CA',\n 'CD',\n 'CF',\n 'CG',\n 'CH',\n 'CI',\n 'CK',\n 'CL',\n 'CM',\n 'CN',\n 'CO',\n 'CR',\n 'CV',\n 'CW',\n 'CY',\n 'CZ',\n 'DE',\n 'DJ',\n 'DK',\n 'DM',\n 'DO',\n 'DZ',\n 'EC',\n 'EE',\n 'EG',\n 'EH',\n 'ER',\n 'ES',\n 'ET',\n 'FI',\n 'FJ',\n 'FK',\n 'FO',\n 'FR',\n 'GA',\n 'GB',\n 'GD',\n 'GE',\n 'GF',\n 'GG',\n 'GH',\n 'GI',\n 'GL',\n 'GM',\n 'GN',\n 'GP',\n 'GQ',\n 'GR',\n 'GS',\n 'GT',\n 'GU',\n 'GW',\n 'GY',\n 'HK',\n 'HN',\n 'HR',\n 'HT',\n 'HU',\n 'ID',\n 'IE',\n 'IL',\n 'IM',\n 'IN',\n 'IO',\n 'IQ',\n 'IS',\n 'IT',\n 'JE',\n 'JM',\n 'JO',\n 'JP',\n 'KE',\n 'KG',\n 'KH',\n 'KI',\n 'KM',\n 'KN',\n 'KR',\n 'KW',\n 'KY',\n 'KZ',\n 'LA',\n 'LB',\n 'LC',\n 'LI',\n 'LK',\n 'LR',\n 'LS',\n 'LT',\n 'LU',\n 'LV',\n 'LY',\n 'MA',\n 'MC',\n 'MD',\n 'ME',\n 'MF',\n 'MG',\n 'MK',\n 'ML',\n 'MM',\n 'MN',\n 'MO',\n 'MQ',\n 'MR',\n 'MS',\n 'MT',\n 'MU',\n 'MV',\n 'MW',\n 'MX',\n 'MY',\n 'MZ',\n 'NA',\n 'NC',\n 'NE',\n 'NG',\n 'NI',\n 'NL',\n 'NO',\n 'NP',\n 'NR',\n 'NU',\n 'NZ',\n 'OM',\n 'PA',\n 'PE',\n 'PF',\n 'PG',\n 'PH',\n 'PK',\n 'PL',\n 'PM',\n 'PN',\n 'PR',\n 'PS',\n 'PT',\n 'PY',\n 'QA',\n 'RE',\n 'RO',\n 'RS',\n 'RU',\n 'RW',\n 'SA',\n 'SB',\n 'SC',\n 'SD',\n 'SE',\n 'SG',\n 'SH',\n 'SI',\n 'SJ',\n 'SK',\n 'SL',\n 'SM',\n 'SN',\n 'SO',\n 'SR',\n 'SS',\n 'ST',\n 'SV',\n 'SX',\n 'SZ',\n 'TA',\n 'TC',\n 'TD',\n 'TF',\n 'TG',\n 'TH',\n 'TJ',\n 'TK',\n 'TL',\n 'TM',\n 'TN',\n 'TO',\n 'TR',\n 'TT',\n 'TV',\n 'TW',\n 'TZ',\n 'UA',\n 'UG',\n 'US',\n 'UY',\n 'UZ',\n 'VA',\n 'VC',\n 'VE',\n 'VG',\n 'VN',\n 'VU',\n 'WF',\n 'WS',\n 'XK',\n 'YE',\n 'YT',\n 'ZA',\n 'ZM',\n 'ZW',\n 'ZZ',\n];\n\n// Stripe has restricted the number of shipping rates to 9.\nexport const stripeAllowedShippingOptionsLength = 9;\n","import { round } from 'lodash';\n\nimport {\n AmountTransformer,\n CustomerInitializeOptions,\n CustomerStrategy,\n InvalidArgumentError,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n Payment,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n ShippingOption,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n isStripePaymentMethodLike,\n StripeAdditionalActionRequired,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeError,\n StripeEventType,\n StripeInitializationData,\n StripeIntegrationService,\n StripeLinkV2Event,\n StripeLinkV2Options,\n StripeLinkV2ShippingRate,\n StripePaymentMethodType,\n StripeResult,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport {\n expressCheckoutAllowedCountryCodes,\n stripeAllowedShippingOptionsLength,\n} from './constants';\nimport { WithStripeOCSCustomerInitializeOptions } from './stripe-ocs-customer-initialize-options';\n\nexport default class StripeLinkV2CustomerStrategy implements CustomerStrategy {\n private _stripeClient?: StripeClient;\n private _stripeElements?: StripeElements;\n private _linkV2Element?: StripeElement;\n private _amountTransformer?: AmountTransformer;\n private _onComplete?: (orderId?: number) => Promise;\n private _loadingIndicatorContainer?: string;\n private _captureMethod?: 'automatic' | 'manual';\n private _currencyCode?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n private stripeIntegrationService: StripeIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithStripeOCSCustomerInitializeOptions,\n ): Promise {\n const { stripeocs } = options || {};\n\n if (!stripeocs) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"options\" argument is not provided.`,\n );\n }\n\n const { gatewayId, container } = stripeocs;\n\n if (!container || !gatewayId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const methodId = this._getMethodId(gatewayId);\n const state = await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n const paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n const { loadingContainerId, buttonHeight, onComplete } = stripeocs;\n\n this._loadingIndicatorContainer = loadingContainerId;\n\n this._onComplete = onComplete;\n\n if (!isStripePaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { initializationData } = paymentMethod;\n const { captureMethod } = initializationData;\n const stripeJsVersion =\n this.stripeIntegrationService.getStripeJsVersion(initializationData);\n\n this._captureMethod = captureMethod;\n this._stripeClient = await this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n stripeJsVersion,\n );\n\n await this._mountExpressCheckoutElement(container, this._stripeClient, buttonHeight);\n\n this._initializeEvents(methodId);\n }\n\n signIn() {\n return Promise.resolve();\n }\n\n signOut() {\n return Promise.resolve();\n }\n\n executePaymentMethodCheckout() {\n return Promise.resolve();\n }\n\n deinitialize() {\n return Promise.resolve();\n }\n\n private async _mountExpressCheckoutElement(\n container: string,\n stripeExpressCheckoutClient: StripeClient,\n buttonHeight = 40,\n ) {\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n const expressCheckoutOptions: StripeElementsCreateOptions = {\n shippingAddressRequired: shouldRequireShippingAddress,\n ...(shouldRequireShippingAddress\n ? { allowedShippingCountries: await this._getAvailableCountries() }\n : {}),\n ...(shouldRequireShippingAddress\n ? { shippingRates: [{ id: '_', amount: 0, displayName: 'Pending rates' }] }\n : {}),\n billingAddressRequired: true,\n emailRequired: true,\n phoneNumberRequired: true,\n paymentMethods: {\n link: StripeStringConstants.AUTO,\n applePay: StripeStringConstants.NEVER,\n googlePay: StripeStringConstants.NEVER,\n amazonPay: StripeStringConstants.NEVER,\n paypal: StripeStringConstants.NEVER,\n klarna: StripeStringConstants.NEVER,\n },\n // Minimal buttonHeight value is 40\n buttonHeight,\n };\n\n const { cartAmount } = this.paymentIntegrationService.getState().getCartOrThrow();\n\n const elementsOptions: StripeLinkV2Options = {\n mode: 'payment',\n amount: this._toCents(cartAmount),\n currency: this._getCurrency(),\n ...(this._captureMethod ? { captureMethod: this._captureMethod } : {}),\n };\n\n this._stripeElements = stripeExpressCheckoutClient.elements(elementsOptions);\n\n this._linkV2Element = this._stripeElements.create(\n StripeElementType.EXPRESS_CHECKOUT,\n expressCheckoutOptions,\n );\n this._linkV2Element.mount(`#${container}`);\n\n return this._linkV2Element;\n }\n\n /** Events * */\n\n private _initializeEvents(methodId: string): void {\n if (!this._linkV2Element) {\n return;\n }\n\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n\n if (shouldRequireShippingAddress) {\n this._linkV2Element.on(StripeElementEvent.SHIPPING_ADDRESS_CHANGE, async (event) =>\n this._onShippingAddressChange(event),\n );\n this._linkV2Element.on(StripeElementEvent.SHIPPING_RATE_CHANGE, async (event) =>\n this._onShippingRateChange(event),\n );\n }\n\n this._linkV2Element.on(StripeElementEvent.CONFIRM, async (event) =>\n this._onConfirm(event, methodId),\n );\n\n this._linkV2Element.on(StripeElementEvent.CANCEL, this._onCancel);\n }\n\n private async _onShippingAddressChange(event: StripeEventType): Promise {\n if (!('address' in event)) {\n return;\n }\n\n const shippingAddress = event.address;\n // Depending on the country, some fields can be missing or partially redacted.\n // For example, the shipping address in the US can only contain a city, state, and ZIP code.\n // The full shipping address appears in the confirm event object after the purchase is confirmed in the browser’s payment interface.\n const result = {\n firstName: '',\n lastName: '',\n phone: '',\n company: '',\n address1: '',\n address2: '',\n city: shippingAddress?.city || '',\n countryCode: shippingAddress?.country || '',\n postalCode: shippingAddress?.postal_code || '',\n stateOrProvince: shippingAddress?.state || '',\n stateOrProvinceCode: shippingAddress?.state || '',\n customFields: [],\n };\n\n await this.paymentIntegrationService.updateShippingAddress(result);\n\n const shippingRates = await this._getAvailableShippingOptions();\n\n await this._updateDisplayedPrice();\n\n if (!shippingRates?.length) {\n event.reject();\n } else {\n event.resolve({\n shippingRates,\n });\n }\n }\n\n private _onCancel() {\n throw new PaymentMethodCancelledError();\n }\n\n private async _onShippingRateChange(event: StripeEventType) {\n if ('shippingRate' in event) {\n const { shippingRate } = event;\n\n await this._handleShippingOptionChange(shippingRate?.id);\n\n await this._updateDisplayedPrice();\n\n event.resolve({});\n }\n }\n\n /** Confirm methods * */\n private async _onConfirm(event: StripeEventType, methodId: string) {\n if (\n 'billingDetails' in event &&\n 'shippingAddress' in event &&\n this._stripeClient &&\n this._stripeElements\n ) {\n await this._updateShippingAndBillingAddress(event);\n await this.paymentIntegrationService.submitOrder();\n\n const paymentPayload = this._getPaymentPayload(methodId);\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._processAdditionalAction(error, methodId);\n }\n }\n\n return Promise.resolve();\n }\n\n private async _updateShippingAndBillingAddress(event: StripeLinkV2Event) {\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n\n const firstName =\n event.shippingAddress?.name?.split(' ')[0] ||\n event.billingDetails?.name?.split(' ')[0] ||\n '';\n const lastName =\n event.shippingAddress?.name?.split(' ')[1] ||\n event.billingDetails?.name?.split(' ')[1] ||\n '';\n\n if (shouldRequireShippingAddress) {\n const shippingAddress = this._mapShippingAddress(\n event.shippingAddress,\n event.billingDetails,\n firstName,\n lastName,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n }\n\n const billingAddress = this._mapBillingAddress(\n event.shippingAddress,\n event.billingDetails,\n firstName,\n lastName,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n private _mapShippingAddress(\n shippingAddress: StripeLinkV2Event['shippingAddress'],\n billingDetails: StripeLinkV2Event['billingDetails'],\n firstName: string,\n lastName: string,\n ) {\n return {\n firstName,\n lastName,\n phone: billingDetails?.phone || '',\n company: '',\n address1: shippingAddress?.address?.line1 || '',\n address2: shippingAddress?.address?.line2 || '',\n city: shippingAddress?.address?.city || '',\n countryCode: shippingAddress?.address?.country || '',\n postalCode: shippingAddress?.address?.postal_code || '',\n stateOrProvince: shippingAddress?.address?.state || '',\n stateOrProvinceCode: shippingAddress?.address?.state || '',\n customFields: [],\n };\n }\n\n private _mapBillingAddress(\n shippingAddress: StripeLinkV2Event['shippingAddress'],\n billingDetails: StripeLinkV2Event['billingDetails'],\n firstName: string,\n lastName: string,\n ) {\n return {\n email: billingDetails?.email || '',\n firstName,\n lastName,\n phone: billingDetails?.phone || '',\n company: '',\n address1: billingDetails?.address?.line1 || '',\n address2: '',\n city: billingDetails?.address?.city || '',\n countryCode: billingDetails?.address?.country || '',\n postalCode: billingDetails?.address?.postal_code || '',\n stateOrProvince: billingDetails?.address?.state || '',\n stateOrProvinceCode: shippingAddress?.address?.state || '',\n customFields: [],\n };\n }\n\n private async _processAdditionalAction(error: unknown, methodId: string): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n if (!this._stripeClient || !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 additionalActionData,\n methodId,\n );\n\n const paymentPayload = this._getPaymentPayload(methodId, paymentIntent?.id || token);\n\n try {\n this._toggleLoadingIndicator(true);\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n await this._completeCheckoutFlow();\n } catch (error) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n } finally {\n this._toggleLoadingIndicator(false);\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n additionalActionData: StripeAdditionalActionRequired['data'],\n methodId: string,\n ): Promise {\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeIntegrationService.mapStripePaymentData(\n this._stripeElements,\n redirect_url,\n );\n let stripeError: StripeError | undefined;\n\n try {\n const isPaymentCompleted = await this.stripeIntegrationService.isPaymentCompleted(\n methodId,\n this._stripeClient,\n );\n\n const confirmationResult = !isPaymentCompleted\n ? await this._stripeClient?.confirmPayment({\n elements: stripePaymentData.elements,\n clientSecret: token,\n redirect: StripeStringConstants.IF_REQUIRED,\n confirmParams: {\n return_url: stripePaymentData.confirmParams?.return_url,\n },\n })\n : await this._stripeClient?.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 return this.stripeIntegrationService.throwStripeError(stripeError);\n }\n }\n\n private async _completeCheckoutFlow() {\n if (typeof this._onComplete === 'function') {\n return this._onComplete();\n }\n\n window.location.replace('/order-confirmation');\n\n return Promise.resolve();\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 ...(token ? { credit_card_token: { token } } : {}),\n confirm: false,\n method: StripePaymentMethodType.Link,\n };\n\n return {\n methodId,\n paymentData: {\n formattedPayload,\n },\n };\n }\n\n /** Utils * */\n\n private _shouldRequireShippingAddress() {\n const { getCartOrThrow } = this.paymentIntegrationService.getState();\n const { lineItems } = getCartOrThrow();\n\n return !!lineItems.physicalItems.length;\n }\n\n private async _updateDisplayedPrice() {\n if (this._stripeElements) {\n this._stripeElements.update({\n currency: this._getCurrency(),\n mode: 'payment',\n amount: await this._getTotalPrice(),\n });\n }\n }\n\n private _getCurrency() {\n if (!this._currencyCode) {\n const { code: currencyCode } = this.paymentIntegrationService\n .getState()\n .getCartOrThrow().currency;\n\n this._currencyCode = currencyCode.toLowerCase();\n }\n\n return this._currencyCode;\n }\n\n private async _getTotalPrice(): Promise {\n await this.paymentIntegrationService.loadCheckout();\n\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 this._toCents(+totalPrice);\n }\n\n private async _getAvailableCountries(): Promise {\n const countries = await this.paymentIntegrationService.loadShippingCountries();\n const deliverableCountries =\n countries.getShippingCountries()?.map((country) => country.code) || [];\n\n return deliverableCountries.filter((code) => {\n return expressCheckoutAllowedCountryCodes.includes(code);\n });\n }\n\n private async _getAvailableShippingOptions(): Promise {\n const state = this.paymentIntegrationService.getState();\n const consignments = state.getConsignments();\n\n if (!consignments?.[0]) {\n return;\n }\n\n const consignment = consignments[0];\n const options = (consignment.availableShippingOptions || []).map(\n this._getStripeShippingOption.bind(this),\n );\n const recommendedShippingOption = consignment.availableShippingOptions?.find(\n (shippingOption) => shippingOption.isRecommended,\n );\n const selectedId = consignment.selectedShippingOption?.id;\n const recommendedId = recommendedShippingOption?.id;\n\n if (selectedId) {\n // Set selected shipping option first in the array, as it will be selected by default\n options.sort((option) => (option.id === selectedId ? -1 : 0));\n } else if (recommendedId) {\n // Set recommended shipping option first in the array, as it will be selected by default\n options.sort((option) => (option.id === recommendedId ? -1 : 0));\n await this._handleShippingOptionChange(recommendedId);\n } else {\n await this._handleShippingOptionChange(options[0]?.id);\n }\n\n // Stripe has restricted the number of shipping rates.\n return options.slice(0, stripeAllowedShippingOptionsLength);\n }\n\n private _getStripeShippingOption({ id, cost, description }: ShippingOption) {\n return {\n id,\n displayName: description,\n amount: this._toCents(cost),\n };\n }\n\n private async _handleShippingOptionChange(optionId?: string) {\n if (!optionId || optionId === 'shipping_option_unselected') {\n return;\n }\n\n return this.paymentIntegrationService.selectShippingOption(optionId);\n }\n\n private _getAmountTransformer() {\n if (this._amountTransformer) {\n return this._amountTransformer;\n }\n\n const { getCart } = this.paymentIntegrationService.getState();\n const { currency } = getCart() || {};\n\n if (currency) {\n const amountTransformer = new AmountTransformer(currency.decimalPlaces);\n\n return amountTransformer;\n }\n }\n\n private _toCents(amount: number) {\n const fallbackValue = Math.round(amount * 100);\n const amountTransformer = this._getAmountTransformer();\n\n if (amountTransformer) {\n return amountTransformer.toInteger(amount);\n }\n\n return fallbackValue;\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 _getMethodId(gatewayId: string): string {\n const { initializationData: { checkoutSessionEnabled } = {} } =\n this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(gatewayId);\n\n return checkoutSessionEnabled\n ? StripePaymentMethodType.CHECKOUT_SESSION\n : StripePaymentMethodType.OCS;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\nimport { DEFAULT_CONTAINER_STYLES, LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport StripeLinkV2CustomerStrategy from './stripe-link-v2-customer-strategy';\n\nconst createStripeLinkV2CustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n const loadingIndicator = new LoadingIndicator({\n containerStyles: DEFAULT_CONTAINER_STYLES,\n });\n\n return new StripeLinkV2CustomerStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n loadingIndicator,\n );\n};\n\nexport default toResolvableModule(createStripeLinkV2CustomerStrategy, [{ id: 'stripeocs' }]);\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 { 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","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: [{ code: string }];\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 type AdyenComponentFieldVisibility = 'hidden' | 'readOnly' | 'editable';\n\nexport interface AdyenOpenInvoiceComponentVisibility {\n personalDetails?: AdyenComponentFieldVisibility;\n billingAddress?: AdyenComponentFieldVisibility;\n deliveryAddress?: AdyenComponentFieldVisibility;\n}\n\nexport interface AdyenBoletoComponentOptions extends AdyenComponentEvents {\n personalDetailsRequired?: boolean;\n billingAddressRequired?: boolean;\n showEmailAddress?: boolean;\n visibility?: AdyenOpenInvoiceComponentVisibility;\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 { 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","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 { 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.71.1/adyen.css`,\n {\n prepend: false,\n attributes: {\n integrity:\n 'sha384-5MvB4RnzvviA3VBT4KYABZ4HXNZG5LRqREEgd41xt/pf/QvKmsj2O9GuNuywRXx9',\n crossorigin: 'anonymous',\n },\n },\n ),\n this._scriptLoader.loadScript(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/5.71.1/adyen.js`,\n {\n async: true,\n attributes: {\n integrity:\n 'sha384-yvY2yFNR4WqIjPqP9MzjI+gJimmaJnAvj4rLHKvgJbgFD5fMuf8zIJrFJOW8Lhhf',\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 static readonly mountContainerMaxWaitMs = 5000;\n private static readonly mountContainerPollIntervalMs = 50;\n\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._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 paymentData.instrumentId,\n bigpayToken,\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 _getLocale(): string | undefined {\n const locale = this.paymentIntegrationService.getState().getLocale();\n\n if (locale && locale.substring(0, 2) === 'es') {\n return 'es';\n }\n\n return locale;\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 void this._mountElement(additionalActionComponent, containerId)\n .then(() => {\n if (onLoad && typeof onLoad === 'function') {\n onLoad(() => {\n reject(new PaymentMethodCancelledError());\n additionalActionComponent.unmount();\n });\n }\n })\n .catch(reject);\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 async _mountCardVerificationComponent(): Promise {\n const adyenv3 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n\n if (!adyenv3.cardVerificationContainerId) {\n return undefined;\n }\n\n const 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 await this._mountElement(\n cardVerificationComponent,\n adyenv3.cardVerificationContainerId,\n );\n } catch {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return cardVerificationComponent;\n }\n\n private async _mountPaymentComponent(paymentMethod: PaymentMethod): Promise {\n const adyenv3 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n const billingAddress = this.paymentIntegrationService.getState().getBillingAddress();\n const { prefillCardHolderName } = paymentMethod.initializationData;\n\n const paymentComponent = adyenClient.create(paymentMethod.method, {\n ...(this._isOneyPaymentMethod(paymentMethod.method)\n ? {\n visibility: {\n personalDetails: 'hidden',\n billingAddress: 'hidden',\n deliveryAddress: 'hidden',\n },\n }\n : {}),\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 await this._mountElement(paymentComponent, adyenv3.containerId);\n } catch {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return paymentComponent;\n }\n\n private _isOneyPaymentMethod(method: string): boolean {\n return method.startsWith('facilypay');\n }\n\n private async _processAdditionalAction(\n error: unknown,\n shouldSaveInstrument?: boolean,\n shouldSetAsDefaultInstrument?: boolean,\n paymentToken?: string,\n bigpayToken?: Record,\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 const basePaymentData = {\n ...payment.paymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n };\n\n const tokenData =\n shouldSetAsDefaultInstrument && !shouldSaveInstrument\n ? {\n instrumentId: paymentToken,\n formattedPayload: {\n bigpay_token: {\n ...bigpayToken,\n token: paymentToken,\n },\n },\n }\n : {};\n\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...basePaymentData,\n ...tokenData,\n },\n });\n } catch (paymentError) {\n return this._processAdditionalAction(\n paymentError,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n paymentToken,\n bigpayToken,\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 async _mountElement(\n adyenComponent: AdyenComponent,\n containerId: string,\n ): Promise {\n await this._waitForMountContainer(containerId);\n\n try {\n adyenComponent.mount(`#${containerId}`);\n } catch {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n }\n\n private async _waitForMountContainer(containerId: string): Promise {\n const maxAttempts = Math.ceil(\n Adyenv3PaymentStrategy.mountContainerMaxWaitMs /\n Adyenv3PaymentStrategy.mountContainerPollIntervalMs,\n );\n const pollIntervalMs = Adyenv3PaymentStrategy.mountContainerPollIntervalMs;\n\n let step = 0;\n\n const poll = async (): Promise => {\n if (step === maxAttempts) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (document.getElementById(containerId)) {\n return;\n }\n\n await new Promise((resolve) => {\n setTimeout(resolve, pollIntervalMs);\n });\n\n step += 1;\n await poll();\n };\n\n await poll();\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","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 {\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","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';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const withHttpsExperimentName = 'PI-4789.afterpay_script_use_https';\n const withHttps = isExperimentEnabled(features, withHttpsExperimentName, false);\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._afterpaySdk = await this._afterpayScriptLoader.load(\n paymentMethod,\n countryCode,\n withHttps,\n );\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.js',\n HTTPS_PROD = 'https://portal.afterpay.com/afterpay-async.js',\n HTTPS_SANDBOX = 'https://portal.sandbox.afterpay.com/afterpay.js',\n}\n\nenum SCRIPTS_US {\n PROD = '//portal.afterpay.com/afterpay-async.js',\n SANDBOX = '//portal.sandbox.afterpay.com/afterpay.js',\n HTTPS_PROD = 'https://portal.afterpay.com/afterpay-async.js',\n HTTPS_SANDBOX = 'https://portal.sandbox.afterpay.com/afterpay.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(\n method: PaymentMethod,\n countryCode: string,\n withHttps = false,\n ): Promise {\n const testMode = method.config.testMode || false;\n const scriptURI = this._getScriptURI(countryCode, testMode, withHttps);\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, withHttps = false): string {\n if (countryCode === 'US') {\n if (withHttps) {\n return testMode ? SCRIPTS_US.HTTPS_SANDBOX : SCRIPTS_US.HTTPS_PROD;\n }\n\n return testMode ? SCRIPTS_US.SANDBOX : SCRIPTS_US.PROD;\n }\n\n if (withHttps) {\n return testMode ? SCRIPTS_DEFAULT.HTTPS_SANDBOX : SCRIPTS_DEFAULT.HTTPS_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 if (!this._amazonPayButton) {\n throw new InvalidArgumentError(\n 'Unable to render the Amazon Pay button to an invalid HTML container element.',\n );\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 ApplePayScriptLoader from './apple-pay-script-loader';\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 private _applePayScriptLoader: ApplePayScriptLoader,\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 await this._applePayScriptLoader.loadSdk();\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 (\n paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE &&\n paymentMethod.clientToken\n ) {\n this._braintreeSdk.initialize(paymentMethod.clientToken);\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","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\n} 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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n\n return new ApplePayPaymentStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), window, braintreeSDKVersionManager),\n ),\n new ApplePayScriptLoader(new ScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createApplePayPaymentStrategy, [{ id: 'applepay' }]);\n","export const LOADING_INDICATOR_STYLES = {\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\n};\n","import { MessagesStyleOptions, PayPalBNPLConfigurationItem } from '../bigcommerce-payments-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","export interface BaseInstrument {\n bigpayToken: string;\n defaultInstrument: boolean;\n provider: string;\n trustedShippingAddress: boolean;\n method: string;\n type: string;\n}\n\nexport function isBaseInstrument(instrument: unknown): instrument is BaseInstrument {\n if (typeof instrument !== 'object' || instrument === null) {\n return false;\n }\n\n return (\n 'bigpayToken' in instrument &&\n 'defaultInstrument' in instrument &&\n 'provider' in instrument &&\n 'trustedShippingAddress' in instrument &&\n 'method' in instrument &&\n 'type' in instrument\n );\n}\n","import {\n getPaypalMessagesStylesFromBNPLConfig,\n isBigCommercePaymentsProviderError,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalMessagesSdk,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isBaseInstrument } from '@bigcommerce/checkout-sdk/utility';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtons,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n ClickCallbackActions,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsPaymentInitializeOptions, {\n WithBigCommercePaymentsPaymentInitializeOptions,\n} from './bigcommerce-payments-payment-initialize-options';\n\nexport default class BigCommercePaymentsPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: BigCommercePaymentsButtons;\n private bigcommerce_payments?: BigCommercePaymentsPaymentInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private paypalSdkHelper: PayPalSdkHelper,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithBigCommercePaymentsPaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments } = options || {};\n\n this.bigcommerce_payments = bigcommerce_payments;\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 (!bigcommerce_payments) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments\" 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 const { container, bannerContainerId } = bigcommerce_payments;\n\n const {\n orderId,\n paypalBNPLConfiguration = [],\n isPayPalCreditAvailable,\n } = paymentMethod.initializationData || {};\n\n if (bannerContainerId !== undefined) {\n if (!document.getElementById(bannerContainerId)) {\n // eslint-disable-next-line no-console\n console.error('Unable to create banner without valid banner container ID.');\n\n return;\n }\n\n const bannerConfiguration = paypalBNPLConfiguration?.find(\n ({ id }) => id === 'checkout',\n );\n\n if (isPayPalCreditAvailable || !bannerConfiguration?.status) {\n return;\n }\n\n const paypalMessages = await this.paypalSdkHelper.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n );\n\n if (!paypalMessages || typeof paypalMessages?.Messages !== 'function') {\n console.error(\n '[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n return this.renderMessages(paypalMessages, bannerContainerId, bannerConfiguration);\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 this.loadingIndicatorContainer = container?.split('#')[1];\n\n await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n if (bigcommerce_payments.onInit && typeof bigcommerce_payments.onInit === 'function') {\n bigcommerce_payments.onInit(() => this.renderButton(methodId, bigcommerce_payments));\n }\n\n if (\n bigcommerce_payments.shouldRenderPayPalButtonOnInitialization === undefined ||\n bigcommerce_payments.shouldRenderPayPalButtonOnInitialization\n ) {\n this.renderButton(methodId, bigcommerce_payments);\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const { onError } = this.bigcommerce_payments || {};\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)) {\n await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(payment.methodId);\n\n await new Promise((_resolve, reject) => {\n if (this.bigcommerce_payments) {\n this.paypalButton?.close();\n this.renderButton(payment.methodId, this.bigcommerce_payments);\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 bigcommerce_payments: BigCommercePaymentsPaymentInitializeOptions,\n ): void {\n const paypalSdk = this.bigCommercePaymentsIntegrationService.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 } = bigcommerce_payments;\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"container\" argument is not provided.',\n );\n }\n\n const buttonOptions: BigCommercePaymentsButtonsOptions = {\n ...(this.isAppSwitchEnabled(methodId) && {\n appSwitchWhenAvailable: true,\n }),\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.bigCommercePaymentsIntegrationService.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 if (this.paypalButton.hasReturned?.() && this.isAppSwitchEnabled(methodId)) {\n this.paypalButton.resume?.();\n } else {\n this.paypalButton.render(container);\n }\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: BigCommercePaymentsPaymentInitializeOptions['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: BigCommercePaymentsPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm?.();\n }\n\n private handleError(\n error: unknown,\n onError: BigCommercePaymentsPaymentInitializeOptions['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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_paymentscheckout',\n {\n shouldSaveInstrument: fieldsValues?.shouldSaveInstrument || false,\n },\n );\n }\n\n /**\n *\n * Vaulting flow methods\n *\n * */\n private getFieldsValues(): HostedInstrument | undefined {\n const { getFieldsValues } = this.bigcommerce_payments || {};\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 findInstrument = instruments?.find(\n (instrument) =>\n isBaseInstrument(instrument) &&\n instrument.bigpayToken === paymentData.instrumentId,\n );\n const trustedShippingAddress = isBaseInstrument(findInstrument)\n ? findInstrument.trustedShippingAddress\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 /**\n *\n * Render Pay Later Messages\n *\n * */\n private renderMessages(\n paypalMessages: PayPalMessagesSdk,\n bannerContainerId: string,\n bannerConfiguration: PayPalBNPLConfigurationItem,\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: checkout.outstandingBalance,\n placement: 'payment',\n style: getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\n };\n\n paypalMessages.Messages(paypalMessagesOptions).render(`#${bannerContainerId}`);\n }\n\n private isProviderError(error: unknown): boolean {\n if (isBigCommercePaymentsProviderError(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 /**\n *\n * AppSwitch enabling handling\n *\n */\n private isAppSwitchEnabled(methodId: string): boolean {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n return paymentMethod.initializationData?.isAppSwitchEnabled ?? 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 isBigCommercePaymentsProviderError(error: unknown): error is ProviderError {\n return typeof error === 'object' && error !== null && 'errors' in error;\n}\n","import { createBigCommercePaymentsSdk } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport { LOADING_INDICATOR_STYLES } from '../bigcommerce-payments-constants';\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsPaymentStrategy from './bigcommerce-payments-payment-strategy';\n\nconst createBigCommercePaymentsPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n createBigCommercePaymentsSdk(),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsPaymentStrategy, [\n { id: 'bigcommerce_payments' },\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 BigCommercePaymentsFastlaneUtils,\n BigCommercePaymentsInitializationData,\n getFastlaneStyles,\n isBigcommerceFastlaneRequestError,\n isPayPalFastlaneCustomer,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneCardComponentMethods,\n PayPalFastlaneCardComponentOptions,\n PayPalFastlanePaymentFormattedPayload,\n PayPalFastlaneSdk,\n PayPalSdkHelper,\n TDSecureAuthenticationState,\n TDSecureVerificationMethod,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport BigCommercePaymentsRequestSender from '../bigcommerce-payments-request-sender';\nimport { LiabilityShiftEnum } from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsFastlanePaymentInitializeOptions, {\n WithBigCommercePaymentsFastlanePaymentInitializeOptions,\n} from './bigcommerce-payments-fastlane-payment-initialize-options';\n\nexport default class BigCommercePaymentsFastlanePaymentStrategy implements PaymentStrategy {\n private paypalComponentMethods?: PayPalFastlaneCardComponentMethods;\n private threeDSVerificationMethod?: string;\n private paypalFastlaneSdk?: PayPalFastlaneSdk;\n private bigcommerce_payments_fastlane?: BigCommercePaymentsFastlanePaymentInitializeOptions;\n private methodId?: string;\n private orderId?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsRequestSender: BigCommercePaymentsRequestSender,\n private bigCommercePaymentsSdk: PayPalSdkHelper,\n private bigCommercePaymentsFastlaneUtils: BigCommercePaymentsFastlaneUtils,\n ) {}\n\n /**\n *\n * Default methods\n *\n * */\n async initialize(\n options: PaymentInitializeOptions & WithBigCommercePaymentsFastlanePaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_fastlane } = 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.methodId = methodId;\n\n if (!bigcommerce_payments_fastlane) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_fastlane\" argument is not provided.',\n );\n }\n\n this.bigcommerce_payments_fastlane = bigcommerce_payments_fastlane;\n\n if (\n !bigcommerce_payments_fastlane.onInit ||\n typeof bigcommerce_payments_fastlane.onInit !== 'function'\n ) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_fastlane.onInit\" argument is not provided or it is not a function.',\n );\n }\n\n if (\n !bigcommerce_payments_fastlane.onChange ||\n typeof bigcommerce_payments_fastlane.onChange !== 'function'\n ) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_fastlane.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 this.threeDSVerificationMethod =\n paymentMethod.initializationData?.threeDSVerificationMethod;\n\n this.paypalFastlaneSdk = await this.bigCommercePaymentsSdk.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 bigcommerce_payments_fastlane?.styles,\n );\n\n await this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(\n this.paypalFastlaneSdk,\n !!isDeveloperModeApplicable,\n fastlaneStyles,\n );\n\n if (this.shouldRunAuthenticationFlow()) {\n await this.runPayPalAuthenticationFlowOrThrow(methodId);\n }\n\n await this.initializePayPalPaymentComponent();\n\n bigcommerce_payments_fastlane.onInit((container: string) =>\n this.renderPayPalPaymentComponent(container),\n );\n bigcommerce_payments_fastlane.onChange(() =>\n this.handlePayPalStoredInstrumentChange(methodId),\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 { paymentData, methodId } = payment;\n\n const isVaultedFlow = paymentData && isVaultedInstrument(paymentData);\n\n try {\n await this.paymentIntegrationService.submitOrder(order, options);\n\n const paymentPayload = isVaultedFlow\n ? await this.prepareVaultedInstrumentPaymentPayload(methodId, paymentData)\n : await this.preparePaymentPayload(methodId, paymentData);\n\n await this.paymentIntegrationService.submitPayment(\n paymentPayload,\n );\n\n this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId();\n } catch (error) {\n if (\n isBigcommerceFastlaneRequestError(error) &&\n error.response.name === 'INVALID_REQUEST'\n ) {\n const invalidRequestError = {\n translationKey: 'payment.errors.invalid_request_error',\n };\n\n this.handleError(invalidRequestError);\n\n return Promise.reject();\n }\n\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.bigCommercePaymentsFastlaneUtils.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.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(customerEmail);\n\n const authenticationResult =\n await this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(\n customerContextId,\n );\n\n const { authenticationState, addresses, instruments } =\n this.bigCommercePaymentsFastlaneUtils.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 if (isAuthenticationFlowCanceled) {\n this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId();\n } else {\n this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(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 * BigCommercePayments 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.bigCommercePaymentsFastlaneUtils.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 paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n const is3DSEnabled =\n this.isBigcommercePaymentsFastlaneThreeDSAvailable() &&\n paymentMethod.config.is3dsEnabled;\n\n const nonce = is3DSEnabled ? await this.get3DSNonce(instrumentId) : instrumentId;\n\n await this.createOrder(nonce);\n\n return {\n methodId,\n paymentData: {\n formattedPayload: {\n paypal_fastlane_token: {\n order_id: this.orderId,\n token: nonce,\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 billingAddress = state.getBillingAddressOrThrow();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\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:\n this.bigCommercePaymentsFastlaneUtils.mapBcToPayPalAddress(billingAddress),\n });\n\n const is3DSEnabled =\n this.isBigcommercePaymentsFastlaneThreeDSAvailable() &&\n paymentMethod.config.is3dsEnabled;\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n const nonce = is3DSEnabled ? await this.get3DSNonce(id) : id;\n\n await this.createOrder(nonce);\n\n return {\n methodId,\n paymentData: {\n ...paymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n formattedPayload: {\n paypal_fastlane_token: {\n order_id: this.orderId,\n token: nonce,\n },\n },\n },\n };\n }\n\n private async createOrder(id: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cartId = state.getCartOrThrow().id;\n\n if (this.methodId) {\n const { orderId } = await this.bigCommercePaymentsRequestSender.createOrder(\n this.methodId,\n {\n cartId,\n fastlaneToken: id,\n },\n );\n\n this.orderId = orderId;\n }\n }\n\n /**\n *\n * 3DSecure methods\n *\n * */\n private async get3DSNonce(nonce: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const order = state.getOrderOrThrow();\n const checkoutUrl = state.getStoreConfigOrThrow().links.checkoutLink;\n\n const threeDomainSecureComponent = this.paypalFastlaneSdk?.ThreeDomainSecureClient;\n\n if (!threeDomainSecureComponent) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n const threeDomainSecureParameters = {\n amount: order.orderAmount.toFixed(2),\n currency: cart.currency.code,\n nonce,\n threeDSRequested: this.threeDSVerificationMethod === TDSecureVerificationMethod.Always,\n transactionContext: {\n experience_context: {\n locale: 'en-US',\n return_url: checkoutUrl,\n cancel_url: checkoutUrl,\n },\n },\n };\n\n const isThreeDomainSecureEligible = await threeDomainSecureComponent.isEligible(\n threeDomainSecureParameters,\n );\n\n if (\n this.threeDSVerificationMethod === TDSecureVerificationMethod.Always &&\n !isThreeDomainSecureEligible\n ) {\n throw new PaymentMethodInvalidError();\n }\n\n if (isThreeDomainSecureEligible) {\n const {\n liabilityShift,\n authenticationState,\n nonce: threeDSNonce,\n } = await threeDomainSecureComponent.show();\n\n if (\n liabilityShift === LiabilityShiftEnum.No ||\n liabilityShift === LiabilityShiftEnum.Unknown ||\n authenticationState === TDSecureAuthenticationState.Errored ||\n authenticationState === TDSecureAuthenticationState.Cancelled\n ) {\n throw new PaymentMethodInvalidError();\n }\n\n if (\n authenticationState === TDSecureAuthenticationState.Succeeded &&\n [LiabilityShiftEnum.Yes, LiabilityShiftEnum.Possible].includes(liabilityShift)\n ) {\n return threeDSNonce;\n }\n }\n\n return nonce;\n }\n\n /**\n *\n * BigCommercePayments Fastlane instrument change\n *\n */\n private async handlePayPalStoredInstrumentChange(\n methodId: string,\n ): Promise {\n const paypalAxoSdk = this.bigCommercePaymentsFastlaneUtils.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 =\n this.bigCommercePaymentsFastlaneUtils.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 /**\n *\n * Bigcommerce Payments Fastlane experiments handling\n *\n */\n private isBigcommercePaymentsFastlaneThreeDSAvailable(): boolean {\n const state = this.paymentIntegrationService.getState();\n const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n\n return isExperimentEnabled(features, 'PROJECT-7080.bcp_fastlane_three_ds');\n }\n\n private handleError(error: unknown): void {\n if (\n this.bigcommerce_payments_fastlane?.onError &&\n typeof this.bigcommerce_payments_fastlane.onError === 'function'\n ) {\n this.bigcommerce_payments_fastlane.onError(error);\n }\n }\n}\n","export interface BigcommerceFastlaneRequestError {\n name: string;\n message: string;\n response: {\n name: string;\n };\n}\n\nexport default function isBigcommerceFastlaneRequestError(\n error: unknown,\n): error is BigcommerceFastlaneRequestError {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'message' in error &&\n 'response' in error &&\n 'name' in (error as BigcommerceFastlaneRequestError).response\n );\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n createBigCommercePaymentsFastlaneUtils,\n createBigCommercePaymentsSdk,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsRequestSender from '../bigcommerce-payments-request-sender';\n\nimport BigCommercePaymentsFastlanePaymentStrategy from './bigcommerce-payments-fastlane-payment-strategy';\n\nconst createBigCommercePaymentsFastlanePaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsFastlanePaymentStrategy\n> = (paymentIntegrationService) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new BigCommercePaymentsFastlanePaymentStrategy(\n paymentIntegrationService,\n new BigCommercePaymentsRequestSender(createRequestSender({ host: getHost() })),\n createBigCommercePaymentsSdk(),\n createBigCommercePaymentsFastlaneUtils(),\n );\n};\n\nexport default toResolvableModule(createBigCommercePaymentsFastlanePaymentStrategy, [\n { id: 'bigcommerce_payments_fastlane' }, // BigCommercePayments Fastlane relates to 'bigcommerce_payments_fastlane' method id\n]);\n","import {\n BigCommercePaymentsInitializationData,\n getPaypalMessagesStylesFromBNPLConfig,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalMessagesSdk,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtons,\n BigCommercePaymentsButtonsOptions,\n ClickCallbackActions,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsPayLaterPaymentInitializeOptions, {\n WithBigCommercePaymentsPayLaterPaymentInitializeOptions,\n} from './bigcommerce-payments-paylater-payment-initialize-options';\n\nexport default class BigCommercePaymentsPayLaterPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private bigCommercePaymentsButtons?: BigCommercePaymentsButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private loadingIndicator: LoadingIndicator,\n private paypalSdkHelper: PayPalSdkHelper,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions &\n WithBigCommercePaymentsPayLaterPaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_paylater } = 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 (!bigcommerce_payments_paylater) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_paylater\" 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 const { paypalBNPLConfiguration = [], orderId } = paymentMethod.initializationData || {};\n const { bannerContainerId, container } = bigcommerce_payments_paylater;\n\n if (bannerContainerId !== undefined) {\n if (!document.getElementById(bannerContainerId)) {\n // eslint-disable-next-line no-console\n console.error('Unable to create banner without valid banner container ID.');\n\n return;\n }\n\n const bannerConfiguration =\n paypalBNPLConfiguration &&\n paypalBNPLConfiguration.find(({ id }) => id === 'checkout');\n\n if (!bannerConfiguration?.status) {\n return;\n }\n\n const paypalMessages = await this.paypalSdkHelper.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n );\n\n return this.renderMessages(paypalMessages, bannerContainerId, bannerConfiguration);\n }\n\n // Info:\n // The BigCommercePayments 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 BigCommercePayments button.\n if (orderId) {\n this.orderId = orderId;\n\n return;\n }\n\n await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = container?.split('#')[1];\n\n this.renderButton(methodId, bigcommerce_payments_paylater);\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.bigCommercePaymentsIntegrationService.submitPayment(\n payment.methodId,\n this.orderId,\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.orderId = undefined;\n\n this.bigCommercePaymentsButtons?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n bigcommerce_payments_paylater: BigCommercePaymentsPayLaterPaymentInitializeOptions,\n ): void {\n if (!bigcommerce_payments_paylater?.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"container\" argument is not provided.',\n );\n }\n\n const bigCommerceSdk = this.bigCommercePaymentsIntegrationService.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 } =\n bigcommerce_payments_paylater;\n\n const fundingSources = [bigCommerceSdk.FUNDING.PAYLATER, bigCommerceSdk.FUNDING.CREDIT];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (hasRenderedSmartButton) {\n return;\n }\n\n const buttonOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(\n checkoutPaymentButtonStyles,\n ),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_paylater',\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.bigCommercePaymentsButtons = bigCommerceSdk.Buttons(buttonOptions);\n\n if (\n !this.bigCommercePaymentsButtons.isEligible() &&\n fundingSource === bigCommerceSdk.FUNDING.PAYLATER\n ) {\n return;\n }\n\n if (\n !this.bigCommercePaymentsButtons.isEligible() &&\n fundingSource === bigCommerceSdk.FUNDING.CREDIT\n ) {\n throw new NotImplementedError(\n `BigCommercePayments ${fundingSource} is not available for your region. Please use BigCommercePayments Checkout instead.`,\n );\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.bigCommercePaymentsButtons.render(container);\n hasRenderedSmartButton = true;\n });\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: BigCommercePaymentsPayLaterPaymentInitializeOptions['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: BigCommercePaymentsPayLaterPaymentInitializeOptions['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: BigCommercePaymentsPayLaterPaymentInitializeOptions['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,\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: checkout.outstandingBalance,\n placement: 'payment',\n style: getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\n };\n\n paypalMessages.Messages(paypalMessagesOptions).render(`#${bannerContainerId}`);\n }\n}\n","import { createBigCommercePaymentsSdk } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport { LOADING_INDICATOR_STYLES } from '../bigcommerce-payments-constants';\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsPayLaterPaymentStrategy from './bigcommerce-payments-paylater-payment-strategy';\n\nconst createBigCommercePaymentsPayLaterPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsPayLaterPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsPayLaterPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n createBigCommercePaymentsSdk(),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsPayLaterPaymentStrategy, [\n { id: 'bigcommerce_payments_paylater' },\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n BigCommercePaymentsInitializationData,\n BirthDate,\n PayPalOrderStatus,\n} from '../bigcommerce-payments-types';\n\nimport {\n BigCommercePaymentsRatePayPaymentInitializeOptions,\n WithBigCommercePaymentsRatePayPaymentInitializeOptions,\n} from './bigcommerce-payments-ratepay-initialize-options';\n\nconst POLLING_INTERVAL = 3000;\nconst MAX_POLLING_TIME = 300000;\n\nexport default class BigCommercePaymentsRatePayPaymentStrategy implements PaymentStrategy {\n private guid?: string;\n private bigcommerce_payments_ratepay?: BigCommercePaymentsRatePayPaymentInitializeOptions;\n private loadingIndicatorContainer?: string;\n private pollingTimer = 0;\n private stopPolling = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\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 & WithBigCommercePaymentsRatePayPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, bigcommerce_payments_ratepay } = 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 (!bigcommerce_payments_ratepay) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_ratepay\" argument is not provided.`,\n );\n }\n\n const { legalTextContainer, container, loadingContainerId } = bigcommerce_payments_ratepay;\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.bigcommerce_payments_ratepay = bigcommerce_payments_ratepay;\n\n await this.bigCommercePaymentsIntegrationService.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.bigcommerce_payments_ratepay || {};\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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_apmscheckout',\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.bigcommerce_payments_ratepay || {};\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 bigCommercePaymentsSdk =\n this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const ratePayButton = bigCommercePaymentsSdk.Legal({\n fundingSource: bigCommercePaymentsSdk.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.bigcommerce_payments_ratepay || {};\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 & WithBigCommercePaymentsRatePayPaymentInitializeOptions,\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.bigCommercePaymentsIntegrationService.getOrderStatus(\n 'bigcommerce_payments_apms',\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 bigcommerce_payments_ratepay: this.bigcommerce_payments_ratepay,\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 { LOADING_INDICATOR_STYLES } from '../bigcommerce-payments-constants';\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsRatePayPaymentStrategy from './bigcommerce-payments-ratepay-payment-strategy';\n\nconst createBigCommercePaymentsRatePayPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsRatePayPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsRatePayPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n new LoadingIndicator({\n containerStyles: { ...LOADING_INDICATOR_STYLES, position: 'fixed' },\n }),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsRatePayPaymentStrategy, [\n { gateway: 'bigcommerce_payments_apms', id: 'ratepay' },\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 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 { isNil, omitBy } from 'lodash';\n\nimport {\n BigCommercePaymentsFastlaneUtils,\n BigCommercePaymentsInitializationData,\n isBigCommercePaymentsFastlaneCustomer,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\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';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n BigCommercePaymentsCardFields,\n BigCommercePaymentsCardFieldsConfig,\n BigCommercePaymentsCardFieldsOnApproveData,\n BigCommercePaymentsCardFieldsState,\n BigCommercePaymentsFields,\n BigCommercePaymentsHostedFieldsRenderOptions,\n LiabilityShiftEnum,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsCreditCardsPaymentInitializeOptions, {\n WithBigCommercePaymentsCreditCardsPaymentInitializeOptions,\n} from './bigcommerce-payments-credit-cards-payment-initialize-options';\n\nexport default class BigCommercePaymentsCreditCardsPaymentStrategy implements PaymentStrategy {\n private executionPaymentData?: OrderPaymentRequestBody['paymentData'];\n private isCreditCardForm?: boolean;\n private isCreditCardVaultedForm?: boolean;\n\n private cardFields?: BigCommercePaymentsCardFields;\n private cvvField?: BigCommercePaymentsFields;\n private expiryField?: BigCommercePaymentsFields;\n private numberField?: BigCommercePaymentsFields;\n private nameField?: BigCommercePaymentsFields;\n\n private hostedFormOptions?: HostedFormOptions;\n private returnedOrderId?: string;\n private returnedVaultedToken?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private bigCommercePaymentsSdk: PayPalSdkHelper,\n private bigCommercePaymentsFastlaneUtils: BigCommercePaymentsFastlaneUtils,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions &\n WithBigCommercePaymentsCreditCardsPaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_creditcards } = options;\n const bigCommercePaymentsInitializationOptions = bigcommerce_payments_creditcards;\n\n const { form, onCreditCardFieldsRenderingError, onLoadComplete } =\n bigCommercePaymentsInitializationOptions || {};\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.bigcommerce_payments_creditcards.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.bigCommercePaymentsIntegrationService.loadPayPalSdk(\n methodId,\n undefined,\n true,\n true,\n );\n\n if (this.isCreditCardForm || this.isCreditCardVaultedForm) {\n await this.initializeFields(form, onCreditCardFieldsRenderingError);\n }\n\n onLoadComplete?.();\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 // The condition gets triggered when customer pays with vaulted instrument and shipping address is trusted\n const { orderId } =\n await this.bigCommercePaymentsIntegrationService.createOrderCardFields(\n 'bigcommerce_payments_creditcardscheckout',\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?: BigCommercePaymentsCreditCardsPaymentInitializeOptions['onCreditCardFieldsRenderingError'],\n ): Promise {\n const { fields, styles } = formOptions;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const executeCallback = this.getExecuteCallback(fields);\n\n const cardFieldsConfig: BigCommercePaymentsCardFieldsConfig = {\n style: this.getInputStyles(styles),\n onApprove: ({\n orderID,\n vaultSetupToken,\n liabilityShift,\n }: BigCommercePaymentsCardFieldsOnApproveData) => {\n if (\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.bigCommercePaymentsIntegrationService.createOrderCardFields(\n 'bigcommerce_payments_creditcardscheckout',\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.bigCommercePaymentsIntegrationService.createOrderCardFields(\n 'bigcommerce_payments_creditcardscheckout',\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({\n orderID,\n vaultSetupToken,\n }: BigCommercePaymentsCardFieldsOnApproveData) {\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 }: BigCommercePaymentsCardFieldsState):\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 * */\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 }: BigCommercePaymentsCardFieldsState): HostedFieldValidateEventData {\n const updatedFields = { ...fields };\n\n delete updatedFields.cardNameField;\n\n const fieldsKeys = Object.keys(updatedFields) as Array<\n keyof BigCommercePaymentsCardFieldsState['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(): BigCommercePaymentsCardFields {\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 ): BigCommercePaymentsHostedFieldsRenderOptions['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: BigCommercePaymentsCardFieldsState,\n ): void {\n formOptions?.onValidate?.(this.getValidityData(event));\n }\n\n private onFocusHandler(\n formOptions: HostedFormOptions,\n event: BigCommercePaymentsCardFieldsState,\n ): void {\n formOptions?.onFocus?.(this.getFieldTypeByEmittedField(event));\n }\n\n private onBlurHandler(\n formOptions: HostedFormOptions,\n event: BigCommercePaymentsCardFieldsState,\n ): void {\n formOptions?.onBlur?.(this.getFieldTypeByEmittedField(event));\n }\n\n private onInputSubmitRequest(\n formOptions: HostedFormOptions,\n event: BigCommercePaymentsCardFieldsState,\n ): void {\n formOptions?.onEnter?.(this.getFieldTypeByEmittedField(event));\n }\n\n /**\n *\n * BigCommercePayments Accelerated checkout related methods\n *\n */\n // TODO: remove this part when BCP Fastlane 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 bigCommercePaymentsPaymentProviderCustomer = isBigCommercePaymentsFastlaneCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n return (\n paymentMethod?.initializationData?.isAcceleratedCheckoutEnabled &&\n paymentMethod?.initializationData?.isBigCommercePaymentsAnalyticsV2Enabled &&\n !bigCommercePaymentsPaymentProviderCustomer?.authenticationState\n );\n }\n\n // TODO: remove this part when BCP Fastlane 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.bigCommercePaymentsSdk.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n );\n\n await this.bigCommercePaymentsFastlaneUtils.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 PaymentProviderCustomer,\n PayPalConnectCustomer,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isBigCommercePaymentsFastlaneCustomer(\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 createBigCommercePaymentsFastlaneUtils,\n createBigCommercePaymentsSdk,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsCreditCardsPaymentStrategy from './bigcommerce-payments-credit-cards-payment-strategy';\n\nconst createBigCommercePaymentsCreditCardsPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsCreditCardsPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsCreditCardsPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n createBigCommercePaymentsSdk(),\n createBigCommercePaymentsFastlaneUtils(),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsCreditCardsPaymentStrategy, [\n { id: 'bigcommerce_payments_creditcards' },\n]);\n","import { noop } from 'lodash';\n\nimport {\n PayPalApmSdk,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodClientUnavailableError,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n TimeoutError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtons,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n NonInstantAlternativePaymentMethods,\n PayPalOrderStatus,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions, {\n WithBigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\n} from './bigcommerce-payments-alternative-methods-payment-initialize-options';\n\nconst POLLING_INTERVAL = 3000;\nconst MAX_POLLING_TIME = 300000;\n\nexport default class BigCommercePaymentsAlternativeMethodsPaymentStrategy\n implements PaymentStrategy\n{\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private bigCommercePaymentsButton?: BigCommercePaymentsButtons;\n private paypalApms?: PayPalApmSdk;\n private pollingTimer = 0;\n private stopPolling = noop;\n private isPollingEnabled = false;\n private bigCommercePaymentsAlternativeMethods?: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private bigCommercePaymentsSdkHelper: PayPalSdkHelper,\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 &\n WithBigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, bigcommerce_payments_apms } = options;\n\n this.bigCommercePaymentsAlternativeMethods = bigcommerce_payments_apms;\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 (!bigcommerce_payments_apms) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_apms\" 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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n\n this.isPollingEnabled = isExperimentEnabled(features, 'PAYPAL-5624.bcp_ideal_polling');\n\n // Info:\n // The APM 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 the button.\n if (orderId) {\n this.orderId = orderId;\n\n return;\n }\n\n this.paypalApms = await this.bigCommercePaymentsSdkHelper.getPayPalApmsSdk(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n );\n\n this.loadingIndicatorContainer = bigcommerce_payments_apms.container.split('#')[1];\n\n this.renderButton(methodId, gatewayId, bigcommerce_payments_apms);\n\n if (shouldRenderFields) {\n this.renderFields(methodId, bigcommerce_payments_apms);\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.isPollingEnabled && methodId === 'ideal') {\n await new Promise((resolve, reject) => {\n void this.initializePollingMechanism(methodId, resolve, reject, gatewayId);\n });\n }\n\n if (!this.isNonInstantPaymentMethod(methodId)) {\n await this.paymentIntegrationService.submitOrder(order, options);\n }\n\n await this.bigCommercePaymentsIntegrationService.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 if (this.isPollingEnabled) {\n this.resetPollingMechanism();\n }\n\n this.bigCommercePaymentsButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Polling mechanism\n *\n *\n * */\n private async initializePollingMechanism(\n methodId: string,\n resolvePromise: (value?: unknown) => void,\n rejectPromise: (value?: unknown) => 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.bigCommercePaymentsIntegrationService.getOrderStatus(\n gatewayId,\n );\n\n const isOrderApproved = orderStatus === PayPalOrderStatus.Approved;\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 bigCommercePaymentsAlternativeMethods: this.bigCommercePaymentsAlternativeMethods,\n });\n\n this.handleError(new TimeoutError());\n } catch (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 private async reinitializeStrategy(\n options: PaymentInitializeOptions &\n WithBigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\n ) {\n await this.deinitialize();\n await this.initialize(options);\n }\n\n private handleError(error: unknown) {\n const { onError } = this.bigCommercePaymentsAlternativeMethods || {};\n\n if (this.isPollingEnabled) {\n this.resetPollingMechanism();\n }\n\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n gatewayId: string,\n bigcommerce_payments_apms: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\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 } = bigcommerce_payments_apms;\n\n const buttonOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource: methodId,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(buttonStyle),\n onInit: (_, actions) => bigcommerce_payments_apms.onInitButton(actions),\n createOrder: () => this.onCreateOrder(methodId, gatewayId, bigcommerce_payments_apms),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onCancel: () => {\n this.toggleLoadingIndicator(false);\n this.deInitializePollingMechanism();\n },\n onError: (error) => {\n this.deInitializePollingMechanism();\n this.handleFailure(error, onError);\n },\n onClick: async (_, actions) =>\n bigcommerce_payments_apms.onValidate(actions.resolve, actions.reject),\n };\n\n this.bigCommercePaymentsButton = paypalAmpsSdk.Buttons(buttonOptions);\n\n if (!this.bigCommercePaymentsButton.isEligible()) {\n return;\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.bigCommercePaymentsButton.render(container);\n }\n\n private async onCreateOrder(\n methodId: string,\n gatewayId: string,\n bigcommerce_payments_apms: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\n ): Promise {\n const { onValidate } = bigcommerce_payments_apms;\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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_apms',\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.bigCommercePaymentsIntegrationService.submitPayment(\n methodId,\n orderId,\n gatewayId,\n );\n }\n\n return orderId;\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n }\n\n private handleFailure(\n error: Error,\n onError: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions['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 bigcommerce_payments_apms: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\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 } = bigcommerce_payments_apms;\n\n if (!apmFieldsContainer) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_apms\" 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 { createBigCommercePaymentsSdk } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport { LOADING_INDICATOR_STYLES } from '../bigcommerce-payments-constants';\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsAlternativeMethodsPaymentStrategy from './bigcommerce-payments-alternative-methods-payment-strategy';\n\nconst createBigCommercePaymentsAlternativeMethodsPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsAlternativeMethodsPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsAlternativeMethodsPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n createBigCommercePaymentsSdk(),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsAlternativeMethodsPaymentStrategy, [\n { gateway: 'bigcommerce_payments_apms' },\n]);\n","import { isRedirectError } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsRedirectAlternativeMethodsPaymentInitializeOptions, {\n WithBigCommercePaymentsRedirectAlternativeMethodsPaymentInitializeOptions,\n} from './bigcomemrce-payments-redirect-alternative-methods-payment-initialize-options';\n\nexport default class BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy\n implements PaymentStrategy\n{\n private bigCommercePaymentsAlternativeMethods?: BigCommercePaymentsRedirectAlternativeMethodsPaymentInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n initialize(\n options: PaymentInitializeOptions &\n WithBigCommercePaymentsRedirectAlternativeMethodsPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, bigcommerce_payments_apms } = options;\n\n this.bigCommercePaymentsAlternativeMethods = bigcommerce_payments_apms;\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 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, gatewayId } = payment;\n\n try {\n const orderId = await this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_apms',\n {\n gatewayId: 'bigcommerce_payments_apms',\n methodId,\n },\n );\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: methodId,\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,\n gatewayId,\n paymentData,\n });\n } catch (error: unknown) {\n if (isRedirectError(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 reject();\n });\n }\n\n this.handleError(error);\n\n return Promise.reject(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 handleError(error: unknown) {\n const { onError } = this.bigCommercePaymentsAlternativeMethods || {};\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n}\n","import { isRequestError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RedirectError } from '../bigcommerce-payments-types';\n\nexport default function isRedirectError(error: unknown): error is RedirectError {\n return isRequestError(error) && error.body?.additional_action_required?.data.redirect_url;\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy from './bigcomemrce-payments-redirect-alternative-methods-payment-strategy';\n\nconst createBigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(\n createBigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy,\n [\n { gateway: 'bigcommerce_payments_apms', id: 'klarna' },\n { gateway: 'bigcommerce_payments_apms', id: 'afterpay' },\n ],\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtons,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n ClickCallbackActions,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsVenmoPaymentInitializeOptions, {\n WithBigCommercePaymentsVenmoPaymentInitializeOptions,\n} from './bigcommerce-payments-venmo-payment-initialize-options';\n\nexport default class BigCommercePaymentsVenmoPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: BigCommercePaymentsButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithBigCommercePaymentsVenmoPaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_venmo } = 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 (!bigcommerce_payments_venmo) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_venmo\" 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.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = bigcommerce_payments_venmo.container.split('#')[1];\n\n this.renderButton(methodId, bigcommerce_payments_venmo);\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.bigCommercePaymentsIntegrationService.submitPayment(\n payment.methodId,\n this.orderId,\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 bigcommerce_payments_venmo: BigCommercePaymentsVenmoPaymentInitializeOptions,\n ): void {\n const paypalSdk = this.bigCommercePaymentsIntegrationService.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 } =\n bigcommerce_payments_venmo;\n\n const buttonOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(\n checkoutPaymentButtonStyles,\n ),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_venmocheckout',\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()) {\n throw new NotImplementedError(\n `Venmo is not available for your region. Please another payment method 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: BigCommercePaymentsVenmoPaymentInitializeOptions['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: BigCommercePaymentsVenmoPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n this.toggleLoadingIndicator(false);\n }\n\n private handleError(\n error: Error,\n onError: BigCommercePaymentsVenmoPaymentInitializeOptions['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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsVenmoPaymentStrategy from './bigcommerce-payments-venmo-payment-strategy';\n\nconst createBigCommercePaymentsVenmoPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsVenmoPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsVenmoPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsVenmoPaymentStrategy, [\n { id: 'bigcommerce_payments_venmo' },\n]);\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","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","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 { 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 try {\n await this._blueSnapDirectHostedForm.attach(\n this._getPaymentFieldsToken(),\n creditCard,\n is3dsEnabled,\n );\n } catch (error) {\n if (error instanceof InvalidArgumentError) {\n return;\n }\n throw error;\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","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 ...(payment.paymentData.companyName\n ? { company_name: payment.paymentData.companyName }\n : {}),\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(\n paymentIntegrationService,\n createBraintreeSdk(paymentIntegrationService),\n );\n};\n\nexport default toResolvableModule(createBraintreeAchPaymentStrategy, [{ id: 'braintreeach' }]);\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport BraintreeSdk from './braintree-sdk';\nimport BraintreeSDKVersionManager from './braintree-sdk-version-manager';\n\nconst createBraintreeSdk = (paymentIntegrationService: PaymentIntegrationService) => {\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeScriptLoader = new BraintreeScriptLoader(\n getScriptLoader(),\n window,\n braintreeSDKVersionManager,\n );\n\n return new BraintreeSdk(braintreeScriptLoader);\n};\n\nexport default createBraintreeSdk;\n","import { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BraintreeHostWindow,\n BraintreeInitializationData,\n PayPalBNPLConfigurationItem,\n} from './braintree';\nimport { MessagesStyleOptions, MessagingPlacements } from './paypal';\n\nexport default class BraintreeMessages {\n private braintreeHostWindow: BraintreeHostWindow = window;\n\n constructor(private paymentIntegrationService: PaymentIntegrationService) {}\n\n render(methodId: string, containerId: string, placement: MessagingPlacements): void {\n const messagingContainer = containerId && document.getElementById(containerId);\n\n if (this.braintreeHostWindow.paypal && messagingContainer) {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const billingAddress = state.getBillingAddressOrThrow();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n if (!paymentMethod.initializationData) {\n return;\n }\n\n const { paypalBNPLConfiguration = [] } = paymentMethod.initializationData;\n\n const bannedId = placement === MessagingPlacements.PAYMENT ? 'checkout' : placement;\n const bannerConfiguration =\n paypalBNPLConfiguration &&\n paypalBNPLConfiguration.find(({ id }) => id === bannedId);\n\n if (!bannerConfiguration || !bannerConfiguration.status) {\n return;\n }\n\n // TODO: remove this code when this data attributes will be removed from banner div container in content service\n if (placement === MessagingPlacements.CART) {\n messagingContainer.removeAttribute('data-pp-style-logo-type');\n messagingContainer.removeAttribute('data-pp-style-logo-position');\n messagingContainer.removeAttribute('data-pp-style-text-color');\n messagingContainer.removeAttribute('data-pp-style-text-size');\n }\n\n this.braintreeHostWindow.paypal\n .Messages({\n amount: cart.cartAmount,\n buyerCountry: billingAddress.countryCode,\n placement,\n style: this.getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\n })\n .render(`#${containerId}`);\n }\n }\n\n private 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}\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","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 BraintreeInitializationData,\n BraintreeIntegrationService,\n BraintreeMessages,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n MessagingPlacements,\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 braintreeButtonOptions?: 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 braintreeMessages: BraintreeMessages,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreePaypalPaymentInitializeOptions,\n ) {\n const { braintree: braintreeOptions, methodId } = options;\n\n if (braintreeOptions?.containerId) {\n this.braintreeButtonOptions = braintreeOptions;\n }\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(braintreeOptions);\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(braintreeOptions);\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 if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { onError } = this.braintreeButtonOptions || {};\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)) {\n await this.loadPaypal();\n\n this.paypalButtonRender?.close();\n\n await this.loadPaypalCheckoutInstance(this.braintreeButtonOptions);\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(options?: BraintreePaypalPaymentInitializeOptions) {\n const { clientToken, initializationData, id: paymentMethodId } = 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 const isBraintreePaypalCredit = paymentMethodId === 'braintreepaypalcredit';\n const shouldShowPayPalCreditBanner =\n isBraintreePaypalCredit || !initializationData?.isCreditEnabled;\n\n await this.braintreeIntegrationService.getPaypalCheckout(\n paypalCheckoutConfig,\n (braintreePaypalCheckout) => {\n if (\n shouldShowPayPalCreditBanner &&\n paymentMethodId &&\n options?.bannerContainerId\n ) {\n this.renderPayPalMessages(paymentMethodId, options.bannerContainerId);\n }\n\n this.renderPayPalButton(braintreePaypalCheckout, options);\n },\n this.handleError,\n );\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private renderPayPalMessages(methodId: string, containerId: string) {\n this.braintreeMessages.render(methodId, containerId, MessagingPlacements.PAYMENT);\n }\n\n private renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n options?: BraintreePaypalPaymentInitializeOptions,\n ) {\n const { onPaymentError, submitForm, onRenderButton, containerId, onError } = options || {};\n\n if (!containerId) {\n return;\n }\n\n const container = this.getSmartButtonContainerId(containerId);\n const smartButtonContainer = document.getElementById(container);\n\n if (!smartButtonContainer) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because element with id ${containerId} does not exist.`,\n );\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 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 private getSmartButtonContainerId(container: string) {\n return container.split('#')[1] ?? container;\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 BraintreeMessages,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n overlay,\n );\n const braintreeMessages = new BraintreeMessages(paymentIntegrationService);\n\n return new BraintreePaypalPaymentStrategy(\n paymentIntegrationService,\n braintreeIntegrationService,\n braintreeMessages,\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 { RequestSender } from '@bigcommerce/request-sender';\n\nimport { BraintreeOrderStatusData } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class BraintreeRequestSender {\n constructor(private requestSender: RequestSender) {}\n\n async getOrderStatus(\n methodId = 'braintreelocalmethods',\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 { noop } from 'lodash';\n\nimport {\n BraintreeInitializationData,\n BraintreeLocalPayment,\n BraintreeLocalPaymentConfig,\n BraintreeLocalPaymentMethodRedirectAction,\n BraintreeLocalPaymentsPayload,\n BraintreeLPMPaymentStartData,\n BraintreeLPMStartPaymentError,\n BraintreeOrderSavedResponse,\n BraintreeOrderStatus,\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 TimeoutError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport BraintreeRequestSender from '../braintree-request-sender';\n\nimport {\n BraintreeLocalMethodsPaymentInitializeOptions,\n WithBraintreeLocalMethodsPaymentInitializeOptions,\n} from './braintree-local-methods-payment-initialize-options';\n\nconst POLLING_INTERVAL = 3000;\nconst MAX_POLLING_TIME = 300000;\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 gatewayId?: string;\n private isLPMsUpdateExperimentEnabled = false;\n private pollingTimer = 0;\n private stopPolling = noop;\n private isPollingEnabled = false;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeSdk: BraintreeSdk,\n private braintreeRequestSender: BraintreeRequestSender,\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 & WithBraintreeLocalMethodsPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, braintreelocalmethods } = options;\n\n this.gatewayId = gatewayId;\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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n\n this.isPollingEnabled = isExperimentEnabled(\n features,\n 'PAYPAL-5258.braintree_local_methods_polling',\n );\n\n this.isLPMsUpdateExperimentEnabled = isExperimentEnabled(\n features,\n 'PAYPAL-4853.add_new_payment_flow_for_braintree_lpms',\n );\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 const checkoutUrl = state.getStoreConfigOrThrow().links.checkoutLink;\n\n return {\n paymentType: methodId,\n amount: grandTotal,\n fallback: {\n url: checkoutUrl,\n buttonText: 'Complete Payment',\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 if (this.isPollingEnabled) {\n return new Promise((resolve, reject) => {\n void this.initializePollingMechanism(\n methodId,\n resolve,\n reject,\n this.gatewayId,\n );\n });\n }\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 this.resetPollingMechanism();\n\n return reject();\n }\n\n if (this.isPollingEnabled) {\n this.resetPollingMechanism();\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 if (this.isPollingEnabled) {\n this.resetPollingMechanism();\n }\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 /**\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.braintreeRequestSender.getOrderStatus(gatewayId, {\n params: {\n useMetadata: false,\n },\n });\n\n const isOrderPending = orderStatus.status === BraintreeOrderStatus.Pending;\n const isOrderApproved = orderStatus.status === BraintreeOrderStatus.Completed;\n const isPollingError = orderStatus.status === BraintreeOrderStatus.Failed;\n\n if (isOrderApproved) {\n this.deinitializePollingMechanism();\n\n return resolvePromise();\n }\n\n if (isPollingError) {\n return rejectPromise();\n }\n\n if (\n !isOrderApproved &&\n isOrderPending &&\n this.pollingTimer < this.maxPollingIntervalTime\n ) {\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 braintreelocalmethods: this.braintreelocalmethods,\n });\n\n this.handleError(new TimeoutError());\n } catch (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 private async reinitializeStrategy(\n options: PaymentInitializeOptions & WithBraintreeLocalMethodsPaymentInitializeOptions,\n ) {\n await this.deinitialize();\n await this.initialize(options);\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\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 BraintreeRequestSender from '../braintree-request-sender';\n\nimport BraintreeLocalMethodsPaymentStrategy from './braintree-local-methods-payment-strategy';\n\nconst createBraintreeLocalMethodsPaymentStrategy: PaymentStrategyFactory<\n BraintreeLocalMethodsPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n );\n const requestSender = createRequestSender();\n const braintreeRequestSender = new BraintreeRequestSender(requestSender);\n\n return new BraintreeLocalMethodsPaymentStrategy(\n paymentIntegrationService,\n braintreeSdk,\n braintreeRequestSender,\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 Braintree3DSVerifyCardError,\n Braintree3DSVerifyCardPayload,\n BraintreeFastlaneAddress,\n BraintreeFastlaneAuthenticationState,\n BraintreeFastlaneCardComponent,\n BraintreeFastlaneCardComponentOptions,\n BraintreeInitializationData,\n BraintreeSdk,\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 PaymentMethodCancelledError,\n PaymentMethodClientUnavailableError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\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 private is3DSEnabled?: boolean;\n private onError?: (error: Error) => void;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeFastlaneUtils: BraintreeFastlaneUtils,\n private braintreeSdk: BraintreeSdk,\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 await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { initializationData, clientToken } = paymentMethod || {};\n const { isFastlaneStylingEnabled } = initializationData || {};\n const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const isThreeDSExperimentEnabled = isExperimentEnabled(\n features,\n 'PROJECT-7080.braintree_fastlane_three_ds',\n );\n\n this.is3DSEnabled = paymentMethod.config.is3dsEnabled;\n\n if (clientToken && isThreeDSExperimentEnabled) {\n this.braintreeSdk.initialize(clientToken);\n }\n\n const paypalFastlaneStyleSettings = isFastlaneStylingEnabled\n ? paymentMethod.initializationData?.fastlaneStyles\n : undefined;\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 this.onError = braintreefastlane.onError;\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 await this.paymentIntegrationService.submitOrder(order, options);\n\n const paymentPayload = await this.preparePaymentPayload(payment.methodId);\n\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n\n this.braintreeFastlaneUtils.removeSessionIdFromCookies();\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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const isThreeDSExperimentEnabled = isExperimentEnabled(\n features,\n 'PROJECT-7080.braintree_fastlane_three_ds',\n );\n\n if (paypalInstrument) {\n const threeDSToken =\n this.is3DSEnabled && isThreeDSExperimentEnabled\n ? await this.get3DS(paypalInstrument.bigpayToken, paypalInstrument?.iin || '')\n : undefined;\n\n return {\n methodId,\n paymentData: {\n deviceSessionId,\n formattedPayload: {\n paypal_fastlane_token: {\n token: threeDSToken || paypalInstrument.bigpayToken,\n },\n },\n },\n };\n }\n\n const { getPaymentToken } = this.getBraintreeCardComponentOrThrow();\n\n const paymentToken = await getPaymentToken({\n name: { fullName },\n billingAddress: this.mapToPayPalAddress(billingAddress),\n });\n\n const binGuest = paymentToken.paymentSource.card?.binDetails?.bin || '';\n const threeDSToken =\n this.is3DSEnabled && isThreeDSExperimentEnabled\n ? await this.get3DS(paymentToken.id, binGuest)\n : undefined;\n\n return {\n methodId,\n paymentData: {\n deviceSessionId,\n nonce: threeDSToken || paymentToken.id,\n },\n };\n }\n\n /**\n * 3DS\n */\n private async get3DS(nonce: string, bin: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const threeDSecure = await this.braintreeSdk.getBraintreeThreeDS();\n const order = state.getOrderOrThrow();\n\n return new Promise((resolve, reject) => {\n void threeDSecure.verifyCard(\n {\n amount: order?.orderAmount,\n nonce,\n bin,\n onLookupComplete: (_data, next) => {\n threeDSecure.on('customer-canceled', () => {\n if (typeof this.onError === 'function') {\n this.onError(new PaymentMethodCancelledError());\n }\n\n reject(new PaymentMethodCancelledError());\n });\n\n next();\n },\n },\n (\n verifyError: Braintree3DSVerifyCardError,\n payload: Braintree3DSVerifyCardPayload,\n ) => {\n if (\n verifyError &&\n verifyError.code === 'THREEDS_VERIFY_CARD_CANCELED_BY_MERCHANT'\n ) {\n if (typeof this.onError === 'function') {\n this.onError(new PaymentMethodCancelledError());\n }\n\n reject(new PaymentMethodCancelledError());\n }\n\n return resolve(payload.nonce);\n },\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.braintreeFastlaneUtils.getSessionIdFromCookies();\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 BraintreeSdk,\n BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n );\n\n const braintreeFastlaneUtils = new BraintreeFastlaneUtils(\n paymentIntegrationService,\n braintreeIntegrationService,\n );\n\n const braintreeScriptLoader = new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n );\n\n const braintreeSdk = new BraintreeSdk(braintreeScriptLoader);\n\n return new BraintreeFastlanePaymentStrategy(\n paymentIntegrationService,\n braintreeFastlaneUtils,\n braintreeSdk,\n );\n};\n\nexport default toResolvableModule(createBraintreeFastlanePaymentStrategy, [\n { id: 'braintreeacceleratedcheckout' },\n]);\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { noop } from 'lodash';\n\nimport {\n BraintreeDataCollector,\n BraintreeInitializationData,\n BraintreeSdk,\n BraintreeVisaCheckout,\n VisaCheckoutAddress,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutTokenizedPayload,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n Address,\n InvalidArgumentError,\n LegacyAddress,\n MissingDataError,\n MissingDataErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithBraintreeVisaCheckoutPaymentInitializeOptions } from './braintree-visa-checkout-payment-options';\n\nexport default class BraintreeVisaCheckoutPaymentStrategy implements PaymentStrategy {\n private paymentMethod?: PaymentMethod;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private formPoster: FormPoster,\n private braintreeSdk: BraintreeSdk,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeVisaCheckoutPaymentInitializeOptions,\n ): 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 await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n\n this.paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n const checkout = state.getCheckoutOrThrow();\n const storeConfig = state.getStoreConfigOrThrow();\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 this.braintreeSdk.initialize(clientToken);\n\n const braintreeVisaCheckout = await this.braintreeSdk.getBraintreeVisaCheckout();\n\n const visaCheckoutSdk = await this.braintreeSdk.getVisaCheckoutSdk(config?.testMode);\n\n const initOptions = braintreeVisaCheckout.createInitOptions({\n settings: {\n locale: storeConfig.storeProfile.storeLanguage,\n shipping: {\n collectShipping: false,\n },\n },\n paymentRequest: {\n currencyCode: storeConfig.currency.code,\n subtotal: String(checkout.subtotal),\n },\n });\n\n await visaCheckoutSdk.init(initOptions);\n\n visaCheckoutSdk.on(\n 'payment.success',\n (paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) =>\n this.tokenizePayment(braintreeVisaCheckout, paymentSuccessPayload)\n .then(() =>\n Promise.all([\n this.paymentIntegrationService.loadCheckout(),\n this.paymentIntegrationService.loadPaymentMethod(methodId),\n ]),\n )\n .then(() => onPaymentSelect())\n .catch((error) => onError(error)),\n );\n visaCheckoutSdk.on('payment.error', (_, error) => onError(error));\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\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 (!this.paymentMethod?.initializationData?.nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { nonce } = this.paymentMethod.initializationData;\n\n try {\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: { nonce },\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.braintreeSdk.deinitialize();\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 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 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 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 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","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\n VisaCheckoutHostWindow,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeVisaCheckoutPaymentStrategy from './braintree-visa-checkout-payment-strategy';\n\nconst createBraintreeVisaCheckoutPaymentStrategy: PaymentStrategyFactory<\n BraintreeVisaCheckoutPaymentStrategy\n> = (paymentIntegrationService) => {\n const hostWindow: VisaCheckoutHostWindow & BraintreeHostWindow = window;\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), hostWindow, braintreeSDKVersionManager),\n );\n\n return new BraintreeVisaCheckoutPaymentStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeSdk,\n );\n};\n\nexport default toResolvableModule(createBraintreeVisaCheckoutPaymentStrategy, [\n { id: 'braintreevisacheckout' },\n]);\n","import {\n BraintreeError,\n BraintreeIntegrationService,\n BraintreeTokenizePayload,\n BraintreeVenmoCheckout,\n isBraintreeError,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n FormattedPayload,\n MissingDataError,\n MissingDataErrorType,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n PaymentStrategy,\n PaypalInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\nimport BraintreeVenmoPaymentStrategyInitializeOptions, {\n WithBraintreeVenmoInitializeOptions,\n} from './braintree-venmo-payment-strategy-initialize-options';\n\nexport default class BraintreeVenmoPaymentStrategy implements PaymentStrategy {\n private braintreeVenmoCheckout?: BraintreeVenmoCheckout;\n private venmoOptions?: BraintreeVenmoPaymentStrategyInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeIntegrationService: BraintreeIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeVenmoInitializeOptions,\n ): Promise {\n const { methodId } = options;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n const state = this.paymentIntegrationService.getState();\n\n this.venmoOptions = options.braintreevenmo;\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n await this.initializeBraintreeVenmo(paymentMethod);\n }\n\n async execute(orderRequest: OrderRequestBody): 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 await this.paymentIntegrationService.submitOrder(order);\n await this.paymentIntegrationService.submitPayment(paymentData);\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.braintreeIntegrationService.teardown();\n\n return Promise.resolve();\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 const state = this.paymentIntegrationService.getState();\n const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const isBraintreeVenmoWebFallbackSupport = isExperimentEnabled(\n features,\n 'PAYPAL-5406.braintree_venmo_web_fallback_support',\n );\n\n try {\n this.braintreeIntegrationService.initialize(clientToken);\n this.braintreeVenmoCheckout = await this.braintreeIntegrationService.getVenmoCheckout({\n ...(this.venmoOptions?.allowDesktop !== undefined\n ? { allowDesktop: this.venmoOptions.allowDesktop }\n : {}),\n ...(isBraintreeVenmoWebFallbackSupport\n ? {\n mobileWebFallBack: isBraintreeVenmoWebFallbackSupport,\n }\n : {}),\n });\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async preparePaymentData(payment: OrderPaymentRequestBody): Promise {\n const state = this.paymentIntegrationService.getState();\n const { nonce } = state.getPaymentMethodOrThrow(payment.methodId);\n\n if (nonce) {\n return { ...payment, paymentData: this.formattedPayload(nonce) };\n }\n const tokenizeResult = await this.braintreeVenmoTokenize();\n const sessionId = await this.braintreeIntegrationService.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 {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport BraintreeVenmoPaymentStrategy from './braintree-venmo-payment-strategy';\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nconst createBraintreeVenmoPaymentStrategy: CheckoutButtonStrategyFactory<\n BraintreeVenmoPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const scriptLoader = getScriptLoader();\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeScriptLoader = new BraintreeScriptLoader(\n scriptLoader,\n braintreeHostWindow,\n braintreeSDKVersionManager,\n );\n const braintreeIntegrationService = new BraintreeIntegrationService(\n braintreeScriptLoader,\n braintreeHostWindow,\n );\n\n return new BraintreeVenmoPaymentStrategy(\n paymentIntegrationService,\n braintreeIntegrationService,\n );\n};\n\nexport default toResolvableModule(createBraintreeVenmoPaymentStrategy, [{ id: 'braintreevenmo' }]);\n","import { some } from 'lodash';\n\nimport {\n BraintreeIntegrationService,\n BraintreeThreeDSecureOptions,\n isBraintreeAcceleratedCheckoutCustomer,\n isBraintreePaymentRequest3DSError,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n Address,\n isHostedInstrumentLike,\n isRequestError,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NonceInstrument,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentInstrument,\n PaymentInstrumentMeta,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodFailedError,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeHostedForm from '../braintree-hosted-form/braintree-hosted-form';\nimport isBraintreeError from '../is-braintree-error';\n\nimport {\n BraintreeCreditCardPaymentInitializeOptions,\n WithBraintreeCreditCardPaymentInitializeOptions,\n} from './braintree-credit-card-payment-initialize-options';\n\nexport default class BraintreeCreditCardPaymentStrategy implements PaymentStrategy {\n private is3dsEnabled?: boolean;\n private isHostedFormInitialized?: boolean;\n private deviceSessionId?: string;\n private paymentMethod?: PaymentMethod;\n private threeDSecure?: BraintreeThreeDSecureOptions;\n private onPaymentError?: BraintreeCreditCardPaymentInitializeOptions['onPaymentError'];\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeIntegrationService: BraintreeIntegrationService,\n private braintreeHostedForm: BraintreeHostedForm,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeCreditCardPaymentInitializeOptions,\n ): Promise {\n const { methodId, gatewayId, braintree } = options;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n\n this.paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n const { clientToken } = this.paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.threeDSecure = braintree?.threeDSecure;\n this.onPaymentError = braintree?.onPaymentError;\n\n try {\n this.braintreeIntegrationService.initialize(clientToken, this.threeDSecure);\n\n if (this.isHostedPaymentFormEnabled(methodId, gatewayId) && braintree?.form) {\n await this.braintreeHostedForm.initialize(\n braintree.form,\n braintree.unsupportedCardBrands,\n clientToken,\n );\n\n this.isHostedFormInitialized = this.braintreeHostedForm.isInitialized();\n }\n\n this.is3dsEnabled = this.paymentMethod.config.is3dsEnabled;\n this.deviceSessionId = await this.braintreeIntegrationService.getSessionId();\n\n // TODO: Remove when BT AXO A/B testing is finished\n if (this.shouldInitializeBraintreeFastlane()) {\n await this.initializeBraintreeFastlaneOrThrow(methodId);\n }\n } catch (error) {\n return this.handleError(error, methodId);\n }\n }\n\n async execute(orderRequest: OrderRequestBody): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (this.isHostedFormInitialized) {\n this.braintreeHostedForm.validate();\n }\n\n await this.paymentIntegrationService.submitOrder(order);\n\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddressOrThrow();\n const orderAmount = state.getOrderOrThrow().orderAmount;\n\n try {\n const paymentData = this.isHostedFormInitialized\n ? await this.prepareHostedPaymentData(payment, billingAddress, orderAmount)\n : await this.preparePaymentData(payment, billingAddress, orderAmount);\n\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData,\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.braintreeIntegrationService.teardown(),\n this.braintreeHostedForm.deinitialize(),\n ]);\n\n return Promise.resolve();\n }\n\n private handleError(error: unknown, methodId?: string): void | Promise {\n if (isBraintreeError(error)) {\n const isPaymentMethodInitialized = !!(\n methodId &&\n this.paymentIntegrationService.getState().isPaymentMethodInitialized({ methodId })\n );\n\n if (\n !isPaymentMethodInitialized &&\n error.code === 'HOSTED_FIELDS_INVALID_FIELD_SELECTOR'\n ) {\n return;\n }\n\n if (error.code.startsWith('THREEDS_')) {\n this.onPaymentError?.(new PaymentMethodFailedError('THREEDS_VERIFICATION_FAILED'));\n\n return Promise.reject();\n }\n\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.braintreeIntegrationService.verifyCard(\n payment,\n billingAddress,\n orderAmount,\n )\n : await this.braintreeIntegrationService.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 } = await this.braintreeHostedForm.tokenizeForStoredCardVerification();\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.verifyCardWithHostedForm(billingAddress, orderAmount)\n : await this.braintreeHostedForm.tokenize(billingAddress);\n\n return {\n ...commonPaymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n nonce,\n };\n }\n\n private prepareAdditionalActionPaymentData(\n payment: OrderPaymentRequestBody,\n nonce: string,\n ): PaymentInstrument & PaymentInstrumentMeta {\n const { paymentData } = payment;\n const commonPaymentData = { deviceSessionId: this.deviceSessionId, nonce };\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n if (\n this.isSubmittingWithStoredCard(payment) &&\n (shouldSaveInstrument || shouldSetAsDefaultInstrument)\n ) {\n return {\n ...paymentData,\n ...commonPaymentData,\n };\n }\n\n return {\n ...commonPaymentData,\n };\n }\n\n private async verifyCardWithHostedForm(\n billingAddress: Address,\n orderAmount: number,\n ): Promise {\n const tokenizationPayload = await this.braintreeHostedForm.tokenize(billingAddress);\n\n return this.braintreeIntegrationService.challenge3DSVerification(\n tokenizationPayload,\n orderAmount,\n );\n }\n\n private async processAdditionalAction(\n error: unknown,\n payment: OrderPaymentRequestBody,\n orderAmount: number,\n ): Promise {\n if (\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return this.handleError(error);\n }\n\n try {\n const { payer_auth_request: storedCreditCardNonce } =\n (isBraintreePaymentRequest3DSError(error) && error.body.three_ds_result) || {};\n const { paymentData } = payment;\n const state = this.paymentIntegrationService.getState();\n\n if (!paymentData || !isVaultedInstrument(paymentData)) {\n throw new PaymentArgumentInvalidError(['instrumentId']);\n }\n\n const instrument = state.getCardInstrumentOrThrow(paymentData.instrumentId);\n const { nonce } = await this.braintreeIntegrationService.challenge3DSVerification(\n {\n nonce: storedCreditCardNonce || '',\n bin: instrument.iin,\n },\n orderAmount,\n );\n\n const newPaymentData = this.prepareAdditionalActionPaymentData(payment, nonce);\n\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: newPaymentData,\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 state = this.paymentIntegrationService.getState();\n const paymentMethod = state.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 when BT AXO A/B testing is finished\n private shouldInitializeBraintreeFastlane(): boolean {\n const state = this.paymentIntegrationService.getState();\n const paymentProviderCustomer = state.getPaymentProviderCustomerOrThrow();\n const braintreeCustomer = isBraintreeAcceleratedCheckoutCustomer(paymentProviderCustomer)\n ? paymentProviderCustomer\n : {};\n const isFastlaneEnabled: boolean =\n this.paymentMethod?.initializationData.isAcceleratedCheckoutEnabled;\n\n return isFastlaneEnabled && !braintreeCustomer?.authenticationState;\n }\n\n // TODO: Remove when BT AXO A/B testing is finished\n private async initializeBraintreeFastlaneOrThrow(methodId: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { clientToken, config } = paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.braintreeIntegrationService.initialize(clientToken, this.threeDSecure);\n\n await this.braintreeIntegrationService.getBraintreeFastlane(cart.id, config.testMode);\n }\n}\n","export interface BraintreePayment3DSRequestErrors {\n code: string;\n}\n\nexport interface BraintreePaymentRequest3DSError {\n name: string;\n body: {\n status: string;\n three_ds_result: {\n payer_auth_request: string;\n };\n errors: BraintreePayment3DSRequestErrors[];\n };\n}\n\nexport default function isBraintreePaymentRequest3DSError(\n error: unknown,\n): error is BraintreePaymentRequest3DSError {\n if (typeof error !== 'object' || error === null) {\n return false;\n }\n /* eslint-disable @typescript-eslint/consistent-type-assertions */\n return (\n 'name' in error &&\n 'body' in error &&\n 'status' in (error as BraintreePaymentRequest3DSError).body &&\n 'three_ds_result' in (error as BraintreePaymentRequest3DSError).body &&\n 'payer_auth_request' in (error as BraintreePaymentRequest3DSError).body.three_ds_result &&\n 'errors' in (error as BraintreePaymentRequest3DSError).body\n );\n}\n","import { BraintreeFormFieldsMap, BraintreeStoredCardFieldsMap } from '../index';\n\nexport function isBraintreeFormFieldsMap(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n): fields is BraintreeFormFieldsMap {\n return 'cardNumber' in fields;\n}\n\nexport function isBraintreeStoredCardFieldsMap(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n): fields is BraintreeStoredCardFieldsMap {\n return !!(\n Object.keys(fields).length > 0 &&\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n ((fields as BraintreeStoredCardFieldsMap).cardCodeVerification ||\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n (fields as BraintreeStoredCardFieldsMap).cardNumberVerification)\n );\n}\n","import isBraintreeError from './is-braintree-error';\nimport { BraintreeHostedFormError } from '../types';\n\nfunction isValidInvalidFieldKeys(invalidFieldKeys: unknown): invalidFieldKeys is string[] {\n return (\n Array.isArray(invalidFieldKeys) && invalidFieldKeys.every((key) => typeof key === 'string')\n );\n}\n\nexport default function isBraintreeHostedFormError(\n error: unknown,\n): 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 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n (details as { invalidFieldKeys?: unknown }).invalidFieldKeys === undefined) ||\n isValidInvalidFieldKeys(details)\n );\n}\n","import { Dictionary, isEmpty, isNil, omitBy } from 'lodash';\n\nimport {\n BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION,\n BraintreeBillingAddressRequestData,\n BraintreeClient,\n BraintreeFormErrorDataKeys,\n BraintreeFormErrorsData,\n BraintreeFormFieldsMap,\n BraintreeFormFieldStyles,\n BraintreeFormFieldStylesMap,\n BraintreeFormFieldType,\n BraintreeFormFieldValidateErrorData,\n BraintreeFormFieldValidateEventData,\n BraintreeFormOptions,\n BraintreeHostedFields,\n BraintreeHostedFieldsCreatorConfig,\n BraintreeHostedFieldsState,\n BraintreeHostedFormError,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\n BraintreeStoredCardFieldsMap,\n isBraintreeFormFieldsMap,\n isBraintreeHostedFormError,\n isBraintreeSupportedCardBrand,\n TokenizationPayload,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n Address,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\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 client?: Promise;\n private clientToken?: string;\n private isInitializedHostedForm = false;\n\n constructor(\n private braintreeScriptLoader: BraintreeScriptLoader,\n private braintreeSDKVersionManager: BraintreeSDKVersionManager,\n ) {}\n\n async initialize(\n options: BraintreeFormOptions,\n unsupportedCardBrands?: string[],\n clientToken?: string,\n ): Promise {\n this.clientToken = clientToken;\n this.formOptions = options;\n this.type = isBraintreeFormFieldsMap(options.fields)\n ? BraintreeHostedFormType.CreditCard\n : BraintreeHostedFormType.StoredCardVerification;\n\n const fields = this.mapFieldOptions(options.fields, unsupportedCardBrands);\n\n if (isEmpty(fields)) {\n this.isInitializedHostedForm = false;\n\n return;\n }\n\n this.cardFields = await this.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 await this.cardFields?.teardown();\n }\n }\n\n validate(): void {\n if (!this.cardFields) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const state = this.cardFields.getState();\n\n if (!this.isValidForm(state)) {\n this.handleValidityChange(state);\n\n const errors = this.mapValidationErrors(state.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 payload = await this.cardFields.tokenize(\n omitBy(\n {\n billingAddress: billingAddress && this.mapBillingAddress(billingAddress),\n },\n isNil,\n ),\n );\n\n this.formOptions?.onValidate?.({ isValid: true, errors: {} });\n\n return {\n nonce: payload.nonce,\n bin: payload.details?.bin,\n };\n } catch (error) {\n if (isBraintreeHostedFormError(error)) {\n const errors = this.mapTokenizeError(error);\n\n if (errors) {\n this.formOptions?.onValidate?.({ isValid: false, errors });\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 payload = await this.cardFields.tokenize();\n\n this.formOptions?.onValidate?.({ isValid: true, errors: {} });\n\n return {\n nonce: payload.nonce,\n bin: payload.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?.({ isValid: false, errors });\n throw new PaymentInvalidFormError(errors as PaymentInvalidFormErrorDetails);\n }\n }\n\n throw error;\n }\n }\n\n async createHostedFields(\n options: Pick,\n ): Promise {\n const client = await this.getClient();\n const hostedFields = await this.braintreeScriptLoader.loadHostedFields();\n\n const currentSdkVersion = this.braintreeSDKVersionManager.getSDKVersion();\n const hostedFieldsOptions =\n currentSdkVersion === BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION\n ? { ...options, preventCursorJumps: true }\n : options;\n\n return hostedFields.create({ ...hostedFieldsOptions, client });\n }\n\n async getClient(): Promise {\n if (!this.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!this.client) {\n const client = await this.braintreeScriptLoader.loadClient();\n\n this.client = client.create({ authorization: this.clientToken });\n }\n\n return this.client;\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 unsupportedCardBrands?: string[],\n ): BraintreeHostedFieldsCreatorConfig['fields'] {\n if (isBraintreeFormFieldsMap(fields)) {\n const supportedCardBrands: Partial> = {};\n\n unsupportedCardBrands?.forEach((cardBrand) => {\n if (isBraintreeSupportedCardBrand(cardBrand)) {\n supportedCardBrands[cardBrand] = false;\n }\n });\n\n return omitBy(\n {\n number: {\n container: `#${fields.cardNumber.containerId}`,\n placeholder: fields.cardNumber.placeholder,\n internalLabel: fields.cardNumber.accessibilityLabel,\n ...(Object.keys(supportedCardBrands).length > 0\n ? { supportedCardBrands }\n : {}),\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 // eslint-disable-next-line no-restricted-syntax\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 cvv = [this.createRequiredError(this.mapFieldType('cvv'))];\n\n if (isStoredCard) {\n return { [this.mapFieldType('cvv')]: cvv };\n }\n\n return {\n [this.mapFieldType('cvv')]: cvv,\n [this.mapFieldType('expirationDate')]: [\n this.createRequiredError(this.mapFieldType('expirationDate')),\n ],\n [this.mapFieldType('number')]: [\n this.createRequiredError(this.mapFieldType('number')),\n ],\n [this.mapFieldType('cardholderName')]: [\n this.createRequiredError(this.mapFieldType('cardholderName')),\n ],\n };\n }\n\n return error.details?.invalidFieldKeys?.reduce((result, key) => {\n const type = this.mapFieldType(key);\n\n return {\n ...result,\n [type]: [this.createInvalidError(type)],\n };\n }, {});\n }\n\n private createRequiredError(\n fieldType: BraintreeFormFieldType,\n ): BraintreeFormFieldValidateErrorData {\n const messages = {\n [BraintreeFormFieldType.CardCode]: 'CVV is required',\n [BraintreeFormFieldType.CardCodeVerification]: 'CVV is required',\n [BraintreeFormFieldType.CardNumber]: 'Credit card number is required',\n [BraintreeFormFieldType.CardNumberVerification]: 'Credit card number is required',\n [BraintreeFormFieldType.CardExpiry]: 'Expiration date is required',\n [BraintreeFormFieldType.CardName]: 'Full name is required',\n };\n\n return {\n fieldType,\n message: messages[fieldType] ?? 'Field is required',\n type: 'required',\n };\n }\n\n private createInvalidError(\n fieldType: BraintreeFormFieldType,\n ): BraintreeFormFieldValidateErrorData {\n const formFields = {\n [BraintreeFormFieldType.CardCode]: {\n message: 'Invalid card code',\n type: 'invalid_card_code',\n },\n [BraintreeFormFieldType.CardCodeVerification]: {\n message: 'Invalid card code',\n type: 'invalid_card_code',\n },\n [BraintreeFormFieldType.CardNumber]: {\n message: 'Invalid card number',\n type: 'invalid_card_number',\n },\n [BraintreeFormFieldType.CardNumberVerification]: {\n message: 'Invalid card number',\n type: 'invalid_card_number',\n },\n [BraintreeFormFieldType.CardExpiry]: {\n message: 'Invalid card expiry',\n type: 'invalid_card_expiry',\n },\n [BraintreeFormFieldType.CardName]: {\n message: 'Invalid card name',\n type: 'invalid_card_name',\n },\n };\n\n return {\n fieldType,\n message: formFields[fieldType]?.message ?? 'Invalid field',\n type: formFields[fieldType]?.type ?? 'invalid',\n };\n }\n\n private handleBlur = (event: BraintreeHostedFieldsState): void => {\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 => {\n this.formOptions?.onFocus?.({\n fieldType: this.mapFieldType(event.emittedBy),\n });\n };\n\n private handleCardTypeChange = (event: BraintreeHostedFieldsState): void => {\n const cardType =\n event.cards.length === 1\n ? event.cards[0].type.replace(/^master-card$/, 'mastercard')\n : undefined;\n\n this.formOptions?.onCardTypeChange?.({ cardType });\n };\n\n private handleInputSubmitRequest = (event: BraintreeHostedFieldsState): void => {\n this.formOptions?.onEnter?.({\n fieldType: this.mapFieldType(event.emittedBy),\n });\n };\n\n private handleValidityChange = (event: BraintreeHostedFieldsState): void => {\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(key: string): key is BraintreeFormErrorDataKeys {\n return [\n 'number',\n 'cvv',\n 'expirationDate',\n 'postalCode',\n 'cardholderName',\n 'cardType',\n ].includes(key);\n }\n}\n","import { BraintreeSupportedCardBrands } from '../types';\n\nexport const isBraintreeSupportedCardBrand = (\n cardBrand: string,\n): cardBrand is BraintreeSupportedCardBrands => {\n const supportedCardBrands = Object.values(BraintreeSupportedCardBrands);\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return supportedCardBrands.includes(cardBrand as BraintreeSupportedCardBrands);\n};\n\nexport default isBraintreeSupportedCardBrand;\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeCreditCardPaymentStrategy from './braintree-credit-card-payment-strategy';\nimport BraintreeHostedForm from '../braintree-hosted-form/braintree-hosted-form';\n\nconst createBraintreeCreditCardPaymentStrategy: PaymentStrategyFactory<\n BraintreeCreditCardPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n\n const braintreeScriptLoader = new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n );\n\n const braintreeIntegrationService = new BraintreeIntegrationService(\n braintreeScriptLoader,\n braintreeHostWindow,\n );\n\n const braintreeHostedForm = new BraintreeHostedForm(\n braintreeScriptLoader,\n braintreeSDKVersionManager,\n );\n\n return new BraintreeCreditCardPaymentStrategy(\n paymentIntegrationService,\n braintreeIntegrationService,\n braintreeHostedForm,\n );\n};\n\nexport default toResolvableModule(createBraintreeCreditCardPaymentStrategy, [{ id: 'braintree' }]);\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 { noop, some } from 'lodash';\n\nimport { CreditCardPaymentStrategy } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStatusTypes,\n RequestError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\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';\nimport { isCBAMPGSPaymentMethodLike, isThreeDSErrorBody } from './is-cba-mpgs-payment-method-like';\n\nexport default class CBAMPGSPaymentStrategy extends CreditCardPaymentStrategy {\n private threeDSjs?: ThreeDSjs;\n\n private sessionId = '';\n private locale?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private cbaMGPSScriptLoader: CBAMPGSScriptLoader,\n ) {\n super(paymentIntegrationService);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const { methodId } = options;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n if (!isCBAMPGSPaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\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 this.locale = state.getLocale();\n\n if (!this.locale) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n await this.threeDSjs.configure({\n merchantId,\n sessionId: this.sessionId,\n callback: () => {\n if (this.threeDSjs?.isConfigured()) {\n return this.paymentIntegrationService.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();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): 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 state = this.paymentIntegrationService.getState();\n const paymentMethod = state.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 !isRequestError(error) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n const retryState = this.paymentIntegrationService.getState();\n const order = retryState.getOrder();\n\n const {\n storeProfile: { storeId },\n } = retryState.getStoreConfigOrThrow();\n\n if (!order || !this.sessionId) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const orderId = `${storeId}_${order.orderId}`;\n\n if (!isThreeDSErrorBody(error.body)) {\n throw new RequestError();\n }\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 async finalize(options?: PaymentRequestOptions): Promise {\n const state = this.paymentIntegrationService.getState();\n const order = state.getOrder();\n\n if (order && state.getPaymentStatus() === PaymentStatusTypes.FINALIZE) {\n await this.paymentIntegrationService.finalizeOrder(options);\n\n return Promise.resolve();\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(orderId: string, transactionId: string): 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 PaymentMethodFailedError(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 PaymentMethodFailedError());\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 PaymentMethodFailedError();\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 // eslint-disable-next-line @typescript-eslint/no-misused-promises\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 // eslint-disable-next-line no-plusplus, no-param-reassign\n return this.authenticatePayer(orderId, transactionId, ++attempt);\n }\n\n return reject(new PaymentMethodFailedError());\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","/* eslint-disable @typescript-eslint/consistent-type-assertions */\nimport { PaymentMethod } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CBAMPGSPaymentMethod, ThreeDSErrorBody } from './cba-mpgs';\n\nexport function isCBAMPGSPaymentMethodLike(\n paymentMethod: PaymentMethod,\n): paymentMethod is CBAMPGSPaymentMethod {\n return (\n typeof paymentMethod === 'object' &&\n paymentMethod !== null &&\n 'initializationData' in paymentMethod &&\n typeof (paymentMethod as CBAMPGSPaymentMethod).initializationData === 'object' &&\n (paymentMethod as CBAMPGSPaymentMethod).initializationData !== null &&\n 'merchantId' in (paymentMethod as CBAMPGSPaymentMethod).initializationData &&\n typeof (paymentMethod as CBAMPGSPaymentMethod).initializationData.merchantId === 'string' &&\n (typeof (paymentMethod as CBAMPGSPaymentMethod).initializationData.isTestModeFlagEnabled ===\n 'boolean' ||\n typeof (paymentMethod as CBAMPGSPaymentMethod).initializationData\n .isTestModeFlagEnabled === 'undefined')\n );\n}\n\nexport function isThreeDSErrorBody(body: unknown): body is ThreeDSErrorBody {\n return (\n typeof body === 'object' &&\n body !== null &&\n 'three_ds_result' in body &&\n typeof (body as ThreeDSErrorBody).three_ds_result === 'object' &&\n (body as ThreeDSErrorBody).three_ds_result !== null &&\n 'token' in (body as ThreeDSErrorBody).three_ds_result &&\n typeof (body as ThreeDSErrorBody).three_ds_result.token === 'string'\n );\n}\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport { PaymentMethod } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport 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\nexport interface CBAMPGSPaymentMethod extends PaymentMethod {\n initializationData: CBAMPGSInitializationData;\n}\n\nexport interface CBAMPGSInitializationData {\n isTestModeFlagEnabled?: boolean;\n merchantId: string;\n}\n\nexport interface ThreeDSErrorBody {\n three_ds_result: {\n token: string;\n };\n}\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\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 { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CBAMPGSPaymentStrategy from './cba-mpgs-payment-strategy';\nimport CBAMPGSScriptLoader from './cba-mpgs-script-loader';\n\nconst createCBAMPGSPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new CBAMPGSPaymentStrategy(\n paymentIntegrationService,\n new CBAMPGSScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createCBAMPGSPaymentStrategy, [{ id: 'cba_mpgs' }]);\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 skipRedirectConfirmationAlert: true,\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\n if (\n methodId === CHECKOUTCOM_SEPA_PAYMENT_METHOD &&\n document &&\n 'iban' in paymentData &&\n 'bic' in paymentData\n ) {\n const { iban, bic } = paymentData as unknown as WithCheckoutcomSEPAInstrument;\n\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 const features = this._paymentIntegrationService.getState().getStoreConfigOrThrow()\n .checkoutSettings.features;\n\n this._clearpaySdk = await this._clearpayScriptLoader.load(paymentMethod, features);\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';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\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 HTTPS_SANDBOX: 'https://portal.sandbox.clearpay.co.uk/afterpay-async.js',\n HTTPS_PROD: 'https://portal.clearpay.co.uk/afterpay-async.js',\n};\n\nconst CLEARPAY_HTTPS_PROD_SCRIPT_EXPERIMENT = 'PI-4555.clearpay_add_https_to_prod_script';\n\nexport default class ClearpayScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, public _window: ClearpayWindow = window) {}\n\n async load(method: PaymentMethod, features = {}): Promise {\n await this._scriptLoader.loadScript(this._getScriptUrl(method.config.testMode, features));\n\n if (!this._window.AfterPay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.AfterPay;\n }\n\n private _getScriptUrl(testMode?: boolean, features = {}): string {\n const httpsEnabled = isExperimentEnabled(\n features,\n CLEARPAY_HTTPS_PROD_SCRIPT_EXPERIMENT,\n false,\n );\n\n if (testMode) {\n return httpsEnabled ? SCRIPTS_DEFAULT.HTTPS_SANDBOX : SCRIPTS_DEFAULT.SANDBOX;\n }\n\n return httpsEnabled ? SCRIPTS_DEFAULT.HTTPS_PROD : 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';\n\nconst SDK_PROD_URL = 'https://static.client.cardinaltrusted.com/songbird/v2.0.0/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, [\n { id: 'cybersourcev2' },\n { id: 'bnz' },\n]);\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 {\n guard,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n Omit,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { DEFAULT_CONTAINER_STYLES, LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\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 ErrorReasonType,\n GooglePayError,\n GooglePayInitializationData,\n GooglePayPaymentOptions,\n HandleCouponsOut,\n IntermediatePaymentData,\n TotalPriceStatusType,\n} from './types';\n\nexport default class GooglePayPaymentStrategy implements PaymentStrategy {\n private _loadingIndicator: LoadingIndicator;\n private _loadingIndicatorContainer?: string;\n private _paymentButton?: HTMLElement;\n private _clickListener?: (event: MouseEvent) => unknown;\n private _methodId?: keyof WithGooglePayPaymentInitializeOptions;\n private _isDeinitializationBlocked = false;\n\n constructor(\n protected _paymentIntegrationService: PaymentIntegrationService,\n protected _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n ) {\n this._loadingIndicator = new LoadingIndicator({\n containerStyles: DEFAULT_CONTAINER_STYLES,\n });\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, loadingContainerId, ...callbacks } = googlePayOptions;\n\n this._loadingIndicatorContainer = loadingContainerId;\n\n await this._paymentIntegrationService.loadPaymentMethod(this._getMethodId());\n\n const paymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(this._getMethodId());\n\n this._googlePayPaymentProcessor.setIsWebViewExperimentOn(\n !!paymentMethod.initializationData?.isWebViewExperimentOn,\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._isDeinitializationBlocked) {\n return Promise.resolve();\n }\n\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 this._googlePayPaymentProcessor.setShouldRequestShipping(false);\n await this._googlePayPaymentProcessor.initializeWidget();\n\n if (this._isDirectPayOnClickEnabled()) {\n await this._interactWithPaymentSheetAndPay();\n } else {\n await this._interactWithPaymentSheet();\n }\n } catch (error) {\n let err: unknown = error;\n\n this._toggleLoadingIndicator(false);\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 } finally {\n this._toggleBlockDeinitialization(false);\n }\n\n onPaymentSelect?.();\n };\n }\n\n protected async _interactWithPaymentSheetAndPay(): Promise {\n const response = await this._googlePayPaymentProcessor.showPaymentSheet();\n\n this._toggleBlockDeinitialization(true);\n this._toggleLoadingIndicator(true);\n\n const methodId = this._getMethodId();\n\n const state = this._paymentIntegrationService.getState();\n const { features } = state.getStoreConfigOrThrow().checkoutSettings;\n const isGooglePayDontOverrideAddresssExperimentOn = isExperimentEnabled(\n features,\n 'PI-5031.google_pay_dont_override_address',\n );\n\n const billingAddress =\n this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(response);\n\n if (billingAddress && !isGooglePayDontOverrideAddresssExperimentOn) {\n await this._paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n await this._googlePayPaymentProcessor.setExternalCheckoutXhr(methodId, response);\n\n await this._paymentIntegrationService.loadCheckout();\n await this._paymentIntegrationService.loadPaymentMethod(methodId);\n\n const freshPaymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n\n await this._googlePayPaymentProcessor.initialize(() => freshPaymentMethod);\n\n await this.execute({ useStoreCredit: false, payment: { methodId } });\n\n this._completeCheckoutFlow();\n }\n\n protected _completeCheckoutFlow(): void {\n window.location.replace('/checkout/order-confirmation');\n this._toggleLoadingIndicator(false);\n this._toggleBlockDeinitialization(false);\n }\n\n protected async _interactWithPaymentSheet(): Promise {\n const response = await this._googlePayPaymentProcessor.showPaymentSheet();\n const state = this._paymentIntegrationService.getState();\n const { features } = state.getStoreConfigOrThrow().checkoutSettings;\n const isGooglePayDontOverrideAddresssExperimentOn = isExperimentEnabled(\n features,\n 'PI-5031.google_pay_dont_override_address',\n );\n\n this._toggleBlockDeinitialization(true);\n this._toggleLoadingIndicator(true);\n\n const billingAddress =\n this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(response);\n\n if (billingAddress && !isGooglePayDontOverrideAddresssExperimentOn) {\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 this._toggleLoadingIndicator(false);\n this._toggleBlockDeinitialization(false);\n }\n\n protected _getMethodId(): keyof WithGooglePayPaymentInitializeOptions {\n return guard(\n this._methodId,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n protected async _getIsSignedInOrThrow(): Promise {\n try {\n return !!(await this._googlePayPaymentProcessor.getNonce(this._getMethodId()));\n } catch (e) {\n if (\n e instanceof MissingDataError &&\n e.subtype === MissingDataErrorType.MissingPaymentToken\n ) {\n return false;\n }\n\n throw e;\n }\n }\n\n protected async _handleOfferTrigger(\n offerData: IntermediatePaymentData['offerData'],\n ): Promise> {\n let isSignedIn = false;\n let errorMessage = 'Sign in to Google Pay first to apply or remove promo codes.';\n\n try {\n isSignedIn = await this._getIsSignedInOrThrow();\n } catch (error) {\n if (error instanceof MissingDataError) {\n errorMessage = error.message;\n }\n }\n\n // We can only apply/remove coupons on the payment step only if we are logged into Google Pay, otherwise we will get an error\n if (isSignedIn) {\n const { newOfferInfo, error } = await this._googlePayPaymentProcessor.handleCoupons(\n offerData,\n );\n\n return {\n newOfferInfo,\n error,\n };\n }\n\n return {\n error: {\n reason: ErrorReasonType.OFFER_INVALID,\n message: errorMessage,\n intent: CallbackTriggerType.OFFER,\n },\n };\n }\n\n protected _getGooglePayClientOptions(countryCode?: string): GooglePayPaymentOptions {\n if (this._googlePayPaymentProcessor.isWebViewWithRestrictions()) {\n return {};\n }\n\n return {\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({ callbackTrigger, offerData }) => {\n if (\n callbackTrigger !== CallbackTriggerType.INITIALIZE &&\n callbackTrigger !== CallbackTriggerType.OFFER\n ) {\n return;\n }\n\n const { offerChangeTriggers } =\n this._googlePayPaymentProcessor.getCallbackTriggers();\n\n const { newOfferInfo = undefined, error: couponsError = undefined } =\n offerChangeTriggers.includes(callbackTrigger)\n ? await this._handleOfferTrigger(offerData)\n : {};\n\n // We can add another errors if needed 'couponsError || shippingError || anotherError'\n const error: GooglePayError | undefined = couponsError;\n\n await this._paymentIntegrationService.loadCheckout();\n\n const { code: currencyCode } = this._paymentIntegrationService\n .getState()\n .getCartOrThrow().currency;\n const totalPrice = this._googlePayPaymentProcessor.getTotalPrice();\n\n return {\n newTransactionInfo: {\n ...(countryCode && { countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n ...(newOfferInfo && {\n newOfferInfo,\n }),\n ...(error && {\n error,\n }),\n };\n },\n },\n };\n }\n\n private _isDirectPayOnClickEnabled(): boolean {\n const { features } = this._paymentIntegrationService\n .getState()\n .getStoreConfigOrThrow().checkoutSettings;\n\n return isExperimentEnabled(features, 'PI-5111.google_pay_direct_pay_on_click');\n }\n\n private _toggleBlockDeinitialization(isBlocked: boolean) {\n this._isDeinitializationBlocked = isBlocked;\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 { 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';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\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';\n\nconst createGooglePayStripePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayStripeGateway(\n paymentIntegrationService,\n new StripeScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayStripePaymentStrategy, [\n { id: 'googlepaystripe' },\n { id: 'googlepaystripeupe' },\n { id: 'googlepaystripeocs' },\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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 MissingDataError,\n MissingDataErrorType,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../google-pay-payment-strategy';\nimport { GooglePayInitializationData, GooglePayPayPalCommerceInitializationData } from '../types';\n\nimport { ConfirmOrderData, ConfirmOrderStatus } from './types';\n\nexport default class GooglePayPaypalCommercePaymentStrategy extends GooglePayPaymentStrategy {\n constructor(\n _paymentIntegrationService: PaymentIntegrationService,\n _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n private _payPalCommerceSdk: PayPalCommerceSdk,\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 if (!paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const currencyCode = state.getCartOrThrow().currency.code;\n\n const payPalSDK = await this._payPalCommerceSdk.getPayPalGooglePaySdk(\n paymentMethod,\n currencyCode,\n state.getLocale(),\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';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\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';\n\nconst createGooglePayPayPalCommercePaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) => {\n const payPalCommerceSdk = new PayPalCommerceSdk(getScriptLoader());\n\n return new GooglePayPaypalCommercePaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayPaypalCommerceGateway(paymentIntegrationService, payPalCommerceSdk),\n createRequestSender(),\n createFormPoster(),\n ),\n payPalCommerceSdk,\n createRequestSender(),\n );\n};\n\nexport default toResolvableModule(createGooglePayPayPalCommercePaymentStrategy, [\n { id: 'googlepaypaypalcommerce' },\n]);\n","import { GooglePayConfig } from '../types';\n\nexport type FundingType = string;\n\n/**\n *\n * BigCommercePayments 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 BigCommercePaymentsHostWindow extends Window {\n paypal?: PayPalSDK;\n}\n\nexport interface BigCommercePaymentsScriptParams {\n options: {\n 'client-id'?: string;\n 'merchant-id'?: string;\n 'buyer-country'?: string;\n 'disable-funding'?: FundingType[];\n 'enable-funding'?: FundingType[];\n currency?: string;\n commit?: boolean;\n intent?: BigCommercePaymentsIntent;\n components?: ComponentsScriptType;\n };\n attributes: {\n 'data-client-token'?: string;\n 'data-partner-attribution-id'?: string;\n };\n}\n\nexport enum BigCommercePaymentsIntent {\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 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 BigCommercePaymentsInitializationData,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentMethod,\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 {\n GooglePayBigCommercePaymentsInitializationData,\n GooglePayInitializationData,\n} from '../types';\n\nimport { ConfirmOrderData, ConfirmOrderStatus } from './types';\n\nexport default class GooglePayBigCommercePaymentsPaymentStrategy extends GooglePayPaymentStrategy {\n constructor(\n _paymentIntegrationService: PaymentIntegrationService,\n _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n private _payPalSdkHelper: PayPalSdkHelper,\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 if (!paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const currencyCode = state.getCartOrThrow().currency.code;\n\n const payPalSDK = await this._payPalSdkHelper.getPayPalGooglePaySdk(\n paymentMethod as 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/googlepay_bigcommerce_paymentscheckout';\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 { PayPalSdkHelper } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\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 GooglePayBigCommercePaymentsGateway from './google-pay-bigcommerce-payments-gateway';\nimport GooglePayBigCommercePaymentsPaymentStrategy from './google-pay-bigcommerce-payments-payment-strategy';\n\nconst createGooglePayBigCommercePaymentsPaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) => {\n const payPalSdkHelper = new PayPalSdkHelper(getScriptLoader());\n\n return new GooglePayBigCommercePaymentsPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayBigCommercePaymentsGateway(paymentIntegrationService, payPalSdkHelper),\n createRequestSender(),\n createFormPoster(),\n ),\n payPalSdkHelper,\n createRequestSender(),\n );\n};\n\nexport default toResolvableModule(createGooglePayBigCommercePaymentsPaymentStrategy, [\n { id: 'googlepay_bigcommerce_payments' },\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","import { 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';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport KlarnaPayments, {\n KlarnaAddress,\n KlarnaAuthorizationResponse,\n KlarnaInitializationData,\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, initializationData } =\n state.getPaymentMethodOrThrow(methodId);\n const { klarnaMultipleRadioButton } = initializationData || {};\n\n await this.klarnav2TokenUpdater.klarnaOrderInitialization(cartId, clientToken);\n\n const paymentMethodСategory = this.isKlarnaMultipleRadioButtonEnabled(\n klarnaMultipleRadioButton,\n gatewayId,\n methodId,\n );\n const { authorization_token: authorizationToken } = await this.authorizeOrThrow(\n paymentMethodСategory,\n methodId,\n );\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 const { klarnaMultipleRadioButton } = paymentMethod.initializationData || {};\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 {\n container,\n payment_method_category: this.isKlarnaMultipleRadioButtonEnabled(\n klarnaMultipleRadioButton,\n gatewayId,\n methodId,\n ),\n },\n (response) => {\n if (onLoad) {\n onLoad(response);\n }\n\n resolve(response);\n },\n );\n });\n }\n\n private getUpdateSessionData(\n methodId: string,\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(\n methodId,\n billingAddress,\n billingAddress.email,\n ),\n };\n\n if (shippingAddress) {\n data.shipping_address = this.mapToKlarnaAddress(\n methodId,\n shippingAddress,\n billingAddress.email,\n );\n }\n\n return data;\n }\n\n private needsStateCode(countryCode: string) {\n return includes(supportedCountriesRequiringStates, countryCode);\n }\n\n private isKlarnaMultipleRadioButtonEnabled(\n klarnaMultipleRadioButton: boolean | undefined,\n gatewayId: string,\n methodId: string,\n ): string {\n return klarnaMultipleRadioButton ? methodId : gatewayId;\n }\n\n private mapToKlarnaAddress(methodId: string, address: Address, email?: string): KlarnaAddress {\n const state = this.paymentIntegrationService.getState();\n const { checkoutSettings } = state.getStoreConfigOrThrow();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { enableBillie } = paymentMethod.initializationData || {};\n\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 if (\n address.company &&\n enableBillie &&\n isExperimentEnabled(checkoutSettings.features, 'PI-3915.b2b_payment_session_for_klarna')\n ) {\n klarnaAddress.organization_name = address.company;\n }\n\n return klarnaAddress;\n }\n\n private async authorizeOrThrow(\n paymentMethodСategory: string,\n methodId: string,\n ): 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(\n methodId,\n billingAddress,\n shippingAddress,\n );\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 {\n payment_method_category: paymentMethodСategory,\n },\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 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 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\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 (\n typeof response.data !== 'string' ||\n response.origin !== `https://${testMode ? 'esqa' : 'www3'}.moneris.com`\n ) {\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 iframe.allow = 'payment';\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 {\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 payment.gatewayId === 'adyen' || payment.gatewayId === 'barclaycard';\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","import { MessagesStyleOptions, PayPalBNPLConfigurationItem } from '../paypal-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 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 {\n ApproveCallbackPayload,\n ClickCallbackActions,\n getPaypalMessagesStylesFromBNPLConfig,\n isPaypalProviderError,\n isRedirectActionError,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalButtons,\n PayPalButtonsOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalMessagesSdk,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isBaseInstrument } from '@bigcommerce/checkout-sdk/utility';\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?: PayPalButtons;\n private paypalcommerce?: PayPalCommercePaymentInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\n private payPalSdkScriptLoader: PayPalSdkScriptLoader,\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 = state.getPaymentMethodOrThrow(methodId);\n\n const { container, bannerContainerId } = paypalcommerce;\n\n const {\n orderId,\n paypalBNPLConfiguration = [],\n isPayPalCreditAvailable,\n } = paymentMethod.initializationData || {};\n\n if (bannerContainerId !== undefined) {\n if (!document.getElementById(bannerContainerId)) {\n // eslint-disable-next-line no-console\n console.error('Unable to create banner without valid banner container ID.');\n\n return;\n }\n\n const bannerConfiguration = paypalBNPLConfiguration?.find(\n ({ id }) => id === 'checkout',\n );\n\n if (isPayPalCreditAvailable || !bannerConfiguration?.status) {\n return;\n }\n\n const paypalMessages = await this.payPalSdkScriptLoader.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n state.getLocale(),\n );\n\n if (!paypalMessages || typeof paypalMessages?.Messages !== 'function') {\n console.error(\n '[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n return this.renderMessages(paypalMessages, bannerContainerId, bannerConfiguration);\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 = paymentMethod.initializationData?.orderId;\n\n return;\n }\n\n this.loadingIndicatorContainer = container?.split('#')[1];\n\n await this.paypalIntegrationService.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\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 (isRedirectActionError(error)) {\n const redirectUrl = error.body.additional_action_required?.data?.redirect_url;\n\n return new Promise(() => window.location.replace(redirectUrl));\n }\n\n if (this.isProviderError(error)) {\n await this.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { paymentButtonStyles } = paymentMethod.initializationData || {};\n const { checkoutPaymentButtonStyles } = paymentButtonStyles || {};\n const { container, onError, onRenderButton, onValidate, submitForm } = paypalcommerce;\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"container\" argument is not provided.',\n );\n }\n\n const containerId = this.getSmartButtonContainerId(container);\n const smartButtonContainer = document.getElementById(containerId);\n\n if (!smartButtonContainer) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because element with id ${containerId} does not exist.`,\n );\n }\n\n const buttonOptions: PayPalButtonsOptions = {\n ...(this.isPaypalCommerceAppSwitchEnabled(methodId) && {\n appSwitchWhenAvailable: true,\n }),\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalIntegrationService.getValidButtonStyle(checkoutPaymentButtonStyles),\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 if (this.paypalButton.hasReturned?.() && this.isPaypalCommerceAppSwitchEnabled(methodId)) {\n this.paypalButton.resume?.();\n } else {\n this.paypalButton.render(container);\n }\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 return 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.paypalIntegrationService.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 const findInstrument = instruments?.find(\n (instrument) =>\n isBaseInstrument(instrument) &&\n instrument.bigpayToken === paymentData.instrumentId,\n );\n const trustedShippingAddress = isBaseInstrument(findInstrument)\n ? findInstrument.trustedShippingAddress\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 /**\n *\n * Render Pay Later Messages\n *\n * */\n private renderMessages(\n paypalMessages: PayPalMessagesSdk,\n bannerContainerId: string,\n bannerConfiguration: PayPalBNPLConfigurationItem,\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: checkout.outstandingBalance,\n placement: 'payment',\n style: getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\n };\n\n paypalMessages.Messages(paypalMessagesOptions).render(`#${bannerContainerId}`);\n }\n\n /**\n *\n * Error handling\n *\n */\n private isProviderError(error: unknown): boolean {\n if (isPaypalProviderError(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 /**\n *\n * PayPal AppSwitch enabling handling\n *\n */\n private isPaypalCommerceAppSwitchEnabled(methodId: string): boolean {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n return paymentMethod.initializationData?.isAppSwitchEnabled || false;\n }\n\n private getSmartButtonContainerId(container: string) {\n return container.split('#')[1] ?? container;\n }\n}\n","import { isRequestError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ProviderError } from './is-paypal-provider-error';\n\nexport interface RedirectActionError extends ProviderError {\n body: {\n additional_action_required: {\n type: 'offsite_redirect';\n data: {\n redirect_url: string;\n };\n };\n };\n}\n\nexport default function isRedirectActionError(error: unknown): error is RedirectActionError {\n return (\n isRequestError(error) && error.body.additional_action_required?.type === 'offsite_redirect'\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 isPaypalProviderError(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 PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalIntegrationService,\n LOADING_INDICATOR_STYLES,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommercePaymentStrategy from './paypal-commerce-payment-strategy';\n\nconst createPayPalCommercePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new PayPalCommercePaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\n new PayPalSdkScriptLoader(getScriptLoader()),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createPayPalCommercePaymentStrategy, [{ id: 'paypalcommerce' }]);\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 ApproveCallbackPayload,\n ClickCallbackActions,\n getPaypalMessagesStylesFromBNPLConfig,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalButtons,\n PayPalButtonsOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalMessagesSdk,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\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?: PayPalButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\n private loadingIndicator: LoadingIndicator,\n private payPalSdkScriptLoader: PayPalSdkScriptLoader,\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 = state.getPaymentMethodOrThrow(methodId);\n\n const { paypalBNPLConfiguration = [], orderId } = paymentMethod.initializationData || {};\n const { bannerContainerId, container } = paypalOptions;\n\n if (bannerContainerId !== undefined) {\n if (!document.getElementById(bannerContainerId)) {\n // eslint-disable-next-line no-console\n console.error('Unable to create banner without valid banner container ID.');\n\n return;\n }\n\n const bannerConfiguration =\n paypalBNPLConfiguration &&\n paypalBNPLConfiguration.find(({ id }) => id === 'checkout');\n\n if (!bannerConfiguration?.status) {\n return;\n }\n\n const paypalMessages = await this.payPalSdkScriptLoader.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n state.getLocale(),\n );\n\n return this.renderMessages(paypalMessages, bannerContainerId, bannerConfiguration);\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.paypalIntegrationService.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.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = 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: PayPalButtonsOptions = {\n fundingSource,\n style: this.paypalIntegrationService.getValidButtonStyle(\n checkoutPaymentButtonStyles,\n ),\n createOrder: () =>\n this.paypalIntegrationService.createOrder('paypalcommercecreditcheckout'),\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 return 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,\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: checkout.outstandingBalance,\n placement: 'payment',\n style: getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\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 {\n createPayPalIntegrationService,\n createPayPalSdkScriptLoader,\n LOADING_INDICATOR_STYLES,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceCreditPaymentStrategy from './paypal-commerce-credit-payment-strategy';\n\nconst createPayPalCommerceCreditPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceCreditPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditPaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n createPayPalSdkScriptLoader(),\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 {\n ApproveCallbackPayload,\n ClickCallbackActions,\n PayPalButtons,\n PayPalButtonsOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\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?: PayPalButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\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 = 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.paypalIntegrationService.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.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = 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: PayPalButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.paypalIntegrationService.getValidButtonStyle(checkoutPaymentButtonStyles),\n createOrder: () =>\n this.paypalIntegrationService.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 return 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 { createPayPalIntegrationService } from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceVenmoPaymentStrategy from './paypal-commerce-venmo-payment-strategy';\n\nconst createPayPalCommerceVenmoPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceVenmoPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceVenmoPaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n\nexport default toResolvableModule(createPayPalCommerceVenmoPaymentStrategy, [\n { id: 'paypalcommercevenmo' },\n]);\n","export const LOADING_INDICATOR_STYLES = {\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\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 TimeoutError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n PayPalApmSdk,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport {\n ApproveCallbackPayload,\n NonInstantAlternativePaymentMethods,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n PayPalOrderStatus,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceAlternativeMethodsPaymentOptions, {\n WithPayPalCommerceAlternativeMethodsPaymentInitializeOptions,\n} from './paypal-commerce-alternative-methods-payment-initialize-options';\n\nconst POLLING_INTERVAL = 3000;\nconst MAX_POLLING_TIME = 300000;\n\nexport default class PayPalCommerceAlternativeMethodsPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n private paypalApms?: PayPalApmSdk;\n private pollingTimer = 0;\n private stopPolling = noop;\n private isOrderApprovedProcessing = false;\n private paypalcommercealternativemethods?: PayPalCommerceAlternativeMethodsPaymentOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalIntegrationService,\n private paypalSdkScriptLoader: PayPalSdkScriptLoader,\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 &\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 this.paypalcommercealternativemethods = paypalcommercealternativemethods;\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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n\n this.isOrderApprovedProcessing = isExperimentEnabled(\n features,\n 'PAYPAL-5431.order_approved_processing',\n false,\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 this.paypalApms = await this.paypalSdkScriptLoader.getPayPalApmsSdk(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n state.getLocale(),\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.isOrderApprovedProcessing && methodId === 'ideal') {\n await new Promise((resolve, reject) => {\n void this.initializePollingMechanism(methodId, resolve, reject, gatewayId);\n });\n }\n\n if (\n !this.isNonInstantPaymentMethod(methodId) ||\n (methodId === NonInstantAlternativePaymentMethods.IDEAL &&\n !this.isOrderApprovedProcessing)\n ) {\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 if (!this.isOrderApprovedProcessing) {\n this.resetPollingMechanism();\n }\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Polling mechanism\n *\n *\n * */\n private async initializePollingMechanism(\n methodId: string,\n resolvePromise: (value?: unknown) => void,\n rejectPromise: (value?: unknown) => 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 gatewayId ?? 'paypalcommerce',\n );\n\n const isOrderApproved = orderStatus === PayPalOrderStatus.Approved;\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 paypalcommercealternativemethods: this.paypalcommercealternativemethods,\n });\n\n this.handleError(new TimeoutError());\n } catch (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 private async reinitializeStrategy(\n options: PaymentInitializeOptions &\n WithPayPalCommerceAlternativeMethodsPaymentInitializeOptions,\n ) {\n await this.deinitialize();\n await this.initialize(options);\n }\n\n private handleError(error: unknown) {\n const { onError } = this.paypalcommercealternativemethods || {};\n\n if (!this.isOrderApprovedProcessing) {\n this.resetPollingMechanism();\n }\n\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\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: () => {\n this.toggleLoadingIndicator(false);\n this.deinitializePollingMechanism();\n },\n onError: (error) => {\n this.deinitializePollingMechanism();\n this.handleFailure(error, onError);\n },\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 (\n this.isNonInstantPaymentMethod(methodId) &&\n ((methodId === NonInstantAlternativePaymentMethods.IDEAL &&\n this.isOrderApprovedProcessing) ||\n methodId === NonInstantAlternativePaymentMethods.OXXO)\n ) {\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\n if (methodId === NonInstantAlternativePaymentMethods.IDEAL) {\n const state = this.paymentIntegrationService.getState();\n const bcOrderId = state.getOrder()?.orderId;\n\n await this.paypalCommerceIntegrationService.updateOrder(\n 'paypalcommercealternativemethods',\n methodId,\n bcOrderId,\n );\n }\n\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 {\n createPayPalIntegrationService,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\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 createPayPalIntegrationService(paymentIntegrationService),\n createPayPalSdkScriptLoader(),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createPayPalCommerceAlternativeMethodsPaymentStrategy, [\n { gateway: 'paypalcommercealternativemethods' },\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 { isPayPalCommerceAcceleratedCheckoutCustomer } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\nimport {\n PayPalFastlaneUtils,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\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 paypalIntegrationService: PayPalIntegrationService,\n private paypalSdkScriptLoader: PayPalSdkScriptLoader,\n private paypalFastlaneUtils: PayPalFastlaneUtils,\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, onLoadComplete } =\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.paypalIntegrationService.loadPayPalSdk(methodId, undefined, true, true);\n\n if (this.isCreditCardForm || this.isCreditCardVaultedForm) {\n await this.initializeFields(form, onCreditCardFieldsRenderingError);\n }\n\n onLoadComplete?.();\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.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n const executeCallback = this.getExecuteCallback(fields);\n\n const cardFieldsConfig: PayPalCommerceCardFieldsConfig = {\n style: this.getInputStyles(styles),\n onApprove: ({\n orderID,\n vaultSetupToken,\n liabilityShift,\n }: PayPalCommerceCardFieldsOnApproveData) => {\n if (\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.paypalIntegrationService.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.paypalIntegrationService.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 = 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 = state.getPaymentMethodOrThrow(methodId);\n const { initializationData } = paymentMethod;\n\n if (!initializationData?.connectClientToken) {\n return;\n }\n\n const payPalFastlaneSdk = await this.paypalSdkScriptLoader.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n state.getLocale(),\n );\n\n await this.paypalFastlaneUtils.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 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 {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalFastlaneUtils,\n createPayPalIntegrationService,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceCreditCardsPaymentStrategy from './paypal-commerce-credit-cards-payment-strategy';\n\nconst createPaypalCommerceCreditCardsPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceCreditCardsPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditCardsPaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\n createPayPalSdkScriptLoader(),\n createPayPalFastlaneUtils(),\n );\n\nexport default toResolvableModule(createPaypalCommerceCreditCardsPaymentStrategy, [\n { id: 'paypalcommercecreditcards' },\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 {\n BirthDate,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalOrderStatus,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\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 paypalCommerceService: PayPalIntegrationService,\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.paypalCommerceService.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.paypalCommerceService.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.paypalCommerceService.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.paypalCommerceService.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 {\n createPayPalIntegrationService,\n LOADING_INDICATOR_STYLES,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PaypalCommerceRatepayPaymentStrategy from './paypal-commerce-ratepay-payment-strategy';\n\nconst createPaypalCommerceRatepayPaymentStrategy: PaymentStrategyFactory<\n PaypalCommerceRatepayPaymentStrategy\n> = (paymentIntegrationService) =>\n new PaypalCommerceRatepayPaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(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 PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n getFastlaneStyles,\n isPayPalFastlaneCustomer,\n isPaypalFastlaneRequestError,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneCardComponentMethods,\n PayPalFastlaneCardComponentOptions,\n PayPalFastlanePaymentFormattedPayload,\n PayPalFastlaneSdk,\n PayPalFastlaneUtils,\n PayPalInitializationData,\n PayPalSdkScriptLoader,\n TDSecureAuthenticationState,\n TDSecureVerificationMethod,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceRequestSender from '../paypal-commerce-request-sender';\nimport { LiabilityShiftEnum } from '../paypal-commerce-types';\n\nimport PayPalCommerceFastlanePaymentInitializeOptions, {\n WithPayPalCommerceFastlanePaymentInitializeOptions,\n} from './paypal-commerce-fastlane-payment-initialize-options';\n\nexport default class PaypalCommerceFastlanePaymentStrategy implements PaymentStrategy {\n private paypalComponentMethods?: PayPalFastlaneCardComponentMethods;\n private paypalFastlaneSdk?: PayPalFastlaneSdk;\n private threeDSVerificationMethod?: string;\n private paypalcommercefastlane?: PayPalCommerceFastlanePaymentInitializeOptions;\n private orderId?: string;\n private methodId?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceRequestSender: PayPalCommerceRequestSender,\n private paypalSdkScriptLoader: PayPalSdkScriptLoader,\n private paypalFastlaneUtils: PayPalFastlaneUtils,\n ) {}\n\n /**\n *\n * Default methods\n *\n * */\n async initialize(\n options: PaymentInitializeOptions & WithPayPalCommerceFastlanePaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommercefastlane } = options;\n\n this.methodId = methodId;\n\n this.paypalcommercefastlane = paypalcommercefastlane;\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 = state.getPaymentMethodOrThrow(methodId);\n const { isDeveloperModeApplicable, isFastlaneStylingEnabled } =\n paymentMethod.initializationData || {};\n\n this.threeDSVerificationMethod =\n paymentMethod.initializationData?.threeDSVerificationMethod;\n\n this.paypalFastlaneSdk = await this.paypalSdkScriptLoader.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n state.getLocale(),\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.paypalFastlaneUtils.initializePayPalFastlane(\n this.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 await this.paymentIntegrationService.submitOrder(order, options);\n\n const paymentPayload = isVaultedFlow\n ? await this.prepareVaultedInstrumentPaymentPayload(methodId, paymentData)\n : await this.preparePaymentPayload(methodId, paymentData);\n\n await this.paymentIntegrationService.submitPayment(\n paymentPayload,\n );\n\n this.paypalFastlaneUtils.removeStorageSessionId();\n } catch (error) {\n if (\n isPaypalFastlaneRequestError(error) &&\n error.response.body.name === 'INVALID_REQUEST'\n ) {\n const invalidRequestError = {\n translationKey: 'payment.errors.invalid_request_error',\n };\n\n this.handleError(invalidRequestError);\n\n return Promise.reject();\n }\n\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.paypalFastlaneUtils.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 } = await this.paypalFastlaneUtils.lookupCustomerOrThrow(\n customerEmail,\n );\n\n const authenticationResult =\n await this.paypalFastlaneUtils.triggerAuthenticationFlowOrThrow(customerContextId);\n\n const { authenticationState, addresses, instruments } =\n this.paypalFastlaneUtils.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 if (isAuthenticationFlowCanceled) {\n this.paypalFastlaneUtils.removeStorageSessionId();\n } else {\n this.paypalFastlaneUtils.updateStorageSessionId(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.paypalFastlaneUtils.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 paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const is3DSEnabled = paymentMethod.config.is3dsEnabled;\n\n const nonce = is3DSEnabled ? await this.get3DSNonce(instrumentId) : instrumentId;\n\n await this.createOrder(nonce);\n\n return {\n methodId,\n paymentData: {\n formattedPayload: {\n paypal_fastlane_token: {\n order_id: this.orderId,\n token: nonce,\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 billingAddress = state.getBillingAddressOrThrow();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\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.paypalFastlaneUtils.mapBcToPayPalAddress(billingAddress),\n });\n\n const is3DSEnabled = paymentMethod.config.is3dsEnabled;\n\n const nonce = is3DSEnabled ? await this.get3DSNonce(id) : id;\n\n await this.createOrder(nonce);\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: this.orderId,\n token: nonce,\n },\n },\n },\n };\n }\n\n private async createOrder(id: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cartId = state.getCartOrThrow().id;\n\n if (this.methodId) {\n const { orderId } = await this.paypalCommerceRequestSender.createOrder(this.methodId, {\n cartId,\n fastlaneToken: id,\n });\n\n this.orderId = orderId;\n }\n }\n\n /**\n *\n * 3DSecure methods\n *\n * */\n private async get3DSNonce(nonce: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const order = state.getOrderOrThrow();\n const checkoutUrl = state.getStoreConfigOrThrow().links.checkoutLink;\n\n const threeDomainSecureComponent = this.paypalFastlaneSdk?.ThreeDomainSecureClient;\n\n if (!threeDomainSecureComponent) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n const threeDomainSecureParameters = {\n amount: order.orderAmount.toFixed(2),\n currency: cart.currency.code,\n nonce,\n threeDSRequested: this.threeDSVerificationMethod === TDSecureVerificationMethod.Always,\n transactionContext: {\n experience_context: {\n locale: 'en-US',\n return_url: checkoutUrl,\n cancel_url: checkoutUrl,\n },\n },\n };\n\n const isThreeDomainSecureEligible = await threeDomainSecureComponent.isEligible(\n threeDomainSecureParameters,\n );\n\n if (\n this.threeDSVerificationMethod === TDSecureVerificationMethod.Always &&\n !isThreeDomainSecureEligible\n ) {\n throw new PaymentMethodInvalidError();\n }\n\n if (isThreeDomainSecureEligible) {\n const {\n liabilityShift,\n authenticationState,\n nonce: threeDSNonce,\n } = await threeDomainSecureComponent.show();\n\n if (\n liabilityShift === LiabilityShiftEnum.No ||\n liabilityShift === LiabilityShiftEnum.Unknown ||\n authenticationState === TDSecureAuthenticationState.Errored ||\n authenticationState === TDSecureAuthenticationState.Cancelled\n ) {\n throw new PaymentMethodInvalidError();\n }\n\n if (\n authenticationState === TDSecureAuthenticationState.Succeeded &&\n [LiabilityShiftEnum.Yes, LiabilityShiftEnum.Possible].includes(liabilityShift)\n ) {\n return threeDSNonce;\n }\n\n throw new PaymentMethodInvalidError();\n }\n\n return nonce;\n }\n\n /**\n *\n * PayPal Fastlane instrument change\n *\n */\n private async handlePayPalStoredInstrumentChange(\n methodId: string,\n ): Promise {\n const paypalAxoSdk = this.paypalFastlaneUtils.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.paypalFastlaneUtils.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 private handleError(error: unknown): void {\n if (\n this.paypalcommercefastlane?.onError &&\n typeof this.paypalcommercefastlane.onError === 'function'\n ) {\n this.paypalcommercefastlane.onError(error);\n }\n }\n}\n","export interface PaypalFastlaneRequestError {\n name: string;\n message: string;\n response: {\n body: {\n name: string;\n };\n };\n}\n\nexport default function isPaypalFastlaneRequestError(\n error: unknown,\n): error is PaypalFastlaneRequestError {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'message' in error &&\n 'response' in error &&\n 'body' in (error as PaypalFastlaneRequestError).response &&\n 'name' in (error as PaypalFastlaneRequestError).response.body\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 createPayPalFastlaneUtils,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-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 createPayPalSdkScriptLoader(),\n createPayPalFastlaneUtils(),\n );\n};\n\nexport default toResolvableModule(createPayPalCommerceFastlanePaymentStrategy, [\n { id: 'paypalcommerceacceleratedcheckout' }, // PayPal Fastlane relates to 'paypalcommerceacceleratedcheckout' method id\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 enum PaymentStatusTypes {\n ACKNOWLEDGE = 'ACKNOWLEDGE',\n FINALIZE = 'FINALIZE',\n INITIALIZE = 'INITIALIZE',\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 { noop } from 'lodash';\n\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithPaypalExpressPaymentInitializeOptions } from './paypal-express-payment-initialize-options';\nimport PaypalScriptLoader from './paypal-express-script-loader';\nimport { PaymentStatusTypes, PaypalHostWindow, PaypalSDK } from './paypal-express-types';\n\nexport default class PaypalExpressPaymentStrategy implements PaymentStrategy {\n private paypalSdk?: PaypalSDK;\n private paymentMethod?: PaymentMethod;\n private useRedirectFlow = false;\n private window: PaypalHostWindow;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: PaypalScriptLoader,\n ) {\n this.window = window;\n }\n\n async initialize(\n options: PaymentInitializeOptions & WithPaypalExpressPaymentInitializeOptions,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n\n this.paymentMethod = state.getPaymentMethodOrThrow(options.methodId);\n this.useRedirectFlow =\n (options.paypalexpress && options.paypalexpress.useRedirectFlow) === true;\n\n const merchantId = this.paymentMethod.config.merchantId;\n\n if (!this.isInContextEnabled() || !merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const paypalSdk = await this.scriptLoader.loadPaypalSDK();\n\n this.paypalSdk = paypalSdk;\n\n this.paypalSdk.checkout.setup(merchantId, {\n button: 'paypal-button',\n environment: this.paymentMethod.config.testMode ? 'sandbox' : 'production',\n });\n }\n\n deinitialize() {\n if (this.isInContextEnabled() && this.paypalSdk) {\n this.paypalSdk.checkout.closeFlow();\n this.paypalSdk = undefined;\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions) {\n let state: PaymentIntegrationSelectors;\n let redirectUrl: string | undefined;\n const paypal = this.paypalSdk;\n\n if (this.isAcknowledgedOrFinalized()) {\n await this.paymentIntegrationService.submitOrder(payload, options);\n\n return;\n }\n\n if (!this.isInContextEnabled() || this.useRedirectFlow) {\n state = await this.paymentIntegrationService.submitOrder(payload, options);\n redirectUrl = state.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 if (!paypal) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n paypal.checkout.initXO();\n\n try {\n state = await this.paymentIntegrationService.submitOrder(payload, options);\n } catch (error) {\n paypal.checkout.closeFlow();\n\n return Promise.reject(error);\n }\n\n redirectUrl = state.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\n async finalize(options?: PaymentRequestOptions) {\n const state = this.paymentIntegrationService.getState();\n const order = state.getOrder();\n\n if (order && this.isAcknowledgedOrFinalized()) {\n await this.paymentIntegrationService.finalizeOrder(options);\n\n return Promise.resolve();\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private isAcknowledgedOrFinalized(): boolean {\n const state = this.paymentIntegrationService.getState();\n\n return (\n state.getPaymentStatus() === PaymentStatusTypes.ACKNOWLEDGE ||\n state.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 '@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 { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PaypalExpressPaymentStrategy from './paypal-express-payment-strategy';\nimport PaypalExpressScriptLoader from './paypal-express-script-loader';\n\nconst createPaypalExpressPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new PaypalExpressPaymentStrategy(\n paymentIntegrationService,\n new PaypalExpressScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createPaypalExpressPaymentStrategy, [\n { id: 'paypalexpress', type: 'PAYMENT_TYPE_HOSTED' },\n { id: 'paypalexpresscredit', type: 'PAYMENT_TYPE_HOSTED' },\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 { 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 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new Promise(() => {\n this.redirectUrl(redirect_url);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }) as any;\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 { 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 ('errors' in result && 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(methodId, 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(methodId: string, shouldSaveInstrument?: boolean) {\n const { getPaymentMethodOrThrow } = this._paymentIntegrationService.getState();\n const { initializationData } = getPaymentMethodOrThrow(methodId);\n\n const cardTokenizationResult = await this._squareV2PaymentProcessor.tokenize();\n\n if (\n initializationData && 'isSquareV2ApiV2Enabled' in initializationData\n ? !initializationData.isSquareV2ApiV2Enabled\n : !this.shouldVerify()\n ) {\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 { getPaymentMethodOrThrow } = this._paymentIntegrationService.getState();\n const { initializationData } = getPaymentMethodOrThrow(methodId);\n\n const { instrumentId } = paymentData;\n const shouldVerify =\n initializationData && 'isSquareV2ApiV2Enabled' in initializationData\n ? initializationData.isSquareV2ApiV2Enabled\n : this.shouldVerify();\n const verificationToken = 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 PaymentStrategy,\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 allow_redisplay?: 'always' | 'limited' | 'unspecified';\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 allowRedisplayForStoredInstruments?: 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 private _allowRedisplayForStoredInstruments?: 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 allowRedisplayForStoredInstruments,\n },\n } = paymentMethod as StripeV3PaymentMethod;\n\n this._allowRedisplayForStoredInstruments = allowRedisplayForStoredInstruments;\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 const shouldAllowRedisplay = this._allowRedisplayForStoredInstruments;\n\n return this.getStripeJs().createPaymentMethod({\n type: StripePaymentMethodType.CreditCard,\n card,\n billing_details: billingDetails,\n ...(shouldAllowRedisplay ? { allow_redisplay: 'always' } : {}),\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","export const supportedLocales: Record = {\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-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 { merge, 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 PaymentRequestOptions,\n PaymentStrategy,\n RequestError,\n StripeUPEIntent,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n formatStripeLocale,\n isStripePaymentMethodLike,\n STRIPE_UPE_CLIENT_API_VERSION,\n STRIPE_UPE_CLIENT_BETAS,\n StripeAdditionalActionRequired,\n StripeAppearanceOptions,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeElementUpdateOptions,\n StripeEventType,\n StripeFormattedPaymentPayload,\n StripeInitializationData,\n StripeIntegrationService,\n StripeJsVersion,\n StripePaymentMethodType,\n StripeResult,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport isStripeAcceleratedCheckoutCustomer from './is-stripe-accelerated-checkout-customer';\nimport StripeUPEPaymentInitializeOptions, {\n WithStripeUPEPaymentInitializeOptions,\n} from './stripe-upe-initialize-options';\n\nexport default class StripeUPEPaymentStrategy implements PaymentStrategy {\n private _stripeUPEClient?: StripeClient;\n private _stripeElements?: StripeElements;\n private _isStripeElementUpdateEnabled?: boolean;\n private _allowRedisplayForStoredInstruments?: boolean;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n private stripeIntegrationService: StripeIntegrationService,\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.stripeIntegrationService.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.stripeIntegrationService.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 await this.paymentIntegrationService.submitOrder(order, options);\n\n if (isVaultedInstrument(paymentData)) {\n const { instrumentId } = paymentData;\n\n await this._executeWithVaulted(\n payment.methodId,\n instrumentId,\n shouldSetAsDefaultInstrument,\n );\n\n return;\n }\n\n await this._executeWithStripeConfirmation(\n payment.methodId,\n payment.gatewayId,\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.stripeIntegrationService.deinitialize();\n this._stripeElements = undefined;\n this._stripeUPEClient = undefined;\n\n return Promise.resolve();\n }\n\n private async _executeWithStripeConfirmation(\n methodId: string,\n gatewayId?: 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 gatewayId,\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\n if (!isStripePaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { clientToken, initializationData } = paymentMethod;\n const {\n shopperLanguage,\n allowRedisplayForStoredInstruments = false,\n enableLink,\n } = initializationData;\n\n this._allowRedisplayForStoredInstruments = allowRedisplayForStoredInstruments;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._stripeUPEClient = await this._loadStripeJs(initializationData);\n this._isStripeElementUpdateEnabled = typeof initStripeElementUpdateTrigger === 'function';\n\n let appearance: StripeAppearanceOptions | undefined;\n\n if (style) {\n const styles = style;\n\n appearance = {\n variables: this.stripeIntegrationService.mapAppearanceVariables(style),\n rules: {\n '.Input': this.stripeIntegrationService.mapInputAppearanceRules(styles),\n },\n };\n }\n\n this._stripeElements = await this.scriptLoader.getElements(this._stripeUPEClient, {\n clientSecret: clientToken,\n locale: formatStripeLocale(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 link: enableLink ? StripeStringConstants.AUTO : StripeStringConstants.NEVER,\n },\n ...this._getStripeElementTerms(),\n });\n\n this.stripeIntegrationService.mountElement(stripeElement, containerId);\n\n stripeElement.on(StripeElementEvent.READY, () => {\n render();\n });\n\n stripeElement.on(StripeElementEvent.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 gatewayId?: string,\n shouldSaveInstrument = false,\n shouldSetAsDefaultInstrument = false,\n ): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.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, error: stripeError } = 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 if (stripeError || !paymentIntent) {\n const { initializationData } = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n const { sendSecondPaymentRequestOnStripeError } = initializationData || {};\n\n if (sendSecondPaymentRequestOnStripeError) {\n // INFO: even in case when stripe payment confirmation was declined\n // we need to send submitPayment request to update status of checkout session on BE side.\n try {\n const paymentPayloadWithError = merge({}, paymentPayload, {\n paymentData: {\n formattedPayload: {\n client_side_error: true,\n },\n },\n });\n\n await this.paymentIntegrationService.submitPayment(paymentPayloadWithError);\n } catch {\n // INFO: additional action should be ignored for this update status request.\n // will throw Stripe error message to the shopper.\n }\n }\n\n this.stripeIntegrationService.throwStripeError(stripeError);\n }\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n methodId: string,\n additionalActionData: StripeAdditionalActionRequired['data'],\n ): Promise {\n if (!this._stripeUPEClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeIntegrationService.mapStripePaymentData(\n this._stripeElements,\n redirect_url,\n !!this._allowRedisplayForStoredInstruments,\n );\n\n const isPaymentCompleted = await this.stripeIntegrationService.isPaymentCompleted(\n methodId,\n this._stripeUPEClient,\n );\n\n return !isPaymentCompleted\n ? this._stripeUPEClient.confirmPayment(stripePaymentData)\n : this._stripeUPEClient.retrievePaymentIntent(token || '');\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.stripeIntegrationService.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 initializationData: StripeInitializationData,\n ): Promise {\n if (this._stripeUPEClient) {\n return this._stripeUPEClient;\n }\n\n const state = this.paymentIntegrationService.getState();\n\n return this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n StripeJsVersion.V3,\n STRIPE_UPE_CLIENT_BETAS,\n STRIPE_UPE_CLIENT_API_VERSION,\n );\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';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeUPEPaymentStrategy from './stripe-upe-payment-strategy';\n\nconst createStripeUPEPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n\n return new StripeUPEPaymentStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n );\n};\n\nexport default toResolvableModule(createStripeUPEPaymentStrategy, [\n { gateway: 'stripeupe' },\n { gateway: 'stripeupe', id: 'klarna' },\n]);\n","import { StripePaymentEvent } from './stripe';\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 { merge } from 'lodash';\n\nimport {\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 PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n isStripePaymentEvent,\n isStripePaymentMethodLike,\n StripeAdditionalActionRequired,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElements,\n StripeElementType,\n StripeEventType,\n StripeFormattedPaymentPayload,\n StripeInitializationData,\n StripeInstrumentSetupFutureUsage,\n StripeIntegrationService,\n StripePIPaymentMethodOptions,\n StripePIPaymentMethodSavingOptions,\n StripeResult,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeOCSPaymentInitializeOptions, {\n WithStripeOCSPaymentInitializeOptions,\n} from './stripe-ocs-initialize-options';\n\nexport default class StripeOCSPaymentStrategy implements PaymentStrategy {\n private stripeClient?: StripeClient;\n private stripeElements?: StripeElements;\n private selectedMethodId?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n private stripeIntegrationService: StripeIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithStripeOCSPaymentInitializeOptions,\n ): Promise {\n const { stripeocs, methodId, gatewayId } = options;\n\n if (!stripeocs?.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(stripeocs, gatewayId, methodId);\n } catch (error) {\n if (error instanceof Error) {\n stripeocs.onError?.(error);\n }\n }\n\n this.stripeIntegrationService.initCheckoutEventsSubscription(\n gatewayId,\n methodId,\n stripeocs,\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.stripeClient) {\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 { isStoreCreditApplied } = this.paymentIntegrationService\n .getState()\n .getCheckoutOrThrow();\n\n if (isStoreCreditApplied) {\n await this.paymentIntegrationService.applyStoreCredit(isStoreCreditApplied);\n }\n\n await this.stripeIntegrationService.updateStripePaymentIntent(gatewayId, methodId);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n const { clientToken } = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n\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, gatewayId);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n const paymentElement = this.stripeElements?.getElement(StripeElementType.PAYMENT);\n\n paymentElement?.unmount();\n paymentElement?.destroy();\n this.stripeIntegrationService.deinitialize();\n this.stripeElements = undefined;\n this.stripeClient = undefined;\n\n return Promise.resolve();\n }\n\n private async _initializeStripeElement(\n stripe: StripeOCSPaymentInitializeOptions,\n gatewayId: string,\n methodId: string,\n ) {\n let paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n\n if (!paymentMethod?.clientToken) {\n const state = await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n\n paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n }\n\n if (!isStripePaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { clientToken, initializationData } = paymentMethod;\n const { customerSessionToken, enableLink } = initializationData;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.stripeClient = await this._loadStripeJs(initializationData);\n\n const {\n appearance,\n containerId,\n fonts,\n layout,\n render,\n paymentMethodSelect,\n handleClosePaymentMethod,\n togglePreloader,\n } = stripe;\n\n this.stripeElements = await this.scriptLoader.getElements(this.stripeClient, {\n clientSecret: clientToken,\n customerSessionClientSecret: customerSessionToken,\n appearance,\n fonts,\n });\n\n const { getBillingAddress, getShippingAddress } = this.paymentIntegrationService.getState();\n const billingAddress = getBillingAddress();\n const { postalCode } = getShippingAddress() || billingAddress || {};\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 link: enableLink ? StripeStringConstants.AUTO : StripeStringConstants.NEVER,\n },\n layout,\n savePaymentMethod: {\n maxVisiblePaymentMethods: 20,\n },\n defaultValues: {\n billingDetails: {\n email: billingAddress?.email || '',\n },\n },\n });\n\n this.stripeIntegrationService.mountElement(stripeElement, containerId);\n\n stripeElement.on(StripeElementEvent.LOADER_START, () => {\n togglePreloader?.(false);\n });\n\n stripeElement.on(StripeElementEvent.READY, () => {\n render();\n });\n\n stripeElement.on(StripeElementEvent.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 initializationData: StripeInitializationData,\n ): Promise {\n if (this.stripeClient) {\n return this.stripeClient;\n }\n\n const state = this.paymentIntegrationService.getState();\n const stripeJsVersion =\n this.stripeIntegrationService.getStripeJsVersion(initializationData);\n\n return this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n stripeJsVersion,\n );\n }\n\n private _collapseStripeElement() {\n const stripeElement = this.stripeElements?.getElement(StripeElementType.PAYMENT);\n\n stripeElement?.collapse();\n }\n\n private _getPaymentPayload(\n methodId: string,\n token: string,\n paymentMethodOptions?: StripePIPaymentMethodOptions,\n ): Payment {\n const cartId = this.paymentIntegrationService.getState().getCart()?.id || '';\n const { card, us_bank_account } = paymentMethodOptions || {};\n const shouldSaveInstrument =\n this._shouldSaveInstrument(card) || this._shouldSaveInstrument(us_bank_account);\n const tokenizedOptions = this._getTokenizedOptions(token, paymentMethodOptions);\n\n const formattedPayload = {\n cart_id: cartId,\n confirm: false,\n method: this.selectedMethodId,\n vault_payment_instrument: shouldSaveInstrument,\n ...tokenizedOptions,\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 gatewayId: string,\n ): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n if (!this.stripeClient || !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, error: stripeError } = await this._confirmStripePaymentOrThrow(\n methodId,\n additionalActionData,\n );\n const {\n client_secret: paymentIntentClientSecret,\n payment_method_options: paymentMethodOptions,\n } = paymentIntent || {};\n\n const paymentPayload = this._getPaymentPayload(\n methodId,\n paymentIntentClientSecret || token,\n paymentMethodOptions,\n );\n\n if (stripeError || !paymentIntent) {\n const { initializationData } = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n const { sendSecondPaymentRequestOnStripeError } = initializationData || {};\n\n if (sendSecondPaymentRequestOnStripeError) {\n // INFO: even in case when stripe payment confirmation was declined\n // we need to send submitPayment request to update status of checkout session on BE side.\n try {\n const paymentPayloadWithError = merge({}, paymentPayload, {\n paymentData: {\n formattedPayload: {\n client_side_error: true,\n },\n },\n });\n\n await this.paymentIntegrationService.submitPayment(paymentPayloadWithError);\n } catch {\n // INFO: additional action should be ignored for this update status request.\n // will throw Stripe error message to the shopper.\n }\n }\n\n this.stripeIntegrationService.throwStripeError(stripeError);\n }\n\n try {\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n methodId: string,\n additionalActionData: StripeAdditionalActionRequired['data'],\n ): Promise {\n if (!this.stripeClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeIntegrationService.mapStripePaymentData(\n this.stripeElements,\n redirect_url,\n );\n\n const isPaymentCompleted = await this.stripeIntegrationService.isPaymentCompleted(\n methodId,\n this.stripeClient,\n );\n\n return !isPaymentCompleted\n ? this.stripeClient.confirmPayment(stripePaymentData)\n : this.stripeClient.retrievePaymentIntent(token || '');\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 private _shouldSaveInstrument(paymentMethodOptions?: StripePIPaymentMethodSavingOptions) {\n const setupFutureUsage = paymentMethodOptions?.setup_future_usage;\n\n return (\n setupFutureUsage === StripeInstrumentSetupFutureUsage.ON_SESSION ||\n setupFutureUsage === StripeInstrumentSetupFutureUsage.OFF_SESSION\n );\n }\n\n private _getTokenizedOptions(\n token: string,\n paymentMethodOptions?: StripePIPaymentMethodOptions,\n ) {\n if (this._shouldSaveInstrument(paymentMethodOptions?.us_bank_account)) {\n return { tokenized_ach: { token } };\n }\n\n return { credit_card_token: { token } };\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeOCSPaymentStrategy from './stripe-ocs-payment-strategy';\n\nconst createStripeOCSPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n\n return new StripeOCSPaymentStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n );\n};\n\nexport default toResolvableModule(createStripeOCSPaymentStrategy, [\n { gateway: 'stripeocs', id: 'optimized_checkout' },\n]);\n","import { merge } from 'lodash';\n\nimport {\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 PaymentMethod,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n isStripePaymentEvent,\n StripeAdditionalActionRequired,\n StripeCheckoutInstance,\n StripeCheckoutSession,\n StripeCheckoutSessionActionResult,\n StripeCheckoutSessionActions,\n StripeCheckoutSessionPaymentStatus,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElementsCreateOptions,\n StripeEventType,\n StripeFormattedPaymentPayload,\n StripeInitializationData,\n StripeIntegrationService,\n StripeJsVersion,\n StripePaymentMethodType,\n StripeSavedPaymentMethod,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeOCSPaymentInitializeOptions, {\n WithStripeOCSPaymentInitializeOptions,\n} from '../stripe-ocs/stripe-ocs-initialize-options';\n\nexport default class StripeCSPaymentStrategy implements PaymentStrategy {\n private stripeClient?: StripeClient;\n private stripeCheckout?: StripeCheckoutInstance;\n private selectedMethodId?: string;\n\n constructor(\n private readonly paymentIntegrationService: PaymentIntegrationService,\n private readonly scriptLoader: StripeScriptLoader,\n private readonly stripeIntegrationService: StripeIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithStripeOCSPaymentInitializeOptions,\n ): Promise {\n const { stripeocs, methodId, gatewayId } = options;\n\n if (!stripeocs?.containerId || !gatewayId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n let paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n\n if (!paymentMethod?.clientToken) {\n await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n\n paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n }\n\n try {\n await this._initStripeCheckoutSession(stripeocs, paymentMethod);\n await this._updateStripeShopperData();\n this._initializePaymentElement(stripeocs, paymentMethod);\n this._initializeAdaptivePricingElement(stripeocs, paymentMethod);\n } catch (error) {\n if (error instanceof Error) {\n stripeocs.onError?.(error);\n }\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.stripeClient) {\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._updateCheckoutSessionData(gatewayId, methodId);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n const { clientToken } = state.getPaymentMethodOrThrow(methodId, gatewayId);\n const paymentPayload = this._getPaymentPayload(methodId, clientToken || '');\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._processAdditionalAction(error, gatewayId, methodId);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n const paymentElement = this.stripeCheckout?.getPaymentElement();\n const currencySelectorElement = this.stripeCheckout?.getCurrencySelectorElement();\n\n paymentElement?.unmount();\n paymentElement?.destroy();\n currencySelectorElement?.unmount();\n currencySelectorElement?.destroy();\n this.stripeCheckout = undefined;\n this.stripeClient = undefined;\n this.selectedMethodId = undefined;\n\n return Promise.resolve();\n }\n\n private async _initStripeCheckoutSession(\n stripe: StripeOCSPaymentInitializeOptions,\n paymentMethod: PaymentMethod,\n ): Promise {\n const { clientToken, initializationData } = paymentMethod;\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.stripeClient = await this._loadStripeJs(initializationData);\n\n const { appearance, fonts } = stripe;\n\n this.stripeCheckout = await this.scriptLoader.getStripeCheckout(this.stripeClient, {\n clientSecret: clientToken,\n elementsOptions: {\n appearance,\n fonts,\n },\n adaptivePricing: {\n allowed: !!initializationData?.adaptivePricingEnabled,\n },\n });\n }\n\n private _initializePaymentElement(\n stripe: StripeOCSPaymentInitializeOptions,\n paymentMethod: PaymentMethod,\n ) {\n const { initializationData, id: methodId, gateway } = paymentMethod;\n\n const { enableLink } = initializationData || {};\n const {\n containerId,\n layout,\n render,\n paymentMethodSelect,\n handleClosePaymentMethod,\n togglePreloader,\n } = stripe;\n\n const stripeElement = this._getStripeElement({\n fields: {\n billingDetails: {\n email: StripeStringConstants.NEVER,\n name: StripeStringConstants.NEVER,\n address: StripeStringConstants.NEVER,\n },\n },\n wallets: {\n applePay: StripeStringConstants.NEVER,\n googlePay: StripeStringConstants.NEVER,\n link: enableLink ? StripeStringConstants.AUTO : StripeStringConstants.NEVER,\n },\n layout,\n });\n\n if (!stripeElement || !gateway) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this.stripeIntegrationService.mountElement(stripeElement, containerId);\n\n stripeElement.on(StripeElementEvent.LOADER_START, () => {\n togglePreloader?.(false);\n });\n\n stripeElement.on(StripeElementEvent.READY, () => {\n render();\n });\n\n stripeElement.on(StripeElementEvent.CHANGE, (event: StripeEventType) => {\n this._onStripeElementChange(event, gateway, methodId, paymentMethodSelect);\n });\n\n handleClosePaymentMethod?.(this._collapseStripeElement.bind(this));\n }\n\n private async _loadStripeJs(\n initializationData: StripeInitializationData,\n ): Promise {\n if (this.stripeClient) {\n return this.stripeClient;\n }\n\n const state = this.paymentIntegrationService.getState();\n\n return this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n StripeJsVersion.CLOVER,\n );\n }\n\n private async _getStripeActionsOrThrow(): Promise {\n if (!this.stripeCheckout) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { actions, error } = await this.stripeCheckout.loadActions();\n\n if (!actions || error) {\n throw new PaymentMethodFailedError(error?.message);\n }\n\n return actions;\n }\n\n private _getStripeElement(options?: StripeElementsCreateOptions): StripeElement | undefined {\n return (\n this.stripeCheckout?.getPaymentElement() ||\n this.stripeCheckout?.createPaymentElement(options)\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 private _collapseStripeElement() {\n const stripeElement = this.stripeCheckout?.getPaymentElement();\n\n stripeElement?.collapse();\n }\n\n private async _updateCheckoutSessionData(gatewayId: string, methodId: string): Promise {\n await this._updateStripeShopperData();\n\n // INFO: to trigger checkout session data update on the BE side we need to make stripe config request\n await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n }\n\n private _getPaymentPayload(\n methodId: string,\n token: string,\n newVaultedStripeInstrument?: StripeSavedPaymentMethod,\n ): Payment {\n const cartId = this.paymentIntegrationService.getState().getCart()?.id || '';\n const tokenizedOptions = this._getTokenizedOptions(token, newVaultedStripeInstrument);\n\n const formattedPayload = {\n cart_id: cartId,\n confirm: false,\n method: this.selectedMethodId,\n vault_payment_instrument: !!newVaultedStripeInstrument,\n ...tokenizedOptions,\n };\n\n return {\n methodId,\n paymentData: {\n formattedPayload,\n },\n };\n }\n\n private async _processAdditionalAction(\n error: unknown,\n gatewayId: string,\n methodId: string,\n ): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n const { data: additionalActionData } = error.body?.additional_action_required || {};\n const { token } = additionalActionData || {};\n const existingStripeSavedPaymentMethods = await this._getStripeSavedPaymentMethodsOrThrow();\n const { session: stripeCheckoutSession, error: stripeError } =\n await this._confirmStripePayment(additionalActionData);\n const newStripeSavedPaymentMethods = await this._getStripeSavedPaymentMethodsOrThrow(\n stripeCheckoutSession,\n );\n const { id: checkoutSessionId, status: checkoutSessionStatus } =\n stripeCheckoutSession || {};\n const newVaultedStripeInstrument = this._getNewVaultedStripeInstrument(\n existingStripeSavedPaymentMethods,\n newStripeSavedPaymentMethods,\n );\n const paymentPayload = this._getPaymentPayload(\n methodId,\n checkoutSessionId || token,\n newVaultedStripeInstrument,\n );\n const { initializationData } = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n const { sendSecondPaymentRequestOnStripeError } = initializationData || {};\n\n if (stripeError || !stripeCheckoutSession) {\n if (sendSecondPaymentRequestOnStripeError) {\n // INFO: even in case when stripe payment confirmation was declined\n // we need to send submitPayment request to update status of checkout session on BE side.\n try {\n const paymentPayloadWithError = merge({}, paymentPayload, {\n paymentData: {\n formattedPayload: {\n client_side_error: true,\n },\n },\n });\n\n await this.paymentIntegrationService.submitPayment(paymentPayloadWithError);\n } catch {\n // INFO: additional action should be ignored for this update status request.\n // will throw Stripe error message to the shopper.\n }\n }\n\n throw new PaymentMethodFailedError(stripeError?.message);\n }\n\n try {\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n if (checkoutSessionStatus?.paymentStatus === StripeCheckoutSessionPaymentStatus.Paid) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n }\n\n throw error;\n }\n }\n\n private async _confirmStripePayment(\n additionalActionData: StripeAdditionalActionRequired['data'],\n ): Promise {\n const { redirect_url } = additionalActionData || {};\n\n if (!this.stripeCheckout) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const stripeActions = await this._getStripeActionsOrThrow();\n\n return stripeActions.confirm({\n redirect: StripeStringConstants.IF_REQUIRED,\n returnUrl: redirect_url,\n });\n }\n\n private async _updateStripeShopperData(): Promise {\n const stripeActions = await this._getStripeActionsOrThrow();\n\n await this._updateStripeEmail(stripeActions);\n await this._updateStripeShippingAddress(stripeActions);\n await this._updateStripeBillingAddress(stripeActions);\n }\n\n private async _updateStripeEmail(stripeActions: StripeCheckoutSessionActions): Promise {\n const stripeCheckoutSession = await stripeActions.getSession();\n\n if (stripeCheckoutSession.email) {\n return;\n }\n\n const { getBillingAddress } = this.paymentIntegrationService.getState();\n const billingAddress = getBillingAddress();\n\n await stripeActions.updateEmail(billingAddress?.email || '');\n }\n\n private async _updateStripeShippingAddress(\n stripeActions: StripeCheckoutSessionActions,\n ): Promise {\n const shippingAddress = this.paymentIntegrationService.getState().getShippingAddress();\n\n if (!shippingAddress) {\n return;\n }\n\n await stripeActions.updateShippingAddress({\n name: this.stripeIntegrationService.getShopperFullName(shippingAddress),\n address: this.stripeIntegrationService.mapStripeAddress(shippingAddress),\n });\n }\n\n private async _updateStripeBillingAddress(\n stripeActions: StripeCheckoutSessionActions,\n ): Promise {\n const billingAddress = this.paymentIntegrationService.getState().getBillingAddress();\n\n if (!billingAddress) {\n return;\n }\n\n await stripeActions.updateBillingAddress({\n name: this.stripeIntegrationService.getShopperFullName(billingAddress),\n address: this.stripeIntegrationService.mapStripeAddress(billingAddress),\n });\n }\n\n private async _getStripeSavedPaymentMethodsOrThrow(\n stripeCheckoutSession?: StripeCheckoutSession,\n ): Promise {\n if (stripeCheckoutSession?.savedPaymentMethods) {\n return stripeCheckoutSession.savedPaymentMethods;\n }\n\n const stripeActions = await this._getStripeActionsOrThrow();\n const { savedPaymentMethods } = await stripeActions.getSession();\n\n return savedPaymentMethods || [];\n }\n\n private _getNewVaultedStripeInstrument(\n existingStripeSavedPaymentMethods: StripeSavedPaymentMethod[],\n newStripeSavedPaymentMethods: StripeSavedPaymentMethod[],\n ): StripeSavedPaymentMethod | undefined {\n return newStripeSavedPaymentMethods.find(\n (method: StripeSavedPaymentMethod) =>\n !existingStripeSavedPaymentMethods.some(\n (existingMethod: StripeSavedPaymentMethod) => existingMethod.id === method.id,\n ),\n );\n }\n\n private _getTokenizedOptions(\n token: string,\n newVaultedStripeInstrument?: StripeSavedPaymentMethod,\n ) {\n if (newVaultedStripeInstrument?.type === StripePaymentMethodType.ACH) {\n return { tokenized_ach: { token } };\n }\n\n return { credit_card_token: { token } };\n }\n\n private _initializeAdaptivePricingElement(\n stripe: StripeOCSPaymentInitializeOptions,\n paymentMethod: PaymentMethod,\n ): void {\n const { initializationData } = paymentMethod;\n const { currencySelectorContainerId } = stripe;\n\n if (!initializationData?.adaptivePricingEnabled) {\n return;\n }\n\n if (!currencySelectorContainerId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const currencySelectorElement = this._getCurrencySelectorElement();\n\n if (!currencySelectorElement) {\n return;\n }\n\n currencySelectorElement.mount(`#${currencySelectorContainerId}`);\n\n this._initAdaptivePricingEvents(currencySelectorElement);\n }\n\n private _getCurrencySelectorElement(): StripeElement | undefined {\n return (\n this.stripeCheckout?.getCurrencySelectorElement() ||\n this.stripeCheckout?.createCurrencySelectorElement()\n );\n }\n\n private _initAdaptivePricingEvents(currencySelectorElement: StripeElement): void {\n currencySelectorElement.on(StripeElementEvent.CHANGE, async (event: StripeEventType) => {\n if (!event.value || !('currency' in event.value)) {\n return;\n }\n\n const { currency } = this.paymentIntegrationService.getState().getCartOrThrow();\n const currencyCode = currency.code.toLowerCase();\n const stripeCurrencyCode = event.value.currency.toLowerCase();\n\n await this.paymentIntegrationService.updatePaymentProviderCustomer({\n isCustomerCurrencySelected: currencyCode !== stripeCurrencyCode,\n customerCurrency: stripeCurrencyCode,\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';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeCSPaymentStrategy from './stripe-cs-payment-strategy';\n\nconst createStripeCSPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n\n return new StripeCSPaymentStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n );\n};\n\nexport default toResolvableModule(createStripeCSPaymentStrategy, [\n { gateway: 'stripeocs', id: 'checkout_session' },\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';\nimport { isBaseInstrument } from '@bigcommerce/checkout-sdk/utility';\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 findInstrument = instruments?.find(\n (instrument) => isBaseInstrument(instrument) && instrument.bigpayToken === instrumentId,\n );\n const trustedShippingAddress = isBaseInstrument(findInstrument)\n ? findInstrument.trustedShippingAddress\n : {};\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 messageEventListener = async (event: MessageEvent) => {\n if (event.origin.indexOf('cardinalcommerce.com') === -1) {\n return;\n }\n\n if (typeof event.data !== 'string' || !this._isValidJsonWithSessionId(event.data)) {\n return reject(new Error(PAYMENT_CANNOT_CONTINUE));\n }\n\n window.removeEventListener('message', messageEventListener);\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', messageEventListener);\n\n let iframeHidden: HTMLIFrameElement;\n\n try {\n iframeHidden = this._createHiddenIframe(error.body);\n } catch (e) {\n window.removeEventListener('message', messageEventListener);\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 && data.Status) {\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, [\n { gateway: 'worldpayaccess', id: 'credit_card' },\n { id: 'worldpayaccess' },\n]);\n","import {\n isHostedInstrumentLike,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WorldpayAccessRedirectResponse } from './worldpayaccess-payment-options';\n\nexport default class WorldpayAccessOpenBankingPaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute({ payment }: OrderRequestBody): Promise {\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n await this._paymentIntegrationService.submitOrder();\n\n try {\n await this._paymentIntegrationService.submitPayment(\n this._buildOpenBankingSubmitPayment(payment),\n );\n } catch (error) {\n if (this._isWorldpayAccessRedirectResponse(error)) {\n const redirectUrl = error.body.additional_action_required.data.redirect_url;\n\n return new Promise(() => window.location.replace(redirectUrl));\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 _buildOpenBankingSubmitPayment(payment: OrderPaymentRequestBody): Payment {\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = isHostedInstrumentLike(\n payment.paymentData,\n )\n ? payment.paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n return {\n ...payment,\n paymentData: {\n formattedPayload: {\n open_banking: {},\n vault_payment_instrument: shouldSaveInstrument || false,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || false,\n },\n },\n };\n }\n\n private _isWorldpayAccessRedirectResponse(\n response: unknown,\n ): response is WorldpayAccessRedirectResponse {\n if (typeof response !== 'object' || response === null) {\n return false;\n }\n\n const partialResponse = response as Partial;\n\n if (!partialResponse.body) {\n return false;\n }\n\n const partialBody = partialResponse.body as {\n status?: string;\n additional_action_required?: {\n data?: { redirect_url?: string };\n };\n };\n\n return (\n partialBody.status === 'additional_action_required' &&\n !!partialBody.additional_action_required?.data?.redirect_url\n );\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport WorldpayAccessOpenBankingPaymentStrategy from './worldpayaccess-open-banking-payment-strategy';\n\nconst createWorldpayAccessOpenBankingPaymentStrategy: PaymentStrategyFactory<\n WorldpayAccessOpenBankingPaymentStrategy\n> = (paymentIntegrationService) =>\n new WorldpayAccessOpenBankingPaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createWorldpayAccessOpenBankingPaymentStrategy, [\n { id: 'open_banking', gateway: 'worldpayaccess' },\n]);\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 } 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 { 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 { 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 * This error is thrown when at least one cart item changed stock position (e.g. moved to a different warehouse)\n * and the server returns type `cart_stock_positions_changed`.\n */\nexport default class CartStockPositionsChangedError extends StandardError {\n changedItemIds: string[];\n\n constructor(changedItemIds: string[], message?: string) {\n super(\n message ||\n 'At least one item changed stock position. Please review your cart and try again.',\n );\n\n this.name = 'CartStockPositionsChangedError';\n this.type = 'cart_stock_positions_changed';\n this.changedItemIds = changedItemIds;\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 { StandardError } from '../../common/error/errors';\n\nexport default class MissingShippingMethodError extends StandardError {\n constructor(message: string) {\n super(message);\n\n this.name = 'MissingShippingMethodError';\n this.type = 'missing_shipping_method';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport default class InvalidShippingAddressError extends StandardError {\n constructor(message: string) {\n super(message);\n\n this.name = 'InvalidShippingAddressError';\n this.type = 'invalid_shipping_address';\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\nimport { isNil, omitBy } from 'lodash';\n\nimport {\n CartConsistencyError,\n CartStockPositionsChangedError,\n EmptyCartError,\n} from '../cart/errors';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport { MissingShippingMethodError, OrderTaxProviderUnavailableError } from './errors';\nimport InvalidShippingAddressError from './errors/invalid-shipping-address-error';\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 if (error.body.type === 'cart_stock_positions_changed') {\n const changedItemIds =\n (error.body.errors as { changedItemIds?: string[] })?.changedItemIds ?? [];\n\n throw new CartStockPositionsChangedError(changedItemIds);\n }\n\n if (error.body.type === 'missing_shipping_method') {\n throw new MissingShippingMethodError(error.body.detail);\n }\n\n if (error.body.type === 'invalid_shipping_address') {\n throw new InvalidShippingAddressError(error.body.detail);\n }\n\n if (error.body.type === 'empty_cart') {\n throw new EmptyCartError();\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 { 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 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 { 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","// / \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 { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\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';\n\nimport { PaymentMethod } from '.';\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\n observer.next(\n createAction(\n PaymentMethodActionType.LoadPaymentMethodsSucceeded,\n methods,\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","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 { 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","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","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 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 CYBERSOURCEV2_GOOGLE_PAY = 'googlepaycybersourcev2',\n HUMM = 'humm',\n KLARNA = 'klarna',\n KLARNAV2 = 'klarnav2',\n LEGACY = 'legacy',\n MOLLIE = 'mollie',\n MONERIS = 'moneris',\n NO_PAYMENT_DATA_REQUIRED = 'nopaymentdatarequired',\n OFFLINE = 'offline',\n OFFSITE = 'offsite',\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 WORLDPAYACCESS = 'worldpayaccess',\n WORLDPAYACCESS_GOOGLE_PAY = 'googlepayworldpayaccess',\n STRIPE_GOOGLE_PAY = 'googlepaystripe',\n SEZZLE = 'sezzle',\n ZIP = 'zip',\n}\n\nexport default PaymentStrategyType;\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 { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, empty, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport {\n PaymentIntegrationService,\n PaymentStrategy as PaymentStrategyV2,\n} 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 { getDefaultLogger } from '../common/log';\nimport {\n LoadOrderPaymentsAction,\n OrderActionCreator,\n OrderPaymentRequestBody,\n OrderRequestBody,\n} from '../order';\nimport { OrderFinalizationNotRequiredError } from '../order/errors';\nimport { registerIntegrations } from '../payment-integration';\nimport { SpamProtectionAction, SpamProtectionActionCreator } from '../spam-protection';\n\nimport PaymentMethod from './payment-method';\nimport {\n OrderFinalizeOptions,\n PaymentInitializeOptions,\n PaymentRequestOptions,\n} 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 private _paymentIntegrationService: PaymentIntegrationService,\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?: OrderFinalizeOptions,\n ): ThunkAction {\n const { integrations } = options ?? {};\n\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 registerIntegrations(\n this._strategyRegistryV2,\n integrations ?? [],\n this._paymentIntegrationService,\n );\n\n let strategy: PaymentStrategy | PaymentStrategyV2;\n\n try {\n strategy = this._getStrategy(method);\n } catch {\n throw new OrderFinalizationNotRequiredError();\n }\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, integrations } = 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 registerIntegrations(\n this._strategyRegistryV2,\n integrations ?? [],\n this._paymentIntegrationService,\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 try {\n strategy = this._strategyRegistryV2.get({\n id: method.id,\n gateway: method.gateway,\n type: method.type,\n });\n } catch (error) {\n getDefaultLogger().error(\n `[PaymentStrategyActionCreator] Unable to resolve V2 strategy for id: ${method.id}, gateway: ${method.gateway}, type: ${method.type}`,\n );\n throw error;\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 { 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 { 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","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 { 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 { 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 { 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 { 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 _checkoutId?: string,\n private _cardInstrument?: CardInstrument,\n ) {\n this._iframe = document.createElement('iframe');\n\n const src = this._checkoutId\n ? `/checkout/payment/hosted-field?version=${LIBRARY_VERSION}&checkoutId=${this._checkoutId}`\n : `/checkout/payment/hosted-field?version=${LIBRARY_VERSION}`;\n\n this._iframe.src = src;\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 { 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 { 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 let paymentMethod = state.paymentMethods.getPaymentMethod(\n payload.methodId,\n payload.gatewayId,\n );\n\n if (paymentMethod?.gateway === 'worldpayaccess' && paymentMethod?.id === 'credit_card') {\n paymentMethod = { ...paymentMethod, id: 'worldpayaccess', method: 'credit-card' };\n }\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, checkoutId?: string): 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 checkoutId,\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 { 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","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","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","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 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 [],\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","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 PAYPALEXPRESS = \"paypalexpress\"\n}\nexport default CheckoutButtonMethodType;\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","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 }, {});\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 // Worldpay Access: sub-methods carry the provider name in `gateway` and the method\n // name in `id`. BigPay's mapToId uses `id` as the gateway field unless\n // `method === 'multi-option'`, so we align with hosted-form-order-data-transformer\n if (paymentMethod.gateway === 'worldpayaccess') {\n if (paymentMethod.id === 'credit_card') {\n return { ...paymentMethod, id: 'worldpayaccess', method: 'credit-card' };\n }\n\n if (paymentMethod.id === 'open_banking') {\n return { ...paymentMethod, id: 'worldpayaccess', method: 'open_banking' };\n }\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","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","export const ACKNOWLEDGE = 'ACKNOWLEDGE';\nexport const FINALIZE = 'FINALIZE';\nexport const INITIALIZE = 'INITIALIZE';\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 { 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 { 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 { 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 { 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 { 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 { 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","export enum SubStrategyType {\n CARD = 'card_ui',\n NONE = 'none',\n UNSUPPORTED = 'unsupported',\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, checkout } = this._store.getState();\n const { paymentSettings: { bigpayBaseUrl: host = '' } = {} } =\n config.getStoreConfig() || {};\n const checkoutId = checkout.getCheckoutOrThrow().id;\n\n if (!formOptions) {\n throw new InvalidArgumentError();\n }\n\n const form = formOptions && this._hostedFormFactory.create(host, formOptions, checkoutId);\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 { 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 { 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 { 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 { 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 { 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 { 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 { 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 { 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 const consignmentInMemory = store\n .getState()\n .consignments.getConsignmentById(consignment.id);\n\n const alreadySelectedOptionId = consignmentInMemory?.selectedShippingOption?.id;\n\n if (alreadySelectedOptionId === consignment.shippingOptionId) {\n observer.complete();\n\n return;\n }\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 { EmptyCartError } from '../cart/errors';\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.physicalItems.stockPosition',\n 'cart.lineItems.digitalItems.options',\n 'cart.lineItems.digitalItems.stockPosition',\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\n .post(url, {\n body: consignments,\n params: {\n include: joinOrMergeIncludes(DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .put(url, {\n body,\n params: {\n include: joinOrMergeIncludes(DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .delete(url, { params: { include }, headers, timeout })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\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 { 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, 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 { 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 { 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 { id } = checkout;\n const checkoutVersion = options?.version ?? checkout.version;\n\n const { body } = await (useStoreCredit\n ? this._storeCreditRequestSender.applyStoreCredit(id, {\n ...options,\n version: checkoutVersion,\n })\n : this._storeCreditRequestSender.removeStoreCredit(id, {\n ...options,\n version: checkoutVersion,\n }));\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, version }: 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 body: { version },\n });\n }\n\n removeStoreCredit(\n checkoutId: string,\n { timeout, version }: 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 body: { version },\n });\n }\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, getLocale: getCartLocale },\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 getCartLocale: clone(getCartLocale),\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 { 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 {\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 CouponActionCreator from '../coupon/coupon-action-creator';\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 _couponActionCreator: CouponActionCreator,\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 const checkoutId = this._storeProjection.getState().getCheckoutOrThrow().id;\n\n return this._hostedFormFactory.create(host, options, checkoutId);\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 applyCoupon(\n coupon: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(this._couponActionCreator.applyCoupon(coupon, options));\n\n return this._storeProjection.getState();\n }\n\n async removeCoupon(\n coupon: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(this._couponActionCreator.removeCoupon(coupon, options));\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, RequestSender } 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 CouponActionCreator from '../coupon/coupon-action-creator';\nimport CouponRequestSender from '../coupon/coupon-request-sender';\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 requestSender?: RequestSender,\n): PaymentIntegrationService {\n const {\n config: { getHost, getLocale },\n } = store.getState();\n\n if (!requestSender) {\n requestSender = createRequestSender({ host: getHost() });\n }\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 applyCouponActionCreator = new CouponActionCreator(\n new CouponRequestSender(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 applyCouponActionCreator,\n spamProtectionActionCreator,\n paymentProviderCustomerActionCreator,\n shippingCountryActionCreator,\n remoteCheckoutActionCreator,\n paymentStrategyWidgetActionCreator,\n );\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 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","export default function isFuture(date: Date): boolean {\n return date.valueOf() > Date.now();\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 { 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 { 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 {\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 { 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","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 { 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","import { isEqual, omit } from 'lodash';\n\nimport {\n BraintreeFastlaneAddress,\n BraintreeFastlaneAuthenticationState,\n BraintreeFastlaneProfileData,\n BraintreeFastlaneStylesOption,\n BraintreeFastlaneVaultedInstrument,\n BraintreeInitializationData,\n BraintreeIntegrationService,\n getFastlaneStyles,\n isBraintreeAcceleratedCheckoutCustomer,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { CookieStorage } 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 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 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\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, fastlane } = options || {};\n const fastlaneOptions = fastlane || braintreefastlane;\n const { onPayPalFastlaneAddressChange } = fastlaneOptions || {};\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 fastlaneOptions?.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 = CookieStorage.get('bc-fastlane-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 CookieStorage.remove('bc-fastlane-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?.authenticationState !==\n 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 PayPalFastlaneAuthenticationState,\n PayPalFastlaneStylesOption,\n PayPalFastlaneUtils,\n PayPalInitializationData,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-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 _paypalSdkScriptLoader: PayPalSdkScriptLoader,\n private _paypalCommerceFastlaneUtils: PayPalFastlaneUtils,\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, fastlane } = options || {};\n const fastlaneOptions = fastlane || paypalcommercefastlane;\n const { onPayPalFastlaneAddressChange, styles } = fastlaneOptions || {};\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._paypalSdkScriptLoader.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n cart.locale,\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 if (isAuthenticationFlowCanceled) {\n this._paypalCommerceFastlaneUtils.removeStorageSessionId();\n } else {\n this._paypalCommerceFastlaneUtils.updateStorageSessionId(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 {\n PaymentProviderCustomer,\n PayPalConnectCustomer,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isPaypalAcceleratedCheckoutCustomer(\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 { 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 {\n STRIPE_UPE_CLIENT_API_VERSION,\n STRIPE_UPE_CLIENT_BETAS,\n StripeAppearanceOptions,\n StripeClient,\n StripeDisplayName,\n StripeElementEvent,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeEventType,\n StripeFormMode,\n StripeJsVersion,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\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 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?: StripeClient;\n private _stripeElements?: StripeElements;\n private sendData?: ReturnType;\n\n constructor(\n private _store: CheckoutStore,\n private _stripeScriptLoader: 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 { initializationData } = 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._stripeScriptLoader.getStripeClient(\n initializationData,\n state.cart.getLocale(),\n StripeJsVersion.V3,\n STRIPE_UPE_CLIENT_BETAS,\n STRIPE_UPE_CLIENT_API_VERSION,\n );\n\n let appearance: StripeAppearanceOptions;\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 = await this._stripeScriptLoader.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: StripeDisplayName.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(StripeElementEvent.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 { 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 { B2BTokenActionCreator } from '../b2b-token';\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 ExtensionMessage,\n ExtensionMessenger,\n ExtensionQueryMap,\n ExtensionRegion,\n WorkerExtensionMessenger,\n} from '../extension';\nimport { FormFieldsActionCreator } from '../form';\nimport { CountryActionCreator } from '../geography';\nimport { OrderActionCreator, OrderRequestBody } from '../order';\nimport {\n OrderFinalizeOptions,\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 CheckoutInitialState from './checkout-initial-state';\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 _b2bTokenActionCreator: B2BTokenActionCreator,\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 private _workerExtensionMessenger: WorkerExtensionMessenger,\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 * Hydrates the checkout service with an initial state.\n *\n * The initial state can contain various checkout data such as cart items,\n * customer information, and other relevant state.\n *\n * ```js\n * const initialState = {\n * // ... initial checkout state data\n * };\n *\n * const state = await service.hydrateInitialState(initialState);\n *\n * console.log(state.data.getCheckout());\n * ```\n *\n * @alpha\n * @param state - The initial state data to hydrate the checkout service with.\n * @returns A promise that resolves to the current state after hydration.\n */\n hydrateInitialState(state: CheckoutInitialState): Promise {\n return this._dispatch(this._checkoutActionCreator.hydrateInitialState(state));\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?: OrderFinalizeOptions): 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 * Retrieves a B2B authentication token for the current customer.\n *\n * The token can be used to authenticate requests to B2B REST and GraphQL\n * endpoints. The customer must be signed in for this method to succeed.\n * The B2B base URL and client ID are read from the checkout settings config.\n *\n * ```js\n * const state = await service.getB2BToken();\n *\n * console.log(state.data.getB2BToken());\n * ```\n *\n * @param options - Options for the request.\n * @returns A promise that resolves to the current state.\n */\n getB2BToken(options?: RequestOptions): Promise {\n const action = this._b2bTokenActionCreator.loadB2BToken(options);\n\n return this._dispatch(action, { queueId: 'b2bToken' });\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(\n container,\n region,\n this._workerExtensionMessenger,\n );\n const state = await this._dispatch(action, { queueId: 'extensions' });\n\n this._extensionEventBroadcaster.listen();\n\n return state;\n }\n\n /**\n * Clear cache for a checkout extension when removing it from UI.\n * This function should be used whenver an extension is removed from the UI.\n *\n * @alpha\n * @param region - The name of an area where the extension should be presented.\n */\n clearExtensionCache(region: ExtensionRegion): void {\n this._extensionMessenger.clearCacheByRegion(region);\n }\n\n /**\n * Posts a message to a checkout extension.\n *\n * @alpha\n * @param extensionId - The ID of an extension to post the event to.\n * @param message - The message to post to an extension.\n */\n postMessageToExtension(extensionId: string, message: ExtensionMessage): void {\n this._extensionMessenger.post(extensionId, message);\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]) => Promise | void,\n ): () => void {\n return this._extensionMessenger.listenForCommand(extensionId, command, handler);\n }\n\n /**\n * Manages the query handler for an extension.\n *\n * @alpha\n * @param extensionId - The ID of the extension sending the query.\n * @param query - The query to be handled.\n * @param handler - The handler function for the extension query.\n * @returns A function that, when called, will deregister the query handler.\n */\n handleExtensionQuery(\n extensionId: string,\n query: T,\n handler: (command: ExtensionQueryMap[T]) => Promise | void,\n ): () => void {\n return this._extensionMessenger.listenForQuery(extensionId, query, 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","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","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 * 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","export interface B2BToken {\n token: string;\n}\n\nexport default interface B2BTokenState {\n data?: B2BToken;\n errors: B2BTokenErrorsState;\n statuses: B2BTokenStatusesState;\n}\n\nexport interface B2BTokenErrorsState {\n loadError?: Error;\n}\n\nexport interface B2BTokenStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: B2BTokenState = {\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';\n\nimport { B2BTokenActionType, LoadB2BTokenAction } from './b2b-token-actions';\nimport B2BTokenState, {\n B2BToken,\n B2BTokenErrorsState,\n B2BTokenStatusesState,\n DEFAULT_STATE,\n} from './b2b-token-state';\n\nexport default function b2bTokenReducer(\n state: B2BTokenState = DEFAULT_STATE,\n action: Action,\n): B2BTokenState {\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: B2BToken | undefined, action: LoadB2BTokenAction): B2BToken | undefined {\n switch (action.type) {\n case B2BTokenActionType.LoadB2BTokenSucceeded:\n return action.payload;\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: B2BTokenErrorsState = DEFAULT_STATE.errors,\n action: LoadB2BTokenAction,\n): B2BTokenErrorsState {\n switch (action.type) {\n case B2BTokenActionType.LoadB2BTokenRequested:\n case B2BTokenActionType.LoadB2BTokenSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case B2BTokenActionType.LoadB2BTokenFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: B2BTokenStatusesState = DEFAULT_STATE.statuses,\n action: LoadB2BTokenAction,\n): B2BTokenStatusesState {\n switch (action.type) {\n case B2BTokenActionType.LoadB2BTokenRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case B2BTokenActionType.LoadB2BTokenFailed:\n case B2BTokenActionType.LoadB2BTokenSucceeded:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\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 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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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 | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return replace(data, action.payload?.checkout?.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, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { BillingAddressAction, BillingAddressActionType } from '../billing';\nimport {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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 | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return objectMerge(data, action.payload?.checkout?.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 { 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 { 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 { CheckoutHydrateAction, CheckoutHydrateActionType } from '../checkout';\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(\n data: Config | undefined,\n action: LoadConfigAction | CheckoutHydrateAction,\n): Config | undefined {\n switch (action.type) {\n case ConfigActionType.LoadConfigSucceeded:\n return objectMerge(data, action.payload);\n\n case CheckoutHydrateActionType.HydrateInitialState: {\n const merged = objectMerge(data, action.payload?.config);\n\n // b2bApiSettings is a top-level field in CheckoutInitialState (separate from config),\n // so it must be merged into storeConfig manually after the config hydration.\n // Skip if config data is absent or this is a non-B2B store (no b2bApiSettings).\n if (!merged || !action.payload?.b2bApiSettings) {\n return merged;\n }\n\n return {\n ...merged,\n storeConfig: {\n ...merged.storeConfig,\n b2bApiSettings: action.payload.b2bApiSettings,\n },\n };\n }\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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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 | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return arrayReplace(data, action.payload?.checkout?.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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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:\n | CheckoutAction\n | GiftCertificateAction\n | ConsignmentAction\n | CouponAction\n | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return arrayReplace(data, action.payload?.checkout?.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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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 | CheckoutHydrateAction;\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 case CheckoutHydrateActionType.HydrateInitialState:\n return objectMerge(data, action.payload?.checkout?.customer);\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 {\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} from '../checkout/checkout-hydrate-actions';\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 | CheckoutHydrateAction,\n): Extension[] | undefined {\n if (action.type === ExtensionActionType.LoadExtensionsSucceeded) {\n return arrayReplace(data, action.payload);\n }\n\n if (action.type === CheckoutHydrateActionType.HydrateInitialState) {\n return arrayReplace(data, action.payload?.extensions);\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 { ExtraFields } from './extra-field';\nimport { FormFields } from './form-field';\n\nexport default interface FormFieldsState {\n data?: FormFields;\n extraFields?: ExtraFields;\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 { CheckoutHydrateAction, CheckoutHydrateActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { ExtraFields } from './extra-field';\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 extraFields: extraFieldsReducer,\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 | CheckoutHydrateAction,\n): FormFields | undefined {\n switch (action.type) {\n case FormFieldsActionType.LoadFormFieldsSucceeded:\n return objectMerge(data, action.payload);\n\n case CheckoutHydrateActionType.HydrateInitialState:\n return objectMerge(data, action.payload?.formFields);\n\n default:\n return data;\n }\n}\n\nfunction extraFieldsReducer(\n extraFields: ExtraFields | undefined,\n action: CheckoutHydrateAction,\n): ExtraFields | undefined {\n switch (action.type) {\n case CheckoutHydrateActionType.HydrateInitialState:\n return action.payload?.extraFields ?? extraFields;\n\n default:\n return extraFields;\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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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:\n | ConsignmentAction\n | CheckoutAction\n | CouponAction\n | CustomerAction\n | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return arrayReplace(data, action.payload?.checkout?.consignments);\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 { CheckoutHydrateAction, CheckoutHydrateActionType } from './checkout-hydrate-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 | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return objectMerge(\n data,\n omit(action.payload?.checkout, [\n 'billingAddress',\n 'cart',\n 'consignments',\n 'customer',\n 'coupons',\n 'giftCertificates',\n ]),\n ) as CheckoutDataState;\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\ntype FunctionProperties = {\n [K in keyof T]: T[K] extends (...args: unknown[]) => unknown ? T[K] : never;\n};\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<{ [key: string]: T }>((result, key) => {\n result[key] = createFreezeProxy(map[key]);\n\n return result;\n }, {}) 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 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 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 'worldpayaccess.credit_card': {\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 bigcommerce_payments_creditcards: {\n provider: 'bigcommerce_payments',\n method: 'credit_card',\n },\n bigcommerce_payments: {\n provider: 'bigcommerce_payments',\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 { createB2BTokenSelectorFactory } from '../b2b-token';\nimport { 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 createB2BTokenSelector = createB2BTokenSelectorFactory();\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 b2bToken = createB2BTokenSelector(state.b2bToken);\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 b2bToken,\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 { createSelector } from '../common/selector';\n\nimport B2BTokenState, { DEFAULT_STATE } from './b2b-token-state';\n\nexport default interface B2BTokenSelector {\n getToken(): string | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type B2BTokenSelectorFactory = (state: B2BTokenState) => B2BTokenSelector;\n\nexport function createB2BTokenSelectorFactory(): B2BTokenSelectorFactory {\n const getToken = createSelector(\n (state: B2BTokenState) => state.data?.token,\n (token) => () => token,\n );\n\n const getLoadError = createSelector(\n (state: B2BTokenState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: B2BTokenState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: B2BTokenState = DEFAULT_STATE): B2BTokenSelector => {\n return {\n getToken: getToken(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';\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 { 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 getLocale(): string | undefined;\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 const getLocale = createSelector(\n (state: CartState) => state.data?.locale,\n (data) => () => data,\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 getLocale: getLocale(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 { 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 = { customerAccount: [], shippingAddress: [], billingAddress: [] }) =>\n () =>\n data\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 { 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 { 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';\nimport mapExtraFieldToFormField from './map-extra-field-to-form-field';\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 getAddressExtraFields(): 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 getAddressExtraFields = createSelector(\n (state: FormFieldsState) => state.extraFields,\n (extraFields) => () => {\n if (!extraFields || !extraFields.address.length) {\n return [];\n }\n\n return extraFields.address.map(mapExtraFieldToFormField);\n },\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 getAddressExtraFields: getAddressExtraFields(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 { 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';\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 [],\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 { 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 { 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 { 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 { 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 initialStoreState: Partial = {},\n options?: CheckoutStoreOptions,\n): CheckoutStore {\n const actionTransformer = createActionTransformer(createRequestErrorFactory());\n const createInternalCheckoutSelectors = createInternalCheckoutSelectorsFactory();\n const stateTransformer = (state: CheckoutStoreState) => createInternalCheckoutSelectors(state);\n const reducer = createCheckoutStoreReducer();\n\n return createDataStore(reducer, initialStoreState, {\n actionTransformer,\n stateTransformer,\n ...options,\n });\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 { 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, combineReducers, Reducer } from '@bigcommerce/data-store';\n\nimport { b2bTokenReducer } from '../b2b-token';\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 b2bToken: b2bTokenReducer,\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, RequestSender } from '@bigcommerce/request-sender';\nimport { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport { B2BTokenActionCreator, B2BTokenRequestSender } from '../b2b-token';\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { createDataStoreProjection } from '../common/data-store';\nimport { ErrorActionCreator, ErrorLogger } from '../common/error';\nimport { ExperimentAwareRequestSender } from '../common/http-request';\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 WorkerExtensionMessenger,\n} from '../extension';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport * as customerStrategyFactories from '../generated/customer-strategies';\nimport * as paymentStrategyFactories 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 experimentRequestSender = new ExperimentAwareRequestSender(requestSender, {\n getBasePath: () => store.getState().config.getStoreConfig()?.links.baseUrl ?? undefined,\n getFeatures: () =>\n store.getState().config.getStoreConfig()?.checkoutSettings?.features ?? {},\n }) as unknown as RequestSender;\n const paymentClient = createPaymentClient(store);\n const orderRequestSender = new OrderRequestSender(experimentRequestSender);\n const checkoutRequestSender = new CheckoutRequestSender(experimentRequestSender);\n const configActionCreator = new ConfigActionCreator(new ConfigRequestSender(requestSender));\n const spamProtection = createSpamProtection(createScriptLoader());\n const spamProtectionRequestSender = new SpamProtectionRequestSender(experimentRequestSender);\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(experimentRequestSender),\n );\n const formFieldsActionCreator = new FormFieldsActionCreator(\n new FormFieldsRequestSender(experimentRequestSender),\n );\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n configActionCreator,\n formFieldsActionCreator,\n );\n const paymentIntegrationService = createPaymentIntegrationService(\n store,\n experimentRequestSender,\n );\n\n // NO_PAYMENT_DATA_REQUIRED must always be available regardless of build mode — it handles\n // free orders / full store credit checkouts and cannot be lazily loaded via integrations.\n const essentialPaymentStrategyFactories = {\n createNoPaymentStrategy: paymentStrategyFactories.createNoPaymentStrategy,\n };\n const registryV2 = createPaymentStrategyRegistryV2(\n paymentIntegrationService,\n process.env.ESSENTIAL_BUILD ? essentialPaymentStrategyFactories : paymentStrategyFactories,\n { useFallback: true },\n );\n const customerRegistryV2 = createCustomerStrategyRegistryV2(\n paymentIntegrationService,\n process.env.ESSENTIAL_BUILD ? {} : customerStrategyFactories,\n );\n const extensionActionCreator = new ExtensionActionCreator(\n new ExtensionRequestSender(experimentRequestSender),\n );\n const workerExtensionMessenger = new WorkerExtensionMessenger();\n const extensionMessenger = new ExtensionMessenger(store, workerExtensionMessenger);\n const storeProjection = createDataStoreProjection(store, createCheckoutSelectorsFactory());\n\n return new CheckoutService(\n store,\n storeProjection,\n extensionMessenger,\n createExtensionEventBroadcaster(storeProjection, extensionMessenger),\n new B2BTokenActionCreator(new B2BTokenRequestSender(requestSender)),\n new BillingAddressActionCreator(\n new BillingAddressRequestSender(experimentRequestSender),\n subscriptionsActionCreator,\n ),\n checkoutActionCreator,\n configActionCreator,\n new CustomerActionCreator(\n new CustomerRequestSender(experimentRequestSender),\n checkoutActionCreator,\n spamProtectionActionCreator,\n ),\n new ConsignmentActionCreator(\n new ConsignmentRequestSender(experimentRequestSender),\n checkoutRequestSender,\n ),\n new CountryActionCreator(new CountryRequestSender(experimentRequestSender, { locale })),\n new CouponActionCreator(new CouponRequestSender(experimentRequestSender)),\n new CustomerStrategyActionCreator(\n createCustomerStrategyRegistry(store, experimentRequestSender),\n customerRegistryV2,\n paymentIntegrationService,\n ),\n new ErrorActionCreator(),\n new GiftCertificateActionCreator(new GiftCertificateRequestSender(experimentRequestSender)),\n new InstrumentActionCreator(\n new InstrumentRequestSender(paymentClient, experimentRequestSender),\n ),\n orderActionCreator,\n new PaymentMethodActionCreator(new PaymentMethodRequestSender(experimentRequestSender)),\n new PaymentStrategyActionCreator(\n createPaymentStrategyRegistry(store, paymentClient, experimentRequestSender),\n registryV2,\n orderActionCreator,\n spamProtectionActionCreator,\n paymentIntegrationService,\n ),\n new PickupOptionActionCreator(new PickupOptionRequestSender(experimentRequestSender)),\n new ShippingCountryActionCreator(\n new ShippingCountryRequestSender(experimentRequestSender, { locale }),\n store,\n ),\n new ShippingStrategyActionCreator(\n createShippingStrategyRegistry(store, experimentRequestSender),\n ),\n new SignInEmailActionCreator(new SignInEmailRequestSender(experimentRequestSender)),\n spamProtectionActionCreator,\n new StoreCreditActionCreator(new StoreCreditRequestSender(experimentRequestSender)),\n subscriptionsActionCreator,\n formFieldsActionCreator,\n extensionActionCreator,\n workerExtensionMessenger,\n );\n}\n\nexport interface CheckoutServiceOptions {\n locale?: string;\n host?: string;\n shouldWarnMutation?: boolean;\n externalSource?: string;\n errorLogger?: ErrorLogger;\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';\n\nexport interface PaymentStrategyFactories {\n [key: string]: PaymentStrategyFactory;\n}\n\nexport default function createPaymentStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n paymentStrategyFactories: PaymentStrategyFactories,\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 {\n CustomerStrategy,\n CustomerStrategyFactory,\n CustomerStrategyResolveId,\n isResolvableModule,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\n\nexport interface CustomerStrategyFactories {\n [key: string]: CustomerStrategyFactory;\n}\n\nexport default function createCustomerStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n customerStrategyFactories: CustomerStrategyFactories,\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 {\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 { 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 B2B authentication token for the current customer.\n *\n * @returns The B2B token string if it has been loaded, otherwise undefined.\n */\n getB2BToken(): string | 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 address extra fields.\n *\n * @returns The list of extra fields if available, otherwise an empty array.\n */\n getAddressExtraFields(): 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 getB2BToken = createSelector(\n ({ b2bToken }: InternalCheckoutSelectors) => b2bToken.getToken,\n (getToken) => clone(getToken),\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 getAddressExtraFields = createSelector(\n ({ form }: InternalCheckoutSelectors) => form.getAddressExtraFields,\n (getAddressExtraFields) => clone(getAddressExtraFields),\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 getB2BToken: getB2BToken(state),\n getInstruments: getInstruments(state),\n getCustomerAccountFields: getCustomerAccountFields(state),\n getBillingAddressFields: getBillingAddressFields(state),\n getShippingAddressFields: getShippingAddressFields(state),\n getAddressExtraFields: getAddressExtraFields(state),\n getPickupOptions: getPickupOptions(state),\n getUserExperienceSettings: getUserExperienceSettings(state),\n getPaymentProviderCustomer: getPaymentProviderCustomer(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport {\n CartChangedError,\n CartConsistencyError,\n CartStockPositionsChangedError,\n} 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():\n | Error\n | CartChangedError\n | CartConsistencyError\n | CartStockPositionsChangedError\n | 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 load the B2B token.\n *\n * @returns The error object if unable to load the B2B token, otherwise undefined.\n */\n getLoadB2BTokenError(): 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 getLoadB2BTokenError: state.b2bToken.getLoadError,\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 a B2B token is being loaded.\n *\n * @returns True if a B2B token is being loaded, otherwise false.\n */\n isLoadingB2BToken(): 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 isLoadingB2BToken: state.b2bToken.isLoading,\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 { 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 { 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 {\n createSpamProtection,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\n\nimport CustomerActionCreator from './customer-action-creator';\nimport CustomerRequestSender from './customer-request-sender';\nimport { CustomerStrategy } from './strategies';\nimport { DefaultCustomerStrategy } from './strategies/default';\n\nexport default function createCustomerStrategyRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\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 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 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 } from '@bigcommerce/script-loader';\n\nimport { CheckoutRequestSender, CheckoutStore, CheckoutValidator } from '../checkout';\nimport { BrowserStorage } from '../common/storage';\nimport { HostedFormFactory } from '../hosted-form';\nimport { OrderActionCreator, OrderRequestSender } from '../order';\nimport { createSpamProtection, PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport PaymentActionCreator from './payment-action-creator';\nimport PaymentRequestSender from './payment-request-sender';\nimport PaymentRequestTransformer from './payment-request-transformer';\nimport PaymentStrategyRegistry from './payment-strategy-registry';\nimport PaymentStrategyType from './payment-strategy-type';\nimport { ConvergePaymentStrategy } from './strategies/converge';\nimport {\n createStepHandler,\n createSubStrategyRegistry,\n PaymentResumer,\n PPSDKStrategy,\n} from './strategies/ppsdk';\n\nexport default function createPaymentStrategyRegistry(\n store: CheckoutStore,\n paymentClient: any,\n requestSender: RequestSender,\n) {\n const registry = new PaymentStrategyRegistry({\n defaultToken: PaymentStrategyType.CREDIT_CARD,\n });\n\n const paymentRequestTransformer = new PaymentRequestTransformer();\n const paymentRequestSender = new PaymentRequestSender(paymentClient);\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const checkoutValidator = new CheckoutValidator(checkoutRequestSender);\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 formPoster = createFormPoster();\n const stepHandler = createStepHandler(formPoster, paymentHumanVerificationHandler);\n const hostedFormFactory = new HostedFormFactory(store);\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.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 return registry;\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';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { createAmazonPayV2PaymentProcessor } from '@bigcommerce/checkout-sdk/amazon-pay-utils';\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n createPayPalFastlaneUtils,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { createPaymentIntegrationService } from '../payment-integration';\nimport { PaymentProviderCustomerActionCreator } from '../payment-provider-customer';\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 paymentIntegrationService = createPaymentIntegrationService(store);\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 const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\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(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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 createPayPalSdkScriptLoader(),\n createPayPalFastlaneUtils(),\n ),\n );\n\n registry.register(\n 'default',\n () => new DefaultShippingStrategy(store, consignmentActionCreator),\n );\n\n return registry;\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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory 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 getButtonStyle = (buttonStyle?: ButtonStyleOption): string => {\n switch (buttonStyle) {\n case ButtonStyleOption.White:\n return 'white';\n\n case ButtonStyleOption.WhiteBorder:\n return 'white-outline';\n\n case ButtonStyleOption.Black:\n default:\n return 'black';\n }\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 private _applePayScriptLoader: ApplePayScriptLoader,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithApplePayButtonInitializeOptions,\n ): Promise {\n const { methodId, containerId, applepay } = options;\n\n if (!methodId || !applepay) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n await this._applePayScriptLoader.loadSdk();\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 (\n this._paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE &&\n this._paymentMethod.clientToken\n ) {\n this._braintreeSdk.initialize(this._paymentMethod.clientToken);\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 applePayButton = this._createApplePayButtonElement(styleOption);\n\n container.appendChild(applePayButton);\n\n return applePayButton;\n }\n\n private _createApplePayButtonElement(styleOption?: ButtonStyleOption): HTMLElement {\n const applePayButton = document.createElement('apple-pay-button');\n\n applePayButton.setAttribute('buttonstyle', getButtonStyle(styleOption));\n applePayButton.setAttribute('type', 'plain');\n applePayButton.setAttribute(\n 'style',\n '--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;',\n );\n\n return applePayButton;\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\n const state = this._paymentIntegrationService.getState();\n const { shouldExecuteSpamCheck } = state.getCheckoutOrThrow();\n\n if (shouldExecuteSpamCheck) {\n await this._paymentIntegrationService.verifyCheckoutSpamProtection();\n }\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","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\n} 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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayButtonStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n\n return new ApplePayButtonStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), window, braintreeSDKVersionManager),\n ),\n new ApplePayScriptLoader(new ScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createApplePayButtonStrategy, [{ id: 'applepay' }]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n PayPalBuyNowInitializeOptions,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsButtonInitializeOptions, {\n WithBigCommercePaymentsButtonInitializeOptions,\n} from './bigcommerce-payments-button-initialize-options';\n\nexport default class BigCommercePaymentsButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithBigCommercePaymentsButtonInitializeOptions,\n ): Promise {\n const { bigcommerce_payments, containerId, methodId } = options;\n\n const isBuyNowFlow = Boolean(bigcommerce_payments?.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 (!bigcommerce_payments) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !bigcommerce_payments.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof bigcommerce_payments.buyNowInitializeOptions?.getBuyNowCartRequestBody !==\n 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments.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 ? bigcommerce_payments.currencyCode\n : this.paymentIntegrationService.getState().getCartOrThrow().currency.code;\n\n await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(\n methodId,\n currencyCode,\n false,\n );\n\n this.renderButton(containerId, methodId, bigcommerce_payments, isBuyNowFlow);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n bigcommerce_payments: BigCommercePaymentsButtonInitializeOptions,\n isBuyNowFlow?: boolean,\n ): void {\n const { buyNowInitializeOptions, style, onComplete, onEligibilityFailure } =\n bigcommerce_payments;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, isAppSwitchEnabled } =\n paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n ...(!isBuyNowFlow &&\n this.isPaypalCommerceAppSwitchEnabled(methodId) && {\n appSwitchWhenAvailable: true,\n }),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder('bigcommerce_payments'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const hostedCheckoutCallbacks = {\n ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n }),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const buttonRenderOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n if (paypalButton.hasReturned?.() && this.isPaypalCommerceAppSwitchEnabled(methodId)) {\n paypalButton.resume?.();\n } else {\n paypalButton.render(`#${containerId}`);\n }\n } else if (onEligibilityFailure && typeof onEligibilityFailure === 'function') {\n onEligibilityFailure();\n } else {\n this.bigCommercePaymentsIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart =\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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 =\n this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n } catch (error) {\n if (typeof error === 'string') {\n throw new Error(error);\n }\n\n throw error;\n }\n }\n\n /**\n *\n * PayPal AppSwitch enabling handling\n *\n */\n private isPaypalCommerceAppSwitchEnabled(methodId: string): boolean {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n return paymentMethod.initializationData?.isAppSwitchEnabled ?? false;\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsButtonStrategy from './bigcommerce-payments-button-strategy';\n\nconst createBigCommercePaymentsButtonStrategy: CheckoutButtonStrategyFactory<\n BigCommercePaymentsButtonStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsButtonStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsButtonStrategy, [\n { id: 'bigcommerce_payments' },\n]);\n","import { BigCommercePaymentsInitializationData } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n PayPalBuyNowInitializeOptions,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsPayLaterButtonInitializeOptions, {\n WithBigCommercePaymentsPayLaterButtonInitializeOptions,\n} from './bigcommerce-payments-paylater-button-initialize-options';\n\nexport default class BigCommercePaymentsPayLaterButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions &\n WithBigCommercePaymentsPayLaterButtonInitializeOptions,\n ): Promise {\n const { bigcommerce_payments_paylater, containerId, methodId } = options;\n const { buyNowInitializeOptions, currencyCode: providedCurrencyCode } =\n bigcommerce_payments_paylater || {};\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 (!bigcommerce_payments_paylater) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_paylater\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_paylater.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.bigcommerce_payments_paylater.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.bigCommercePaymentsIntegrationService.loadPayPalSdk(\n methodId,\n currencyCode,\n false,\n );\n\n this.renderButton(containerId, methodId, bigcommerce_payments_paylater);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n bigcommerce_payments_paylater: BigCommercePaymentsPayLaterButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style, onComplete, onEligibilityFailure } =\n bigcommerce_payments_paylater;\n\n const bigCommercePaymentsSdk =\n this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_paylater',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.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 = [\n bigCommercePaymentsSdk.FUNDING.PAYLATER,\n bigCommercePaymentsSdk.FUNDING.CREDIT,\n ];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (!hasRenderedSmartButton) {\n const buttonRenderOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = bigCommercePaymentsSdk.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.bigCommercePaymentsIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart =\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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 =\n this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsPayLaterButtonStrategy from './bigcommerce-payments-paylater-button-strategy';\n\nconst createBigCommercePaymentsPayLaterButtonStrategy: CheckoutButtonStrategyFactory<\n BigCommercePaymentsPayLaterButtonStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsPayLaterButtonStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsPayLaterButtonStrategy, [\n { id: 'bigcommerce_payments_paylater' },\n]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n StyleButtonColor,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsVenmoButtonInitializeOptions, {\n WithBigCommercePaymentsVenmoButtonInitializeOptions,\n} from './bigcommerce-payments-venmo-button-initialize-options';\n\nexport default class BigCommercePaymentsVenmoButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions &\n WithBigCommercePaymentsVenmoButtonInitializeOptions,\n ): Promise {\n const { bigcommerce_payments_venmo, containerId, methodId } = options;\n const { buyNowInitializeOptions, currencyCode: providedCurrencyCode } =\n bigcommerce_payments_venmo || {};\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 (!bigcommerce_payments_venmo) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_venmo\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_venmo.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.bigcommerce_payments_venmo.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.bigCommercePaymentsIntegrationService.loadPayPalSdk(\n methodId,\n currencyCode,\n false,\n );\n\n this.renderButton(containerId, methodId, bigcommerce_payments_venmo);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n bigcommerce_payments_venmo: BigCommercePaymentsVenmoButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style, onEligibilityFailure } = bigcommerce_payments_venmo;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const fundingSource = paypalSdk.FUNDING.VENMO;\n\n const defaultCallbacks = {\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_venmo',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const buttonRenderOptions: BigCommercePaymentsButtonsOptions = {\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.bigCommercePaymentsIntegrationService.removeElement(containerId);\n }\n }\n\n private getValidVenmoButtonStyles(style: PayPalButtonStyleOptions | undefined) {\n const validButtonStyle =\n this.bigCommercePaymentsIntegrationService.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 =\n await this.bigCommercePaymentsIntegrationService.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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsVenmoButtonStrategy from './bigcommerce-payments-venmo-button-strategy';\n\nconst createBigCommercePaymentsVenmoButtonStrategy: CheckoutButtonStrategyFactory<\n BigCommercePaymentsVenmoButtonStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsVenmoButtonStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsVenmoButtonStrategy, [\n { id: 'bigcommerce_payments_venmo' },\n]);\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 { isNil, omitBy } from 'lodash';\n\nimport { PaypalStyleOptions } from '@bigcommerce/checkout-sdk/braintree-utils';\n\nexport default function getValidButtonStyle(style?: PaypalStyleOptions): PaypalStyleOptions {\n const { color, fundingicons, height = 40, 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 | string): number {\n const minHeight = 25;\n const defaultHeight = 40;\n const maxHeight = 55;\n\n const currentHeight = Number(height);\n\n if (!currentHeight || Number.isNaN(currentHeight)) {\n return defaultHeight;\n }\n\n if (currentHeight > maxHeight) {\n return maxHeight;\n }\n\n if (currentHeight < minHeight) {\n return minHeight;\n }\n\n return currentHeight;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n BraintreeError,\n BraintreeHostWindow,\n BraintreeInitializationData,\n BraintreeIntegrationService,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n isBraintreeError,\n PaypalAuthorizeData,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n BuyNowCartCreationError,\n BuyNowCartRequestBody,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport getValidButtonStyle from '../get-valid-button-style';\nimport mapToBraintreeShippingAddressOverride from '../map-to-braintree-shipping-address-override';\n\nimport BraintreePaypalButtonInitializeOptions, {\n WithBraintreePaypalButtonInitializeOptions,\n} from './braintree-paypal-button-initialize-options';\n\nexport default class BraintreePaypalButtonStrategy implements CheckoutButtonStrategy {\n private buyNowCartId: string | undefined;\n\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: CheckoutButtonInitializeOptions & WithBraintreePaypalButtonInitializeOptions,\n ): Promise {\n const { braintreepaypal, 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 (!braintreepaypal) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal\" argument is not provided.`,\n );\n }\n\n let state = this.paymentIntegrationService.getState();\n let currencyCode: string;\n\n if (braintreepaypal.buyNowInitializeOptions) {\n if (!braintreepaypal.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypalcredit.currencyCode\" argument is not provided.`,\n );\n }\n\n currencyCode = braintreepaypal.currencyCode;\n } else {\n await this.paymentIntegrationService.loadDefaultCheckout();\n\n state = this.paymentIntegrationService.getState();\n currencyCode = state.getCartOrThrow().currency.code;\n }\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { clientToken, config, 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 commit: false,\n };\n\n const paypalCheckoutSuccessCallback = (\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n this.renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypal,\n containerId,\n methodId,\n !!config.testMode,\n );\n };\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this.handleError(error, containerId, braintreepaypal.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 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.braintreeHostWindow;\n\n if (paypal) {\n const paypalButtonRender = paypal.Buttons({\n env: testMode ? 'sandbox' : 'production',\n fundingSource: paypal.FUNDING.PAYPAL,\n style: getValidButtonStyle(style),\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.braintreeIntegrationService.removeElement(containerId);\n }\n }\n\n private async setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalButtonInitializeOptions,\n methodId: string,\n ): Promise {\n const { onPaymentError, shippingAddress, buyNowInitializeOptions } = braintreepaypal;\n\n try {\n const buyNowCart =\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function'\n ? await this.createBuyNowCart(\n buyNowInitializeOptions.getBuyNowCartRequestBody(),\n )\n : undefined;\n\n this.buyNowCartId = buyNowCart?.id;\n\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomer();\n const paymentMethod: PaymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n const amount = buyNowCart ? buyNowCart.cartAmount : state.getCartOrThrow().cartAmount;\n const currencyCode = buyNowCart\n ? braintreepaypal.currencyCode\n : state.getCartOrThrow().currency.code;\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: unknown) {\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 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.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: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(billingAddress),\n shipping_address: JSON.stringify(shippingAddress),\n ...(this.buyNowCartId && { cart_id: this.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 async createBuyNowCart(buyNowCardRequestBody?: BuyNowCartRequestBody | void) {\n if (!buyNowCardRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n return await this.paymentIntegrationService.createBuyNowCart(buyNowCardRequestBody);\n } catch (error) {\n throw new BuyNowCartCreationError();\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 BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreePaypalButtonStrategy from './braintree-paypal-button-strategy';\n\nconst createBraintreePaypalButtonStrategy: CheckoutButtonStrategyFactory<\n BraintreePaypalButtonStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n );\n\n return new BraintreePaypalButtonStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeIntegrationService,\n braintreeHostWindow,\n );\n};\n\nexport default toResolvableModule(createBraintreePaypalButtonStrategy, [{ id: 'braintreepaypal' }]);\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n BraintreeError,\n BraintreeHostWindow,\n BraintreeInitializationData,\n BraintreeIntegrationService,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n isBraintreeError,\n PaypalAuthorizeData,\n PaypalButtonStyleLabelOption,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n BuyNowCartCreationError,\n BuyNowCartRequestBody,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport getValidButtonStyle from '../get-valid-button-style';\nimport mapToBraintreeShippingAddressOverride from '../map-to-braintree-shipping-address-override';\n\nimport BraintreePaypalCreditButtonInitializeOptions, {\n WithBraintreePaypalCreditButtonInitializeOptions,\n} from './braintree-paypal-credit-button-initialize-options';\n\nexport default class BraintreePaypalCreditButtonStrategy implements CheckoutButtonStrategy {\n private buyNowCartId: string | undefined;\n\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: CheckoutButtonInitializeOptions & WithBraintreePaypalCreditButtonInitializeOptions,\n ): 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 = this.paymentIntegrationService.getState();\n let currencyCode: string;\n\n if (braintreepaypalcredit.buyNowInitializeOptions) {\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 await this.paymentIntegrationService.loadDefaultCheckout();\n\n state = this.paymentIntegrationService.getState();\n currencyCode = state.getCartOrThrow().currency.code;\n }\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { clientToken, config, 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 commit: false,\n };\n\n const paypalCheckoutSuccessCallback = (\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n this.renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n containerId,\n methodId,\n !!config.testMode,\n );\n };\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this.handleError(error, containerId, braintreepaypalcredit.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 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.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 const buttonStyle =\n fundingSource === paypal.FUNDING.CREDIT\n ? {\n label: PaypalButtonStyleLabelOption.CREDIT,\n ...getValidButtonStyle(style),\n }\n : getValidButtonStyle(style);\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.braintreeIntegrationService.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\n try {\n const buyNowCart =\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function'\n ? await this.createBuyNowCart(\n buyNowInitializeOptions.getBuyNowCartRequestBody(),\n )\n : undefined;\n\n this.buyNowCartId = buyNowCart?.id;\n\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomer();\n const paymentMethod: PaymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n const amount = buyNowCart ? buyNowCart.cartAmount : state.getCartOrThrow().cartAmount; // state.getCheckoutOrThrow().outstandingBalance\n const currencyCode = buyNowCart\n ? braintreepaypalcredit.currencyCode\n : state.getCartOrThrow().currency.code;\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: true,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error: unknown) {\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 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.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: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(billingAddress),\n shipping_address: JSON.stringify(shippingAddress),\n ...(this.buyNowCartId && { cart_id: this.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 async createBuyNowCart(buyNowCardRequestBody?: BuyNowCartRequestBody | void) {\n if (!buyNowCardRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n return await this.paymentIntegrationService.createBuyNowCart(buyNowCardRequestBody);\n } catch (error) {\n throw new BuyNowCartCreationError();\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 BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreePaypalCreditButtonStrategy from './braintree-paypal-credit-button-strategy';\n\nconst createBraintreePaypalCreditButtonStrategy: CheckoutButtonStrategyFactory<\n BraintreePaypalCreditButtonStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n );\n return new BraintreePaypalCreditButtonStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeIntegrationService,\n braintreeHostWindow,\n );\n};\n\nexport default toResolvableModule(createBraintreePaypalCreditButtonStrategy, [\n { id: 'braintreepaypalcredit' },\n]);\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), hostWindow, braintreeSDKVersionManager),\n );\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 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 || 40}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 await this.paymentIntegrationService.loadDefaultCheckout();\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeScriptLoader = new BraintreeScriptLoader(\n scriptLoader,\n braintreeHostWindow,\n braintreeSDKVersionManager,\n );\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 GooglePayError,\n GooglePayInitializationData,\n GooglePayPaymentDataRequest,\n GooglePayPaymentOptions,\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 this._googlePayPaymentProcessor.setIsWebViewExperimentOn(\n !!paymentMethod.initializationData?.isWebViewExperimentOn,\n );\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) => Promise {\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 if (this._googlePayPaymentProcessor.isWebViewWithRestrictions()) {\n return {};\n }\n\n return {\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({\n callbackTrigger,\n shippingAddress,\n shippingOptionData,\n offerData,\n }) => {\n const {\n availableTriggers,\n addressChangeTriggers,\n shippingOptionsChangeTriggers,\n offerChangeTriggers,\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 const { newOfferInfo = undefined, error: couponsError = undefined } =\n offerChangeTriggers.includes(callbackTrigger)\n ? await this._googlePayPaymentProcessor.handleCoupons(offerData)\n : {};\n\n // We can add another errors if needed 'couponsError || shippingError || anotherError'\n const error: GooglePayError | undefined = couponsError;\n\n if (this._buyNowInitializeOptions) {\n return this._getBuyNowTransactionInfo(\n availableShippingOptions,\n newOfferInfo,\n error,\n );\n }\n\n return this._getTransactionInfo(availableShippingOptions, newOfferInfo, error);\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(\n availableShippingOptions?: ShippingOptionParameters,\n newOfferInfo?: GooglePayPaymentDataRequest['offerInfo'],\n error?: GooglePayError,\n ) {\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 ...(newOfferInfo && {\n newOfferInfo,\n }),\n ...(error && {\n error,\n }),\n };\n }\n\n private async _getTransactionInfo(\n availableShippingOptions?: ShippingOptionParameters,\n newOfferInfo?: GooglePayPaymentDataRequest['offerInfo'],\n error?: GooglePayError,\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 ...(this._countryCode && { countryCode: this._countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n ...(availableShippingOptions && {\n newShippingOptionParameters: availableShippingOptions,\n }),\n ...(newOfferInfo && {\n newOfferInfo,\n }),\n ...(error && {\n error,\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\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';\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 PayPalCommerceSdk(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';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PayPalSdkHelper } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\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 GooglePayBigCommercePaymentsGateway from './google-pay-bigcommerce-payments-gateway';\n\nconst createGooglePayBigCommercePaymentsButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayBigCommercePaymentsGateway(\n paymentIntegrationService,\n new PayPalSdkHelper(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayBigCommercePaymentsButtonStrategy, [\n { id: 'googlepay_bigcommerce_payments' },\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';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\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';\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 StripeScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayStripeButtonStrategy, [\n { id: 'googlepaystripe' },\n { id: 'googlepaystripeupe' },\n { id: 'googlepaystripeocs' },\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 PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n PaypalButtonCreationService,\n PayPalButtonOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\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 paypalIntegrationService: PayPalIntegrationService,\n private paypalButtonCreationService: PaypalButtonCreationService,\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.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, isAppSwitchEnabled } =\n paymentMethod.initializationData || {};\n\n const buyNowFlowCallbacks = {\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const buttonOptions: PayPalButtonOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalIntegrationService.getValidButtonStyle(style),\n isAppSwitchEnabled,\n isHostedCheckoutEnabled,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && onComplete && { onPaymentComplete: () => onComplete() }),\n };\n\n const paypalButton = this.paypalButtonCreationService.createPayPalButton(\n 'paypalcommerce',\n methodId,\n buttonOptions,\n buyNowInitializeOptions,\n );\n\n if (paypalButton.isEligible()) {\n if (paypalButton.hasReturned?.() && isAppSwitchEnabled) {\n paypalButton.resume?.();\n } else {\n paypalButton.render(`#${containerId}`);\n }\n } else if (onEligibilityFailure && typeof onEligibilityFailure === 'function') {\n onEligibilityFailure();\n } else {\n this.paypalIntegrationService.removeElement(containerId);\n }\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalIntegrationService,\n PaypalButtonCreationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceButtonStrategy from './paypal-commerce-button-strategy';\n\nconst createPayPalCommerceButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceButtonStrategy\n> = (paymentIntegrationService) => {\n const paypalIntegrationService = createPayPalIntegrationService(paymentIntegrationService);\n const paypalButtonCreationService = new PaypalButtonCreationService(\n paymentIntegrationService,\n paypalIntegrationService,\n );\n\n return new PayPalCommerceButtonStrategy(\n paymentIntegrationService,\n paypalIntegrationService,\n paypalButtonCreationService,\n );\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 ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalButtonsOptions,\n PayPalBuyNowInitializeOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\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 paypalIntegrationService: PayPalIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPayPalCommerceCreditButtonInitializeOptions,\n ): Promise {\n const { paypalcommercecredit, containerId, methodId } = options;\n const { buyNowInitializeOptions, currencyCode: providedCurrencyCode } =\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.paypalIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommercecredit);\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.paypalIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, isAppSwitchEnabled } =\n paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n createOrder: () => this.paypalIntegrationService.createOrder('paypalcommercecredit'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const hostedCheckoutCallbacks = {\n ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n }),\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: PayPalButtonsOptions = {\n fundingSource,\n style: this.paypalIntegrationService.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.paypalIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalIntegrationService.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.paypalIntegrationService.getBillingAddressFromOrderDetails(orderDetails);\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalIntegrationService.getShippingAddressFromOrderDetails(orderDetails);\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalIntegrationService.updateOrder('paypalcommerce');\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalIntegrationService.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.paypalIntegrationService.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.paypalIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalIntegrationService.updateOrder('paypalcommerce');\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.paypalIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalIntegrationService.updateOrder('paypalcommerce');\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';\nimport { createPayPalIntegrationService } from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceCreditButtonStrategy from './paypal-commerce-credit-button-strategy';\n\nconst createPayPalCommerceCreditButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceCreditButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditButtonStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\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 { 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 { 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 { round } from 'lodash';\n\nimport {\n AmountTransformer,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n Payment,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n ShippingOption,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n isStripePaymentMethodLike,\n StripeAdditionalActionRequired,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeError,\n StripeEventType,\n StripeInitializationData,\n StripeIntegrationService,\n StripeLinkV2Event,\n StripeLinkV2Options,\n StripeLinkV2ShippingRate,\n StripePaymentMethodType,\n StripeResult,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport {\n expressCheckoutAllowedCountryCodes,\n stripeAllowedShippingOptionsLength,\n} from './constants';\nimport { WithStripeOCSCustomerInitializeOptions } from './stripe-ocs-customer-initialize-options';\n\nexport default class StripeLinkV2ButtonStrategy implements CheckoutButtonStrategy {\n private _stripeClient?: StripeClient;\n private _stripeElements?: StripeElements;\n private _linkV2Element?: StripeElement;\n private _amountTransformer?: AmountTransformer;\n private _onComplete?: (orderId?: number) => Promise;\n private _loadingIndicatorContainer?: string;\n private _currencyCode?: string;\n private _captureMethod?: 'automatic' | 'manual';\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n private stripeIntegrationService: StripeIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithStripeOCSCustomerInitializeOptions,\n ): Promise {\n const { stripeocs, containerId } = options || {};\n\n if (!stripeocs || !containerId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { gatewayId } = stripeocs;\n\n if (!gatewayId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const methodId = this._getMethodId(gatewayId);\n const state = await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n const paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n const { loadingContainerId, buttonHeight, onComplete } = stripeocs;\n\n this._loadingIndicatorContainer = loadingContainerId;\n\n this._onComplete = onComplete;\n\n if (!isStripePaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { initializationData } = paymentMethod;\n const { captureMethod } = initializationData;\n const stripeJsVersion =\n this.stripeIntegrationService.getStripeJsVersion(initializationData);\n\n this._captureMethod = captureMethod;\n this._stripeClient = await this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n stripeJsVersion,\n );\n\n await this.paymentIntegrationService.loadDefaultCheckout();\n\n await this._mountExpressCheckoutElement(containerId, this._stripeClient, buttonHeight);\n\n this._initializeEvents(methodId);\n }\n\n signIn() {\n return Promise.resolve();\n }\n\n signOut() {\n return Promise.resolve();\n }\n\n executePaymentMethodCheckout() {\n return Promise.resolve();\n }\n\n deinitialize() {\n return Promise.resolve();\n }\n\n private async _mountExpressCheckoutElement(\n container: string,\n stripeExpressCheckoutClient: StripeClient,\n buttonHeight = 40,\n ) {\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n const expressCheckoutOptions: StripeElementsCreateOptions = {\n shippingAddressRequired: shouldRequireShippingAddress,\n ...(shouldRequireShippingAddress\n ? { allowedShippingCountries: await this._getAvailableCountries() }\n : {}),\n ...(shouldRequireShippingAddress\n ? { shippingRates: [{ id: '_', amount: 0, displayName: 'Pending rates' }] }\n : {}),\n billingAddressRequired: true,\n emailRequired: true,\n phoneNumberRequired: true,\n paymentMethods: {\n link: StripeStringConstants.AUTO,\n applePay: StripeStringConstants.NEVER,\n googlePay: StripeStringConstants.NEVER,\n amazonPay: StripeStringConstants.NEVER,\n paypal: StripeStringConstants.NEVER,\n klarna: StripeStringConstants.NEVER,\n },\n // Minimal buttonHeight value is 40\n buttonHeight,\n };\n\n const { cartAmount = 1 } = this.paymentIntegrationService.getState().getCart() || {};\n\n const elementsOptions: StripeLinkV2Options = {\n mode: 'payment',\n amount: this._toCents(cartAmount),\n currency: this._getCurrency(),\n ...(this._captureMethod ? { captureMethod: this._captureMethod } : {}),\n };\n\n this._stripeElements = stripeExpressCheckoutClient.elements(elementsOptions);\n\n this._linkV2Element = this._stripeElements.create(\n StripeElementType.EXPRESS_CHECKOUT,\n expressCheckoutOptions,\n );\n this._linkV2Element.mount(`#${container}`);\n }\n\n /** Events * */\n\n private _initializeEvents(methodId: string): void {\n if (!this._linkV2Element) {\n return;\n }\n\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n\n if (shouldRequireShippingAddress) {\n this._linkV2Element.on(StripeElementEvent.SHIPPING_ADDRESS_CHANGE, async (event) =>\n this._onShippingAddressChange(event),\n );\n this._linkV2Element.on(StripeElementEvent.SHIPPING_RATE_CHANGE, async (event) =>\n this._onShippingRateChange(event),\n );\n }\n\n this._linkV2Element.on(StripeElementEvent.CONFIRM, async (event) =>\n this._onConfirm(event, methodId),\n );\n\n this._linkV2Element.on(StripeElementEvent.CANCEL, this._onCancel);\n }\n\n private async _onShippingAddressChange(event: StripeEventType) {\n if (!('address' in event)) {\n return;\n }\n\n const shippingAddress = event.address;\n // Depending on the country, some fields can be missing or partially redacted.\n // For example, the shipping address in the US can only contain a city, state, and ZIP code.\n // The full shipping address appears in the confirm event object after the purchase is confirmed in the browser’s payment interface.\n const result = {\n firstName: '',\n lastName: '',\n phone: '',\n company: '',\n address1: '',\n address2: '',\n city: shippingAddress?.city || '',\n countryCode: shippingAddress?.country || '',\n postalCode: shippingAddress?.postal_code || '',\n stateOrProvince: shippingAddress?.state || '',\n stateOrProvinceCode: shippingAddress?.state || '',\n customFields: [],\n };\n\n await this.paymentIntegrationService.updateShippingAddress(result);\n\n const shippingRates = await this._getAvailableShippingOptions();\n\n await this._updateDisplayedPrice();\n\n if (!shippingRates?.length) {\n event.reject();\n } else {\n event.resolve({\n shippingRates,\n });\n }\n }\n\n private _onCancel() {\n throw new PaymentMethodCancelledError();\n }\n\n private async _onShippingRateChange(event: StripeEventType) {\n if ('shippingRate' in event) {\n const { shippingRate } = event;\n\n await this._handleShippingOptionChange(shippingRate?.id);\n\n await this._updateDisplayedPrice();\n\n event.resolve({});\n }\n }\n\n /** Confirm methods * */\n private async _onConfirm(event: StripeEventType, methodId: string) {\n if (\n 'billingDetails' in event &&\n 'shippingAddress' in event &&\n this._stripeClient &&\n this._stripeElements\n ) {\n await this._updateShippingAndBillingAddress(event);\n await this.paymentIntegrationService.submitOrder();\n\n const paymentPayload = this._getPaymentPayload(methodId);\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._processAdditionalAction(error, methodId);\n }\n }\n\n return Promise.resolve();\n }\n\n private async _updateShippingAndBillingAddress(event: StripeLinkV2Event) {\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n\n const firstName =\n event.shippingAddress?.name?.split(' ')[0] ||\n event.billingDetails?.name?.split(' ')[0] ||\n '';\n const lastName =\n event.shippingAddress?.name?.split(' ')[1] ||\n event.billingDetails?.name?.split(' ')[1] ||\n '';\n\n if (shouldRequireShippingAddress) {\n const shippingAddress = this._mapShippingAddress(\n event.shippingAddress,\n event.billingDetails,\n firstName,\n lastName,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n }\n\n const billingAddress = this._mapBillingAddress(\n event.shippingAddress,\n event.billingDetails,\n firstName,\n lastName,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n private _mapShippingAddress(\n shippingAddress: StripeLinkV2Event['shippingAddress'],\n billingDetails: StripeLinkV2Event['billingDetails'],\n firstName: string,\n lastName: string,\n ) {\n return {\n firstName,\n lastName,\n phone: billingDetails?.phone || '',\n company: '',\n address1: shippingAddress?.address?.line1 || '',\n address2: shippingAddress?.address?.line2 || '',\n city: shippingAddress?.address?.city || '',\n countryCode: shippingAddress?.address?.country || '',\n postalCode: shippingAddress?.address?.postal_code || '',\n stateOrProvince: shippingAddress?.address?.state || '',\n stateOrProvinceCode: shippingAddress?.address?.state || '',\n customFields: [],\n };\n }\n\n private _mapBillingAddress(\n shippingAddress: StripeLinkV2Event['shippingAddress'],\n billingDetails: StripeLinkV2Event['billingDetails'],\n firstName: string,\n lastName: string,\n ) {\n return {\n email: billingDetails?.email || '',\n firstName,\n lastName,\n phone: billingDetails?.phone || '',\n company: '',\n address1: billingDetails?.address?.line1 || '',\n address2: '',\n city: billingDetails?.address?.city || '',\n countryCode: billingDetails?.address?.country || '',\n postalCode: billingDetails?.address?.postal_code || '',\n stateOrProvince: billingDetails?.address?.state || '',\n stateOrProvinceCode: shippingAddress?.address?.state || '',\n customFields: [],\n };\n }\n\n private async _processAdditionalAction(error: unknown, methodId: string): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n if (!this._stripeClient || !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 additionalActionData,\n methodId,\n );\n\n const paymentPayload = this._getPaymentPayload(methodId, paymentIntent?.id || token);\n\n try {\n this._toggleLoadingIndicator(true);\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n await this._completeCheckoutFlow();\n } catch (error) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n } finally {\n this._toggleLoadingIndicator(false);\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n additionalActionData: StripeAdditionalActionRequired['data'],\n methodId: string,\n ): Promise {\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeIntegrationService.mapStripePaymentData(\n this._stripeElements,\n redirect_url,\n );\n let stripeError: StripeError | undefined;\n\n try {\n const isPaymentCompleted = await this.stripeIntegrationService.isPaymentCompleted(\n methodId,\n this._stripeClient,\n );\n\n const confirmationResult = !isPaymentCompleted\n ? await this._stripeClient?.confirmPayment({\n elements: stripePaymentData.elements,\n clientSecret: token,\n redirect: StripeStringConstants.IF_REQUIRED,\n confirmParams: {\n return_url: stripePaymentData.confirmParams?.return_url,\n },\n })\n : await this._stripeClient?.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 return this.stripeIntegrationService.throwStripeError(stripeError);\n }\n }\n\n private async _completeCheckoutFlow() {\n if (typeof this._onComplete === 'function') {\n return this._onComplete();\n }\n\n window.location.replace('/checkout/order-confirmation');\n\n return Promise.resolve();\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 ...(token ? { credit_card_token: { token } } : {}),\n confirm: false,\n method: StripePaymentMethodType.Link,\n };\n\n return {\n methodId,\n paymentData: {\n formattedPayload,\n },\n };\n }\n\n /** Utils * */\n\n private _shouldRequireShippingAddress() {\n const { getCart } = this.paymentIntegrationService.getState();\n\n const { lineItems } = getCart() || {};\n\n return !!lineItems?.physicalItems.length;\n }\n\n private async _updateDisplayedPrice() {\n if (this._stripeElements) {\n this._stripeElements.update({\n currency: this._getCurrency(),\n mode: 'payment',\n amount: await this._getTotalPrice(),\n });\n }\n }\n\n private _getCurrency() {\n if (!this._currencyCode) {\n const currencyCode = this.paymentIntegrationService.getState().getCart()?.currency;\n\n if (currencyCode) {\n this._currencyCode = currencyCode.code.toLowerCase();\n }\n }\n\n return this._currencyCode;\n }\n\n private async _getTotalPrice(): Promise {\n await this.paymentIntegrationService.loadCheckout();\n\n const { getCheckoutOrThrow, getCart } = this.paymentIntegrationService.getState();\n const { decimalPlaces } = getCart()?.currency || {};\n const totalPrice = round(getCheckoutOrThrow().outstandingBalance, decimalPlaces).toFixed(\n decimalPlaces,\n );\n\n return this._toCents(+totalPrice);\n }\n\n private async _getAvailableCountries(): Promise {\n const countries = await this.paymentIntegrationService.loadShippingCountries();\n const deliverableCountries =\n countries.getShippingCountries()?.map((country) => country.code) || [];\n\n return deliverableCountries.filter((code) => {\n return expressCheckoutAllowedCountryCodes.includes(code);\n });\n }\n\n private async _getAvailableShippingOptions(): Promise {\n const state = this.paymentIntegrationService.getState();\n const consignments = state.getConsignments();\n\n if (!consignments?.[0]) {\n return;\n }\n\n const consignment = consignments[0];\n const options = (consignment.availableShippingOptions || []).map(\n this._getStripeShippingOption.bind(this),\n );\n const recommendedShippingOption = consignment.availableShippingOptions?.find(\n (shippingOption) => shippingOption.isRecommended,\n );\n const selectedId = consignment.selectedShippingOption?.id;\n const recommendedId = recommendedShippingOption?.id;\n\n if (selectedId) {\n // Set selected shipping option first in the array, as it will be selected by default\n options.sort((option) => (option.id === selectedId ? -1 : 0));\n } else if (recommendedId) {\n // Set recommended shipping option first in the array, as it will be selected by default\n options.sort((option) => (option.id === recommendedId ? -1 : 0));\n await this._handleShippingOptionChange(recommendedId);\n } else {\n await this._handleShippingOptionChange(options[0]?.id);\n }\n\n // Stripe has restricted the number of shipping rates.\n return options.slice(0, stripeAllowedShippingOptionsLength);\n }\n\n private _getStripeShippingOption({ id, cost, description }: ShippingOption) {\n return {\n id,\n displayName: description,\n amount: this._toCents(cost),\n };\n }\n\n private async _handleShippingOptionChange(optionId?: string) {\n if (!optionId || optionId === 'shipping_option_unselected') {\n return;\n }\n\n return this.paymentIntegrationService.selectShippingOption(optionId);\n }\n\n private _getAmountTransformer() {\n if (this._amountTransformer) {\n return this._amountTransformer;\n }\n\n const { getCart } = this.paymentIntegrationService.getState();\n const { currency } = getCart() || {};\n\n if (currency) {\n const amountTransformer = new AmountTransformer(currency.decimalPlaces);\n\n return amountTransformer;\n }\n }\n\n private _toCents(amount: number) {\n const fallbackValue = Math.round(amount * 100);\n const amountTransformer = this._getAmountTransformer();\n\n if (amountTransformer) {\n return amountTransformer.toInteger(amount);\n }\n\n return fallbackValue;\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 _getMethodId(gatewayId: string): string {\n const { initializationData: { checkoutSessionEnabled } = {} } =\n this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(gatewayId);\n\n return checkoutSessionEnabled\n ? StripePaymentMethodType.CHECKOUT_SESSION\n : StripePaymentMethodType.OCS;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\nimport { DEFAULT_CONTAINER_STYLES, LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport StripeLinkV2ButtonStrategy from './stripe-link-v2-button-strategy';\n\nconst createLinkV2ButtonStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n const loadingIndicator = new LoadingIndicator({\n containerStyles: DEFAULT_CONTAINER_STYLES,\n });\n\n return new StripeLinkV2ButtonStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n loadingIndicator,\n );\n};\n\nexport default toResolvableModule(createLinkV2ButtonStrategy, [{ id: 'stripeocs' }]);\n","import { uniqueId } from 'lodash';\n\nimport { InvalidArgumentError } from '../error/errors';\n\nconst getUniqId = (idPrefix?: string): string => {\n const id = uniqueId(idPrefix);\n\n return document.getElementById(id) ? getUniqId(idPrefix) : id;\n};\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 = getUniqId(idPrefix);\n }\n\n return container.id;\n });\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 { 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 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","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 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 { 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 { 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","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 = '',\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 { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { createCheckoutStore } from '../checkout';\nimport { ConfigState } from '../config';\nimport * as defaultCheckoutButtonStrategyFactories from '../generated/checkout-button-strategies';\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 } = 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(\n paymentIntegrationService,\n process.env.ESSENTIAL_BUILD ? {} : defaultCheckoutButtonStrategyFactories,\n );\n\n return new CheckoutButtonInitializer(\n store,\n new CheckoutButtonStrategyActionCreator(\n createCheckoutButtonRegistry(store, requestSender, formPoster, 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';\n\nexport interface CheckoutButtonStrategyFactories {\n [key: string]: CheckoutButtonStrategyFactory;\n}\n\nexport default function createCheckoutButtonStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n checkoutButtonStrategyFactories: CheckoutButtonStrategyFactories,\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 { CheckoutActionCreator, CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { PaypalScriptLoader } from '../payment/strategies/paypal';\n\nimport { CheckoutButtonMethodType, CheckoutButtonStrategy } from './strategies';\nimport { PaypalButtonStrategy } from './strategies/paypal';\n\nexport default function createCheckoutButtonRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\n formPoster: FormPoster,\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 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 { 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 { 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","import { FormatError, IntlMessageFormat } from 'intl-messageformat';\nimport { isObject, union } from 'lodash';\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\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 }\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._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 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 }, {});\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","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 { 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","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":["y","x","module","exports","iframeResizer","__WEBPACK_EXTERNAL_MODULE_iframe_resizer_1512d797__","__webpack_require__","d","__WEBPACK_EXTERNAL_MODULE_iframe_resizer_js_iframeResizer_contentWindow_a6cfc03f__","__webpack_module_cache__","moduleId","cachedModule","undefined","__webpack_modules__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","r","Symbol","toStringTag","value","B2B_EXTRA_FIELD_PREFIX","isExtraField","field","name","startsWith","mapExtraFieldToFormField","extraField","fieldType","type","extraFieldType","getFieldTypeInfo","options","config","numberOfRows","rows","_a","length","assign","items","map","val","label","id","custom","hidden","visibleToStorefront","required","isRequired","default","defaultValue","String","maxLength","max","maxValue","throwErrorAction","error","meta","action","__WEBPACK_EXTERNAL_MODULE_rxjs_concat__","__WEBPACK_EXTERNAL_MODULE_rxjs_of__","__WEBPACK_EXTERNAL_MODULE_rxjs_throwError__","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_createErrorAction__","payload","B2BTokenActionType","B2BTokenActionCreator","constructor","_requestSender","this","loadB2BToken","store","state","getState","storeConfig","getStoreConfigOrThrow","storeHash","storeProfile","baseUrl","b2bBaseUrl","clientId","b2bClientId","b2bApiSettings","customerId","customer","getCustomerOrThrow","channelId","checkout","getCheckoutOrThrow","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_createAction__","LoadB2BTokenRequested","__WEBPACK_EXTERNAL_MODULE_rxjs_defer__","__awaiter","body","getB2BToken","LoadB2BTokenSucceeded","token","data","pipe","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_catchError__","LoadB2BTokenFailed","SDK_VERSION_HEADERS","MissingDataErrorType","BillingAddressActionType","B2BTokenRequestSender","appClientId","jwtBody","timeout","params","app_client_id","headers","post","credentials","bcToken","StandardError","Error","message","super","setPrototypeOf","__proto__","captureStackTrace","stack","MissingDataError","subtype","MissingBillingAddress","MissingCart","MissingConsignments","MissingCheckout","MissingCustomer","MissingCheckoutConfig","MissingOrderConfig","MissingOrder","MissingOrderId","MissingPayment","MissingPaymentToken","MissingPaymentMethod","MissingPaymentProviderCustomer","MissingShippingAddress","getErrorMessage","UnableToContinueAsGuestError","ContentType","BillingAddressActionCreator","_subscriptionActionCreator","continueAsGuest","getCheckout","getCustomer","isGuest","billingAddress","getBillingAddress","billingAddressRequestBody","country","existingBillingAddressRequestBody","__rest","hasBillingAddress","__WEBPACK_EXTERNAL_MODULE_lodash_isEmpty__","__WEBPACK_EXTERNAL_MODULE_rxjs_merge__","ContinueAsGuestRequested","billing_address_action_creator_awaiter","_createOrUpdateBillingAddress","ContinueAsGuestSucceeded","ContinueAsGuestFailed","_updateCustomerConsent","updateAddress","address","__WEBPACK_EXTERNAL_MODULE_rxjs_Observable__","create","observer","next","UpdateBillingAddressRequested","email","then","UpdateBillingAddressSucceeded","complete","catch","response","UpdateBillingAddressFailed","acceptsAbandonedCartEmails","acceptsMarketingNewsletter","__WEBPACK_EXTERNAL_MODULE_rxjs_empty__","updateSubscriptions","checkoutId","createAddress","EmptyCartError","content_type","DEFAULT_PARAMS","include","join","BillingAddressRequestSender","url","Accept","JsonV1","err","billing_address_request_sender_rest","put","ProjectionActionType","ErrorActionType","createDataStoreProjection","stateTransformer","projection","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_createDataStore__","Synchronize","subscribe","dispatch","initial","ErrorActionCreator","clearError","ClearError","ExperimentAwareRequestSender","_config","sendRequest","_prefixed","patch","delete","basePath","getBasePath","getFeatures","endsWith","test","getEnvironment","e","ConsoleLogger","_console","log","messages","_logToConsole","info","warn","debug","NoopLogger","logger","isEnabled","console","createLogger","getDefaultLogger","cachableActionDecorator","_","descriptor","memoizedMethods","WeakMap","decorateMethod","method","args","lastArg","useCache","param","instanceMethods","fn","set","__WEBPACK_EXTERNAL_MODULE__bigcommerce_memoize_bf7b411a_memoize__","__WEBPACK_EXTERNAL_MODULE_rxjs_from__","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_shareReplay__","isEqual","__WEBPACK_EXTERNAL_MODULE_lodash_isEqual__","ConfigActionType","ConfigActionCreator","_configRequestSender","loadConfig","LoadConfigRequested","LoadConfigSucceeded","LoadConfigFailed","__decorate","DEFAULT_RESPONSE","status","RequestError","errors","CheckoutNotAvailableError","title","INTERNAL_USE_ONLY","ConfigRequestSender","CouponActionType","CouponActionCreator","_couponRequestSender","applyCoupon","code","ApplyCouponRequested","ApplyCouponSucceeded","ApplyCouponFailed","removeCoupon","RemoveCouponRequested","RemoveCouponSucceeded","RemoveCouponFailed","checkout_default_includes","CheckoutIncludes","GiftCertificateActionType","CartSource","CustomerActionType","joinIncludes","includes","__WEBPACK_EXTERNAL_MODULE_lodash_uniq__","CouponRequestSender","couponCode","AvailableShippingOptions","GiftCertificateActionCreator","_giftCertificateRequestSender","applyGiftCertificate","giftCertificate","ApplyGiftCertificateRequested","ApplyGiftCertificateSucceeded","ApplyGiftCertificateFailed","removeGiftCertificate","RemoveGiftCertificateRequested","RemoveGiftCertificateSucceeded","RemoveGiftCertificateFailed","GiftCertificateRequestSender","giftCertificateCode","isResolvableModule","InvalidArgumentError","Registry","_factories","_instances","_defaultToken","defaultToken","_useFallback","_b","useFallback","_tokenResolver","_c","tokenResolver","cacheToken","_getInstance","getFactory","exactMatch","resolvedToken","keys","register","factory","_hasFactory","_hasInstance","ResolveIdRegistry","_registry","_resolveToken","bind","_encodeToken","resolveId","getUseFallback","btoa","JSON","stringify","_decodeToken","parse","atob","registeredTokens","query","results","forEach","registeredToken","resolverId","result","matches","totalKeys","entries","push","matchedResults","sort","a","b","filter","queryKeyCount","exactResult","find","matched","isSpamProtectionExecuteSucceededAction","succeededAction","CustomerStrategyActionType","CheckoutActionType","CheckoutHydrateActionType","CustomerActionCreator","_customerRequestSender","_checkoutActionCreator","_spamProtectionActionCreator","createCustomer","customerAccount","isStorefrontSpamProtectionEnabled","checkoutSettings","createAccount","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_switchMap__","loadCurrentCheckout","CreateCustomerSucceeded","CreateCustomerRequested","execute","CreateCustomerFailed","customerAddress","CreateCustomerAddressRequested","customer_action_creator_awaiter","CreateCustomerAddressSucceeded","CreateCustomerAddressFailed","signInCustomer","cartId","cart","source","BuyNow","SignInCustomerRequested","persistentCartRetrievalInformation","loadCheckout","SignInCustomerSucceeded","SignInCustomerFailed","signOutCustomer","SignOutCustomerRequested","SignOutCustomerSucceeded","SignOutCustomerFailed","CustomerRequestSender","registerIntegrations","registry","integrations","paymentIntegrationService","resolveIds","CustomerStrategyActionCreator","_strategyRegistry","_strategyRegistryV2","_paymentIntegrationService","signIn","methodId","SignInRequested","_getStrategy","SignInSucceeded","SignInFailed","signOut","SignOutRequested","SignOutSucceeded","SignOutFailed","executePaymentMethodCheckout","ExecutePaymentMethodCheckoutRequested","ExecutePaymentMethodCheckoutSucceeded","ExecutePaymentMethodCheckoutFailed","initialize","customerStrategies","isInitialized","InitializeRequested","InitializeSucceeded","InitializeFailed","deinitialize","DeinitializeRequested","DeinitializeSucceeded","DeinitializeFailed","widgetInteraction","WidgetInteractionStarted","WidgetInteractionFinished","WidgetInteractionFailed","strategy","joinOrMergeIncludes","baseIncludes","includeDictionaryOrList","Array","isArray","includesDictionary","deletions","__WEBPACK_EXTERNAL_MODULE_lodash_keys__","__WEBPACK_EXTERNAL_MODULE_lodash_pickBy__","on","additions","__WEBPACK_EXTERNAL_MODULE_lodash_filter__","__WEBPACK_EXTERNAL_MODULE_lodash_difference__","mergeIncludes","CheckoutRequestSender","updateCheckout","FormFieldsActionType","CheckoutActionCreator","_checkoutRequestSender","_configActionCreator","_formFieldsActionCreator","LoadCheckoutRequested","loadFormFields","LoadCheckoutSucceeded","_transformCustomerAddresses","LoadCheckoutFailed","loadDefaultCheckout","checkout_action_creator_awaiter","context","getContextConfig","UpdateCheckoutRequested","UpdateCheckoutSucceeded","UpdateCheckoutFailed","hydrateInitialState","HydrateInitialState","addresses","shouldSaveAddress","SpamProtectionActionType","FormFieldsActionCreator","_formFieldsRequestSender","LoadFormFieldsRequested","form_fields_action_creator_awaiter","loadFields","LoadFormFieldsSucceeded","LoadFormFieldsFailed","form_fields_action_creator_decorate","FormFieldsRequestSender","SpamProtectionChallengeNotCompletedError","SpamProtectionFailedError","NotInitializedErrorType","ExtensionActionType","ExtensionInternalEventType","SpamProtectionActionCreator","_googleRecaptcha","spam_protection_action_creator_awaiter","spamProtectionElementId","containerId","document","getElementById","reset","spamProtectionElement","createElement","setAttribute","appendChild","recaptchaSitekey","googleRecaptchaSitekey","load","verifyCheckoutSpamProtection","VerifyCheckoutRequested","validate","VerifyCheckoutSucceeded","VerifyCheckoutFailed","ExecuteRequested","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_take__","ExecuteSucceeded","ExecuteFailed","MutationObserverFactory","_window","window","callback","MutationObserver","NotInitializedError","CustomerNotInitialized","PaymentNotInitialized","ShippingNotInitialized","SpamProtectionNotInitialized","not_initialized_error_getErrorMessage","SpamProtectionNotLoadedError","GoogleRecaptcha","googleRecaptchaScriptLoader","mutationObserverFactory","_memoized","recaptcha","sitekey","container","event$","__WEBPACK_EXTERNAL_MODULE_rxjs_Subject__","_widgetId","render","size","getResponse","_event$","_recaptcha","element","remove","querySelector","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_retryWhen__","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_delay__","index","TIMEOUT","_watchRecaptchaChallengeWindow","event","iframeContainer","parentElement","style","visibility","observe","attributes","attributeFilter","GoogleRecaptchaScriptLoader","_scriptLoader","_loadPromise","_loadScript","callbackName","Promise","resolve","reject","grecaptcha","loadScript","createSpamProtection","scriptLoader","SpamProtectionRequestSender","DefaultCustomerStrategy","_store","_customerActionCreator","continueWithCheckoutCallback","parseUrl","anchor","href","port","indexOf","hostname","hash","origin","protocol","pathname","search","ExtensionNotFoundError","isIframeEvent","object","IframeEventPoster","targetOrigin","_targetWindow","_context","_targetOrigin","targetWindow","__WEBPACK_EXTERNAL_MODULE_rxjs_fromEvent__","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_filter__","successType","errorType","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_map__","toPromise","postMessage","setTarget","setContext","createExtensionEventPoster","extension","iframe","contentWindow","CancellablePromise","promise","cancellable","cancel","race","UnexpectedDetachmentError","ExtensionInternalCommandType","DetachmentObserver","_mutationObserver","ensurePresence","targets","mutationsList","mutation","from","removedNodes","node","some","target","contains","childList","subtree","output","disconnect","originalIframeResizer","ExtensionNotLoadedError","ResizableIframeCreator","_options","createFrame","src","initCallback","failedCallback","border","display","width","_toResizableFrame","removeChild","timeoutInterval","detachmentObserver","setTimeout","handleMessage","ResizeIframe","iframes","autoResize","scrolling","sizeWidth","heightCalculationMethod","teardown","removeEventListener","clearTimeout","addEventListener","ExtensionIframe","_containerId","_extension","parentOrigin","_url","URL","searchParams","attach","iframeCreator","iframeResizerCallback","_iframe","toString","ExtensionReady","ExtensionFailed","detach","ExtensionActionCreator","loadExtensions","LoadExtensionsRequested","extensions","LoadExtensionsSucceeded","LoadExtensionsFailed","renderExtension","region","workerExtensionMessenger","extension_action_creator_awaiter","getCartOrThrow","links","checkoutLink","getExtensionByRegion","RenderExtensionRequested","worker","Worker","blob","createObjectURL","Blob","createExtensionWebWorker","add","RenderExtensionSucceeded","RenderExtensionFailed","ExtensionRequestSender","bind_decorator","bindMethodDecorator","decoratedTarget","getOwnPropertyNames","getOwnPropertyDescriptor","bindClassDecorator","boundMethod","ExtensionCommandType","ExtensionQueryType","WorkerEventListener","_worker","_isListening","_listeners","listen","_handleMessage","stopListen","addListener","listener","listeners","removeListener","splice","trigger","messageEvent","worker_event_listener_rest","worker_event_listener_decorate","WorkerEventPoster","UnsupportedExtensionCommandError","UnsupportedExtensionQueryError","WorkerExtensionMessenger","_workers","_commandListeners","_queryListeners","extensionId","listenForCommand","command","commandHandler","_getWorkerById","validCommandType","_validateCommand","commandHandlerProxy","listenForQuery","queryHandler","validQueryType","_validateQuery","queryHandlerProxy","clearCacheById","values","appendWww","replace","ExtensionEventType","IframeEventListener","sourceOrigin","_sourceOrigins","iframe_event_listener_rest","iframe_event_listener_decorate","ExtensionMessenger","_workerExtensionMessenger","_posters","clearCacheByRegion","_getExtensionByRegion","_getExtensionById","_getExtensions","_extensions","getExtensions","ExtensionEventBroadcaster","_extensionMessenger","_subscribers","_subscribed","_unsubscribers","eventListener","Subscribe","_handleSubscribe","Unsubscribe","_handleUnsubscribe","broadcast","eventType","subscribeConsignmentsChange","broadcaster","getConsignments","getInitialConsignments","consignments","currentConsignments","ConsignmentsChanged","previousConsignments","standard_error_StandardError","missing_data_error_MissingDataErrorType","not_initialized_error_NotInitializedErrorType","missing_data_error_MissingDataError","missing_data_error_getErrorMessage","getShippableItemsCount","lineItems","physicalItems","item","addedByPromotion","__WEBPACK_EXTERNAL_MODULE_lodash_reduce__","total","quantity","guard","errorFactory","not_initialized_error_NotInitializedError","errors_not_initialized_error_getErrorMessage","amazonPayV2Regions","de","jp","uk","us","AmazonPayV2CheckoutLanguage","AmazonPayV2Placement","AmazonPayV2LedgerCurrency","AmazonPayV2PayOptions","AmazonPayV2ButtonColor","AmazonPayV2ButtonDesign","AmazonPayV2PaymentProcessor","amazonPayV2ScriptLoader","paymentMethod","amazonPayV2SDK","buttonParentContainer","createAmazonPayButtonParentContainer","amazonPayV2Button","bindButton","buttonId","sessionId","changeAction","getAmazonPayV2SDK","Pay","bindChangeAction","amazonCheckoutSessionId","createButton","renderButton","prepareCheckout","createCheckoutSessionConfig","requestConfig","prepareRequestConfig","getAmazonPayV2Button","onClick","initCheckout","prepareCheckoutWithCreationRequestConfig","createCheckoutConfig","amazon_pay_v2_payment_processor_awaiter","estimatedOrderAmount","productType","signout","renderAmazonPayButton","buttonColor","checkoutState","decoupleCheckoutInitiation","placement","isButtonMicroTextDisabled","parentContainerId","getButtonParentContainer","design","C0001","amazonPayV2ButtonOptions","getAmazonPayV2ButtonOptions","updateBuyNowFlowFlag","isBuyNowFlow","Boolean","isPh4Enabled","features","storeCountryCode","isPh4UsOnly","publicKeyId","signedPayload","amazon_pay_v2_payment_processor_rest","isEnvironmentSpecific","uid","Math","random","substr","parentContainer","Gold","getCart","getPaymentMethodOrThrow","getCheckoutState","merchantId","testMode","initializationData","checkoutLanguage","checkoutSessionMethod","extractAmazonCheckoutSessionId","ledgerCurrency","buttonBaseConfig","sandbox","PayOnly","PayAndShip","shopPath","amount","outstandingBalance","currencyCode","currency","buttonOptions","tmpConfig","createCheckoutSession","getOrThrow","checkoutSelectors","paymentMethods","PaymentMethodClientUnavailableError","AmazonPayV2ScriptLoader","windowWithAmazonPay","amazonPayV2Region","amazon","createAmazonPayV2PaymentProcessor","__WEBPACK_EXTERNAL_MODULE__bigcommerce_script_loader_875b3e8f_getScriptLoader__","toResolvableModule","invalid_argument_error_InvalidArgumentError","NotImplementedError","AmazonPayV2CustomerStrategy","amazonPayV2PaymentProcessor","amazonpay","_e","loadPaymentMethod","Checkout","payment","getPaymentId","remoteCheckoutSignOut","providerId","create_amazon_pay_v2_customer_strategy","isExperimentEnabled","experimentName","fallbackValue","BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION","BRAINTREE_SDK_DEFAULT_VERSION","BRAINTREE_SDK_STABLE_VERSION","BraintreeSDKVersionManager","braintreeWindow","getSDKVersion","getStoreConfig","getPreloadedSDKVersion","braintree","preloadedVersion","__WEBPACK_EXTERNAL_MODULE_lodash_find__","VERSION","UnsupportedBrowserError","TotalPriceStatusType","BraintreeOrderStatus","NonInstantLocalPaymentMethods","BraintreeFastlaneAuthenticationState","BraintreeErrorType","BraintreeErrorCode","BraintreeSupportedCardBrands","isBraintreeError","BraintreeEnv","BraintreeModuleName","BraintreeFormFieldType","BraintreeSdk","braintreeScriptLoader","clientToken","setClientToken","teardownModule","dataCollector","getClient","client","getClientTokenOrThrow","clientCreator","loadClient","authorization","getDataCollectorOrThrow","emptyDataCollector","deviceData","loadDataCollector","dataCollectorConfig","kount","KountNotEnabled","getBraintreeGooglePayment","googlePayment","braintreeGooglePayment","all","loadGooglePayment","getBraintreeThreeDS","threeDS","threeDSecure","load3DS","version","getBraintreeLocalPayment","merchantAccountId","braintreeLocalPayment","localPaymentCreator","loadLocalPayment","getUsBankAccount","usBankAccount","loadUsBankAccount","getBraintreeVisaCheckout","visaCheckout","loadVisaCheckout","paypal","getVisaCheckoutSdk","visaCheckoutSDK","loadVisaCheckoutSdk","getVenmoCheckoutOrThrow","braintreeVenmo","venmoCheckout","loadVenmoCheckout","venmoCheckoutConfig","allowDesktop","paymentMethodUsage","braintreeVenmoCheckout","isBrowserSupported","BRAINTREE_SDK_SCRIPTS_INTEGRITY","Client","PaypalCheckout","Paypal","LocalPayment","DataCollector","UsBankAccount","GooglePayment","ThreeDSecure","VisaCheckout","Venmo","HostedFields","Fastlane","ApplePayGatewayType","BraintreeScriptLoader","braintreeHostWindow","braintreeSDKVersionManager","loadBraintreeModuleOrThrow","loadFastlane","loadPaypalCheckout","loadPaypal","loadHostedFields","V","async","integrity","crossorigin","braintreeModuleName","fileName","getBraintreeModule","braintreeSdkVersion","scriptPath","getIntegrityValuesByModuleName","moduleName","PaymentMethodCancelledError","DefaultLabels","ApplePayCustomerStrategy","_sessionFactory","_braintreeSdk","_applePayScriptLoader","_onAuthorizeCallback","__WEBPACK_EXTERNAL_MODULE_lodash_noop__","_onError","_onClick","_subTotalLabel","Subtotal","_shippingLabel","Shipping","_hasApplePaySession","applepay","shippingLabel","subtotalLabel","onError","onPaymentAuthorize","loadSdk","_paymentMethod","_applePayButton","_createButton","_handleWalletButtonClick","gateway","BRAINTREE","applePayButton","_createApplePayButtonElement","preventDefault","request","_getBaseRequest","applePaySession","_handleApplePayEvents","begin","storeName","decimalPlaces","merchantCapabilities","supportedNetworks","requiresShipping","requiredBillingContactFields","requiredShippingContactFields","countryCode","grandTotal","toFixed","subtotal","taxes","tax","onvalidatemerchant","apple_pay_customer_strategy_awaiter","merchantSession","_onValidateMerchant","completeMerchantValidation","onshippingcontactselected","_handleShippingContactSelected","onshippingmethodselected","_handleShippingMethodSelected","oncancel","onpaymentauthorized","_onPaymentAuthorized","shippingAddress","_transformContactToAddress","shippingContact","updateShippingAddress","abort","selectionShippingOptionId","selectedShippingOption","availableOptions","availableShippingOptions","selectedOption","unselectedOptions","option","shippingOptions","description","cost","detail","additionalDescription","identifier","isRecommended","completeShippingContactSelection","ApplePaySession","STATUS_INVALID_SHIPPING_POSTAL_ADDRESS","recommendedOption","optionId","selectedOptionId","_updateShippingOption","newShippingMethods","newTotal","newLineItems","_getUpdatedLineItems","shippingMethod","completeShippingMethodSelection","shippingCostTotal","selectShippingOption","paymentData","validationURL","location","paymentsUrl","billingContact","deviceSessionId","_getBraintreeDeviceData","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","assertApplePayWindow","isApplePayWindow","ApplePaySessionFactory","ApplePayScriptLoader","sdkVersion","isApplePaySdkWindow","create_apple_pay_customer_strategy","getHost","__WEBPACK_EXTERNAL_MODULE__bigcommerce_request_sender_01d1f546_createRequestSender__","host","__WEBPACK_EXTERNAL_MODULE__bigcommerce_script_loader_875b3e8f_ScriptLoader__","BuyNowCartCreationError","request_error_DEFAULT_RESPONSE","request_error_RequestError","LiabilityShiftEnum","BigCommercePaymentsIntent","StyleButtonLabel","StyleButtonColor","StyleButtonShape","NonInstantAlternativePaymentMethods","PayPalOrderStatus","BigCommercePaymentsIntegrationService","formPoster","bigCommercePaymentsRequestSender","bigCommercePaymentsScriptLoader","loadPayPalSdk","providedCurrencyCode","initializesOnCheckoutPage","forceLoad","paypalSdk","getPayPalSDK","getPayPalSdkOrThrow","createBuyNowCartOrThrow","buyNowInitializeOptions","cartRequestBody","getBuyNowCartRequestBody","createBuyNowCart","createOrder","requestBody","orderId","createOrderCardFields","setupToken","updateOrder","consignment","getConsignmentsOrThrow","_error","getOrderStatus","tokenizePayment","postForm","payment_type","provider","order_id","cart_id","gatewayId","vault_payment_instrument","set_as_default_stored_instrument","device_info","method_id","paypal_account","getShippingOptionOrThrow","selectedShippingOptionId","recommendedShippingOption","shippingOptionToSelect","getAddress","getBillingAddressFromOrderDetails","payer","given_name","surname","email_address","address_line_1","address_line_2","admin_area_2","country_code","postal_code","admin_area_1","phone_number","national_number","getShippingAddressFromOrderDetails","orderDetails","purchase_units","full_name","shipping","split","getValidButtonStyle","color","height","shape","validStyles","getValidHeight","__WEBPACK_EXTERNAL_MODULE_lodash_omitBy__","__WEBPACK_EXTERNAL_MODULE_lodash_isNil__","removeElement","elementId","internal_api_headers_INTERNAL_USE_ONLY","content_type_ContentType","http_request_content_type","sdk_version_headers_SDK_VERSION_HEADERS","BigCommercePaymentsRequestSender","requestSender","Json","BigCommercePaymentsScriptLoader","paypalSdkScriptConfig","getPayPalSdkScriptConfigOrThrow","loadPayPalSDK","bigCommercePaymentsPayPalSDK","transformConfig","scriptSrc","URLSearchParams","intent","buyerCountry","attributionId","isVenmoEnabled","isHostedCheckoutEnabled","isPayPalCreditAvailable","isDeveloperModeApplicable","availableAlternativePaymentMethods","enabledAlternativePaymentMethods","isGooglePayEnabled","commit","shouldEnableCard","enableCardFunding","disableCardFunding","enableCreditFunding","disableCreditFunding","enableVenmoFunding","disableVenmoFunding","disableAPMsFunding","apm","googlePayComponent","cardFieldsComponent","disableFunding","filterFundingOptions","enableFunding","components","fundingOptions","fundingTypesToBeFiltered","fundingOption","transformedConfig","create_bigcommerce_payments_integration_service","__WEBPACK_EXTERNAL_MODULE__bigcommerce_form_poster_1cd9ef62_createFormPoster__","default_checkout_button_height","BigCommercePaymentsCustomerStrategy","bigCommercePaymentsIntegrationService","bigcommerce_payments","getPaymentMethod","Buttons","onComplete","paymentButtonStyles","isAppSwitchEnabled","checkoutTopButtonStyles","defaultCallbacks","appSwitchWhenAvailable","onApprove","orderID","hostedCheckoutCallbacks","onShippingAddressChange","onShippingOptionsChange","actions","onHostedCheckoutApprove","buttonRenderOptions","fundingSource","FUNDING","PAYPAL","paypalButton","isEligible","hasReturned","resume","order","handleError","shippingOption","create_bigcommerce_payments_customer_strategy","UntrustedShippingCardVerificationType","bigcommerce_payments_types_BigCommercePaymentsIntent","bigcommerce_payments_types_LiabilityShiftEnum","TDSecureVerificationMethod","TDSecureAuthenticationState","bigcommerce_payments_types_StyleButtonLabel","bigcommerce_payments_types_StyleButtonColor","bigcommerce_payments_types_StyleButtonShape","PayPalFastlaneAuthenticationState","PayPalSdkHelper","getPayPalFastlaneSdk","bigCommercePaymentsFastlaneSdk","getPayPalFastlaneSdkConfiguration","getPayPalGooglePaySdk","bigCommercePaymentsGooglePay","getPayPalGooglePaySdkScriptConfigOrThrow","getPayPalApmsSdk","bigCommercePaymentsApms","getPayPalApmSdkConfiguration","getPayPalMessages","bigCommercePaymentsMessages","paypalSdkMessagesConfig","getPayPalSdkMessagesConfiguration","scriptOptions","scriptAttributes","enableAPMsFunding","createBigCommercePaymentsSdk","__WEBPACK_EXTERNAL_MODULE__bigcommerce_script_loader_875b3e8f_createScriptLoader__","CookieStorage","cookieKey","encodeURIComponent","cookie","firstIndex","lastIndex","decodeURIComponent","substring","secure","cookieText","expires","path","domain","toUTCString","now","Date","minutes","setTime","getTime","BigCommercePaymentsFastlaneUtils","initializePayPalFastlane","paypalFastlaneSdk","isTestModeEnabled","styles","localStorage","setItem","bigCommercePaymentsFastlane","defaultStyles","root","backgroundColorPrimary","getPayPalFastlaneOrThrow","lookupCustomerOrThrow","identity","lookupCustomerByEmail","triggerAuthenticationFlowOrThrow","customerContextId","triggerAuthenticationFlow","updateStorageSessionId","setDate","getDate","cookiesOption","removeStorageSessionId","getStorageSessionId","mapPayPalFastlaneProfileToBcCustomerData","authenticationResult","authenticationState","profileData","paypalBillingAddress","card","paymentSource","paypalShippingAddress","paypalProfileName","paypalInstrument","mapPayPalToBcAddress","instruments","mapPayPalToBcInstrument","filterAddresses","UNRECOGNIZED","instrument","brand","expiry","lastDigits","expiryYear","expiryMonth","bigpayToken","defaultInstrument","iin","last4","trustedShippingAddress","untrustedShippingCardVerificationMode","PAN","mapBcToPayPalAddress","addressLine1","addressLine2","adminArea1","adminArea2","profileName","fullName","phoneData","nationalNumber","reduce","customerAddresses","currentAddress","isEqualAddresses","firstAddress","secondAddress","normalizeAddress","__WEBPACK_EXTERNAL_MODULE_lodash_omit__","createBigCommercePaymentsFastlaneUtils","isInvalidStyleOption","styleOption","getFastlaneStyles","styleSettings","uiStyles","fastlaneStyles","input","toggle","textBody","text","textCaption","caption","branding","cleanUpFastlaneStyles","fastlaneRootSettingsBackgroundColor","errorColor","fastlaneRootSettingsErrorColor","fontFamily","fastlaneRootSettingsFontFamily","fontSizeBase","fastlaneRootSettingsFontSize","_d","padding","fastlaneRootSettingsPadding","primaryColor","fastlaneRootSettingsPrimaryColor","_f","borderRadius","fastlaneInputSettingsBorderRadius","_g","borderColor","fastlaneInputSettingsBorderColor","_h","focusBorderColor","fastlaneInputSettingsFocusBorderBase","_j","backgroundColor","fastlaneInputSettingsBackgroundColor","_k","borderWidth","fastlaneInputSettingsBorderWidth","_l","textColorBase","fastlaneInputSettingsTextColorBase","_m","colorPrimary","fastlaneToggleSettingsColorPrimary","_o","colorSecondary","fastlaneToggleSettingsColorSecondary","_p","fastlaneTextBodySettingsColor","_r","_q","fontSize","fastlaneTextBodySettingsFontSize","_t","_s","fastlaneTextCaptionSettingsColor","_v","_u","fastlaneTextCaptionSettingsFontSize","_x","_w","fastlaneBrandingSettings","mergeFastlaneStyles","BigCommercePaymentsFastlaneCustomerStrategy","bigCommercePaymentsSdk","bigCommercePaymentsFastlaneUtils","bigcommerce_payments_fastlane","updatePaymentProviderCustomer","checkoutPaymentMethodExecuted","runPayPalAuthenticationFlowOrThrow","customerEmail","isAuthenticationFlowCanceled","CANCELED","updateCustomerDataState","updatedState","isFastlaneShippingOptionAutoSelectEnabled","firstShippingOption","shippingOptionId","isFastlaneStylingEnabled","create_bigcommerce_payments_fastlane_customer_strategy","BigCommercePaymentsPayLaterCustomerStrategy","bigcommerce_payments_paylater","bigCommercePaymentsPayLater","fundingSources","PAYLATER","CREDIT","hasRenderedSmartButton","create_bigcommerce_payments_paylater_customer_strategy","BigCommercePaymentsVenmoCustomerStrategy","bigcommerce_payments_venmo","VENMO","paypalButtonRender","create_bigcommerce_payments_venmo_customer_strategy","PaymentMethodFailedError","PaymentMethodInvalidError","BoltDeveloperMode","StyleButtonSize","bolt_StyleButtonShape","BoltCustomerStrategy","boltScriptLoader","boltHostWindow","bolt","onInit","publishableKey","developerConfig","loadBoltClient","getCustomerEmail","hasBoltAccount","__WEBPACK_EXTERNAL_MODULE_rxjs_noop__","openBoltCheckoutModalOrThrow","boltClient","getBoltClientOrThrow","embeddedOneClickEnabled","callbacks","close","openCheckout","isCustomError","BoltCheckout","BoltScriptLoader","developerModeParams","storefrontApiToken","getDomainURL","getScriptOptions","loadBoltEmbedded","Bolt","developerMode","StagingMode","DevelopmentMode","developerDomain","create_bolt_customer_strategy","PaymentArgumentInvalidError","invalidFields","PaymentInvalidFormError","details","paypalSdkPromise","PAYPAL_COMPONENTS","PaypalButtonStyleLayoutOption","PaypalButtonStyleSizeOption","PaypalButtonStyleColorOption","PaypalButtonStyleLabelOption","PaypalButtonStyleShapeOption","MessagingPlacements","BraintreeIntegrationService","overlay","dataCollectors","threeDSecureOptions","getBraintreeFastlane","cardId","braintreeFastlane","getSessionId","braintreeFastlaneCreator","getPaypal","braintreePaypal","shouldSaveInstrument","braintree_integration_service_rest","newWindowFlow","__WEBPACK_EXTERNAL_MODULE__braintree_browser_detection_e7ac357c_supportsPopups__","show","focusWindow","tokenize","enableShippingAddress","flow","useraction","getPaypalCheckout","onSuccess","paypalCheckout","paypalCheckoutConfig","braintreePaypalCheckout","paypalSdkLoadConfig","isCreditEnabled","loadPayPalSDKOnce","getDataCollector","cacheKey","cached","getBraintreeEnv","isTestMode","Sandbox","Production","mapToBraintreeShippingAddressOverride","recipientName","line1","line2","mapToLegacyShippingAddress","first_name","last_name","mapToLegacyBillingAddress","riskCorrelationId","get3DS","getVenmoCheckout","venmoConfig","verifyCard","tokenizationPayload","tokenizeCard","challenge3DSVerification","creditCardInstrument","ccExpiry","ccNumber","ccName","isCreditCardInstrumentLike","getErrorsRequiredFields","requestData","mapToCreditCard","creditCards","nonce","bin","present3DSChallenge","creditCard","cardholderName","number","cvv","ccCvv","expirationDate","month","year","countryCodeAlpha2","countryName","streetAddress","endpoint","addFrame","removeFrame","challengeRequested","additionalInformation","cancelVerifyCard","braintree_integration_service_awaiter","verification","roundedAmount","Number","onLookupComplete","_data","collectDeviceData","BraintreePaypalCustomerStrategy","braintreeIntegrationService","braintreepaypal","paypalCheckoutOptions","renderPayPalButton","buttonStyles","env","setupPayment","authorizeData","shippingAddressOverride","createPayment","shippingAddressEditable","offerCredit","tokenizePayload","device_data","billing_address","shipping_address","buttonContainerId","onErrorCallback","create_braintree_paypal_customer_strategy","BraintreePaypalCreditCustomerStrategy","braintreepaypalcredit","create_braintree_paypal_credit_customer_strategy","get_fastlane_styles_isInvalidStyleOption","get_fastlane_styles_getFastlaneStyles","get_fastlane_styles_cleanUpFastlaneStyles","get_fastlane_styles_mergeFastlaneStyles","BraintreeFastlaneCustomerStrategy","braintreeFastlaneUtils","isAcceleratedCheckoutEnabled","braintreefastlane","getValidPaymentMethodOrThrow","paypalFastlaneStylesSettings","initializeBraintreeFastlaneOrThrow","shouldRunAuthenticationFlow","primaryMethodId","shouldRunAcceleratedCheckout","validPaymentMethodId","BraintreeFastlaneUtils","getDeviceSessionId","getBraintreeFastlaneOrThrow","getBraintreeFastlaneComponentOrThrow","FastlaneCardComponent","shouldSetShippingOption","getMethodIdOrThrow","saveSessionIdToCookies","removeSessionIdFromCookies","shippingAddresses","getPayPalBillingAddresses","billingAddresses","mergeShippingAndBillingAddresses","digitalItems","digitalItemBilling","setShippingOption","getSessionIdFromCookies","binDetails","phones","countries","getCountries","getCountryNameByCountryCode","matchedCountry","extendedAddress","filteredBillingAddresses","create_braintree_fastlane_customer_strategy","BraintreeVisaCheckoutCustomerStrategy","braintreeSdk","buttonClassName","braintreevisacheckout","visaCheckoutOptions","braintreeVisaCheckout","visaCheckoutInstance","initOptions","createInitOptions","paymentRequest","settings","locale","storeLanguage","collectShipping","signInButton","createSignInButton","init","paymentSuccessPayload","getShippingAddress","billing","mapToVisaCheckoutAddress","userData","cardInformation","userEmail","card_information","cardType","lastTwo","buttonClass","insertVisaCheckoutButton","visaCheckoutButton","flexDirection","className","innerHTML","create_braintree_visa_checkout_customer_strategy","hostWindow","CurrencyFormatter","currencySettings","symbolLocation","symbol","thousandsSeparator","decimalSeparator","_decimalPlaces","parseInt","_symbolLocation","_symbol","_thousandsSeparator","_decimalSeparator","format","formattedNumber","_formatNumber","formattedCurrency","_formatCurrency","positiveAmount","abs","integerAmount","decimalAmount","_toFixed","parsedIntegerAmount","toLowerCase","precision","round","CurrencyService","_storeConfig","_customerFormatter","shopperCurrency","_storeFormatter","toCustomerCurrency","exchangeRate","toStoreCurrency","currency_service_decorate","items_require_shipping","lineItem","isShippingRequired","customItems","isWebView","isReactNativeWindow","userAgent","navigator","vendor","isOperaWindow","opera","isAndroidWebView","isIOSWebView","PayPalCommerceIntent","types_StyleButtonLabel","types_StyleButtonColor","types_StyleButtonShape","types_TotalPriceStatusType","GooglePayCardNetwork","CallbackIntentsType","ErrorReasonType","CallbackTriggerType","isGooglePayCardNetworkKey","GooglePayKey","GooglePayGateway","_gatewayIdentifier","_isBuyNowFlow","_shouldRequestShipping","_isWebViewExperimentOn","mapToShippingAddressRequestBody","_mapToAddressRequestBody","mapToBillingAddressRequestBody","paymentMethodData","mapToExternalCheckoutData","tokenizationData","cardNetwork","cardDetails","getRequiredData","emailRequired","_isShippingAddressRequired","loadShippingCountries","allowedCountryCodes","getShippingCountries","shippingAddressRequired","shippingAddressParameters","phoneNumberRequired","shippingOptionRequired","getCallbackIntents","OFFER","SHIPPING_ADDRESS","SHIPPING_OPTION","getCallbackTriggers","availableTriggers","INITIALIZE","initializationTrigger","addressChangeTriggers","shippingOptionsChangeTriggers","offerChangeTriggers","getNonce","extraPaymentData","getMerchantInfo","googleMerchantName","merchantName","googleMerchantId","platformToken","authJwt","getGooglePayInitializationData","getTransactionInfo","_getCurrencyCodeOrThrow","storeCountry","isWebViewWithRestrictions","totalPrice","getTotalPrice","totalPriceStatus","ESTIMATED","setIsWebViewExperimentOn","isWebViewExperimentOn","getPaymentGatewayParameters","gatewayMerchantId","getCardParameters","allowedAuthMethods","allowedCardNetworks","supportedCards","billingAddressRequired","billingAddressParameters","_getPaymentMethodFn","_currencyCode","handleShippingAddressChange","mappedShippingAddress","_currencyService","currency_service","_getGooglePayShippingOption","handleShippingOptionChange","defaultSelectedOptionId","maxDecimalPlaces","min","__WEBPACK_EXTERNAL_MODULE_lodash_round__","handleCoupons","offerData","redemptionCodes","newCouponsState","offers","appliedCoupons","getAppliedCoupons","google_pay_gateway_awaiter","redemptionCode","appliedCouponError","coupon","newOfferInfo","coupons","displayName","reason","OFFER_INVALID","setShouldRequestShipping","getGatewayIdentifier","setGatewayIdentifier","shippingContextRequiresCheck","address3","_getFirstAndLastName","trim","nameParts","slice","isGooglePayErrorObject","isGooglePayKey","GooglePayCustomerStrategy","_googlePayPaymentProcessor","_methodId","googlePayOptions","_getMethodId","_getGooglePayClientOptions","_addPaymentButton","_paymentButton","paymentDataCallbacks","onPaymentDataChanged","callbackTrigger","shippingOptionData","google_pay_customer_strategy_awaiter","couponsError","newTransactionInfo","FINAL","newShippingOptionParameters","buttonType","addPaymentButton","_handleClick","initializeWidget","_interactWithPaymentSheet","statusCode","showPaymentSheet","siteLink","setExternalCheckoutForm","GooglePayPaymentProcessor","_gateway","_formPoster","_baseRequest","apiVersion","apiVersionMinor","googlePayPaymentOptions","_paymentsClient","getGooglePaymentsClient","_buildButtonPayloads","_buildWidgetPayloads","_determineReadinessToPay","_prefetchGooglePaymentData","paymentButton","_getPaymentsClient","allowedPaymentMethods","_getBaseCardPaymentMethod","paymentDataRequest","_getPaymentDataRequest","loadPaymentData","setExternalCheckoutXhr","_setExternalCheckout","processAdditionalAction","useFormPoster","transactionInfo","prefetchPaymentData","isReadyToPay","_getIsReadyToPayRequest","_baseCardPaymentMethod","parameters","baseCardPaymentMethod","_cardPaymentMethod","tokenizationSpecification","isWebViewLogic","callbackIntents","offerInfo","_paymentDataRequest","merchantInfo","_isReadyToPayRequest","_getOrThrow","GooglePayScriptLoader","google","payments","api","PaymentsClient","environment","createGooglePayScriptLoader","create_google_pay_adyenv2_customer_strategy","create_google_pay_adyenv3_customer_strategy","GooglePayAuthorizeNetGateway","service","_super","isGooglePayAuthorizeNetInitializationData","assertsIsGooglePayAuthorizeNetInitializationData","paymentGatewayId","create_google_pay_authorizenet_customer_strategy","is_request_error","assertIsGooglePayCheckoutComInitializationData","isGooglePayCheckoutComInitializationData","GooglePayCheckoutComGateway","_resolve","threeDSBody","three_ds_result","acs_url","isGooglePayThreeDSecureResult","isGooglePayTokenObject","assertIsGooglePayTokenObject","_tokenize","checkoutcomkey","token_data","Authorization","create_google_pay_checkoutcom_customer_strategy","GooglePayCybersourceGateway","create_google_pay_cybersource_customer_strategy","create_google_pay_bnz_customer_strategy","GooglePayOrbitalGateway","create_google_pay_orbital_customer_strategy","StripeFormMode","StripeDisplayName","StripeCheckoutSessionStatusType","StripeCheckoutSessionPaymentStatus","StripeLoadActionsResultType","StripePaymentMethodType","StripeStringConstants","StripeJsVersion","StripeElementType","StripePaymentIntentStatus","StripeElementEvent","StripeInstrumentSetupFutureUsage","StripeScriptLoader","stripeWindow","getStripeClient","stripeJsVersion","betas","bcStripeClient","stripe","stripePublishableKey","stripeConnectedAccount","stripeClient","stripeAccount","getElements","stripeElements","bcStripeElements","updateStripeElements","elements","update","fetchUpdates","getStripeCheckout","stripeCheckout","getStoredStripeCheckout","bcStripeCheckout","Stripe","getScriptUrl","V3","loadActions","logErrorToConsole","stripeCheckoutSession","getSession","stripeSessionIdFromOptions","clientSecret","STRIPE_UPE_CLIENT_BETAS","STRIPE_UPE_CLIENT_API_VERSION","assertsIsGooglePayStripeInitializationData","isGooglePayStripeInitializationData","GooglePayStripeGateway","isGooglePayStripeTokenObject","assertIsGooglePayStripeTokenObject","stripeVersion","__WEBPACK_EXTERNAL_MODULE_lodash_some__","initialization","stripeUPEClient","loadStripeJs","catchedConfirmError","confirmCardPayment","retrievePaymentIntent","__","_throwDisplayableStripeError","_isCancellationError","paymentIntent","getCartLocale","useNewStripeJsVersion","CLOVER","stripeError","payment_intent","last_payment_error","__WEBPACK_EXTERNAL_MODULE_lodash_includes__","create_google_pay_stripe_customer_strategy","create_google_pay_stripeupe_customer_strategy","GooglePayWorldpayAccessGateway","create_google_pay_worldpayaccess_customer_strategy","GooglePayBraintreeGateway","_service","_braintreeGooglePayment","isThreeDSecureEnabled","isNetworkTokenized","orderAmount","getOrderOrThrow","_braintreePresent3DSChallenge","isGooglePayBraintreeTokenObject","assertIsGooglePayBraintreeTokenObject","androidPayCards","createPaymentDataRequest","cardRequirements","billingAddressFormat","paymentMethodTokenizationParameters","create_google_pay_braintree_customer_strategy","LOADING_INDICATOR_STYLES","PAYPAL_SDK_SUPPORTED_LOCALES","transformLocaleToPayPalFormat","language","toUpperCase","PayPalCommerceSdk","paypalGooglePay","paypalApms","paypalMessages","assertsIsGooglePayPayPalCommercePaymentMethod","isGooglePayPaypalCommercePaymentMethod","GooglePayPaypalCommerceGateway","payPalCommerceSdk","googlePaySdk","getLocale","googlepayConfig","Googlepay","create_google_pay_paypal_commerce_customer_strategy","GooglePayBigCommercePaymentsGateway","payPalSdkHelper","create_google_pay_bigcommerce_payments_customer_strategy","getBrowserInfo","userLanguage","color_depth","screen","colorDepth","java_enabled","javaEnabled","screen_height","screen_width","time_zone_offset","getTimezoneOffset","GooglePayTdOnlineMartGateway","browser_info","errorBody","__WEBPACK_EXTERNAL_MODULE_lodash_isObject__","__WEBPACK_EXTERNAL_MODULE_lodash_isArray__","isTdOnlineMartAdditionalAction","threeDSResult","formUrl","payer_auth_request","threeDSSessionData","merchant_data","creq","create_google_pay_tdonlinemart_customer_strategy","PayPalIntent","paypal_types_TDSecureVerificationMethod","paypal_types_TDSecureAuthenticationState","paypal_types_LiabilityShiftEnum","paypal_types_StyleButtonLabel","paypal_types_StyleButtonColor","paypal_types_StyleButtonShape","paypal_types_PayPalFastlaneAuthenticationState","paypal_types_NonInstantAlternativePaymentMethods","paypal_types_PayPalOrderStatus","PayPalSdkScriptLoader","createPayPalSdkScriptLoader","PayPalIntegrationService","paypalRequestSender","paypalSdkLoader","PayPalRequestSender","create_paypal_integration_service","paypal_button_creation_service","paypalIntegrationService","createPayPalButton","onCancel","onPaymentComplete","paypal_button_creation_service_awaiter","buyNowCart","PayPalCommerceCustomerStrategy","paypalButtonCreationService","paypalcommerce","create_paypal_commerce_customer_strategy","paypal_commerce_types_LiabilityShiftEnum","paypal_commerce_types_PayPalCommerceIntent","paypal_commerce_types_StyleButtonLabel","paypal_commerce_types_StyleButtonColor","paypal_commerce_types_StyleButtonShape","paypal_commerce_types_NonInstantAlternativePaymentMethods","paypal_commerce_types_PayPalOrderStatus","PayPalCommerceIntegrationService","paypalCommerceRequestSender","paypalCommerceScriptLoader","PayPalCommerceRequestSender","PayPalCommerceScriptLoader","create_paypal_commerce_integration_service","PayPalCommerceCreditCustomerStrategy","paypalCommerceIntegrationService","paypalcommercecredit","paypalCommerceCredit","create_paypal_commerce_credit_customer_strategy","PayPalCommerceVenmoCustomerStrategy","paypalcommercevenmo","create_paypal_commerce_venmo_customer_strategy","PaypalFastlaneUtils","paypalFastlane","createPaypalFastlaneUtils","utils_get_fastlane_styles_isInvalidStyleOption","utils_get_fastlane_styles_getFastlaneStyles","utils_get_fastlane_styles_cleanUpFastlaneStyles","utils_get_fastlane_styles_mergeFastlaneStyles","PayPalCommerceFastlaneCustomerStrategy","paypalSdkScriptLoader","paypalFastlaneUtils","paypalcommercefastlane","create_paypal_commerce_fastlane_customer_strategy","isStripePaymentMethodLike","shopperLanguage","isStripeAcceleratedCheckoutCustomer","StripeUPECustomerStrategy","stripeupe","onEmailChange","getStyles","isLoading","paymentProviderCustomer","getPaymentProviderCustomerOrThrow","stripeLinkAuthenticationState","appearance","variables","fieldInnerShadow","colorBackground","fieldBackground","colorText","labelText","colorDanger","fieldErrorText","colorTextSecondary","colorTextPlaceholder","fieldPlaceholderText","rules","fieldBorder","fieldText","boxShadow","_stripeElements","billingEmail","defaultValues","mode","SHIPPING","linkAuthenticationElement","getElement","AUTHENTICATION","CHANGE","authenticated","deleteConsignment","mount","unmount","create_stripe_upe_customer_strategy","StripeIntegrationService","isMounted","checkoutEventsUnsubscribe","initCheckoutEventsSubscription","stripeInitializationOptions","stripe_integration_service_awaiter","paymentElement","PAYMENT","updateStripePaymentIntent","mountElement","stripeElement","mapAppearanceVariables","colorIcon","mapInputAppearanceRules","throwStripeError","throwDisplayableStripeError","isCancellationError","errorMessage","throwPaymentConfirmationProceedMessage","isPaymentCompleted","SUCCEEDED","mapStripePaymentData","returnUrl","shouldAllowRedisplay","mapStripeAddress","redirect","IF_REQUIRED","confirmParams","payment_method_data","allow_redisplay","billing_details","getShopperFullName","return_url","isAdditionalActionError","isRedirectAction","additionalAction","redirect_url","isOnPageAdditionalAction","getStripeJsVersion","DEFAULT_STYLES","DEFAULT_CONTAINER_STYLES","position","ROTATION_ANIMATION","LoadingIndicator","containerStyles","defineAnimation","buildContainer","indicator","buildIndicator","parentId","parent","opacity","hide","handleTransitionEnd","bottom","left","right","top","transition","setStyleAttribute","margin","transform","transformStyle","animation","attrs","k","setProperty","head","sheet","CSSStyleSheet","insertRule","AmountTransformer","toInteger","pow","expressCheckoutAllowedCountryCodes","StripeLinkV2CustomerStrategy","stripeIntegrationService","loadingIndicator","stripeocs","loadingContainerId","buttonHeight","_loadingIndicatorContainer","_onComplete","captureMethod","_captureMethod","_stripeClient","_mountExpressCheckoutElement","_initializeEvents","stripeExpressCheckoutClient","shouldRequireShippingAddress","_shouldRequireShippingAddress","expressCheckoutOptions","allowedShippingCountries","_getAvailableCountries","shippingRates","link","AUTO","applePay","NEVER","googlePay","amazonPay","klarna","cartAmount","elementsOptions","_toCents","_getCurrency","_linkV2Element","EXPRESS_CHECKOUT","SHIPPING_ADDRESS_CHANGE","stripe_link_v2_customer_strategy_awaiter","_onShippingAddressChange","SHIPPING_RATE_CHANGE","_onShippingRateChange","CONFIRM","_onConfirm","CANCEL","_onCancel","_getAvailableShippingOptions","_updateDisplayedPrice","shippingRate","_handleShippingOptionChange","_updateShippingAndBillingAddress","paymentPayload","_getPaymentPayload","_processAdditionalAction","billingDetails","_mapShippingAddress","_mapBillingAddress","additionalActionData","additional_action_required","_confirmStripePaymentOrThrow","_toggleLoadingIndicator","_completeCheckoutFlow","stripePaymentData","confirmationResult","confirmPayment","credit_card_token","confirm","Link","_getTotalPrice","_getStripeShippingOption","selectedId","recommendedId","_getAmountTransformer","_amountTransformer","amountTransformer","checkoutSessionEnabled","CHECKOUT_SESSION","OCS","create_stripe_link_v2_customer_strategy","stripeScriptLoader","OrderFinalizationNotRequiredError","NoPaymentDataRequiredPaymentStrategy","finalize","create_no_payment_strategy","AdyenV3ActionType","AdyenV2ActionType","AdyenComponentType","AdyenPaymentMethodType","HTTPMethod","ResultCode","AdyenCardFields","AdyenV2ScriptLoader","_stylesheetLoader","configuration","loadStylesheet","prepend","AdyenCheckout","isCardState","encryptedSecurityCode","encryptedExpiryMonth","isVaultedInstrument","instrumentId","AdyenV2PaymentStrategy","adyenv2","_paymentInitializeOptions","originKey","clientKey","paymentMethodsResponse","clientSideAuthentication","_adyenClient","translations","es","_paymentComponent","_mountPaymentComponent","CreditCard","Bancontact","_cardVerificationComponent","_mountCardVerificationComponent","adyenv2_payment_strategy_rest","shouldSetAsDefaultInstrument","_validateCardData","componentState","_componentState","encryptedCardNumber","encryptedExpiryYear","credit_card_number_confirmation","expiry_month","expiry_year","verification_value","bigpay_token","_getAdyenClient","_getPaymentInitializeOptions","_getThreeDS2ChallengeWidgetSize","additionalActionOptions","threeDS2Options","widgetSize","_handleAction","threeDS2ContainerId","onBeforeLoad","onLoad","adyenAction","additionalActionComponent","createFromAction","onAdditionalDetails","additionalActionState","paymentMethodType","ThreeDS2Challenge","QRCode","_mapAdyenPlaceholderData","prefillCardHolderName","street","houseNumberOrName","holderName","adyenClient","cardVerificationComponent","cardVerificationContainerId","SecuredFields","placeholder","caretColor","onChange","_updateComponentState","validateState","validateCardFields","onFieldValid","paymentComponent","ACH","IDEAL","SEPA","hasVaultedInstruments","AliPay","GiroPay","Sofort","Klarna","KlarnaPayNow","KlarnaAccount","Vipps","WeChatPayQR","provider_data","paymentError","cardComponent","componentRef","showValidation","isValid","issuer","props","_mapCardErrors","cardStateErrors","create_adyenv2_payment_strategy","__WEBPACK_EXTERNAL_MODULE__bigcommerce_script_loader_875b3e8f_getStylesheetLoader__","AdyenV3ScriptLoader","isHostedInstrumentLike","Adyenv3PaymentStrategy","adyenv3","paymentInitializeOptions","installmentOptions","paymentMethodsConfiguration","useKlarnaWidget","klarna_account","klarna_paynow","showInstallmentAmounts","_getLocale","showPayButton","adyenv3_payment_strategy_rest","submit","paymentToken","socialSecurityNumber","shopperName","isBoletoState","installments","plan","onActionHandled","componentType","challengeWindowSize","ThreeDS2","Sdk","_mountElement","_isOneyPaymentMethod","personalDetails","deliveryAddress","showBrandsUnderCardNumber","showEmailAddress","onSubmit","basePaymentData","tokenData","adyenComponent","_waitForMountContainer","maxAttempts","ceil","mountContainerMaxWaitMs","mountContainerPollIntervalMs","pollIntervalMs","step","poll","adyenv3_payment_strategy_awaiter","create_adyenv3_payment_strategy","AFFIRM_SCRIPTS","AffirmPaymentStrategy","affirmScriptLoader","affirm","initializeAffirmCheckout","checkout_token","getCheckoutInformation","open","onFail","failObject","successObject","ui","getOrder","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","taxTotal","first","last","full","zipcode","display_name","sku","unit_price","salePrice","qty","item_image_url","imageUrl","item_url","categories","getCategories","giftCertificates","listPrice","line","discountedAmount","discount_amount","discount_display_name","discountAmount","DISCOUNTED_AMOUNT","categoryTree","category","AffirmScriptLoader","affirmWindow","apikey","scriptURI","SANDBOX","PROD","m","g","n","h","p","getElementsByTagName","l","c","arguments","f","a1","c1","a2","c2","parentNode","insertBefore","public_api_key","script","create_affirm_payment_strategy","OrderFinalizationNotCompletedError","AfterpayPaymentStrategy","_afterpayScriptLoader","_mapCurrencyToISO2","withHttps","_afterpaySdk","applyStoreCredit","_loadPaymentMethod","validateCheckout","_redirectToAfterpay","forgetCheckout","loadPaymentMethods","AUD","NZD","CAD","USD","SCRIPTS_DEFAULT","SCRIPTS_US","AfterpayScriptLoader","_getScriptURI","isAfterpayWindow","AfterPay","HTTPS_SANDBOX","HTTPS_PROD","create_afterpay_payment_strategy","AmazonPayV2PaymentStrategy","_isReadyToPay","editButtonId","_bindEditButton","_isModalFlow","_createContainer","_amazonPayButton","_isOneTimeTransaction","_getAmazonPayButton","click","onFocus","isModalFlow","button","clone","cloneNode","replaceChild","_showLoadingSpinner","create_amazon_pay_v2_payment_strategy","apple_pay_payment_strategy_DefaultLabels","ApplePayPaymentStrategy","_storeCreditLabel","StoreCredit","storeCreditLabel","isStoreCreditApplied","storeCredit","apple_pay_payment_strategy_awaiter","create_apple_pay_payment_strategy","bigcommerce_payments_constants_LOADING_INDICATOR_STYLES","get_paypal_messages_styles_from_bnpl_config","messagesStyles","layout","logo","ratio","isBaseInstrument","BigCommercePaymentsPaymentStrategy","paypalSdkHelper","bannerContainerId","paypalBNPLConfiguration","bannerConfiguration","Messages","renderMessages","loadingIndicatorContainer","shouldRenderPayPalButtonOnInitialization","bigcommerce_payments_payment_strategy_rest","isPayPalVaultedInstrumentPaymentData","prepareVaultedInstrumentPaymentPayload","preparePaymentPayload","isProviderError","paypalOrderId","shouldConfirmInstrument","isTrustedVaultingFlow","checkoutPaymentButtonStyles","onRenderButton","onValidate","submitForm","handleClick","handleApprove","toggleLoadingIndicator","fieldsValues","getFieldsValues","getInstruments","findInstrument","paypalMessagesOptions","isBigCommercePaymentsProviderError","provider_error","create_bigcommerce_payments_payment_strategy","isPayPalFastlaneCustomer","BigCommercePaymentsFastlanePaymentStrategy","threeDSVerificationMethod","initializePayPalPaymentComponent","renderPayPalPaymentComponent","handlePayPalStoredInstrumentChange","orderRequest","bigcommerce_payments_fastlane_payment_strategy_rest","isVaultedFlow","isBigcommerceFastlaneRequestError","invalidRequestError","translationKey","getPaymentProviderCustomer","paypalFastlaneCustomer","paypalFastlaneSessionId","getBillingAddressOrThrow","cardComponentOptions","fields","prefill","enabled","paypalComponentMethods","getPayPalComponentMethodsOrThrow","isBigcommercePaymentsFastlaneThreeDSAvailable","is3dsEnabled","get3DSNonce","paypal_fastlane_token","getPaymentToken","is3DSEnabled","fastlaneToken","checkoutUrl","threeDomainSecureComponent","ThreeDomainSecureClient","threeDomainSecureParameters","threeDSRequested","Always","transactionContext","experience_context","cancel_url","isThreeDomainSecureEligible","liabilityShift","threeDSNonce","No","Unknown","Errored","Cancelled","Succeeded","Yes","Possible","paypalAxoSdk","selectionChanged","selectedCard","profile","showCardSelector","selectedInstrument","create_bigcommerce_payments_fastlane_payment_strategy","BigCommercePaymentsPayLaterPaymentStrategy","bigcommerce_payments_paylater_payment_strategy_rest","bigCommercePaymentsButtons","bigCommerceSdk","create_bigcommerce_payments_paylater_payment_strategy","TimeoutError","BigCommercePaymentsRatePayPaymentStrategy","pollingInterval","maxPollingIntervalTime","pollingTimer","stopPolling","bigcommerce_payments_ratepay","legalTextContainer","createFraudNetScript","loadFraudnetConfig","renderLegalText","bigcommerce_payments_ratepay_payment_strategy_rest","metadataId","guid","ratepayBirthDate","ratepayPhoneNumber","ratepayPhoneCountryCode","rate_pay","birth_date","normalizeDate","initializePollingMechanism","fraudNetScript","querySelectorAll","fraudNetConfig","deinitializePollingMechanism","legalTextContainerElement","date","formattedDate","formatDate","formattedMonth","getMonth","getFullYear","legalTextContainerElementId","legalTextContainerId","buttonContainer","buttonContainerParent","marginBottom","ratePayButton","Legal","PAY_UPON_INVOICE","resetPollingMechanism","scriptElement","generateGUID","s","i","floor","characters","reinitializeStrategy","resolvePromise","rejectPromise","orderStatus","useMetadata","isOrderApproved","PollingStop","isPollingError","PollingError","create_bigcommerce_payments_ratepay_payment_strategy","HostedFieldType","hosted_field_type","isCreditCardFormFields","CardNumber","CardName","CardExpiry","isCreditCardVaultedFormFields","CardNumberVerification","CardCodeVerification","CardExpiryVerification","BigCommercePaymentsCreditCardsPaymentStrategy","bigcommerce_payments_creditcards","bigCommercePaymentsInitializationOptions","form","onCreditCardFieldsRenderingError","onLoadComplete","hostedFormOptions","isCreditCardForm","isCreditCardVaultedForm","hasUndefinedValues","initializeFields","shouldInitializePayPalFastlane","initializePayPalFastlaneOrThrow","bigcommerce_payments_credit_cards_payment_strategy_rest","executionPaymentData","validateHostedFormOrThrow","submitHostedForm","getInstrumentParams","returnedOrderId","submitPaymentPayload","returnedVaultedToken","cvvField","expiryField","numberField","nameField","verification_nonce","card_with_order","formOptions","executeCallback","getExecuteCallback","cardFieldsConfig","getInputStyles","vaultSetupToken","inputEvents","onChangeHandler","onFocusHandler","onBlur","onBlurHandler","onInputSubmitRequest","cardFields","CardFields","stylizeInputContainers","renderFields","renderVaultedFields","createVaultSetupTokenCallback","createOrderCallback","createVaultSetupToken","bigcommerce_payments_credit_cards_payment_strategy_awaiter","fieldsOptions","getCardFieldsOrThrow","cardCode","CVVField","cardExpiry","ExpiryField","cardName","NameField","cardNumber","NumberField","cardCodeVerification","cardExpiryVerification","cardNumberVerification","getFieldTypeByEmittedField","emittedBy","mapFieldType","submitConfig","cardFieldsState","validationData","getValidityData","mapValidationErrors","updatedFields","cardNameField","fieldsKeys","every","fieldsErrors","getInvalidErrorByFieldType","CardCode","validationErrors","commonStyles","fontWeight","outline","background","marginLeft","onEnter","bigCommercePaymentsPaymentProviderCustomer","isBigCommercePaymentsAnalyticsV2Enabled","connectClientToken","payPalFastlaneSdk","create_bigcommerce_payments_credit_cards_payment_strategy","BigCommercePaymentsAlternativeMethodsPaymentStrategy","bigCommercePaymentsSdkHelper","isPollingEnabled","bigcommerce_payments_apms","bigCommercePaymentsAlternativeMethods","shouldRenderFields","bigcommerce_payments_alternative_methods_payment_strategy_rest","isNonInstantPaymentMethod","bigCommercePaymentsButton","Approved","deInitializePollingMechanism","paypalAmpsSdk","getPaypalAmpsSdkOrThrow","buttonStyle","onInitButton","onCreateOrder","handleFailure","bigcommerce_payments_alternative_methods_payment_strategy_awaiter","apmFieldsContainer","apmFieldsStyles","fieldContainerElement","PaymentFields","create_bigcommerce_payments_alternative_methods_payment_strategy","BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy","bigcomemrce_payments_redirect_alternative_methods_payment_strategy_rest","isRedirectError","redirectUrl","create_bigcommerce_payments_redirect_alternative_methods_payment_strategy","BigCommercePaymentsVenmoPaymentStrategy","bigcommerce_payments_venmo_payment_strategy_rest","create_bigcommerce_payments_venmo_payment_strategy","BlueSnapDirect3ds","blueSnapSdk","_blueSnapSdk","initialize3ds","cardData","_getBlueSnapSdk","threeDsPaymentsSetup","sdkResponse","threeDSecureReferenceId","threeDsPaymentsSubmitData","isHostedCardFieldOptionsMap","isHostedStoredCardFieldOptionsMap","BlueSnapDirectCardType","BlueSnapDirectEventOrigin","BlueSnapDirectErrorDescription","BlueSnapDirectErrorCode","BlueSnapDirectHostedFieldTagId","BlueSnapDirectCreditCardPaymentStrategy","_blueSnapDirectHostedForm","_blueSnapDirect3ds","_paymentFieldsToken","_shouldUseHostedFields","_getPaymentFieldsToken","pfToken","bluesnapSubmitedForm","_getBlueSnapDirectThreeDSecureData","getCardInstrumentOrThrow","previouslyUsedCard","last4Digits","ccType","cardHolderName","billingFirstName","billingLastName","billingCountry","billingCity","billingZip","shippingFirstName","shippingLastName","shippingCountry","shippingCity","shippingZip","BlueSnapHostedFieldType","CREDIT_CARD_ERRORS","empty","invalid","BlueSnapDirectHostedForm","_nameOnCardInput","_hostedInputValidator","initializeValidationFields","paymentFieldsToken","enable3DS","callbacksAndStyles","bluesnap_direct_hosted_form_rest","_onValidate","_setCustomBlueSnapAttributes","_setCustomStoredCardsBlueSnapAttributes","_getHostedPaymentFieldsOptions","hostedPaymentFieldsCreate","accessibilityLabel","threeDSecureData","shouldSendName","hostedPaymentFieldsSubmitData","_isBlueSnapDirectCallbackError","THREE_DS_AUTH_FAILED","errorDescription","getValue","onCardTypeChange","onFieldEventHandler","setupComplete","_usetUiEventCallback","_handleError","onType","_tagId","onValid","tagId","ccnPlaceHolder","cvvPlaceHolder","expPlaceHolder","_mapStyles","focus","selector","declaration","declarationBlock","property","__WEBPACK_EXTERNAL_MODULE_lodash_kebabCase__","errorCode","eventOrigin","INVALID_OR_EMPTY","EMPTY","INVALID","isBlueSnapDirectInputValidationErrorDescription","cardNumberContainer","cardExpiryContainer","cardCodeContainer","cardNameContainer","dataset","bluesnap","BlueSnapHostedInputValidator","_errors","_updateErrors","errorData","BluesnapDirectNameOnCardInput","_style","_create","_getInput","_handleFocus","_handleBlur","_handleEnter","_input","_applyStyles","HTMLInputElement","ON_BLUR","allowedStyle","styleKeys","_configureInput","autocomplete","inputMode","BlueSnapDirectSdkEnv","BlueSnapDirectScriptLoader","PRODUCTION","create_bluesnap_direct_credit_card_payment_strategy","BlueSnapDirectAPMPaymentStrategy","_formatePaymentPayload","_isBlueSnapDirectRedirectResponse","providerData","frameUrl","partialValue","merchantid","isBlueSnapDirectRedirectResponseProviderData","providerDataQuery","ecp","account_number","accountNumber","account_type","accountType","shopper_permission","shopperPermission","routing_number","routingNumber","companyName","company_name","sepa_direct_debit","iban","isIdealInstrument","ideal","bic","isPayByBankInstrument","pay_by_bank","partialResponse","partialBody","create_bluesnap_direct_apm_payment_strategy","PaymentStatusTypes","payment_status_types","BlueSnapV2PaymentStrategy","_initializeOptions","frame","_createIframe","initializeOffsitePayment","getPaymentStatus","ACKNOWLEDGE","FINALIZE","finalizeOrder","bluesnapv2","create_bluesnapv2_payment_strategy","AnalyticsExtraItemsManager","storage","saveExtraItemsData","productId","categoryNames","getStorageKey","readExtraItemsData","getItem","itemsData","hasNotExtraItems","isExtraItemsData","clearExtraItemData","removeItem","isAnalyticsTrackerWindow","isWithAccountCreation","BoltError","getError","BoltPaymentStrategy","analyticsExtraItemsManager","useBoltClient","useBoltEmbedded","onPaymentSelect","useBigCommerceCheckout","boltEmbedded","mountBoltEmbeddedField","embeddedField","setExtraItemsForAnalytics","bolt_payment_strategy_rest","isBoltPaymentData","getBoltClientPaymentPayload","getBoltEmbeddedPaymentPayload","getBoltFullCheckoutPaymentPayload","orderToken","boltTransaction","success","transaction","reference","configure","tokenizeResult","validateTokenizeResultOrThrow","last_four_digits","expiration_month","expiration","expiration_year","create_account","shouldCreateAccount","embedded_checkout","setBoltOrderId","transactionReference","getTransactionReference","getBoltEmbeddedOrThrow","setOrderId","renderSeparateFields","lastFourDigits","expirationMonth","expirationYear","isNaN","isAnalyticsEnabled","create_bolt_payment_strategy","__WEBPACK_EXTERNAL_MODULE_local_storage_fallback_5dc95480_default__","isUsBankAccountInstrumentLike","BraintreeAchPaymentStrategy","braintreeach","getMandateText","handleBraintreeError","braintree_ach_payment_strategy_rest","isSubmittingWithVaultingInstrument","tokenizePaymentForVaultedInstrument","preparePaymentDataForVaultedInstrument","preparePaymentData","getUsBankAccountOrThrow","mandateText","bankDetails","getBankDetails","isVaultingEnabled","tokenized_bank_account","masked_account_number","ownershipType","businessName","create_braintree_ach_payment_strategy","create_braintree_sdk","BraintreeMessages","messagingContainer","bannedId","CART","removeAttribute","getPaypalMessagesStylesFromBNPLConfig","Overlay","closeElement","mainElement","_createElements","_element","_closeElement","_mainElement","_registerClick","_unregisterClick","_removeAfterTransition","transitionDuration","hasCloseButton","innerHtml","classLayout","classClose","classOverlayText","overlayText","addClassLayout","innerText","getOverlayStyle","_addEventListener","_removeEventListener","onClickClose","handleTransition","propertyName","braintree_paypal_constants_LOADING_INDICATOR_STYLES","is_braintree_error_isBraintreeError","BraintreePaypalPaymentStrategy","braintreeMessages","braintreeOptions","braintreeButtonOptions","loadPaypalCheckoutInstance","braintree_paypal_payment_strategy_rest","braintreeTokenizePayload","getOutstandingBalance","vaultPaymentInstrument","paymentMethodId","shouldShowPayPalCreditBanner","renderPayPalMessages","onPaymentError","getSmartButtonContainerId","braintree_paypal_payment_strategy_awaiter","tokenizePaymentOrThrow","isBraintreePaypalProviderError","create_braintree_paypal_payment_strategy","BraintreeRequestSender","BraintreeLocalMethodsPaymentStrategy","braintreeRequestSender","isLPMsUpdateExperimentEnabled","braintreelocalmethods","braintree_local_methods_payment_strategy_rest","executeWithNotInstantLPM","executeWithInstantLPM","basicPaymentData","getLPMsBasicPaymentData","isBraintreeRedirectError","startPayment","getInstantLPMConfig","getInstantLPMCallback","paymentType","fallback","buttonText","onPaymentStart","start","braintree_local_methods_payment_strategy_awaiter","paymentId","isBraintreeOrderSavedResponse","order_id_saved_successfully","startPaymentError","payloadData","isOrderPending","Pending","Completed","Failed","create_braintree_local_methods_payment_strategy","isBraintreeAcceleratedCheckoutCustomer","BraintreeFastlanePaymentStrategy","isThreeDSExperimentEnabled","initializeCardComponent","renderBraintreeCardComponent","handleBraintreeStoredInstrumentChange","braintree_fastlane_payment_strategy_rest","braintreeCardComponent","paypalPaymentComponent","getBraintreeCardComponentOrThrow","getPayPalInstruments","threeDSToken","mapToPayPalAddress","binGuest","verifyError","braintreePaymentProviderCustomer","braintreeFastlaneCustomer","selectedInstruments","create_braintree_fastlane_payment_strategy","BraintreeVisaCheckoutPaymentStrategy","visaCheckoutSdk","braintree_visa_checkout_payment_strategy_rest","create_braintree_visa_checkout_payment_strategy","BraintreeVenmoPaymentStrategy","venmoOptions","braintreevenmo","initializeBraintreeVenmo","braintree_venmo_payment_strategy_rest","isBraintreeVenmoWebFallbackSupport","mobileWebFallBack","braintreeVenmoTokenize","create_braintree_venmo_payment_strategy","BraintreeCreditCardPaymentStrategy","braintreeHostedForm","isHostedPaymentFormEnabled","unsupportedCardBrands","isHostedFormInitialized","shouldInitializeBraintreeFastlane","braintree_credit_card_payment_strategy_rest","prepareHostedPaymentData","isPaymentMethodInitialized","commonPaymentData","isSubmittingWithStoredCard","shouldPerform3DSVerification","tokenizeForStoredCardVerification","verifyCardWithHostedForm","prepareAdditionalActionPaymentData","storedCreditCardNonce","isBraintreePaymentRequest3DSError","newPaymentData","isHostedFormEnabled","braintreeCustomer","isBraintreeFormFieldsMap","isBraintreeHostedFormError","invalidFieldKeys","BraintreeHostedFormType","BraintreeHostedForm","isInitializedHostedForm","handleBlur","mapErrors","handleFocus","handleCardTypeChange","cards","handleInputSubmitRequest","handleValidityChange","isValidForm","StoredCardVerification","mapFieldOptions","createHostedFields","mapStyleOptions","mapBillingAddress","mapTokenizeError","hostedFields","hostedFieldsOptions","preventCursorJumps","supportedCardBrands","cardBrand","is_braintree_supported_card_brand","internalLabel","mapStyles","isValidParam","isEmpty","isPotentiallyValid","fieldKey","createInvalidError","isStoredCard","createRequiredError","formFields","create_braintree_credit_card_payment_strategy","CreditCardPaymentStrategy","_isHostedPaymentFormEnabled","_shouldRenderHostedForm","_executeWithHostedForm","_executeWithoutHostedForm","_isHostedFieldAvailable","paymentSettings","bigpayBaseUrl","createHostedForm","_hostedForm","credit_card_payment_strategy_rest","__WEBPACK_EXTERNAL_MODULE_lodash_values__","CBAMPGSPaymentStrategy","cbaMGPSScriptLoader","isTestModeFlagEnabled","isCBAMPGSPaymentMethodLike","threeDSjs","isConfigured","wsVersion","retryState","storeId","transactionId","initiateAuthentication","msg","gatewayRecommendation","restApiResponse","authenticationStatus","authenticatePayer","attempt","cba_mpgs_payment_strategy_awaiter","cause","fullScreenRedirect","CBAMPGSScriptLoader","ThreeDS","create_cba_mpgs_payment_strategy","AdditionalActionType","CheckoutComCustomPaymentStrategy","checkoutcom_custom_payment_strategy_rest","_processResponse","loadCurrentOrder","additionalActionRequired","OffsiteRedirect","_performRedirect","CheckoutComFawryPaymentStrategy","checkoutcom_fawry_payment_strategy_rest","_createFormattedPayload","fawryPaymentData","customerMobile","create_checkoutcom_fawry_payment_strategy","isThreeDSecureRequiredError","CheckoutComCreditCardPaymentStrategy","checkoutcom_credit_card_payment_strategy_rest","_handleThreeDSecure","callback_url","PaReq","TermUrl","MD","create_checkoutcom_credit_card_payment_strategy","CheckoutComSEPAPaymentStrategy","checkoutcom_sepa_payment_strategy_rest","create_checkoutcom_sepa_payment_strategy","CheckoutComiDealPaymentStrategy","checkoutcom_ideal_payment_strategy_rest","create_checkoutcom_ideal_payment_strategy","DOCUMENT_SUPPORTED_APMS","CheckoutComAPMPaymentStrategy","checkoutcom_apm_payment_strategy_rest","ccDocument","create_checkoutcom_apm_payment_strategy","ClearpayPaymentStrategy","_clearpayScriptLoader","_clearpaySdk","_isCountrySupported","_redirectToClearpay","ClearpayScriptLoader","_getScriptUrl","httpsEnabled","create_clearpay_payment_strategy","create_credit_card_payment_strategy","CardinalThreeDSecureFlow","_cardinalClient","prepare","_getClientToken","hostedForm","getCardInstrument","getBin","runBinProcess","__WEBPACK_EXTERNAL_MODULE_lodash_merge__","getThreeDSecureData","_getOrderData","CardinalSignatureValidationErrors","CardinalEventType","CardinalInitializationType","CardinalValidatedAction","CardinalPaymentType","CardinalTriggerEvents","CardinalPaymentBrand","CardinalSignatureVerification","CardinalClient","_provider","_testMode","_configurationToken","_sdk","_getClientSDK","SetupCompleted","off","Validated","ActionCode","ErrorNumber","ErrorDescription","setup","Init","jwt","binNumber","BinProcess","Status","orderData","Success","NoAction","Payment","ExtendedData","SignatureVerification","Failure","continueObject","AcsUrl","Payload","partialOrder","_mapToPartialOrder","continue","CCA","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","CardinalScriptLoader","Cardinal","CyberSourcePaymentStrategy","_threeDSecureFlow","create_cybersource_payment_strategy","CardinalThreeDSecureFlowV2","xid","_getBin","_submitPayment","threeDsResult","threeDsToken","isCreditCardInstrument","hostedFormBin","CyberSourceV2PaymentStrategy","create_cybersourcev2_payment_strategy","isAdditionalActionRequiredErrorResponse","GooglePayAdyenV2","googlePayToken","GooglePayPaymentStrategy","_isDeinitializationBlocked","_loadingIndicator","walletButton","google_pay_payment_strategy_rest","extraData","_clickListener","google_pay_payment_strategy_awaiter","_isDirectPayOnClickEnabled","_interactWithPaymentSheetAndPay","_toggleBlockDeinitialization","isGooglePayDontOverrideAddresssExperimentOn","freshPaymentMethod","_getIsSignedInOrThrow","_handleOfferTrigger","isSignedIn","isBlocked","create_google_pay_adyenv2_payment_strategy","GooglePayAdyenV3","create_google_pay_adyenv3_payment_strategy","create_google_pay_authorizenet_payment_strategy","create_google_pay_checkoutcom_payment_strategy","create_google_pay_cybersource_payment_strategy","create_google_pay_orbital_payment_strategy","create_google_pay_stripe_payment_strategy","create_google_pay_worldpayaccess_payment_strategy","create_google_pay_braintree_payment_strategy","ConfirmOrderStatus","types_PayPalCommerceIntent","GooglePayPaypalCommercePaymentStrategy","_payPalCommerceSdk","getOrderId","confirmOrderData","confirmOrder","payPalSDK","PayerActionRequired","initiatePayerAction","create_google_pay_paypal_commerce_payment_strategy","types_ConfirmOrderStatus","types_BigCommercePaymentsIntent","GooglePayBigCommercePaymentsPaymentStrategy","_payPalSdkHelper","create_google_pay_bigcommerce_payments_payment_strategy","create_google_pay_tdonlinemart_payment_strategy","PaymentExecuteError","HummPaymentStrategy","humm_payment_strategy_rest","processable","isOffsiteRedirectResponse","handleOffsiteRedirectResponse","create_humm_payment_strategy","supportedCountries","supportedCountriesRequiringStates","KlarnaPaymentStrategy","klarnaScriptLoader","klarnaCredit","unsubscribe","loadWidget","klarna_payment_strategy_rest","authorization_token","authorizationToken","authorize","initializePayment","client_token","getUpdateSessionData","mapToKlarnaAddress","needsStateCode","klarnaAddress","street_address","family_name","street_address2","updateSessionData","res","approved","show_form","KlarnaScriptLoader","klarnaWindow","Credit","create_klarna_payment_strategy","KlarnaV2PaymentStrategy","klarnav2ScriptLoader","klarnav2TokenUpdater","klarnaPayments","loadPaymentsWidget","klarnav2_payment_strategy_rest","klarnaMultipleRadioButton","klarnaOrderInitialization","isKlarnaMultipleRadioButtonEnabled","authorizeOrThrow","klarnav2","updateClientToken","payment_method_category","enableBillie","organization_name","KlarnaV2ScriptLoader","Payments","KlarnaV2TokenUpdater","create_klarnav2_payment_strategy","LegacyPaymentStrategy","create_legacy_payment_strategy","MolliePaymentMethodType","methodsNotAllowedWhenDigitalOrder","MolliePaymentStrategy","mollieScriptLoader","mollie","controllers","__WEBPACK_EXTERNAL_MODULE_lodash_each__","controller","initializeOptions","isCreditCard","shouldShowTSVHostedForm","mountCardVerificationfields","mollieClient","loadMollieJs","mountElements","disableButton","loadPaymentMethodsAllowed","mollie_payment_strategy_rest","executeWithVaulted","executeWithCC","executeWithAPM","cardHolderElement","cardNumberElement","verificationCodeElement","expiryDateElement","getMollieClient","createToken","shopper_locale","getShopperLocale","CREDIT_CARD","isHostedFieldAvailable","mollie_payment_strategy_awaiter","getInitializeOptions","testmode","cardNumberId","cardCvcId","cardExpiryId","cardHolderId","createComponent","cartDigitalItems","paragraph","unsupportedMethodMessage","MollieScriptLoader","mollieHostWindow","isMollieWindow","Mollie","create_mollie_payment_strategy","moneris_payment_strategy_IFRAME_NAME","MonerisPaymentStrategy","moneris","monerisOptions","profileId","createIframe","moneris_payment_strategy_rest","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","__WEBPACK_EXTERNAL_MODULE_lodash_map__","allow","monerisResponse","responseCode","dataKey","create_moneris_payment_strategy","OfflinePaymentStrategy","create_offline_payment_strategy","OffsitePaymentStrategy","offsite_payment_strategy_rest","orderPayload","_shouldSubmitFullPayload","create_offsite_payment_strategy","utils_get_paypal_messages_styles_from_bnpl_config","PayPalCommercePaymentStrategy","payPalSdkScriptLoader","paypal_commerce_payment_strategy_rest","isRedirectActionError","isPaypalCommerceAppSwitchEnabled","isPaypalProviderError","create_paypal_commerce_payment_strategy","PayPalCommerceCreditPaymentStrategy","paypalOptions","paypal_commerce_credit_payment_strategy_rest","create_paypal_commerce_credit_payment_strategy","PayPalCommerceVenmoPaymentStrategy","paypal_commerce_venmo_payment_strategy_rest","create_paypal_commerce_venmo_payment_strategy","paypal_commerce_constants_LOADING_INDICATOR_STYLES","PayPalCommerceAlternativeMethodsPaymentStrategy","isOrderApprovedProcessing","paypalcommercealternativemethods","paypal_commerce_alternative_methods_payment_strategy_rest","paypal_commerce_alternative_methods_payment_strategy_awaiter","OXXO","bcOrderId","create_paypal_commerce_alternative_methods_payment_strategy","PayPalCommerceCreditCardsPaymentStrategy","paypalcommercecreditcards","paypalCommerceInitializationOptions","paypal_commerce_credit_cards_payment_strategy_rest","paypal_commerce_credit_cards_payment_strategy_awaiter","paypalCommercePaymentProviderCustomer","isPayPalCommerceAnalyticsV2Enabled","create_paypal_commerce_credit_cards_payment_strategy","PaypalCommerceRatepayPaymentStrategy","paypalCommerceService","paypalcommerceratepay","paypal_commerce_ratepay_payment_strategy_rest","create_paypal_commerce_ratepay_payment_strategy","is_paypal_fastlane_customer_isPayPalFastlaneCustomer","PaypalCommerceFastlanePaymentStrategy","paypal_commerce_fastlane_payment_strategy_rest","isPaypalFastlaneRequestError","create_paypal_commerce_fastlane_payment_strategy","paypal_express_types_PaypalButtonStyleLayoutOption","paypal_express_types_PaypalButtonStyleSizeOption","paypal_express_types_PaypalButtonStyleColorOption","paypal_express_types_PaypalButtonStyleLabelOption","paypal_express_types_PaypalButtonStyleShapeOption","paypal_express_types_PaymentStatusTypes","PaypalExpressPaymentStrategy","useRedirectFlow","paypalexpress","isInContextEnabled","loadPaypalSDK","closeFlow","isAcknowledgedOrFinalized","getPaymentRedirectUrl","initXO","startFlow","PaypalScriptLoader","create_paypal_express_payment_strategy","PaypalProPaymentStrategy","threeDSecureFlow","create_paypal_pro_payment_strategy","SagePayPaymentStrategy","_isThreeDSTwoExperimentOn","create_sage_pay_payment_strategy","ExternalPaymentStrategy","external_payment_strategy_rest","_isAdditionalActionRequired","SezzlePaymentStrategy","create_sezzle_payment_strategy","SquareIntent","SquareV2PaymentProcessor","applicationId","locationId","square","_payments","_formValidationSubscription","_card","destroy","initializeCard","onValidationChange","_getPayments","_subscribeToFormValidation","_getCard","verifyBuyer","CHARGE","_chargeVerifyBuyer","_storeVerifyBuyer","blacklist","Set","eventObservables","currentState","isCompletelyValid","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_distinctUntilChanged__","_mapToSquareBillingContact","STORE","SquareV2PaymentStrategy","_squareV2PaymentProcessor","squarev2","_getVaultedInstrumentPayload","_getCardPayload","shouldVerify","cardTokenizationResult","isSquareV2ApiV2Enabled","tokenForSavingCard","store_card_nonce","store_card_token","verificationToken","_getSquareCardIdOrThrow","three_d_secure","SquareV2WebPaymentsSdkEnv","SquareV2ScriptLoader","LIVE","isSquareV2Window","assertSquareV2Window","Square","create_squarev2_payment_strategy","isIndividualCardElementOptions","individualCardElementOptions","cardNumberElementOptions","cardCvcElementOptions","cardExpiryElementOptions","IconStyle","stripev3_StripeElementType","stripev3_StripePaymentMethodType","StripeV3ErrorType","StripeV3Error","AuthFailure","APM_REDIRECT","Alipay","StripeV3PaymentStrategy","stripev3","isDeinitialize","useIndividualCardFields","allowRedisplayForStoredInstruments","_allowRedisplayForStoredInstruments","stripeV3Client","mountCardVerificationFields","mountCardFields","stripev3_payment_strategy_rest","shouldSubmitOrderBeforeLoadingAPM","confirmStripePayment","buildPaymentPayload","handleEmptyPaymentIntentError","unmountElement","isAuthError","getStripeJs","confirmAlipayPayment","handleActions","confirmIdealPayment","Sepa","confirmSepaDebitPayment","getStripeCardElements","getStripeElement","mapStripeBillingDetails","createPaymentMethod","stripeCardElements","zipCodeElementOptions","isBillingAddressLike","stripePaymentMethodType","cardExpiryElement","cardCvcElement","CardCvc","needsConfirm","StripeV3ScriptLoader","create_stripev3_payment_strategy","supportedLocales","ar","bg","cs","da","el","en","et","fi","fil","fr","he","hr","hu","it","ja","ko","lt","lv","ms","mt","nb","nl","pl","pt","ro","ru","sk","sl","sv","th","tr","vi","zh","formatLocale","localeLanguage","countryLocales","formattedLocale","StripeUPEPaymentStrategy","_loadStripeElement","stripe_upe_payment_strategy_rest","_stripeUPEClient","_executeWithVaulted","_executeWithStripeConfirmation","_processAdditionalActionWithStripeConfirmation","_processVaultedAdditionalAction","initStripeElementUpdateTrigger","enableLink","_loadStripeJs","_isStripeElementUpdateEnabled","wallets","_getStripeElementTerms","READY","_updateStripeLinkStateByElementType","_updateStripeElement","sendSecondPaymentRequestOnStripeError","paymentPayloadWithError","client_side_error","shouldShowTerms","terms","paymentElementType","isStripeLinkElementType","create_stripe_upe_payment_strategy","isStripePaymentEvent","StripeOCSPaymentStrategy","_initializeStripeElement","stripe_ocs_payment_strategy_rest","customerSessionToken","fonts","paymentMethodSelect","handleClosePaymentMethod","togglePreloader","customerSessionClientSecret","savePaymentMethod","maxVisiblePaymentMethods","LOADER_START","_onStripeElementChange","_collapseStripeElement","collapse","paymentMethodOptions","us_bank_account","_shouldSaveInstrument","tokenizedOptions","_getTokenizedOptions","selectedMethodId","client_secret","paymentIntentClientSecret","payment_method_options","collapsed","setupFutureUsage","setup_future_usage","ON_SESSION","OFF_SESSION","tokenized_ach","create_stripe_ocs_payment_strategy","StripeCSPaymentStrategy","_initStripeCheckoutSession","_updateStripeShopperData","_initializePaymentElement","_initializeAdaptivePricingElement","stripe_cs_payment_strategy_rest","_updateCheckoutSessionData","getPaymentElement","currencySelectorElement","getCurrencySelectorElement","adaptivePricing","allowed","adaptivePricingEnabled","_getStripeElement","_getStripeActionsOrThrow","createPaymentElement","newVaultedStripeInstrument","existingStripeSavedPaymentMethods","_getStripeSavedPaymentMethodsOrThrow","session","_confirmStripePayment","newStripeSavedPaymentMethods","checkoutSessionId","checkoutSessionStatus","_getNewVaultedStripeInstrument","paymentStatus","Paid","stripeActions","_updateStripeEmail","_updateStripeShippingAddress","_updateStripeBillingAddress","updateEmail","savedPaymentMethods","existingMethod","currencySelectorContainerId","_getCurrencySelectorElement","_initAdaptivePricingEvents","createCurrencySelectorElement","stripe_cs_payment_strategy_awaiter","stripeCurrencyCode","isCustomerCurrencySelected","customerCurrency","create_stripe_cs_payment_strategy","FieldType","TDOnlineMartPaymentStrategy","tdOnlineMartScriptLoader","tdInputs","CARD_NUMBER","CVV","EXPIRY","tdOnlineMartClient","loadTDOnlineMartJs","mountHostedFields","td_online_mart_payment_strategy_rest","getPaymentPayloadOrThrow","processWithAdditionalAction","inputElement","digitalItemsInCart","shouldAddVerificationToken","isTrustedVaultingInstrument","getTokenOrThrow","throwTokenizationError","getHostedFieldsOptions","getTDOnlineMartClientOrThrow","inputId","isTdOnlineMartAdditionalAction_isTdOnlineMartAdditionalAction","isCreateTokenError","classes","TDOnlineMartScriptLoader","tdOnlineMartWindow","customcheckout","create_td_online_mart_payment_strategy","PAYMENT_CANNOT_CONTINUE","worldpayaccess_payment_strategy_submit","WorldpayAccessPaymentStrategy","worldpay","_submitAdditionalAction","messageEventListener","worldpayaccess_payment_strategy_awaiter","_isValidJsonWithSessionId","iframeHidden","SessionId","submitError","onLoadError","_createHiddenIframe","formId","inputBin","source_id","inputJWT","match","srcdoc","outerHTML","str","create_worldpayaccess_payment_strategy","WorldpayAccessOpenBankingPaymentStrategy","_buildOpenBankingSubmitPayment","_isWorldpayAccessRedirectResponse","open_banking","create_worldpayaccess_open_banking_payment_strategy","StorefrontPaymentRequestSender","saveExternalId","externalId","ZipPaymentStrategy","storefrontPaymentRequestSender","zip_payment_strategy_rest","_prepareForReferredRegistration","create_zip_payment_strategy","CountryActionType","OrderActionType","CountryActionCreator","_countryRequestSender","loadCountries","LoadCountriesRequested","LoadCountriesSucceeded","LoadCountriesFailed","CountryRequestSender","CartConsistencyError","CartStockPositionsChangedError","changedItemIds","OrderTaxProviderUnavailableError","MissingShippingMethodError","InvalidShippingAddressError","OrderRequestSender","loadOrder","checkoutVariant","SpamProtectionNotCompletedError","PaymentMethodActionType","OrderActionCreator","_orderRequestSender","_checkoutValidator","LoadOrderRequested","LoadOrderSucceeded","LoadOrderFailed","loadOrderPayments","LoadOrderPaymentsRequested","LoadOrderPaymentsSucceeded","LoadOrderPaymentsFailed","_getCurrentOrderId","SubmitOrderRequested","externalSource","getExternalSource","variantIdentificationToken","getVariantIdentificationToken","shouldExecuteSpamCheck","_mapToOrderRequestBody","customerMessage","SubmitOrderSucceeded","SubmitOrderFailed","FinalizeOrderRequested","FinalizeOrderSucceeded","FinalizeOrderFailed","order_action_creator_rest","createPaymentClient","paymentClient","__WEBPACK_EXTERNAL_MODULE__bigcommerce_bigpay_client_fce6db19_createClient__","setHost","isPaymentMethod","PaymentMethodActionCreator","loadPaymentMethodsById","methodIds","LoadPaymentMethodsRequested","payment_method_action_creator_awaiter","LoadPaymentMethodsSucceeded","LoadPaymentMethodsFailed","sessionHash","methods","LoadPaymentMethodRequested","LoadPaymentMethodSucceeded","LoadPaymentMethodFailed","payment_method_action_creator_decorate","PaymentMethodRequestSender","order_finalization_not_required_error_OrderFinalizationNotRequiredError","PaymentStrategyActionType","PaymentStrategyType","payment_strategy_type","PaymentStrategyWidgetActionCreator","PaymentStrategyActionCreator","_orderActionCreator","_paymentStrategyWidgetActionCreator","isPaymentDataRequired","NO_PAYMENT_DATA_REQUIRED","FinalizeRequested","_loadOrderPaymentsIfNeeded","payment_strategy_action_creator_awaiter","FinalizeSucceeded","FinalizeFailed","paymentStrategies","getByMethod","CartComparator","cartA","cartB","_normalize","itemA","itemB","variantId","localeCompare","extendedSalePrice","recipient","giftWrapping","CartChangedError","previous","updated","CheckoutValidator","comparator","_compareCoupons","_compareGiftCertificates","_getComparableCheckout","couponsA","couponsB","giftCertificatesA","giftCertificatesB","BrowserStorage","_namespace","rawValue","withNamespace","getItemOnce","CardingProtectionChallengeNotCompletedError","CardingProtectionFailedError","HostedFieldEventType","HostedInputEventType","PaymentHumanVerificationHandler","handle","errorOrId","handleWithRecaptchaSitekey","handleWithPaymentHumanVerificationRequestError","_isPaymentHumanVerificationRequest","_initialize","_performRecaptcha","payment_human_verification_handler_awaiter","human_verification_token","cardingProtectionElementId","cardingProtectionElement","mapFromPaymentErrorResponse","joinErrors","InvalidHostedFormConfigError","InvalidHostedFormError","InvalidHostedFormValueError","__WEBPACK_EXTERNAL_MODULE_lodash_flatMap__","fieldErrors","HostedField","_type","_placeholder","_accessibilityLabel","_styles","_eventPoster","_eventListener","_detachmentObserver","_checkoutId","_cardInstrument","overflow","getType","hosted_field_awaiter","AttachRequested","cardInstrument","fontUrls","_getFontUrls","AttachSucceeded","AttachFailed","SubmitRequested","SubmitSucceeded","SubmitFailed","_isSubmitErrorEvent","submitStoredCardForm","StoredCardRequested","StoredCardSucceeded","StoredCardFailed","validateForm","ValidateRequested","family","PaymentActionType","HostedForm","_fields","_payloadTransformer","_eventCallbacks","_paymentHumanVerificationHandler","hosted_form_awaiter","Blurred","CardTypeChanged","Focused","Entered","_cardType","BinChanged","_bin","getCardType","_getFirstField","otherFields","__WEBPACK_EXTERNAL_MODULE_lodash_without__","otherField","submitStoredCard","is_vaulted_instrument_isVaultedInstrument","HostedFormOrderDataTransformer","getConfig","instrumentMeta","getInstrumentsMeta","orderMeta","getOrderMeta","paymentMethodMeta","getPaymentMethodsMeta","authToken","vaultAccessToken","HostedFormFactory","fieldOptions","_getCardInstrument","__WEBPACK_EXTERNAL_MODULE_lodash_pick__","MissingPaymentInstrument","PaymentActionCreator","_paymentRequestSender","_paymentRequestTransformer","InitializeOffsitePaymentRequested","InitializeOffsitePaymentSucceeded","InitializeOffsitePaymentFailed","SubmitPaymentRequested","payment_action_creator_awaiter","SubmitPaymentSucceeded","SubmitPaymentFailed","PaymentRequestSender","_client","_transformResponse","statusText","mapToInternalAddress","addressId","is_billing_address_like_isBillingAddressLike","province","provinceCode","postCode","couponTypes","mapToInternalCoupon","discount","discountType","couponType","mapToInternalGiftCertificate","used","remainingBalance","remaining","balance","purchaseDate","mapToDiscountNotifications","promotions","notifications","promotion","banners","banner","placeholders","messageHtml","mapToInternalLineItems","itemMap","idKey","amountAfterDiscount","integerAmountAfterDiscount","integerUnitPrice","integerUnitPriceAfterDiscount","integerDiscount","sender","mapGiftCertificateToInternalLineItem","extendedListPrice","downloadsPageUrl","downloadPageUrl","mapToInternalLineItem","mapToInternalLineItemType","mapToInternalCart","sum","discountNotifications","totalDiscountedAmount","certificate","appliedGiftCertificates","__WEBPACK_EXTERNAL_MODULE_lodash_keyBy__","amountBeforeDiscount","shippingCostBeforeDiscount","integerAmountBeforeDiscount","taxSubtotal","handling","handlingCostTotal","CheckoutButtonMethodType","checkout_button_method_type","mapToInternalCustomer","customerGroupName","customerGroup","CardExpiryFormatter","RegExp","trimmedMonth","trimmedYear","toObject","CardNumberFormatter","__WEBPACK_EXTERNAL_MODULE_card_validator_0e6920dd_number__","__WEBPACK_EXTERNAL_MODULE_lodash_max__","__WEBPACK_EXTERNAL_MODULE_card_validator_0e6920dd_creditCardType__","lengths","unformattedValue","unformat","gaps","gapIndex","mapToInternalOrder","customerCanBeCreated","mapToInternalOrderPayment","baseAmount","callbackUrl","mapToGiftCertificates","socialData","mapToInternalSocialDataList","hasDigitalItems","isDownloadable","isComplete","mapToStoreCredit","orderAmountAsInteger","isDefaultOrderPayment","helpText","instructions","socialDataObject","socialMedia","image","shareText","sharingLink","channelName","channel","channelCode","mapToInternalShippingOption","isSelected","price","selected","transitTime","PaymentRequestTransformer","_cardExpiryFormatter","_cardNumberFormatter","getShippingOption","contextConfig","paymentMeta","internalCustomer","formattedInstrument","is_vaulted_instrument_isFormattedVaultedInstrument","_transformPaymentMethod","quoteMeta","geoCountryCode","transformWithHostedFormData","_transformHostedInputValues","BRAINTREE_VENMO","BRAINTREE_PAYPAL","hostedFormNonce","isBopisEnabled","bopis","requiredAddress","isPickup","selectedPickupOption","isPPSDKPaymentMethod","initializationStrategy","PPSDK","PaymentStrategyRegistry","_getToken","KLARNAV2","_hasFactoryForMethod","OFFLINE","payment_argument_invalid_error_PaymentArgumentInvalidError","credit_card_payment_strategy_CreditCardPaymentStrategy","_paymentActionCreator","_hostedFormFactory","credit_card_credit_card_payment_strategy_rest","ConvergePaymentStrategy","orderActionCreator","paymentActionCreator","hostedFormFactory","payment_method_cancelled_error_PaymentMethodCancelledError","PENDING_REDIRECT_PARAM","RedirectionState","_isRedirecting","currentUrlHasRedirectingParam","isRedirecting","setRedirecting","setRedirectingParamOnUrl","removeRedirectingParamFromUrl","getCurrentUrl","__WEBPACK_EXTERNAL_MODULE_query_string_2dcf3be8_parseUrl__","replaceCurrentUrl","history","replaceState","currentUrl","updatedUrl","__WEBPACK_EXTERNAL_MODULE_query_string_2dcf3be8_stringifyUrl__","__WEBPACK_EXTERNAL_MODULE_query_string_2dcf3be8_exclude__","isAnyContinue","__WEBPACK_EXTERNAL_MODULE_lodash_overSome__","__WEBPACK_EXTERNAL_MODULE_lodash_get__","__WEBPACK_EXTERNAL_MODULE_lodash_isString__","__WEBPACK_EXTERNAL_MODULE_lodash_isUndefined__","redirect_isParameters","availableMethods","isParameters","ContinueHandler","_humanVerificationHandler","form_fields","redirectionState","handleRedirect","available_methods","humanVerificationHandler","human_verification_awaiter","handleHumanVerification","humanVerification","StepHandler","_continueHandler","isSuccess","isContinue","isFailure","failureResponse","isError","COMPLETED_PAYMENTS_KEY","PPSDKCompletedPayments","_browserStorage","isCompleted","getCompletedPayments","setCompleted","completedPayments","setCompletedPayments","SubStrategyType","PPSDKStrategy","_subStrategyRegistry","_paymentResumer","browserStorage","_completedPayments","ppsdk_strategy_rest","_subStrategy","subStrategy","getPPSDKMethod","getToken","__WEBPACK_EXTERNAL_MODULE_lodash_cond__","__WEBPACK_EXTERNAL_MODULE_lodash_constant__","CARD","NONE","__WEBPACK_EXTERNAL_MODULE_lodash_stubTrue__","UNSUPPORTED","SubStrategyRegistry","CardSubStrategy","_ppsdkStepHandler","card_sub_strategy_awaiter","NoneSubStrategy","_stepHandler","payment_method_id","PaymentProviderCustomerType","RemoteCheckoutActionType","PaymentResumer","auth_token","CartRequestSender","PaymentProviderCustomerActionCreator","providerCustomerData","UpdatePaymentProviderCustomer","ConsignmentActionType","RemoteCheckoutActionCreator","_remoteCheckoutRequestSender","initializeBilling","InitializeRemoteBillingRequested","InitializeRemoteBillingSucceeded","InitializeRemoteBillingFailed","initializeShipping","InitializeRemoteShippingRequested","InitializeRemoteShippingSucceeded","InitializeRemoteShippingFailed","InitializeRemotePaymentRequested","InitializeRemotePaymentSucceeded","InitializeRemotePaymentFailed","loadSettings","LoadRemoteSettingsRequested","LoadRemoteSettingsSucceeded","LoadRemoteSettingsFailed","SignOutRemoteCustomerRequested","SignOutRemoteCustomerSucceeded","SignOutRemoteCustomerFailed","ForgetCheckoutRemoteCustomerRequested","remote_checkout_action_creator_awaiter","ForgetCheckoutRemoteCustomerSucceeded","ForgetCheckoutRemoteCustomerFailed","UpdateRemoteCheckout","RemoteCheckoutRequestSender","methodName","generateToken","trackAuthorizationEvent","ConsignmentActionCreator","_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","consignmentInMemory","getConsignmentById","_isUpdateConsignmentRequest","itemId","_hydrateLineItems","lineItemIds","existingItem","sharedItem","concat","DEFAULT_INCLUDES","ConsignmentRequestSender","consignment_request_sender_rest","ShippingCountryActionType","StoreCreditActionType","ShippingCountryActionCreator","_shippingCountryRequestSender","checkoutData","LoadShippingCountriesRequested","LoadShippingCountriesSucceeded","LoadShippingCountriesFailed","ShippingCountryRequestSender","SubscriptionsActionType","StoreCreditActionCreator","_storeCreditRequestSender","ApplyStoreCreditRequested","store_credit_action_creator_awaiter","checkoutVersion","removeStoreCredit","ApplyStoreCreditSucceeded","ApplyStoreCreditFailed","StoreCreditRequestSender","UpdateSubscriptionsError","SubscriptionsActionCreator","_subscriptionsRequestSender","subscriptions","UpdateSubscriptionsRequested","subscriptions_action_creator_awaiter","UpdateSubscriptionsSucceeded","UpdateSubscriptionsFailed","SubscriptionsRequestSender","isPlainObject","__WEBPACK_EXTERNAL_MODULE_lodash_isPlainObject__","cloneDeep","__WEBPACK_EXTERNAL_MODULE_lodash_memoize__","cloneDeepSafe","cache","cloneResult","createPaymentIntegrationSelectors","getPaymentTokenOrThrow","getPaymentIdOrThrow","getPaymentStatusOrThrow","getPaymentRedirectUrlOrThrow","getShippingAddressOrThrow","getShippingAddresses","getShippingAddressesOrThrow","shippingCountries","InstrumentActionType","DefaultPaymentIntegrationService","_storeProjectionFactory","_billingAddressActionCreator","_consignmentActionCreator","_paymentMethodActionCreator","_cartRequestSender","_storeCreditActionCreator","_couponActionCreator","_paymentProviderCustomerActionCreator","_shippingCountryActionCreator","_remoteCheckoutActionCreator","_storeProjection","subscriber","filters","initializeOffsitePaymentConfig","buyNowCartRequestBody","handlePaymentHumanVerification","queueId","PaymentIntegrationStoreProjectionFactory","_transformSelectors","createPaymentIntegrationService","storeProjectionFactory","checkoutActionCreator","checkoutValidator","billingAddressActionCreator","consignmentActionCreator","paymentMethodActionCreator","paymentHumanVerificationHandler","customerActionCreator","storeCreditActionCreator","applyCouponActionCreator","spamProtection","spamProtectionRequestSender","spamProtectionActionCreator","cartRequestSender","paymentProviderCustomerActionCreator","shippingCountryActionCreator","remoteCheckoutActionCreator","paymentStrategyWidgetActionCreator","InstrumentActionCreator","_instrumentRequestSender","loadInstruments","LoadInstrumentsRequested","_getSessionContext","_getCurrentAccessToken","_getShippingAddress","_getValidAccessToken","currentToken","LoadInstrumentsSucceeded","LoadInstrumentsFailed","deleteInstrument","DeleteInstrumentRequested","DeleteInstrumentSucceeded","DeleteInstrumentFailed","_isValidVaultAccessToken","newDate","setMinutes","getMinutes","addMinutes","vaultAccessExpiry","valueOf","getVaultAccessToken","isTransactional","PickupOptionActionType","ShippingStrategyActionType","InstrumentResponseTransformer","transformResponse","instrument_response_transformer_rest","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","InstrumentRequestSender","_transformer","requestContext","_loadInstrumentsWithAddress","_loadInstruments","deleteShopperInstrument","errorResponse","loadInstrumentsWithAddress","PickupOptionActionCreator","_pickupOptionRequestSender","loadPickupOptions","apiQuery","_hydrateApiQuery","LoadPickupOptionsRequested","fetchPickupOptions","LoadPickupOptionsSucceeded","LoadPickupOptionsFailed","consignmentLineItems","cartItems","searchArea","PickupOptionRequestSender","ShippingStrategyActionCreator","UpdateAddressRequested","UpdateAddressSucceeded","UpdateAddressFailed","selectOption","SelectOptionRequested","SelectOptionSucceeded","SelectOptionFailed","mergedOptions","shippingStrategies","instrument_UntrustedShippingCardVerificationType","AmazonPayV2ShippingStrategy","_amazonPayV2PaymentProcessor","_shippingStrategyActionCreator","updateAddressRequestBody","editAddressButtonId","shouldShowLoadingSpinner","_shouldShowLoadingSpinner","BraintreeFastlaneShippingStrategy","_braintreeIntegrationService","fastlane","fastlaneOptions","onPayPalFastlaneAddressChange","_shouldRunAuthenticationFlow","_runAuthenticationFlowOrThrow","_shouldUseBraintreeFastlaneShippingComponent","_handleBraintreeFastlaneShippingAddressChange","_getPayPalBillingAddress","paypalPhoneNumber","_mapPayPalToBcAddress","_mergeShippingAndBillingAddresses","_mapPayPalToBcInstrument","_getCountryNameByCountryCode","_normalizeAddress","selectedAddress","showShippingAddressSelector","paymentProviderCustomerAddresses","_filterAddresses","_isEqualAddresses","_getBraintreePaymentMethodOrThrow","isFastlaneEnabled","DefaultShippingStrategy","PayPalCommerceFastlaneShippingStrategy","_paypalSdkScriptLoader","_paypalCommerceFastlaneUtils","_shouldAuthenticateUserWithFastlane","_initializePayPalSdk","_authenticateUserWithFastlaneOtp","_shouldUsePayPalFastlaneShippingComponent","_handlePayPalShippingAddressChange","_getPayPalPaymentMethodOrThrow","_getPayPalCustomerAuthenticationState","paypalConnectSessionId","customerAuthenticationState","billingAddressEmail","SignInEmailActionType","StripeUPEShippingStrategy","_stripeScriptLoader","onChangeShipping","availableCountries","getStripeState","getShippingAddressFields","shippingFields","spacingUnit","shippingPhoneField","allowedCountries","validation","SPLIT","stripeState","shippingAddressElement","isNewAddress","sendData","phoneFieldRequired","SignInEmailActionCreator","sendSignInEmail","emailRequest","SendSignInEmailRequested","signin_email_action_creator_awaiter","SendSignInEmailSucceeded","SendSignInEmailFailed","SignInEmailRequestSender","ErrorMessageTransformer","_messageCustomizer","CheckoutService","_extensionEventBroadcaster","_b2bTokenActionCreator","_countryActionCreator","_customerStrategyActionCreator","_errorActionCreator","_giftCertificateActionCreator","_instrumentActionCreator","_paymentStrategyActionCreator","_pickupOptionActionCreator","_signInEmailActionCreator","_subscriptionsActionCreator","_extensionActionCreator","_errorTransformer","isDevelopment","isCheckoutServiceError","createCheckoutServiceErrorTransformer","notifyState","_dispatch","loadCheckoutAction","formFieldsAction","loadConfigAction","finalizeOrderIfNeeded","loadPaymentMethodByIds","deinitializePayment","loadBillingCountries","loadBillingAddressFields","loadShippingAddressFields","initializeCustomer","deinitializeCustomer","signInEmailRequest","createCustomerAccount","createCustomerAddress","deinitializeShipping","assignItemsToAddress","unassignItemsToAddress","selectConsignmentShippingOption","initializeSpamProtection","executeSpamCheck","clearExtensionCache","postMessageToExtension","handleExtensionCommand","handler","handleExtensionQuery","checkout_service_decorate","withMemoizedCombiner","creator","combiner","pop","combinerArgs","create_selector","__WEBPACK_EXTERNAL_MODULE_reselect_createSelector__","create_shallow_equal_selector","__WEBPACK_EXTERNAL_MODULE_reselect_createSelectorCreator__","__WEBPACK_EXTERNAL_MODULE_reselect_defaultMemoize__","__WEBPACK_EXTERNAL_MODULE_shallowequal_default__","UnrecoverableError","map_from_internal_error_response_joinErrors","timeout_error_TimeoutError","RequestErrorFactory","_factoryMethods","mapFromInternalErrorResponse","mapFromStorefrontErrorResponse","factoryMethod","createError","_getType","_isStorefrontErrorResponseBody","_isInternalErrorResponseBody","internalType","__WEBPACK_EXTERNAL_MODULE_lodash_last__","storefrontErrorResponse","internalErrorResponse","omitDeep","predicate","__WEBPACK_EXTERNAL_MODULE_lodash_transform__","clearErrorReducer","isClearErrorAction","objectA","objectB","isArrayEqual","isDateEqual","isRegExpEqual","keyFilter","keysA","keysB","isObjectEqual","objectSet","DEFAULT_STATE","statuses","b2bTokenReducer","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_combineReducers__","dataReducer","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_composeReducers__","errorsReducer","statusesReducer","reducer","currentValue","newValue","billing_address_state_DEFAULT_STATE","billingAddressReducer","billing_address_reducer_dataReducer","billing_address_reducer_errorsReducer","billing_address_reducer_statusesReducer","array_replace","arrayReplace","currentArray","newArray","matchObject","sameAsCurrentCount","sameAsNewCount","countSameAsReplaced","replacedValue","newItem","currentItem","object_merge","objectMerge","currentObject","newObject","cart_state_DEFAULT_STATE","cartReducer","cart_reducer_dataReducer","cart_reducer_errorsReducer","cart_reducer_statusesReducer","CheckoutButtonActionType","checkout_button_state_DEFAULT_STATE","DEFAULT_DATA_STATE","initializedContainers","DEFAULT_ERROR_STATE","DEFAULT_STATUS_STATE","checkoutButtonReducer","checkout_button_reducer_dataReducer","checkout_button_reducer_errorsReducer","checkout_button_reducer_statusesReducer","InitializeButtonSucceeded","DeinitializeButtonSucceeded","InitializeButtonRequested","InitializeButtonFailed","DeinitializeButtonRequested","DeinitializeButtonFailed","config_state_DEFAULT_STATE","configReducer","config_reducer_dataReducer","config_reducer_errorsReducer","config_reducer_statusesReducer","merged","coupon_state_DEFAULT_STATE","couponReducer","coupon_reducer_dataReducer","coupon_reducer_errorsReducer","coupon_reducer_statusesReducer","gift_certificate_state_DEFAULT_STATE","giftCertificateReducer","gift_certificate_reducer_dataReducer","gift_certificate_reducer_errorsReducer","gift_certificate_reducer_statusesReducer","customer_state_DEFAULT_STATE","customerReducer","customer_reducer_dataReducer","customer_reducer_errorsReducer","customer_reducer_statusesReducer","customer_strategy_state_DEFAULT_STATE","customerStrategyReducer","customer_strategy_reducer_dataReducer","customer_strategy_reducer_errorsReducer","customer_strategy_reducer_statusesReducer","initializeErrors","initializeMethodId","deinitializeError","deinitializeMethodId","signInError","signInMethodId","signOutError","signOutMethodId","executePaymentMethodCheckoutError","executePaymentMethodCheckoutMethodId","widgetInteractionError","widgetInteractionMethodId","isInitializing","isDeinitializing","isSigningIn","isSigningOut","isExecutingPaymentMethodCheckout","isWidgetInteracting","extension_state_DEFAULT_STATE","extensionReducer","extension_reducer_dataReducer","extension_reducer_errorsReducer","extension_reducer_statusesReducer","form_fields_state_DEFAULT_STATE","formFieldsReducer","form_fields_reducer_dataReducer","extraFields","extraFieldsReducer","form_fields_reducer_errorsReducer","form_fields_reducer_statusesReducer","country_state_DEFAULT_STATE","countryReducer","country_reducer_dataReducer","country_reducer_errorsReducer","country_reducer_statusesReducer","order_state_DEFAULT_STATE","orderReducer","order_reducer_dataReducer","order_reducer_errorsReducer","metaReducer","order_reducer_statusesReducer","order_billing_address_state_DEFAULT_STATE","orderBillingAddressReducer","order_billing_address_reducer_dataReducer","paymentReducer","payment_reducer_dataReducer","payment_method_state_DEFAULT_STATE","paymentMethodReducer","payment_method_reducer_dataReducer","payment_method_reducer_errorsReducer","payment_method_reducer_metaReducer","payment_method_reducer_statusesReducer","array","defaultPredicate","derivedPredicate","__WEBPACK_EXTERNAL_MODULE_lodash_findIndex__","mergeOrPush","methodA","methodB","loadMethodId","loadMethodError","isLoadingMethod","payment_strategy_state_DEFAULT_STATE","paymentStrategyReducer","payment_strategy_reducer_dataReducer","payment_strategy_reducer_errorsReducer","payment_strategy_reducer_statusesReducer","initializeError","executeError","executeMethodId","finalizeError","finalizeMethodId","isExecuting","isFinalizing","payment_provider_customer_state_DEFAULT_STATE","paymentProviderCustomerReducer","payment_provider_customer_reducer_dataReducer","instrument_state_DEFAULT_STATE","instrumentReducer","instrument_reducer_dataReducer","instrument_reducer_errorsReducer","instrument_reducer_metaReducer","instrument_reducer_statusesReducer","deleteError","failedInstrument","isDeleting","deletingInstrument","remote_checkout_state_DEFAULT_STATE","remoteCheckoutReducer","remote_checkout_reducer_dataReducer","consignment_state_DEFAULT_STATE","updateShippingOptionError","updateError","isUpdating","isUpdatingShippingOption","consignmentReducer","consignment_reducer_dataReducer","consignment_reducer_errorsReducer","consignment_reducer_statusesReducer","objectFlatten","flattened","keyString","objectWithSortedKeys","current","pickup_option_state_DEFAULT_STATE","pickupOptionReducer","pickup_option_reducer_dataReducer","pickup_option_reducer_errorsReducer","pickup_option_reducer_statusesReducer","sortedflattenedMeta","shipping_country_state_DEFAULT_STATE","shippingCountryReducer","shipping_country_reducer_dataReducer","shipping_country_reducer_errorsReducer","shipping_country_reducer_statusesReducer","shipping_strategy_state_DEFAULT_STATE","shippingStrategyReducer","shipping_strategy_reducer_dataReducer","shipping_strategy_reducer_errorsReducer","shipping_strategy_reducer_statusesReducer","updateAddressError","updateAddressMethodId","selectOptionError","selectOptionMethodId","isUpdatingAddress","isSelectingOption","signin_email_state_DEFAULT_STATE","signInEmailReducer","signin_email_reducer_dataReducer","signin_email_reducer_errorsReducer","signin_email_reducer_statusesReducer","store_credit_reducer_DEFAULT_STATE","storeCreditReducer","store_credit_reducer_errorsReducer","store_credit_reducer_statusesReducer","subscriptions_state_DEFAULT_STATE","subscriptionsReducer","subscriptions_reducer_errorsReducer","subscriptions_reducer_statusesReducer","checkout_state_DEFAULT_STATE","checkoutReducer","checkout_reducer_dataReducer","checkout_reducer_errorsReducer","checkout_reducer_statusesReducer","guard_guard","createFreezeProxy","proxy","iteratee","getPrototypeOf","traversePrototypeOf","charAt","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_deepFreeze__","trap","createProxy","supported_payment_instruments","authorizenet","elavon","checkoutcom","sagepay","cybersource","cybersourcev2","bnz","converge","orbital","paymetric","cba_mpgs","worldpayaccess","tdonlinemart","normalize","__WEBPACK_EXTERNAL_MODULE_lodash_identity__","store_credit_state_DEFAULT_STATE","createInternalCheckoutSelectorsFactory","createB2BTokenSelector","getLoadError","loadError","__WEBPACK_EXTERNAL_MODULE__bigcommerce_memoize_bf7b411a_memoizeOne__","createB2BTokenSelectorFactory","createBillingAddressSelector","getUpdateError","getContinueAsGuestError","continueAsGuestError","isContinuingAsGuest","createBillingAddressSelectorFactory","createCartSelector","createCartSelectorFactory","createCheckoutButtonSelector","getInitializeError","getDeinitializeError","createCheckoutButtonSelectorFactory","createConfigSelector","getFlashMessages","filterType","flashMessages","formState","createConfigSelectorFactory","createCountrySelector","createCountrySelectorFactory","createCouponSelector","getCoupons","getRemoveError","removeCouponError","getApplyError","applyCouponError","isApplying","isApplyingCoupon","isRemoving","isRemovingCoupon","createCouponSelectorFactory","createCustomerSelector","getCreateAccountError","isCreatingCustomerAccount","isCreating","getCreateAddressError","createAddressError","isCreatingCustomerAddress","isCreatingAddress","createCustomerSelectorFactory","createCustomerStrategySelector","getSignInError","getSignOutError","getExecutePaymentMethodCheckoutError","getWidgetInteractionError","createCustomerStrategySelectorFactory","createGiftCertificateSelector","getGiftCertificates","removeGiftCertificateError","applyGiftCertificateError","isApplyingGiftCertificate","isRemovingGiftCertificate","createGiftCertificateSelectorFactory","createInstrumentSelector","getInstrumentsByPaymentMethod","paymentMethodKey","currentMethod","__WEBPACK_EXTERNAL_MODULE_lodash_isMatch__","supportedProvider","getDeleteError","createInstrumentSelectorFactory","createFormSelector","selectedCountry","processField","getBillingAddressFields","getCustomerAccountFields","getAddressExtraFields","itemtype","processCountry","subdivisions","requiresState","processProvince","hasPostalCodes","processsPostCode","createFormSelectorFactory","createPaymentMethodSelector","getPaymentMethods","getLoadMethodError","createPaymentMethodSelectorFactory","createPaymentStrategySelector","getExecuteError","getFinalizeError","getWidgetInteractingError","createPaymentStrategySelectorFactory","createPickupOptionSelector","getPickupOptions","pickupOptions","sortedFlattenedParams","createPickupOptionSelectorFactory","createPaymentProviderCustomerSelector","createPaymentProviderCustomerSelectorFactory","createRemoteCheckoutSelector","createRemoteCheckoutSelectorFactory","createShippingAddressSelector","shippingConsignment","shippingConsignments","createShippingAddressSelectorFactory","createShippingCountrySelector","createShippingCountrySelectorFactory","createShippingStrategySelector","getUpdateAddressError","getSelectOptionError","createShippingStrategySelectorFactory","createConsignmentSelector","isAddressEqual","addressA","addressB","getCreateError","getLoadShippingOptionsError","loadShippingOptionsError","getUnassignedItems","assignedLineItemIds","itemIds","getItemAssignmentError","getUpdateShippingOptionError","isLoadingShippingOptions","isAssigningItems","createConsignmentSelectorFactory","createCheckoutSelector","isExecutingSpamCheck","createCheckoutSelectorFactory","createOrderSelector","getOrderBillingAddress","currentPayment","createOrderSelectorFactory","createOrderBillingAddressSelector","createOrderBillingAddressSelectorFactory","createPaymentSelector","getInternalPayment","getGatewayPayment","getHostedPayment","providerType","internalPayment","MissingPaymentId","MissingPaymentStatus","MissingPaymentRedirectUrl","isPaymentDataSubmitted","createPaymentSelectorFactory","createStoreCreditSelector","applyError","createStoreCreditSelectorFactory","createSubscriptionsSelector","createSubscriptionsSelectorFactory","createSignInEmailSelector","getEmail","signInEmail","getSendError","sendError","isSending","createSignInEmailSelectorFactory","createExtensionSelector","createExtensionSelectorFactory","b2bToken","checkoutButton","orderBillingAddress","remoteCheckout","selectors","shouldWarnMutation","createCheckoutStore","initialStoreState","actionTransformer","requestErrorFactory","createRequestErrorFactory","action$","createInternalCheckoutSelectors","createCheckoutService","checkoutVariantIdentificationToken","experimentRequestSender","orderRequestSender","checkoutRequestSender","configActionCreator","subscriptionsActionCreator","formFieldsActionCreator","registryV2","paymentStrategyFactories","createPaymentStrategy","createPaymentStrategyRegistry","payment_strategies_namespaceObject","customerRegistryV2","customerStrategyFactories","createCustomerStrategy","createCustomerStrategyRegistry","customer_strategies_namespaceObject","extensionActionCreator","extensionMessenger","storeProjection","createCheckoutStoreSelector","getShippingOptions","getSelectedShippingOption","getBillingCountries","getSelectedPaymentMethod","getSignInEmail","getUserExperienceSettings","checkoutUserExperienceSettings","createCheckoutStoreSelectorFactory","createCheckoutStoreErrorSelector","getSelectShippingOptionError","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","getLoadB2BTokenError","getCreateCustomerAccountError","getCreateCustomerAddressError","getPickupOptionsError","getLoadExtensionsError","createCheckoutStoreErrorSelectorFactory","createCheckoutStoreStatusSelector","isPending","isSelectingShippingOption","isCustomerStepPending","isShippingStepPending","isPaymentStepPending","isSubmittingOrder","isLoadingCheckout","isUpdatingCheckout","isFinalizingOrder","isLoadingOrder","isLoadingCart","isLoadingBillingCountries","isLoadingShippingCountries","isLoadingPaymentMethods","isLoadingPaymentMethod","isInitializingPayment","isInitializingCustomer","isInitializedCustomer","isUpdatingBillingAddress","isUpdatingSubscriptions","isUpdatingShippingAddress","isUpdatingConsignment","isDeletingConsignment","isCreatingConsignments","isInitializingShipping","isApplyingStoreCredit","isLoadingInstruments","isDeletingInstrument","isLoadingConfig","isSendingSignInEmail","isLoadingB2BToken","isLoadingPickupOptions","createCheckoutStoreStatusSelectorFactory","createCheckoutSelectorsFactory","checkout_service","messenger","subscribers","createExtensionEventBroadcaster","create_customer_strategy_registry_createCustomerStrategyRegistry","paymentRequestTransformer","paymentRequestSender","stepHandler","createStepHandler","CONVERGE","createSubStrategyRegistry","create_payment_strategy_registry_createPaymentStrategyRegistry","consignmentRequestSender","createShippingStrategyRegistry","AmazonPayV2ConfigCreationError","isWithBuyNowFeatures","AmazonPayV2ButtonStrategy","amazonPayV2ConfigRequestSender","initializeAmazonButtonOptions","_buyNowInitializeOptions","Cart","_getCheckoutCreationRequestConfig","_createBuyNowCartOrThrow","_createCheckoutConfig","public_key","rest","amazon_pay_v2_button_strategy_rest","payloadJSON","AmazonPayV2RequestSender","create_amazon_pay_v2_button_strategy","amazonPayV2RequestSender","apple_pay_button_strategy_DefaultLabels","ButtonStyleOption","ApplePayButtonStrategy","_requiresShipping","White","WhiteBorder","Black","getButtonStyle","_getRequestWithEmptyTotal","apple_pay_button_strategy_awaiter","onpaymentmethodselected","_createBuyNowCart","_handlePaymentMethodSelected","completePaymentMethodSelection","create_apple_pay_button_strategy","BigCommercePaymentsButtonStrategy","onEligibilityFailure","buyNowFlowCallbacks","create_bigcommerce_payments_button_strategy","BigCommercePaymentsPayLaterButtonStrategy","create_bigcommerce_payments_paylater_button_strategy","BigCommercePaymentsVenmoButtonStrategy","getValidVenmoButtonStyles","validButtonStyle","gold","create_bigcommerce_payments_venmo_button_strategy","BoltButtonStrategy","BoltConnect","setupProductPageCheckout","addButtonContainer","boltButtonContainer","boltButtonObject","getBoltObjectData","append","domainUrl","getButtonHeight","buttonBorderRadius","getButtonBorderRadius","publishable_key","variant","border_radius","buttonSize","Small","Large","Medium","buttonShape","Pill","Rect","create_bolt_button_strategy","fundingicons","tagline","currentHeight","BraintreePaypalButtonStrategy","shouldProcessPayment","onAuthorizeError","buyNowCartId","buyNowCardRequestBody","create_braintree_paypal_button_strategy","BraintreePaypalCreditButtonStrategy","create_braintree_paypal_credit_button_strategy","BraintreeVisaCheckoutButtonStrategy","braintree_visa_checkout_button_strategy_awaiter","paymentSuccess","toVisaCheckoutAddress","alignItems","create_braintree_visa_checkout_button_strategy","getVenmoButtonStyle","WHITE","backgroundPosition","backgroundSize","backgroundImage","BLUE","backgroundRepeat","cursor","minHeight","minWidth","BraintreeVenmoButtonStrategy","cartButtonStyles","renderVenmoButton","isUnsupportedBrowserError","handleInitializationVenmoError","removeVenmoContainer","venmoButton","braintree_venmo_button_strategy_awaiter","buyBowCart","handlePostForm","create_braintree_venmo_button_strategy","GooglePayButtonStrategy","_getMethodOrThrow","_countryCode","google_pay_button_strategy_awaiter","_buyNowCart","_getBuyNowTransactionInfo","_getTransactionInfo","create_google_pay_braintree_button_strategy","create_google_pay_paypal_commerce_button_strategy","create_google_pay_bigcommerce_payments_button_strategy","create_google_pay_adyenv2_button_strategy","create_google_pay_adyenv3_button_strategy","create_google_pay_authorizenet_button_strategy","create_google_pay_checkoutcom_button_strategy","create_google_pay_cybersource_button_strategy","create_google_pay_orbital_button_strategy","create_google_pay_stripe_button_strategy","create_google_pay_worldpayaccess_button_strategy","create_google_pay_tdonlinemart_button_strategy","PayPalCommerceButtonStrategy","create_paypal_commerce_button_strategy","PayPalCommerceCreditButtonStrategy","create_paypal_commerce_credit_button_strategy","PayPalCommerceVenmoButtonStrategy","create_paypal_commerce_venmo_button_strategy","PaypalButtonStrategy","paypalExpressScriptLoader","paypalSDK","allowCredit","fundingCreditOption","allowedSources","disallowedSources","Button","funding","disallowed","getStyle","onAuthorize","RECT","RESPONSIVE","CheckoutButtonNotInitialized","paymentID","payerID","getPaymentData","payerId","payerInfo","payer_info","create_paypal_express_button_strategy","StripeLinkV2ButtonStrategy","stripe_link_v2_button_strategy_awaiter","create_stripe_link_v2_button_strategy","getUniqId","idPrefix","__WEBPACK_EXTERNAL_MODULE_lodash_uniqueId__","isTerminalCacheKeyMap","CacheKeyResolver","_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","CheckoutButtonErrorSelector","_checkoutButton","getInitializeButtonError","getDeinitializeButtonError","checkout_button_error_selector_decorate","CheckoutButtonStatusSelector","isInitializingButton","isDeinitializingButton","checkout_button_status_selector_decorate","createCheckoutButtonSelectors","checkout_button_error_selector","checkout_button_status_selector","CheckoutButtonInitializer","_buttonStrategyActionCreator","_state","initializeButton","containerIds","containers","setUniqueElementId","deinitializeButton","checkout_button_initializer_decorate","CheckoutButtonStrategyActionCreator","_registryV2","paymentMethodRequestParams","paymentMethodRequestOptions","payment_method_client_unavailable_error_PaymentMethodClientUnavailableError","paypal_sdk_PaypalButtonStyleLayoutOption","paypal_sdk_PaypalButtonStyleSizeOption","paypal_sdk_PaypalButtonStyleColorOption","paypal_sdk_PaypalButtonStyleLabelOption","paypal_sdk_PaypalButtonStyleShapeOption","EmbeddedCheckoutEventType","NotEmbeddableErrorType","EmbeddedContentEventType","paypal_script_loader_PaypalScriptLoader","paypal_button_strategy_PaypalButtonStrategy","_paypalScriptLoader","_host","_setupPayment","_tokenizePayment","createCheckoutButtonInitializer","checkoutButtonStrategyFactories","createCheckoutButtonStrategy","createCheckoutButtonStrategyRegistry","checkout_button_strategies_namespaceObject","checkout_button_initializer","PAYPALEXPRESS","createCheckoutButtonRegistry","InvalidLoginTokenError","NotEmbeddableError","UnknownError","IS_COOKIE_ALLOWED_KEY","LAST_ALLOW_COOKIE_ATTEMPT_KEY","EmbeddedCheckout","_iframeCreator","_messageListener","_messagePoster","_storage","_location","_isAttached","CheckoutComplete","CheckoutError","CheckoutLoaded","onFrameLoad","FrameLoaded","onSignOut","SignedOut","_configureStyles","_allowCookie","_attemptLogin","_retryAllowCookie","FrameError","iFrameResizer","StyleConfigured","lastAttempt","MissingContent","embedded_checkout_decorate","resizable_iframe_creator_ResizableIframeCreator","MissingContainer","allowPaymentRequest","contentId","embedCheckout","handleFrameLoadedEvent","hasAttribute","custom_error_isCustomError","IframeEmbeddedCheckoutMessenger","_untargetedMessagePoster","_messageHandlers","postComplete","_postMessage","postError","_transformError","postFrameError","untargeted","postFrameLoaded","postLoaded","postSignedOut","receiveStyles","_notifyMessageHandlers","iframe_embedded_checkout_messenger_decorate","NoopEmbeddedCheckoutMessenger","noop_embedded_checkout_messenger_decorate","createEmbeddedCheckoutMessenger","parentWindow","noop_embedded_checkout_messenger","iframe_embedded_checkout_messenger","DEFAULT_LOCALE","KEY_PREFIX","LanguageService","_logger","locales","_transformConfig","_locale","_locales","_translations","_formatters","mapKeys","_hasTranslations","translate","prefixedKey","__WEBPACK_EXTERNAL_MODULE_intl_messageformat_1c4020d9_IntlMessageFormat__","_escapeSpecialCharacters","ignoreTag","_transformData","_isFormatError","originalMessage","defaultLocale","defaultTranslations","_flattenObject","fallbackTranslations","__WEBPACK_EXTERNAL_MODULE_lodash_union__","fallbackLocale","parentKey","resultKey","language_service_decorate","createLanguageService","language_service","currency_service_CurrencyService","currency_currency_service_decorate","create_currency_service_createCurrencyService","currency_currency_service","isAnalyticsTrackerWindowGA","ga","sendGoogleAnalytics","nonInteraction","isPayloadSizeLimitReached","serializeAnalyticsEventPayload","acc","AnalyticStepId","ANALYTIC_STEPS","CUSTOMER","BILLING","AnalyticsStepTracker","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","getShopperCurrency","getPaymentMethodName","shipping_method","shippingMethodId","completedStepId","getStoreProfile","toShopperCurrency","getProducts","product_id","giftCertificateItems","itemAttributes","image_url","NoopStepTracker","createStepTracker","stepTrackerConfig","isBraintreeFastlaneWindow","BraintreeAnalyticTracker","_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","PayPalCommerceAnalyticTracker","_checkoutService","paypalHostWindow","_getPayPalEventsOrThrow","createPayPalCommerceAnalyticTracker","AnalyticStepType","StoredCardHostedFormService","createStoredCardHostedFormService","AnalyticStepOrder","BodlEmitterService","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","__WEBPACK_EXTERNAL_MODULE_lodash_flatten__","retail_price","retailPrice","NoopBodlService","createBodlService","isBodlEnabled"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"checkout-sdk.js","mappings":"k+DAAA,IAAAA,EACAC,EAGAC,EAAAC,SAJAH,EAIA,CAAqBI,cAAA,IAAAC,EAAA,eAHrBJ,EAAA,GAAaK,EAAAC,EAAAN,EAAAD,GAA6BC,WCD1CC,EAAAC,QAAAK,ICCAC,GAAA,GAGA,SAAAH,GAAAI,GAEA,IAAAC,EAAAF,GAAAC,GACA,QAAAE,IAAAD,EACA,OAAAA,EAAAR,QAGA,IAAAD,EAAAO,GAAAC,GAAA,CAGAP,QAAA,IAOA,OAHAU,GAAAH,GAAAR,EAAAA,EAAAC,QAAAG,IAGAJ,EAAAC,OACA,CCrBAG,GAAAC,EAAA,CAAAJ,EAAAW,KACA,QAAAC,KAAAD,EACAR,GAAAU,EAAAF,EAAAC,KAAAT,GAAAU,EAAAb,EAAAY,IACAE,OAAAC,eAAAf,EAAAY,EAAA,CAAyCI,YAAA,EAAAC,IAAAN,EAAAC,MCJzCT,GAAAU,EA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B,MACAD,QACAwB,iBAAkB,CAACC,EAAO3+C,KACtBA,QAKQ0b,OACxB,EE1JJ,MA0BAo/C,GAAehtC,GAxBVjf,IACD,MAAMy1B,EAAgB1F,IAEhBjK,EAA2C7e,OAC3C8e,EAA6B,IAAI1F,GAA2BrgB,GAC5Di0C,EAAe,IAAIvyB,GACrB,IAAImE,GACA7G,IACA8G,EACAC,IAIR,OAAO,IAAIm6B,GACPlgD,EACA,IAAI4hD,GACA8C,KACA,IAAIwG,GAA0BlrD,EAA2Bi0C,GACzDxe,EACAyC,QAK+D,CACvE,CAAE1uC,GAAI,wBC/CG0iE,GAA2B,CACpC,mBAAoB,qBACpB,UAAW,QAOFC,GAA+B,CACxC,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,SC3mBW,SAASC,GACpBxX,GAEA,IAAKA,EACD,OAGJ,IAAID,EAEJ,GAAIC,EAAcj8C,SAAS,KAAM,CAC7B,MAAO0zD,EAAUj7C,GAAUwjC,EAAcngB,MAAM,KAE/CkgB,EAAS,GAAG0X,KAAYj7C,EAAOk7C,qBAE/B3X,EAAS,GAAGC,KAAiBA,EAAc0X,gBAG/C,OAAOH,GAA6BxzD,SAASg8C,GAAUA,OAAS3tD,CACpE,wSC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GJ,GAAItyD,SAASC,eAAekyD,IACxB,OAGJ,MAAM1uD,EAAQzD,SAASI,cAAc,SAErCqD,EAAM7f,GAAKuuE,GAGE,QAAb9uE,EAAA2c,SAAS4zD,YAAI,IAAAvwE,GAAAA,EAAEid,YAAYmD,GAEvBA,EAAMowD,iBAAiBC,eAGvBrwD,EAAMowD,MAAME,WACR,gCACa5B,wLAKb,EAGZ,EChJW,MAAM6B,GACjB,WAAA7uE,CAAoB0rD,GAAAxrD,KAAAwrD,eAAAA,CAAyB,CAE7C,SAAAojB,CAAU77C,GACN,OAAOpB,KAAKg7B,MAAM55B,EAASpB,KAAAk9C,IAAA,GAAM7uE,KAAKwrD,gBAC1C,ECLG,MAAMsjB,GAAqC,CAC9C,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KAC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A+B,CAE/B,cAAA2E,GAAwB,CAExB,eAAAC,GAAyB,CAEzB,eAAA9E,GAAyB,CAEzB,YAAA+E,GAAsB,ECNX,SAASoB,GACpBjrL,GAEA,OCtBG,SAAuB4T,GAC1B,MAAO,eAAgBA,CAC3B,CDoBQs3K,CAAct3K,QACP,IAAIk0K,GAAmB9nL,EAAW4T,OAAOm0K,WAAWjvL,UAGxD,IAAIkyL,EACf","sources":["webpack://@bigcommerce/checkout-sdk/external module \"iframe-resizer\"","webpack://@bigcommerce/checkout-sdk/external module \"iframe-resizer/js/iframeResizer.contentWindow\"","webpack://@bigcommerce/checkout-sdk/webpack/bootstrap","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/./packages/core/src/form/map-extra-field-to-form-field.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/throw-error-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/b2b-token/b2b-token-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/b2b-token/b2b-token-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/sdk-version-headers.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/b2b-token/b2b-token-request-sender.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/billing/errors/unable-to-continue-as-guest-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/content-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/empty-cart-error.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/http-request/experiment-aware-request-sender.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/./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-actions.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/coupon/gift-certificate-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/cart/cart-source.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-actions.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-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/core/src/spam-protection/is-spam-protection-succeeded-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-hydrate-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/payment-integration/register-integrations.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/form/form-fields-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/spam-protection-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/spam-protection/errors/spam-protection-challenge-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-failed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/not-initialized-error.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/spam-protection/spam-protection-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/mutation-observer.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/spam-protection/spam-protection-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/default/default-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/parse-url.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/extension-not-found-error.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/extension/create-extension-event-poster.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/cancellable-promise/cancellable-promise.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/errors/unexpected-detachment-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-internal-commands.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/detachment-observer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-resizer.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-iframe.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/create-extension-web-worker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/bind-decorator/bind-decorator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-commands.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-queries.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/worker/worker-event-listener.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/worker/worker-event-poster.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/unsupported-extension-command-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/unsupported-extension-query-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/worker-extension-messenger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/append-www.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-listener.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-messenger.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/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/missing-data-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/not-initialized-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/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/invalid-argument-error.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/utility/src/is-experiment-enabled/is-experiment-enabled.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk-verison.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk-version-manager.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.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk-scripts-integrity.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/isManageableBraintreeSDKVersion.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-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-session-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/is-apple-pay-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/is-apple-pay-sdk-window.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/buy-now-cart-creation-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/internal-api-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/content-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/sdk-version-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/create-bigcommerce-payments-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/checkout-buttons/default-checkout-button-height.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/bigcommerce-payments-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/create-bigcommerce-payments-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/bigcommerce-payments-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/paypal-sdk-helper.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/create-bigcommerce-payments-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/storage/src/cookie-storage.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/bigcommerce-payments-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/create-bigcommerce-payments-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/get-fastlane-styles.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-fastlane/bigcommerce-payments-fastlane-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-fastlane/create-bigcommerce-payments-fastlane-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/bigcommerce-payments-paylater-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/create-bigcommerce-payments-paylater-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/bigcommerce-payments-venmo-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/create-bigcommerce-payments-venmo-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/payment-method-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt.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-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/create-bolt-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-argument-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-invalid-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/load-paypal-sdk-once.ts","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/braintree-utils/src/utils/is-credit-card-instrument-like.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/./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/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/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/utility/src/is-web-view/is-web-view.ts","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/is-react-native-window/is-react-native-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/is-opera-window/is-opera-window.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/google-pay-payment-initialize-options.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/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/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/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/stripe-utils/src/stripe.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/stripe-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/stripe-upe/stripe-upe-constants.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/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/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/paypal-utils/src/paypal-commerce-constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/utils/transform-locale-to-paypal-format.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/paypal-commerce-sdk.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-gateway.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/google-pay-integration/src/google-pay-bigcommerce-payments/google-pay-bigcommerce-payments-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-bigcommerce-payments/create-google-pay-bigcommerce-payments-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/paypal-utils/src/paypal-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/paypal-sdk-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/create-paypal-sdk-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/paypal-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/paypal-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/create-paypal-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/paypal-button-creation-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-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-integration-service.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-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-utils/src/paypal-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/create-paypal-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-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-utils/src/is-stripe-payment-method-like.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/stripe-upe-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/create-stripe-upe-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/stripe-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/is-stripe-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/ui/src/loading-indicator/loading-indicator.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/utility/amount-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/stripe-link-v2-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/create-stripe-link-v2-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/order-finalization-not-required-error.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/adyen-utils/src/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-utils/src/adyenv2/adyenv2-script-loader.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/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.ts","webpack://@bigcommerce/checkout-sdk/./packages/affirm-integration/src/affirm-payment-strategy.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/bigcommerce-payments-integration/src/bigcommerce-payments-constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/get-paypal-messages-styles-from-bnpl-config.ts","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/is-base-instrument/is-base-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/bigcommerce-payments-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-bigcommerce-payments-provider-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/create-bigcommerce-payments-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-paypal-fastlane-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-fastlane/bigcommerce-payments-fastlane-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-bigcommerce-fastlane-request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-fastlane/create-bigcommerce-payments-fastlane-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/bigcommerce-payments-paylater-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/create-bigcommerce-payments-paylater-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/timeout-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-ratepay/bigcommerce-payments-ratepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-ratepay/create-bigcommerce-payments-ratepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/hosted-form/hosted-field-type.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/bigcommerce-payments-integration/src/bigcommerce-payments-credit-cards/bigcommerce-payments-credit-cards-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-bigcommerce-payments-fastlane-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-credit-cards/create-bigcommerce-payments-credit-cards-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-alternative-methods/bigcommerce-payments-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-alternative-methods/create-bigcommerce-payments-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-redirect-alternative-methods/bigcomemrce-payments-redirect-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-redirect-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-redirect-alternative-methods/create-bigcommerce-payments-redirect-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/bigcommerce-payments-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/create-bigcommerce-payments-venmo-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/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/types.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/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/braintree-utils/src/braintree-messages.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/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-request-sender.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/braintree-integration/src/braintree-visa-checkout/braintree-visa-checkout-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-visa-checkout/create-braintree-visa-checkout-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-venmo/braintree-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-venmo/create-braintree-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-credit-card/braintree-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-payment-request-3ds-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-form-fields-map.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-hosted-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-hosted-form/braintree-hosted-form.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-supported-card-brand.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-credit-card/create-braintree-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/credit-card-integration/src/credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/cba-mpgs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/is-cba-mpgs-payment-method-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/cba-mpgs.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/cba-mpgs-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/create-cba-mpgs-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/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/google-pay-bigcommerce-payments/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-bigcommerce-payments/google-pay-bigcommerce-payments-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-bigcommerce-payments/create-google-pay-bigcommerce-payments-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/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-utils/src/utils/get-paypal-messages-styles-from-bnpl-config.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/paypal-commerce-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/utils/is-redirect-action-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/utils/is-paypal-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-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-constants.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/paypal-commerce-integration/src/paypal-commerce-credit-card/paypal-commerce-credit-cards-payment-strategy.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/create-paypal-commerce-credit-cards-payment-strategy.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-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-utils/src/utils/is-paypal-fastlane-request-error.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-express-integration/src/paypal-express-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/paypal-express-payment-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-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/external-integration/src/external-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/external-integration/src/is-additional-action.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-utils/src/stripe-supported-locales.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/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-utils/src/is-stripe-payment-event.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/stripe-ocs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/create-stripe-ocs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-cs/stripe-cs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-cs/create-stripe-cs-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/worldpayaccess-integration/src/worldpayaccess-open-banking-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/worldpayaccess-integration/src/create-worldpayaccess-open-banking-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/order/order-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/cart/errors/cart-consistency-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/cart-stock-positions-changed-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/errors/missing-shipping-method-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/errors/invalid-shipping-address-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/create-payment-client.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-request-sender.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-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-widget-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-action-creator.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/storage/browser-storage.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/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/spam-protection/payment-human-verification-handler.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.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-actions.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/payment/payment-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-request-sender.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/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/promotion/map-to-discount-notifications.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/generated/checkout-button-method-type.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/./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/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/payment-status-types.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/converge/converge-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-method-cancelled-error.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/redirect/redirect.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/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-sub-strategy-type.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-provider-customer/payment-provider-customer-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-payment-resumer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-provider-customer/payment-provider-customer-actions-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-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-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/store-credit/store-credit-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/subscription/subscriptions-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/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/instrument/instrument-actions.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/payment/instrument/instrument-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/date-time/add-minutes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/date-time/is-future.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-actions.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-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-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument.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/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/paypal-utils/src/utils/is-paypal-accelerated-checkout-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-actions.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-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/./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/./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/object-set.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/b2b-token/b2b-token-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/b2b-token/b2b-token-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/replace.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/cart/cart-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-actions.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/b2b-token/b2b-token-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-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/coupon/coupon-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-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/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/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/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/store-credit/store-credit-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-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/checkout/create-action-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/create-request-error-factory.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/payment/create-payment-strategy-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/create-customer-strategy-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-selectors.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/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/ppsdk/create-ppsdk-sub-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/create-shipping-strategy-registry.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/bigcommerce-payments-integration/src/bigcommerce-payments/bigcommerce-payments-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/create-bigcommerce-payments-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/bigcommerce-payments-paylater-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/create-bigcommerce-payments-paylater-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/bigcommerce-payments-venmo-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/create-bigcommerce-payments-venmo-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/get-valid-button-style.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/braintree-paypal-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/create-braintree-paypal-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal-credit/braintree-paypal-credit-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal-credit/create-braintree-paypal-credit-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/google-pay-bigcommerce-payments/create-google-pay-bigcommerce-payments-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-express-integration/src/paypal-express-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/create-paypal-express-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/stripe-link-v2-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/create-stripe-link-v2-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/set-unique-element-id.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/checkout-buttons/checkout-button-strategy-action-creator.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/paypal/paypal-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/embedded-checkout-events.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/payment/strategies/paypal/paypal-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/paypal/paypal-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/errors/invalid-login-token-error.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/./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/bodl/analytics-steps.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/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":["var x = (y) => {\n\tvar x = {}; __webpack_require__.d(x, y); return x\n} \nvar y = (x) => (() => (x))\nmodule.exports = x({ [\"iframeResizer\"]: () => (__WEBPACK_EXTERNAL_MODULE_iframe_resizer_1512d797__.iframeResizer) });","module.exports = __WEBPACK_EXTERNAL_MODULE_iframe_resizer_js_iframeResizer_contentWindow_a6cfc03f__;","// 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","// 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};","import { ExtraField, ExtraFieldType } from './extra-field';\nimport FormField, { FormFieldFieldType, FormFieldType } from './form-field';\n\nexport const B2B_EXTRA_FIELD_PREFIX = 'b2bExtraField_';\n\nexport function isExtraField(field: FormField): boolean {\n return field.name.startsWith(B2B_EXTRA_FIELD_PREFIX);\n}\n\nexport default function mapExtraFieldToFormField(extraField: ExtraField): FormField {\n const { fieldType, type } = getFieldTypeInfo(extraField.type);\n\n let options: FormField['options'];\n\n if (extraField.config.numberOfRows) {\n options = { rows: extraField.config.numberOfRows };\n }\n\n if (extraField.config.options?.length) {\n options = {\n ...options,\n items: extraField.config.options.map((val) => ({\n value: val,\n label: val,\n })),\n };\n }\n\n return {\n id: `${B2B_EXTRA_FIELD_PREFIX}${extraField.id}`,\n name: `${B2B_EXTRA_FIELD_PREFIX}${extraField.id}`,\n custom: false,\n label: extraField.name,\n hidden: !extraField.visibleToStorefront,\n required: extraField.isRequired,\n default:\n extraField.config.defaultValue != null\n ? String(extraField.config.defaultValue)\n : undefined,\n fieldType,\n type,\n maxLength: extraField.config.maxLength,\n max: extraField.config.maxValue,\n options,\n };\n}\n\nfunction getFieldTypeInfo(extraFieldType: ExtraFieldType): {\n fieldType: FormFieldFieldType;\n type: FormFieldType;\n} {\n switch (extraFieldType) {\n case 'multiline_text':\n return { fieldType: 'multiline', type: 'string' };\n\n case 'number':\n return { fieldType: 'text', type: 'integer' };\n\n case 'dropdown':\n return { fieldType: 'dropdown', type: 'array' };\n\n case 'text':\n default:\n return { fieldType: 'text', type: 'string' };\n }\n}\n","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 { Action } from '@bigcommerce/data-store';\n\nimport { B2BToken } from './b2b-token-state';\n\nexport enum B2BTokenActionType {\n LoadB2BTokenRequested = 'LOAD_B2B_TOKEN_REQUESTED',\n LoadB2BTokenSucceeded = 'LOAD_B2B_TOKEN_SUCCEEDED',\n LoadB2BTokenFailed = 'LOAD_B2B_TOKEN_FAILED',\n}\n\nexport type LoadB2BTokenAction =\n | LoadB2BTokenRequestedAction\n | LoadB2BTokenSucceededAction\n | LoadB2BTokenFailedAction;\n\nexport interface LoadB2BTokenRequestedAction extends Action {\n type: B2BTokenActionType.LoadB2BTokenRequested;\n}\n\nexport interface LoadB2BTokenSucceededAction extends Action {\n type: B2BTokenActionType.LoadB2BTokenSucceeded;\n}\n\nexport interface LoadB2BTokenFailedAction extends Action {\n type: B2BTokenActionType.LoadB2BTokenFailed;\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 { RequestOptions } from '../common/http-request';\n\nimport { B2BTokenActionType, LoadB2BTokenAction } from './b2b-token-actions';\nimport B2BTokenRequestSender from './b2b-token-request-sender';\n\nexport default class B2BTokenActionCreator {\n constructor(private _requestSender: B2BTokenRequestSender) {}\n\n loadB2BToken(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const storeConfig = state.config.getStoreConfigOrThrow();\n const { storeHash } = storeConfig.storeProfile;\n const { baseUrl: b2bBaseUrl = '', clientId: b2bClientId = '' } =\n storeConfig.b2bApiSettings ?? {};\n const { id: customerId } = state.customer.getCustomerOrThrow();\n const { channelId } = state.checkout.getCheckoutOrThrow();\n\n return concat(\n of(createAction(B2BTokenActionType.LoadB2BTokenRequested)),\n defer(async () => {\n const { body } = await this._requestSender.getB2BToken(\n b2bClientId,\n customerId,\n storeHash,\n channelId,\n b2bBaseUrl,\n options,\n );\n\n return createAction(B2BTokenActionType.LoadB2BTokenSucceeded, {\n token: body.data.token,\n });\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(B2BTokenActionType.LoadB2BTokenFailed, error),\n ),\n );\n };\n }\n}\n","export const SDK_VERSION_HEADERS = { 'X-Checkout-SDK-Version': LIBRARY_VERSION };\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 { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nexport interface B2BTokenResponseBody {\n code: number;\n data: {\n token: string;\n };\n}\n\nexport default class B2BTokenRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n async getB2BToken(\n appClientId: string,\n customerId: number,\n storeHash: string,\n channelId: number,\n b2bBaseUrl: string,\n options?: RequestOptions,\n ): Promise> {\n const { body: jwtBody } = await this._requestSender.get<{ token: string }>(\n '/customer/current.jwt',\n {\n timeout: options?.timeout,\n params: { app_client_id: appClientId },\n headers: SDK_VERSION_HEADERS,\n },\n );\n\n return this._requestSender.post(`${b2bBaseUrl}/api/v2/login`, {\n timeout: options?.timeout,\n credentials: false,\n headers: { 'Content-Type': 'application/json' },\n body: {\n bcToken: jwtBody.token,\n customerId,\n storeHash,\n channelId,\n },\n });\n }\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 '../../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","enum ContentType {\n Json = 'application/json',\n JsonV1 = 'application/vnd.bc.v1+json',\n}\n\nexport default ContentType;\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\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 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\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 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 hasBillingAddress: boolean,\n options?: RequestOptions,\n ): Promise> {\n if (!hasBillingAddress) {\n return this._requestSender.createAddress(checkoutId, address, options);\n }\n\n return this._requestSender.updateAddress(checkoutId, address, options);\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error is thrown when cart is removed or empty.\n */\nexport default class EmptyCartError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Your checkout could not be processed because your cart is empty. Please add items to your cart and try again.',\n );\n\n this.name = 'EmptyCartError';\n this.type = 'empty_cart';\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { AddressRequestBody } from '../address';\nimport { EmptyCartError } from '../cart/errors';\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.physicalItems.stockPosition',\n 'cart.lineItems.digitalItems.options',\n 'cart.lineItems.digitalItems.stockPosition',\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\n .post(url, {\n body: address,\n params: DEFAULT_PARAMS,\n headers,\n timeout,\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .put(url, { params: DEFAULT_PARAMS, body, headers, timeout })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\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","import { RequestOptions, RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { StoreConfig } from '../../config';\n\nexport interface ExperimentConfig {\n getBasePath: () => string | undefined;\n getFeatures: () => StoreConfig['checkoutSettings']['features'];\n}\n\nexport default class ExperimentAwareRequestSender {\n constructor(private _requestSender: RequestSender, private _config: ExperimentConfig) {}\n\n sendRequest(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.sendRequest(url, options);\n }\n\n get(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.get(url, options);\n }\n\n post(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.post(this._prefixed(url), options);\n }\n\n put(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.put(this._prefixed(url), options);\n }\n\n patch(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.patch(this._prefixed(url), options);\n }\n\n delete(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.delete(this._prefixed(url), options);\n }\n\n private _prefixed(url: string): string {\n const basePath = this._config.getBasePath();\n\n const isExperimentEnabled =\n this._config.getFeatures()['CHECKOUT-9950.update_sf_checkout_url_for_subfolder'];\n\n if (\n !isExperimentEnabled ||\n !basePath ||\n basePath.endsWith('/checkout') ||\n /^https?:\\/\\//.test(url)\n ) {\n return url;\n }\n\n return `${basePath}${url}`;\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","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 { 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 { 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 | object;\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.physicalItems.stockPosition',\n 'cart.lineItems.digitalItems.options',\n 'cart.lineItems.digitalItems.stockPosition',\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 { 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","export enum CartSource {\n BuyNow = 'BUY_NOW',\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 { 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 { EmptyCartError } from '../cart/errors';\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\n .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 .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes([\n ...CHECKOUT_DEFAULT_INCLUDES,\n CheckoutIncludes.AvailableShippingOptions,\n ]),\n },\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\n }\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 { EmptyCartError } from '../cart/errors';\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\n .post(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n body: { giftCertificateCode },\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\n }\n}\n","import ResolvableModule from './resolvable-module';\n\nexport default function isResolvableModule(\n module: TModule,\n): module is ResolvableModule {\n return module && '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: (\n token: string,\n registeredTokens: string[],\n exactMatch?: boolean,\n ) => 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 getFactory(token: string, exactMatch?: boolean): Factory | undefined {\n const resolvedToken = this._tokenResolver(token, Object.keys(this._factories), exactMatch);\n const factory = resolvedToken ? this._factories[resolvedToken] : undefined;\n\n return factory;\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 factory = this.getFactory(token);\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 defaultToken: this._encodeToken({ default: true } as unknown as TToken),\n useFallback: this._useFallback,\n });\n }\n\n get(resolveId: TToken): TType {\n return this._registry.get(this._encodeToken(resolveId));\n }\n\n getFactory(resolveId: TToken, exactMatch?: boolean): Factory | undefined {\n try {\n return this._registry.getFactory(this._encodeToken(resolveId), exactMatch);\n } catch (error) {\n return undefined;\n }\n }\n\n getUseFallback(): boolean {\n return this._useFallback;\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(\n token: string,\n registeredTokens: string[],\n exactMatch?: boolean,\n ): string | undefined {\n const query = this._decodeToken(token);\n\n const results: Array<{\n token: string;\n matches: number;\n default: boolean;\n totalKeys: number;\n }> = [];\n\n registeredTokens.forEach((registeredToken) => {\n const resolverId = this._decodeToken(registeredToken);\n\n const result = {\n token: registeredToken,\n matches: 0,\n default: false,\n totalKeys: Object.keys(resolverId).length,\n };\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 queryKeyCount = Object.keys(query).length;\n\n if (exactMatch) {\n const exactResult = matchedResults.find(\n (result) => result.matches === queryKeyCount && result.matches === result.totalKeys,\n );\n\n if (!exactResult) {\n throw new Error(\n `Unable to resolve to a registered token with the provided token for ${JSON.stringify(\n query,\n )} with exact match.`,\n );\n }\n\n return exactResult.token;\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(\n `Unable to resolve to a registered token with the provided token for ${JSON.stringify(\n query,\n )}.`,\n );\n }\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\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 { 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 { Action } from '@bigcommerce/data-store';\n\nimport CheckoutInitialState from './checkout-initial-state';\n\nexport enum CheckoutHydrateActionType {\n HydrateInitialState = 'HYDRATE_INITIAL_STATE',\n}\n\nexport interface CheckoutHydrateAction extends Action {\n type: CheckoutHydrateActionType.HydrateInitialState;\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 { CartSource } from '@bigcommerce/checkout-sdk/payment-integration-api';\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 const checkout = store.getState().checkout.getCheckoutOrThrow();\n const cartId = checkout.cart.source === CartSource.BuyNow ? checkout.id : undefined;\n\n return concat(\n of(createAction(CustomerActionType.SignInCustomerRequested)),\n from(\n this._customerRequestSender.signInCustomer({ ...credentials, cartId }, options),\n ).pipe(\n switchMap(({ body }) => {\n if (body.data.persistentCartRetrievalInformation) {\n return concat(\n this._checkoutActionCreator.loadCheckout(\n body.data.persistentCartRetrievalInformation.id,\n options,\n )(store),\n of(\n createAction(\n CustomerActionType.SignInCustomerSucceeded,\n body.data,\n ),\n ),\n );\n }\n\n return 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\n signOutCustomer(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const checkout = store.getState().checkout.getCheckoutOrThrow();\n const cartId = checkout.cart.source === CartSource.BuyNow ? checkout.id : undefined;\n\n return concat(\n of(createAction(CustomerActionType.SignOutCustomerRequested)),\n from(this._customerRequestSender.signOutCustomer(options, cartId)).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}\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(\n { timeout }: RequestOptions = {},\n cartId?: string,\n ): Promise> {\n const url = '/internalapi/v1/checkout/customer';\n\n return this._requestSender.delete(url, {\n timeout,\n headers: SDK_VERSION_HEADERS,\n ...(cartId && { body: { cartId } }),\n });\n }\n}\n","import {\n isResolvableModule,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\n\nexport type StrategyFactory = (\n paymentIntegrationService: PaymentIntegrationService,\n) => TStrategy;\n\nexport function registerIntegrations(\n registry: ResolveIdRegistry,\n integrations: Array>,\n paymentIntegrationService: PaymentIntegrationService,\n): void {\n integrations.forEach((factory) => {\n if (!isResolvableModule, TResolveId>(factory)) {\n return;\n }\n\n factory.resolveIds.forEach((resolveId) => {\n if (registry.getFactory(resolveId, true)) {\n return;\n }\n\n registry.register(resolveId, () => factory(paymentIntegrationService));\n });\n });\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport {\n CustomerStrategy as CustomerStrategyV2,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { registerIntegrations } from '../payment-integration';\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 private _paymentIntegrationService: PaymentIntegrationService,\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 registerIntegrations(\n this._strategyRegistryV2,\n options?.integrations ?? [],\n this._paymentIntegrationService,\n );\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 { EmptyCartError } from '../cart/errors';\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\n .put(url, {\n params: {\n include: joinOrMergeIncludes(CHECKOUT_DEFAULT_INCLUDES, include),\n },\n body,\n headers,\n timeout,\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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 { Action, 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 } from '../config';\nimport { FormFieldsActionCreator } from '../form';\n\nimport Checkout, { CheckoutRequestBody } from './checkout';\nimport { CheckoutActionType, LoadCheckoutAction, UpdateCheckoutAction } from './checkout-actions';\nimport { CheckoutHydrateActionType } from './checkout-hydrate-actions';\nimport CheckoutInitialState from './checkout-initial-state';\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 () => {\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._transformCustomerAddresses(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._transformCustomerAddresses(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 hydrateInitialState(state: CheckoutInitialState): Action {\n return {\n type: CheckoutHydrateActionType.HydrateInitialState,\n payload: state,\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 { 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 } 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 { 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 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 './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 { 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 { 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 return concat(\n of(createAction(SpamProtectionActionType.InitializeRequested, undefined)),\n defer(async () => {\n const spamProtectionElementId = options\n ? options.containerId\n : 'spamProtectionContainer';\n\n const element = document.getElementById(spamProtectionElementId);\n\n if (element) {\n this._googleRecaptcha.reset(spamProtectionElementId);\n }\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\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","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 { 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\n .load()\n .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 .catch((err) => {\n throw err;\n });\n }\n\n reset(containerId: string): void {\n const element = document.getElementById(containerId);\n\n element?.remove();\n this._recaptcha?.reset(this._widgetId);\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 { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { EmptyCartError } from '../cart/errors';\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\n .post(url, { body: { token }, headers, timeout })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\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","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 { 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 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 { 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","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 { 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 { 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 { 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","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 { 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","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 { createExtensionWebWorker } from './create-extension-web-worker';\nimport { ExtensionNotFoundError } from './errors';\nimport { ExtensionRegion, ExtensionType } from './extension';\nimport { ExtensionAction, ExtensionActionType } from './extension-actions';\nimport { ExtensionIframe } from './extension-iframe';\nimport { ExtensionRequestSender } from './extension-request-sender';\nimport { WorkerExtensionMessenger } from './worker-extension-messenger';\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 workerExtensionMessenger: WorkerExtensionMessenger,\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 } = state.config.getStoreConfigOrThrow();\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 if (extension.type === ExtensionType.Worker) {\n const worker = createExtensionWebWorker(extension.url);\n\n workerExtensionMessenger.add(extension.id, worker);\n } else {\n const iframe = new ExtensionIframe(container, extension, {\n cartId,\n parentOrigin: parseUrl(checkoutLink).origin,\n });\n\n await iframe.attach();\n }\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","export function createExtensionWebWorker(url: string): Worker {\n if (!window.Worker) {\n throw new Error(\n `Unable to load the extension's web worker: your browser does not support Web Workers.`,\n );\n }\n\n try {\n const blob = URL.createObjectURL(\n new Blob(\n [\n `importScripts=((i)=>(...a)=>i(...a.map((u)=>''+new URL(u,\"${url}\"))))(importScripts);importScripts(\"${url}\")`,\n ],\n { type: 'text/javascript' },\n ),\n );\n\n return new Worker(blob);\n } catch (error) {\n throw new Error(`Unable to load the extension's web worker`);\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","/**\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","export type ExtensionCommand =\n | ReloadCheckoutCommand\n | ShowLoadingIndicatorCommand\n | SetIframeStyleCommand\n | ReRenderShippingForm\n | ReRenderShippingStep;\n\nexport enum ExtensionCommandType {\n ReloadCheckout = 'EXTENSION:RELOAD_CHECKOUT',\n ShowLoadingIndicator = 'EXTENSION:SHOW_LOADING_INDICATOR',\n SetIframeStyle = 'EXTENSION:SET_IFRAME_STYLE',\n ReRenderShippingForm = 'EXTENSION:RE_RENDER_SHIPPING_FORM',\n ReRenderShippingStep = 'EXTENSION:RE_RENDER_SHIPPING_STEP',\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 ReRenderShippingForm {\n type: ExtensionCommandType.ReRenderShippingForm;\n}\n\nexport interface ReRenderShippingStep {\n type: ExtensionCommandType.ReRenderShippingStep;\n}\nexport interface ExtensionCommandMap {\n [ExtensionCommandType.ReloadCheckout]: ReloadCheckoutCommand;\n [ExtensionCommandType.ShowLoadingIndicator]: ShowLoadingIndicatorCommand;\n [ExtensionCommandType.SetIframeStyle]: SetIframeStyleCommand;\n [ExtensionCommandType.ReRenderShippingForm]: ReRenderShippingForm;\n [ExtensionCommandType.ReRenderShippingStep]: ReRenderShippingStep;\n}\n","export type ExtensionQuery = GetConsignmentsQuery;\n\nexport enum ExtensionQueryType {\n GetConsignments = 'EXTENSION:GET_CONSIGNMENTS',\n}\n\nexport interface GetConsignmentsQuery {\n type: ExtensionQueryType.GetConsignments;\n payload?: {\n useCache?: boolean;\n };\n}\n\nexport interface ExtensionQueryMap {\n [ExtensionQueryType.GetConsignments]: GetConsignmentsQuery;\n}\n","import { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { WorkerEventListeners, WorkerEventMap } from './WorkerEvent';\n\nexport class WorkerEventListener<\n TEventMap extends WorkerEventMap,\n TContext = undefined,\n> {\n private _isListening: boolean;\n private _listeners: WorkerEventListeners;\n\n constructor(private _worker: Worker) {\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 this._worker.addEventListener('message', this._handleMessage);\n }\n\n stopListen(): void {\n if (!this._isListening) {\n return;\n }\n\n this._isListening = false;\n this._worker.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 const { context, ...event } = messageEvent.data;\n\n this.trigger(event, context);\n }\n}\n","export class WorkerEventPoster {\n constructor(private _worker: Worker, private _context: TContext) {}\n\n post(event: TEvent): void {\n if (!this._worker) {\n throw new Error(\n 'WorkerPoster: Worker is not initialized or creation failed. Cannot post message.',\n );\n }\n\n this._worker.postMessage({ ...event, context: this._context });\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 { StandardError } from '../../common/error/errors';\n\nexport class UnsupportedExtensionQueryError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unable to proceed due to unsupported extension query.');\n\n this.name = 'UnsupportedExtensionQueryError';\n this.type = 'unsupported_extension_query_error';\n }\n}\n","import { WorkerEventListener, WorkerEventPoster } from '../common/worker';\n\nimport {\n ExtensionNotFoundError,\n UnsupportedExtensionCommandError,\n UnsupportedExtensionQueryError,\n} from './errors';\nimport { ExtensionCommandMap, ExtensionCommandType } from './extension-commands';\nimport { ExtensionCommandOrQueryContext, ExtensionMessage } from './extension-message';\nimport { ExtensionQueryMap, ExtensionQueryType } from './extension-queries';\n\nexport class WorkerExtensionMessenger {\n constructor(\n private _workers: { [extensionId: string]: Worker } = {},\n private _commandListeners: {\n [extensionId: string]: WorkerEventListener;\n } = {},\n private _queryListeners: {\n [extensionId: string]: WorkerEventListener;\n } = {},\n ) {}\n\n add(extensionId: string, worker: Worker): void {\n this._workers[extensionId] = worker;\n }\n\n listenForCommand(\n extensionId: string,\n command: T,\n commandHandler: (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => Promise | void,\n ): () => void {\n const worker = this._getWorkerById(extensionId);\n\n if (!this._commandListeners[extensionId]) {\n this._commandListeners[extensionId] = new WorkerEventListener(worker);\n }\n\n const listener = this._commandListeners[extensionId];\n\n listener.listen();\n\n const validCommandType = this._validateCommand(command);\n\n const commandHandlerProxy = (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandOrQueryContext,\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 listenForQuery(\n extensionId: string,\n query: T,\n queryHandler: (\n query: ExtensionQueryMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => Promise | void,\n ): () => void {\n const worker = this._getWorkerById(extensionId);\n\n if (!this._queryListeners[extensionId]) {\n this._queryListeners[extensionId] = new WorkerEventListener(worker);\n }\n\n const listener = this._queryListeners[extensionId];\n\n listener.listen();\n\n const validQueryType = this._validateQuery(query);\n\n const queryHandlerProxy = (\n query: ExtensionQueryMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => {\n if (context?.extensionId === extensionId) {\n queryHandler(query, context);\n }\n };\n\n listener.addListener(validQueryType, queryHandlerProxy);\n\n return () => {\n listener.removeListener(validQueryType, queryHandlerProxy);\n };\n }\n\n stopListen(extensionId: string): void {\n if (this._commandListeners[extensionId]) {\n this._commandListeners[extensionId].stopListen();\n }\n\n if (this._queryListeners[extensionId]) {\n this._queryListeners[extensionId].stopListen();\n }\n }\n\n post(extensionId: string, message: ExtensionMessage): void {\n if (!this._workers[extensionId]) {\n throw new Error(`Worker with extensionId ${extensionId} not found`);\n }\n\n const workerPoster = new WorkerEventPoster(this._workers[extensionId], extensionId);\n\n workerPoster.post(message);\n }\n\n clearCacheById(extensionId: string): void {\n delete this._workers[extensionId];\n }\n\n private _getWorkerById(extensionId: string): Worker {\n const worker = this._workers[extensionId];\n\n if (!worker) {\n throw new ExtensionNotFoundError(`Worker with extensionId ${extensionId} not found`);\n }\n\n return worker;\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 private _validateQuery(query: T): T {\n if (Object.values(ExtensionQueryType).includes(query)) {\n return query;\n }\n\n throw new UnsupportedExtensionQueryError();\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 { 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 { 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\nexport type EventListeners = {\n [key in keyof TEventMap]?: Array<(event: TEventMap[key], context?: TContext) => void>;\n};\n","import { ReadableCheckoutStore } from '../checkout';\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\n\nimport { createExtensionEventPoster } from './create-extension-event-poster';\nimport {\n ExtensionNotFoundError,\n UnsupportedExtensionCommandError,\n UnsupportedExtensionQueryError,\n} from './errors';\nimport { Extension, ExtensionType } from './extension';\nimport { ExtensionCommandMap, ExtensionCommandType } from './extension-commands';\nimport { ExtensionCommandOrQueryContext, ExtensionMessage } from './extension-message';\nimport { ExtensionQueryMap, ExtensionQueryType } from './extension-queries';\nimport { WorkerExtensionMessenger } from './worker-extension-messenger';\n\nexport class ExtensionMessenger {\n private _extensions: Extension[] | undefined;\n\n constructor(\n private _store: ReadableCheckoutStore,\n private _workerExtensionMessenger: WorkerExtensionMessenger,\n private _commandListeners: {\n [extensionId: string]: IframeEventListener;\n } = {},\n private _queryListeners: {\n [extensionId: string]: IframeEventListener;\n } = {},\n private _posters: { [extensionId: string]: IframeEventPoster } = {},\n ) {}\n\n clearCacheByRegion(region: string): void {\n const extension = this._getExtensionByRegion(region);\n\n if (extension.type === ExtensionType.Worker) {\n this._workerExtensionMessenger.clearCacheById(extension.id);\n\n return;\n }\n\n this.clearCacheById(extension.id);\n }\n\n clearCacheById(extensionId: string): void {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n this._workerExtensionMessenger.clearCacheById(extension.id);\n\n return;\n }\n\n if (this._commandListeners[extensionId]) {\n delete this._commandListeners[extensionId];\n }\n\n if (this._queryListeners[extensionId]) {\n delete this._queryListeners[extensionId];\n }\n\n if (this._posters[extensionId]) {\n delete this._posters[extensionId];\n }\n }\n\n listenForCommand(\n extensionId: string,\n command: T,\n commandHandler: (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => Promise | void,\n ): () => void {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n return this._workerExtensionMessenger.listenForCommand(\n extensionId,\n command,\n commandHandler,\n );\n }\n\n if (!this._commandListeners[extensionId]) {\n this._commandListeners[extensionId] = new IframeEventListener(extension.url);\n }\n\n const listener = this._commandListeners[extensionId];\n\n listener.listen();\n\n const validCommandType = this._validateCommand(command);\n\n const commandHandlerProxy = (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandOrQueryContext,\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 listenForQuery(\n extensionId: string,\n query: T,\n queryHandler: (\n query: ExtensionQueryMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => Promise | void,\n ): () => void {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n return this._workerExtensionMessenger.listenForQuery(extensionId, query, queryHandler);\n }\n\n if (!this._queryListeners[extensionId]) {\n this._queryListeners[extensionId] = new IframeEventListener(extension.url);\n }\n\n const listener = this._queryListeners[extensionId];\n\n listener.listen();\n\n const validQueryType = this._validateQuery(query);\n\n const queryHandlerProxy = (\n query: ExtensionQueryMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => {\n if (context?.extensionId === extensionId) {\n queryHandler(query, context);\n }\n };\n\n listener.addListener(validQueryType, queryHandlerProxy);\n\n return () => {\n listener.removeListener(validQueryType, queryHandlerProxy);\n };\n }\n\n stopListen(extensionId: string): void {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n this._workerExtensionMessenger.stopListen(extensionId);\n\n return;\n }\n\n if (this._commandListeners[extensionId]) {\n this._commandListeners[extensionId].stopListen();\n }\n\n if (this._queryListeners[extensionId]) {\n this._queryListeners[extensionId].stopListen();\n }\n }\n\n post(extensionId: string, message: ExtensionMessage): void {\n try {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n this._workerExtensionMessenger.post(extensionId, message);\n\n return;\n }\n\n if (!this._posters[extensionId]) {\n this._posters[extensionId] =\n createExtensionEventPoster(extension);\n }\n\n this._posters[extensionId].post(message);\n } catch (error) {\n this.clearCacheById(extensionId);\n // eslint-disable-next-line no-console\n console.log(\n `Unable to post event to extension(${extensionId}) because extension iframe is not mounted.\\nThe event that could not be delivered:`,\n message,\n );\n }\n }\n\n private _getExtensionById(extensionId: string): Extension {\n this._getExtensions();\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 _getExtensionByRegion(region: string): Extension {\n this._getExtensions();\n\n const extension = this._extensions?.find((e) => e.region === region);\n\n if (!extension) {\n throw new ExtensionNotFoundError(\n `Unable to proceed due to no extension found for region: ${region}.`,\n );\n }\n\n return extension;\n }\n\n private _getExtensions(): void {\n if (this._extensions) {\n return;\n }\n\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\n private _validateCommand(command: T): T {\n if (Object.values(ExtensionCommandType).includes(command)) {\n return command;\n }\n\n throw new UnsupportedExtensionCommandError();\n }\n private _validateQuery(query: T): T {\n if (Object.values(ExtensionQueryType).includes(query)) {\n return query;\n }\n\n throw new UnsupportedExtensionQueryError();\n }\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 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\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 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 { 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: number, 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 {\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 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 | undefined {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n return;\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) {\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 if (!createCheckoutSessionConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\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: `${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 * 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\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 let paymentMethod: PaymentMethod;\n\n try {\n paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n } catch (_e) {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n paymentMethod = this.paymentIntegrationService\n .getState()\n .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","export interface Features {\n [featureName: string]: boolean | undefined;\n}\n\nexport default function isExperimentEnabled(\n features: Features,\n experimentName: string,\n fallbackValue = true,\n): boolean {\n return features[experimentName] ?? fallbackValue;\n}\n","export const BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION = '3.128.0';\nexport const BRAINTREE_SDK_DEFAULT_VERSION = '3.123.2';\nexport const BRAINTREE_SDK_STABLE_VERSION = '3.106.0';\n","import { find } from 'lodash';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport { BraintreeHostWindow } from './braintree';\nimport {\n BRAINTREE_SDK_DEFAULT_VERSION,\n BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION,\n BRAINTREE_SDK_STABLE_VERSION,\n} from './braintree-sdk-verison';\n\nexport default class BraintreeSDKVersionManager {\n private braintreeWindow: BraintreeHostWindow = window;\n\n constructor(private paymentIntegrationService: PaymentIntegrationService) {}\n\n getSDKVersion() {\n const state = this.paymentIntegrationService.getState();\n const storeConfig = state.getStoreConfig();\n const features = storeConfig?.checkoutSettings.features || {};\n\n const preloadedVersion = this.getPreloadedSDKVersion();\n\n if (preloadedVersion) {\n return preloadedVersion;\n }\n\n if (isExperimentEnabled(features, 'PAYPAL-5809.braintree_hosted_fields_fix_version')) {\n return BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION;\n }\n\n if (isExperimentEnabled(features, 'PAYPAL-5636.update_braintree_sdk_version')) {\n return BRAINTREE_SDK_DEFAULT_VERSION;\n }\n\n return BRAINTREE_SDK_STABLE_VERSION;\n }\n\n private getPreloadedSDKVersion(): void | string {\n const braintree = this.braintreeWindow.braintree;\n\n if (braintree) {\n const preloadedVersion = find<{ VERSION?: string }>(\n Object.values(braintree),\n (module) => !!module.VERSION,\n );\n\n return preloadedVersion?.VERSION;\n }\n }\n}\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","import { Address } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport * 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(\n options: BraintreeThreeDSecureOptions,\n callback?: Braintree3DSVerifyCardCallback,\n ): Promise;\n cancelVerifyCard(): Promise;\n on(\n event: K,\n handler: BraintreeThreeDSecureEventMap[K],\n ): void;\n}\n\nexport type Braintree3DSVerifyCardCallback = (\n verifyError: Braintree3DSVerifyCardError,\n payload: Braintree3DSVerifyCardPayload,\n) => void;\n\nexport interface BraintreeThreeDSecureEventMap {\n 'customer-canceled': () => void;\n}\n\nexport interface Braintree3DSVerifyCardError {\n code: string;\n}\n\nexport interface Braintree3DSVerifyCardPayload {\n nonce: string;\n}\n\nexport interface BraintreeThreeDSecureCreatorConfig extends BraintreeModuleCreatorConfig {\n version?: number;\n}\n\nexport interface BraintreeThreeDSecureOptions {\n nonce: string;\n amount: number | string;\n challengeRequested?: boolean;\n showLoader?: boolean;\n bin?: string;\n additionalInformation?: {\n acsWindowSize?: '01' | '02' | '03' | '04' | '05';\n };\n collectDeviceData?: boolean;\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\nexport enum BraintreeOrderStatus {\n Completed = 'COMPLETED',\n Pending = 'PENDING',\n Failed = 'FAILED',\n}\n\nexport interface BraintreeOrderStatusData {\n status: BraintreeOrderStatus;\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 non-instant payment methods\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 BraintreeOrderSavedResponse {\n body: {\n additional_action_required: {\n data: {\n order_id_saved_successfully: string;\n };\n };\n };\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 binDetails?: {\n bin: string;\n };\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\nexport interface BraintreeRedirectError {\n body: {\n additional_action_required: {\n data: {\n redirect_url: string;\n };\n };\n };\n}\n\nexport default interface BillingAddress extends Address {\n id: string;\n email?: string;\n}\n\nexport enum BraintreeSupportedCardBrands {\n Visa = 'visa',\n Mastercard = 'mastercard',\n AmericanExpress = 'american-express',\n DinersClub = 'diners-club',\n Discover = 'discover',\n Jcb = 'jcb',\n UnionPay = 'union-pay',\n Maestro = 'maestro',\n Elo = 'elo',\n Mir = 'mir',\n Hiper = 'hiper',\n Hipercard = 'hipercard',\n}\n\nexport 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 interface BraintreeRequestData {\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","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 { 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 enableCheckoutPaywallBanner?: boolean;\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 paypalBNPLConfiguration?: PayPalBNPLConfigurationItem[] | null;\n nonce?: string;\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 preventCursorJumps?: boolean;\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: (err: null | undefined | BraintreeError) => 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 BNPL Configurator related types\n *\n */\nexport interface PayPalBNPLConfigurationItem {\n id: string;\n name: string;\n status: boolean;\n styles: Record;\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 {\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 { BraintreeModuleName } from './braintree';\nimport {\n BRAINTREE_SDK_DEFAULT_VERSION,\n BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION,\n BRAINTREE_SDK_STABLE_VERSION,\n} from './braintree-sdk-verison';\n\nexport const BRAINTREE_SDK_SCRIPTS_INTEGRITY = {\n [BRAINTREE_SDK_STABLE_VERSION]: {\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 [BRAINTREE_SDK_DEFAULT_VERSION]: {\n [BraintreeModuleName.Client]:\n 'sha384-o+nbQGcwNNxIBeXeu3+XmbSq+Cg8R3EN3N0l5hXCgMMU2RGY0t1z0LroSEIAbfAO',\n [BraintreeModuleName.PaypalCheckout]:\n 'sha384-WrfbWPBS4mH86GAoycPSgiH8hQ8KH7A67C93Hjhunv/xhNk2YpBn3wbFA4Fhg9U/',\n [BraintreeModuleName.Paypal]:\n 'sha384-VF389nvvrRUgDsTXMxTYORDtVegB9IQa3Cxr//DyJnLYnz8/X8VCzEvck2c+Megt',\n [BraintreeModuleName.LocalPayment]:\n 'sha384-tZKx2rEQbfmZpoPSY5VPmJEhaq4X75dLvwHMs3VE9U+C8lPyw+hWTIL1+GPvWCIH',\n [BraintreeModuleName.DataCollector]:\n 'sha384-E6k3wOpP7syCDDwaRDLF06942Y00NkbwJvWi2OQXwwKzGwG5fd3E7RFUvCCecfvO',\n [BraintreeModuleName.UsBankAccount]:\n 'sha384-258FON8LZGG0W9Qaz4Jij83pZHu30YnKjJA7gNulLBh6CclkucgF+tHDQuYFRYfW',\n [BraintreeModuleName.GooglePayment]:\n 'sha384-taJ2p/0+n0VH328POAoBiuEbL3tnHUTE9S42hK1V+Txs3X+QYjZOyKW35JgHRFfO',\n [BraintreeModuleName.ThreeDSecure]:\n 'sha384-+NSZH4Zj3sO5bdWvPKhU5N16QDxeueTVTnUVeleeESkhLSaz4Ob1hh/5myecc9Ym',\n [BraintreeModuleName.VisaCheckout]:\n 'sha384-66DiBjghxk1OmBj8aksN8gbQ+CwoQcx1vPfiXUN08g1iQVM+BwewF0p7toM3i7SS',\n [BraintreeModuleName.Venmo]:\n 'sha384-B5UwY42kE4RoLoWbQ7YpqosUlUad2/DlGWiw0HhoZbSPk30CQAaSA10ohyLDTkDU',\n [BraintreeModuleName.HostedFields]:\n 'sha384-Aw9EesSaUeWxe36PqEHiOyOyOq8M6CIb1gw7/yHNVPRzGtFXXcd2OQ8qXrIlOj2P',\n [BraintreeModuleName.Fastlane]:\n 'sha384-rhBL1hpZ71JqG+2TsT0Dih47mbjx8cjJCpeZjk9tw3df1gFMKfCTmMyZunhr7H4Y',\n },\n [BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION]: {\n [BraintreeModuleName.Client]:\n 'sha384-0WNxksIpRP+fYZiIdr12g6DBUQfLDzYCQJZtR/C8KkcwSGhPHfcFp3tTaGcMyFTq',\n [BraintreeModuleName.PaypalCheckout]:\n 'sha384-lWM1jk4BOxoDNV6Kop7tVNvQgINlmEVz0c/OwM+HNHK3QC8xqwd54Ovrt2QRDTjh',\n [BraintreeModuleName.Paypal]:\n 'sha384-fXUmVxC2EMZBDXZ7eTHSTL/LFBrHej/MSXT/vTBXvra4lzgLNGvREAp+x0GYObuH',\n [BraintreeModuleName.LocalPayment]:\n 'sha384-pha1xGuGSkmZH5x9aqHvRaO4xLea7rmQ/79PFj9zxNzxuFcOWZg7gOP7FibygOEC',\n [BraintreeModuleName.DataCollector]:\n 'sha384-Q6PI2F9eekWbAxhroybl+aEcvqhdowN/EQlGwBUyJOzPFn9982u9xl6SU6XfGKzc',\n [BraintreeModuleName.UsBankAccount]:\n 'sha384-W3RLQSKJL1tQ3+Y7mP6tmkamtZ8bV4Yw/XxL9Jj5JtXHraD8loMF8hAIG5m2zK7F',\n [BraintreeModuleName.GooglePayment]:\n 'sha384-TITQMsFWA3elDNGP2mWz2oKBo4qjt+TlqzovcaPoeBiAh/wPBi6nae50ADdgU1/i',\n [BraintreeModuleName.ThreeDSecure]:\n 'sha384-YiycYN89ZlL/Evcaq4y1ajW1mhd7JYfZBDuOwHtIn4/Jnm20GL+/XCM+zYAwWD8D',\n [BraintreeModuleName.VisaCheckout]:\n 'sha384-/OdaTv9qrkKzjObtUe6yzfDhHozFW/+uXlrSl736sOZRJpjGQETvpYXqMFFg69xv',\n [BraintreeModuleName.Venmo]:\n 'sha384-dA+ojdW9vbJS4JavcXyOs9d5uZHJg5dNtYupoPSH2zsXIiYDVS5amLb/u8qmQ6oz',\n [BraintreeModuleName.HostedFields]:\n 'sha384-31ZkS58+iaWsW06ftW52zzVZFp43WPd7pNYRiddYynSNg6Oh7WGbSFGorAUH6T1z',\n [BraintreeModuleName.Fastlane]:\n 'sha384-jlbrwNvL3HvLAUCtLSmrnQ2GH1udCUrRS/bVmReAS5fuIVvcW8Pko/Gkg82tlgtr',\n },\n};\n","export enum ApplePayGatewayType {\n BRAINTREE = 'braintree',\n BRAINTREE_FASTLANE = 'braintreeacceleratedcheckout',\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 BraintreeSDKVersionManager from './braintree-sdk-version-manager';\nimport isManageableBraintreeSDKVersion from './isManageableBraintreeSDKVersion';\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 constructor(\n private scriptLoader: ScriptLoader,\n private braintreeHostWindow: BraintreeHostWindow,\n private braintreeSDKVersionManager: BraintreeSDKVersionManager,\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 braintreeSdkVersion = this.braintreeSDKVersionManager.getSDKVersion();\n\n const scriptPath = `//js.braintreegateway.com/web/${braintreeSdkVersion}/js/${fileName}`;\n\n const integrity = isManageableBraintreeSDKVersion(braintreeSdkVersion)\n ? this.getIntegrityValuesByModuleName(braintreeModuleName, braintreeSdkVersion)\n : undefined;\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(\n moduleName: BraintreeModuleName,\n version: keyof typeof BRAINTREE_SDK_SCRIPTS_INTEGRITY,\n ): string {\n const integrity = BRAINTREE_SDK_SCRIPTS_INTEGRITY[version][moduleName];\n\n if (!integrity) {\n throw new Error('Unexpected fileName value');\n }\n\n return integrity;\n }\n}\n","import { BRAINTREE_SDK_SCRIPTS_INTEGRITY } from './braintree-sdk-scripts-integrity';\n\nfunction isManageableBraintreeSDKVersion(\n version: string,\n): version is keyof typeof BRAINTREE_SDK_SCRIPTS_INTEGRITY {\n return version in BRAINTREE_SDK_SCRIPTS_INTEGRITY;\n}\n\nexport default isManageableBraintreeSDKVersion;\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","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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory 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 private _applePayScriptLoader: ApplePayScriptLoader,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithApplePayCustomerInitializeOptions,\n ): Promise {\n const { methodId, applepay } = options;\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 await this._applePayScriptLoader.loadSdk();\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 (\n this._paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE &&\n this._paymentMethod.clientToken\n ) {\n this._braintreeSdk.initialize(this._paymentMethod.clientToken);\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 applePayButton = this._createApplePayButtonElement();\n\n container.appendChild(applePayButton);\n\n return applePayButton;\n }\n\n private _createApplePayButtonElement(): HTMLElement {\n const applePayButton = document.createElement('apple-pay-button');\n\n applePayButton.setAttribute('buttonstyle', 'black');\n applePayButton.setAttribute('type', 'plain');\n applePayButton.setAttribute(\n 'style',\n '--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;',\n );\n\n return applePayButton;\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","import ApplePayWindow from './apple-pay-window';\nimport isApplePayWindow from './is-apple-pay-window';\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 ApplePayWindow from './apple-pay-window';\n\nexport default function isApplePayWindow(window: Window): window is ApplePayWindow {\n return 'ApplePaySession' in window;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { assertApplePayWindow } from './apple-pay-session-factory';\nimport isApplePaySdkWindow from './is-apple-pay-sdk-window';\n\nexport default class ApplePayScriptLoader {\n private sdkVersion = '1.latest';\n\n constructor(private scriptLoader: ScriptLoader) {}\n\n async loadSdk() {\n if (isApplePaySdkWindow(window)) {\n return;\n }\n\n await this.scriptLoader.loadScript(\n `https://applepay.cdn-apple.com/jsapi/${this.sdkVersion}/apple-pay-sdk.js`,\n );\n\n assertApplePayWindow(window);\n }\n}\n","interface ApplePaySdkWindow extends Window {\n ApplePaySDK?: {\n origin: string;\n publicPath: string;\n token: string | undefined;\n };\n}\n\nexport default function isApplePaySdkWindow(window: Window): window is ApplePaySdkWindow {\n return 'ApplePaySDK' in window;\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\n} 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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayCustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n\n return new ApplePayCustomerStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), window, braintreeSDKVersionManager),\n ),\n new ApplePayScriptLoader(new ScriptLoader()),\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 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 { 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 | object;\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 { PayPalBNPLConfigurationItem } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n BuyNowCartRequestBody,\n HostedInstrument,\n ShippingOption,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n/**\n *\n * BigCommerce Payments Funding sources\n *\n */\nexport type FundingType = string;\n// TODO: rename BigCommercePaymentsSDKFunding to PayPalSDKFunding\nexport interface BigCommercePaymentsSDKFunding {\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 * BigCommerce Payments SDK\n *\n */\n\nexport interface BigCommercePaymentsCardFieldsConfig {\n inputEvents: {\n onChange(data: BigCommercePaymentsCardFieldsState): void;\n onFocus(data: BigCommercePaymentsCardFieldsState): void;\n onBlur(data: BigCommercePaymentsCardFieldsState): void;\n onInputSubmitRequest(data: BigCommercePaymentsCardFieldsState): void;\n };\n createVaultSetupToken?: (data: BigCommercePaymentsCardFieldsState) => void;\n createOrder?: () => Promise;\n style: BigCommercePaymentsHostedFieldsRenderOptions['styles'];\n onApprove(data: BigCommercePaymentsCardFieldsOnApproveData): void;\n onError(): void;\n}\n\nexport interface BigCommercePaymentsCardFieldsOnApproveData {\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 BigCommercePaymentsCardFieldsFieldData {\n isFocused: boolean;\n isEmpty: boolean;\n isValid: boolean;\n isPotentiallyValid: boolean;\n}\n\ntype BigCommercePaymentsCardFieldsCard = BigCommercePaymentsHostedFieldsCard;\n\nexport interface BigCommercePaymentsCardFieldsState {\n cards: BigCommercePaymentsCardFieldsCard[];\n emittedBy: string;\n isFormValid: boolean;\n errors: string[];\n fields: {\n cardCvvField: BigCommercePaymentsCardFieldsFieldData;\n cardNumberField: BigCommercePaymentsCardFieldsFieldData;\n cardNameField?: BigCommercePaymentsCardFieldsFieldData;\n cardExpiryField: BigCommercePaymentsCardFieldsFieldData;\n };\n}\n\nexport interface BigCommercePaymentsFields {\n render(container: HTMLElement | string): Promise;\n clear(): void;\n removeClass(className: string): Promise;\n close(): Promise;\n}\n\ninterface BigCommercePaymentsFieldsInitializationData {\n placeholder?: string;\n}\n\nexport interface BigCommercePaymentsCardFields {\n isEligible(): boolean;\n CVVField(config?: BigCommercePaymentsFieldsInitializationData): BigCommercePaymentsFields;\n ExpiryField(config?: BigCommercePaymentsFieldsInitializationData): BigCommercePaymentsFields;\n NameField(config?: BigCommercePaymentsFieldsInitializationData): BigCommercePaymentsFields;\n NumberField(config?: BigCommercePaymentsFieldsInitializationData): BigCommercePaymentsFields;\n submit(config?: BigCommercePaymentsCardFieldsSubmitConfig): Promise;\n getState(): Promise;\n}\n\nexport interface BigCommercePaymentsCardFieldsSubmitConfig {\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: (\n data: BigCommercePaymentsCardFieldsConfig,\n ) => 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: BigCommercePaymentsSDKFunding;\n HostedFields: {\n isEligible(): boolean;\n render(\n data: BigCommercePaymentsHostedFieldsRenderOptions,\n ): Promise;\n };\n Legal: PayPalLegal & LegalFunding;\n Buttons(options: BigCommercePaymentsButtonsOptions): BigCommercePaymentsButtons;\n PaymentFields(\n options: BigCommercePaymentsPaymentFieldsOptions,\n ): BigCommercePaymentsPaymentFields;\n Messages(options: BigCommercePaymentsMessagesOptions): BigCommercePaymentsMessages;\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 BigCommercePaymentsScriptParams {\n options: {\n 'client-id'?: string;\n 'merchant-id'?: string;\n 'buyer-country'?: string;\n 'disable-funding'?: FundingType[];\n 'enable-funding'?: FundingType[];\n currency?: string;\n commit?: boolean;\n intent?: BigCommercePaymentsIntent;\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 'data-namespace'?: string;\n };\n}\n\nexport enum BigCommercePaymentsIntent {\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 BigCommercePaymentsHostWindow extends Window {\n bigCommercePaymentsPayPalSDK?: PayPalSDK;\n}\n\n/**\n *\n * BigCommerce Payments Initialization Data\n *\n */\nexport interface BigCommercePaymentsInitializationData {\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?: BigCommercePaymentsIntent;\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 isAppSwitchEnabled?: boolean;\n paypalBNPLConfiguration?: PayPalBNPLConfigurationItem[];\n}\n\n/**\n *\n * BigCommerce Payments BuyNow\n *\n */\nexport interface PayPalBuyNowInitializeOptions {\n getBuyNowCartRequestBody(): BuyNowCartRequestBody;\n}\n\n/**\n *\n * BigCommerce Payments Hosted Fields\n *\n */\nexport interface BigCommercePaymentsHostedFieldsRenderOptions {\n fields?: {\n number?: BigCommercePaymentsHostedFieldOption;\n cvv?: BigCommercePaymentsHostedFieldOption;\n expirationDate?: BigCommercePaymentsHostedFieldOption;\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 BigCommercePaymentsHostedFieldOption {\n selector: string;\n placeholder?: string;\n}\n\nexport interface BigCommercePaymentsHostedFields {\n submit(\n options?: BigCommercePaymentsHostedFieldsSubmitOptions,\n ): Promise;\n getState(): BigCommercePaymentsHostedFieldsState;\n on(eventName: string, callback: (event: BigCommercePaymentsHostedFieldsState) => void): void;\n}\n\nexport interface BigCommercePaymentsHostedFieldsSubmitOptions {\n contingencies?: Array<'3D_SECURE'>;\n cardholderName?: string;\n}\n\nexport interface BigCommercePaymentsHostedFieldsApprove {\n orderId: string;\n liabilityShift?: 'POSSIBLE' | 'NO' | 'UNKNOWN';\n}\n\nexport interface BigCommercePaymentsHostedFieldsState {\n cards: BigCommercePaymentsHostedFieldsCard[];\n emittedBy: string;\n fields: {\n number?: BigCommercePaymentsHostedFieldsFieldData;\n expirationDate?: BigCommercePaymentsHostedFieldsFieldData;\n expirationMonth?: BigCommercePaymentsHostedFieldsFieldData;\n expirationYear?: BigCommercePaymentsHostedFieldsFieldData;\n cvv?: BigCommercePaymentsHostedFieldsFieldData;\n postalCode?: BigCommercePaymentsHostedFieldsFieldData;\n };\n}\n\nexport interface BigCommercePaymentsHostedFieldsCard {\n type: string;\n niceType: string;\n code: {\n name: string;\n size: number;\n };\n}\n\nexport interface BigCommercePaymentsHostedFieldsFieldData {\n container: HTMLElement;\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\n/**\n *\n * BigCommerce Payments Buttons\n *\n */\nexport interface BigCommercePaymentsButtons {\n render(id: string): void;\n close(): void;\n isEligible(): boolean;\n hasReturned?(): boolean;\n resume?(): void;\n}\n\nexport interface BigCommercePaymentsButtonsOptions {\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 phone?: {\n phone_number: {\n national_number: string;\n };\n };\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 * BigCommerce Payments Payment fields\n *\n */\nexport interface BigCommercePaymentsPaymentFields {\n render(id: string): void;\n}\n\nexport interface BigCommercePaymentsPaymentFieldsOptions {\n style?: BigCommercePaymentsFieldsStyleOptions;\n fundingSource: string;\n fields: {\n name?: {\n value?: string;\n };\n email?: {\n value?: string;\n };\n };\n}\n\nexport interface BigCommercePaymentsFieldsStyleOptions {\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 * BigCommercePayments Messages\n */\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface BigCommercePaymentsMessages {\n render(id: string): void;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface BigCommercePaymentsMessagesOptions {\n amount: number;\n placement: string;\n style?: BigCommercePaymentsMessagesStyleOptions;\n fundingSource?: string;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface BigCommercePaymentsMessagesStyleOptions {\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 fastlaneToken?: string;\n methodId?: string;\n gatewayId?: string;\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 BigCommercePaymentsRequestSender from './bigcommerce-payments-request-sender';\nimport BigCommercePaymentsScriptLoader from './bigcommerce-payments-script-loader';\nimport {\n BigCommercePaymentsInitializationData,\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n PayPalCreateOrderCardFieldsResponse,\n PayPalCreateOrderRequestBody,\n PayPalOrderDetails,\n PayPalOrderStatus,\n PayPalSDK,\n StyleButtonColor,\n StyleButtonLabel,\n StyleButtonShape,\n} from './bigcommerce-payments-types';\n\nexport default class BigCommercePaymentsIntegrationService {\n private paypalSdk?: PayPalSDK;\n\n constructor(\n private formPoster: FormPoster,\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsRequestSender: BigCommercePaymentsRequestSender,\n private bigCommercePaymentsScriptLoader: BigCommercePaymentsScriptLoader,\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.bigCommercePaymentsScriptLoader.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.bigCommercePaymentsRequestSender.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.bigCommercePaymentsRequestSender.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.bigCommercePaymentsRequestSender.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.bigCommercePaymentsRequestSender.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: address?.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 phone: payer.phone?.phone_number?.national_number,\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","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 } 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 './bigcommerce-payments-types';\n\nexport default class BigCommercePaymentsRequestSender {\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/bigcommerce_payments`;\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 = 'bigcommerce_payments',\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 BigCommercePaymentsHostWindow,\n BigCommercePaymentsInitializationData,\n BigCommercePaymentsScriptParams,\n ComponentsScriptType,\n FundingType,\n PayPalSDK,\n} from './bigcommerce-payments-types';\n\nexport default class BigCommercePaymentsScriptLoader {\n private window: BigCommercePaymentsHostWindow;\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: BigCommercePaymentsScriptParams,\n forceLoad = false,\n ): Promise {\n if (!this.window.bigCommercePaymentsPayPalSDK || 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.bigCommercePaymentsPayPalSDK) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.bigCommercePaymentsPayPalSDK;\n }\n\n private getPayPalSdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage = true,\n ): BigCommercePaymentsScriptParams {\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 === 'bigcommerce_payments_creditcards';\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 enableVenmoFunding = isVenmoEnabled ? ['venmo'] : [];\n const disableVenmoFunding = !isVenmoEnabled ? ['venmo'] : [];\n const disableAPMsFunding = availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n );\n const googlePayComponent: ComponentsScriptType = isGooglePayEnabled ? ['googlepay'] : [];\n const cardFieldsComponent: ComponentsScriptType = initializesOnCheckoutPage\n ? ['card-fields']\n : [];\n const disableFunding: FundingType[] = this.filterFundingOptions([\n ...disableCardFunding,\n ...disableCreditFunding,\n ...disableVenmoFunding,\n ...disableAPMsFunding,\n ]);\n const enableFunding: FundingType[] = this.filterFundingOptions([\n ...enableCardFunding,\n ...enableCreditFunding,\n ...enableVenmoFunding,\n ...enabledAlternativePaymentMethods,\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 'data-namespace': 'bigCommercePaymentsPayPalSDK',\n },\n };\n }\n\n private filterFundingOptions(fundingOptions: FundingType[] | undefined): FundingType[] {\n const fundingTypesToBeFiltered = ['klarna', 'afterpay'];\n\n if (!fundingOptions) {\n return [];\n }\n\n return fundingOptions.filter(\n (fundingOption: FundingType) => !fundingTypesToBeFiltered.includes(fundingOption),\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 BigCommercePaymentsIntegrationService,\n BigCommercePaymentsRequestSender,\n BigCommercePaymentsScriptLoader,\n} from './index';\n\nconst createBigCommercePaymentsIntegrationService = (\n paymentIntegrationService: PaymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new BigCommercePaymentsIntegrationService(\n createFormPoster(),\n paymentIntegrationService,\n new BigCommercePaymentsRequestSender(createRequestSender({ host: getHost() })),\n new BigCommercePaymentsScriptLoader(getScriptLoader()),\n );\n};\n\nexport default createBigCommercePaymentsIntegrationService;\n","const DefaultCheckoutButtonHeight = 40;\n\nexport default DefaultCheckoutButtonHeight;\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsCustomerInitializeOptions, {\n WithBigCommercePaymentsCustomerInitializeOptions,\n} from './bigcommerce-payments-customer-initialize-options';\n\nexport default class BigCommercePaymentsCustomerStrategy implements CustomerStrategy {\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBigCommercePaymentsCustomerInitializeOptions,\n ): Promise {\n const { bigcommerce_payments, 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 (!bigcommerce_payments) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments\" argument is not provided.',\n );\n }\n\n if (!bigcommerce_payments.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments.container\" argument is not provided.',\n );\n }\n\n if (bigcommerce_payments.onClick && typeof bigcommerce_payments.onClick !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments.onClick\" argument is not a function.',\n );\n }\n\n this.onError = bigcommerce_payments.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 const paypalSdk = await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n // eslint-disable-next-line no-console\n console.error(\n '[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n this.renderButton(methodId, bigcommerce_payments);\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 bigcommerce_payments: BigCommercePaymentsCustomerInitializeOptions,\n ): void {\n const { container, onClick, onComplete } = bigcommerce_payments;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const {\n isHostedCheckoutEnabled,\n paymentButtonStyles,\n isAppSwitchEnabled = false,\n } = paymentMethod.initializationData || {};\n const { checkoutTopButtonStyles } = paymentButtonStyles || {};\n\n const defaultCallbacks = {\n ...(isAppSwitchEnabled && {\n appSwitchWhenAvailable: true,\n }),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder('bigcommerce_payments'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.tokenizePayment(methodId, orderID),\n ...(onClick && { onClick: () => onClick() }),\n };\n\n const hostedCheckoutCallbacks = {\n ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n }),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const buttonRenderOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.bigCommercePaymentsIntegrationService.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 if (paypalButton.hasReturned?.() && isAppSwitchEnabled) {\n paypalButton.resume?.();\n } else {\n paypalButton.render(`#${container}`);\n }\n } else {\n this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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 =\n this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsCustomerStrategy from './bigcommerce-payments-customer-strategy';\n\nconst createBigCommercePaymentsCustomerStrategy: CustomerStrategyFactory<\n BigCommercePaymentsCustomerStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsCustomerStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsCustomerStrategy, [\n { id: 'bigcommerce_payments' },\n]);\n","import { HostedInstrument, NonceInstrument } from './payment';\n\ntype PaymentInstrument = CardInstrument | AccountInstrument | HostedInstrument | NonceInstrument;\n\nexport default PaymentInstrument;\n\nexport interface 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 { CardInstrument, CustomerAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n/**\n *\n * BigCommerce Payments Funding sources\n *\n */\nexport type FundingType = string;\n\n/**\n *\n * BigCommerce Payments Initialization Data\n *\n */\nexport interface BigCommercePaymentsInitializationData {\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 BCP Fastlane A/B test will be finished\n enabledAlternativePaymentMethods: FundingType[];\n isDeveloperModeApplicable?: boolean;\n intent?: BigCommercePaymentsIntent;\n isAcceleratedCheckoutEnabled?: boolean; // PayPal Fastlane related\n isFastlaneShippingOptionAutoSelectEnabled?: boolean; // PayPal Fastlane related\n isFastlaneStylingEnabled?: boolean;\n isHostedCheckoutEnabled?: boolean;\n isBigCommercePaymentsAnalyticsV2Enabled?: 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 BCP Fastlane A/B test will be finished\n paymentButtonStyles?: Record;\n paypalBNPLConfiguration?: PayPalBNPLConfigurationItem[];\n threeDSVerificationMethod?: string;\n}\n\n/**\n *\n * PayPalHostWindow contains different\n * PayPal Sdk instances for different purposes\n *\n */\nexport interface PayPalHostWindow extends Window {\n bigCommercePaymentsFastlane?: PayPalFastlane;\n bigCommercePaymentsFastlaneSdk?: PayPalFastlaneSdk;\n bigCommercePaymentsMessages?: PayPalMessagesSdk;\n bigCommercePaymentsApms?: PayPalApmSdk;\n bigCommercePaymentsGooglePay?: PayPalGooglePaySdk;\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'?: FundingType[];\n 'disable-funding'?: FundingType[];\n currency?: string;\n commit?: boolean;\n intent?: BigCommercePaymentsIntent;\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 'data-sdk-client-token'?: string;\n };\n}\n\nexport enum BigCommercePaymentsIntent {\n AUTHORIZE = 'authorize',\n CAPTURE = 'capture',\n}\n\nexport type PayPalSdkComponents = Array<\n 'fastlane' | 'messages' | 'buttons' | 'payment-fields' | 'googlepay' | 'three-domain-secure'\n>;\n\n/**\n *\n * PayPal Sdk instances\n *\n */\nexport enum LiabilityShiftEnum {\n Possible = 'POSSIBLE',\n No = 'NO',\n Unknown = 'UNKNOWN',\n Yes = 'YES',\n}\n\nexport interface threeDSecureParameters {\n amount: string;\n currency: string;\n nonce: string;\n threeDSRequested: boolean;\n transactionContext: {\n experience_context: {\n brand_name?: string;\n locale: string;\n return_url: string;\n cancel_url: string;\n };\n };\n}\n\nexport interface PayPalFastlaneSdk {\n ThreeDomainSecureClient: {\n isEligible(params: threeDSecureParameters): Promise;\n show(): Promise;\n };\n Fastlane(options?: PayPalFastlaneOptions): Promise;\n}\n\ninterface ThreeDomainSecureClientShowResponse {\n liabilityShift: LiabilityShiftEnum;\n authenticationState: TDSecureAuthenticationState;\n nonce: string; // Enriched nonce or the original nonce\n}\n\nexport interface PayPalMessagesSdk {\n Messages(options: MessagingOptions): MessagingRender;\n}\n\nexport interface PayPalApmSdk {\n Buttons(options: BigCommercePaymentsButtonsOptions): BigCommercePaymentsButtons;\n PaymentFields(\n options: BigCommercePaymentsPaymentFieldsOptions,\n ): BigCommercePaymentsPaymentFields;\n}\n\nexport interface PayPalGooglePaySdk {\n Googlepay(): GooglePay;\n}\n\nexport enum TDSecureVerificationMethod {\n Always = 'SCA_ALWAYS',\n}\n\nexport enum TDSecureAuthenticationState {\n Succeeded = 'succeeded',\n Cancelled = 'cancelled',\n Errored = 'errored',\n}\n\n/**\n *\n * Google Pay related types\n *\n */\n\ninterface GooglePay {\n config: () => Promise;\n confirmOrder: (confirmOrderConfig: ConfirmOrderConfig) => Promise<{ status: string }>;\n initiatePayerAction: (payerActionConfig: PayerActionConfig) => Promise;\n}\n\ninterface ConfirmOrderConfig {\n orderId: string;\n paymentMethodData: ConfirmOrderData;\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\ninterface PayerActionConfig {\n orderId: 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\n/**\n *\n * BigCommerce Payments Buttons\n *\n */\nexport interface BigCommercePaymentsButtons {\n render(id: string): void;\n close(): void;\n isEligible(): boolean;\n}\n\nexport interface BigCommercePaymentsButtonsOptions {\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 * BigCommerce Payments PaymentFields fields\n *\n */\nexport interface BigCommercePaymentsPaymentFields {\n render(id: string): void;\n}\n\nexport interface BigCommercePaymentsPaymentFieldsOptions {\n style?: BigCommercePaymentsFieldsStyleOptions;\n fundingSource: string;\n fields: {\n name?: {\n value?: string;\n };\n email?: {\n value?: string;\n };\n };\n}\n\nexport interface BigCommercePaymentsFieldsStyleOptions {\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 = 'canceled',\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\nexport interface RedirectError {\n body: {\n additional_action_required: {\n data: {\n redirect_url: string;\n };\n };\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 BigCommercePaymentsInitializationData,\n FundingType,\n PayPalFastlaneSdk,\n PayPalGooglePaySdk,\n PayPalHostWindow,\n PayPalMessagesSdk,\n PayPalSdkConfig,\n} from './bigcommerce-payments-types';\n\nexport default class PayPalSdkHelper {\n private window: PayPalHostWindow;\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.bigCommercePaymentsFastlaneSdk) {\n const config = this.getPayPalFastlaneSdkConfiguration(\n paymentMethod,\n currencyCode,\n sessionId,\n );\n\n await this.loadPayPalSdk(config);\n\n if (!this.window.bigCommercePaymentsFastlaneSdk) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.window.bigCommercePaymentsFastlaneSdk;\n }\n\n async getPayPalGooglePaySdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n if (!this.window.bigCommercePaymentsGooglePay || forceLoad) {\n const paypalSdkScriptConfig = this.getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n initializesOnCheckoutPage,\n );\n\n await this.loadPayPalSdk(paypalSdkScriptConfig);\n }\n\n if (!this.window.bigCommercePaymentsGooglePay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.bigCommercePaymentsGooglePay;\n }\n\n async getPayPalApmsSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n ) {\n if (!this.window.bigCommercePaymentsApms) {\n const config = this.getPayPalApmSdkConfiguration(paymentMethod, currencyCode);\n\n await this.loadPayPalSdk(config);\n\n if (!this.window.bigCommercePaymentsApms) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.window.bigCommercePaymentsApms;\n }\n\n async getPayPalMessages(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n ): Promise {\n if (!this.window.bigCommercePaymentsMessages) {\n const paypalSdkMessagesConfig = this.getPayPalSdkMessagesConfiguration(\n paymentMethod,\n currencyCode,\n );\n\n await this.loadPayPalSdk(paypalSdkMessagesConfig);\n }\n\n if (!this.window.bigCommercePaymentsMessages) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.bigCommercePaymentsMessages;\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 { intent, clientId, merchantId, attributionId } = initializationData;\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit: true,\n components: ['fastlane', 'three-domain-secure'],\n currency: currencyCode,\n intent,\n },\n attributes: {\n 'data-client-metadata-id': sessionId.replace(/-/g, ''),\n 'data-namespace': 'bigCommercePaymentsFastlaneSdk',\n 'data-partner-attribution-id': attributionId,\n 'data-sdk-client-token': clientToken,\n },\n };\n }\n\n private getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage = true,\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 buyerCountry,\n attributionId,\n isHostedCheckoutEnabled,\n isDeveloperModeApplicable,\n } = initializationData;\n\n const commit = isHostedCheckoutEnabled || initializesOnCheckoutPage;\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit,\n components: ['googlepay'],\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 'data-namespace': 'bigCommercePaymentsGooglePay',\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 = this.filterFundingOptions(enabledAlternativePaymentMethods);\n const disableAPMsFunding = this.filterFundingOptions(\n availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n ),\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': 'bigCommercePaymentsApms',\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': 'bigCommercePaymentsMessages',\n 'data-partner-attribution-id': attributionId,\n },\n };\n }\n\n /**\n *\n * Utils methods\n *\n */\n private filterFundingOptions(fundingOptions: FundingType[] | undefined): FundingType[] {\n const fundingTypesToBeFiltered = ['klarna', 'afterpay'];\n\n if (!fundingOptions) {\n return [];\n }\n\n return fundingOptions.filter(\n (fundingOption: FundingType) => !fundingTypesToBeFiltered.includes(fundingOption),\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 { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport PayPalSdkHelper from './paypal-sdk-helper';\n\nexport default function createBigCommercePaymentsSdk(): PayPalSdkHelper {\n return new PayPalSdkHelper(createScriptLoader());\n}\n","interface CookieOptions {\n expires?: Date;\n path?: string;\n domain?: string;\n secure?: boolean;\n}\n\nexport default class CookieStorage {\n static get(name: string): string | null {\n const cookieKey = `${encodeURIComponent(`${name}`)}=`;\n const cookie = document.cookie;\n\n let value = null;\n\n const firstIndex = cookie.indexOf(cookieKey);\n\n if (firstIndex > -1) {\n let lastIndex = cookie.indexOf(';', firstIndex);\n\n if (lastIndex === -1) {\n lastIndex = cookie.length;\n }\n\n value = decodeURIComponent(cookie.substring(firstIndex + cookieKey.length, lastIndex));\n }\n\n return value;\n }\n\n static set(name: string, value: string, options: CookieOptions = { secure: true }) {\n let cookieText = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;\n\n const { expires, path, domain, secure } = options;\n\n if (expires) {\n cookieText += `; expires=${expires.toUTCString()}`;\n } else {\n const now = new Date();\n // info: default cookie expiration time after setup\n const minutes = 60;\n\n now.setTime(now.getTime() + minutes * 60 * 1000);\n\n cookieText += `; expires=${now.toUTCString()}`;\n }\n\n if (path) {\n cookieText += `; path=${path}`;\n }\n\n if (domain) {\n cookieText += `; domain=${domain}`;\n }\n\n if (secure) {\n cookieText += '; secure';\n }\n\n document.cookie = cookieText;\n }\n\n static remove(name: string, options?: CookieOptions) {\n CookieStorage.set(name, '', { expires: new Date(0), ...options });\n }\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 { CookieStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport {\n PayPalFastlane,\n PayPalFastlaneAddress,\n PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneLookupCustomerByEmailResult,\n PayPalFastlaneProfileCard,\n PayPalFastlaneProfileName,\n PayPalFastlaneProfilePhone,\n PayPalFastlaneProfileToBcCustomerDataMappingResult,\n PayPalFastlaneSdk,\n PayPalFastlaneStylesOption,\n PayPalHostWindow,\n} from './bigcommerce-payments-types';\n\nexport default class BigCommercePaymentsFastlaneUtils {\n private window: PayPalHostWindow;\n\n constructor() {\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.bigCommercePaymentsFastlane) {\n const defaultStyles = {\n root: {\n backgroundColorPrimary: 'transparent',\n },\n };\n\n this.window.bigCommercePaymentsFastlane = await paypalFastlaneSdk.Fastlane({\n styles: styles || defaultStyles,\n });\n }\n\n return this.window.bigCommercePaymentsFastlane;\n }\n\n getPayPalFastlaneOrThrow(): PayPalFastlane {\n if (!this.window.bigCommercePaymentsFastlane) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.bigCommercePaymentsFastlane;\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 *\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(sessionId: string): void {\n const expires = new Date();\n\n expires.setDate(expires.getDate() + 14); // 2 weeks expiry\n\n const cookiesOption = {\n expires,\n secure: true,\n };\n\n CookieStorage.set('bc-fastlane-sessionId', sessionId, cookiesOption);\n }\n\n removeStorageSessionId(): void {\n CookieStorage.remove('bc-fastlane-sessionId');\n }\n\n getStorageSessionId(): string {\n return CookieStorage.get('bc-fastlane-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 BigCommercePaymentsFastlaneUtils from './bigcommerce-payments-fastlane-utils';\n\nexport default function createBigCommercePaymentsFastlaneUtils(): BigCommercePaymentsFastlaneUtils {\n return new BigCommercePaymentsFastlaneUtils();\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 BigCommercePaymentsFastlaneUtils,\n BigCommercePaymentsInitializationData,\n getFastlaneStyles,\n PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneStylesOption,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsFastlaneCustomerInitializeOptions, {\n WithBigCommercePaymentsFastlaneCustomerInitializeOptions,\n} from './bigcommerce-payments-fastlane-customer-initialize-options';\n\nexport default class BigCommercePaymentsFastlaneCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsSdk: PayPalSdkHelper,\n private bigCommercePaymentsFastlaneUtils: BigCommercePaymentsFastlaneUtils,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions &\n WithBigCommercePaymentsFastlaneCustomerInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_fastlane } = 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.bigCommercePaymentsSdk.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n );\n\n await this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(\n paypalFastlaneSdk,\n isTestModeEnabled,\n this.getFastlaneStyles(methodId, bigcommerce_payments_fastlane),\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 await this.paymentIntegrationService.updatePaymentProviderCustomer({\n authenticationState: undefined,\n addresses: undefined,\n instruments: undefined,\n });\n\n this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId();\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 } =\n await this.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(customerEmail);\n\n const authenticationResult =\n await this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(\n customerContextId,\n );\n\n const isAuthenticationFlowCanceled =\n authenticationResult.authenticationState === PayPalFastlaneAuthenticationState.CANCELED;\n\n await this.updateCustomerDataState(methodId, authenticationResult);\n\n if (isAuthenticationFlowCanceled) {\n this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId();\n } else {\n this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(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.bigCommercePaymentsFastlaneUtils.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(\n methodId,\n );\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 bigcommerce_payments_fastlane:\n | BigCommercePaymentsFastlaneCustomerInitializeOptions\n | 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 bigcommerce_payments_fastlane?.styles,\n );\n }\n}\n","import {\n createBigCommercePaymentsFastlaneUtils,\n createBigCommercePaymentsSdk,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsFastlaneCustomerStrategy from './bigcommerce-payments-fastlane-customer-strategy';\n\nconst createBigCommercePaymentsFastlaneCustomerStrategy: CustomerStrategyFactory<\n BigCommercePaymentsFastlaneCustomerStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsFastlaneCustomerStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsSdk(),\n createBigCommercePaymentsFastlaneUtils(),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsFastlaneCustomerStrategy, [\n { id: 'bigcommerce_payments_fastlane' }, // this method id will be provided for users from test group\n { id: 'bigcommerce_payments_creditcards' }, // this method id will be provided for users from control group\n]);\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsPayLaterCustomerInitializeOptions, {\n WithBigCommercePaymentsPayLaterCustomerInitializeOptions,\n} from './bigcommerce-payments-paylater-customer-initialize-options';\n\nexport default class BigCommercePaymentsPayLaterCustomerStrategy implements CustomerStrategy {\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions &\n WithBigCommercePaymentsPayLaterCustomerInitializeOptions,\n ): Promise {\n const { bigcommerce_payments_paylater, 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 (!bigcommerce_payments_paylater) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_paylater\" argument is not provided.',\n );\n }\n\n if (!bigcommerce_payments_paylater.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_paylater.container\" argument is not provided.',\n );\n }\n\n if (\n bigcommerce_payments_paylater.onClick &&\n typeof bigcommerce_payments_paylater.onClick !== 'function'\n ) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_paylater.onClick\" argument is not a function.',\n );\n }\n\n this.onError = bigcommerce_payments_paylater.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 const paypalSdk = await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n // eslint-disable-next-line no-console\n console.error(\n '[BC BigCommercePayments PayLater]: button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n this.renderButton(methodId, bigcommerce_payments_paylater);\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 bigCommercePaymentsPayLater: BigCommercePaymentsPayLaterCustomerInitializeOptions,\n ): void {\n const { container, onComplete, onClick } = bigCommercePaymentsPayLater;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_paylater',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.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: BigCommercePaymentsButtonsOptions = {\n fundingSource,\n style: this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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 =\n this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsPayLaterCustomerStrategy from './bigcommerce-payments-paylater-customer-strategy';\n\nconst createBigCommercePaymentsPayLaterCustomerStrategy: CustomerStrategyFactory<\n BigCommercePaymentsPayLaterCustomerStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsPayLaterCustomerStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsPayLaterCustomerStrategy, [\n { id: 'bigcommerce_payments_paylater' },\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsVenmoCustomerInitializeOptions, {\n WithBigCommercePaymentsVenmoCustomerInitializeOptions,\n} from './bigcommerce-payments-venmo-customer-initialize-options';\n\nexport default class BigCommercePaymentsVenmoCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBigCommercePaymentsVenmoCustomerInitializeOptions,\n ): Promise {\n const { bigcommerce_payments_venmo, 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 (!bigcommerce_payments_venmo) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_venmo\" argument is not provided.',\n );\n }\n\n if (!bigcommerce_payments_venmo.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_venmo.container\" argument is not provided.',\n );\n }\n\n if (\n bigcommerce_payments_venmo.onClick &&\n typeof bigcommerce_payments_venmo.onClick !== 'function'\n ) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_venmo.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 const paypalSdk = await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n // eslint-disable-next-line no-console\n console.error(\n '[BC Payments Venmo]: Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n this.renderButton(methodId, bigcommerce_payments_venmo);\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 bigcommerce_payments_venmo: BigCommercePaymentsVenmoCustomerInitializeOptions,\n ): void {\n const { container, onClick } = bigcommerce_payments_venmo;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.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: BigCommercePaymentsButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle({\n ...checkoutTopButtonStyles,\n height: DefaultCheckoutButtonHeight,\n }),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_venmo',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.removeElement(container);\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsVenmoCustomerStrategy from './bigcommerce-payments-venmo-customer-strategy';\n\nconst createBigCommercePaymentsVenmoCustomerStrategy: CustomerStrategyFactory<\n BigCommercePaymentsVenmoCustomerStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsVenmoCustomerStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsVenmoCustomerStrategy, [\n { id: 'bigcommerce_payments_venmo' },\n]);\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 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 {\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 { 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 { 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","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 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 { BraintreePaypalCheckout, BraintreePaypalSdkCreatorConfig } from './braintree';\nimport { BraintreeError } from './types';\n\nlet paypalSdkPromise: Promise | null = null;\n\nexport default function loadPayPalSDKOnce(\n paypalCheckout: BraintreePaypalCheckout,\n config: BraintreePaypalSdkCreatorConfig,\n): Promise {\n if (!paypalSdkPromise) {\n paypalSdkPromise = new Promise((resolve, reject) => {\n paypalCheckout.loadPayPalSDK(config, (err: null | undefined | BraintreeError) => {\n if (err) {\n paypalSdkPromise = null;\n\n reject(err);\n } else {\n resolve(paypalCheckout);\n }\n });\n });\n }\n\n return paypalSdkPromise;\n}\n\n// for testing purposes\nexport function resetLoadPayPalSDKOncePromise() {\n paypalSdkPromise = null;\n}\n","// 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 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 enum MessagingPlacements {\n CART = 'cart',\n HOME = 'homepage',\n PAYMENT = 'payment',\n PRODUCT = 'product',\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 | string;\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';\nimport { isEmpty } from 'lodash';\n\nimport {\n Address,\n CancellablePromise,\n CreditCardInstrument,\n LegacyAddress,\n NonceInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethodCancelledError,\n UnsupportedBrowserError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { Overlay } from '@bigcommerce/checkout-sdk/ui';\n\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport loadPayPalSDKOnce from './load-paypal-sdk-once';\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 BraintreeRequestData,\n BraintreeShippingAddressOverride,\n BraintreeThreeDSecure,\n BraintreeThreeDSecureOptions,\n BraintreeTokenizationDetails,\n BraintreeTokenizePayload,\n BraintreeVenmoCheckout,\n BraintreeVenmoCreatorConfig,\n BraintreeVerifyPayload,\n PAYPAL_COMPONENTS,\n TokenizationPayload,\n} from './types';\nimport isBraintreeError from './utils/is-braintree-error';\nimport isCreditCardInstrumentLike from './utils/is-credit-card-instrument-like';\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 private threeDSecureOptions?: BraintreeThreeDSecureOptions;\n private threeDS?: Promise;\n private venmoCheckout?: BraintreeVenmoCheckout;\n\n constructor(\n private braintreeScriptLoader: BraintreeScriptLoader,\n private braintreeHostWindow: BraintreeHostWindow,\n private overlay?: Overlay,\n ) {}\n\n initialize(clientToken: string, threeDSecureOptions?: BraintreeThreeDSecureOptions) {\n this.clientToken = clientToken;\n this.threeDSecureOptions = threeDSecureOptions;\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 void loadPayPalSDKOnce(braintreePaypalCheckout, paypalSdkLoadConfig).then(\n paypalSdkLoadCallback,\n );\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 async get3DS(): Promise {\n if (!this.threeDS) {\n this.threeDS = Promise.all([\n this.getClient(),\n this.braintreeScriptLoader.load3DS(),\n ]).then(([client, threeDSecure]) => threeDSecure.create({ client, version: 2 }));\n }\n\n return this.threeDS;\n }\n\n async getVenmoCheckout(\n venmoConfig?: BraintreeVenmoCreatorConfig,\n ): Promise {\n if (!this.venmoCheckout) {\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 ...(venmoConfig || {}),\n };\n\n this.venmoCheckout = await new Promise((resolve, reject) => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n venmoCheckout.create(\n venmoCheckoutConfig,\n (error: BraintreeError, braintreeVenmoCheckout: BraintreeVenmoCheckout) => {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (error) {\n return reject(error);\n }\n\n if (!braintreeVenmoCheckout.isBrowserSupported()) {\n return reject(new UnsupportedBrowserError());\n }\n\n resolve(braintreeVenmoCheckout);\n },\n );\n });\n }\n\n return this.venmoCheckout;\n }\n\n /*\n Braintree Credit Card and Braintree Hosted Form\n */\n async verifyCard(\n payment: Payment,\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 async tokenizeCard(payment: Payment, billingAddress: Address): 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.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 challenge3DSVerification(\n tokenizationPayload: TokenizationPayload,\n amount: number,\n ): Promise {\n const threeDSecure = await this.get3DS();\n\n return this.present3DSChallenge(threeDSecure, amount, tokenizationPayload);\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 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 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\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 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 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 // eslint-disable-next-line @typescript-eslint/no-use-before-define\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 if (addFrame) {\n addFrame(error, iframe, cancelVerifyCard);\n }\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","import { CreditCardInstrument } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isCreditCardInstrumentLike(\n instrument: unknown,\n): instrument is CreditCardInstrument {\n if (typeof instrument !== 'object' || instrument === null) {\n return false;\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const creditCardInstrument = instrument as Partial>;\n\n return (\n typeof creditCardInstrument.ccExpiry === 'object' &&\n creditCardInstrument.ccExpiry !== null &&\n typeof creditCardInstrument.ccNumber === 'string' &&\n typeof creditCardInstrument.ccName === 'string'\n );\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 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\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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-initialize-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\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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","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","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 { CookieStorage } 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 ) {}\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.saveSessionIdToCookies(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.removeSessionIdFromCookies();\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.saveSessionIdToCookies(cart.id);\n\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 * Session id management\n *\n */\n getSessionIdFromCookies(): string {\n return CookieStorage.get('bc-fastlane-sessionId') || '';\n }\n\n saveSessionIdToCookies(sessionId: string): void {\n const expires = new Date();\n\n expires.setDate(expires.getDate() + 14); // 2 weeks expiry\n\n CookieStorage.set('bc-fastlane-sessionId', sessionId, {\n expires,\n secure: true,\n });\n }\n\n removeSessionIdFromCookies(): void {\n CookieStorage.remove('bc-fastlane-sessionId');\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, binDetails } = 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: binDetails?.bin || '',\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 BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n );\n const braintreeFastlaneUtils = new BraintreeFastlaneUtils(\n paymentIntegrationService,\n braintreeIntegrationService,\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), hostWindow, braintreeSDKVersionManager),\n );\n\n return new BraintreeVisaCheckoutCustomerStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeSdk,\n );\n};\n\nexport default toResolvableModule(createBraintreeVisaCheckoutCustomerStrategy, [\n { id: 'braintreevisacheckout' },\n]);\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 { isOperaWindow } from '../is-opera-window';\nimport { isReactNativeWindow } from '../is-react-native-window';\n\nexport function isWebView(): boolean {\n if (typeof window === 'undefined') {\n return false;\n }\n\n if (isReactNativeWindow(window)) {\n return true;\n }\n\n const userAgent =\n navigator.userAgent || navigator.vendor || (isOperaWindow(window) ? window.opera : '');\n\n const isAndroidWebView = /android.+; wv/i.test(userAgent);\n const isIOSWebView =\n /iPhone|iPod|iPad/i.test(userAgent) &&\n /AppleWebKit/i.test(userAgent) &&\n !/Safari/i.test(userAgent);\n\n return isAndroidWebView || isIOSWebView;\n}\n","interface ReactNativeWindow extends Window {\n ReactNativeWebView: {\n postMessage(msg: string): void;\n };\n}\n\nexport function isReactNativeWindow(window: Window): window is ReactNativeWindow {\n return 'ReactNativeWebView' in window;\n}\n","interface OperaWindow extends Window {\n opera: string;\n}\n\nexport function isOperaWindow(window: Window): window is OperaWindow {\n return 'opera' in window;\n}\n","import { BigCommercePaymentsIntent } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 offerInfo?: Offers;\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 NewOfferInfo {\n newOfferInfo?: Offers;\n}\n\nexport interface Offers {\n offers: OfferInfoItem[];\n}\n\nexport interface GooglePayError {\n message: string;\n reason: ErrorReasonType;\n intent: CallbackTriggerType;\n}\n\nexport enum ErrorReasonType {\n OFFER_INVALID = 'OFFER_INVALID',\n PAYMENT_DATA_INVALID = 'PAYMENT_DATA_INVALID',\n SHIPPING_ADDRESS_INVALID = 'SHIPPING_ADDRESS_INVALID',\n SHIPPING_ADDRESS_UNSERVICEABLE = 'SHIPPING_ADDRESS_UNSERVICEABLE',\n SHIPPING_OPTION_INVALID = 'SHIPPING_OPTION_INVALID',\n OTHER_ERROR = 'OTHER_ERROR',\n}\n\nexport interface OfferInfoItem {\n redemptionCode: string;\n description: string;\n}\n\nexport interface HandleCouponsOut {\n newOfferInfo: GooglePayPaymentDataRequest['offerInfo'];\n error?: GooglePayError;\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 offerData: {\n redemptionCodes: string[];\n };\n}\n\nexport interface GooglePayPaymentOptions {\n paymentDataCallbacks?: {\n onPaymentDataChanged(\n intermediatePaymentData: IntermediatePaymentData,\n ): onPaymentDataChangedOut;\n };\n}\n\nexport type onPaymentDataChangedOut = Promise<\n | (NewTransactionInfo & NewShippingOptionParameters & NewOfferInfo & { error?: GooglePayError })\n | void\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) => Promise;\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 isWebViewExperimentOn?: boolean;\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 GooglePayBigCommercePaymentsInitializationData\n 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?: BigCommercePaymentsIntent;\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 shopperLanguage: string;\n useNewStripeJsVersion?: boolean;\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 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 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 | GooglePayBigCommercePaymentsInitializationData;\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","/**\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 * A container for loading spinner.\n */\n loadingContainerId?: string;\n\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 BIGCOMMERCE_PAYMENTS = 'googlepay_bigcommerce_payments',\n CHECKOUT_COM = 'googlepaycheckoutcom',\n CYBERSOURCE_V2 = 'googlepaycybersourcev2',\n ORBITAL = 'googlepayorbital',\n STRIPE = 'googlepaystripe',\n STRIPE_UPE = 'googlepaystripeupe',\n STRIPE_OCS = 'googlepaystripeocs',\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 { 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';\nimport { isExperimentEnabled, isWebView } from '@bigcommerce/checkout-sdk/utility';\n\nimport isGooglePayCardNetworkKey from '../guards/is-google-pay-card-network-key';\nimport {\n CallbackIntentsType,\n CallbackTriggerType,\n ErrorReasonType,\n ExtraPaymentData,\n GooglePayCardDataResponse,\n GooglePayCardNetwork,\n GooglePayCardParameters,\n GooglePayError,\n GooglePayFullBillingAddress,\n GooglePayGatewayParameters,\n GooglePayInitializationData,\n GooglePayMerchantInfo,\n GooglePayPaymentDataRequest,\n GooglePayRequiredPaymentData,\n GooglePaySetExternalCheckoutData,\n GooglePayTransactionInfo,\n HandleCouponsOut,\n IntermediatePaymentData,\n ShippingOptionParameters,\n TotalPriceStatusType,\n} from '../types';\n\nexport default class GooglePayGateway {\n private _getPaymentMethodFn?: () => PaymentMethod;\n private _isBuyNowFlow = false;\n private _shouldRequestShipping = true;\n private _currencyCode?: string;\n private _currencyService?: CurrencyService;\n private _isWebViewExperimentOn: null | boolean = null;\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 customFields = [],\n } = this._paymentIntegrationService.getState().getBillingAddress() || {};\n\n return {\n ...this._mapToAddressRequestBody(billingAddress, company, phone, customFields),\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 if (!nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\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 CallbackTriggerType.OFFER,\n ];\n\n const initializationTrigger = [CallbackTriggerType.INITIALIZE];\n const addressChangeTriggers = [\n CallbackTriggerType.INITIALIZE,\n CallbackTriggerType.SHIPPING_ADDRESS,\n ];\n const shippingOptionsChangeTriggers = [CallbackTriggerType.SHIPPING_OPTION];\n const offerChangeTriggers = [CallbackTriggerType.OFFER];\n\n return {\n availableTriggers,\n initializationTrigger,\n addressChangeTriggers,\n shippingOptionsChangeTriggers,\n offerChangeTriggers,\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 const { getCartOrThrow } = this._paymentIntegrationService.getState();\n\n if (this._isBuyNowFlow) {\n currencyCode = this._getCurrencyCodeOrThrow();\n } else {\n currencyCode = getCartOrThrow().currency.code;\n }\n\n const countryCode = this.getGooglePayInitializationData().storeCountry;\n\n if (this.isWebViewWithRestrictions()) {\n const totalPrice = this.getTotalPrice();\n\n return {\n ...(countryCode && { countryCode }),\n currencyCode,\n totalPrice,\n totalPriceStatus: TotalPriceStatusType.ESTIMATED,\n };\n }\n\n return {\n ...(countryCode && { countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.ESTIMATED,\n totalPrice: '0',\n };\n }\n\n isWebViewWithRestrictions(): boolean {\n if (this._isWebViewExperimentOn !== null) {\n return this._isWebViewExperimentOn && isWebView();\n }\n\n return isWebView();\n }\n\n setIsWebViewExperimentOn(isWebViewExperimentOn: boolean): void {\n this._isWebViewExperimentOn = isWebViewExperimentOn;\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, getStoreConfigOrThrow } =\n this._paymentIntegrationService.getState();\n const { decimalPlaces } = getCartOrThrow().currency;\n const isRoundingExperimentOn = isExperimentEnabled(\n getStoreConfigOrThrow().checkoutSettings.features,\n 'PI-5075.google_pay_round_total_price_to_max_2_decimal_places',\n );\n const maxDecimalPlaces = isRoundingExperimentOn\n ? Math.min(decimalPlaces, 2)\n : decimalPlaces;\n const totalPrice = round(getCheckoutOrThrow().outstandingBalance, maxDecimalPlaces).toFixed(\n maxDecimalPlaces,\n );\n\n return totalPrice;\n }\n\n async handleCoupons(\n offerData: IntermediatePaymentData['offerData'],\n ): Promise {\n const { redemptionCodes: newCouponsState = [] } = offerData;\n const { offers: appliedCoupons } = this.getAppliedCoupons() || {};\n let error;\n\n await newCouponsState.reduce(async (promise, code) => {\n await promise;\n\n const exists = (appliedCoupons || []).some(\n ({ redemptionCode }) => redemptionCode === code,\n );\n\n if (exists) {\n return;\n }\n\n const appliedCouponError = await this.applyCoupon(code);\n\n if (appliedCouponError) {\n error = appliedCouponError;\n }\n }, Promise.resolve());\n\n await (appliedCoupons || []).reduce(async (promise, coupon) => {\n await promise;\n\n const stillExists = newCouponsState.includes(coupon.redemptionCode);\n\n if (!stillExists) {\n await this._paymentIntegrationService.removeCoupon(coupon.redemptionCode);\n }\n }, Promise.resolve());\n\n return {\n newOfferInfo: this.getAppliedCoupons(),\n error,\n };\n }\n\n getAppliedCoupons(): GooglePayPaymentDataRequest['offerInfo'] {\n const state = this._paymentIntegrationService.getState();\n const { coupons } = state.getCheckout() || {};\n\n const offers = (coupons || []).map((coupon) => {\n const { displayName, code } = coupon;\n\n return {\n redemptionCode: code,\n description: displayName,\n };\n });\n\n return {\n offers,\n };\n }\n\n async applyCoupon(code: string): Promise {\n let error: GooglePayError | undefined;\n\n try {\n await this._paymentIntegrationService.applyCoupon(code);\n } catch (e) {\n if (e instanceof Error) {\n error = {\n reason: ErrorReasonType.OFFER_INVALID,\n message: e.message,\n intent: CallbackTriggerType.OFFER,\n };\n }\n\n return error;\n }\n }\n\n setShouldRequestShipping(isRequired: boolean): void {\n this._shouldRequestShipping = isRequired;\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, getStoreConfigOrThrow, getShippingAddress } =\n this._paymentIntegrationService.getState();\n const storeConfig = getStoreConfigOrThrow();\n const features = storeConfig.checkoutSettings.features;\n const checkWithExperiment = isExperimentEnabled(\n features,\n 'PI-4290.google_pay_require_shipping_address',\n );\n\n let shippingContextRequiresCheck: boolean;\n\n if (checkWithExperiment) {\n shippingContextRequiresCheck = this._shouldRequestShipping;\n } else {\n shippingContextRequiresCheck = getShippingAddress() === undefined;\n }\n\n return shippingContextRequiresCheck && itemsRequireShipping(getCartOrThrow(), storeConfig);\n }\n\n private _mapToAddressRequestBody(\n address: GooglePayFullBillingAddress,\n company: string,\n phone: string,\n customFields?: AddressRequestBody['customFields'],\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: 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({\n id,\n cost,\n description,\n additionalDescription,\n }: ShippingOption) {\n const formattedCost = this._currencyService?.toCustomerCurrency(cost);\n\n return {\n id,\n label: `${formattedCost || cost} ${description}`,\n description: additionalDescription,\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","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 GooglePayError,\n GooglePayInitializationData,\n GooglePayPaymentOptions,\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 this._googlePayPaymentProcessor.setIsWebViewExperimentOn(\n !!paymentMethod.initializationData?.isWebViewExperimentOn,\n );\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 if (this._googlePayPaymentProcessor.isWebViewWithRestrictions()) {\n return {};\n }\n\n return {\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({\n callbackTrigger,\n shippingAddress,\n shippingOptionData,\n offerData,\n }) => {\n const {\n availableTriggers,\n addressChangeTriggers,\n shippingOptionsChangeTriggers,\n offerChangeTriggers,\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 const { newOfferInfo = undefined, error: couponsError = undefined } =\n offerChangeTriggers.includes(callbackTrigger)\n ? await this._googlePayPaymentProcessor.handleCoupons(offerData)\n : {};\n\n // We can add another errors if needed 'couponsError || shippingError || anotherError'\n const error: GooglePayError | undefined = couponsError;\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 ...(newOfferInfo && {\n newOfferInfo,\n }),\n ...(error && {\n error,\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) => Promise {\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\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","import { FormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\n\nimport {\n AddressRequestBody,\n BillingAddressRequestBody,\n guard,\n NotInitializedError,\n NotInitializedErrorType,\n Omit,\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 HandleCouponsOut,\n IntermediatePaymentData,\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 | undefined {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n return;\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 setShouldRequestShipping(isRequired: boolean): void {\n return this._gateway.setShouldRequestShipping(isRequired);\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 async handleCoupons(\n offerData: IntermediatePaymentData['offerData'],\n ): Promise {\n return this._gateway.handleCoupons(offerData);\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 isWebViewWithRestrictions(): boolean {\n return this._gateway.isWebViewWithRestrictions();\n }\n\n setIsWebViewExperimentOn(isWebViewExperimentOn: boolean): void {\n return this._gateway.setIsWebViewExperimentOn(isWebViewExperimentOn);\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\n const isWebViewLogic = this._gateway.isWebViewWithRestrictions()\n ? {\n shippingOptionRequired: false,\n }\n : {\n callbackIntents: this._gateway.getCallbackIntents(),\n offerInfo: this._gateway.getAppliedCoupons(),\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 ...isWebViewLogic,\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","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 { PaymentMethod } from '@bigcommerce/checkout-sdk/payment-integration-api';\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\n/**\n * The PaymentIntent object.\n */\nexport interface PaymentIntent {\n /**\n * Unique identifier for the object.\n */\n id: string;\n\n /**\n * The client secret of the PaymentIntent. Used for client-side retrieval using a publishable key.\n */\n client_secret?: 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 payment_method_options?: StripePIPaymentMethodOptions;\n}\n\nexport interface StripePIPaymentMethodSavingOptions {\n setup_future_usage?: StripeInstrumentSetupFutureUsage;\n verification_method?: string;\n}\n\nexport interface StripePIPaymentMethodOptions {\n card?: StripePIPaymentMethodSavingOptions;\n us_bank_account?: StripePIPaymentMethodSavingOptions;\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 * 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 StripeCustomFont = CssFontSource | CustomFontSource;\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 StripeCheckoutSessionConfirmationError {\n code?: string;\n message: string;\n paymentFailed?: {\n declineCode?: string;\n };\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: StripeElementEvent, 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\nexport interface StripeCurrencyEvent extends StripeEvent {\n value: {\n currency: string;\n };\n}\n\nexport interface 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 =\n | StripeCurrencyEvent\n | StripeShippingEvent\n | StripeCustomerEvent\n | StripePaymentEvent\n | StripeLinkV2Event;\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
& { country: string };\n\nexport interface StripeAddressValues {\n name?: string;\n address?: AddressOptions;\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 allow_redisplay?: 'always' | 'limited' | 'unspecified';\n}\n\n/**\n * Parameters that will be passed on to the Stripe API to confirm the PaymentIntent.\n */\nexport interface StripeConfirmParams {\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?: StripeConfirmParams;\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 clientSecret?: string;\n}\n\nexport interface StripeCheckoutSessionConfirmPaymentData {\n redirect?: StripeStringConstants.ALWAYS | StripeStringConstants.IF_REQUIRED;\n returnUrl?: string;\n}\n\nexport interface FieldsOptions {\n billingDetails?: AutoOrNever | BillingDetailsProperties;\n phone?: string;\n}\n\nexport interface WalletOptions {\n applePay?: AutoOrNever;\n googlePay?: AutoOrNever;\n link?: AutoOrNever;\n}\n\nexport interface TermOptions {\n card?: AutoOrNever;\n}\n\nexport interface StripeLayoutOptions {\n type?: 'accordion' | 'tabs';\n linkInAccordion?: boolean;\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 | PaymentDefaultValues;\n validation?: validationElement;\n display?: { name: StripeDisplayName };\n terms?: TermOptions;\n layout?: StripeLayoutOptions;\n paymentMethodOrder?: string[];\n // Link v2 options\n lineItems?: LineItem[];\n allowedShippingCountries?: string[];\n shippingAddressRequired?: boolean;\n shippingRates?: StripeLinkV2ShippingRate[];\n billingAddressRequired?: boolean;\n emailRequired?: boolean;\n phoneNumberRequired?: boolean;\n paymentMethods?: {\n link: StripeStringConstants.AUTO;\n applePay: StripeStringConstants.NEVER;\n googlePay: StripeStringConstants.NEVER;\n amazonPay: StripeStringConstants.NEVER;\n paypal: StripeStringConstants.NEVER;\n klarna: StripeStringConstants.NEVER;\n };\n buttonHeight?: number;\n savePaymentMethod?: StripeSavePaymentMethod;\n}\n\ninterface validationElement {\n phone?: validationRequiredElement;\n}\n\ninterface validationRequiredElement {\n required?: string;\n}\n\ninterface PaymentDefaultValues {\n savePaymentMethod?: boolean;\n billingDetails?: BillingDetailsOptions;\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 StripeDisplayName {\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: StripeDisplayName;\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\nexport enum StripeCheckoutSessionStatusType {\n Open = 'open',\n Expired = 'expired',\n Complete = 'complete',\n}\n\nexport enum StripeCheckoutSessionPaymentStatus {\n Paid = 'paid',\n UnPaid = 'unpaid',\n NoPaymentRequired = 'no_payment_required',\n}\n\nexport interface StripeCheckoutSessionStatus {\n type: StripeCheckoutSessionStatusType;\n paymentStatus: StripeCheckoutSessionPaymentStatus;\n}\n\nexport interface StripeCheckoutSessionAmount {\n minorUnitsAmount: number;\n amount: string;\n}\n\nexport interface StripeCheckoutSessionTotal {\n appliedBalance: StripeCheckoutSessionAmount;\n balanceAppliedToNextInvoice: boolean;\n discount: StripeCheckoutSessionAmount;\n shippingRate: StripeCheckoutSessionAmount;\n subtotal: StripeCheckoutSessionAmount;\n taxExclusive: StripeCheckoutSessionAmount;\n taxInclusive: StripeCheckoutSessionAmount;\n total: StripeCheckoutSessionAmount;\n}\n\nexport interface StripeCheckoutSession {\n id: string;\n savedPaymentMethods?: StripeSavedPaymentMethod[];\n billingAddress: StripeAddressValues;\n businessName: string;\n canConfirm: boolean;\n currency: string;\n email: string;\n phoneNumber: string;\n shipping: unknown;\n shippingAddress: StripeAddressValues;\n shippingOptions: unknown;\n status: StripeCheckoutSessionStatus;\n tax: unknown;\n taxAmounts: unknown;\n total: StripeCheckoutSessionTotal;\n}\n\nexport interface StripeCheckoutInstance {\n loadActions(): Promise;\n createPaymentElement(options?: StripeElementsCreateOptions): StripeElement;\n getPaymentElement(): StripeElement | null;\n getCurrencySelectorElement(): StripeElement | null;\n createCurrencySelectorElement(): StripeElement;\n}\n\nexport enum StripeLoadActionsResultType {\n SUCCESS = 'success',\n ERROR = 'error',\n}\n\nexport interface StripeLoadActionsResult {\n type: StripeLoadActionsResultType;\n error?: { message: string };\n actions?: StripeCheckoutSessionActions;\n}\n\nexport interface StripeCheckoutSessionActionResult {\n type: StripeLoadActionsResultType;\n error?: StripeCheckoutSessionConfirmationError;\n session?: StripeCheckoutSession;\n}\n\nexport interface StripeCheckoutSessionActions {\n updateEmail(email: string): Promise;\n updateShippingAddress(\n shippingAddress: StripeAddressValues,\n ): Promise;\n updateBillingAddress(\n billingAddress: StripeAddressValues,\n ): Promise;\n getSession(): Promise;\n confirm(\n options: StripeCheckoutSessionConfirmPaymentData,\n ): Promise;\n}\n\nexport interface StripeSavedPaymentMethod {\n id: string;\n type: string;\n billingDetails: BillingDetailsOptions;\n card?: StripeCardDetails;\n usBankAccount?: StripeUsBankAccountDetails;\n}\n\nexport interface StripeCardDetails {\n brand: string;\n last4: string;\n expMonth: number;\n expYear: number;\n}\n\nexport interface StripeUsBankAccountDetails {\n accountHolderType: string;\n accountType: string;\n bankName: string;\n last4: string;\n}\n\n/**\n * All available options are here https://stripe.com/docs/stripe-js/appearance-api#supported-css-properties\n */\nexport interface StripeAppearanceOptions {\n variables?: Record;\n\n rules?: Record>;\n}\n\nexport type StripeAppearanceValues = string | string[] | number | undefined;\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?: StripeCustomFont[];\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 * A token that represents the Stripe customer session.\n * Stripe documentation: https://docs.stripe.com/api/checkout/sessions\n */\n customerSessionClientSecret?: 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?: StripeAppearanceOptions;\n\n mode?: string;\n amount?: number;\n currency?: string;\n paymentMethodTypes?: string[];\n}\n\nexport interface StripeInitCheckoutOptions {\n clientSecret: string;\n elementsOptions?: StripeCheckoutSessionElementOptions;\n adaptivePricing?: {\n allowed: boolean;\n };\n defaultValues?: StripeCheckoutSessionDefaultValues;\n wallets?: any;\n}\n\nexport interface StripeCheckoutSessionElementOptions {\n appearance?: StripeAppearanceOptions;\n loader?: StripeStringConstants;\n fonts?: StripeCustomFont[];\n savedPaymentMethod?: {\n enableRedisplay?: StripeStringConstants;\n enableSave?: StripeStringConstants;\n };\n}\n\nexport interface StripeCheckoutSessionDefaultValues {\n billingAddress?: StripeAddressValues;\n shippingAddress?: StripeAddressValues;\n email?: string;\n phoneNumber?: 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?: StripeAppearanceOptions;\n mode?: string;\n amount?: number;\n currency?: string;\n}\n\nexport interface StripeClient {\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 initCheckout(options: StripeInitCheckoutOptions): Promise;\n}\n\nexport interface StripeResult {\n paymentIntent?: PaymentIntent;\n error?: StripeError;\n}\n\nexport interface StripeHostWindow extends Window {\n bcStripeClient?: StripeClient;\n bcStripeElements?: StripeElements;\n bcStripeCheckout?: StripeCheckoutInstance;\n Stripe?(\n stripePublishableKey: string,\n options?: StripeConfigurationOptions,\n ): T;\n}\n\nexport enum StripePaymentMethodType {\n CreditCard = 'card',\n ACH = 'us_bank_account',\n Link = 'link',\n EPS = 'eps',\n GRABPAY = 'grabpay',\n BANCONTACT = 'bancontact',\n IDEAL = 'ideal',\n ALIPAY = 'alipay',\n KLARNA = 'klarna',\n OCS = 'optimized_checkout',\n CHECKOUT_SESSION = 'checkout_session',\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 StripeJsVersion {\n V3 = 'v3',\n ACACIA = 'acacia',\n BASIL = 'basil',\n CLOVER = 'clover',\n}\n\nexport enum StripeElementType {\n PAYMENT = 'payment',\n AUTHENTICATION = 'linkAuthentication',\n SHIPPING = 'address',\n EXPRESS_CHECKOUT = 'expressCheckout',\n}\n\nexport enum StripePaymentIntentStatus {\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 StripePaymentMethod extends PaymentMethod {\n initializationData: StripeInitializationData;\n}\n\nexport interface StripeInitializationData {\n stripePublishableKey: string;\n stripeConnectedAccount: string;\n shopperLanguage: string;\n customerSessionToken?: string;\n enableLink?: boolean;\n allowRedisplayForStoredInstruments?: boolean;\n captureMethod?: 'automatic' | 'manual';\n useNewStripeJsVersion?: boolean;\n checkoutSessionEnabled?: boolean;\n sendSecondPaymentRequestOnStripeError?: boolean;\n adaptivePricingEnabled?: boolean;\n hasSectionOnTopOfPaymentsList?: 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\nexport enum StripeElementEvent {\n CLICK = 'click',\n CHANGE = 'change',\n READY = 'ready',\n SHIPPING_ADDRESS_CHANGE = 'shippingaddresschange',\n SHIPPING_RATE_CHANGE = 'shippingratechange',\n CONFIRM = 'confirm',\n CANCEL = 'cancel',\n LOADER_START = 'loaderstart',\n}\n\nexport interface LineItem {\n name: string;\n amount: number;\n}\n\nexport interface StripeSavePaymentMethod {\n maxVisiblePaymentMethods?: number;\n}\n\nexport enum StripeInstrumentSetupFutureUsage {\n ON_SESSION = 'on_session',\n OFF_SESSION = 'off_session',\n}\n\nexport interface StripeLinkV2Event {\n value?: null;\n billingDetails?: {\n name?: string;\n email?: string;\n phone?: string;\n address?: {\n line1?: string;\n city?: string;\n country?: string;\n postal_code?: string;\n state?: string;\n };\n };\n shippingAddress?: {\n name?: string;\n address?: {\n line1?: string;\n line2?: string;\n city?: string;\n country?: string;\n postal_code?: string;\n state?: string;\n };\n };\n address?: {\n line1?: string;\n city?: string;\n country?: string;\n postal_code?: string;\n state?: string;\n };\n shippingRate?: StripeLinkV2ShippingRate;\n elementType: string;\n expressPaymentType: string;\n resolve(data: StripeLinkV2EventResolveData): void;\n reject(): void;\n}\n\nexport interface StripeLinkV2EventResolveData {\n lineItems?: LineItem[];\n allowedShippingCountries?: string[];\n shippingAddressRequired?: boolean;\n shippingRates?: StripeLinkV2ShippingRate[];\n billingAddressRequired?: boolean;\n emailRequired?: boolean;\n phoneNumberRequired?: boolean;\n}\n\nexport interface StripeLinkV2ShippingRate {\n id: string;\n amount: number;\n displayName: string;\n}\n\nexport interface StripeLinkV2Options {\n clientSecret?: string;\n mode?: string;\n currency?: string;\n captureMethod?: 'automatic' | 'manual';\n amount?: number;\n}\n\nexport interface StripeFormattedPaymentPayload {\n cart_id: string;\n confirm: boolean;\n method?: string;\n credit_card_token?: { token: string };\n tokenized_ach?: { token: string };\n vault_payment_instrument?: boolean;\n set_as_default_stored_instrument?: boolean;\n client_side_error?: boolean;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n StripeCheckoutInstance,\n StripeClient,\n StripeElements,\n StripeElementsOptions,\n StripeHostWindow,\n StripeInitCheckoutOptions,\n StripeInitializationData,\n StripeJsVersion,\n} from './stripe';\n\nexport default class StripeScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private stripeWindow: StripeHostWindow = window,\n ) {}\n\n async getStripeClient(\n initializationData: StripeInitializationData,\n locale?: string,\n stripeJsVersion?: string,\n betas?: string[],\n apiVersion?: string,\n ): Promise {\n if (this.stripeWindow.bcStripeClient) {\n return this.stripeWindow.bcStripeClient;\n }\n\n const stripe = await this.load(stripeJsVersion);\n const { stripePublishableKey, stripeConnectedAccount } = initializationData;\n const options = {\n ...(stripeConnectedAccount ? { stripeAccount: stripeConnectedAccount } : {}),\n ...(locale ? { locale } : {}),\n ...(betas ? { betas } : {}),\n ...(apiVersion ? { apiVersion } : {}),\n };\n\n const stripeClient = stripe(stripePublishableKey, options);\n\n Object.assign(this.stripeWindow, { bcStripeClient: stripeClient });\n\n return stripeClient;\n }\n\n async getElements(\n stripeClient: StripeClient,\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 async getStripeCheckout(\n stripeClient: StripeClient,\n options: StripeInitCheckoutOptions,\n ): Promise {\n let stripeCheckout = await this.getStoredStripeCheckout(options);\n\n if (!stripeCheckout) {\n stripeCheckout = await stripeClient.initCheckout(options);\n\n Object.assign(this.stripeWindow, { bcStripeCheckout: stripeCheckout });\n }\n\n return stripeCheckout;\n }\n\n private async load(stripeJsVersion?: string) {\n if (!this.stripeWindow.Stripe) {\n await this.scriptLoader.loadScript(this.getScriptUrl(stripeJsVersion));\n\n if (!this.stripeWindow.Stripe) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.stripeWindow.Stripe;\n }\n\n private getScriptUrl(stripeJsVersion?: string) {\n if (!stripeJsVersion || stripeJsVersion === StripeJsVersion.V3) {\n return 'https://js.stripe.com/v3/';\n }\n\n return `https://js.stripe.com/${stripeJsVersion}/stripe.js`;\n }\n\n private async getStoredStripeCheckout(\n options: StripeInitCheckoutOptions,\n ): Promise {\n const stripeCheckout = this.stripeWindow.bcStripeCheckout;\n\n if (!stripeCheckout) {\n return undefined;\n }\n\n try {\n const { actions, error } = await stripeCheckout.loadActions();\n\n if (error || !actions) {\n this.logErrorToConsole(error);\n\n return undefined;\n }\n\n const stripeCheckoutSession = await actions.getSession();\n const stripeSessionIdFromOptions = options.clientSecret.split('_secret_')[0];\n\n if (stripeCheckoutSession.id === stripeSessionIdFromOptions) {\n return stripeCheckout;\n }\n } catch (error) {\n this.logErrorToConsole(error);\n\n return undefined;\n }\n\n return undefined;\n }\n\n private logErrorToConsole(error?: unknown) {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n error\n ? console.error(error)\n : console.error('No stripe checkout actions available on loadActions().');\n }\n}\n","export const STRIPE_UPE_CLIENT_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\nexport const STRIPE_UPE_CLIENT_API_VERSION = '2020-03-02;alipay_beta=v1;link_beta=v1';\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';\nimport {\n STRIPE_UPE_CLIENT_API_VERSION,\n STRIPE_UPE_CLIENT_BETAS,\n StripeJsVersion,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\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 GooglePayStripeInitializationData,\n} from '../types';\n\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: StripeScriptLoader,\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 shouldTrigger3DS = some(error.body.errors, { code: 'three_d_secure_required' });\n\n if (shouldTrigger3DS) {\n const initialization = this.getGooglePayInitializationData();\n\n assertsIsGooglePayStripeInitializationData(initialization);\n\n this.stripeUPEClient = await this.loadStripeJs(initialization, methodId);\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 initializationData: GooglePayStripeInitializationData,\n methodId: string,\n ): Promise {\n if (this.stripeUPEClient) {\n return this.stripeUPEClient;\n }\n\n const locale = this.paymentIntegrationService.getState().getCartLocale();\n\n if (methodId === 'googlepaystripeocs' && !!initializationData.useNewStripeJsVersion) {\n return this.scriptLoader.getStripeClient(\n initializationData,\n locale,\n StripeJsVersion.CLOVER,\n );\n }\n\n return this.scriptLoader.getStripeClient(\n initializationData,\n locale,\n StripeJsVersion.V3,\n STRIPE_UPE_CLIENT_BETAS,\n STRIPE_UPE_CLIENT_API_VERSION,\n );\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 { 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';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\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';\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 StripeScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayStripeCustomerStrategy, [\n { id: 'googlepaystripe' },\n { id: 'googlepaystripeocs' },\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';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\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';\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 StripeScriptLoader(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","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 { GooglePayKey } from '../google-pay-payment-initialize-options';\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 private _methodId = GooglePayKey.BRAINTREE;\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 let paymentMethod = super.getPaymentMethod();\n\n if (!paymentMethod.clientToken) {\n const state = await this._service.loadPaymentMethod(this._methodId);\n\n paymentMethod = state.getPaymentMethodOrThrow(this._methodId);\n }\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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","export const LOADING_INDICATOR_STYLES = {\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\n};\n\n/**\n * PayPal SDK supported locales\n * https://developer.paypal.com/sdk/js/configuration/#link-locale\n */\nexport const PAYPAL_SDK_SUPPORTED_LOCALES = [\n 'ar_BH',\n 'ar_DZ',\n 'ar_EG',\n 'ar_JO',\n 'ar_KW',\n 'ar_MA',\n 'ar_OM',\n 'ar_QA',\n 'ar_SA',\n 'ar_TN',\n 'ar_YE',\n 'ar_AE',\n 'bg_BG',\n 'cs_CZ',\n 'da_DK',\n 'da_FO',\n 'da_GL',\n 'de_AT',\n 'de_CH',\n 'de_DE',\n 'de_LU',\n 'el_GR',\n 'en_AD',\n 'en_AE',\n 'en_AG',\n 'en_AI',\n 'en_AL',\n 'en_AM',\n 'en_AN',\n 'en_AO',\n 'en_AT',\n 'en_AU',\n 'en_AW',\n 'en_AZ',\n 'en_BB',\n 'en_BE',\n 'en_BH',\n 'en_BJ',\n 'en_BM',\n 'en_BN',\n 'en_BS',\n 'en_BT',\n 'en_BW',\n 'en_BY',\n 'en_BZ',\n 'en_C2',\n 'en_CA',\n 'en_CD',\n 'en_CG',\n 'en_CH',\n 'en_CI',\n 'en_CK',\n 'en_CL',\n 'en_CM',\n 'en_CN',\n 'en_CO',\n 'en_CR',\n 'en_CV',\n 'en_CY',\n 'en_CZ',\n 'en_DE',\n 'en_DJ',\n 'en_DK',\n 'en_DM',\n 'en_DO',\n 'en_DZ',\n 'en_EC',\n 'en_EE',\n 'en_EG',\n 'en_ER',\n 'en_ES',\n 'en_ET',\n 'en_FI',\n 'en_FJ',\n 'en_FK',\n 'en_FM',\n 'en_FO',\n 'en_FR',\n 'en_GA',\n 'en_GB',\n 'en_GD',\n 'en_GE',\n 'en_GF',\n 'en_GI',\n 'en_GL',\n 'en_GM',\n 'en_GN',\n 'en_GP',\n 'en_GR',\n 'en_GT',\n 'en_GW',\n 'en_GY',\n 'en_HK',\n 'en_HN',\n 'en_HR',\n 'en_HU',\n 'en_ID',\n 'en_IE',\n 'en_IL',\n 'en_IN',\n 'en_IS',\n 'en_IT',\n 'en_JM',\n 'en_JO',\n 'en_JP',\n 'en_KE',\n 'en_KG',\n 'en_KH',\n 'en_KI',\n 'en_KM',\n 'en_KN',\n 'en_KR',\n 'en_KW',\n 'en_KY',\n 'en_KZ',\n 'en_LA',\n 'en_LC',\n 'en_LI',\n 'en_LK',\n 'en_LS',\n 'en_LT',\n 'en_LU',\n 'en_LV',\n 'en_MA',\n 'en_MC',\n 'en_MD',\n 'en_ME',\n 'en_MG',\n 'en_MH',\n 'en_MK',\n 'en_ML',\n 'en_MN',\n 'en_MQ',\n 'en_MR',\n 'en_MS',\n 'en_MT',\n 'en_MU',\n 'en_MV',\n 'en_MW',\n 'en_MY',\n 'en_MZ',\n 'en_NA',\n 'en_NC',\n 'en_NE',\n 'en_NF',\n 'en_NG',\n 'en_NI',\n 'en_NL',\n 'en_NO',\n 'en_NP',\n 'en_NR',\n 'en_NU',\n 'en_NZ',\n 'en_OM',\n 'en_PA',\n 'en_PE',\n 'en_PF',\n 'en_PG',\n 'en_PH',\n 'en_PL',\n 'en_PM',\n 'en_PN',\n 'en_PT',\n 'en_PW',\n 'en_PY',\n 'en_QA',\n 'en_RE',\n 'en_RO',\n 'en_RS',\n 'en_RU',\n 'en_RW',\n 'en_SA',\n 'en_SB',\n 'en_SC',\n 'en_SE',\n 'en_SG',\n 'en_SH',\n 'en_SI',\n 'en_SJ',\n 'en_SK',\n 'en_SL',\n 'en_SM',\n 'en_SN',\n 'en_SO',\n 'en_SR',\n 'en_ST',\n 'en_SV',\n 'en_SZ',\n 'en_TC',\n 'en_TD',\n 'en_TG',\n 'en_TH',\n 'en_TJ',\n 'en_TM',\n 'en_TN',\n 'en_TO',\n 'en_TR',\n 'en_TT',\n 'en_TV',\n 'en_TW',\n 'en_TZ',\n 'en_UA',\n 'en_UG',\n 'en_US',\n 'en_UY',\n 'en_VA',\n 'en_VC',\n 'en_VE',\n 'en_VG',\n 'en_VN',\n 'en_VU',\n 'en_WF',\n 'en_WS',\n 'en_YE',\n 'en_YT',\n 'en_ZA',\n 'en_ZM',\n 'en_ZW',\n 'es_AD',\n 'es_AI',\n 'es_AO',\n 'es_AR',\n 'es_AW',\n 'es_BB',\n 'es_BJ',\n 'es_BM',\n 'es_BO',\n 'es_BS',\n 'es_BZ',\n 'es_CD',\n 'es_CG',\n 'es_CK',\n 'es_CL',\n 'es_CO',\n 'es_CR',\n 'es_CV',\n 'es_DJ',\n 'es_DM',\n 'es_DO',\n 'es_DZ',\n 'es_EC',\n 'es_EG',\n 'es_ER',\n 'es_ES',\n 'es_ET',\n 'es_FJ',\n 'es_FK',\n 'es_FO',\n 'es_GA',\n 'es_GD',\n 'es_GE',\n 'es_GI',\n 'es_GL',\n 'es_GM',\n 'es_GN',\n 'es_GT',\n 'es_GW',\n 'es_GY',\n 'es_HN',\n 'es_IE',\n 'es_JM',\n 'es_JO',\n 'es_KE',\n 'es_KG',\n 'es_KI',\n 'es_KM',\n 'es_KN',\n 'es_KW',\n 'es_KY',\n 'es_KZ',\n 'es_LC',\n 'es_LI',\n 'es_LS',\n 'es_LU',\n 'es_MA',\n 'es_MG',\n 'es_MH',\n 'es_ML',\n 'es_MR',\n 'es_MS',\n 'es_MU',\n 'es_MW',\n 'es_MX',\n 'es_MZ',\n 'es_NA',\n 'es_NC',\n 'es_NE',\n 'es_NF',\n 'es_NI',\n 'es_NR',\n 'es_NU',\n 'es_NZ',\n 'es_OM',\n 'es_PA',\n 'es_PE',\n 'es_PF',\n 'es_PG',\n 'es_PM',\n 'es_PN',\n 'es_PW',\n 'es_PY',\n 'es_QA',\n 'es_RS',\n 'es_RW',\n 'es_SA',\n 'es_SB',\n 'es_SC',\n 'es_SH',\n 'es_SJ',\n 'es_SL',\n 'es_SM',\n 'es_SN',\n 'es_SO',\n 'es_SR',\n 'es_ST',\n 'es_SV',\n 'es_SZ',\n 'es_TC',\n 'es_TD',\n 'es_TG',\n 'es_TJ',\n 'es_TM',\n 'es_TN',\n 'es_TT',\n 'es_TV',\n 'es_UA',\n 'es_UG',\n 'es_US',\n 'es_UY',\n 'es_VA',\n 'es_VC',\n 'es_VE',\n 'es_VG',\n 'es_VU',\n 'es_WF',\n 'es_YE',\n 'es_ZM',\n 'et_EE',\n 'fi_FI',\n 'fr_AD',\n 'fr_AE',\n 'fr_AI',\n 'fr_AM',\n 'fr_AO',\n 'fr_AW',\n 'fr_AZ',\n 'fr_BB',\n 'fr_BE',\n 'fr_BF',\n 'fr_BI',\n 'fr_BJ',\n 'fr_BM',\n 'fr_BS',\n 'fr_BZ',\n 'fr_CA',\n 'fr_CD',\n 'fr_CG',\n 'fr_CH',\n 'fr_CI',\n 'fr_CK',\n 'fr_CM',\n 'fr_CV',\n 'fr_DJ',\n 'fr_DM',\n 'fr_DO',\n 'fr_DZ',\n 'fr_EC',\n 'fr_ER',\n 'fr_ET',\n 'fr_FJ',\n 'fr_FK',\n 'fr_FO',\n 'fr_FR',\n 'fr_GA',\n 'fr_GD',\n 'fr_GE',\n 'fr_GF',\n 'fr_GI',\n 'fr_GL',\n 'fr_GM',\n 'fr_GN',\n 'fr_GP',\n 'fr_GT',\n 'fr_GW',\n 'fr_GY',\n 'fr_HN',\n 'fr_IE',\n 'fr_JM',\n 'fr_JO',\n 'fr_KE',\n 'fr_KG',\n 'fr_KI',\n 'fr_KM',\n 'fr_KN',\n 'fr_KW',\n 'fr_KY',\n 'fr_KZ',\n 'fr_LC',\n 'fr_LI',\n 'fr_LS',\n 'fr_LU',\n 'fr_MA',\n 'fr_MC',\n 'fr_MG',\n 'fr_MH',\n 'fr_ML',\n 'fr_MQ',\n 'fr_MR',\n 'fr_MS',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VG',\n 'zh_VU',\n 'zh_WF',\n 'zh_YE',\n 'zh_ZA',\n 'zh_ZM',\n];\n","import { PAYPAL_SDK_SUPPORTED_LOCALES } from '../paypal-commerce-constants';\n\n/**\n * Transforms store language to PayPal SDK locale format.\n * PayPal SDK expects locale in format 'en_US' (underscore separator).\n * Returns undefined if the locale is not supported by PayPal SDK.\n * Examples: 'fr-CA' -> 'fr_CA', 'fr' -> 'fr_FR'\n */\nexport default function transformLocaleToPayPalFormat(\n storeLanguage: string | undefined,\n): string | undefined {\n if (!storeLanguage) {\n return undefined;\n }\n\n let locale: string;\n\n if (storeLanguage.includes('-')) {\n const [language, region] = storeLanguage.split('-');\n\n locale = `${language}_${region.toUpperCase()}`;\n } else {\n locale = `${storeLanguage}_${storeLanguage.toUpperCase()}`;\n }\n\n return PAYPAL_SDK_SUPPORTED_LOCALES.includes(locale) ? locale : undefined;\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';\nimport { transformLocaleToPayPalFormat } from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport {\n PayPalCommerceHostWindow,\n PayPalCommerceInitializationData,\n PayPalFastlaneSdk,\n PayPalGooglePaySdk,\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 storeLanguage: string | undefined,\n ): Promise {\n if (!this.window.paypalFastlaneSdk) {\n const config = this.getPayPalFastlaneSdkConfiguration(\n paymentMethod,\n currencyCode,\n sessionId,\n storeLanguage,\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 getPayPalGooglePaySdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n if (!this.window.paypalGooglePay || forceLoad) {\n const paypalSdkScriptConfig = this.getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n storeLanguage,\n initializesOnCheckoutPage,\n );\n\n await this.loadPayPalSdk(paypalSdkScriptConfig);\n }\n\n if (!this.window.paypalGooglePay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypalGooglePay;\n }\n\n async getPayPalApmsSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n ) {\n if (!this.window.paypalApms) {\n const config = this.getPayPalApmSdkConfiguration(\n paymentMethod,\n currencyCode,\n storeLanguage,\n );\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 storeLanguage: string | undefined,\n ): Promise {\n if (!this.window.paypalMessages) {\n const paypalSdkMessagesConfig = this.getPayPalSdkMessagesConfiguration(\n paymentMethod,\n currencyCode,\n storeLanguage,\n );\n\n await this.loadPayPalSdk(paypalSdkMessagesConfig);\n }\n\n if (!this.window.paypalMessages) {\n throw new PaymentMethodClientUnavailableError();\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 storeLanguage: string | undefined,\n ): PayPalSdkConfig {\n const { clientToken, initializationData } = paymentMethod;\n\n if (!initializationData || !initializationData.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { intent, clientId, merchantId, attributionId } = initializationData;\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit: true,\n components: [\n 'fastlane',\n 'buttons',\n 'payment-fields',\n 'hosted-fields',\n 'three-domain-secure',\n ],\n currency: currencyCode,\n intent,\n ...(locale && { locale }),\n },\n attributes: {\n 'data-client-metadata-id': sessionId.replace(/-/g, ''),\n 'data-namespace': 'paypalFastlaneSdk',\n 'data-partner-attribution-id': attributionId,\n 'data-sdk-client-token': clientToken,\n },\n };\n }\n\n private getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage = true,\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 buyerCountry,\n attributionId,\n isHostedCheckoutEnabled,\n isDeveloperModeApplicable,\n } = initializationData;\n\n const commit = isHostedCheckoutEnabled || initializesOnCheckoutPage;\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit,\n components: ['googlepay'],\n currency: currencyCode,\n intent,\n ...(isDeveloperModeApplicable && { 'buyer-country': buyerCountry }),\n ...(locale && { locale }),\n },\n attributes: {\n 'data-partner-attribution-id': attributionId,\n 'data-client-token': clientToken,\n 'data-namespace': 'paypalGooglePay',\n },\n };\n }\n\n private getPayPalApmSdkConfiguration(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\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 const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 storeLanguage: string | undefined,\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 const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 {\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 {\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\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 { GooglePayConfig } from './types';\n\nexport default class GooglePayPaypalCommerceGateway extends GooglePayGateway {\n private googlepayConfig?: GooglePayConfig;\n private service: PaymentIntegrationService;\n\n constructor(service: PaymentIntegrationService, private payPalCommerceSdk: PayPalCommerceSdk) {\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 state = this.service.getState();\n const currency = state.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 const googlePaySdk = await this.payPalCommerceSdk.getPayPalGooglePaySdk(\n paymentMethod,\n currency,\n state.getLocale(),\n );\n\n this.googlepayConfig = await googlePaySdk.Googlepay().config();\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 { 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';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\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';\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 PayPalCommerceSdk(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayPayPalCommerceCustomerStrategy, [\n { id: 'googlepaypaypalcommerce' },\n]);\n","import {\n BigCommercePaymentsInitializationData,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 GooglePayConfig,\n GooglePayPayPalCommerceGatewayParameters,\n GooglePayPayPalCommerceInitializationData,\n GooglePaySetExternalCheckoutData,\n} from '../types';\n\nexport default class GooglePayBigCommercePaymentsGateway extends GooglePayGateway {\n private googlepayConfig?: GooglePayConfig;\n private service: PaymentIntegrationService;\n\n constructor(service: PaymentIntegrationService, private payPalSdkHelper: PayPalSdkHelper) {\n super('googlepay_bigcommerce_payments', 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 const googlePaySdk = await this.payPalSdkHelper.getPayPalGooglePaySdk(\n paymentMethod as PaymentMethod,\n currency,\n );\n\n this.googlepayConfig = await googlePaySdk.Googlepay().config();\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 { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PayPalSdkHelper } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\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 GooglePayBigCommercePaymentsGateway from './google-pay-bigcommerce-payments-gateway';\n\nconst createGooglePayBigCommercePaymentsCustomerStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayBigCommercePaymentsGateway(\n paymentIntegrationService,\n new PayPalSdkHelper(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayBigCommercePaymentsCustomerStrategy, [\n { id: 'googlepay_bigcommerce_payments' },\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 {\n BuyNowCartRequestBody,\n CardInstrument,\n CustomerAddress,\n HostedInstrument,\n ShippingOption,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n/**\n *\n * PayPal 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 BuyNow\n *\n */\nexport interface PayPalBuyNowInitializeOptions {\n getBuyNowCartRequestBody(): BuyNowCartRequestBody;\n}\n\n/**\n *\n * PayPal Initialization Data\n *\n */\nexport interface PayPalInitializationData {\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?: PayPalIntent;\n isAcceleratedCheckoutEnabled?: boolean; // PayPal Fastlane related\n isFastlaneShippingOptionAutoSelectEnabled?: boolean; // PayPal Fastlane related\n isFastlaneStylingEnabled?: boolean;\n isHostedCheckoutEnabled?: boolean;\n isPayPalAnalyticsV2Enabled?: boolean; // PayPal Fastlane related\n isPayPalCreditAvailable?: boolean;\n isPayPalCommerceAnalyticsV2Enabled?: boolean; // PayPal Fastlane related\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 threeDSVerificationMethod?: string;\n isAppSwitchEnabled?: boolean;\n}\n\n/**\n *\n * PayPalHostWindow contains different\n * PayPal Sdk instances for different purposes\n *\n */\nexport interface PayPalHostWindow extends Window {\n paypal?: PayPalSDK;\n paypalFastlane?: PayPalFastlane;\n paypalFastlaneSdk?: PayPalFastlaneSdk;\n paypalMessages?: PayPalMessagesSdk;\n paypalApms?: PayPalApmSdk;\n paypalGooglePay?: PayPalGooglePaySdk;\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?: PayPalIntent;\n components?: PayPalSdkComponents;\n locale?: string;\n };\n attributes: {\n 'data-client-metadata-id'?: string;\n 'data-partner-attribution-id'?: string;\n 'data-sdk-client-token'?: string;\n 'data-namespace'?: string;\n 'data-client-token'?: string;\n };\n}\n\nexport enum PayPalIntent {\n AUTHORIZE = 'authorize',\n CAPTURE = 'capture',\n}\n\nexport type PayPalSdkComponents = Array<\n | 'fastlane'\n | 'three-domain-secure'\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 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\n/**\n *\n * PayPal Sdk instances\n *\n */\nexport interface PayPalSDK {\n CardFields: (data: PaypalCardFieldsConfig) => 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: PayPalHostedFieldsRenderOptions): Promise;\n };\n Legal: PayPalLegal & LegalFunding;\n Buttons(options: PayPalButtonsOptions): PayPalButtons;\n PaymentFields(options: PayPalPaymentFieldsOptions): PayPalPaymentFields;\n Messages(options: PayPalMessagesOptions): PayPalMessages;\n}\n\nexport interface PaypalCardFieldsConfig {\n inputEvents: {\n onChange(data: PayPalCardFieldsState): void;\n onFocus(data: PayPalCardFieldsState): void;\n onBlur(data: PayPalCardFieldsState): void;\n onInputSubmitRequest(data: PayPalCardFieldsState): void;\n };\n createVaultSetupToken?: (data: PayPalCardFieldsState) => void;\n createOrder?: () => Promise;\n style: PayPalHostedFieldsRenderOptions['styles'];\n onApprove(data: PayPalCardFieldsOnApproveData): void;\n onError(): void;\n}\n\ninterface PayPalFieldsInitializationData {\n placeholder?: string;\n}\n\nexport interface PayPalCardFields {\n isEligible(): boolean;\n CVVField(config?: PayPalFieldsInitializationData): PayPalFields;\n ExpiryField(config?: PayPalFieldsInitializationData): PayPalFields;\n NameField(config?: PayPalFieldsInitializationData): PayPalFields;\n NumberField(config?: PayPalFieldsInitializationData): PayPalFields;\n submit(config?: PayPalCardFieldsSubmitConfig): Promise;\n getState(): Promise;\n}\n\nexport interface PayPalCardFieldsSubmitConfig {\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 PayPalCardFieldsOnApproveData {\n vaultSetupToken?: string;\n orderID: string;\n liabilityShift?: LiabilityShiftEnum;\n}\n\ninterface PayPalCardFieldsFieldData {\n isFocused: boolean;\n isEmpty: boolean;\n isValid: boolean;\n isPotentiallyValid: boolean;\n}\n\ntype PayPalCardFieldsCard = PayPalHostedFieldsCard;\n\nexport interface PayPalCardFieldsState {\n cards: PayPalCardFieldsCard[];\n emittedBy: string;\n isFormValid: boolean;\n errors: string[];\n fields: {\n cardCvvField: PayPalCardFieldsFieldData;\n cardNumberField: PayPalCardFieldsFieldData;\n cardNameField?: PayPalCardFieldsFieldData;\n cardExpiryField: PayPalCardFieldsFieldData;\n };\n}\n\nexport interface PayPalFields {\n render(container: HTMLElement | string): Promise;\n clear(): void;\n removeClass(className: string): Promise;\n close(): Promise;\n}\n\nexport interface PayPalFastlaneSdk {\n ThreeDomainSecureClient: {\n isEligible(params: threeDSecureParameters): Promise;\n show(): Promise;\n };\n Fastlane(options?: PayPalFastlaneOptions): Promise;\n}\n\ninterface ThreeDomainSecureClientShowResponse {\n liabilityShift: LiabilityShiftEnum;\n authenticationState: TDSecureAuthenticationState;\n nonce: string; // Enriched nonce or the original nonce\n}\n\nexport enum TDSecureVerificationMethod {\n Always = 'SCA_ALWAYS',\n}\n\nexport enum TDSecureAuthenticationState {\n Succeeded = 'succeeded',\n Cancelled = 'cancelled',\n Errored = 'errored',\n}\n\nexport enum LiabilityShiftEnum {\n Possible = 'POSSIBLE',\n No = 'NO',\n Unknown = 'UNKNOWN',\n Yes = 'YES',\n}\n\nexport interface threeDSecureParameters {\n amount: string;\n currency: string;\n nonce: string;\n threeDSRequested: boolean;\n transactionContext: {\n experience_context: {\n brand_name?: string;\n locale: string;\n return_url: string;\n cancel_url: string;\n };\n };\n}\n\nexport interface PayPalMessagesSdk {\n Messages(options: MessagingOptions): MessagingRender;\n}\n\nexport interface PayPalApmSdk {\n Buttons(options: PayPalButtonsOptions): PayPalButtons;\n PaymentFields(options: PayPalPaymentFieldsOptions): PayPalPaymentFields;\n}\n\nexport interface PayPalGooglePaySdk {\n Googlepay(): GooglePay;\n}\n\n/**\n *\n * PayPal Payments Hosted Fields\n *\n */\nexport interface PayPalHostedFieldsRenderOptions {\n fields?: {\n number?: PayPalHostedFieldOption;\n cvv?: PayPalHostedFieldOption;\n expirationDate?: PayPalHostedFieldOption;\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 PayPalHostedFieldOption {\n selector: string;\n placeholder?: string;\n}\n\nexport interface PayPalHostedFields {\n submit(options?: PayPalHostedFieldsSubmitOptions): Promise;\n getState(): PayPalHostedFieldsState;\n on(eventName: string, callback: (event: PayPalHostedFieldsState) => void): void;\n}\n\nexport interface PayPalHostedFieldsSubmitOptions {\n contingencies?: Array<'3D_SECURE'>;\n cardholderName?: string;\n}\n\nexport interface PayPalHostedFieldsApprove {\n orderId: string;\n liabilityShift?: 'POSSIBLE' | 'NO' | 'UNKNOWN';\n}\n\nexport interface PayPalHostedFieldsState {\n cards: PayPalHostedFieldsCard[];\n emittedBy: string;\n fields: {\n number?: PayPalHostedFieldsFieldData;\n expirationDate?: PayPalHostedFieldsFieldData;\n expirationMonth?: PayPalHostedFieldsFieldData;\n expirationYear?: PayPalHostedFieldsFieldData;\n cvv?: PayPalHostedFieldsFieldData;\n postalCode?: PayPalHostedFieldsFieldData;\n };\n}\n\nexport interface PayPalHostedFieldsCard {\n type: string;\n niceType: string;\n code: {\n name: string;\n size: number;\n };\n}\n\nexport interface PayPalHostedFieldsFieldData {\n container: HTMLElement;\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\n/**\n *\n * PayPal Buttons\n *\n */\nexport interface PayPalButtons {\n render(id: string): void;\n close(): void;\n isEligible(): boolean;\n hasReturned?(): boolean;\n resume?(): void;\n}\n\nexport interface PayPalButtonsOptions {\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 phone?: {\n phone_number: {\n national_number: string;\n };\n };\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\nexport interface PayPalButtonOptions {\n fundingSource: string;\n style?: PayPalButtonStyleOptions;\n isAppSwitchEnabled?: boolean;\n isHostedCheckoutEnabled?: boolean;\n onClick?: () => void;\n onCancel?: () => void;\n onPaymentComplete?: () => void;\n onError?(error?: Error | unknown): void;\n}\n\n/**\n *\n * PayPal Messages\n */\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface PayPalMessages {\n render(id: string): void;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface PayPalMessagesOptions {\n amount: number;\n placement: string;\n style?: PayPalMessagesStyleOptions;\n fundingSource?: string;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface PayPalMessagesStyleOptions {\n layout?: string;\n}\n\n/**\n *\n * Google Pay related types\n *\n */\n\ninterface GooglePay {\n config: () => Promise;\n confirmOrder: (confirmOrderConfig: ConfirmOrderConfig) => Promise<{ status: string }>;\n initiatePayerAction: (payerActionConfig: PayerActionConfig) => Promise;\n}\n\ninterface ConfirmOrderConfig {\n orderId: string;\n paymentMethodData: ConfirmOrderData;\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\ninterface PayerActionConfig {\n orderId: 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\n/**\n *\n * PayPal Payment fields\n *\n */\nexport interface PayPalPaymentFields {\n render(id: string): void;\n}\n\nexport interface PayPalPaymentFieldsOptions {\n style?: PayPalFieldsStyleOptions;\n fundingSource: string;\n fields: {\n name?: {\n value?: string;\n };\n email?: {\n value?: string;\n };\n };\n}\n\nexport interface PayPalFieldsStyleOptions {\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 = 'canceled',\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\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 methodId?: string;\n orderId?: number;\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 fastlaneToken?: string;\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 { 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 FundingType,\n PayPalFastlaneSdk,\n PayPalGooglePaySdk,\n PayPalHostWindow,\n PayPalInitializationData,\n PayPalMessagesSdk,\n PayPalSDK,\n PayPalSdkComponents,\n PayPalSdkConfig,\n} from './paypal-types';\nimport { transformLocaleToPayPalFormat } from './utils';\n\nexport default class PayPalSdkScriptLoader {\n private window: PayPalHostWindow;\n\n constructor(private scriptLoader: ScriptLoader) {\n this.window = window;\n }\n\n async getPayPalSDK(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n if (!this.window.paypal || forceLoad) {\n const paypalSdkScriptConfig = this.getPayPalSdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n storeLanguage,\n initializesOnCheckoutPage,\n );\n\n await this.loadPayPalSdk(paypalSdkScriptConfig);\n\n if (!this.window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.window.paypal;\n }\n\n async getPayPalFastlaneSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n sessionId: string,\n storeLanguage: string | undefined,\n ): Promise {\n if (!this.window.paypalFastlaneSdk) {\n const config = this.getPayPalFastlaneSdkConfiguration(\n paymentMethod,\n currencyCode,\n sessionId,\n storeLanguage,\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 getPayPalGooglePaySdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n if (!this.window.paypalGooglePay || forceLoad) {\n const paypalSdkScriptConfig = this.getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n storeLanguage,\n initializesOnCheckoutPage,\n );\n\n await this.loadPayPalSdk(paypalSdkScriptConfig);\n }\n\n if (!this.window.paypalGooglePay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypalGooglePay;\n }\n\n async getPayPalApmsSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n ) {\n if (!this.window.paypalApms) {\n const config = this.getPayPalApmSdkConfiguration(\n paymentMethod,\n currencyCode,\n storeLanguage,\n );\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 storeLanguage: string | undefined,\n ): Promise {\n if (!this.window.paypalMessages) {\n const paypalSdkMessagesConfig = this.getPayPalSdkMessagesConfiguration(\n paymentMethod,\n currencyCode,\n storeLanguage,\n );\n\n await this.loadPayPalSdk(paypalSdkMessagesConfig);\n }\n\n if (!this.window.paypalMessages) {\n throw new PaymentMethodClientUnavailableError();\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 getPayPalSdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage = true,\n ): PayPalSdkConfig {\n const { id, 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 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 =\n id === 'paypalcommercecreditcards' || id === 'bigcommerce_payments_creditcards';\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 enableVenmoFunding = isVenmoEnabled ? ['venmo'] : [];\n const disableVenmoFunding = !isVenmoEnabled ? ['venmo'] : [];\n const disableAPMsFunding = availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n );\n const googlePayComponent: PayPalSdkComponents = isGooglePayEnabled ? ['googlepay'] : [];\n const cardFieldsComponent: PayPalSdkComponents = 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 ...enabledAlternativePaymentMethods,\n ];\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\n },\n attributes: {\n 'data-partner-attribution-id': attributionId,\n 'data-client-token': clientToken,\n },\n };\n }\n\n private getPayPalFastlaneSdkConfiguration(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n sessionId: string,\n storeLanguage: string | undefined,\n ): PayPalSdkConfig {\n const { clientToken, initializationData } = paymentMethod;\n\n if (!initializationData || !initializationData.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { intent, clientId, merchantId, attributionId } = initializationData;\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit: true,\n components: [\n 'fastlane',\n 'buttons',\n 'payment-fields',\n 'hosted-fields',\n 'three-domain-secure',\n ],\n currency: currencyCode,\n ...(locale && { locale }),\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-sdk-client-token': clientToken,\n },\n };\n }\n\n private getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage = true,\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 buyerCountry,\n attributionId,\n isHostedCheckoutEnabled,\n isDeveloperModeApplicable,\n } = initializationData;\n\n const commit = isHostedCheckoutEnabled || initializesOnCheckoutPage;\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit,\n components: ['googlepay'],\n currency: currencyCode,\n intent,\n ...(isDeveloperModeApplicable && { 'buyer-country': buyerCountry }),\n ...(locale && { locale }),\n },\n attributes: {\n 'data-partner-attribution-id': attributionId,\n 'data-client-token': clientToken,\n 'data-namespace': 'paypalGooglePay',\n },\n };\n }\n\n private getPayPalApmSdkConfiguration(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\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 const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 storeLanguage: string | undefined,\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 const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport PayPalSdkScriptLoader from './paypal-sdk-script-loader';\n\nexport default function createPayPalSdkScriptLoader(): PayPalSdkScriptLoader {\n return new PayPalSdkScriptLoader(getScriptLoader());\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 PayPalRequestSender from './paypal-request-sender';\nimport PayPalSdkScriptLoader from './paypal-sdk-script-loader';\nimport {\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n PayPalCreateOrderCardFieldsResponse,\n PayPalCreateOrderRequestBody,\n PayPalInitializationData,\n PayPalOrderDetails,\n PayPalOrderStatus,\n PayPalSDK,\n StyleButtonColor,\n StyleButtonLabel,\n StyleButtonShape,\n} from './paypal-types';\n\nexport default class PayPalIntegrationService {\n private paypalSdk?: PayPalSDK;\n\n constructor(\n private formPoster: FormPoster,\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalRequestSender: PayPalRequestSender,\n private paypalSdkLoader: PayPalSdkScriptLoader,\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 = state.getPaymentMethodOrThrow(methodId);\n const storeLanguage = state.getLocale();\n\n this.paypalSdk = await this.paypalSdkLoader.getPayPalSDK(\n paymentMethod,\n currencyCode,\n storeLanguage,\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.paypalRequestSender.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.paypalRequestSender.createOrder(providerId, {\n cartId,\n ...requestBody,\n });\n\n return { orderId, ...(setupToken ? { setupToken } : {}) };\n }\n\n async updateOrder(providerId: string, methodId?: string, orderId?: number): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const consignment = state.getConsignmentsOrThrow()[0];\n\n try {\n await this.paypalRequestSender.updateOrder(providerId, {\n availableShippingOptions: consignment.availableShippingOptions,\n cartId: cart.id,\n selectedShippingOption: consignment.selectedShippingOption,\n ...(methodId ? { methodId } : {}),\n ...(orderId ? { orderId } : {}),\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.paypalRequestSender.getOrderStatus(methodId, options);\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((option) => {\n if (consignment.selectedShippingOption) {\n const shippingOptionId = consignment.selectedShippingOption.id;\n\n return option.id === shippingOptionId;\n }\n\n return false;\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: address?.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 phone: payer.phone?.phone_number?.national_number,\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","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-types';\n\nexport default class PayPalRequestSender {\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 methodId: string,\n requestBody: PayPalUpdateOrderRequestBody,\n ): Promise {\n const url = `/api/storefront/initialization/${methodId}`;\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: string,\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 { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalSdkScriptLoader from './create-paypal-sdk-script-loader';\nimport PaypalIntegrationService from './paypal-integration-service';\nimport PaypalRequestSender from './paypal-request-sender';\n\nconst createPayPalIntegrationService = (paymentIntegrationService: PaymentIntegrationService) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new PaypalIntegrationService(\n createFormPoster(),\n paymentIntegrationService,\n new PaypalRequestSender(createRequestSender({ host: getHost() })),\n createPayPalSdkScriptLoader(),\n );\n};\n\nexport default createPayPalIntegrationService;\n","import {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalIntegrationService from './paypal-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalButtonOptions,\n PayPalButtons,\n PayPalBuyNowInitializeOptions,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from './paypal-types';\n\nclass PaypalButtonCreationService {\n private onError?: PayPalButtonOptions['onError'];\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\n ) {}\n\n createPayPalButton(\n providerId: string,\n methodId: string,\n buttonOptions: PayPalButtonOptions,\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): PayPalButtons {\n const {\n style,\n fundingSource,\n isAppSwitchEnabled,\n isHostedCheckoutEnabled,\n onClick,\n onCancel,\n onPaymentComplete,\n onError,\n } = buttonOptions;\n\n this.onError = onError;\n\n const paypalSdk = this.paypalIntegrationService.getPayPalSdkOrThrow();\n const isAvailableFundingSource = Object.values(paypalSdk.FUNDING).includes(fundingSource);\n\n if (!isAvailableFundingSource) {\n throw new InvalidArgumentError(\n `Unable to initialize PayPal button because \"fundingSource\" argument is not valid funding source.`,\n );\n }\n\n const hostedCheckoutCallbacks = {\n ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data, providerId),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data, providerId),\n }),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(\n data,\n actions,\n methodId,\n providerId,\n onPaymentComplete,\n ),\n };\n\n return paypalSdk.Buttons({\n fundingSource,\n style: this.paypalIntegrationService.getValidButtonStyle(style),\n ...(isAppSwitchEnabled && {\n appSwitchWhenAvailable: true,\n }),\n createOrder: async () => {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n\n return this.paypalIntegrationService.createOrder(providerId);\n },\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalIntegrationService.tokenizePayment(methodId, orderID),\n ...(onClick ? { onClick } : {}),\n ...(onCancel ? { onCancel } : {}),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n });\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n providerId: 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.paypalIntegrationService.getBillingAddressFromOrderDetails(orderDetails);\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalIntegrationService.getShippingAddressFromOrderDetails(orderDetails);\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalIntegrationService.updateOrder(providerId);\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalIntegrationService.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 providerId: string,\n ): Promise {\n const address = this.paypalIntegrationService.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.paypalIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalIntegrationService.updateOrder(providerId);\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n providerId: string,\n ): Promise {\n const shippingOption = this.paypalIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalIntegrationService.updateOrder(providerId);\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\nexport default PaypalButtonCreationService;\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';\nimport {\n PaypalButtonCreationService,\n PayPalButtonOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceCustomerInitializeOptions, {\n WithPayPalCommerceCustomerInitializeOptions,\n} from './paypal-commerce-customer-initialize-options';\n\nexport default class PayPalCommerceCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\n private paypalButtonCreationService: PaypalButtonCreationService,\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 const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethod(methodId);\n\n if (!paymentMethod) {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n }\n\n const paypalSdk = await this.paypalIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n console.error(\n '[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\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, onError } = paypalcommerce;\n\n const paypalSdk = this.paypalIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, paymentButtonStyles, isAppSwitchEnabled } =\n paymentMethod.initializationData || {};\n const { checkoutTopButtonStyles } = paymentButtonStyles || {};\n\n const buttonOptions: PayPalButtonOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n isAppSwitchEnabled,\n isHostedCheckoutEnabled,\n style: {\n ...checkoutTopButtonStyles,\n height: DefaultCheckoutButtonHeight,\n },\n ...(onClick && { onClick: () => onClick() }),\n ...(isHostedCheckoutEnabled && onComplete && { onPaymentComplete: () => onComplete() }),\n onError,\n };\n\n const paypalButton = this.paypalButtonCreationService.createPayPalButton(\n 'paypalcommerce',\n methodId,\n buttonOptions,\n );\n\n if (paypalButton.isEligible()) {\n if (paypalButton.hasReturned?.() && isAppSwitchEnabled) {\n paypalButton.resume?.();\n } else {\n paypalButton.render(`#${container}`);\n }\n } else {\n this.paypalIntegrationService.removeElement(container);\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalIntegrationService,\n PaypalButtonCreationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceCustomerStrategy from './paypal-commerce-customer-strategy';\n\nconst createPayPalCommerceCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceCustomerStrategy\n> = (paymentIntegrationService) => {\n const paypalIntegrationService = createPayPalIntegrationService(paymentIntegrationService);\n const paypalButtonCreationService = new PaypalButtonCreationService(\n paymentIntegrationService,\n paypalIntegrationService,\n );\n\n return new PayPalCommerceCustomerStrategy(\n paymentIntegrationService,\n paypalIntegrationService,\n paypalButtonCreationService,\n );\n};\n\nexport default toResolvableModule(createPayPalCommerceCustomerStrategy, [{ id: 'paypalcommerce' }]);\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 locale?: string;\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}\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 paypalBNPLConfiguration?: PayPalBNPLConfigurationItem[];\n isAppSwitchEnabled?: boolean;\n}\n\nexport interface PayPalBNPLConfigurationItem {\n id: string;\n name: string;\n status: boolean;\n styles: 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 hasReturned?(): boolean;\n resume?(): void;\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 phone?: {\n phone_number: {\n national_number: string;\n };\n };\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 IDEAL = 'ideal',\n}\n\nexport interface PayPalOrderData {\n orderId: string;\n setupToken?: string;\n approveUrl: string;\n fastlaneToken?: 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 fastlaneToken?: string;\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 state.getLocale(),\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: address?.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 phone: payer.phone?.phone_number?.national_number,\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","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';\nimport { transformLocaleToPayPalFormat } from '@bigcommerce/checkout-sdk/paypal-utils';\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 storeLanguage: string | undefined,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n const paypalSdkScriptConfig = this.getPayPalSdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n storeLanguage,\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 storeLanguage: string | undefined,\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 enableVenmoFunding = isVenmoEnabled ? ['venmo'] : [];\n const disableVenmoFunding = !isVenmoEnabled ? ['venmo'] : [];\n const disableAPMsFunding = availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n );\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 ...enabledAlternativePaymentMethods,\n ];\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 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 const paypalSdk = await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n console.error(\n '[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\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, isAppSwitchEnabled } =\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 ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n }),\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 const paypalSdk = await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n console.error(\n '[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\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 { 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 { CookieStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport {\n PayPalFastlane,\n PayPalFastlaneAddress,\n PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneLookupCustomerByEmailResult,\n PayPalFastlaneProfileCard,\n PayPalFastlaneProfileName,\n PayPalFastlaneProfilePhone,\n PayPalFastlaneProfileToBcCustomerDataMappingResult,\n PayPalFastlaneSdk,\n PayPalFastlaneStylesOption,\n PayPalHostWindow,\n} from './paypal-types';\n\nexport default class PaypalFastlaneUtils {\n private window: PayPalHostWindow;\n\n constructor() {\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 *\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(sessionId: string): void {\n const expires = new Date();\n\n expires.setDate(expires.getDate() + 14); // 2 weeks expiry\n\n const cookiesOption = {\n expires,\n secure: true,\n };\n\n CookieStorage.set('bc-fastlane-sessionId', sessionId, cookiesOption);\n }\n\n removeStorageSessionId(): void {\n CookieStorage.remove('bc-fastlane-sessionId');\n }\n\n getStorageSessionId(): string {\n return CookieStorage.get('bc-fastlane-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 PaypalFastlaneUtils from './paypal-fastlane-utils';\n\nexport default function createPaypalFastlaneUtils(): PaypalFastlaneUtils {\n return new PaypalFastlaneUtils();\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 PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneStylesOption,\n PayPalFastlaneUtils,\n PayPalInitializationData,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-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 paypalSdkScriptLoader: PayPalSdkScriptLoader,\n private paypalFastlaneUtils: PayPalFastlaneUtils,\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 = state.getPaymentMethodOrThrow(methodId);\n\n const isTestModeEnabled = !!paymentMethod.initializationData?.isDeveloperModeApplicable;\n\n const paypalFastlaneSdk = await this.paypalSdkScriptLoader.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n state.getLocale(),\n );\n\n await this.paypalFastlaneUtils.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 await this.paymentIntegrationService.updatePaymentProviderCustomer({\n authenticationState: undefined,\n addresses: undefined,\n instruments: undefined,\n });\n\n this.paypalFastlaneUtils.removeStorageSessionId();\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.paypalFastlaneUtils.lookupCustomerOrThrow(\n customerEmail,\n );\n\n const authenticationResult =\n await this.paypalFastlaneUtils.triggerAuthenticationFlowOrThrow(customerContextId);\n\n const isAuthenticationFlowCanceled =\n authenticationResult.authenticationState === PayPalFastlaneAuthenticationState.CANCELED;\n\n await this.updateCustomerDataState(methodId, authenticationResult);\n\n if (isAuthenticationFlowCanceled) {\n this.paypalFastlaneUtils.removeStorageSessionId();\n } else {\n this.paypalFastlaneUtils.updateStorageSessionId(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.paypalFastlaneUtils.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 = 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 createPayPalFastlaneUtils,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceFastlaneCustomerStrategy from './paypal-commerce-fastlane-customer-strategy';\n\nconst createPayPalCommerceFastlaneCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceFastlaneCustomerStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceFastlaneCustomerStrategy(\n paymentIntegrationService,\n createPayPalSdkScriptLoader(),\n createPayPalFastlaneUtils(),\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 { PaymentMethod } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { StripePaymentMethod } from './stripe';\n\nexport function isStripePaymentMethodLike(\n paymentMethod: PaymentMethod,\n): paymentMethod is StripePaymentMethod {\n return (\n typeof paymentMethod === 'object' &&\n paymentMethod !== null &&\n 'initializationData' in paymentMethod &&\n (paymentMethod as StripePaymentMethod).initializationData !== undefined &&\n (paymentMethod as StripePaymentMethod).initializationData !== null &&\n typeof (paymentMethod as StripePaymentMethod).initializationData === 'object' &&\n 'stripePublishableKey' in (paymentMethod as StripePaymentMethod).initializationData &&\n 'stripeConnectedAccount' in (paymentMethod as StripePaymentMethod).initializationData &&\n 'shopperLanguage' in (paymentMethod as StripePaymentMethod).initializationData &&\n typeof (paymentMethod as StripePaymentMethod).initializationData.stripePublishableKey !==\n 'undefined' &&\n typeof (paymentMethod as StripePaymentMethod).initializationData.stripeConnectedAccount !==\n 'undefined' &&\n typeof (paymentMethod as StripePaymentMethod).initializationData.shopperLanguage !==\n 'undefined'\n );\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 {\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';\nimport {\n isStripePaymentMethodLike,\n STRIPE_UPE_CLIENT_API_VERSION,\n STRIPE_UPE_CLIENT_BETAS,\n StripeAppearanceOptions,\n StripeClient,\n StripeElementEvent,\n StripeElements,\n StripeElementType,\n StripeEventType,\n StripeFormMode,\n StripeJsVersion,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport isStripeAcceleratedCheckoutCustomer from './is-stripe-accelerated-checkout-customer';\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: StripeScriptLoader,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithStripeUPECustomerInitializeOptions,\n ): Promise {\n let stripeUPEClient: StripeClient;\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 (!isStripePaymentMethodLike(paymentMethod) || !clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\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: StripeAppearanceOptions | 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 paymentMethod.initializationData,\n state.getCartLocale(),\n StripeJsVersion.V3,\n STRIPE_UPE_CLIENT_BETAS,\n STRIPE_UPE_CLIENT_API_VERSION,\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(StripeElementEvent.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 { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeUPECustomerStrategy from './stripe-upe-customer-strategy';\n\nconst createStripeUPECustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new StripeUPECustomerStrategy(\n paymentIntegrationService,\n new StripeScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createStripeUPECustomerStrategy, [{ id: 'stripeupe' }]);\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 StripeClient,\n StripeConfirmPaymentData,\n StripeElement,\n StripeElements,\n StripeElementType,\n StripeError,\n StripeInitializationData,\n StripeJsVersion,\n StripePaymentIntentStatus,\n StripeStringConstants,\n} from './stripe';\nimport StripePaymentInitializeOptions from './stripe-initialize-options';\nimport StripeScriptLoader from './stripe-script-loader';\n\nexport default class StripeIntegrationService {\n private isMounted = false;\n private checkoutEventsUnsubscribe?: () => void;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n ) {}\n\n deinitialize(): void {\n this.checkoutEventsUnsubscribe?.();\n this.isMounted = false;\n }\n\n initCheckoutEventsSubscription(\n gatewayId: string,\n methodId: string,\n stripeInitializationOptions: StripePaymentInitializeOptions,\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 stripeInitializationOptions.onError?.(error);\n }\n\n return;\n }\n\n if (!this.isMounted) {\n await stripeElements?.fetchUpdates();\n this.mountElement(paymentElement, stripeInitializationOptions.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(methodId: string, stripeUPEClient?: StripeClient): 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 === StripePaymentIntentStatus.SUCCEEDED;\n }\n\n mapStripePaymentData(\n stripeElements?: StripeElements,\n returnUrl?: string,\n shouldAllowRedisplay = false,\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 ...(shouldAllowRedisplay ? { allow_redisplay: 'always' } : {}),\n billing_details: {\n email,\n address,\n name: this.getShopperFullName(billingAddress),\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 // INFO: no need to update Stripe Element if client token is not present\n return;\n }\n\n this.scriptLoader.updateStripeElements({ clientSecret: clientToken });\n }\n\n getStripeJsVersion(initializationData: StripeInitializationData): StripeJsVersion {\n return initializationData.useNewStripeJsVersion\n ? StripeJsVersion.CLOVER\n : StripeJsVersion.V3;\n }\n\n mapStripeAddress(address?: Address): AddressOptions {\n if (address) {\n const {\n city,\n address1,\n address2,\n countryCode: country,\n postalCode,\n stateOrProvinceCode,\n } = address;\n\n return {\n city,\n country,\n postal_code: postalCode,\n line1: address1,\n line2: address2,\n ...(stateOrProvinceCode ? { state: stateOrProvinceCode } : {}),\n };\n }\n\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n getShopperFullName(address?: Address): string {\n const { firstName = '', lastName = '' } = address || {};\n\n return `${firstName} ${lastName}`.trim();\n }\n}\n","import { StripeError } from './stripe';\n\nexport function isStripeError(error: unknown): error is StripeError {\n return typeof error === 'object' && error !== null && 'type' in error;\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\nexport const DEFAULT_CONTAINER_STYLES = {\n position: 'fixed',\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\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 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","export const expressCheckoutAllowedCountryCodes = [\n 'AC',\n 'AD',\n 'AE',\n 'AF',\n 'AG',\n 'AI',\n 'AL',\n 'AM',\n 'AO',\n 'AQ',\n 'AR',\n 'AT',\n 'AU',\n 'AW',\n 'AX',\n 'AZ',\n 'BA',\n 'BB',\n 'BD',\n 'BE',\n 'BF',\n 'BG',\n 'BH',\n 'BI',\n 'BJ',\n 'BL',\n 'BM',\n 'BN',\n 'BO',\n 'BQ',\n 'BR',\n 'BS',\n 'BT',\n 'BV',\n 'BW',\n 'BY',\n 'BZ',\n 'CA',\n 'CD',\n 'CF',\n 'CG',\n 'CH',\n 'CI',\n 'CK',\n 'CL',\n 'CM',\n 'CN',\n 'CO',\n 'CR',\n 'CV',\n 'CW',\n 'CY',\n 'CZ',\n 'DE',\n 'DJ',\n 'DK',\n 'DM',\n 'DO',\n 'DZ',\n 'EC',\n 'EE',\n 'EG',\n 'EH',\n 'ER',\n 'ES',\n 'ET',\n 'FI',\n 'FJ',\n 'FK',\n 'FO',\n 'FR',\n 'GA',\n 'GB',\n 'GD',\n 'GE',\n 'GF',\n 'GG',\n 'GH',\n 'GI',\n 'GL',\n 'GM',\n 'GN',\n 'GP',\n 'GQ',\n 'GR',\n 'GS',\n 'GT',\n 'GU',\n 'GW',\n 'GY',\n 'HK',\n 'HN',\n 'HR',\n 'HT',\n 'HU',\n 'ID',\n 'IE',\n 'IL',\n 'IM',\n 'IN',\n 'IO',\n 'IQ',\n 'IS',\n 'IT',\n 'JE',\n 'JM',\n 'JO',\n 'JP',\n 'KE',\n 'KG',\n 'KH',\n 'KI',\n 'KM',\n 'KN',\n 'KR',\n 'KW',\n 'KY',\n 'KZ',\n 'LA',\n 'LB',\n 'LC',\n 'LI',\n 'LK',\n 'LR',\n 'LS',\n 'LT',\n 'LU',\n 'LV',\n 'LY',\n 'MA',\n 'MC',\n 'MD',\n 'ME',\n 'MF',\n 'MG',\n 'MK',\n 'ML',\n 'MM',\n 'MN',\n 'MO',\n 'MQ',\n 'MR',\n 'MS',\n 'MT',\n 'MU',\n 'MV',\n 'MW',\n 'MX',\n 'MY',\n 'MZ',\n 'NA',\n 'NC',\n 'NE',\n 'NG',\n 'NI',\n 'NL',\n 'NO',\n 'NP',\n 'NR',\n 'NU',\n 'NZ',\n 'OM',\n 'PA',\n 'PE',\n 'PF',\n 'PG',\n 'PH',\n 'PK',\n 'PL',\n 'PM',\n 'PN',\n 'PR',\n 'PS',\n 'PT',\n 'PY',\n 'QA',\n 'RE',\n 'RO',\n 'RS',\n 'RU',\n 'RW',\n 'SA',\n 'SB',\n 'SC',\n 'SD',\n 'SE',\n 'SG',\n 'SH',\n 'SI',\n 'SJ',\n 'SK',\n 'SL',\n 'SM',\n 'SN',\n 'SO',\n 'SR',\n 'SS',\n 'ST',\n 'SV',\n 'SX',\n 'SZ',\n 'TA',\n 'TC',\n 'TD',\n 'TF',\n 'TG',\n 'TH',\n 'TJ',\n 'TK',\n 'TL',\n 'TM',\n 'TN',\n 'TO',\n 'TR',\n 'TT',\n 'TV',\n 'TW',\n 'TZ',\n 'UA',\n 'UG',\n 'US',\n 'UY',\n 'UZ',\n 'VA',\n 'VC',\n 'VE',\n 'VG',\n 'VN',\n 'VU',\n 'WF',\n 'WS',\n 'XK',\n 'YE',\n 'YT',\n 'ZA',\n 'ZM',\n 'ZW',\n 'ZZ',\n];\n\n// Stripe has restricted the number of shipping rates to 9.\nexport const stripeAllowedShippingOptionsLength = 9;\n","import { round } from 'lodash';\n\nimport {\n AmountTransformer,\n CustomerInitializeOptions,\n CustomerStrategy,\n InvalidArgumentError,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n Payment,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n ShippingOption,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n isStripePaymentMethodLike,\n StripeAdditionalActionRequired,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeError,\n StripeEventType,\n StripeInitializationData,\n StripeIntegrationService,\n StripeLinkV2Event,\n StripeLinkV2Options,\n StripeLinkV2ShippingRate,\n StripePaymentMethodType,\n StripeResult,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport {\n expressCheckoutAllowedCountryCodes,\n stripeAllowedShippingOptionsLength,\n} from './constants';\nimport { WithStripeOCSCustomerInitializeOptions } from './stripe-ocs-customer-initialize-options';\n\nexport default class StripeLinkV2CustomerStrategy implements CustomerStrategy {\n private _stripeClient?: StripeClient;\n private _stripeElements?: StripeElements;\n private _linkV2Element?: StripeElement;\n private _amountTransformer?: AmountTransformer;\n private _onComplete?: (orderId?: number) => Promise;\n private _loadingIndicatorContainer?: string;\n private _captureMethod?: 'automatic' | 'manual';\n private _currencyCode?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n private stripeIntegrationService: StripeIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithStripeOCSCustomerInitializeOptions,\n ): Promise {\n const { stripeocs } = options || {};\n\n if (!stripeocs) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"options\" argument is not provided.`,\n );\n }\n\n const { gatewayId, container } = stripeocs;\n\n if (!container || !gatewayId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const methodId = this._getMethodId(gatewayId);\n const state = await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n const paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n const { loadingContainerId, buttonHeight, onComplete } = stripeocs;\n\n this._loadingIndicatorContainer = loadingContainerId;\n\n this._onComplete = onComplete;\n\n if (!isStripePaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { initializationData } = paymentMethod;\n const { captureMethod } = initializationData;\n const stripeJsVersion =\n this.stripeIntegrationService.getStripeJsVersion(initializationData);\n\n this._captureMethod = captureMethod;\n this._stripeClient = await this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n stripeJsVersion,\n );\n\n await this._mountExpressCheckoutElement(container, this._stripeClient, buttonHeight);\n\n this._initializeEvents(methodId);\n }\n\n signIn() {\n return Promise.resolve();\n }\n\n signOut() {\n return Promise.resolve();\n }\n\n executePaymentMethodCheckout() {\n return Promise.resolve();\n }\n\n deinitialize() {\n return Promise.resolve();\n }\n\n private async _mountExpressCheckoutElement(\n container: string,\n stripeExpressCheckoutClient: StripeClient,\n buttonHeight = 40,\n ) {\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n const expressCheckoutOptions: StripeElementsCreateOptions = {\n shippingAddressRequired: shouldRequireShippingAddress,\n ...(shouldRequireShippingAddress\n ? { allowedShippingCountries: await this._getAvailableCountries() }\n : {}),\n ...(shouldRequireShippingAddress\n ? { shippingRates: [{ id: '_', amount: 0, displayName: 'Pending rates' }] }\n : {}),\n billingAddressRequired: true,\n emailRequired: true,\n phoneNumberRequired: true,\n paymentMethods: {\n link: StripeStringConstants.AUTO,\n applePay: StripeStringConstants.NEVER,\n googlePay: StripeStringConstants.NEVER,\n amazonPay: StripeStringConstants.NEVER,\n paypal: StripeStringConstants.NEVER,\n klarna: StripeStringConstants.NEVER,\n },\n // Minimal buttonHeight value is 40\n buttonHeight,\n };\n\n const { cartAmount } = this.paymentIntegrationService.getState().getCartOrThrow();\n\n const elementsOptions: StripeLinkV2Options = {\n mode: 'payment',\n amount: this._toCents(cartAmount),\n currency: this._getCurrency(),\n ...(this._captureMethod ? { captureMethod: this._captureMethod } : {}),\n };\n\n this._stripeElements = stripeExpressCheckoutClient.elements(elementsOptions);\n\n this._linkV2Element = this._stripeElements.create(\n StripeElementType.EXPRESS_CHECKOUT,\n expressCheckoutOptions,\n );\n this._linkV2Element.mount(`#${container}`);\n\n return this._linkV2Element;\n }\n\n /** Events * */\n\n private _initializeEvents(methodId: string): void {\n if (!this._linkV2Element) {\n return;\n }\n\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n\n if (shouldRequireShippingAddress) {\n this._linkV2Element.on(StripeElementEvent.SHIPPING_ADDRESS_CHANGE, async (event) =>\n this._onShippingAddressChange(event),\n );\n this._linkV2Element.on(StripeElementEvent.SHIPPING_RATE_CHANGE, async (event) =>\n this._onShippingRateChange(event),\n );\n }\n\n this._linkV2Element.on(StripeElementEvent.CONFIRM, async (event) =>\n this._onConfirm(event, methodId),\n );\n\n this._linkV2Element.on(StripeElementEvent.CANCEL, this._onCancel);\n }\n\n private async _onShippingAddressChange(event: StripeEventType): Promise {\n if (!('address' in event)) {\n return;\n }\n\n const shippingAddress = event.address;\n // Depending on the country, some fields can be missing or partially redacted.\n // For example, the shipping address in the US can only contain a city, state, and ZIP code.\n // The full shipping address appears in the confirm event object after the purchase is confirmed in the browser’s payment interface.\n const result = {\n firstName: '',\n lastName: '',\n phone: '',\n company: '',\n address1: '',\n address2: '',\n city: shippingAddress?.city || '',\n countryCode: shippingAddress?.country || '',\n postalCode: shippingAddress?.postal_code || '',\n stateOrProvince: shippingAddress?.state || '',\n stateOrProvinceCode: shippingAddress?.state || '',\n customFields: [],\n };\n\n await this.paymentIntegrationService.updateShippingAddress(result);\n\n const shippingRates = await this._getAvailableShippingOptions();\n\n await this._updateDisplayedPrice();\n\n if (!shippingRates?.length) {\n event.reject();\n } else {\n event.resolve({\n shippingRates,\n });\n }\n }\n\n private _onCancel() {\n throw new PaymentMethodCancelledError();\n }\n\n private async _onShippingRateChange(event: StripeEventType) {\n if ('shippingRate' in event) {\n const { shippingRate } = event;\n\n await this._handleShippingOptionChange(shippingRate?.id);\n\n await this._updateDisplayedPrice();\n\n event.resolve({});\n }\n }\n\n /** Confirm methods * */\n private async _onConfirm(event: StripeEventType, methodId: string) {\n if (\n 'billingDetails' in event &&\n 'shippingAddress' in event &&\n this._stripeClient &&\n this._stripeElements\n ) {\n await this._updateShippingAndBillingAddress(event);\n await this.paymentIntegrationService.submitOrder();\n\n const paymentPayload = this._getPaymentPayload(methodId);\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._processAdditionalAction(error, methodId);\n }\n }\n\n return Promise.resolve();\n }\n\n private async _updateShippingAndBillingAddress(event: StripeLinkV2Event) {\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n\n const firstName =\n event.shippingAddress?.name?.split(' ')[0] ||\n event.billingDetails?.name?.split(' ')[0] ||\n '';\n const lastName =\n event.shippingAddress?.name?.split(' ')[1] ||\n event.billingDetails?.name?.split(' ')[1] ||\n '';\n\n if (shouldRequireShippingAddress) {\n const shippingAddress = this._mapShippingAddress(\n event.shippingAddress,\n event.billingDetails,\n firstName,\n lastName,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n }\n\n const billingAddress = this._mapBillingAddress(\n event.shippingAddress,\n event.billingDetails,\n firstName,\n lastName,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n private _mapShippingAddress(\n shippingAddress: StripeLinkV2Event['shippingAddress'],\n billingDetails: StripeLinkV2Event['billingDetails'],\n firstName: string,\n lastName: string,\n ) {\n return {\n firstName,\n lastName,\n phone: billingDetails?.phone || '',\n company: '',\n address1: shippingAddress?.address?.line1 || '',\n address2: shippingAddress?.address?.line2 || '',\n city: shippingAddress?.address?.city || '',\n countryCode: shippingAddress?.address?.country || '',\n postalCode: shippingAddress?.address?.postal_code || '',\n stateOrProvince: shippingAddress?.address?.state || '',\n stateOrProvinceCode: shippingAddress?.address?.state || '',\n customFields: [],\n };\n }\n\n private _mapBillingAddress(\n shippingAddress: StripeLinkV2Event['shippingAddress'],\n billingDetails: StripeLinkV2Event['billingDetails'],\n firstName: string,\n lastName: string,\n ) {\n return {\n email: billingDetails?.email || '',\n firstName,\n lastName,\n phone: billingDetails?.phone || '',\n company: '',\n address1: billingDetails?.address?.line1 || '',\n address2: '',\n city: billingDetails?.address?.city || '',\n countryCode: billingDetails?.address?.country || '',\n postalCode: billingDetails?.address?.postal_code || '',\n stateOrProvince: billingDetails?.address?.state || '',\n stateOrProvinceCode: shippingAddress?.address?.state || '',\n customFields: [],\n };\n }\n\n private async _processAdditionalAction(error: unknown, methodId: string): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n if (!this._stripeClient || !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 additionalActionData,\n methodId,\n );\n\n const paymentPayload = this._getPaymentPayload(methodId, paymentIntent?.id || token);\n\n try {\n this._toggleLoadingIndicator(true);\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n await this._completeCheckoutFlow();\n } catch (error) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n } finally {\n this._toggleLoadingIndicator(false);\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n additionalActionData: StripeAdditionalActionRequired['data'],\n methodId: string,\n ): Promise {\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeIntegrationService.mapStripePaymentData(\n this._stripeElements,\n redirect_url,\n );\n let stripeError: StripeError | undefined;\n\n try {\n const isPaymentCompleted = await this.stripeIntegrationService.isPaymentCompleted(\n methodId,\n this._stripeClient,\n );\n\n const confirmationResult = !isPaymentCompleted\n ? await this._stripeClient?.confirmPayment({\n elements: stripePaymentData.elements,\n clientSecret: token,\n redirect: StripeStringConstants.IF_REQUIRED,\n confirmParams: {\n return_url: stripePaymentData.confirmParams?.return_url,\n },\n })\n : await this._stripeClient?.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 return this.stripeIntegrationService.throwStripeError(stripeError);\n }\n }\n\n private async _completeCheckoutFlow() {\n if (typeof this._onComplete === 'function') {\n return this._onComplete();\n }\n\n window.location.replace('/order-confirmation');\n\n return Promise.resolve();\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 ...(token ? { credit_card_token: { token } } : {}),\n confirm: false,\n method: StripePaymentMethodType.Link,\n };\n\n return {\n methodId,\n paymentData: {\n formattedPayload,\n },\n };\n }\n\n /** Utils * */\n\n private _shouldRequireShippingAddress() {\n const { getCartOrThrow } = this.paymentIntegrationService.getState();\n const { lineItems } = getCartOrThrow();\n\n return !!lineItems.physicalItems.length;\n }\n\n private async _updateDisplayedPrice() {\n if (this._stripeElements) {\n this._stripeElements.update({\n currency: this._getCurrency(),\n mode: 'payment',\n amount: await this._getTotalPrice(),\n });\n }\n }\n\n private _getCurrency() {\n if (!this._currencyCode) {\n const { code: currencyCode } = this.paymentIntegrationService\n .getState()\n .getCartOrThrow().currency;\n\n this._currencyCode = currencyCode.toLowerCase();\n }\n\n return this._currencyCode;\n }\n\n private async _getTotalPrice(): Promise {\n await this.paymentIntegrationService.loadCheckout();\n\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 this._toCents(+totalPrice);\n }\n\n private async _getAvailableCountries(): Promise {\n const countries = await this.paymentIntegrationService.loadShippingCountries();\n const deliverableCountries =\n countries.getShippingCountries()?.map((country) => country.code) || [];\n\n return deliverableCountries.filter((code) => {\n return expressCheckoutAllowedCountryCodes.includes(code);\n });\n }\n\n private async _getAvailableShippingOptions(): Promise {\n const state = this.paymentIntegrationService.getState();\n const consignments = state.getConsignments();\n\n if (!consignments?.[0]) {\n return;\n }\n\n const consignment = consignments[0];\n const options = (consignment.availableShippingOptions || []).map(\n this._getStripeShippingOption.bind(this),\n );\n const recommendedShippingOption = consignment.availableShippingOptions?.find(\n (shippingOption) => shippingOption.isRecommended,\n );\n const selectedId = consignment.selectedShippingOption?.id;\n const recommendedId = recommendedShippingOption?.id;\n\n if (selectedId) {\n // Set selected shipping option first in the array, as it will be selected by default\n options.sort((option) => (option.id === selectedId ? -1 : 0));\n } else if (recommendedId) {\n // Set recommended shipping option first in the array, as it will be selected by default\n options.sort((option) => (option.id === recommendedId ? -1 : 0));\n await this._handleShippingOptionChange(recommendedId);\n } else {\n await this._handleShippingOptionChange(options[0]?.id);\n }\n\n // Stripe has restricted the number of shipping rates.\n return options.slice(0, stripeAllowedShippingOptionsLength);\n }\n\n private _getStripeShippingOption({ id, cost, description }: ShippingOption) {\n return {\n id,\n displayName: description,\n amount: this._toCents(cost),\n };\n }\n\n private async _handleShippingOptionChange(optionId?: string) {\n if (!optionId || optionId === 'shipping_option_unselected') {\n return;\n }\n\n return this.paymentIntegrationService.selectShippingOption(optionId);\n }\n\n private _getAmountTransformer() {\n if (this._amountTransformer) {\n return this._amountTransformer;\n }\n\n const { getCart } = this.paymentIntegrationService.getState();\n const { currency } = getCart() || {};\n\n if (currency) {\n const amountTransformer = new AmountTransformer(currency.decimalPlaces);\n\n return amountTransformer;\n }\n }\n\n private _toCents(amount: number) {\n const fallbackValue = Math.round(amount * 100);\n const amountTransformer = this._getAmountTransformer();\n\n if (amountTransformer) {\n return amountTransformer.toInteger(amount);\n }\n\n return fallbackValue;\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 _getMethodId(gatewayId: string): string {\n const { initializationData: { checkoutSessionEnabled } = {} } =\n this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(gatewayId);\n\n return checkoutSessionEnabled\n ? StripePaymentMethodType.CHECKOUT_SESSION\n : StripePaymentMethodType.OCS;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\nimport { DEFAULT_CONTAINER_STYLES, LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport StripeLinkV2CustomerStrategy from './stripe-link-v2-customer-strategy';\n\nconst createStripeLinkV2CustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n const loadingIndicator = new LoadingIndicator({\n containerStyles: DEFAULT_CONTAINER_STYLES,\n });\n\n return new StripeLinkV2CustomerStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n loadingIndicator,\n );\n};\n\nexport default toResolvableModule(createStripeLinkV2CustomerStrategy, [{ id: 'stripeocs' }]);\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 { 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","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: [{ code: string }];\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 type AdyenComponentFieldVisibility = 'hidden' | 'readOnly' | 'editable';\n\nexport interface AdyenOpenInvoiceComponentVisibility {\n personalDetails?: AdyenComponentFieldVisibility;\n billingAddress?: AdyenComponentFieldVisibility;\n deliveryAddress?: AdyenComponentFieldVisibility;\n}\n\nexport interface AdyenBoletoComponentOptions extends AdyenComponentEvents {\n personalDetailsRequired?: boolean;\n billingAddressRequired?: boolean;\n showEmailAddress?: boolean;\n visibility?: AdyenOpenInvoiceComponentVisibility;\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 { 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","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 { 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.71.1/adyen.css`,\n {\n prepend: false,\n attributes: {\n integrity:\n 'sha384-5MvB4RnzvviA3VBT4KYABZ4HXNZG5LRqREEgd41xt/pf/QvKmsj2O9GuNuywRXx9',\n crossorigin: 'anonymous',\n },\n },\n ),\n this._scriptLoader.loadScript(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/5.71.1/adyen.js`,\n {\n async: true,\n attributes: {\n integrity:\n 'sha384-yvY2yFNR4WqIjPqP9MzjI+gJimmaJnAvj4rLHKvgJbgFD5fMuf8zIJrFJOW8Lhhf',\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 static readonly mountContainerMaxWaitMs = 5000;\n private static readonly mountContainerPollIntervalMs = 50;\n\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._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 paymentData.instrumentId,\n bigpayToken,\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 _getLocale(): string | undefined {\n const locale = this.paymentIntegrationService.getState().getLocale();\n\n if (locale && locale.substring(0, 2) === 'es') {\n return 'es';\n }\n\n return locale;\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 void this._mountElement(additionalActionComponent, containerId)\n .then(() => {\n if (onLoad && typeof onLoad === 'function') {\n onLoad(() => {\n reject(new PaymentMethodCancelledError());\n additionalActionComponent.unmount();\n });\n }\n })\n .catch(reject);\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 async _mountCardVerificationComponent(): Promise {\n const adyenv3 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n\n if (!adyenv3.cardVerificationContainerId) {\n return undefined;\n }\n\n const 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 await this._mountElement(\n cardVerificationComponent,\n adyenv3.cardVerificationContainerId,\n );\n } catch {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return cardVerificationComponent;\n }\n\n private async _mountPaymentComponent(paymentMethod: PaymentMethod): Promise {\n const adyenv3 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n const billingAddress = this.paymentIntegrationService.getState().getBillingAddress();\n const { prefillCardHolderName } = paymentMethod.initializationData;\n\n const paymentComponent = adyenClient.create(paymentMethod.method, {\n ...(this._isOneyPaymentMethod(paymentMethod.method)\n ? {\n visibility: {\n personalDetails: 'hidden',\n billingAddress: 'hidden',\n deliveryAddress: 'hidden',\n },\n }\n : {}),\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 await this._mountElement(paymentComponent, adyenv3.containerId);\n } catch {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return paymentComponent;\n }\n\n private _isOneyPaymentMethod(method: string): boolean {\n return method.startsWith('facilypay');\n }\n\n private async _processAdditionalAction(\n error: unknown,\n shouldSaveInstrument?: boolean,\n shouldSetAsDefaultInstrument?: boolean,\n paymentToken?: string,\n bigpayToken?: Record,\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 const basePaymentData = {\n ...payment.paymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n };\n\n const tokenData =\n shouldSetAsDefaultInstrument && !shouldSaveInstrument\n ? {\n instrumentId: paymentToken,\n formattedPayload: {\n bigpay_token: {\n ...bigpayToken,\n token: paymentToken,\n },\n },\n }\n : {};\n\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...basePaymentData,\n ...tokenData,\n },\n });\n } catch (paymentError) {\n return this._processAdditionalAction(\n paymentError,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n paymentToken,\n bigpayToken,\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 async _mountElement(\n adyenComponent: AdyenComponent,\n containerId: string,\n ): Promise {\n await this._waitForMountContainer(containerId);\n\n try {\n adyenComponent.mount(`#${containerId}`);\n } catch {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n }\n\n private async _waitForMountContainer(containerId: string): Promise {\n const maxAttempts = Math.ceil(\n Adyenv3PaymentStrategy.mountContainerMaxWaitMs /\n Adyenv3PaymentStrategy.mountContainerPollIntervalMs,\n );\n const pollIntervalMs = Adyenv3PaymentStrategy.mountContainerPollIntervalMs;\n\n let step = 0;\n\n const poll = async (): Promise => {\n if (step === maxAttempts) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (document.getElementById(containerId)) {\n return;\n }\n\n await new Promise((resolve) => {\n setTimeout(resolve, pollIntervalMs);\n });\n\n step += 1;\n await poll();\n };\n\n await poll();\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","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 {\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","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';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const withHttpsExperimentName = 'PI-4789.afterpay_script_use_https';\n const withHttps = isExperimentEnabled(features, withHttpsExperimentName, false);\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._afterpaySdk = await this._afterpayScriptLoader.load(\n paymentMethod,\n countryCode,\n withHttps,\n );\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.js',\n HTTPS_PROD = 'https://portal.afterpay.com/afterpay-async.js',\n HTTPS_SANDBOX = 'https://portal.sandbox.afterpay.com/afterpay.js',\n}\n\nenum SCRIPTS_US {\n PROD = '//portal.afterpay.com/afterpay-async.js',\n SANDBOX = '//portal.sandbox.afterpay.com/afterpay.js',\n HTTPS_PROD = 'https://portal.afterpay.com/afterpay-async.js',\n HTTPS_SANDBOX = 'https://portal.sandbox.afterpay.com/afterpay.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(\n method: PaymentMethod,\n countryCode: string,\n withHttps = false,\n ): Promise {\n const testMode = method.config.testMode || false;\n const scriptURI = this._getScriptURI(countryCode, testMode, withHttps);\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, withHttps = false): string {\n if (countryCode === 'US') {\n if (withHttps) {\n return testMode ? SCRIPTS_US.HTTPS_SANDBOX : SCRIPTS_US.HTTPS_PROD;\n }\n\n return testMode ? SCRIPTS_US.SANDBOX : SCRIPTS_US.PROD;\n }\n\n if (withHttps) {\n return testMode ? SCRIPTS_DEFAULT.HTTPS_SANDBOX : SCRIPTS_DEFAULT.HTTPS_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 if (!this._amazonPayButton) {\n throw new InvalidArgumentError(\n 'Unable to render the Amazon Pay button to an invalid HTML container element.',\n );\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 ApplePayScriptLoader from './apple-pay-script-loader';\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 private _applePayScriptLoader: ApplePayScriptLoader,\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 await this._applePayScriptLoader.loadSdk();\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 (\n paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE &&\n paymentMethod.clientToken\n ) {\n this._braintreeSdk.initialize(paymentMethod.clientToken);\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","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\n} 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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n\n return new ApplePayPaymentStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), window, braintreeSDKVersionManager),\n ),\n new ApplePayScriptLoader(new ScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createApplePayPaymentStrategy, [{ id: 'applepay' }]);\n","export const LOADING_INDICATOR_STYLES = {\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\n};\n","import { MessagesStyleOptions, PayPalBNPLConfigurationItem } from '../bigcommerce-payments-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","export interface BaseInstrument {\n bigpayToken: string;\n defaultInstrument: boolean;\n provider: string;\n trustedShippingAddress: boolean;\n method: string;\n type: string;\n}\n\nexport function isBaseInstrument(instrument: unknown): instrument is BaseInstrument {\n if (typeof instrument !== 'object' || instrument === null) {\n return false;\n }\n\n return (\n 'bigpayToken' in instrument &&\n 'defaultInstrument' in instrument &&\n 'provider' in instrument &&\n 'trustedShippingAddress' in instrument &&\n 'method' in instrument &&\n 'type' in instrument\n );\n}\n","import {\n getPaypalMessagesStylesFromBNPLConfig,\n isBigCommercePaymentsProviderError,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalMessagesSdk,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isBaseInstrument } from '@bigcommerce/checkout-sdk/utility';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtons,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n ClickCallbackActions,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsPaymentInitializeOptions, {\n WithBigCommercePaymentsPaymentInitializeOptions,\n} from './bigcommerce-payments-payment-initialize-options';\n\nexport default class BigCommercePaymentsPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: BigCommercePaymentsButtons;\n private bigcommerce_payments?: BigCommercePaymentsPaymentInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private paypalSdkHelper: PayPalSdkHelper,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithBigCommercePaymentsPaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments } = options || {};\n\n this.bigcommerce_payments = bigcommerce_payments;\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 (!bigcommerce_payments) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments\" 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 const { container, bannerContainerId } = bigcommerce_payments;\n\n const {\n orderId,\n paypalBNPLConfiguration = [],\n isPayPalCreditAvailable,\n } = paymentMethod.initializationData || {};\n\n if (bannerContainerId !== undefined) {\n if (!document.getElementById(bannerContainerId)) {\n // eslint-disable-next-line no-console\n console.error('Unable to create banner without valid banner container ID.');\n\n return;\n }\n\n const bannerConfiguration = paypalBNPLConfiguration?.find(\n ({ id }) => id === 'checkout',\n );\n\n if (isPayPalCreditAvailable || !bannerConfiguration?.status) {\n return;\n }\n\n const paypalMessages = await this.paypalSdkHelper.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n );\n\n if (!paypalMessages || typeof paypalMessages?.Messages !== 'function') {\n console.error(\n '[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n return this.renderMessages(paypalMessages, bannerContainerId, bannerConfiguration);\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 this.loadingIndicatorContainer = container?.split('#')[1];\n\n await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n if (bigcommerce_payments.onInit && typeof bigcommerce_payments.onInit === 'function') {\n bigcommerce_payments.onInit(() => this.renderButton(methodId, bigcommerce_payments));\n }\n\n if (\n bigcommerce_payments.shouldRenderPayPalButtonOnInitialization === undefined ||\n bigcommerce_payments.shouldRenderPayPalButtonOnInitialization\n ) {\n this.renderButton(methodId, bigcommerce_payments);\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const { onError } = this.bigcommerce_payments || {};\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)) {\n await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(payment.methodId);\n\n await new Promise((_resolve, reject) => {\n if (this.bigcommerce_payments) {\n this.paypalButton?.close();\n this.renderButton(payment.methodId, this.bigcommerce_payments);\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 bigcommerce_payments: BigCommercePaymentsPaymentInitializeOptions,\n ): void {\n const paypalSdk = this.bigCommercePaymentsIntegrationService.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 } = bigcommerce_payments;\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"container\" argument is not provided.',\n );\n }\n\n const buttonOptions: BigCommercePaymentsButtonsOptions = {\n ...(this.isAppSwitchEnabled(methodId) && {\n appSwitchWhenAvailable: true,\n }),\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.bigCommercePaymentsIntegrationService.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 if (this.paypalButton.hasReturned?.() && this.isAppSwitchEnabled(methodId)) {\n this.paypalButton.resume?.();\n } else {\n this.paypalButton.render(container);\n }\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: BigCommercePaymentsPaymentInitializeOptions['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: BigCommercePaymentsPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm?.();\n }\n\n private handleError(\n error: unknown,\n onError: BigCommercePaymentsPaymentInitializeOptions['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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_paymentscheckout',\n {\n shouldSaveInstrument: fieldsValues?.shouldSaveInstrument || false,\n },\n );\n }\n\n /**\n *\n * Vaulting flow methods\n *\n * */\n private getFieldsValues(): HostedInstrument | undefined {\n const { getFieldsValues } = this.bigcommerce_payments || {};\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 findInstrument = instruments?.find(\n (instrument) =>\n isBaseInstrument(instrument) &&\n instrument.bigpayToken === paymentData.instrumentId,\n );\n const trustedShippingAddress = isBaseInstrument(findInstrument)\n ? findInstrument.trustedShippingAddress\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 /**\n *\n * Render Pay Later Messages\n *\n * */\n private renderMessages(\n paypalMessages: PayPalMessagesSdk,\n bannerContainerId: string,\n bannerConfiguration: PayPalBNPLConfigurationItem,\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: checkout.outstandingBalance,\n placement: 'payment',\n style: getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\n };\n\n paypalMessages.Messages(paypalMessagesOptions).render(`#${bannerContainerId}`);\n }\n\n private isProviderError(error: unknown): boolean {\n if (isBigCommercePaymentsProviderError(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 /**\n *\n * AppSwitch enabling handling\n *\n */\n private isAppSwitchEnabled(methodId: string): boolean {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n return paymentMethod.initializationData?.isAppSwitchEnabled ?? 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 isBigCommercePaymentsProviderError(error: unknown): error is ProviderError {\n return typeof error === 'object' && error !== null && 'errors' in error;\n}\n","import { createBigCommercePaymentsSdk } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport { LOADING_INDICATOR_STYLES } from '../bigcommerce-payments-constants';\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsPaymentStrategy from './bigcommerce-payments-payment-strategy';\n\nconst createBigCommercePaymentsPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n createBigCommercePaymentsSdk(),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsPaymentStrategy, [\n { id: 'bigcommerce_payments' },\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 BigCommercePaymentsFastlaneUtils,\n BigCommercePaymentsInitializationData,\n getFastlaneStyles,\n isBigcommerceFastlaneRequestError,\n isPayPalFastlaneCustomer,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneCardComponentMethods,\n PayPalFastlaneCardComponentOptions,\n PayPalFastlanePaymentFormattedPayload,\n PayPalFastlaneSdk,\n PayPalSdkHelper,\n TDSecureAuthenticationState,\n TDSecureVerificationMethod,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport BigCommercePaymentsRequestSender from '../bigcommerce-payments-request-sender';\nimport { LiabilityShiftEnum } from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsFastlanePaymentInitializeOptions, {\n WithBigCommercePaymentsFastlanePaymentInitializeOptions,\n} from './bigcommerce-payments-fastlane-payment-initialize-options';\n\nexport default class BigCommercePaymentsFastlanePaymentStrategy implements PaymentStrategy {\n private paypalComponentMethods?: PayPalFastlaneCardComponentMethods;\n private threeDSVerificationMethod?: string;\n private paypalFastlaneSdk?: PayPalFastlaneSdk;\n private bigcommerce_payments_fastlane?: BigCommercePaymentsFastlanePaymentInitializeOptions;\n private methodId?: string;\n private orderId?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsRequestSender: BigCommercePaymentsRequestSender,\n private bigCommercePaymentsSdk: PayPalSdkHelper,\n private bigCommercePaymentsFastlaneUtils: BigCommercePaymentsFastlaneUtils,\n ) {}\n\n /**\n *\n * Default methods\n *\n * */\n async initialize(\n options: PaymentInitializeOptions & WithBigCommercePaymentsFastlanePaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_fastlane } = 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.methodId = methodId;\n\n if (!bigcommerce_payments_fastlane) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_fastlane\" argument is not provided.',\n );\n }\n\n this.bigcommerce_payments_fastlane = bigcommerce_payments_fastlane;\n\n if (\n !bigcommerce_payments_fastlane.onInit ||\n typeof bigcommerce_payments_fastlane.onInit !== 'function'\n ) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_fastlane.onInit\" argument is not provided or it is not a function.',\n );\n }\n\n if (\n !bigcommerce_payments_fastlane.onChange ||\n typeof bigcommerce_payments_fastlane.onChange !== 'function'\n ) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_fastlane.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 this.threeDSVerificationMethod =\n paymentMethod.initializationData?.threeDSVerificationMethod;\n\n this.paypalFastlaneSdk = await this.bigCommercePaymentsSdk.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 bigcommerce_payments_fastlane?.styles,\n );\n\n await this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(\n this.paypalFastlaneSdk,\n !!isDeveloperModeApplicable,\n fastlaneStyles,\n );\n\n if (this.shouldRunAuthenticationFlow()) {\n await this.runPayPalAuthenticationFlowOrThrow(methodId);\n }\n\n await this.initializePayPalPaymentComponent();\n\n bigcommerce_payments_fastlane.onInit((container: string) =>\n this.renderPayPalPaymentComponent(container),\n );\n bigcommerce_payments_fastlane.onChange(() =>\n this.handlePayPalStoredInstrumentChange(methodId),\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 { paymentData, methodId } = payment;\n\n const isVaultedFlow = paymentData && isVaultedInstrument(paymentData);\n\n try {\n await this.paymentIntegrationService.submitOrder(order, options);\n\n const paymentPayload = isVaultedFlow\n ? await this.prepareVaultedInstrumentPaymentPayload(methodId, paymentData)\n : await this.preparePaymentPayload(methodId, paymentData);\n\n await this.paymentIntegrationService.submitPayment(\n paymentPayload,\n );\n\n this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId();\n } catch (error) {\n if (\n isBigcommerceFastlaneRequestError(error) &&\n error.response.name === 'INVALID_REQUEST'\n ) {\n const invalidRequestError = {\n translationKey: 'payment.errors.invalid_request_error',\n };\n\n this.handleError(invalidRequestError);\n\n return Promise.reject();\n }\n\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.bigCommercePaymentsFastlaneUtils.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.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(customerEmail);\n\n const authenticationResult =\n await this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(\n customerContextId,\n );\n\n const { authenticationState, addresses, instruments } =\n this.bigCommercePaymentsFastlaneUtils.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 if (isAuthenticationFlowCanceled) {\n this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId();\n } else {\n this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(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 * BigCommercePayments 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.bigCommercePaymentsFastlaneUtils.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 paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n const is3DSEnabled =\n this.isBigcommercePaymentsFastlaneThreeDSAvailable() &&\n paymentMethod.config.is3dsEnabled;\n\n const nonce = is3DSEnabled ? await this.get3DSNonce(instrumentId) : instrumentId;\n\n await this.createOrder(nonce);\n\n return {\n methodId,\n paymentData: {\n formattedPayload: {\n paypal_fastlane_token: {\n order_id: this.orderId,\n token: nonce,\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 billingAddress = state.getBillingAddressOrThrow();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\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:\n this.bigCommercePaymentsFastlaneUtils.mapBcToPayPalAddress(billingAddress),\n });\n\n const is3DSEnabled =\n this.isBigcommercePaymentsFastlaneThreeDSAvailable() &&\n paymentMethod.config.is3dsEnabled;\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n const nonce = is3DSEnabled ? await this.get3DSNonce(id) : id;\n\n await this.createOrder(nonce);\n\n return {\n methodId,\n paymentData: {\n ...paymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n formattedPayload: {\n paypal_fastlane_token: {\n order_id: this.orderId,\n token: nonce,\n },\n },\n },\n };\n }\n\n private async createOrder(id: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cartId = state.getCartOrThrow().id;\n\n if (this.methodId) {\n const { orderId } = await this.bigCommercePaymentsRequestSender.createOrder(\n this.methodId,\n {\n cartId,\n fastlaneToken: id,\n },\n );\n\n this.orderId = orderId;\n }\n }\n\n /**\n *\n * 3DSecure methods\n *\n * */\n private async get3DSNonce(nonce: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const order = state.getOrderOrThrow();\n const checkoutUrl = state.getStoreConfigOrThrow().links.checkoutLink;\n\n const threeDomainSecureComponent = this.paypalFastlaneSdk?.ThreeDomainSecureClient;\n\n if (!threeDomainSecureComponent) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n const threeDomainSecureParameters = {\n amount: order.orderAmount.toFixed(2),\n currency: cart.currency.code,\n nonce,\n threeDSRequested: this.threeDSVerificationMethod === TDSecureVerificationMethod.Always,\n transactionContext: {\n experience_context: {\n locale: 'en-US',\n return_url: checkoutUrl,\n cancel_url: checkoutUrl,\n },\n },\n };\n\n const isThreeDomainSecureEligible = await threeDomainSecureComponent.isEligible(\n threeDomainSecureParameters,\n );\n\n if (\n this.threeDSVerificationMethod === TDSecureVerificationMethod.Always &&\n !isThreeDomainSecureEligible\n ) {\n throw new PaymentMethodInvalidError();\n }\n\n if (isThreeDomainSecureEligible) {\n const {\n liabilityShift,\n authenticationState,\n nonce: threeDSNonce,\n } = await threeDomainSecureComponent.show();\n\n if (\n liabilityShift === LiabilityShiftEnum.No ||\n liabilityShift === LiabilityShiftEnum.Unknown ||\n authenticationState === TDSecureAuthenticationState.Errored ||\n authenticationState === TDSecureAuthenticationState.Cancelled\n ) {\n throw new PaymentMethodInvalidError();\n }\n\n if (\n authenticationState === TDSecureAuthenticationState.Succeeded &&\n [LiabilityShiftEnum.Yes, LiabilityShiftEnum.Possible].includes(liabilityShift)\n ) {\n return threeDSNonce;\n }\n }\n\n return nonce;\n }\n\n /**\n *\n * BigCommercePayments Fastlane instrument change\n *\n */\n private async handlePayPalStoredInstrumentChange(\n methodId: string,\n ): Promise {\n const paypalAxoSdk = this.bigCommercePaymentsFastlaneUtils.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 =\n this.bigCommercePaymentsFastlaneUtils.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 /**\n *\n * Bigcommerce Payments Fastlane experiments handling\n *\n */\n private isBigcommercePaymentsFastlaneThreeDSAvailable(): boolean {\n const state = this.paymentIntegrationService.getState();\n const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n\n return isExperimentEnabled(features, 'PROJECT-7080.bcp_fastlane_three_ds');\n }\n\n private handleError(error: unknown): void {\n if (\n this.bigcommerce_payments_fastlane?.onError &&\n typeof this.bigcommerce_payments_fastlane.onError === 'function'\n ) {\n this.bigcommerce_payments_fastlane.onError(error);\n }\n }\n}\n","export interface BigcommerceFastlaneRequestError {\n name: string;\n message: string;\n response: {\n name: string;\n };\n}\n\nexport default function isBigcommerceFastlaneRequestError(\n error: unknown,\n): error is BigcommerceFastlaneRequestError {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'message' in error &&\n 'response' in error &&\n 'name' in (error as BigcommerceFastlaneRequestError).response\n );\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n createBigCommercePaymentsFastlaneUtils,\n createBigCommercePaymentsSdk,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsRequestSender from '../bigcommerce-payments-request-sender';\n\nimport BigCommercePaymentsFastlanePaymentStrategy from './bigcommerce-payments-fastlane-payment-strategy';\n\nconst createBigCommercePaymentsFastlanePaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsFastlanePaymentStrategy\n> = (paymentIntegrationService) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new BigCommercePaymentsFastlanePaymentStrategy(\n paymentIntegrationService,\n new BigCommercePaymentsRequestSender(createRequestSender({ host: getHost() })),\n createBigCommercePaymentsSdk(),\n createBigCommercePaymentsFastlaneUtils(),\n );\n};\n\nexport default toResolvableModule(createBigCommercePaymentsFastlanePaymentStrategy, [\n { id: 'bigcommerce_payments_fastlane' }, // BigCommercePayments Fastlane relates to 'bigcommerce_payments_fastlane' method id\n]);\n","import {\n BigCommercePaymentsInitializationData,\n getPaypalMessagesStylesFromBNPLConfig,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalMessagesSdk,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtons,\n BigCommercePaymentsButtonsOptions,\n ClickCallbackActions,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsPayLaterPaymentInitializeOptions, {\n WithBigCommercePaymentsPayLaterPaymentInitializeOptions,\n} from './bigcommerce-payments-paylater-payment-initialize-options';\n\nexport default class BigCommercePaymentsPayLaterPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private bigCommercePaymentsButtons?: BigCommercePaymentsButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private loadingIndicator: LoadingIndicator,\n private paypalSdkHelper: PayPalSdkHelper,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions &\n WithBigCommercePaymentsPayLaterPaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_paylater } = 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 (!bigcommerce_payments_paylater) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_paylater\" 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 const { paypalBNPLConfiguration = [], orderId } = paymentMethod.initializationData || {};\n const { bannerContainerId, container } = bigcommerce_payments_paylater;\n\n if (bannerContainerId !== undefined) {\n if (!document.getElementById(bannerContainerId)) {\n // eslint-disable-next-line no-console\n console.error('Unable to create banner without valid banner container ID.');\n\n return;\n }\n\n const bannerConfiguration =\n paypalBNPLConfiguration &&\n paypalBNPLConfiguration.find(({ id }) => id === 'checkout');\n\n if (!bannerConfiguration?.status) {\n return;\n }\n\n const paypalMessages = await this.paypalSdkHelper.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n );\n\n return this.renderMessages(paypalMessages, bannerContainerId, bannerConfiguration);\n }\n\n // Info:\n // The BigCommercePayments 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 BigCommercePayments button.\n if (orderId) {\n this.orderId = orderId;\n\n return;\n }\n\n await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = container?.split('#')[1];\n\n this.renderButton(methodId, bigcommerce_payments_paylater);\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.bigCommercePaymentsIntegrationService.submitPayment(\n payment.methodId,\n this.orderId,\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.orderId = undefined;\n\n this.bigCommercePaymentsButtons?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n bigcommerce_payments_paylater: BigCommercePaymentsPayLaterPaymentInitializeOptions,\n ): void {\n if (!bigcommerce_payments_paylater?.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"container\" argument is not provided.',\n );\n }\n\n const bigCommerceSdk = this.bigCommercePaymentsIntegrationService.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 } =\n bigcommerce_payments_paylater;\n\n const fundingSources = [bigCommerceSdk.FUNDING.PAYLATER, bigCommerceSdk.FUNDING.CREDIT];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (hasRenderedSmartButton) {\n return;\n }\n\n const buttonOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(\n checkoutPaymentButtonStyles,\n ),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_paylater',\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.bigCommercePaymentsButtons = bigCommerceSdk.Buttons(buttonOptions);\n\n if (\n !this.bigCommercePaymentsButtons.isEligible() &&\n fundingSource === bigCommerceSdk.FUNDING.PAYLATER\n ) {\n return;\n }\n\n if (\n !this.bigCommercePaymentsButtons.isEligible() &&\n fundingSource === bigCommerceSdk.FUNDING.CREDIT\n ) {\n throw new NotImplementedError(\n `BigCommercePayments ${fundingSource} is not available for your region. Please use BigCommercePayments Checkout instead.`,\n );\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.bigCommercePaymentsButtons.render(container);\n hasRenderedSmartButton = true;\n });\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: BigCommercePaymentsPayLaterPaymentInitializeOptions['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: BigCommercePaymentsPayLaterPaymentInitializeOptions['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: BigCommercePaymentsPayLaterPaymentInitializeOptions['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,\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: checkout.outstandingBalance,\n placement: 'payment',\n style: getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\n };\n\n paypalMessages.Messages(paypalMessagesOptions).render(`#${bannerContainerId}`);\n }\n}\n","import { createBigCommercePaymentsSdk } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport { LOADING_INDICATOR_STYLES } from '../bigcommerce-payments-constants';\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsPayLaterPaymentStrategy from './bigcommerce-payments-paylater-payment-strategy';\n\nconst createBigCommercePaymentsPayLaterPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsPayLaterPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsPayLaterPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n createBigCommercePaymentsSdk(),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsPayLaterPaymentStrategy, [\n { id: 'bigcommerce_payments_paylater' },\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n BigCommercePaymentsInitializationData,\n BirthDate,\n PayPalOrderStatus,\n} from '../bigcommerce-payments-types';\n\nimport {\n BigCommercePaymentsRatePayPaymentInitializeOptions,\n WithBigCommercePaymentsRatePayPaymentInitializeOptions,\n} from './bigcommerce-payments-ratepay-initialize-options';\n\nconst POLLING_INTERVAL = 3000;\nconst MAX_POLLING_TIME = 300000;\n\nexport default class BigCommercePaymentsRatePayPaymentStrategy implements PaymentStrategy {\n private guid?: string;\n private bigcommerce_payments_ratepay?: BigCommercePaymentsRatePayPaymentInitializeOptions;\n private loadingIndicatorContainer?: string;\n private pollingTimer = 0;\n private stopPolling = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\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 & WithBigCommercePaymentsRatePayPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, bigcommerce_payments_ratepay } = 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 (!bigcommerce_payments_ratepay) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_ratepay\" argument is not provided.`,\n );\n }\n\n const { legalTextContainer, container, loadingContainerId } = bigcommerce_payments_ratepay;\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.bigcommerce_payments_ratepay = bigcommerce_payments_ratepay;\n\n await this.bigCommercePaymentsIntegrationService.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.bigcommerce_payments_ratepay || {};\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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_apmscheckout',\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.bigcommerce_payments_ratepay || {};\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 bigCommercePaymentsSdk =\n this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const ratePayButton = bigCommercePaymentsSdk.Legal({\n fundingSource: bigCommercePaymentsSdk.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.bigcommerce_payments_ratepay || {};\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 & WithBigCommercePaymentsRatePayPaymentInitializeOptions,\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.bigCommercePaymentsIntegrationService.getOrderStatus(\n 'bigcommerce_payments_apms',\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 bigcommerce_payments_ratepay: this.bigcommerce_payments_ratepay,\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 { LOADING_INDICATOR_STYLES } from '../bigcommerce-payments-constants';\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsRatePayPaymentStrategy from './bigcommerce-payments-ratepay-payment-strategy';\n\nconst createBigCommercePaymentsRatePayPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsRatePayPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsRatePayPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n new LoadingIndicator({\n containerStyles: { ...LOADING_INDICATOR_STYLES, position: 'fixed' },\n }),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsRatePayPaymentStrategy, [\n { gateway: 'bigcommerce_payments_apms', id: 'ratepay' },\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 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 { isNil, omitBy } from 'lodash';\n\nimport {\n BigCommercePaymentsFastlaneUtils,\n BigCommercePaymentsInitializationData,\n isBigCommercePaymentsFastlaneCustomer,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\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';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n BigCommercePaymentsCardFields,\n BigCommercePaymentsCardFieldsConfig,\n BigCommercePaymentsCardFieldsOnApproveData,\n BigCommercePaymentsCardFieldsState,\n BigCommercePaymentsFields,\n BigCommercePaymentsHostedFieldsRenderOptions,\n LiabilityShiftEnum,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsCreditCardsPaymentInitializeOptions, {\n WithBigCommercePaymentsCreditCardsPaymentInitializeOptions,\n} from './bigcommerce-payments-credit-cards-payment-initialize-options';\n\nexport default class BigCommercePaymentsCreditCardsPaymentStrategy implements PaymentStrategy {\n private executionPaymentData?: OrderPaymentRequestBody['paymentData'];\n private isCreditCardForm?: boolean;\n private isCreditCardVaultedForm?: boolean;\n\n private cardFields?: BigCommercePaymentsCardFields;\n private cvvField?: BigCommercePaymentsFields;\n private expiryField?: BigCommercePaymentsFields;\n private numberField?: BigCommercePaymentsFields;\n private nameField?: BigCommercePaymentsFields;\n\n private hostedFormOptions?: HostedFormOptions;\n private returnedOrderId?: string;\n private returnedVaultedToken?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private bigCommercePaymentsSdk: PayPalSdkHelper,\n private bigCommercePaymentsFastlaneUtils: BigCommercePaymentsFastlaneUtils,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions &\n WithBigCommercePaymentsCreditCardsPaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_creditcards } = options;\n const bigCommercePaymentsInitializationOptions = bigcommerce_payments_creditcards;\n\n const { form, onCreditCardFieldsRenderingError, onLoadComplete } =\n bigCommercePaymentsInitializationOptions || {};\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.bigcommerce_payments_creditcards.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.bigCommercePaymentsIntegrationService.loadPayPalSdk(\n methodId,\n undefined,\n true,\n true,\n );\n\n if (this.isCreditCardForm || this.isCreditCardVaultedForm) {\n await this.initializeFields(form, onCreditCardFieldsRenderingError);\n }\n\n onLoadComplete?.();\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 // The condition gets triggered when customer pays with vaulted instrument and shipping address is trusted\n const { orderId } =\n await this.bigCommercePaymentsIntegrationService.createOrderCardFields(\n 'bigcommerce_payments_creditcardscheckout',\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?: BigCommercePaymentsCreditCardsPaymentInitializeOptions['onCreditCardFieldsRenderingError'],\n ): Promise {\n const { fields, styles } = formOptions;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const executeCallback = this.getExecuteCallback(fields);\n\n const cardFieldsConfig: BigCommercePaymentsCardFieldsConfig = {\n style: this.getInputStyles(styles),\n onApprove: ({\n orderID,\n vaultSetupToken,\n liabilityShift,\n }: BigCommercePaymentsCardFieldsOnApproveData) => {\n if (\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.bigCommercePaymentsIntegrationService.createOrderCardFields(\n 'bigcommerce_payments_creditcardscheckout',\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.bigCommercePaymentsIntegrationService.createOrderCardFields(\n 'bigcommerce_payments_creditcardscheckout',\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({\n orderID,\n vaultSetupToken,\n }: BigCommercePaymentsCardFieldsOnApproveData) {\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 }: BigCommercePaymentsCardFieldsState):\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 * */\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 }: BigCommercePaymentsCardFieldsState): HostedFieldValidateEventData {\n const updatedFields = { ...fields };\n\n delete updatedFields.cardNameField;\n\n const fieldsKeys = Object.keys(updatedFields) as Array<\n keyof BigCommercePaymentsCardFieldsState['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(): BigCommercePaymentsCardFields {\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 ): BigCommercePaymentsHostedFieldsRenderOptions['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: BigCommercePaymentsCardFieldsState,\n ): void {\n formOptions?.onValidate?.(this.getValidityData(event));\n }\n\n private onFocusHandler(\n formOptions: HostedFormOptions,\n event: BigCommercePaymentsCardFieldsState,\n ): void {\n formOptions?.onFocus?.(this.getFieldTypeByEmittedField(event));\n }\n\n private onBlurHandler(\n formOptions: HostedFormOptions,\n event: BigCommercePaymentsCardFieldsState,\n ): void {\n formOptions?.onBlur?.(this.getFieldTypeByEmittedField(event));\n }\n\n private onInputSubmitRequest(\n formOptions: HostedFormOptions,\n event: BigCommercePaymentsCardFieldsState,\n ): void {\n formOptions?.onEnter?.(this.getFieldTypeByEmittedField(event));\n }\n\n /**\n *\n * BigCommercePayments Accelerated checkout related methods\n *\n */\n // TODO: remove this part when BCP Fastlane 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 bigCommercePaymentsPaymentProviderCustomer = isBigCommercePaymentsFastlaneCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n return (\n paymentMethod?.initializationData?.isAcceleratedCheckoutEnabled &&\n paymentMethod?.initializationData?.isBigCommercePaymentsAnalyticsV2Enabled &&\n !bigCommercePaymentsPaymentProviderCustomer?.authenticationState\n );\n }\n\n // TODO: remove this part when BCP Fastlane 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.bigCommercePaymentsSdk.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n );\n\n await this.bigCommercePaymentsFastlaneUtils.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 PaymentProviderCustomer,\n PayPalConnectCustomer,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isBigCommercePaymentsFastlaneCustomer(\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 createBigCommercePaymentsFastlaneUtils,\n createBigCommercePaymentsSdk,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsCreditCardsPaymentStrategy from './bigcommerce-payments-credit-cards-payment-strategy';\n\nconst createBigCommercePaymentsCreditCardsPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsCreditCardsPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsCreditCardsPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n createBigCommercePaymentsSdk(),\n createBigCommercePaymentsFastlaneUtils(),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsCreditCardsPaymentStrategy, [\n { id: 'bigcommerce_payments_creditcards' },\n]);\n","import { noop } from 'lodash';\n\nimport {\n PayPalApmSdk,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodClientUnavailableError,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n TimeoutError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtons,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n NonInstantAlternativePaymentMethods,\n PayPalOrderStatus,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions, {\n WithBigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\n} from './bigcommerce-payments-alternative-methods-payment-initialize-options';\n\nconst POLLING_INTERVAL = 3000;\nconst MAX_POLLING_TIME = 300000;\n\nexport default class BigCommercePaymentsAlternativeMethodsPaymentStrategy\n implements PaymentStrategy\n{\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private bigCommercePaymentsButton?: BigCommercePaymentsButtons;\n private paypalApms?: PayPalApmSdk;\n private pollingTimer = 0;\n private stopPolling = noop;\n private isPollingEnabled = false;\n private bigCommercePaymentsAlternativeMethods?: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private bigCommercePaymentsSdkHelper: PayPalSdkHelper,\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 &\n WithBigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, bigcommerce_payments_apms } = options;\n\n this.bigCommercePaymentsAlternativeMethods = bigcommerce_payments_apms;\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 (!bigcommerce_payments_apms) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_apms\" 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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n\n this.isPollingEnabled = isExperimentEnabled(features, 'PAYPAL-5624.bcp_ideal_polling');\n\n // Info:\n // The APM 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 the button.\n if (orderId) {\n this.orderId = orderId;\n\n return;\n }\n\n this.paypalApms = await this.bigCommercePaymentsSdkHelper.getPayPalApmsSdk(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n );\n\n this.loadingIndicatorContainer = bigcommerce_payments_apms.container.split('#')[1];\n\n this.renderButton(methodId, gatewayId, bigcommerce_payments_apms);\n\n if (shouldRenderFields) {\n this.renderFields(methodId, bigcommerce_payments_apms);\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.isPollingEnabled && methodId === 'ideal') {\n await new Promise((resolve, reject) => {\n void this.initializePollingMechanism(methodId, resolve, reject, gatewayId);\n });\n }\n\n if (!this.isNonInstantPaymentMethod(methodId)) {\n await this.paymentIntegrationService.submitOrder(order, options);\n }\n\n await this.bigCommercePaymentsIntegrationService.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 if (this.isPollingEnabled) {\n this.resetPollingMechanism();\n }\n\n this.bigCommercePaymentsButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Polling mechanism\n *\n *\n * */\n private async initializePollingMechanism(\n methodId: string,\n resolvePromise: (value?: unknown) => void,\n rejectPromise: (value?: unknown) => 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.bigCommercePaymentsIntegrationService.getOrderStatus(\n gatewayId,\n );\n\n const isOrderApproved = orderStatus === PayPalOrderStatus.Approved;\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 bigCommercePaymentsAlternativeMethods: this.bigCommercePaymentsAlternativeMethods,\n });\n\n this.handleError(new TimeoutError());\n } catch (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 private async reinitializeStrategy(\n options: PaymentInitializeOptions &\n WithBigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\n ) {\n await this.deinitialize();\n await this.initialize(options);\n }\n\n private handleError(error: unknown) {\n const { onError } = this.bigCommercePaymentsAlternativeMethods || {};\n\n if (this.isPollingEnabled) {\n this.resetPollingMechanism();\n }\n\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n gatewayId: string,\n bigcommerce_payments_apms: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\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 } = bigcommerce_payments_apms;\n\n const buttonOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource: methodId,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(buttonStyle),\n onInit: (_, actions) => bigcommerce_payments_apms.onInitButton(actions),\n createOrder: () => this.onCreateOrder(methodId, gatewayId, bigcommerce_payments_apms),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onCancel: () => {\n this.toggleLoadingIndicator(false);\n this.deInitializePollingMechanism();\n },\n onError: (error) => {\n this.deInitializePollingMechanism();\n this.handleFailure(error, onError);\n },\n onClick: async (_, actions) =>\n bigcommerce_payments_apms.onValidate(actions.resolve, actions.reject),\n };\n\n this.bigCommercePaymentsButton = paypalAmpsSdk.Buttons(buttonOptions);\n\n if (!this.bigCommercePaymentsButton.isEligible()) {\n return;\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.bigCommercePaymentsButton.render(container);\n }\n\n private async onCreateOrder(\n methodId: string,\n gatewayId: string,\n bigcommerce_payments_apms: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\n ): Promise {\n const { onValidate } = bigcommerce_payments_apms;\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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_apms',\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.bigCommercePaymentsIntegrationService.submitPayment(\n methodId,\n orderId,\n gatewayId,\n );\n }\n\n return orderId;\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n }\n\n private handleFailure(\n error: Error,\n onError: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions['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 bigcommerce_payments_apms: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\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 } = bigcommerce_payments_apms;\n\n if (!apmFieldsContainer) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_apms\" 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 { createBigCommercePaymentsSdk } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport { LOADING_INDICATOR_STYLES } from '../bigcommerce-payments-constants';\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsAlternativeMethodsPaymentStrategy from './bigcommerce-payments-alternative-methods-payment-strategy';\n\nconst createBigCommercePaymentsAlternativeMethodsPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsAlternativeMethodsPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsAlternativeMethodsPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n createBigCommercePaymentsSdk(),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsAlternativeMethodsPaymentStrategy, [\n { gateway: 'bigcommerce_payments_apms' },\n]);\n","import { isRedirectError } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsRedirectAlternativeMethodsPaymentInitializeOptions, {\n WithBigCommercePaymentsRedirectAlternativeMethodsPaymentInitializeOptions,\n} from './bigcomemrce-payments-redirect-alternative-methods-payment-initialize-options';\n\nexport default class BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy\n implements PaymentStrategy\n{\n private bigCommercePaymentsAlternativeMethods?: BigCommercePaymentsRedirectAlternativeMethodsPaymentInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n initialize(\n options: PaymentInitializeOptions &\n WithBigCommercePaymentsRedirectAlternativeMethodsPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, bigcommerce_payments_apms } = options;\n\n this.bigCommercePaymentsAlternativeMethods = bigcommerce_payments_apms;\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 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, gatewayId } = payment;\n\n try {\n const orderId = await this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_apms',\n {\n gatewayId: 'bigcommerce_payments_apms',\n methodId,\n },\n );\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: methodId,\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,\n gatewayId,\n paymentData,\n });\n } catch (error: unknown) {\n if (isRedirectError(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 reject();\n });\n }\n\n this.handleError(error);\n\n return Promise.reject(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 handleError(error: unknown) {\n const { onError } = this.bigCommercePaymentsAlternativeMethods || {};\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n}\n","import { isRequestError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RedirectError } from '../bigcommerce-payments-types';\n\nexport default function isRedirectError(error: unknown): error is RedirectError {\n return isRequestError(error) && error.body?.additional_action_required?.data.redirect_url;\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy from './bigcomemrce-payments-redirect-alternative-methods-payment-strategy';\n\nconst createBigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(\n createBigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy,\n [\n { gateway: 'bigcommerce_payments_apms', id: 'klarna' },\n { gateway: 'bigcommerce_payments_apms', id: 'afterpay' },\n ],\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtons,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n ClickCallbackActions,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsVenmoPaymentInitializeOptions, {\n WithBigCommercePaymentsVenmoPaymentInitializeOptions,\n} from './bigcommerce-payments-venmo-payment-initialize-options';\n\nexport default class BigCommercePaymentsVenmoPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: BigCommercePaymentsButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithBigCommercePaymentsVenmoPaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_venmo } = 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 (!bigcommerce_payments_venmo) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_venmo\" 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.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = bigcommerce_payments_venmo.container.split('#')[1];\n\n this.renderButton(methodId, bigcommerce_payments_venmo);\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.bigCommercePaymentsIntegrationService.submitPayment(\n payment.methodId,\n this.orderId,\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 bigcommerce_payments_venmo: BigCommercePaymentsVenmoPaymentInitializeOptions,\n ): void {\n const paypalSdk = this.bigCommercePaymentsIntegrationService.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 } =\n bigcommerce_payments_venmo;\n\n const buttonOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(\n checkoutPaymentButtonStyles,\n ),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_venmocheckout',\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()) {\n throw new NotImplementedError(\n `Venmo is not available for your region. Please another payment method 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: BigCommercePaymentsVenmoPaymentInitializeOptions['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: BigCommercePaymentsVenmoPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n this.toggleLoadingIndicator(false);\n }\n\n private handleError(\n error: Error,\n onError: BigCommercePaymentsVenmoPaymentInitializeOptions['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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsVenmoPaymentStrategy from './bigcommerce-payments-venmo-payment-strategy';\n\nconst createBigCommercePaymentsVenmoPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsVenmoPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsVenmoPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsVenmoPaymentStrategy, [\n { id: 'bigcommerce_payments_venmo' },\n]);\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","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","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 { 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 try {\n await this._blueSnapDirectHostedForm.attach(\n this._getPaymentFieldsToken(),\n creditCard,\n is3dsEnabled,\n );\n } catch (error) {\n if (error instanceof InvalidArgumentError) {\n return;\n }\n throw error;\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","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 ...(payment.paymentData.companyName\n ? { company_name: payment.paymentData.companyName }\n : {}),\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(\n paymentIntegrationService,\n createBraintreeSdk(paymentIntegrationService),\n );\n};\n\nexport default toResolvableModule(createBraintreeAchPaymentStrategy, [{ id: 'braintreeach' }]);\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport BraintreeSdk from './braintree-sdk';\nimport BraintreeSDKVersionManager from './braintree-sdk-version-manager';\n\nconst createBraintreeSdk = (paymentIntegrationService: PaymentIntegrationService) => {\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeScriptLoader = new BraintreeScriptLoader(\n getScriptLoader(),\n window,\n braintreeSDKVersionManager,\n );\n\n return new BraintreeSdk(braintreeScriptLoader);\n};\n\nexport default createBraintreeSdk;\n","import { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BraintreeHostWindow,\n BraintreeInitializationData,\n PayPalBNPLConfigurationItem,\n} from './braintree';\nimport { MessagesStyleOptions, MessagingPlacements } from './paypal';\n\nexport default class BraintreeMessages {\n private braintreeHostWindow: BraintreeHostWindow = window;\n\n constructor(private paymentIntegrationService: PaymentIntegrationService) {}\n\n render(methodId: string, containerId: string, placement: MessagingPlacements): void {\n const messagingContainer = containerId && document.getElementById(containerId);\n\n if (this.braintreeHostWindow.paypal && messagingContainer) {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const billingAddress = state.getBillingAddressOrThrow();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n if (!paymentMethod.initializationData) {\n return;\n }\n\n const { paypalBNPLConfiguration = [] } = paymentMethod.initializationData;\n\n const bannedId = placement === MessagingPlacements.PAYMENT ? 'checkout' : placement;\n const bannerConfiguration =\n paypalBNPLConfiguration &&\n paypalBNPLConfiguration.find(({ id }) => id === bannedId);\n\n if (!bannerConfiguration || !bannerConfiguration.status) {\n return;\n }\n\n // TODO: remove this code when this data attributes will be removed from banner div container in content service\n if (placement === MessagingPlacements.CART) {\n messagingContainer.removeAttribute('data-pp-style-logo-type');\n messagingContainer.removeAttribute('data-pp-style-logo-position');\n messagingContainer.removeAttribute('data-pp-style-text-color');\n messagingContainer.removeAttribute('data-pp-style-text-size');\n }\n\n this.braintreeHostWindow.paypal\n .Messages({\n amount: cart.cartAmount,\n buyerCountry: billingAddress.countryCode,\n placement,\n style: this.getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\n })\n .render(`#${containerId}`);\n }\n }\n\n private 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}\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","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 BraintreeInitializationData,\n BraintreeIntegrationService,\n BraintreeMessages,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n MessagingPlacements,\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 braintreeButtonOptions?: 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 braintreeMessages: BraintreeMessages,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreePaypalPaymentInitializeOptions,\n ) {\n const { braintree: braintreeOptions, methodId } = options;\n\n if (braintreeOptions?.containerId) {\n this.braintreeButtonOptions = braintreeOptions;\n }\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(braintreeOptions);\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(braintreeOptions);\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 if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { onError } = this.braintreeButtonOptions || {};\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)) {\n await this.loadPaypal();\n\n this.paypalButtonRender?.close();\n\n await this.loadPaypalCheckoutInstance(this.braintreeButtonOptions);\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(options?: BraintreePaypalPaymentInitializeOptions) {\n const { clientToken, initializationData, id: paymentMethodId } = 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 const isBraintreePaypalCredit = paymentMethodId === 'braintreepaypalcredit';\n const shouldShowPayPalCreditBanner =\n isBraintreePaypalCredit || !initializationData?.isCreditEnabled;\n\n await this.braintreeIntegrationService.getPaypalCheckout(\n paypalCheckoutConfig,\n (braintreePaypalCheckout) => {\n if (\n shouldShowPayPalCreditBanner &&\n paymentMethodId &&\n options?.bannerContainerId\n ) {\n this.renderPayPalMessages(paymentMethodId, options.bannerContainerId);\n }\n\n this.renderPayPalButton(braintreePaypalCheckout, options);\n },\n this.handleError,\n );\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private renderPayPalMessages(methodId: string, containerId: string) {\n this.braintreeMessages.render(methodId, containerId, MessagingPlacements.PAYMENT);\n }\n\n private renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n options?: BraintreePaypalPaymentInitializeOptions,\n ) {\n const { onPaymentError, submitForm, onRenderButton, containerId, onError } = options || {};\n\n if (!containerId) {\n return;\n }\n\n const container = this.getSmartButtonContainerId(containerId);\n const smartButtonContainer = document.getElementById(container);\n\n if (!smartButtonContainer) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because element with id ${containerId} does not exist.`,\n );\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 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 private getSmartButtonContainerId(container: string) {\n return container.split('#')[1] ?? container;\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 BraintreeMessages,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n overlay,\n );\n const braintreeMessages = new BraintreeMessages(paymentIntegrationService);\n\n return new BraintreePaypalPaymentStrategy(\n paymentIntegrationService,\n braintreeIntegrationService,\n braintreeMessages,\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 { RequestSender } from '@bigcommerce/request-sender';\n\nimport { BraintreeOrderStatusData } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class BraintreeRequestSender {\n constructor(private requestSender: RequestSender) {}\n\n async getOrderStatus(\n methodId = 'braintreelocalmethods',\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 { noop } from 'lodash';\n\nimport {\n BraintreeInitializationData,\n BraintreeLocalPayment,\n BraintreeLocalPaymentConfig,\n BraintreeLocalPaymentMethodRedirectAction,\n BraintreeLocalPaymentsPayload,\n BraintreeLPMPaymentStartData,\n BraintreeLPMStartPaymentError,\n BraintreeOrderSavedResponse,\n BraintreeOrderStatus,\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 TimeoutError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport BraintreeRequestSender from '../braintree-request-sender';\n\nimport {\n BraintreeLocalMethodsPaymentInitializeOptions,\n WithBraintreeLocalMethodsPaymentInitializeOptions,\n} from './braintree-local-methods-payment-initialize-options';\n\nconst POLLING_INTERVAL = 3000;\nconst MAX_POLLING_TIME = 300000;\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 gatewayId?: string;\n private isLPMsUpdateExperimentEnabled = false;\n private pollingTimer = 0;\n private stopPolling = noop;\n private isPollingEnabled = false;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeSdk: BraintreeSdk,\n private braintreeRequestSender: BraintreeRequestSender,\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 & WithBraintreeLocalMethodsPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, braintreelocalmethods } = options;\n\n this.gatewayId = gatewayId;\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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n\n this.isPollingEnabled = isExperimentEnabled(\n features,\n 'PAYPAL-5258.braintree_local_methods_polling',\n );\n\n this.isLPMsUpdateExperimentEnabled = isExperimentEnabled(\n features,\n 'PAYPAL-4853.add_new_payment_flow_for_braintree_lpms',\n );\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 const checkoutUrl = state.getStoreConfigOrThrow().links.checkoutLink;\n\n return {\n paymentType: methodId,\n amount: grandTotal,\n fallback: {\n url: checkoutUrl,\n buttonText: 'Complete Payment',\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 if (this.isPollingEnabled) {\n return new Promise((resolve, reject) => {\n void this.initializePollingMechanism(\n methodId,\n resolve,\n reject,\n this.gatewayId,\n );\n });\n }\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 this.resetPollingMechanism();\n\n return reject();\n }\n\n if (this.isPollingEnabled) {\n this.resetPollingMechanism();\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 if (this.isPollingEnabled) {\n this.resetPollingMechanism();\n }\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 /**\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.braintreeRequestSender.getOrderStatus(gatewayId, {\n params: {\n useMetadata: false,\n },\n });\n\n const isOrderPending = orderStatus.status === BraintreeOrderStatus.Pending;\n const isOrderApproved = orderStatus.status === BraintreeOrderStatus.Completed;\n const isPollingError = orderStatus.status === BraintreeOrderStatus.Failed;\n\n if (isOrderApproved) {\n this.deinitializePollingMechanism();\n\n return resolvePromise();\n }\n\n if (isPollingError) {\n return rejectPromise();\n }\n\n if (\n !isOrderApproved &&\n isOrderPending &&\n this.pollingTimer < this.maxPollingIntervalTime\n ) {\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 braintreelocalmethods: this.braintreelocalmethods,\n });\n\n this.handleError(new TimeoutError());\n } catch (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 private async reinitializeStrategy(\n options: PaymentInitializeOptions & WithBraintreeLocalMethodsPaymentInitializeOptions,\n ) {\n await this.deinitialize();\n await this.initialize(options);\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\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 BraintreeRequestSender from '../braintree-request-sender';\n\nimport BraintreeLocalMethodsPaymentStrategy from './braintree-local-methods-payment-strategy';\n\nconst createBraintreeLocalMethodsPaymentStrategy: PaymentStrategyFactory<\n BraintreeLocalMethodsPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n );\n const requestSender = createRequestSender();\n const braintreeRequestSender = new BraintreeRequestSender(requestSender);\n\n return new BraintreeLocalMethodsPaymentStrategy(\n paymentIntegrationService,\n braintreeSdk,\n braintreeRequestSender,\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 Braintree3DSVerifyCardError,\n Braintree3DSVerifyCardPayload,\n BraintreeFastlaneAddress,\n BraintreeFastlaneAuthenticationState,\n BraintreeFastlaneCardComponent,\n BraintreeFastlaneCardComponentOptions,\n BraintreeInitializationData,\n BraintreeSdk,\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 PaymentMethodCancelledError,\n PaymentMethodClientUnavailableError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\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 private is3DSEnabled?: boolean;\n private onError?: (error: Error) => void;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeFastlaneUtils: BraintreeFastlaneUtils,\n private braintreeSdk: BraintreeSdk,\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 await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { initializationData, clientToken } = paymentMethod || {};\n const { isFastlaneStylingEnabled } = initializationData || {};\n const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const isThreeDSExperimentEnabled = isExperimentEnabled(\n features,\n 'PROJECT-7080.braintree_fastlane_three_ds',\n );\n\n this.is3DSEnabled = paymentMethod.config.is3dsEnabled;\n\n if (clientToken && isThreeDSExperimentEnabled) {\n this.braintreeSdk.initialize(clientToken);\n }\n\n const paypalFastlaneStyleSettings = isFastlaneStylingEnabled\n ? paymentMethod.initializationData?.fastlaneStyles\n : undefined;\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 this.onError = braintreefastlane.onError;\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 await this.paymentIntegrationService.submitOrder(order, options);\n\n const paymentPayload = await this.preparePaymentPayload(payment.methodId);\n\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n\n this.braintreeFastlaneUtils.removeSessionIdFromCookies();\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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const isThreeDSExperimentEnabled = isExperimentEnabled(\n features,\n 'PROJECT-7080.braintree_fastlane_three_ds',\n );\n\n if (paypalInstrument) {\n const threeDSToken =\n this.is3DSEnabled && isThreeDSExperimentEnabled\n ? await this.get3DS(paypalInstrument.bigpayToken, paypalInstrument?.iin || '')\n : undefined;\n\n return {\n methodId,\n paymentData: {\n deviceSessionId,\n formattedPayload: {\n paypal_fastlane_token: {\n token: threeDSToken || paypalInstrument.bigpayToken,\n },\n },\n },\n };\n }\n\n const { getPaymentToken } = this.getBraintreeCardComponentOrThrow();\n\n const paymentToken = await getPaymentToken({\n name: { fullName },\n billingAddress: this.mapToPayPalAddress(billingAddress),\n });\n\n const binGuest = paymentToken.paymentSource.card?.binDetails?.bin || '';\n const threeDSToken =\n this.is3DSEnabled && isThreeDSExperimentEnabled\n ? await this.get3DS(paymentToken.id, binGuest)\n : undefined;\n\n return {\n methodId,\n paymentData: {\n deviceSessionId,\n nonce: threeDSToken || paymentToken.id,\n },\n };\n }\n\n /**\n * 3DS\n */\n private async get3DS(nonce: string, bin: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const threeDSecure = await this.braintreeSdk.getBraintreeThreeDS();\n const order = state.getOrderOrThrow();\n\n return new Promise((resolve, reject) => {\n void threeDSecure.verifyCard(\n {\n amount: order?.orderAmount,\n nonce,\n bin,\n onLookupComplete: (_data, next) => {\n threeDSecure.on('customer-canceled', () => {\n if (typeof this.onError === 'function') {\n this.onError(new PaymentMethodCancelledError());\n }\n\n reject(new PaymentMethodCancelledError());\n });\n\n next();\n },\n },\n (\n verifyError: Braintree3DSVerifyCardError,\n payload: Braintree3DSVerifyCardPayload,\n ) => {\n if (\n verifyError &&\n verifyError.code === 'THREEDS_VERIFY_CARD_CANCELED_BY_MERCHANT'\n ) {\n if (typeof this.onError === 'function') {\n this.onError(new PaymentMethodCancelledError());\n }\n\n reject(new PaymentMethodCancelledError());\n }\n\n return resolve(payload.nonce);\n },\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.braintreeFastlaneUtils.getSessionIdFromCookies();\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 BraintreeSdk,\n BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n );\n\n const braintreeFastlaneUtils = new BraintreeFastlaneUtils(\n paymentIntegrationService,\n braintreeIntegrationService,\n );\n\n const braintreeScriptLoader = new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n );\n\n const braintreeSdk = new BraintreeSdk(braintreeScriptLoader);\n\n return new BraintreeFastlanePaymentStrategy(\n paymentIntegrationService,\n braintreeFastlaneUtils,\n braintreeSdk,\n );\n};\n\nexport default toResolvableModule(createBraintreeFastlanePaymentStrategy, [\n { id: 'braintreeacceleratedcheckout' },\n]);\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { noop } from 'lodash';\n\nimport {\n BraintreeDataCollector,\n BraintreeInitializationData,\n BraintreeSdk,\n BraintreeVisaCheckout,\n VisaCheckoutAddress,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutTokenizedPayload,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n Address,\n InvalidArgumentError,\n LegacyAddress,\n MissingDataError,\n MissingDataErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithBraintreeVisaCheckoutPaymentInitializeOptions } from './braintree-visa-checkout-payment-options';\n\nexport default class BraintreeVisaCheckoutPaymentStrategy implements PaymentStrategy {\n private paymentMethod?: PaymentMethod;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private formPoster: FormPoster,\n private braintreeSdk: BraintreeSdk,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeVisaCheckoutPaymentInitializeOptions,\n ): 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 await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n\n this.paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n const checkout = state.getCheckoutOrThrow();\n const storeConfig = state.getStoreConfigOrThrow();\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 this.braintreeSdk.initialize(clientToken);\n\n const braintreeVisaCheckout = await this.braintreeSdk.getBraintreeVisaCheckout();\n\n const visaCheckoutSdk = await this.braintreeSdk.getVisaCheckoutSdk(config?.testMode);\n\n const initOptions = braintreeVisaCheckout.createInitOptions({\n settings: {\n locale: storeConfig.storeProfile.storeLanguage,\n shipping: {\n collectShipping: false,\n },\n },\n paymentRequest: {\n currencyCode: storeConfig.currency.code,\n subtotal: String(checkout.subtotal),\n },\n });\n\n await visaCheckoutSdk.init(initOptions);\n\n visaCheckoutSdk.on(\n 'payment.success',\n (paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) =>\n this.tokenizePayment(braintreeVisaCheckout, paymentSuccessPayload)\n .then(() =>\n Promise.all([\n this.paymentIntegrationService.loadCheckout(),\n this.paymentIntegrationService.loadPaymentMethod(methodId),\n ]),\n )\n .then(() => onPaymentSelect())\n .catch((error) => onError(error)),\n );\n visaCheckoutSdk.on('payment.error', (_, error) => onError(error));\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\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 (!this.paymentMethod?.initializationData?.nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { nonce } = this.paymentMethod.initializationData;\n\n try {\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: { nonce },\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.braintreeSdk.deinitialize();\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 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 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 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 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","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\n VisaCheckoutHostWindow,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeVisaCheckoutPaymentStrategy from './braintree-visa-checkout-payment-strategy';\n\nconst createBraintreeVisaCheckoutPaymentStrategy: PaymentStrategyFactory<\n BraintreeVisaCheckoutPaymentStrategy\n> = (paymentIntegrationService) => {\n const hostWindow: VisaCheckoutHostWindow & BraintreeHostWindow = window;\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), hostWindow, braintreeSDKVersionManager),\n );\n\n return new BraintreeVisaCheckoutPaymentStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeSdk,\n );\n};\n\nexport default toResolvableModule(createBraintreeVisaCheckoutPaymentStrategy, [\n { id: 'braintreevisacheckout' },\n]);\n","import {\n BraintreeError,\n BraintreeIntegrationService,\n BraintreeTokenizePayload,\n BraintreeVenmoCheckout,\n isBraintreeError,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n FormattedPayload,\n MissingDataError,\n MissingDataErrorType,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n PaymentStrategy,\n PaypalInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\nimport BraintreeVenmoPaymentStrategyInitializeOptions, {\n WithBraintreeVenmoInitializeOptions,\n} from './braintree-venmo-payment-strategy-initialize-options';\n\nexport default class BraintreeVenmoPaymentStrategy implements PaymentStrategy {\n private braintreeVenmoCheckout?: BraintreeVenmoCheckout;\n private venmoOptions?: BraintreeVenmoPaymentStrategyInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeIntegrationService: BraintreeIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeVenmoInitializeOptions,\n ): Promise {\n const { methodId } = options;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n const state = this.paymentIntegrationService.getState();\n\n this.venmoOptions = options.braintreevenmo;\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n await this.initializeBraintreeVenmo(paymentMethod);\n }\n\n async execute(orderRequest: OrderRequestBody): 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 await this.paymentIntegrationService.submitOrder(order);\n await this.paymentIntegrationService.submitPayment(paymentData);\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.braintreeIntegrationService.teardown();\n\n return Promise.resolve();\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 const state = this.paymentIntegrationService.getState();\n const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const isBraintreeVenmoWebFallbackSupport = isExperimentEnabled(\n features,\n 'PAYPAL-5406.braintree_venmo_web_fallback_support',\n );\n\n try {\n this.braintreeIntegrationService.initialize(clientToken);\n this.braintreeVenmoCheckout = await this.braintreeIntegrationService.getVenmoCheckout({\n ...(this.venmoOptions?.allowDesktop !== undefined\n ? { allowDesktop: this.venmoOptions.allowDesktop }\n : {}),\n ...(isBraintreeVenmoWebFallbackSupport\n ? {\n mobileWebFallBack: isBraintreeVenmoWebFallbackSupport,\n }\n : {}),\n });\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async preparePaymentData(payment: OrderPaymentRequestBody): Promise {\n const state = this.paymentIntegrationService.getState();\n const { nonce } = state.getPaymentMethodOrThrow(payment.methodId);\n\n if (nonce) {\n return { ...payment, paymentData: this.formattedPayload(nonce) };\n }\n const tokenizeResult = await this.braintreeVenmoTokenize();\n const sessionId = await this.braintreeIntegrationService.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 {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport BraintreeVenmoPaymentStrategy from './braintree-venmo-payment-strategy';\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nconst createBraintreeVenmoPaymentStrategy: CheckoutButtonStrategyFactory<\n BraintreeVenmoPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const scriptLoader = getScriptLoader();\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeScriptLoader = new BraintreeScriptLoader(\n scriptLoader,\n braintreeHostWindow,\n braintreeSDKVersionManager,\n );\n const braintreeIntegrationService = new BraintreeIntegrationService(\n braintreeScriptLoader,\n braintreeHostWindow,\n );\n\n return new BraintreeVenmoPaymentStrategy(\n paymentIntegrationService,\n braintreeIntegrationService,\n );\n};\n\nexport default toResolvableModule(createBraintreeVenmoPaymentStrategy, [{ id: 'braintreevenmo' }]);\n","import { some } from 'lodash';\n\nimport {\n BraintreeIntegrationService,\n BraintreeThreeDSecureOptions,\n isBraintreeAcceleratedCheckoutCustomer,\n isBraintreePaymentRequest3DSError,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n Address,\n isHostedInstrumentLike,\n isRequestError,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NonceInstrument,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentInstrument,\n PaymentInstrumentMeta,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodFailedError,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeHostedForm from '../braintree-hosted-form/braintree-hosted-form';\nimport isBraintreeError from '../is-braintree-error';\n\nimport {\n BraintreeCreditCardPaymentInitializeOptions,\n WithBraintreeCreditCardPaymentInitializeOptions,\n} from './braintree-credit-card-payment-initialize-options';\n\nexport default class BraintreeCreditCardPaymentStrategy implements PaymentStrategy {\n private is3dsEnabled?: boolean;\n private isHostedFormInitialized?: boolean;\n private deviceSessionId?: string;\n private paymentMethod?: PaymentMethod;\n private threeDSecure?: BraintreeThreeDSecureOptions;\n private onPaymentError?: BraintreeCreditCardPaymentInitializeOptions['onPaymentError'];\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeIntegrationService: BraintreeIntegrationService,\n private braintreeHostedForm: BraintreeHostedForm,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeCreditCardPaymentInitializeOptions,\n ): Promise {\n const { methodId, gatewayId, braintree } = options;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n\n this.paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n const { clientToken } = this.paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.threeDSecure = braintree?.threeDSecure;\n this.onPaymentError = braintree?.onPaymentError;\n\n try {\n this.braintreeIntegrationService.initialize(clientToken, this.threeDSecure);\n\n if (this.isHostedPaymentFormEnabled(methodId, gatewayId) && braintree?.form) {\n await this.braintreeHostedForm.initialize(\n braintree.form,\n braintree.unsupportedCardBrands,\n clientToken,\n );\n\n this.isHostedFormInitialized = this.braintreeHostedForm.isInitialized();\n }\n\n this.is3dsEnabled = this.paymentMethod.config.is3dsEnabled;\n this.deviceSessionId = await this.braintreeIntegrationService.getSessionId();\n\n // TODO: Remove when BT AXO A/B testing is finished\n if (this.shouldInitializeBraintreeFastlane()) {\n await this.initializeBraintreeFastlaneOrThrow(methodId);\n }\n } catch (error) {\n return this.handleError(error, methodId);\n }\n }\n\n async execute(orderRequest: OrderRequestBody): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (this.isHostedFormInitialized) {\n this.braintreeHostedForm.validate();\n }\n\n await this.paymentIntegrationService.submitOrder(order);\n\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddressOrThrow();\n const orderAmount = state.getOrderOrThrow().orderAmount;\n\n try {\n const paymentData = this.isHostedFormInitialized\n ? await this.prepareHostedPaymentData(payment, billingAddress, orderAmount)\n : await this.preparePaymentData(payment, billingAddress, orderAmount);\n\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData,\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.braintreeIntegrationService.teardown(),\n this.braintreeHostedForm.deinitialize(),\n ]);\n\n return Promise.resolve();\n }\n\n private handleError(error: unknown, methodId?: string): void | Promise {\n if (isBraintreeError(error)) {\n const isPaymentMethodInitialized = !!(\n methodId &&\n this.paymentIntegrationService.getState().isPaymentMethodInitialized({ methodId })\n );\n\n if (\n !isPaymentMethodInitialized &&\n error.code === 'HOSTED_FIELDS_INVALID_FIELD_SELECTOR'\n ) {\n return;\n }\n\n if (error.code.startsWith('THREEDS_')) {\n this.onPaymentError?.(new PaymentMethodFailedError('THREEDS_VERIFICATION_FAILED'));\n\n return Promise.reject();\n }\n\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.braintreeIntegrationService.verifyCard(\n payment,\n billingAddress,\n orderAmount,\n )\n : await this.braintreeIntegrationService.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 } = await this.braintreeHostedForm.tokenizeForStoredCardVerification();\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.verifyCardWithHostedForm(billingAddress, orderAmount)\n : await this.braintreeHostedForm.tokenize(billingAddress);\n\n return {\n ...commonPaymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n nonce,\n };\n }\n\n private prepareAdditionalActionPaymentData(\n payment: OrderPaymentRequestBody,\n nonce: string,\n ): PaymentInstrument & PaymentInstrumentMeta {\n const { paymentData } = payment;\n const commonPaymentData = { deviceSessionId: this.deviceSessionId, nonce };\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n if (\n this.isSubmittingWithStoredCard(payment) &&\n (shouldSaveInstrument || shouldSetAsDefaultInstrument)\n ) {\n return {\n ...paymentData,\n ...commonPaymentData,\n };\n }\n\n return {\n ...commonPaymentData,\n };\n }\n\n private async verifyCardWithHostedForm(\n billingAddress: Address,\n orderAmount: number,\n ): Promise {\n const tokenizationPayload = await this.braintreeHostedForm.tokenize(billingAddress);\n\n return this.braintreeIntegrationService.challenge3DSVerification(\n tokenizationPayload,\n orderAmount,\n );\n }\n\n private async processAdditionalAction(\n error: unknown,\n payment: OrderPaymentRequestBody,\n orderAmount: number,\n ): Promise {\n if (\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return this.handleError(error);\n }\n\n try {\n const { payer_auth_request: storedCreditCardNonce } =\n (isBraintreePaymentRequest3DSError(error) && error.body.three_ds_result) || {};\n const { paymentData } = payment;\n const state = this.paymentIntegrationService.getState();\n\n if (!paymentData || !isVaultedInstrument(paymentData)) {\n throw new PaymentArgumentInvalidError(['instrumentId']);\n }\n\n const instrument = state.getCardInstrumentOrThrow(paymentData.instrumentId);\n const { nonce } = await this.braintreeIntegrationService.challenge3DSVerification(\n {\n nonce: storedCreditCardNonce || '',\n bin: instrument.iin,\n },\n orderAmount,\n );\n\n const newPaymentData = this.prepareAdditionalActionPaymentData(payment, nonce);\n\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: newPaymentData,\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 state = this.paymentIntegrationService.getState();\n const paymentMethod = state.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 when BT AXO A/B testing is finished\n private shouldInitializeBraintreeFastlane(): boolean {\n const state = this.paymentIntegrationService.getState();\n const paymentProviderCustomer = state.getPaymentProviderCustomerOrThrow();\n const braintreeCustomer = isBraintreeAcceleratedCheckoutCustomer(paymentProviderCustomer)\n ? paymentProviderCustomer\n : {};\n const isFastlaneEnabled: boolean =\n this.paymentMethod?.initializationData.isAcceleratedCheckoutEnabled;\n\n return isFastlaneEnabled && !braintreeCustomer?.authenticationState;\n }\n\n // TODO: Remove when BT AXO A/B testing is finished\n private async initializeBraintreeFastlaneOrThrow(methodId: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { clientToken, config } = paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.braintreeIntegrationService.initialize(clientToken, this.threeDSecure);\n\n await this.braintreeIntegrationService.getBraintreeFastlane(cart.id, config.testMode);\n }\n}\n","export interface BraintreePayment3DSRequestErrors {\n code: string;\n}\n\nexport interface BraintreePaymentRequest3DSError {\n name: string;\n body: {\n status: string;\n three_ds_result: {\n payer_auth_request: string;\n };\n errors: BraintreePayment3DSRequestErrors[];\n };\n}\n\nexport default function isBraintreePaymentRequest3DSError(\n error: unknown,\n): error is BraintreePaymentRequest3DSError {\n if (typeof error !== 'object' || error === null) {\n return false;\n }\n /* eslint-disable @typescript-eslint/consistent-type-assertions */\n return (\n 'name' in error &&\n 'body' in error &&\n 'status' in (error as BraintreePaymentRequest3DSError).body &&\n 'three_ds_result' in (error as BraintreePaymentRequest3DSError).body &&\n 'payer_auth_request' in (error as BraintreePaymentRequest3DSError).body.three_ds_result &&\n 'errors' in (error as BraintreePaymentRequest3DSError).body\n );\n}\n","import { BraintreeFormFieldsMap, BraintreeStoredCardFieldsMap } from '../index';\n\nexport function isBraintreeFormFieldsMap(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n): fields is BraintreeFormFieldsMap {\n return 'cardNumber' in fields;\n}\n\nexport function isBraintreeStoredCardFieldsMap(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n): fields is BraintreeStoredCardFieldsMap {\n return !!(\n Object.keys(fields).length > 0 &&\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n ((fields as BraintreeStoredCardFieldsMap).cardCodeVerification ||\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n (fields as BraintreeStoredCardFieldsMap).cardNumberVerification)\n );\n}\n","import isBraintreeError from './is-braintree-error';\nimport { BraintreeHostedFormError } from '../types';\n\nfunction isValidInvalidFieldKeys(invalidFieldKeys: unknown): invalidFieldKeys is string[] {\n return (\n Array.isArray(invalidFieldKeys) && invalidFieldKeys.every((key) => typeof key === 'string')\n );\n}\n\nexport default function isBraintreeHostedFormError(\n error: unknown,\n): 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 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n (details as { invalidFieldKeys?: unknown }).invalidFieldKeys === undefined) ||\n isValidInvalidFieldKeys(details)\n );\n}\n","import { Dictionary, isEmpty, isNil, omitBy } from 'lodash';\n\nimport {\n BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION,\n BraintreeBillingAddressRequestData,\n BraintreeClient,\n BraintreeFormErrorDataKeys,\n BraintreeFormErrorsData,\n BraintreeFormFieldsMap,\n BraintreeFormFieldStyles,\n BraintreeFormFieldStylesMap,\n BraintreeFormFieldType,\n BraintreeFormFieldValidateErrorData,\n BraintreeFormFieldValidateEventData,\n BraintreeFormOptions,\n BraintreeHostedFields,\n BraintreeHostedFieldsCreatorConfig,\n BraintreeHostedFieldsState,\n BraintreeHostedFormError,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\n BraintreeStoredCardFieldsMap,\n isBraintreeFormFieldsMap,\n isBraintreeHostedFormError,\n isBraintreeSupportedCardBrand,\n TokenizationPayload,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n Address,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\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 client?: Promise;\n private clientToken?: string;\n private isInitializedHostedForm = false;\n\n constructor(\n private braintreeScriptLoader: BraintreeScriptLoader,\n private braintreeSDKVersionManager: BraintreeSDKVersionManager,\n ) {}\n\n async initialize(\n options: BraintreeFormOptions,\n unsupportedCardBrands?: string[],\n clientToken?: string,\n ): Promise {\n this.clientToken = clientToken;\n this.formOptions = options;\n this.type = isBraintreeFormFieldsMap(options.fields)\n ? BraintreeHostedFormType.CreditCard\n : BraintreeHostedFormType.StoredCardVerification;\n\n const fields = this.mapFieldOptions(options.fields, unsupportedCardBrands);\n\n if (isEmpty(fields)) {\n this.isInitializedHostedForm = false;\n\n return;\n }\n\n this.cardFields = await this.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 await this.cardFields?.teardown();\n }\n }\n\n validate(): void {\n if (!this.cardFields) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const state = this.cardFields.getState();\n\n if (!this.isValidForm(state)) {\n this.handleValidityChange(state);\n\n const errors = this.mapValidationErrors(state.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 payload = await this.cardFields.tokenize(\n omitBy(\n {\n billingAddress: billingAddress && this.mapBillingAddress(billingAddress),\n },\n isNil,\n ),\n );\n\n this.formOptions?.onValidate?.({ isValid: true, errors: {} });\n\n return {\n nonce: payload.nonce,\n bin: payload.details?.bin,\n };\n } catch (error) {\n if (isBraintreeHostedFormError(error)) {\n const errors = this.mapTokenizeError(error);\n\n if (errors) {\n this.formOptions?.onValidate?.({ isValid: false, errors });\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 payload = await this.cardFields.tokenize();\n\n this.formOptions?.onValidate?.({ isValid: true, errors: {} });\n\n return {\n nonce: payload.nonce,\n bin: payload.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?.({ isValid: false, errors });\n throw new PaymentInvalidFormError(errors as PaymentInvalidFormErrorDetails);\n }\n }\n\n throw error;\n }\n }\n\n async createHostedFields(\n options: Pick,\n ): Promise {\n const client = await this.getClient();\n const hostedFields = await this.braintreeScriptLoader.loadHostedFields();\n\n const currentSdkVersion = this.braintreeSDKVersionManager.getSDKVersion();\n const hostedFieldsOptions =\n currentSdkVersion === BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION\n ? { ...options, preventCursorJumps: true }\n : options;\n\n return hostedFields.create({ ...hostedFieldsOptions, client });\n }\n\n async getClient(): Promise {\n if (!this.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!this.client) {\n const client = await this.braintreeScriptLoader.loadClient();\n\n this.client = client.create({ authorization: this.clientToken });\n }\n\n return this.client;\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 unsupportedCardBrands?: string[],\n ): BraintreeHostedFieldsCreatorConfig['fields'] {\n if (isBraintreeFormFieldsMap(fields)) {\n const supportedCardBrands: Partial> = {};\n\n unsupportedCardBrands?.forEach((cardBrand) => {\n if (isBraintreeSupportedCardBrand(cardBrand)) {\n supportedCardBrands[cardBrand] = false;\n }\n });\n\n return omitBy(\n {\n number: {\n container: `#${fields.cardNumber.containerId}`,\n placeholder: fields.cardNumber.placeholder,\n internalLabel: fields.cardNumber.accessibilityLabel,\n ...(Object.keys(supportedCardBrands).length > 0\n ? { supportedCardBrands }\n : {}),\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 // eslint-disable-next-line no-restricted-syntax\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 cvv = [this.createRequiredError(this.mapFieldType('cvv'))];\n\n if (isStoredCard) {\n return { [this.mapFieldType('cvv')]: cvv };\n }\n\n return {\n [this.mapFieldType('cvv')]: cvv,\n [this.mapFieldType('expirationDate')]: [\n this.createRequiredError(this.mapFieldType('expirationDate')),\n ],\n [this.mapFieldType('number')]: [\n this.createRequiredError(this.mapFieldType('number')),\n ],\n [this.mapFieldType('cardholderName')]: [\n this.createRequiredError(this.mapFieldType('cardholderName')),\n ],\n };\n }\n\n return error.details?.invalidFieldKeys?.reduce((result, key) => {\n const type = this.mapFieldType(key);\n\n return {\n ...result,\n [type]: [this.createInvalidError(type)],\n };\n }, {});\n }\n\n private createRequiredError(\n fieldType: BraintreeFormFieldType,\n ): BraintreeFormFieldValidateErrorData {\n const messages = {\n [BraintreeFormFieldType.CardCode]: 'CVV is required',\n [BraintreeFormFieldType.CardCodeVerification]: 'CVV is required',\n [BraintreeFormFieldType.CardNumber]: 'Credit card number is required',\n [BraintreeFormFieldType.CardNumberVerification]: 'Credit card number is required',\n [BraintreeFormFieldType.CardExpiry]: 'Expiration date is required',\n [BraintreeFormFieldType.CardName]: 'Full name is required',\n };\n\n return {\n fieldType,\n message: messages[fieldType] ?? 'Field is required',\n type: 'required',\n };\n }\n\n private createInvalidError(\n fieldType: BraintreeFormFieldType,\n ): BraintreeFormFieldValidateErrorData {\n const formFields = {\n [BraintreeFormFieldType.CardCode]: {\n message: 'Invalid card code',\n type: 'invalid_card_code',\n },\n [BraintreeFormFieldType.CardCodeVerification]: {\n message: 'Invalid card code',\n type: 'invalid_card_code',\n },\n [BraintreeFormFieldType.CardNumber]: {\n message: 'Invalid card number',\n type: 'invalid_card_number',\n },\n [BraintreeFormFieldType.CardNumberVerification]: {\n message: 'Invalid card number',\n type: 'invalid_card_number',\n },\n [BraintreeFormFieldType.CardExpiry]: {\n message: 'Invalid card expiry',\n type: 'invalid_card_expiry',\n },\n [BraintreeFormFieldType.CardName]: {\n message: 'Invalid card name',\n type: 'invalid_card_name',\n },\n };\n\n return {\n fieldType,\n message: formFields[fieldType]?.message ?? 'Invalid field',\n type: formFields[fieldType]?.type ?? 'invalid',\n };\n }\n\n private handleBlur = (event: BraintreeHostedFieldsState): void => {\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 => {\n this.formOptions?.onFocus?.({\n fieldType: this.mapFieldType(event.emittedBy),\n });\n };\n\n private handleCardTypeChange = (event: BraintreeHostedFieldsState): void => {\n const cardType =\n event.cards.length === 1\n ? event.cards[0].type.replace(/^master-card$/, 'mastercard')\n : undefined;\n\n this.formOptions?.onCardTypeChange?.({ cardType });\n };\n\n private handleInputSubmitRequest = (event: BraintreeHostedFieldsState): void => {\n this.formOptions?.onEnter?.({\n fieldType: this.mapFieldType(event.emittedBy),\n });\n };\n\n private handleValidityChange = (event: BraintreeHostedFieldsState): void => {\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(key: string): key is BraintreeFormErrorDataKeys {\n return [\n 'number',\n 'cvv',\n 'expirationDate',\n 'postalCode',\n 'cardholderName',\n 'cardType',\n ].includes(key);\n }\n}\n","import { BraintreeSupportedCardBrands } from '../types';\n\nexport const isBraintreeSupportedCardBrand = (\n cardBrand: string,\n): cardBrand is BraintreeSupportedCardBrands => {\n const supportedCardBrands = Object.values(BraintreeSupportedCardBrands);\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return supportedCardBrands.includes(cardBrand as BraintreeSupportedCardBrands);\n};\n\nexport default isBraintreeSupportedCardBrand;\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeCreditCardPaymentStrategy from './braintree-credit-card-payment-strategy';\nimport BraintreeHostedForm from '../braintree-hosted-form/braintree-hosted-form';\n\nconst createBraintreeCreditCardPaymentStrategy: PaymentStrategyFactory<\n BraintreeCreditCardPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n\n const braintreeScriptLoader = new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n );\n\n const braintreeIntegrationService = new BraintreeIntegrationService(\n braintreeScriptLoader,\n braintreeHostWindow,\n );\n\n const braintreeHostedForm = new BraintreeHostedForm(\n braintreeScriptLoader,\n braintreeSDKVersionManager,\n );\n\n return new BraintreeCreditCardPaymentStrategy(\n paymentIntegrationService,\n braintreeIntegrationService,\n braintreeHostedForm,\n );\n};\n\nexport default toResolvableModule(createBraintreeCreditCardPaymentStrategy, [{ id: 'braintree' }]);\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 { noop, some } from 'lodash';\n\nimport { CreditCardPaymentStrategy } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStatusTypes,\n RequestError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\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';\nimport { isCBAMPGSPaymentMethodLike, isThreeDSErrorBody } from './is-cba-mpgs-payment-method-like';\n\nexport default class CBAMPGSPaymentStrategy extends CreditCardPaymentStrategy {\n private threeDSjs?: ThreeDSjs;\n\n private sessionId = '';\n private locale?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private cbaMGPSScriptLoader: CBAMPGSScriptLoader,\n ) {\n super(paymentIntegrationService);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const { methodId } = options;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n if (!isCBAMPGSPaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\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 this.locale = state.getLocale();\n\n if (!this.locale) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n await this.threeDSjs.configure({\n merchantId,\n sessionId: this.sessionId,\n callback: () => {\n if (this.threeDSjs?.isConfigured()) {\n return this.paymentIntegrationService.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();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): 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 state = this.paymentIntegrationService.getState();\n const paymentMethod = state.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 !isRequestError(error) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n const retryState = this.paymentIntegrationService.getState();\n const order = retryState.getOrder();\n\n const {\n storeProfile: { storeId },\n } = retryState.getStoreConfigOrThrow();\n\n if (!order || !this.sessionId) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const orderId = `${storeId}_${order.orderId}`;\n\n if (!isThreeDSErrorBody(error.body)) {\n throw new RequestError();\n }\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 async finalize(options?: PaymentRequestOptions): Promise {\n const state = this.paymentIntegrationService.getState();\n const order = state.getOrder();\n\n if (order && state.getPaymentStatus() === PaymentStatusTypes.FINALIZE) {\n await this.paymentIntegrationService.finalizeOrder(options);\n\n return Promise.resolve();\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(orderId: string, transactionId: string): 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 PaymentMethodFailedError(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 PaymentMethodFailedError());\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 PaymentMethodFailedError();\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 // eslint-disable-next-line @typescript-eslint/no-misused-promises\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 // eslint-disable-next-line no-plusplus, no-param-reassign\n return this.authenticatePayer(orderId, transactionId, ++attempt);\n }\n\n return reject(new PaymentMethodFailedError());\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","/* eslint-disable @typescript-eslint/consistent-type-assertions */\nimport { PaymentMethod } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CBAMPGSPaymentMethod, ThreeDSErrorBody } from './cba-mpgs';\n\nexport function isCBAMPGSPaymentMethodLike(\n paymentMethod: PaymentMethod,\n): paymentMethod is CBAMPGSPaymentMethod {\n return (\n typeof paymentMethod === 'object' &&\n paymentMethod !== null &&\n 'initializationData' in paymentMethod &&\n typeof (paymentMethod as CBAMPGSPaymentMethod).initializationData === 'object' &&\n (paymentMethod as CBAMPGSPaymentMethod).initializationData !== null &&\n 'merchantId' in (paymentMethod as CBAMPGSPaymentMethod).initializationData &&\n typeof (paymentMethod as CBAMPGSPaymentMethod).initializationData.merchantId === 'string' &&\n (typeof (paymentMethod as CBAMPGSPaymentMethod).initializationData.isTestModeFlagEnabled ===\n 'boolean' ||\n typeof (paymentMethod as CBAMPGSPaymentMethod).initializationData\n .isTestModeFlagEnabled === 'undefined')\n );\n}\n\nexport function isThreeDSErrorBody(body: unknown): body is ThreeDSErrorBody {\n return (\n typeof body === 'object' &&\n body !== null &&\n 'three_ds_result' in body &&\n typeof (body as ThreeDSErrorBody).three_ds_result === 'object' &&\n (body as ThreeDSErrorBody).three_ds_result !== null &&\n 'token' in (body as ThreeDSErrorBody).three_ds_result &&\n typeof (body as ThreeDSErrorBody).three_ds_result.token === 'string'\n );\n}\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport { PaymentMethod } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport 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\nexport interface CBAMPGSPaymentMethod extends PaymentMethod {\n initializationData: CBAMPGSInitializationData;\n}\n\nexport interface CBAMPGSInitializationData {\n isTestModeFlagEnabled?: boolean;\n merchantId: string;\n}\n\nexport interface ThreeDSErrorBody {\n three_ds_result: {\n token: string;\n };\n}\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\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 { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CBAMPGSPaymentStrategy from './cba-mpgs-payment-strategy';\nimport CBAMPGSScriptLoader from './cba-mpgs-script-loader';\n\nconst createCBAMPGSPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new CBAMPGSPaymentStrategy(\n paymentIntegrationService,\n new CBAMPGSScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createCBAMPGSPaymentStrategy, [{ id: 'cba_mpgs' }]);\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 skipRedirectConfirmationAlert: true,\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\n if (\n methodId === CHECKOUTCOM_SEPA_PAYMENT_METHOD &&\n document &&\n 'iban' in paymentData &&\n 'bic' in paymentData\n ) {\n const { iban, bic } = paymentData as unknown as WithCheckoutcomSEPAInstrument;\n\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 const features = this._paymentIntegrationService.getState().getStoreConfigOrThrow()\n .checkoutSettings.features;\n\n this._clearpaySdk = await this._clearpayScriptLoader.load(paymentMethod, features);\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';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\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 HTTPS_SANDBOX: 'https://portal.sandbox.clearpay.co.uk/afterpay-async.js',\n HTTPS_PROD: 'https://portal.clearpay.co.uk/afterpay-async.js',\n};\n\nconst CLEARPAY_HTTPS_PROD_SCRIPT_EXPERIMENT = 'PI-4555.clearpay_add_https_to_prod_script';\n\nexport default class ClearpayScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, public _window: ClearpayWindow = window) {}\n\n async load(method: PaymentMethod, features = {}): Promise {\n await this._scriptLoader.loadScript(this._getScriptUrl(method.config.testMode, features));\n\n if (!this._window.AfterPay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.AfterPay;\n }\n\n private _getScriptUrl(testMode?: boolean, features = {}): string {\n const httpsEnabled = isExperimentEnabled(\n features,\n CLEARPAY_HTTPS_PROD_SCRIPT_EXPERIMENT,\n false,\n );\n\n if (testMode) {\n return httpsEnabled ? SCRIPTS_DEFAULT.HTTPS_SANDBOX : SCRIPTS_DEFAULT.SANDBOX;\n }\n\n return httpsEnabled ? SCRIPTS_DEFAULT.HTTPS_PROD : 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';\n\nconst SDK_PROD_URL = 'https://static.client.cardinaltrusted.com/songbird/v2.0.0/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, [\n { id: 'cybersourcev2' },\n { id: 'bnz' },\n]);\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 {\n guard,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n Omit,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { DEFAULT_CONTAINER_STYLES, LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\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 ErrorReasonType,\n GooglePayError,\n GooglePayInitializationData,\n GooglePayPaymentOptions,\n HandleCouponsOut,\n IntermediatePaymentData,\n TotalPriceStatusType,\n} from './types';\n\nexport default class GooglePayPaymentStrategy implements PaymentStrategy {\n private _loadingIndicator: LoadingIndicator;\n private _loadingIndicatorContainer?: string;\n private _paymentButton?: HTMLElement;\n private _clickListener?: (event: MouseEvent) => unknown;\n private _methodId?: keyof WithGooglePayPaymentInitializeOptions;\n private _isDeinitializationBlocked = false;\n\n constructor(\n protected _paymentIntegrationService: PaymentIntegrationService,\n protected _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n ) {\n this._loadingIndicator = new LoadingIndicator({\n containerStyles: DEFAULT_CONTAINER_STYLES,\n });\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, loadingContainerId, ...callbacks } = googlePayOptions;\n\n this._loadingIndicatorContainer = loadingContainerId;\n\n await this._paymentIntegrationService.loadPaymentMethod(this._getMethodId());\n\n const paymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(this._getMethodId());\n\n this._googlePayPaymentProcessor.setIsWebViewExperimentOn(\n !!paymentMethod.initializationData?.isWebViewExperimentOn,\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._isDeinitializationBlocked) {\n return Promise.resolve();\n }\n\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 this._googlePayPaymentProcessor.setShouldRequestShipping(false);\n await this._googlePayPaymentProcessor.initializeWidget();\n\n if (this._isDirectPayOnClickEnabled()) {\n await this._interactWithPaymentSheetAndPay();\n } else {\n await this._interactWithPaymentSheet();\n }\n } catch (error) {\n let err: unknown = error;\n\n this._toggleLoadingIndicator(false);\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 } finally {\n this._toggleBlockDeinitialization(false);\n }\n\n onPaymentSelect?.();\n };\n }\n\n protected async _interactWithPaymentSheetAndPay(): Promise {\n const response = await this._googlePayPaymentProcessor.showPaymentSheet();\n\n this._toggleBlockDeinitialization(true);\n this._toggleLoadingIndicator(true);\n\n const methodId = this._getMethodId();\n\n const state = this._paymentIntegrationService.getState();\n const { features } = state.getStoreConfigOrThrow().checkoutSettings;\n const isGooglePayDontOverrideAddresssExperimentOn = isExperimentEnabled(\n features,\n 'PI-5031.google_pay_dont_override_address',\n );\n\n const billingAddress =\n this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(response);\n\n if (billingAddress && !isGooglePayDontOverrideAddresssExperimentOn) {\n await this._paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n await this._googlePayPaymentProcessor.setExternalCheckoutXhr(methodId, response);\n\n await this._paymentIntegrationService.loadCheckout();\n await this._paymentIntegrationService.loadPaymentMethod(methodId);\n\n const freshPaymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n\n await this._googlePayPaymentProcessor.initialize(() => freshPaymentMethod);\n\n await this.execute({ useStoreCredit: false, payment: { methodId } });\n\n this._completeCheckoutFlow();\n }\n\n protected _completeCheckoutFlow(): void {\n window.location.replace('/checkout/order-confirmation');\n this._toggleLoadingIndicator(false);\n this._toggleBlockDeinitialization(false);\n }\n\n protected async _interactWithPaymentSheet(): Promise {\n const response = await this._googlePayPaymentProcessor.showPaymentSheet();\n const state = this._paymentIntegrationService.getState();\n const { features } = state.getStoreConfigOrThrow().checkoutSettings;\n const isGooglePayDontOverrideAddresssExperimentOn = isExperimentEnabled(\n features,\n 'PI-5031.google_pay_dont_override_address',\n );\n\n this._toggleBlockDeinitialization(true);\n this._toggleLoadingIndicator(true);\n\n const billingAddress =\n this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(response);\n\n if (billingAddress && !isGooglePayDontOverrideAddresssExperimentOn) {\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 this._toggleLoadingIndicator(false);\n this._toggleBlockDeinitialization(false);\n }\n\n protected _getMethodId(): keyof WithGooglePayPaymentInitializeOptions {\n return guard(\n this._methodId,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n protected async _getIsSignedInOrThrow(): Promise {\n try {\n return !!(await this._googlePayPaymentProcessor.getNonce(this._getMethodId()));\n } catch (e) {\n if (\n e instanceof MissingDataError &&\n e.subtype === MissingDataErrorType.MissingPaymentToken\n ) {\n return false;\n }\n\n throw e;\n }\n }\n\n protected async _handleOfferTrigger(\n offerData: IntermediatePaymentData['offerData'],\n ): Promise> {\n let isSignedIn = false;\n let errorMessage = 'Sign in to Google Pay first to apply or remove promo codes.';\n\n try {\n isSignedIn = await this._getIsSignedInOrThrow();\n } catch (error) {\n if (error instanceof MissingDataError) {\n errorMessage = error.message;\n }\n }\n\n // We can only apply/remove coupons on the payment step only if we are logged into Google Pay, otherwise we will get an error\n if (isSignedIn) {\n const { newOfferInfo, error } = await this._googlePayPaymentProcessor.handleCoupons(\n offerData,\n );\n\n return {\n newOfferInfo,\n error,\n };\n }\n\n return {\n error: {\n reason: ErrorReasonType.OFFER_INVALID,\n message: errorMessage,\n intent: CallbackTriggerType.OFFER,\n },\n };\n }\n\n protected _getGooglePayClientOptions(countryCode?: string): GooglePayPaymentOptions {\n if (this._googlePayPaymentProcessor.isWebViewWithRestrictions()) {\n return {};\n }\n\n return {\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({ callbackTrigger, offerData }) => {\n if (\n callbackTrigger !== CallbackTriggerType.INITIALIZE &&\n callbackTrigger !== CallbackTriggerType.OFFER\n ) {\n return;\n }\n\n const { offerChangeTriggers } =\n this._googlePayPaymentProcessor.getCallbackTriggers();\n\n const { newOfferInfo = undefined, error: couponsError = undefined } =\n offerChangeTriggers.includes(callbackTrigger)\n ? await this._handleOfferTrigger(offerData)\n : {};\n\n // We can add another errors if needed 'couponsError || shippingError || anotherError'\n const error: GooglePayError | undefined = couponsError;\n\n await this._paymentIntegrationService.loadCheckout();\n\n const { code: currencyCode } = this._paymentIntegrationService\n .getState()\n .getCartOrThrow().currency;\n const totalPrice = this._googlePayPaymentProcessor.getTotalPrice();\n\n return {\n newTransactionInfo: {\n ...(countryCode && { countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n ...(newOfferInfo && {\n newOfferInfo,\n }),\n ...(error && {\n error,\n }),\n };\n },\n },\n };\n }\n\n private _isDirectPayOnClickEnabled(): boolean {\n const { features } = this._paymentIntegrationService\n .getState()\n .getStoreConfigOrThrow().checkoutSettings;\n\n return isExperimentEnabled(features, 'PI-5111.google_pay_direct_pay_on_click');\n }\n\n private _toggleBlockDeinitialization(isBlocked: boolean) {\n this._isDeinitializationBlocked = isBlocked;\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 { 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';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\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';\n\nconst createGooglePayStripePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayStripeGateway(\n paymentIntegrationService,\n new StripeScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayStripePaymentStrategy, [\n { id: 'googlepaystripe' },\n { id: 'googlepaystripeupe' },\n { id: 'googlepaystripeocs' },\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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 MissingDataError,\n MissingDataErrorType,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../google-pay-payment-strategy';\nimport { GooglePayInitializationData, GooglePayPayPalCommerceInitializationData } from '../types';\n\nimport { ConfirmOrderData, ConfirmOrderStatus } from './types';\n\nexport default class GooglePayPaypalCommercePaymentStrategy extends GooglePayPaymentStrategy {\n constructor(\n _paymentIntegrationService: PaymentIntegrationService,\n _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n private _payPalCommerceSdk: PayPalCommerceSdk,\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 if (!paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const currencyCode = state.getCartOrThrow().currency.code;\n\n const payPalSDK = await this._payPalCommerceSdk.getPayPalGooglePaySdk(\n paymentMethod,\n currencyCode,\n state.getLocale(),\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';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\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';\n\nconst createGooglePayPayPalCommercePaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) => {\n const payPalCommerceSdk = new PayPalCommerceSdk(getScriptLoader());\n\n return new GooglePayPaypalCommercePaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayPaypalCommerceGateway(paymentIntegrationService, payPalCommerceSdk),\n createRequestSender(),\n createFormPoster(),\n ),\n payPalCommerceSdk,\n createRequestSender(),\n );\n};\n\nexport default toResolvableModule(createGooglePayPayPalCommercePaymentStrategy, [\n { id: 'googlepaypaypalcommerce' },\n]);\n","import { GooglePayConfig } from '../types';\n\nexport type FundingType = string;\n\n/**\n *\n * BigCommercePayments 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 BigCommercePaymentsHostWindow extends Window {\n paypal?: PayPalSDK;\n}\n\nexport interface BigCommercePaymentsScriptParams {\n options: {\n 'client-id'?: string;\n 'merchant-id'?: string;\n 'buyer-country'?: string;\n 'disable-funding'?: FundingType[];\n 'enable-funding'?: FundingType[];\n currency?: string;\n commit?: boolean;\n intent?: BigCommercePaymentsIntent;\n components?: ComponentsScriptType;\n };\n attributes: {\n 'data-client-token'?: string;\n 'data-partner-attribution-id'?: string;\n };\n}\n\nexport enum BigCommercePaymentsIntent {\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 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 BigCommercePaymentsInitializationData,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentMethod,\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 {\n GooglePayBigCommercePaymentsInitializationData,\n GooglePayInitializationData,\n} from '../types';\n\nimport { ConfirmOrderData, ConfirmOrderStatus } from './types';\n\nexport default class GooglePayBigCommercePaymentsPaymentStrategy extends GooglePayPaymentStrategy {\n constructor(\n _paymentIntegrationService: PaymentIntegrationService,\n _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n private _payPalSdkHelper: PayPalSdkHelper,\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 if (!paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const currencyCode = state.getCartOrThrow().currency.code;\n\n const payPalSDK = await this._payPalSdkHelper.getPayPalGooglePaySdk(\n paymentMethod as 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/googlepay_bigcommerce_paymentscheckout';\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 { PayPalSdkHelper } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\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 GooglePayBigCommercePaymentsGateway from './google-pay-bigcommerce-payments-gateway';\nimport GooglePayBigCommercePaymentsPaymentStrategy from './google-pay-bigcommerce-payments-payment-strategy';\n\nconst createGooglePayBigCommercePaymentsPaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) => {\n const payPalSdkHelper = new PayPalSdkHelper(getScriptLoader());\n\n return new GooglePayBigCommercePaymentsPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayBigCommercePaymentsGateway(paymentIntegrationService, payPalSdkHelper),\n createRequestSender(),\n createFormPoster(),\n ),\n payPalSdkHelper,\n createRequestSender(),\n );\n};\n\nexport default toResolvableModule(createGooglePayBigCommercePaymentsPaymentStrategy, [\n { id: 'googlepay_bigcommerce_payments' },\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","import { 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';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport KlarnaPayments, {\n KlarnaAddress,\n KlarnaAuthorizationResponse,\n KlarnaInitializationData,\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, initializationData } =\n state.getPaymentMethodOrThrow(methodId);\n const { klarnaMultipleRadioButton } = initializationData || {};\n\n await this.klarnav2TokenUpdater.klarnaOrderInitialization(cartId, clientToken);\n\n const paymentMethodСategory = this.isKlarnaMultipleRadioButtonEnabled(\n klarnaMultipleRadioButton,\n gatewayId,\n methodId,\n );\n const { authorization_token: authorizationToken } = await this.authorizeOrThrow(\n paymentMethodСategory,\n methodId,\n );\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 const { klarnaMultipleRadioButton } = paymentMethod.initializationData || {};\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 {\n container,\n payment_method_category: this.isKlarnaMultipleRadioButtonEnabled(\n klarnaMultipleRadioButton,\n gatewayId,\n methodId,\n ),\n },\n (response) => {\n if (onLoad) {\n onLoad(response);\n }\n\n resolve(response);\n },\n );\n });\n }\n\n private getUpdateSessionData(\n methodId: string,\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(\n methodId,\n billingAddress,\n billingAddress.email,\n ),\n };\n\n if (shippingAddress) {\n data.shipping_address = this.mapToKlarnaAddress(\n methodId,\n shippingAddress,\n billingAddress.email,\n );\n }\n\n return data;\n }\n\n private needsStateCode(countryCode: string) {\n return includes(supportedCountriesRequiringStates, countryCode);\n }\n\n private isKlarnaMultipleRadioButtonEnabled(\n klarnaMultipleRadioButton: boolean | undefined,\n gatewayId: string,\n methodId: string,\n ): string {\n return klarnaMultipleRadioButton ? methodId : gatewayId;\n }\n\n private mapToKlarnaAddress(methodId: string, address: Address, email?: string): KlarnaAddress {\n const state = this.paymentIntegrationService.getState();\n const { checkoutSettings } = state.getStoreConfigOrThrow();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { enableBillie } = paymentMethod.initializationData || {};\n\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 if (\n address.company &&\n enableBillie &&\n isExperimentEnabled(checkoutSettings.features, 'PI-3915.b2b_payment_session_for_klarna')\n ) {\n klarnaAddress.organization_name = address.company;\n }\n\n return klarnaAddress;\n }\n\n private async authorizeOrThrow(\n paymentMethodСategory: string,\n methodId: string,\n ): 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(\n methodId,\n billingAddress,\n shippingAddress,\n );\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 {\n payment_method_category: paymentMethodСategory,\n },\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 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 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\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 (\n typeof response.data !== 'string' ||\n response.origin !== `https://${testMode ? 'esqa' : 'www3'}.moneris.com`\n ) {\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 iframe.allow = 'payment';\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 {\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\n console.log('payload =======1', payload)\n\n await this._paymentIntegrationService.submitOrder(\n {\n ...payload,\n payment: payload.payment\n ? {\n methodId: payload.payment.methodId,\n ...(payload.payment.methodId === 'purchaseorder' && {\n paymentData: payload.payment.paymentData,\n }),\n }\n : 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 payment.gatewayId === 'adyen' || payment.gatewayId === 'barclaycard';\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","import { MessagesStyleOptions, PayPalBNPLConfigurationItem } from '../paypal-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 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 {\n ApproveCallbackPayload,\n ClickCallbackActions,\n getPaypalMessagesStylesFromBNPLConfig,\n isPaypalProviderError,\n isRedirectActionError,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalButtons,\n PayPalButtonsOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalMessagesSdk,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isBaseInstrument } from '@bigcommerce/checkout-sdk/utility';\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?: PayPalButtons;\n private paypalcommerce?: PayPalCommercePaymentInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\n private payPalSdkScriptLoader: PayPalSdkScriptLoader,\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 = state.getPaymentMethodOrThrow(methodId);\n\n const { container, bannerContainerId } = paypalcommerce;\n\n const {\n orderId,\n paypalBNPLConfiguration = [],\n isPayPalCreditAvailable,\n } = paymentMethod.initializationData || {};\n\n if (bannerContainerId !== undefined) {\n if (!document.getElementById(bannerContainerId)) {\n // eslint-disable-next-line no-console\n console.error('Unable to create banner without valid banner container ID.');\n\n return;\n }\n\n const bannerConfiguration = paypalBNPLConfiguration?.find(\n ({ id }) => id === 'checkout',\n );\n\n if (isPayPalCreditAvailable || !bannerConfiguration?.status) {\n return;\n }\n\n const paypalMessages = await this.payPalSdkScriptLoader.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n state.getLocale(),\n );\n\n if (!paypalMessages || typeof paypalMessages?.Messages !== 'function') {\n console.error(\n '[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n return this.renderMessages(paypalMessages, bannerContainerId, bannerConfiguration);\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 = paymentMethod.initializationData?.orderId;\n\n return;\n }\n\n this.loadingIndicatorContainer = container?.split('#')[1];\n\n await this.paypalIntegrationService.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\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 (isRedirectActionError(error)) {\n const redirectUrl = error.body.additional_action_required?.data?.redirect_url;\n\n return new Promise(() => window.location.replace(redirectUrl));\n }\n\n if (this.isProviderError(error)) {\n await this.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { paymentButtonStyles } = paymentMethod.initializationData || {};\n const { checkoutPaymentButtonStyles } = paymentButtonStyles || {};\n const { container, onError, onRenderButton, onValidate, submitForm } = paypalcommerce;\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"container\" argument is not provided.',\n );\n }\n\n const containerId = this.getSmartButtonContainerId(container);\n const smartButtonContainer = document.getElementById(containerId);\n\n if (!smartButtonContainer) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because element with id ${containerId} does not exist.`,\n );\n }\n\n const buttonOptions: PayPalButtonsOptions = {\n ...(this.isPaypalCommerceAppSwitchEnabled(methodId) && {\n appSwitchWhenAvailable: true,\n }),\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalIntegrationService.getValidButtonStyle(checkoutPaymentButtonStyles),\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 if (this.paypalButton.hasReturned?.() && this.isPaypalCommerceAppSwitchEnabled(methodId)) {\n this.paypalButton.resume?.();\n } else {\n this.paypalButton.render(container);\n }\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 return 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.paypalIntegrationService.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 const findInstrument = instruments?.find(\n (instrument) =>\n isBaseInstrument(instrument) &&\n instrument.bigpayToken === paymentData.instrumentId,\n );\n const trustedShippingAddress = isBaseInstrument(findInstrument)\n ? findInstrument.trustedShippingAddress\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 /**\n *\n * Render Pay Later Messages\n *\n * */\n private renderMessages(\n paypalMessages: PayPalMessagesSdk,\n bannerContainerId: string,\n bannerConfiguration: PayPalBNPLConfigurationItem,\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: checkout.outstandingBalance,\n placement: 'payment',\n style: getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\n };\n\n paypalMessages.Messages(paypalMessagesOptions).render(`#${bannerContainerId}`);\n }\n\n /**\n *\n * Error handling\n *\n */\n private isProviderError(error: unknown): boolean {\n if (isPaypalProviderError(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 /**\n *\n * PayPal AppSwitch enabling handling\n *\n */\n private isPaypalCommerceAppSwitchEnabled(methodId: string): boolean {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n return paymentMethod.initializationData?.isAppSwitchEnabled || false;\n }\n\n private getSmartButtonContainerId(container: string) {\n return container.split('#')[1] ?? container;\n }\n}\n","import { isRequestError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ProviderError } from './is-paypal-provider-error';\n\nexport interface RedirectActionError extends ProviderError {\n body: {\n additional_action_required: {\n type: 'offsite_redirect';\n data: {\n redirect_url: string;\n };\n };\n };\n}\n\nexport default function isRedirectActionError(error: unknown): error is RedirectActionError {\n return (\n isRequestError(error) && error.body.additional_action_required?.type === 'offsite_redirect'\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 isPaypalProviderError(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 PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalIntegrationService,\n LOADING_INDICATOR_STYLES,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommercePaymentStrategy from './paypal-commerce-payment-strategy';\n\nconst createPayPalCommercePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new PayPalCommercePaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\n new PayPalSdkScriptLoader(getScriptLoader()),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createPayPalCommercePaymentStrategy, [{ id: 'paypalcommerce' }]);\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 ApproveCallbackPayload,\n ClickCallbackActions,\n getPaypalMessagesStylesFromBNPLConfig,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalButtons,\n PayPalButtonsOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalMessagesSdk,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\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?: PayPalButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\n private loadingIndicator: LoadingIndicator,\n private payPalSdkScriptLoader: PayPalSdkScriptLoader,\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 = state.getPaymentMethodOrThrow(methodId);\n\n const { paypalBNPLConfiguration = [], orderId } = paymentMethod.initializationData || {};\n const { bannerContainerId, container } = paypalOptions;\n\n if (bannerContainerId !== undefined) {\n if (!document.getElementById(bannerContainerId)) {\n // eslint-disable-next-line no-console\n console.error('Unable to create banner without valid banner container ID.');\n\n return;\n }\n\n const bannerConfiguration =\n paypalBNPLConfiguration &&\n paypalBNPLConfiguration.find(({ id }) => id === 'checkout');\n\n if (!bannerConfiguration?.status) {\n return;\n }\n\n const paypalMessages = await this.payPalSdkScriptLoader.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n state.getLocale(),\n );\n\n return this.renderMessages(paypalMessages, bannerContainerId, bannerConfiguration);\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.paypalIntegrationService.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.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = 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: PayPalButtonsOptions = {\n fundingSource,\n style: this.paypalIntegrationService.getValidButtonStyle(\n checkoutPaymentButtonStyles,\n ),\n createOrder: () =>\n this.paypalIntegrationService.createOrder('paypalcommercecreditcheckout'),\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 return 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,\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: checkout.outstandingBalance,\n placement: 'payment',\n style: getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\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 {\n createPayPalIntegrationService,\n createPayPalSdkScriptLoader,\n LOADING_INDICATOR_STYLES,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceCreditPaymentStrategy from './paypal-commerce-credit-payment-strategy';\n\nconst createPayPalCommerceCreditPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceCreditPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditPaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n createPayPalSdkScriptLoader(),\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 {\n ApproveCallbackPayload,\n ClickCallbackActions,\n PayPalButtons,\n PayPalButtonsOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\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?: PayPalButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\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 = 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.paypalIntegrationService.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.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = 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: PayPalButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.paypalIntegrationService.getValidButtonStyle(checkoutPaymentButtonStyles),\n createOrder: () =>\n this.paypalIntegrationService.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 return 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 { createPayPalIntegrationService } from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceVenmoPaymentStrategy from './paypal-commerce-venmo-payment-strategy';\n\nconst createPayPalCommerceVenmoPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceVenmoPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceVenmoPaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n\nexport default toResolvableModule(createPayPalCommerceVenmoPaymentStrategy, [\n { id: 'paypalcommercevenmo' },\n]);\n","export const LOADING_INDICATOR_STYLES = {\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\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 TimeoutError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n PayPalApmSdk,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport {\n ApproveCallbackPayload,\n NonInstantAlternativePaymentMethods,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n PayPalOrderStatus,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceAlternativeMethodsPaymentOptions, {\n WithPayPalCommerceAlternativeMethodsPaymentInitializeOptions,\n} from './paypal-commerce-alternative-methods-payment-initialize-options';\n\nconst POLLING_INTERVAL = 3000;\nconst MAX_POLLING_TIME = 300000;\n\nexport default class PayPalCommerceAlternativeMethodsPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n private paypalApms?: PayPalApmSdk;\n private pollingTimer = 0;\n private stopPolling = noop;\n private isOrderApprovedProcessing = false;\n private paypalcommercealternativemethods?: PayPalCommerceAlternativeMethodsPaymentOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalIntegrationService,\n private paypalSdkScriptLoader: PayPalSdkScriptLoader,\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 &\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 this.paypalcommercealternativemethods = paypalcommercealternativemethods;\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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n\n this.isOrderApprovedProcessing = isExperimentEnabled(\n features,\n 'PAYPAL-5431.order_approved_processing',\n false,\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 this.paypalApms = await this.paypalSdkScriptLoader.getPayPalApmsSdk(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n state.getLocale(),\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.isOrderApprovedProcessing && methodId === 'ideal') {\n await new Promise((resolve, reject) => {\n void this.initializePollingMechanism(methodId, resolve, reject, gatewayId);\n });\n }\n\n if (\n !this.isNonInstantPaymentMethod(methodId) ||\n (methodId === NonInstantAlternativePaymentMethods.IDEAL &&\n !this.isOrderApprovedProcessing)\n ) {\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 if (!this.isOrderApprovedProcessing) {\n this.resetPollingMechanism();\n }\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Polling mechanism\n *\n *\n * */\n private async initializePollingMechanism(\n methodId: string,\n resolvePromise: (value?: unknown) => void,\n rejectPromise: (value?: unknown) => 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 gatewayId ?? 'paypalcommerce',\n );\n\n const isOrderApproved = orderStatus === PayPalOrderStatus.Approved;\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 paypalcommercealternativemethods: this.paypalcommercealternativemethods,\n });\n\n this.handleError(new TimeoutError());\n } catch (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 private async reinitializeStrategy(\n options: PaymentInitializeOptions &\n WithPayPalCommerceAlternativeMethodsPaymentInitializeOptions,\n ) {\n await this.deinitialize();\n await this.initialize(options);\n }\n\n private handleError(error: unknown) {\n const { onError } = this.paypalcommercealternativemethods || {};\n\n if (!this.isOrderApprovedProcessing) {\n this.resetPollingMechanism();\n }\n\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\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: () => {\n this.toggleLoadingIndicator(false);\n this.deinitializePollingMechanism();\n },\n onError: (error) => {\n this.deinitializePollingMechanism();\n this.handleFailure(error, onError);\n },\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 (\n this.isNonInstantPaymentMethod(methodId) &&\n ((methodId === NonInstantAlternativePaymentMethods.IDEAL &&\n this.isOrderApprovedProcessing) ||\n methodId === NonInstantAlternativePaymentMethods.OXXO)\n ) {\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\n if (methodId === NonInstantAlternativePaymentMethods.IDEAL) {\n const state = this.paymentIntegrationService.getState();\n const bcOrderId = state.getOrder()?.orderId;\n\n await this.paypalCommerceIntegrationService.updateOrder(\n 'paypalcommercealternativemethods',\n methodId,\n bcOrderId,\n );\n }\n\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 {\n createPayPalIntegrationService,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\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 createPayPalIntegrationService(paymentIntegrationService),\n createPayPalSdkScriptLoader(),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createPayPalCommerceAlternativeMethodsPaymentStrategy, [\n { gateway: 'paypalcommercealternativemethods' },\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 { isPayPalCommerceAcceleratedCheckoutCustomer } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\nimport {\n PayPalFastlaneUtils,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\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 paypalIntegrationService: PayPalIntegrationService,\n private paypalSdkScriptLoader: PayPalSdkScriptLoader,\n private paypalFastlaneUtils: PayPalFastlaneUtils,\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, onLoadComplete } =\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.paypalIntegrationService.loadPayPalSdk(methodId, undefined, true, true);\n\n if (this.isCreditCardForm || this.isCreditCardVaultedForm) {\n await this.initializeFields(form, onCreditCardFieldsRenderingError);\n }\n\n onLoadComplete?.();\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.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n const executeCallback = this.getExecuteCallback(fields);\n\n const cardFieldsConfig: PayPalCommerceCardFieldsConfig = {\n style: this.getInputStyles(styles),\n onApprove: ({\n orderID,\n vaultSetupToken,\n liabilityShift,\n }: PayPalCommerceCardFieldsOnApproveData) => {\n if (\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.paypalIntegrationService.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.paypalIntegrationService.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 = 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 = state.getPaymentMethodOrThrow(methodId);\n const { initializationData } = paymentMethod;\n\n if (!initializationData?.connectClientToken) {\n return;\n }\n\n const payPalFastlaneSdk = await this.paypalSdkScriptLoader.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n state.getLocale(),\n );\n\n await this.paypalFastlaneUtils.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 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 {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalFastlaneUtils,\n createPayPalIntegrationService,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceCreditCardsPaymentStrategy from './paypal-commerce-credit-cards-payment-strategy';\n\nconst createPaypalCommerceCreditCardsPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceCreditCardsPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditCardsPaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\n createPayPalSdkScriptLoader(),\n createPayPalFastlaneUtils(),\n );\n\nexport default toResolvableModule(createPaypalCommerceCreditCardsPaymentStrategy, [\n { id: 'paypalcommercecreditcards' },\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 {\n BirthDate,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalOrderStatus,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\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 paypalCommerceService: PayPalIntegrationService,\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.paypalCommerceService.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.paypalCommerceService.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.paypalCommerceService.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.paypalCommerceService.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 {\n createPayPalIntegrationService,\n LOADING_INDICATOR_STYLES,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PaypalCommerceRatepayPaymentStrategy from './paypal-commerce-ratepay-payment-strategy';\n\nconst createPaypalCommerceRatepayPaymentStrategy: PaymentStrategyFactory<\n PaypalCommerceRatepayPaymentStrategy\n> = (paymentIntegrationService) =>\n new PaypalCommerceRatepayPaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(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 PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n getFastlaneStyles,\n isPayPalFastlaneCustomer,\n isPaypalFastlaneRequestError,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneCardComponentMethods,\n PayPalFastlaneCardComponentOptions,\n PayPalFastlanePaymentFormattedPayload,\n PayPalFastlaneSdk,\n PayPalFastlaneUtils,\n PayPalInitializationData,\n PayPalSdkScriptLoader,\n TDSecureAuthenticationState,\n TDSecureVerificationMethod,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceRequestSender from '../paypal-commerce-request-sender';\nimport { LiabilityShiftEnum } from '../paypal-commerce-types';\n\nimport PayPalCommerceFastlanePaymentInitializeOptions, {\n WithPayPalCommerceFastlanePaymentInitializeOptions,\n} from './paypal-commerce-fastlane-payment-initialize-options';\n\nexport default class PaypalCommerceFastlanePaymentStrategy implements PaymentStrategy {\n private paypalComponentMethods?: PayPalFastlaneCardComponentMethods;\n private paypalFastlaneSdk?: PayPalFastlaneSdk;\n private threeDSVerificationMethod?: string;\n private paypalcommercefastlane?: PayPalCommerceFastlanePaymentInitializeOptions;\n private orderId?: string;\n private methodId?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceRequestSender: PayPalCommerceRequestSender,\n private paypalSdkScriptLoader: PayPalSdkScriptLoader,\n private paypalFastlaneUtils: PayPalFastlaneUtils,\n ) {}\n\n /**\n *\n * Default methods\n *\n * */\n async initialize(\n options: PaymentInitializeOptions & WithPayPalCommerceFastlanePaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommercefastlane } = options;\n\n this.methodId = methodId;\n\n this.paypalcommercefastlane = paypalcommercefastlane;\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 = state.getPaymentMethodOrThrow(methodId);\n const { isDeveloperModeApplicable, isFastlaneStylingEnabled } =\n paymentMethod.initializationData || {};\n\n this.threeDSVerificationMethod =\n paymentMethod.initializationData?.threeDSVerificationMethod;\n\n this.paypalFastlaneSdk = await this.paypalSdkScriptLoader.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n state.getLocale(),\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.paypalFastlaneUtils.initializePayPalFastlane(\n this.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 await this.paymentIntegrationService.submitOrder(order, options);\n\n const paymentPayload = isVaultedFlow\n ? await this.prepareVaultedInstrumentPaymentPayload(methodId, paymentData)\n : await this.preparePaymentPayload(methodId, paymentData);\n\n await this.paymentIntegrationService.submitPayment(\n paymentPayload,\n );\n\n this.paypalFastlaneUtils.removeStorageSessionId();\n } catch (error) {\n if (\n isPaypalFastlaneRequestError(error) &&\n error.response.body.name === 'INVALID_REQUEST'\n ) {\n const invalidRequestError = {\n translationKey: 'payment.errors.invalid_request_error',\n };\n\n this.handleError(invalidRequestError);\n\n return Promise.reject();\n }\n\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.paypalFastlaneUtils.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 } = await this.paypalFastlaneUtils.lookupCustomerOrThrow(\n customerEmail,\n );\n\n const authenticationResult =\n await this.paypalFastlaneUtils.triggerAuthenticationFlowOrThrow(customerContextId);\n\n const { authenticationState, addresses, instruments } =\n this.paypalFastlaneUtils.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 if (isAuthenticationFlowCanceled) {\n this.paypalFastlaneUtils.removeStorageSessionId();\n } else {\n this.paypalFastlaneUtils.updateStorageSessionId(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.paypalFastlaneUtils.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 paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const is3DSEnabled = paymentMethod.config.is3dsEnabled;\n\n const nonce = is3DSEnabled ? await this.get3DSNonce(instrumentId) : instrumentId;\n\n await this.createOrder(nonce);\n\n return {\n methodId,\n paymentData: {\n formattedPayload: {\n paypal_fastlane_token: {\n order_id: this.orderId,\n token: nonce,\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 billingAddress = state.getBillingAddressOrThrow();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\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.paypalFastlaneUtils.mapBcToPayPalAddress(billingAddress),\n });\n\n const is3DSEnabled = paymentMethod.config.is3dsEnabled;\n\n const nonce = is3DSEnabled ? await this.get3DSNonce(id) : id;\n\n await this.createOrder(nonce);\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: this.orderId,\n token: nonce,\n },\n },\n },\n };\n }\n\n private async createOrder(id: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cartId = state.getCartOrThrow().id;\n\n if (this.methodId) {\n const { orderId } = await this.paypalCommerceRequestSender.createOrder(this.methodId, {\n cartId,\n fastlaneToken: id,\n });\n\n this.orderId = orderId;\n }\n }\n\n /**\n *\n * 3DSecure methods\n *\n * */\n private async get3DSNonce(nonce: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const order = state.getOrderOrThrow();\n const checkoutUrl = state.getStoreConfigOrThrow().links.checkoutLink;\n\n const threeDomainSecureComponent = this.paypalFastlaneSdk?.ThreeDomainSecureClient;\n\n if (!threeDomainSecureComponent) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n const threeDomainSecureParameters = {\n amount: order.orderAmount.toFixed(2),\n currency: cart.currency.code,\n nonce,\n threeDSRequested: this.threeDSVerificationMethod === TDSecureVerificationMethod.Always,\n transactionContext: {\n experience_context: {\n locale: 'en-US',\n return_url: checkoutUrl,\n cancel_url: checkoutUrl,\n },\n },\n };\n\n const isThreeDomainSecureEligible = await threeDomainSecureComponent.isEligible(\n threeDomainSecureParameters,\n );\n\n if (\n this.threeDSVerificationMethod === TDSecureVerificationMethod.Always &&\n !isThreeDomainSecureEligible\n ) {\n throw new PaymentMethodInvalidError();\n }\n\n if (isThreeDomainSecureEligible) {\n const {\n liabilityShift,\n authenticationState,\n nonce: threeDSNonce,\n } = await threeDomainSecureComponent.show();\n\n if (\n liabilityShift === LiabilityShiftEnum.No ||\n liabilityShift === LiabilityShiftEnum.Unknown ||\n authenticationState === TDSecureAuthenticationState.Errored ||\n authenticationState === TDSecureAuthenticationState.Cancelled\n ) {\n throw new PaymentMethodInvalidError();\n }\n\n if (\n authenticationState === TDSecureAuthenticationState.Succeeded &&\n [LiabilityShiftEnum.Yes, LiabilityShiftEnum.Possible].includes(liabilityShift)\n ) {\n return threeDSNonce;\n }\n\n throw new PaymentMethodInvalidError();\n }\n\n return nonce;\n }\n\n /**\n *\n * PayPal Fastlane instrument change\n *\n */\n private async handlePayPalStoredInstrumentChange(\n methodId: string,\n ): Promise {\n const paypalAxoSdk = this.paypalFastlaneUtils.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.paypalFastlaneUtils.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 private handleError(error: unknown): void {\n if (\n this.paypalcommercefastlane?.onError &&\n typeof this.paypalcommercefastlane.onError === 'function'\n ) {\n this.paypalcommercefastlane.onError(error);\n }\n }\n}\n","export interface PaypalFastlaneRequestError {\n name: string;\n message: string;\n response: {\n body: {\n name: string;\n };\n };\n}\n\nexport default function isPaypalFastlaneRequestError(\n error: unknown,\n): error is PaypalFastlaneRequestError {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'message' in error &&\n 'response' in error &&\n 'body' in (error as PaypalFastlaneRequestError).response &&\n 'name' in (error as PaypalFastlaneRequestError).response.body\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 createPayPalFastlaneUtils,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-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 createPayPalSdkScriptLoader(),\n createPayPalFastlaneUtils(),\n );\n};\n\nexport default toResolvableModule(createPayPalCommerceFastlanePaymentStrategy, [\n { id: 'paypalcommerceacceleratedcheckout' }, // PayPal Fastlane relates to 'paypalcommerceacceleratedcheckout' method id\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 enum PaymentStatusTypes {\n ACKNOWLEDGE = 'ACKNOWLEDGE',\n FINALIZE = 'FINALIZE',\n INITIALIZE = 'INITIALIZE',\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 { noop } from 'lodash';\n\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithPaypalExpressPaymentInitializeOptions } from './paypal-express-payment-initialize-options';\nimport PaypalScriptLoader from './paypal-express-script-loader';\nimport { PaymentStatusTypes, PaypalHostWindow, PaypalSDK } from './paypal-express-types';\n\nexport default class PaypalExpressPaymentStrategy implements PaymentStrategy {\n private paypalSdk?: PaypalSDK;\n private paymentMethod?: PaymentMethod;\n private useRedirectFlow = false;\n private window: PaypalHostWindow;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: PaypalScriptLoader,\n ) {\n this.window = window;\n }\n\n async initialize(\n options: PaymentInitializeOptions & WithPaypalExpressPaymentInitializeOptions,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n\n this.paymentMethod = state.getPaymentMethodOrThrow(options.methodId);\n this.useRedirectFlow =\n (options.paypalexpress && options.paypalexpress.useRedirectFlow) === true;\n\n const merchantId = this.paymentMethod.config.merchantId;\n\n if (!this.isInContextEnabled() || !merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const paypalSdk = await this.scriptLoader.loadPaypalSDK();\n\n this.paypalSdk = paypalSdk;\n\n this.paypalSdk.checkout.setup(merchantId, {\n button: 'paypal-button',\n environment: this.paymentMethod.config.testMode ? 'sandbox' : 'production',\n });\n }\n\n deinitialize() {\n if (this.isInContextEnabled() && this.paypalSdk) {\n this.paypalSdk.checkout.closeFlow();\n this.paypalSdk = undefined;\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions) {\n let state: PaymentIntegrationSelectors;\n let redirectUrl: string | undefined;\n const paypal = this.paypalSdk;\n\n if (this.isAcknowledgedOrFinalized()) {\n await this.paymentIntegrationService.submitOrder(payload, options);\n\n return;\n }\n\n if (!this.isInContextEnabled() || this.useRedirectFlow) {\n state = await this.paymentIntegrationService.submitOrder(payload, options);\n redirectUrl = state.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 if (!paypal) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n paypal.checkout.initXO();\n\n try {\n state = await this.paymentIntegrationService.submitOrder(payload, options);\n } catch (error) {\n paypal.checkout.closeFlow();\n\n return Promise.reject(error);\n }\n\n redirectUrl = state.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\n async finalize(options?: PaymentRequestOptions) {\n const state = this.paymentIntegrationService.getState();\n const order = state.getOrder();\n\n if (order && this.isAcknowledgedOrFinalized()) {\n await this.paymentIntegrationService.finalizeOrder(options);\n\n return Promise.resolve();\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private isAcknowledgedOrFinalized(): boolean {\n const state = this.paymentIntegrationService.getState();\n\n return (\n state.getPaymentStatus() === PaymentStatusTypes.ACKNOWLEDGE ||\n state.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 '@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 { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PaypalExpressPaymentStrategy from './paypal-express-payment-strategy';\nimport PaypalExpressScriptLoader from './paypal-express-script-loader';\n\nconst createPaypalExpressPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new PaypalExpressPaymentStrategy(\n paymentIntegrationService,\n new PaypalExpressScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createPaypalExpressPaymentStrategy, [\n { id: 'paypalexpress', type: 'PAYMENT_TYPE_HOSTED' },\n { id: 'paypalexpresscredit', type: 'PAYMENT_TYPE_HOSTED' },\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 { 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 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new Promise(() => {\n this.redirectUrl(redirect_url);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }) as any;\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 { 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 ('errors' in result && 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(methodId, 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(methodId: string, shouldSaveInstrument?: boolean) {\n const { getPaymentMethodOrThrow } = this._paymentIntegrationService.getState();\n const { initializationData } = getPaymentMethodOrThrow(methodId);\n\n const cardTokenizationResult = await this._squareV2PaymentProcessor.tokenize();\n\n if (\n initializationData && 'isSquareV2ApiV2Enabled' in initializationData\n ? !initializationData.isSquareV2ApiV2Enabled\n : !this.shouldVerify()\n ) {\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 { getPaymentMethodOrThrow } = this._paymentIntegrationService.getState();\n const { initializationData } = getPaymentMethodOrThrow(methodId);\n\n const { instrumentId } = paymentData;\n const shouldVerify =\n initializationData && 'isSquareV2ApiV2Enabled' in initializationData\n ? initializationData.isSquareV2ApiV2Enabled\n : this.shouldVerify();\n const verificationToken = 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 PaymentStrategy,\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 allow_redisplay?: 'always' | 'limited' | 'unspecified';\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 allowRedisplayForStoredInstruments?: 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 private _allowRedisplayForStoredInstruments?: 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 allowRedisplayForStoredInstruments,\n },\n } = paymentMethod as StripeV3PaymentMethod;\n\n this._allowRedisplayForStoredInstruments = allowRedisplayForStoredInstruments;\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 const shouldAllowRedisplay = this._allowRedisplayForStoredInstruments;\n\n return this.getStripeJs().createPaymentMethod({\n type: StripePaymentMethodType.CreditCard,\n card,\n billing_details: billingDetails,\n ...(shouldAllowRedisplay ? { allow_redisplay: 'always' } : {}),\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","export const supportedLocales: Record = {\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-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 { merge, 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 PaymentRequestOptions,\n PaymentStrategy,\n RequestError,\n StripeUPEIntent,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n formatStripeLocale,\n isStripePaymentMethodLike,\n STRIPE_UPE_CLIENT_API_VERSION,\n STRIPE_UPE_CLIENT_BETAS,\n StripeAdditionalActionRequired,\n StripeAppearanceOptions,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeElementUpdateOptions,\n StripeEventType,\n StripeFormattedPaymentPayload,\n StripeInitializationData,\n StripeIntegrationService,\n StripeJsVersion,\n StripePaymentMethodType,\n StripeResult,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport isStripeAcceleratedCheckoutCustomer from './is-stripe-accelerated-checkout-customer';\nimport StripeUPEPaymentInitializeOptions, {\n WithStripeUPEPaymentInitializeOptions,\n} from './stripe-upe-initialize-options';\n\nexport default class StripeUPEPaymentStrategy implements PaymentStrategy {\n private _stripeUPEClient?: StripeClient;\n private _stripeElements?: StripeElements;\n private _isStripeElementUpdateEnabled?: boolean;\n private _allowRedisplayForStoredInstruments?: boolean;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n private stripeIntegrationService: StripeIntegrationService,\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.stripeIntegrationService.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.stripeIntegrationService.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 await this.paymentIntegrationService.submitOrder(order, options);\n\n if (isVaultedInstrument(paymentData)) {\n const { instrumentId } = paymentData;\n\n await this._executeWithVaulted(\n payment.methodId,\n instrumentId,\n shouldSetAsDefaultInstrument,\n );\n\n return;\n }\n\n await this._executeWithStripeConfirmation(\n payment.methodId,\n payment.gatewayId,\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.stripeIntegrationService.deinitialize();\n this._stripeElements = undefined;\n this._stripeUPEClient = undefined;\n\n return Promise.resolve();\n }\n\n private async _executeWithStripeConfirmation(\n methodId: string,\n gatewayId?: 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 gatewayId,\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\n if (!isStripePaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { clientToken, initializationData } = paymentMethod;\n const {\n shopperLanguage,\n allowRedisplayForStoredInstruments = false,\n enableLink,\n } = initializationData;\n\n this._allowRedisplayForStoredInstruments = allowRedisplayForStoredInstruments;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._stripeUPEClient = await this._loadStripeJs(initializationData);\n this._isStripeElementUpdateEnabled = typeof initStripeElementUpdateTrigger === 'function';\n\n let appearance: StripeAppearanceOptions | undefined;\n\n if (style) {\n const styles = style;\n\n appearance = {\n variables: this.stripeIntegrationService.mapAppearanceVariables(style),\n rules: {\n '.Input': this.stripeIntegrationService.mapInputAppearanceRules(styles),\n },\n };\n }\n\n this._stripeElements = await this.scriptLoader.getElements(this._stripeUPEClient, {\n clientSecret: clientToken,\n locale: formatStripeLocale(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 link: enableLink ? StripeStringConstants.AUTO : StripeStringConstants.NEVER,\n },\n ...this._getStripeElementTerms(),\n });\n\n this.stripeIntegrationService.mountElement(stripeElement, containerId);\n\n stripeElement.on(StripeElementEvent.READY, () => {\n render();\n });\n\n stripeElement.on(StripeElementEvent.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 gatewayId?: string,\n shouldSaveInstrument = false,\n shouldSetAsDefaultInstrument = false,\n ): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.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, error: stripeError } = 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 if (stripeError || !paymentIntent) {\n const { initializationData } = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n const { sendSecondPaymentRequestOnStripeError } = initializationData || {};\n\n if (sendSecondPaymentRequestOnStripeError) {\n // INFO: even in case when stripe payment confirmation was declined\n // we need to send submitPayment request to update status of checkout session on BE side.\n try {\n const paymentPayloadWithError = merge({}, paymentPayload, {\n paymentData: {\n formattedPayload: {\n client_side_error: true,\n },\n },\n });\n\n await this.paymentIntegrationService.submitPayment(paymentPayloadWithError);\n } catch {\n // INFO: additional action should be ignored for this update status request.\n // will throw Stripe error message to the shopper.\n }\n }\n\n this.stripeIntegrationService.throwStripeError(stripeError);\n }\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n methodId: string,\n additionalActionData: StripeAdditionalActionRequired['data'],\n ): Promise {\n if (!this._stripeUPEClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeIntegrationService.mapStripePaymentData(\n this._stripeElements,\n redirect_url,\n !!this._allowRedisplayForStoredInstruments,\n );\n\n const isPaymentCompleted = await this.stripeIntegrationService.isPaymentCompleted(\n methodId,\n this._stripeUPEClient,\n );\n\n return !isPaymentCompleted\n ? this._stripeUPEClient.confirmPayment(stripePaymentData)\n : this._stripeUPEClient.retrievePaymentIntent(token || '');\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.stripeIntegrationService.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 initializationData: StripeInitializationData,\n ): Promise {\n if (this._stripeUPEClient) {\n return this._stripeUPEClient;\n }\n\n const state = this.paymentIntegrationService.getState();\n\n return this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n StripeJsVersion.V3,\n STRIPE_UPE_CLIENT_BETAS,\n STRIPE_UPE_CLIENT_API_VERSION,\n );\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';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeUPEPaymentStrategy from './stripe-upe-payment-strategy';\n\nconst createStripeUPEPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n\n return new StripeUPEPaymentStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n );\n};\n\nexport default toResolvableModule(createStripeUPEPaymentStrategy, [\n { gateway: 'stripeupe' },\n { gateway: 'stripeupe', id: 'klarna' },\n]);\n","import { StripePaymentEvent } from './stripe';\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 { merge } from 'lodash';\n\nimport {\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 PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n isStripePaymentEvent,\n isStripePaymentMethodLike,\n StripeAdditionalActionRequired,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElements,\n StripeElementType,\n StripeEventType,\n StripeFormattedPaymentPayload,\n StripeInitializationData,\n StripeInstrumentSetupFutureUsage,\n StripeIntegrationService,\n StripePIPaymentMethodOptions,\n StripePIPaymentMethodSavingOptions,\n StripeResult,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeOCSPaymentInitializeOptions, {\n WithStripeOCSPaymentInitializeOptions,\n} from './stripe-ocs-initialize-options';\n\nexport default class StripeOCSPaymentStrategy implements PaymentStrategy {\n private stripeClient?: StripeClient;\n private stripeElements?: StripeElements;\n private selectedMethodId?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n private stripeIntegrationService: StripeIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithStripeOCSPaymentInitializeOptions,\n ): Promise {\n const { stripeocs, methodId, gatewayId } = options;\n\n if (!stripeocs?.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(stripeocs, gatewayId, methodId);\n } catch (error) {\n if (error instanceof Error) {\n stripeocs.onError?.(error);\n }\n }\n\n this.stripeIntegrationService.initCheckoutEventsSubscription(\n gatewayId,\n methodId,\n stripeocs,\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.stripeClient) {\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 { isStoreCreditApplied } = this.paymentIntegrationService\n .getState()\n .getCheckoutOrThrow();\n\n if (isStoreCreditApplied) {\n await this.paymentIntegrationService.applyStoreCredit(isStoreCreditApplied);\n }\n\n await this.stripeIntegrationService.updateStripePaymentIntent(gatewayId, methodId);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n const { clientToken } = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n\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, gatewayId);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n const paymentElement = this.stripeElements?.getElement(StripeElementType.PAYMENT);\n\n paymentElement?.unmount();\n paymentElement?.destroy();\n this.stripeIntegrationService.deinitialize();\n this.stripeElements = undefined;\n this.stripeClient = undefined;\n\n return Promise.resolve();\n }\n\n private async _initializeStripeElement(\n stripe: StripeOCSPaymentInitializeOptions,\n gatewayId: string,\n methodId: string,\n ) {\n let paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n\n if (!paymentMethod?.clientToken) {\n const state = await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n\n paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n }\n\n if (!isStripePaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { clientToken, initializationData } = paymentMethod;\n const { customerSessionToken, enableLink } = initializationData;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.stripeClient = await this._loadStripeJs(initializationData);\n\n const {\n appearance,\n containerId,\n fonts,\n layout,\n render,\n paymentMethodSelect,\n handleClosePaymentMethod,\n togglePreloader,\n } = stripe;\n\n this.stripeElements = await this.scriptLoader.getElements(this.stripeClient, {\n clientSecret: clientToken,\n customerSessionClientSecret: customerSessionToken,\n appearance,\n fonts,\n });\n\n const { getBillingAddress, getShippingAddress } = this.paymentIntegrationService.getState();\n const billingAddress = getBillingAddress();\n const { postalCode } = getShippingAddress() || billingAddress || {};\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 link: enableLink ? StripeStringConstants.AUTO : StripeStringConstants.NEVER,\n },\n layout,\n savePaymentMethod: {\n maxVisiblePaymentMethods: 20,\n },\n defaultValues: {\n billingDetails: {\n email: billingAddress?.email || '',\n },\n },\n });\n\n this.stripeIntegrationService.mountElement(stripeElement, containerId);\n\n stripeElement.on(StripeElementEvent.LOADER_START, () => {\n togglePreloader?.(false);\n });\n\n stripeElement.on(StripeElementEvent.READY, () => {\n render();\n });\n\n stripeElement.on(StripeElementEvent.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 initializationData: StripeInitializationData,\n ): Promise {\n if (this.stripeClient) {\n return this.stripeClient;\n }\n\n const state = this.paymentIntegrationService.getState();\n const stripeJsVersion =\n this.stripeIntegrationService.getStripeJsVersion(initializationData);\n\n return this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n stripeJsVersion,\n );\n }\n\n private _collapseStripeElement() {\n const stripeElement = this.stripeElements?.getElement(StripeElementType.PAYMENT);\n\n stripeElement?.collapse();\n }\n\n private _getPaymentPayload(\n methodId: string,\n token: string,\n paymentMethodOptions?: StripePIPaymentMethodOptions,\n ): Payment {\n const cartId = this.paymentIntegrationService.getState().getCart()?.id || '';\n const { card, us_bank_account } = paymentMethodOptions || {};\n const shouldSaveInstrument =\n this._shouldSaveInstrument(card) || this._shouldSaveInstrument(us_bank_account);\n const tokenizedOptions = this._getTokenizedOptions(token, paymentMethodOptions);\n\n const formattedPayload = {\n cart_id: cartId,\n confirm: false,\n method: this.selectedMethodId,\n vault_payment_instrument: shouldSaveInstrument,\n ...tokenizedOptions,\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 gatewayId: string,\n ): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n if (!this.stripeClient || !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, error: stripeError } = await this._confirmStripePaymentOrThrow(\n methodId,\n additionalActionData,\n );\n const {\n client_secret: paymentIntentClientSecret,\n payment_method_options: paymentMethodOptions,\n } = paymentIntent || {};\n\n const paymentPayload = this._getPaymentPayload(\n methodId,\n paymentIntentClientSecret || token,\n paymentMethodOptions,\n );\n\n if (stripeError || !paymentIntent) {\n const { initializationData } = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n const { sendSecondPaymentRequestOnStripeError } = initializationData || {};\n\n if (sendSecondPaymentRequestOnStripeError) {\n // INFO: even in case when stripe payment confirmation was declined\n // we need to send submitPayment request to update status of checkout session on BE side.\n try {\n const paymentPayloadWithError = merge({}, paymentPayload, {\n paymentData: {\n formattedPayload: {\n client_side_error: true,\n },\n },\n });\n\n await this.paymentIntegrationService.submitPayment(paymentPayloadWithError);\n } catch {\n // INFO: additional action should be ignored for this update status request.\n // will throw Stripe error message to the shopper.\n }\n }\n\n this.stripeIntegrationService.throwStripeError(stripeError);\n }\n\n try {\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n methodId: string,\n additionalActionData: StripeAdditionalActionRequired['data'],\n ): Promise {\n if (!this.stripeClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeIntegrationService.mapStripePaymentData(\n this.stripeElements,\n redirect_url,\n );\n\n const isPaymentCompleted = await this.stripeIntegrationService.isPaymentCompleted(\n methodId,\n this.stripeClient,\n );\n\n return !isPaymentCompleted\n ? this.stripeClient.confirmPayment(stripePaymentData)\n : this.stripeClient.retrievePaymentIntent(token || '');\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 private _shouldSaveInstrument(paymentMethodOptions?: StripePIPaymentMethodSavingOptions) {\n const setupFutureUsage = paymentMethodOptions?.setup_future_usage;\n\n return (\n setupFutureUsage === StripeInstrumentSetupFutureUsage.ON_SESSION ||\n setupFutureUsage === StripeInstrumentSetupFutureUsage.OFF_SESSION\n );\n }\n\n private _getTokenizedOptions(\n token: string,\n paymentMethodOptions?: StripePIPaymentMethodOptions,\n ) {\n if (this._shouldSaveInstrument(paymentMethodOptions?.us_bank_account)) {\n return { tokenized_ach: { token } };\n }\n\n return { credit_card_token: { token } };\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeOCSPaymentStrategy from './stripe-ocs-payment-strategy';\n\nconst createStripeOCSPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n\n return new StripeOCSPaymentStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n );\n};\n\nexport default toResolvableModule(createStripeOCSPaymentStrategy, [\n { gateway: 'stripeocs', id: 'optimized_checkout' },\n]);\n","import { merge } from 'lodash';\n\nimport {\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 PaymentMethod,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n isStripePaymentEvent,\n StripeAdditionalActionRequired,\n StripeCheckoutInstance,\n StripeCheckoutSession,\n StripeCheckoutSessionActionResult,\n StripeCheckoutSessionActions,\n StripeCheckoutSessionPaymentStatus,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElementsCreateOptions,\n StripeEventType,\n StripeFormattedPaymentPayload,\n StripeInitializationData,\n StripeIntegrationService,\n StripeJsVersion,\n StripePaymentMethodType,\n StripeSavedPaymentMethod,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeOCSPaymentInitializeOptions, {\n WithStripeOCSPaymentInitializeOptions,\n} from '../stripe-ocs/stripe-ocs-initialize-options';\n\nexport default class StripeCSPaymentStrategy implements PaymentStrategy {\n private stripeClient?: StripeClient;\n private stripeCheckout?: StripeCheckoutInstance;\n private selectedMethodId?: string;\n\n constructor(\n private readonly paymentIntegrationService: PaymentIntegrationService,\n private readonly scriptLoader: StripeScriptLoader,\n private readonly stripeIntegrationService: StripeIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithStripeOCSPaymentInitializeOptions,\n ): Promise {\n const { stripeocs, methodId, gatewayId } = options;\n\n if (!stripeocs?.containerId || !gatewayId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n let paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n\n if (!paymentMethod?.clientToken) {\n await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n\n paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n }\n\n try {\n await this._initStripeCheckoutSession(stripeocs, paymentMethod);\n await this._updateStripeShopperData();\n this._initializePaymentElement(stripeocs, paymentMethod);\n this._initializeAdaptivePricingElement(stripeocs, paymentMethod);\n } catch (error) {\n if (error instanceof Error) {\n stripeocs.onError?.(error);\n }\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.stripeClient) {\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._updateCheckoutSessionData(gatewayId, methodId);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n const { clientToken } = state.getPaymentMethodOrThrow(methodId, gatewayId);\n const paymentPayload = this._getPaymentPayload(methodId, clientToken || '');\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._processAdditionalAction(error, gatewayId, methodId);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n const paymentElement = this.stripeCheckout?.getPaymentElement();\n const currencySelectorElement = this.stripeCheckout?.getCurrencySelectorElement();\n\n paymentElement?.unmount();\n paymentElement?.destroy();\n currencySelectorElement?.unmount();\n currencySelectorElement?.destroy();\n this.stripeCheckout = undefined;\n this.stripeClient = undefined;\n this.selectedMethodId = undefined;\n\n return Promise.resolve();\n }\n\n private async _initStripeCheckoutSession(\n stripe: StripeOCSPaymentInitializeOptions,\n paymentMethod: PaymentMethod,\n ): Promise {\n const { clientToken, initializationData } = paymentMethod;\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.stripeClient = await this._loadStripeJs(initializationData);\n\n const { appearance, fonts } = stripe;\n\n this.stripeCheckout = await this.scriptLoader.getStripeCheckout(this.stripeClient, {\n clientSecret: clientToken,\n elementsOptions: {\n appearance,\n fonts,\n },\n adaptivePricing: {\n allowed: !!initializationData?.adaptivePricingEnabled,\n },\n });\n }\n\n private _initializePaymentElement(\n stripe: StripeOCSPaymentInitializeOptions,\n paymentMethod: PaymentMethod,\n ) {\n const { initializationData, id: methodId, gateway } = paymentMethod;\n\n const { enableLink } = initializationData || {};\n const {\n containerId,\n layout,\n render,\n paymentMethodSelect,\n handleClosePaymentMethod,\n togglePreloader,\n } = stripe;\n\n const stripeElement = this._getStripeElement({\n fields: {\n billingDetails: {\n email: StripeStringConstants.NEVER,\n name: StripeStringConstants.NEVER,\n address: StripeStringConstants.NEVER,\n },\n },\n wallets: {\n applePay: StripeStringConstants.NEVER,\n googlePay: StripeStringConstants.NEVER,\n link: enableLink ? StripeStringConstants.AUTO : StripeStringConstants.NEVER,\n },\n layout,\n });\n\n if (!stripeElement || !gateway) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this.stripeIntegrationService.mountElement(stripeElement, containerId);\n\n stripeElement.on(StripeElementEvent.LOADER_START, () => {\n togglePreloader?.(false);\n });\n\n stripeElement.on(StripeElementEvent.READY, () => {\n render();\n });\n\n stripeElement.on(StripeElementEvent.CHANGE, (event: StripeEventType) => {\n this._onStripeElementChange(event, gateway, methodId, paymentMethodSelect);\n });\n\n handleClosePaymentMethod?.(this._collapseStripeElement.bind(this));\n }\n\n private async _loadStripeJs(\n initializationData: StripeInitializationData,\n ): Promise {\n if (this.stripeClient) {\n return this.stripeClient;\n }\n\n const state = this.paymentIntegrationService.getState();\n\n return this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n StripeJsVersion.CLOVER,\n );\n }\n\n private async _getStripeActionsOrThrow(): Promise {\n if (!this.stripeCheckout) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { actions, error } = await this.stripeCheckout.loadActions();\n\n if (!actions || error) {\n throw new PaymentMethodFailedError(error?.message);\n }\n\n return actions;\n }\n\n private _getStripeElement(options?: StripeElementsCreateOptions): StripeElement | undefined {\n return (\n this.stripeCheckout?.getPaymentElement() ||\n this.stripeCheckout?.createPaymentElement(options)\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 private _collapseStripeElement() {\n const stripeElement = this.stripeCheckout?.getPaymentElement();\n\n stripeElement?.collapse();\n }\n\n private async _updateCheckoutSessionData(gatewayId: string, methodId: string): Promise {\n await this._updateStripeShopperData();\n\n // INFO: to trigger checkout session data update on the BE side we need to make stripe config request\n await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n }\n\n private _getPaymentPayload(\n methodId: string,\n token: string,\n newVaultedStripeInstrument?: StripeSavedPaymentMethod,\n ): Payment {\n const cartId = this.paymentIntegrationService.getState().getCart()?.id || '';\n const tokenizedOptions = this._getTokenizedOptions(token, newVaultedStripeInstrument);\n\n const formattedPayload = {\n cart_id: cartId,\n confirm: false,\n method: this.selectedMethodId,\n vault_payment_instrument: !!newVaultedStripeInstrument,\n ...tokenizedOptions,\n };\n\n return {\n methodId,\n paymentData: {\n formattedPayload,\n },\n };\n }\n\n private async _processAdditionalAction(\n error: unknown,\n gatewayId: string,\n methodId: string,\n ): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n const { data: additionalActionData } = error.body?.additional_action_required || {};\n const { token } = additionalActionData || {};\n const existingStripeSavedPaymentMethods = await this._getStripeSavedPaymentMethodsOrThrow();\n const { session: stripeCheckoutSession, error: stripeError } =\n await this._confirmStripePayment(additionalActionData);\n const newStripeSavedPaymentMethods = await this._getStripeSavedPaymentMethodsOrThrow(\n stripeCheckoutSession,\n );\n const { id: checkoutSessionId, status: checkoutSessionStatus } =\n stripeCheckoutSession || {};\n const newVaultedStripeInstrument = this._getNewVaultedStripeInstrument(\n existingStripeSavedPaymentMethods,\n newStripeSavedPaymentMethods,\n );\n const paymentPayload = this._getPaymentPayload(\n methodId,\n checkoutSessionId || token,\n newVaultedStripeInstrument,\n );\n const { initializationData } = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n const { sendSecondPaymentRequestOnStripeError } = initializationData || {};\n\n if (stripeError || !stripeCheckoutSession) {\n if (sendSecondPaymentRequestOnStripeError) {\n // INFO: even in case when stripe payment confirmation was declined\n // we need to send submitPayment request to update status of checkout session on BE side.\n try {\n const paymentPayloadWithError = merge({}, paymentPayload, {\n paymentData: {\n formattedPayload: {\n client_side_error: true,\n },\n },\n });\n\n await this.paymentIntegrationService.submitPayment(paymentPayloadWithError);\n } catch {\n // INFO: additional action should be ignored for this update status request.\n // will throw Stripe error message to the shopper.\n }\n }\n\n throw new PaymentMethodFailedError(stripeError?.message);\n }\n\n try {\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n if (checkoutSessionStatus?.paymentStatus === StripeCheckoutSessionPaymentStatus.Paid) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n }\n\n throw error;\n }\n }\n\n private async _confirmStripePayment(\n additionalActionData: StripeAdditionalActionRequired['data'],\n ): Promise {\n const { redirect_url } = additionalActionData || {};\n\n if (!this.stripeCheckout) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const stripeActions = await this._getStripeActionsOrThrow();\n\n return stripeActions.confirm({\n redirect: StripeStringConstants.IF_REQUIRED,\n returnUrl: redirect_url,\n });\n }\n\n private async _updateStripeShopperData(): Promise {\n const stripeActions = await this._getStripeActionsOrThrow();\n\n await this._updateStripeEmail(stripeActions);\n await this._updateStripeShippingAddress(stripeActions);\n await this._updateStripeBillingAddress(stripeActions);\n }\n\n private async _updateStripeEmail(stripeActions: StripeCheckoutSessionActions): Promise {\n const stripeCheckoutSession = await stripeActions.getSession();\n\n if (stripeCheckoutSession.email) {\n return;\n }\n\n const { getBillingAddress } = this.paymentIntegrationService.getState();\n const billingAddress = getBillingAddress();\n\n await stripeActions.updateEmail(billingAddress?.email || '');\n }\n\n private async _updateStripeShippingAddress(\n stripeActions: StripeCheckoutSessionActions,\n ): Promise {\n const shippingAddress = this.paymentIntegrationService.getState().getShippingAddress();\n\n if (!shippingAddress) {\n return;\n }\n\n await stripeActions.updateShippingAddress({\n name: this.stripeIntegrationService.getShopperFullName(shippingAddress),\n address: this.stripeIntegrationService.mapStripeAddress(shippingAddress),\n });\n }\n\n private async _updateStripeBillingAddress(\n stripeActions: StripeCheckoutSessionActions,\n ): Promise {\n const billingAddress = this.paymentIntegrationService.getState().getBillingAddress();\n\n if (!billingAddress) {\n return;\n }\n\n await stripeActions.updateBillingAddress({\n name: this.stripeIntegrationService.getShopperFullName(billingAddress),\n address: this.stripeIntegrationService.mapStripeAddress(billingAddress),\n });\n }\n\n private async _getStripeSavedPaymentMethodsOrThrow(\n stripeCheckoutSession?: StripeCheckoutSession,\n ): Promise {\n if (stripeCheckoutSession?.savedPaymentMethods) {\n return stripeCheckoutSession.savedPaymentMethods;\n }\n\n const stripeActions = await this._getStripeActionsOrThrow();\n const { savedPaymentMethods } = await stripeActions.getSession();\n\n return savedPaymentMethods || [];\n }\n\n private _getNewVaultedStripeInstrument(\n existingStripeSavedPaymentMethods: StripeSavedPaymentMethod[],\n newStripeSavedPaymentMethods: StripeSavedPaymentMethod[],\n ): StripeSavedPaymentMethod | undefined {\n return newStripeSavedPaymentMethods.find(\n (method: StripeSavedPaymentMethod) =>\n !existingStripeSavedPaymentMethods.some(\n (existingMethod: StripeSavedPaymentMethod) => existingMethod.id === method.id,\n ),\n );\n }\n\n private _getTokenizedOptions(\n token: string,\n newVaultedStripeInstrument?: StripeSavedPaymentMethod,\n ) {\n if (newVaultedStripeInstrument?.type === StripePaymentMethodType.ACH) {\n return { tokenized_ach: { token } };\n }\n\n return { credit_card_token: { token } };\n }\n\n private _initializeAdaptivePricingElement(\n stripe: StripeOCSPaymentInitializeOptions,\n paymentMethod: PaymentMethod,\n ): void {\n const { initializationData } = paymentMethod;\n const { currencySelectorContainerId } = stripe;\n\n if (!initializationData?.adaptivePricingEnabled) {\n return;\n }\n\n if (!currencySelectorContainerId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const currencySelectorElement = this._getCurrencySelectorElement();\n\n if (!currencySelectorElement) {\n return;\n }\n\n currencySelectorElement.mount(`#${currencySelectorContainerId}`);\n\n this._initAdaptivePricingEvents(currencySelectorElement);\n }\n\n private _getCurrencySelectorElement(): StripeElement | undefined {\n return (\n this.stripeCheckout?.getCurrencySelectorElement() ||\n this.stripeCheckout?.createCurrencySelectorElement()\n );\n }\n\n private _initAdaptivePricingEvents(currencySelectorElement: StripeElement): void {\n currencySelectorElement.on(StripeElementEvent.CHANGE, async (event: StripeEventType) => {\n if (!event.value || !('currency' in event.value)) {\n return;\n }\n\n const { currency } = this.paymentIntegrationService.getState().getCartOrThrow();\n const currencyCode = currency.code.toLowerCase();\n const stripeCurrencyCode = event.value.currency.toLowerCase();\n\n await this.paymentIntegrationService.updatePaymentProviderCustomer({\n isCustomerCurrencySelected: currencyCode !== stripeCurrencyCode,\n customerCurrency: stripeCurrencyCode,\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';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeCSPaymentStrategy from './stripe-cs-payment-strategy';\n\nconst createStripeCSPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n\n return new StripeCSPaymentStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n );\n};\n\nexport default toResolvableModule(createStripeCSPaymentStrategy, [\n { gateway: 'stripeocs', id: 'checkout_session' },\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';\nimport { isBaseInstrument } from '@bigcommerce/checkout-sdk/utility';\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 findInstrument = instruments?.find(\n (instrument) => isBaseInstrument(instrument) && instrument.bigpayToken === instrumentId,\n );\n const trustedShippingAddress = isBaseInstrument(findInstrument)\n ? findInstrument.trustedShippingAddress\n : {};\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 messageEventListener = async (event: MessageEvent) => {\n if (event.origin.indexOf('cardinalcommerce.com') === -1) {\n return;\n }\n\n if (typeof event.data !== 'string' || !this._isValidJsonWithSessionId(event.data)) {\n return reject(new Error(PAYMENT_CANNOT_CONTINUE));\n }\n\n window.removeEventListener('message', messageEventListener);\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', messageEventListener);\n\n let iframeHidden: HTMLIFrameElement;\n\n try {\n iframeHidden = this._createHiddenIframe(error.body);\n } catch (e) {\n window.removeEventListener('message', messageEventListener);\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 && data.Status) {\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, [\n { gateway: 'worldpayaccess', id: 'credit_card' },\n { id: 'worldpayaccess' },\n]);\n","import {\n isHostedInstrumentLike,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WorldpayAccessRedirectResponse } from './worldpayaccess-payment-options';\n\nexport default class WorldpayAccessOpenBankingPaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute({ payment }: OrderRequestBody): Promise {\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n await this._paymentIntegrationService.submitOrder();\n\n try {\n await this._paymentIntegrationService.submitPayment(\n this._buildOpenBankingSubmitPayment(payment),\n );\n } catch (error) {\n if (this._isWorldpayAccessRedirectResponse(error)) {\n const redirectUrl = error.body.additional_action_required.data.redirect_url;\n\n return new Promise(() => window.location.replace(redirectUrl));\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 _buildOpenBankingSubmitPayment(payment: OrderPaymentRequestBody): Payment {\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = isHostedInstrumentLike(\n payment.paymentData,\n )\n ? payment.paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n return {\n ...payment,\n paymentData: {\n formattedPayload: {\n open_banking: {},\n vault_payment_instrument: shouldSaveInstrument || false,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || false,\n },\n },\n };\n }\n\n private _isWorldpayAccessRedirectResponse(\n response: unknown,\n ): response is WorldpayAccessRedirectResponse {\n if (typeof response !== 'object' || response === null) {\n return false;\n }\n\n const partialResponse = response as Partial;\n\n if (!partialResponse.body) {\n return false;\n }\n\n const partialBody = partialResponse.body as {\n status?: string;\n additional_action_required?: {\n data?: { redirect_url?: string };\n };\n };\n\n return (\n partialBody.status === 'additional_action_required' &&\n !!partialBody.additional_action_required?.data?.redirect_url\n );\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport WorldpayAccessOpenBankingPaymentStrategy from './worldpayaccess-open-banking-payment-strategy';\n\nconst createWorldpayAccessOpenBankingPaymentStrategy: PaymentStrategyFactory<\n WorldpayAccessOpenBankingPaymentStrategy\n> = (paymentIntegrationService) =>\n new WorldpayAccessOpenBankingPaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createWorldpayAccessOpenBankingPaymentStrategy, [\n { id: 'open_banking', gateway: 'worldpayaccess' },\n]);\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 } 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 { 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 { 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 * This error is thrown when at least one cart item changed stock position (e.g. moved to a different warehouse)\n * and the server returns type `cart_stock_positions_changed`.\n */\nexport default class CartStockPositionsChangedError extends StandardError {\n changedItemIds: string[];\n\n constructor(changedItemIds: string[], message?: string) {\n super(\n message ||\n 'At least one item changed stock position. Please review your cart and try again.',\n );\n\n this.name = 'CartStockPositionsChangedError';\n this.type = 'cart_stock_positions_changed';\n this.changedItemIds = changedItemIds;\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 { StandardError } from '../../common/error/errors';\n\nexport default class MissingShippingMethodError extends StandardError {\n constructor(message: string) {\n super(message);\n\n this.name = 'MissingShippingMethodError';\n this.type = 'missing_shipping_method';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport default class InvalidShippingAddressError extends StandardError {\n constructor(message: string) {\n super(message);\n\n this.name = 'InvalidShippingAddressError';\n this.type = 'invalid_shipping_address';\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\nimport { isNil, omitBy } from 'lodash';\n\nimport {\n CartConsistencyError,\n CartStockPositionsChangedError,\n EmptyCartError,\n} from '../cart/errors';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport { MissingShippingMethodError, OrderTaxProviderUnavailableError } from './errors';\nimport InvalidShippingAddressError from './errors/invalid-shipping-address-error';\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 if (error.body.type === 'cart_stock_positions_changed') {\n const changedItemIds =\n (error.body.errors as { changedItemIds?: string[] })?.changedItemIds ?? [];\n\n throw new CartStockPositionsChangedError(changedItemIds);\n }\n\n if (error.body.type === 'missing_shipping_method') {\n throw new MissingShippingMethodError(error.body.detail);\n }\n\n if (error.body.type === 'invalid_shipping_address') {\n throw new InvalidShippingAddressError(error.body.detail);\n }\n\n if (error.body.type === 'empty_cart') {\n throw new EmptyCartError();\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 { 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 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 { 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","// / \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 { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\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';\n\nimport { PaymentMethod } from '.';\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\n observer.next(\n createAction(\n PaymentMethodActionType.LoadPaymentMethodsSucceeded,\n methods,\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","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 { 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","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","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 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 CYBERSOURCEV2_GOOGLE_PAY = 'googlepaycybersourcev2',\n HUMM = 'humm',\n KLARNA = 'klarna',\n KLARNAV2 = 'klarnav2',\n LEGACY = 'legacy',\n MOLLIE = 'mollie',\n MONERIS = 'moneris',\n NO_PAYMENT_DATA_REQUIRED = 'nopaymentdatarequired',\n OFFLINE = 'offline',\n OFFSITE = 'offsite',\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 WORLDPAYACCESS = 'worldpayaccess',\n WORLDPAYACCESS_GOOGLE_PAY = 'googlepayworldpayaccess',\n STRIPE_GOOGLE_PAY = 'googlepaystripe',\n SEZZLE = 'sezzle',\n ZIP = 'zip',\n}\n\nexport default PaymentStrategyType;\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 { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, empty, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport {\n PaymentIntegrationService,\n PaymentStrategy as PaymentStrategyV2,\n} 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 { getDefaultLogger } from '../common/log';\nimport {\n LoadOrderPaymentsAction,\n OrderActionCreator,\n OrderPaymentRequestBody,\n OrderRequestBody,\n} from '../order';\nimport { OrderFinalizationNotRequiredError } from '../order/errors';\nimport { registerIntegrations } from '../payment-integration';\nimport { SpamProtectionAction, SpamProtectionActionCreator } from '../spam-protection';\n\nimport PaymentMethod from './payment-method';\nimport {\n OrderFinalizeOptions,\n PaymentInitializeOptions,\n PaymentRequestOptions,\n} 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 private _paymentIntegrationService: PaymentIntegrationService,\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?: OrderFinalizeOptions,\n ): ThunkAction {\n const { integrations } = options ?? {};\n\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 registerIntegrations(\n this._strategyRegistryV2,\n integrations ?? [],\n this._paymentIntegrationService,\n );\n\n let strategy: PaymentStrategy | PaymentStrategyV2;\n\n try {\n strategy = this._getStrategy(method);\n } catch {\n throw new OrderFinalizationNotRequiredError();\n }\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, integrations } = 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 registerIntegrations(\n this._strategyRegistryV2,\n integrations ?? [],\n this._paymentIntegrationService,\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 try {\n strategy = this._strategyRegistryV2.get({\n id: method.id,\n gateway: method.gateway,\n type: method.type,\n });\n } catch (error) {\n getDefaultLogger().error(\n `[PaymentStrategyActionCreator] Unable to resolve V2 strategy for id: ${method.id}, gateway: ${method.gateway}, type: ${method.type}`,\n );\n throw error;\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 { 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 { 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","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 { 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 { 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 { 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 { 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 _checkoutId?: string,\n private _cardInstrument?: CardInstrument,\n ) {\n this._iframe = document.createElement('iframe');\n\n const src = this._checkoutId\n ? `/checkout/payment/hosted-field?version=${LIBRARY_VERSION}&checkoutId=${this._checkoutId}`\n : `/checkout/payment/hosted-field?version=${LIBRARY_VERSION}`;\n\n this._iframe.src = src;\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 { 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 { 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 let paymentMethod = state.paymentMethods.getPaymentMethod(\n payload.methodId,\n payload.gatewayId,\n );\n\n if (paymentMethod?.gateway === 'worldpayaccess' && paymentMethod?.id === 'credit_card') {\n paymentMethod = { ...paymentMethod, id: 'worldpayaccess', method: 'credit-card' };\n }\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, checkoutId?: string): 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 checkoutId,\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 { 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","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","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","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 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 [],\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","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 PAYPALEXPRESS = \"paypalexpress\"\n}\nexport default CheckoutButtonMethodType;\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","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 }, {});\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 // Worldpay Access: sub-methods carry the provider name in `gateway` and the method\n // name in `id`. BigPay's mapToId uses `id` as the gateway field unless\n // `method === 'multi-option'`, so we align with hosted-form-order-data-transformer\n if (paymentMethod.gateway === 'worldpayaccess') {\n if (paymentMethod.id === 'credit_card') {\n return { ...paymentMethod, id: 'worldpayaccess', method: 'credit-card' };\n }\n\n if (paymentMethod.id === 'open_banking') {\n return { ...paymentMethod, id: 'worldpayaccess', method: 'open_banking' };\n }\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","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","export const ACKNOWLEDGE = 'ACKNOWLEDGE';\nexport const FINALIZE = 'FINALIZE';\nexport const INITIALIZE = 'INITIALIZE';\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 { 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 { 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 { 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 { 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 { 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 { 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","export enum SubStrategyType {\n CARD = 'card_ui',\n NONE = 'none',\n UNSUPPORTED = 'unsupported',\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, checkout } = this._store.getState();\n const { paymentSettings: { bigpayBaseUrl: host = '' } = {} } =\n config.getStoreConfig() || {};\n const checkoutId = checkout.getCheckoutOrThrow().id;\n\n if (!formOptions) {\n throw new InvalidArgumentError();\n }\n\n const form = formOptions && this._hostedFormFactory.create(host, formOptions, checkoutId);\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 { 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 { 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 { 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 { 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 { 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 { 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 { 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 { 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 const consignmentInMemory = store\n .getState()\n .consignments.getConsignmentById(consignment.id);\n\n const alreadySelectedOptionId = consignmentInMemory?.selectedShippingOption?.id;\n\n if (alreadySelectedOptionId === consignment.shippingOptionId) {\n observer.complete();\n\n return;\n }\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 { EmptyCartError } from '../cart/errors';\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.physicalItems.stockPosition',\n 'cart.lineItems.digitalItems.options',\n 'cart.lineItems.digitalItems.stockPosition',\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\n .post(url, {\n body: consignments,\n params: {\n include: joinOrMergeIncludes(DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .put(url, {\n body,\n params: {\n include: joinOrMergeIncludes(DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .delete(url, { params: { include }, headers, timeout })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\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 { 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, 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 { 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 { 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 { id } = checkout;\n const checkoutVersion = options?.version ?? checkout.version;\n\n const { body } = await (useStoreCredit\n ? this._storeCreditRequestSender.applyStoreCredit(id, {\n ...options,\n version: checkoutVersion,\n })\n : this._storeCreditRequestSender.removeStoreCredit(id, {\n ...options,\n version: checkoutVersion,\n }));\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, version }: 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 body: { version },\n });\n }\n\n removeStoreCredit(\n checkoutId: string,\n { timeout, version }: 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 body: { version },\n });\n }\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, getLocale: getCartLocale },\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 getCartLocale: clone(getCartLocale),\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 { 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 {\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 CouponActionCreator from '../coupon/coupon-action-creator';\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 _couponActionCreator: CouponActionCreator,\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 const checkoutId = this._storeProjection.getState().getCheckoutOrThrow().id;\n\n return this._hostedFormFactory.create(host, options, checkoutId);\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 applyCoupon(\n coupon: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(this._couponActionCreator.applyCoupon(coupon, options));\n\n return this._storeProjection.getState();\n }\n\n async removeCoupon(\n coupon: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(this._couponActionCreator.removeCoupon(coupon, options));\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, RequestSender } 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 CouponActionCreator from '../coupon/coupon-action-creator';\nimport CouponRequestSender from '../coupon/coupon-request-sender';\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 requestSender?: RequestSender,\n): PaymentIntegrationService {\n const {\n config: { getHost, getLocale },\n } = store.getState();\n\n if (!requestSender) {\n requestSender = createRequestSender({ host: getHost() });\n }\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 applyCouponActionCreator = new CouponActionCreator(\n new CouponRequestSender(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 applyCouponActionCreator,\n spamProtectionActionCreator,\n paymentProviderCustomerActionCreator,\n shippingCountryActionCreator,\n remoteCheckoutActionCreator,\n paymentStrategyWidgetActionCreator,\n );\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 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","export default function isFuture(date: Date): boolean {\n return date.valueOf() > Date.now();\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 { 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 { 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 {\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 { 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","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 { 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","import { isEqual, omit } from 'lodash';\n\nimport {\n BraintreeFastlaneAddress,\n BraintreeFastlaneAuthenticationState,\n BraintreeFastlaneProfileData,\n BraintreeFastlaneStylesOption,\n BraintreeFastlaneVaultedInstrument,\n BraintreeInitializationData,\n BraintreeIntegrationService,\n getFastlaneStyles,\n isBraintreeAcceleratedCheckoutCustomer,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { CookieStorage } 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 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 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\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, fastlane } = options || {};\n const fastlaneOptions = fastlane || braintreefastlane;\n const { onPayPalFastlaneAddressChange } = fastlaneOptions || {};\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 fastlaneOptions?.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 = CookieStorage.get('bc-fastlane-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 CookieStorage.remove('bc-fastlane-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?.authenticationState !==\n 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 PayPalFastlaneAuthenticationState,\n PayPalFastlaneStylesOption,\n PayPalFastlaneUtils,\n PayPalInitializationData,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-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 _paypalSdkScriptLoader: PayPalSdkScriptLoader,\n private _paypalCommerceFastlaneUtils: PayPalFastlaneUtils,\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, fastlane } = options || {};\n const fastlaneOptions = fastlane || paypalcommercefastlane;\n const { onPayPalFastlaneAddressChange, styles } = fastlaneOptions || {};\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._paypalSdkScriptLoader.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n cart.locale,\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 if (isAuthenticationFlowCanceled) {\n this._paypalCommerceFastlaneUtils.removeStorageSessionId();\n } else {\n this._paypalCommerceFastlaneUtils.updateStorageSessionId(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 {\n PaymentProviderCustomer,\n PayPalConnectCustomer,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isPaypalAcceleratedCheckoutCustomer(\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 { 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 {\n STRIPE_UPE_CLIENT_API_VERSION,\n STRIPE_UPE_CLIENT_BETAS,\n StripeAppearanceOptions,\n StripeClient,\n StripeDisplayName,\n StripeElementEvent,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeEventType,\n StripeFormMode,\n StripeJsVersion,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\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 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?: StripeClient;\n private _stripeElements?: StripeElements;\n private sendData?: ReturnType;\n\n constructor(\n private _store: CheckoutStore,\n private _stripeScriptLoader: 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 { initializationData } = 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._stripeScriptLoader.getStripeClient(\n initializationData,\n state.cart.getLocale(),\n StripeJsVersion.V3,\n STRIPE_UPE_CLIENT_BETAS,\n STRIPE_UPE_CLIENT_API_VERSION,\n );\n\n let appearance: StripeAppearanceOptions;\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 = await this._stripeScriptLoader.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: StripeDisplayName.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(StripeElementEvent.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 { 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 { B2BTokenActionCreator } from '../b2b-token';\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 ExtensionMessage,\n ExtensionMessenger,\n ExtensionQueryMap,\n ExtensionRegion,\n WorkerExtensionMessenger,\n} from '../extension';\nimport { FormFieldsActionCreator } from '../form';\nimport { CountryActionCreator } from '../geography';\nimport { OrderActionCreator, OrderRequestBody } from '../order';\nimport {\n OrderFinalizeOptions,\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 CheckoutInitialState from './checkout-initial-state';\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 _b2bTokenActionCreator: B2BTokenActionCreator,\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 private _workerExtensionMessenger: WorkerExtensionMessenger,\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 * Hydrates the checkout service with an initial state.\n *\n * The initial state can contain various checkout data such as cart items,\n * customer information, and other relevant state.\n *\n * ```js\n * const initialState = {\n * // ... initial checkout state data\n * };\n *\n * const state = await service.hydrateInitialState(initialState);\n *\n * console.log(state.data.getCheckout());\n * ```\n *\n * @alpha\n * @param state - The initial state data to hydrate the checkout service with.\n * @returns A promise that resolves to the current state after hydration.\n */\n hydrateInitialState(state: CheckoutInitialState): Promise {\n return this._dispatch(this._checkoutActionCreator.hydrateInitialState(state));\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?: OrderFinalizeOptions): 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 * Retrieves a B2B authentication token for the current customer.\n *\n * The token can be used to authenticate requests to B2B REST and GraphQL\n * endpoints. The customer must be signed in for this method to succeed.\n * The B2B base URL and client ID are read from the checkout settings config.\n *\n * ```js\n * const state = await service.getB2BToken();\n *\n * console.log(state.data.getB2BToken());\n * ```\n *\n * @param options - Options for the request.\n * @returns A promise that resolves to the current state.\n */\n getB2BToken(options?: RequestOptions): Promise {\n const action = this._b2bTokenActionCreator.loadB2BToken(options);\n\n return this._dispatch(action, { queueId: 'b2bToken' });\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(\n container,\n region,\n this._workerExtensionMessenger,\n );\n const state = await this._dispatch(action, { queueId: 'extensions' });\n\n this._extensionEventBroadcaster.listen();\n\n return state;\n }\n\n /**\n * Clear cache for a checkout extension when removing it from UI.\n * This function should be used whenver an extension is removed from the UI.\n *\n * @alpha\n * @param region - The name of an area where the extension should be presented.\n */\n clearExtensionCache(region: ExtensionRegion): void {\n this._extensionMessenger.clearCacheByRegion(region);\n }\n\n /**\n * Posts a message to a checkout extension.\n *\n * @alpha\n * @param extensionId - The ID of an extension to post the event to.\n * @param message - The message to post to an extension.\n */\n postMessageToExtension(extensionId: string, message: ExtensionMessage): void {\n this._extensionMessenger.post(extensionId, message);\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]) => Promise | void,\n ): () => void {\n return this._extensionMessenger.listenForCommand(extensionId, command, handler);\n }\n\n /**\n * Manages the query handler for an extension.\n *\n * @alpha\n * @param extensionId - The ID of the extension sending the query.\n * @param query - The query to be handled.\n * @param handler - The handler function for the extension query.\n * @returns A function that, when called, will deregister the query handler.\n */\n handleExtensionQuery(\n extensionId: string,\n query: T,\n handler: (command: ExtensionQueryMap[T]) => Promise | void,\n ): () => void {\n return this._extensionMessenger.listenForQuery(extensionId, query, 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","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","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 * 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","export interface B2BToken {\n token: string;\n}\n\nexport default interface B2BTokenState {\n data?: B2BToken;\n errors: B2BTokenErrorsState;\n statuses: B2BTokenStatusesState;\n}\n\nexport interface B2BTokenErrorsState {\n loadError?: Error;\n}\n\nexport interface B2BTokenStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: B2BTokenState = {\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';\n\nimport { B2BTokenActionType, LoadB2BTokenAction } from './b2b-token-actions';\nimport B2BTokenState, {\n B2BToken,\n B2BTokenErrorsState,\n B2BTokenStatusesState,\n DEFAULT_STATE,\n} from './b2b-token-state';\n\nexport default function b2bTokenReducer(\n state: B2BTokenState = DEFAULT_STATE,\n action: Action,\n): B2BTokenState {\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: B2BToken | undefined, action: LoadB2BTokenAction): B2BToken | undefined {\n switch (action.type) {\n case B2BTokenActionType.LoadB2BTokenSucceeded:\n return action.payload;\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: B2BTokenErrorsState = DEFAULT_STATE.errors,\n action: LoadB2BTokenAction,\n): B2BTokenErrorsState {\n switch (action.type) {\n case B2BTokenActionType.LoadB2BTokenRequested:\n case B2BTokenActionType.LoadB2BTokenSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case B2BTokenActionType.LoadB2BTokenFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: B2BTokenStatusesState = DEFAULT_STATE.statuses,\n action: LoadB2BTokenAction,\n): B2BTokenStatusesState {\n switch (action.type) {\n case B2BTokenActionType.LoadB2BTokenRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case B2BTokenActionType.LoadB2BTokenFailed:\n case B2BTokenActionType.LoadB2BTokenSucceeded:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\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 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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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 | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return replace(data, action.payload?.checkout?.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, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { BillingAddressAction, BillingAddressActionType } from '../billing';\nimport {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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 | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return objectMerge(data, action.payload?.checkout?.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 { 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 { 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 { CheckoutHydrateAction, CheckoutHydrateActionType } from '../checkout';\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(\n data: Config | undefined,\n action: LoadConfigAction | CheckoutHydrateAction,\n): Config | undefined {\n switch (action.type) {\n case ConfigActionType.LoadConfigSucceeded:\n return objectMerge(data, action.payload);\n\n case CheckoutHydrateActionType.HydrateInitialState: {\n const merged = objectMerge(data, action.payload?.config);\n\n // b2bApiSettings is a top-level field in CheckoutInitialState (separate from config),\n // so it must be merged into storeConfig manually after the config hydration.\n // Skip if config data is absent or this is a non-B2B store (no b2bApiSettings).\n if (!merged || !action.payload?.b2bApiSettings) {\n return merged;\n }\n\n return {\n ...merged,\n storeConfig: {\n ...merged.storeConfig,\n b2bApiSettings: action.payload.b2bApiSettings,\n },\n };\n }\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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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 | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return arrayReplace(data, action.payload?.checkout?.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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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:\n | CheckoutAction\n | GiftCertificateAction\n | ConsignmentAction\n | CouponAction\n | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return arrayReplace(data, action.payload?.checkout?.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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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 | CheckoutHydrateAction;\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 case CheckoutHydrateActionType.HydrateInitialState:\n return objectMerge(data, action.payload?.checkout?.customer);\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 {\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} from '../checkout/checkout-hydrate-actions';\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 | CheckoutHydrateAction,\n): Extension[] | undefined {\n if (action.type === ExtensionActionType.LoadExtensionsSucceeded) {\n return arrayReplace(data, action.payload);\n }\n\n if (action.type === CheckoutHydrateActionType.HydrateInitialState) {\n return arrayReplace(data, action.payload?.extensions);\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 { ExtraFields } from './extra-field';\nimport { FormFields } from './form-field';\n\nexport default interface FormFieldsState {\n data?: FormFields;\n extraFields?: ExtraFields;\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 { CheckoutHydrateAction, CheckoutHydrateActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { ExtraFields } from './extra-field';\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 extraFields: extraFieldsReducer,\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 | CheckoutHydrateAction,\n): FormFields | undefined {\n switch (action.type) {\n case FormFieldsActionType.LoadFormFieldsSucceeded:\n return objectMerge(data, action.payload);\n\n case CheckoutHydrateActionType.HydrateInitialState:\n return objectMerge(data, action.payload?.formFields);\n\n default:\n return data;\n }\n}\n\nfunction extraFieldsReducer(\n extraFields: ExtraFields | undefined,\n action: CheckoutHydrateAction,\n): ExtraFields | undefined {\n switch (action.type) {\n case CheckoutHydrateActionType.HydrateInitialState:\n return action.payload?.extraFields ?? extraFields;\n\n default:\n return extraFields;\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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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:\n | ConsignmentAction\n | CheckoutAction\n | CouponAction\n | CustomerAction\n | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return arrayReplace(data, action.payload?.checkout?.consignments);\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 { CheckoutHydrateAction, CheckoutHydrateActionType } from './checkout-hydrate-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 | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return objectMerge(\n data,\n omit(action.payload?.checkout, [\n 'billingAddress',\n 'cart',\n 'consignments',\n 'customer',\n 'coupons',\n 'giftCertificates',\n ]),\n ) as CheckoutDataState;\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\ntype FunctionProperties = {\n [K in keyof T]: T[K] extends (...args: unknown[]) => unknown ? T[K] : never;\n};\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<{ [key: string]: T }>((result, key) => {\n result[key] = createFreezeProxy(map[key]);\n\n return result;\n }, {}) 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 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 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 'worldpayaccess.credit_card': {\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 bigcommerce_payments_creditcards: {\n provider: 'bigcommerce_payments',\n method: 'credit_card',\n },\n bigcommerce_payments: {\n provider: 'bigcommerce_payments',\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 { createB2BTokenSelectorFactory } from '../b2b-token';\nimport { 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 createB2BTokenSelector = createB2BTokenSelectorFactory();\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 b2bToken = createB2BTokenSelector(state.b2bToken);\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 b2bToken,\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 { createSelector } from '../common/selector';\n\nimport B2BTokenState, { DEFAULT_STATE } from './b2b-token-state';\n\nexport default interface B2BTokenSelector {\n getToken(): string | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type B2BTokenSelectorFactory = (state: B2BTokenState) => B2BTokenSelector;\n\nexport function createB2BTokenSelectorFactory(): B2BTokenSelectorFactory {\n const getToken = createSelector(\n (state: B2BTokenState) => state.data?.token,\n (token) => () => token,\n );\n\n const getLoadError = createSelector(\n (state: B2BTokenState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: B2BTokenState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: B2BTokenState = DEFAULT_STATE): B2BTokenSelector => {\n return {\n getToken: getToken(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';\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 { 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 getLocale(): string | undefined;\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 const getLocale = createSelector(\n (state: CartState) => state.data?.locale,\n (data) => () => data,\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 getLocale: getLocale(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 { 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 = { customerAccount: [], shippingAddress: [], billingAddress: [] }) =>\n () =>\n data\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 { 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 { 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';\nimport mapExtraFieldToFormField from './map-extra-field-to-form-field';\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 getAddressExtraFields(): 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 getAddressExtraFields = createSelector(\n (state: FormFieldsState) => state.extraFields,\n (extraFields) => () => {\n if (!extraFields || !extraFields.address.length) {\n return [];\n }\n\n return extraFields.address.map(mapExtraFieldToFormField);\n },\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 getAddressExtraFields: getAddressExtraFields(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 { 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';\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 [],\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 { 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 { 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 { 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 { 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 initialStoreState: Partial = {},\n options?: CheckoutStoreOptions,\n): CheckoutStore {\n const actionTransformer = createActionTransformer(createRequestErrorFactory());\n const createInternalCheckoutSelectors = createInternalCheckoutSelectorsFactory();\n const stateTransformer = (state: CheckoutStoreState) => createInternalCheckoutSelectors(state);\n const reducer = createCheckoutStoreReducer();\n\n return createDataStore(reducer, initialStoreState, {\n actionTransformer,\n stateTransformer,\n ...options,\n });\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 { 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, combineReducers, Reducer } from '@bigcommerce/data-store';\n\nimport { b2bTokenReducer } from '../b2b-token';\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 b2bToken: b2bTokenReducer,\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, RequestSender } from '@bigcommerce/request-sender';\nimport { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport { B2BTokenActionCreator, B2BTokenRequestSender } from '../b2b-token';\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { createDataStoreProjection } from '../common/data-store';\nimport { ErrorActionCreator, ErrorLogger } from '../common/error';\nimport { ExperimentAwareRequestSender } from '../common/http-request';\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 WorkerExtensionMessenger,\n} from '../extension';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport * as customerStrategyFactories from '../generated/customer-strategies';\nimport * as paymentStrategyFactories 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 experimentRequestSender = new ExperimentAwareRequestSender(requestSender, {\n getBasePath: () => store.getState().config.getStoreConfig()?.links.baseUrl ?? undefined,\n getFeatures: () =>\n store.getState().config.getStoreConfig()?.checkoutSettings?.features ?? {},\n }) as unknown as RequestSender;\n const paymentClient = createPaymentClient(store);\n const orderRequestSender = new OrderRequestSender(experimentRequestSender);\n const checkoutRequestSender = new CheckoutRequestSender(experimentRequestSender);\n const configActionCreator = new ConfigActionCreator(new ConfigRequestSender(requestSender));\n const spamProtection = createSpamProtection(createScriptLoader());\n const spamProtectionRequestSender = new SpamProtectionRequestSender(experimentRequestSender);\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(experimentRequestSender),\n );\n const formFieldsActionCreator = new FormFieldsActionCreator(\n new FormFieldsRequestSender(experimentRequestSender),\n );\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n configActionCreator,\n formFieldsActionCreator,\n );\n const paymentIntegrationService = createPaymentIntegrationService(\n store,\n experimentRequestSender,\n );\n\n // NO_PAYMENT_DATA_REQUIRED must always be available regardless of build mode — it handles\n // free orders / full store credit checkouts and cannot be lazily loaded via integrations.\n const essentialPaymentStrategyFactories = {\n createNoPaymentStrategy: paymentStrategyFactories.createNoPaymentStrategy,\n };\n const registryV2 = createPaymentStrategyRegistryV2(\n paymentIntegrationService,\n process.env.ESSENTIAL_BUILD ? essentialPaymentStrategyFactories : paymentStrategyFactories,\n { useFallback: true },\n );\n const customerRegistryV2 = createCustomerStrategyRegistryV2(\n paymentIntegrationService,\n process.env.ESSENTIAL_BUILD ? {} : customerStrategyFactories,\n );\n const extensionActionCreator = new ExtensionActionCreator(\n new ExtensionRequestSender(experimentRequestSender),\n );\n const workerExtensionMessenger = new WorkerExtensionMessenger();\n const extensionMessenger = new ExtensionMessenger(store, workerExtensionMessenger);\n const storeProjection = createDataStoreProjection(store, createCheckoutSelectorsFactory());\n\n return new CheckoutService(\n store,\n storeProjection,\n extensionMessenger,\n createExtensionEventBroadcaster(storeProjection, extensionMessenger),\n new B2BTokenActionCreator(new B2BTokenRequestSender(requestSender)),\n new BillingAddressActionCreator(\n new BillingAddressRequestSender(experimentRequestSender),\n subscriptionsActionCreator,\n ),\n checkoutActionCreator,\n configActionCreator,\n new CustomerActionCreator(\n new CustomerRequestSender(experimentRequestSender),\n checkoutActionCreator,\n spamProtectionActionCreator,\n ),\n new ConsignmentActionCreator(\n new ConsignmentRequestSender(experimentRequestSender),\n checkoutRequestSender,\n ),\n new CountryActionCreator(new CountryRequestSender(experimentRequestSender, { locale })),\n new CouponActionCreator(new CouponRequestSender(experimentRequestSender)),\n new CustomerStrategyActionCreator(\n createCustomerStrategyRegistry(store, experimentRequestSender),\n customerRegistryV2,\n paymentIntegrationService,\n ),\n new ErrorActionCreator(),\n new GiftCertificateActionCreator(new GiftCertificateRequestSender(experimentRequestSender)),\n new InstrumentActionCreator(\n new InstrumentRequestSender(paymentClient, experimentRequestSender),\n ),\n orderActionCreator,\n new PaymentMethodActionCreator(new PaymentMethodRequestSender(experimentRequestSender)),\n new PaymentStrategyActionCreator(\n createPaymentStrategyRegistry(store, paymentClient, experimentRequestSender),\n registryV2,\n orderActionCreator,\n spamProtectionActionCreator,\n paymentIntegrationService,\n ),\n new PickupOptionActionCreator(new PickupOptionRequestSender(experimentRequestSender)),\n new ShippingCountryActionCreator(\n new ShippingCountryRequestSender(experimentRequestSender, { locale }),\n store,\n ),\n new ShippingStrategyActionCreator(\n createShippingStrategyRegistry(store, experimentRequestSender),\n ),\n new SignInEmailActionCreator(new SignInEmailRequestSender(experimentRequestSender)),\n spamProtectionActionCreator,\n new StoreCreditActionCreator(new StoreCreditRequestSender(experimentRequestSender)),\n subscriptionsActionCreator,\n formFieldsActionCreator,\n extensionActionCreator,\n workerExtensionMessenger,\n );\n}\n\nexport interface CheckoutServiceOptions {\n locale?: string;\n host?: string;\n shouldWarnMutation?: boolean;\n externalSource?: string;\n errorLogger?: ErrorLogger;\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';\n\nexport interface PaymentStrategyFactories {\n [key: string]: PaymentStrategyFactory;\n}\n\nexport default function createPaymentStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n paymentStrategyFactories: PaymentStrategyFactories,\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 {\n CustomerStrategy,\n CustomerStrategyFactory,\n CustomerStrategyResolveId,\n isResolvableModule,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\n\nexport interface CustomerStrategyFactories {\n [key: string]: CustomerStrategyFactory;\n}\n\nexport default function createCustomerStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n customerStrategyFactories: CustomerStrategyFactories,\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 {\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 { 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 B2B authentication token for the current customer.\n *\n * @returns The B2B token string if it has been loaded, otherwise undefined.\n */\n getB2BToken(): string | 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 address extra fields.\n *\n * @returns The list of extra fields if available, otherwise an empty array.\n */\n getAddressExtraFields(): 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 getB2BToken = createSelector(\n ({ b2bToken }: InternalCheckoutSelectors) => b2bToken.getToken,\n (getToken) => clone(getToken),\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 getAddressExtraFields = createSelector(\n ({ form }: InternalCheckoutSelectors) => form.getAddressExtraFields,\n (getAddressExtraFields) => clone(getAddressExtraFields),\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 getB2BToken: getB2BToken(state),\n getInstruments: getInstruments(state),\n getCustomerAccountFields: getCustomerAccountFields(state),\n getBillingAddressFields: getBillingAddressFields(state),\n getShippingAddressFields: getShippingAddressFields(state),\n getAddressExtraFields: getAddressExtraFields(state),\n getPickupOptions: getPickupOptions(state),\n getUserExperienceSettings: getUserExperienceSettings(state),\n getPaymentProviderCustomer: getPaymentProviderCustomer(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport {\n CartChangedError,\n CartConsistencyError,\n CartStockPositionsChangedError,\n} 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():\n | Error\n | CartChangedError\n | CartConsistencyError\n | CartStockPositionsChangedError\n | 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 load the B2B token.\n *\n * @returns The error object if unable to load the B2B token, otherwise undefined.\n */\n getLoadB2BTokenError(): 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 getLoadB2BTokenError: state.b2bToken.getLoadError,\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 a B2B token is being loaded.\n *\n * @returns True if a B2B token is being loaded, otherwise false.\n */\n isLoadingB2BToken(): 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 isLoadingB2BToken: state.b2bToken.isLoading,\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 { 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 { 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 {\n createSpamProtection,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\n\nimport CustomerActionCreator from './customer-action-creator';\nimport CustomerRequestSender from './customer-request-sender';\nimport { CustomerStrategy } from './strategies';\nimport { DefaultCustomerStrategy } from './strategies/default';\n\nexport default function createCustomerStrategyRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\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 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 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 } from '@bigcommerce/script-loader';\n\nimport { CheckoutRequestSender, CheckoutStore, CheckoutValidator } from '../checkout';\nimport { BrowserStorage } from '../common/storage';\nimport { HostedFormFactory } from '../hosted-form';\nimport { OrderActionCreator, OrderRequestSender } from '../order';\nimport { createSpamProtection, PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport PaymentActionCreator from './payment-action-creator';\nimport PaymentRequestSender from './payment-request-sender';\nimport PaymentRequestTransformer from './payment-request-transformer';\nimport PaymentStrategyRegistry from './payment-strategy-registry';\nimport PaymentStrategyType from './payment-strategy-type';\nimport { ConvergePaymentStrategy } from './strategies/converge';\nimport {\n createStepHandler,\n createSubStrategyRegistry,\n PaymentResumer,\n PPSDKStrategy,\n} from './strategies/ppsdk';\n\nexport default function createPaymentStrategyRegistry(\n store: CheckoutStore,\n paymentClient: any,\n requestSender: RequestSender,\n) {\n const registry = new PaymentStrategyRegistry({\n defaultToken: PaymentStrategyType.CREDIT_CARD,\n });\n\n const paymentRequestTransformer = new PaymentRequestTransformer();\n const paymentRequestSender = new PaymentRequestSender(paymentClient);\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const checkoutValidator = new CheckoutValidator(checkoutRequestSender);\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 formPoster = createFormPoster();\n const stepHandler = createStepHandler(formPoster, paymentHumanVerificationHandler);\n const hostedFormFactory = new HostedFormFactory(store);\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.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 return registry;\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';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { createAmazonPayV2PaymentProcessor } from '@bigcommerce/checkout-sdk/amazon-pay-utils';\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n createPayPalFastlaneUtils,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { createPaymentIntegrationService } from '../payment-integration';\nimport { PaymentProviderCustomerActionCreator } from '../payment-provider-customer';\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 paymentIntegrationService = createPaymentIntegrationService(store);\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 const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\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(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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 createPayPalSdkScriptLoader(),\n createPayPalFastlaneUtils(),\n ),\n );\n\n registry.register(\n 'default',\n () => new DefaultShippingStrategy(store, consignmentActionCreator),\n );\n\n return registry;\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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory 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 getButtonStyle = (buttonStyle?: ButtonStyleOption): string => {\n switch (buttonStyle) {\n case ButtonStyleOption.White:\n return 'white';\n\n case ButtonStyleOption.WhiteBorder:\n return 'white-outline';\n\n case ButtonStyleOption.Black:\n default:\n return 'black';\n }\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 private _applePayScriptLoader: ApplePayScriptLoader,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithApplePayButtonInitializeOptions,\n ): Promise {\n const { methodId, containerId, applepay } = options;\n\n if (!methodId || !applepay) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n await this._applePayScriptLoader.loadSdk();\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 (\n this._paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE &&\n this._paymentMethod.clientToken\n ) {\n this._braintreeSdk.initialize(this._paymentMethod.clientToken);\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 applePayButton = this._createApplePayButtonElement(styleOption);\n\n container.appendChild(applePayButton);\n\n return applePayButton;\n }\n\n private _createApplePayButtonElement(styleOption?: ButtonStyleOption): HTMLElement {\n const applePayButton = document.createElement('apple-pay-button');\n\n applePayButton.setAttribute('buttonstyle', getButtonStyle(styleOption));\n applePayButton.setAttribute('type', 'plain');\n applePayButton.setAttribute(\n 'style',\n '--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;',\n );\n\n return applePayButton;\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\n const state = this._paymentIntegrationService.getState();\n const { shouldExecuteSpamCheck } = state.getCheckoutOrThrow();\n\n if (shouldExecuteSpamCheck) {\n await this._paymentIntegrationService.verifyCheckoutSpamProtection();\n }\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","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\n} 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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayButtonStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n\n return new ApplePayButtonStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), window, braintreeSDKVersionManager),\n ),\n new ApplePayScriptLoader(new ScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createApplePayButtonStrategy, [{ id: 'applepay' }]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n PayPalBuyNowInitializeOptions,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsButtonInitializeOptions, {\n WithBigCommercePaymentsButtonInitializeOptions,\n} from './bigcommerce-payments-button-initialize-options';\n\nexport default class BigCommercePaymentsButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithBigCommercePaymentsButtonInitializeOptions,\n ): Promise {\n const { bigcommerce_payments, containerId, methodId } = options;\n\n const isBuyNowFlow = Boolean(bigcommerce_payments?.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 (!bigcommerce_payments) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !bigcommerce_payments.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof bigcommerce_payments.buyNowInitializeOptions?.getBuyNowCartRequestBody !==\n 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments.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 ? bigcommerce_payments.currencyCode\n : this.paymentIntegrationService.getState().getCartOrThrow().currency.code;\n\n await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(\n methodId,\n currencyCode,\n false,\n );\n\n this.renderButton(containerId, methodId, bigcommerce_payments, isBuyNowFlow);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n bigcommerce_payments: BigCommercePaymentsButtonInitializeOptions,\n isBuyNowFlow?: boolean,\n ): void {\n const { buyNowInitializeOptions, style, onComplete, onEligibilityFailure } =\n bigcommerce_payments;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, isAppSwitchEnabled } =\n paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n ...(!isBuyNowFlow &&\n this.isPaypalCommerceAppSwitchEnabled(methodId) && {\n appSwitchWhenAvailable: true,\n }),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder('bigcommerce_payments'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const hostedCheckoutCallbacks = {\n ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n }),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const buttonRenderOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n if (paypalButton.hasReturned?.() && this.isPaypalCommerceAppSwitchEnabled(methodId)) {\n paypalButton.resume?.();\n } else {\n paypalButton.render(`#${containerId}`);\n }\n } else if (onEligibilityFailure && typeof onEligibilityFailure === 'function') {\n onEligibilityFailure();\n } else {\n this.bigCommercePaymentsIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart =\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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 =\n this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n } catch (error) {\n if (typeof error === 'string') {\n throw new Error(error);\n }\n\n throw error;\n }\n }\n\n /**\n *\n * PayPal AppSwitch enabling handling\n *\n */\n private isPaypalCommerceAppSwitchEnabled(methodId: string): boolean {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n return paymentMethod.initializationData?.isAppSwitchEnabled ?? false;\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsButtonStrategy from './bigcommerce-payments-button-strategy';\n\nconst createBigCommercePaymentsButtonStrategy: CheckoutButtonStrategyFactory<\n BigCommercePaymentsButtonStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsButtonStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsButtonStrategy, [\n { id: 'bigcommerce_payments' },\n]);\n","import { BigCommercePaymentsInitializationData } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n PayPalBuyNowInitializeOptions,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsPayLaterButtonInitializeOptions, {\n WithBigCommercePaymentsPayLaterButtonInitializeOptions,\n} from './bigcommerce-payments-paylater-button-initialize-options';\n\nexport default class BigCommercePaymentsPayLaterButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions &\n WithBigCommercePaymentsPayLaterButtonInitializeOptions,\n ): Promise {\n const { bigcommerce_payments_paylater, containerId, methodId } = options;\n const { buyNowInitializeOptions, currencyCode: providedCurrencyCode } =\n bigcommerce_payments_paylater || {};\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 (!bigcommerce_payments_paylater) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_paylater\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_paylater.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.bigcommerce_payments_paylater.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.bigCommercePaymentsIntegrationService.loadPayPalSdk(\n methodId,\n currencyCode,\n false,\n );\n\n this.renderButton(containerId, methodId, bigcommerce_payments_paylater);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n bigcommerce_payments_paylater: BigCommercePaymentsPayLaterButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style, onComplete, onEligibilityFailure } =\n bigcommerce_payments_paylater;\n\n const bigCommercePaymentsSdk =\n this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_paylater',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.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 = [\n bigCommercePaymentsSdk.FUNDING.PAYLATER,\n bigCommercePaymentsSdk.FUNDING.CREDIT,\n ];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (!hasRenderedSmartButton) {\n const buttonRenderOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = bigCommercePaymentsSdk.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.bigCommercePaymentsIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart =\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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 =\n this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsPayLaterButtonStrategy from './bigcommerce-payments-paylater-button-strategy';\n\nconst createBigCommercePaymentsPayLaterButtonStrategy: CheckoutButtonStrategyFactory<\n BigCommercePaymentsPayLaterButtonStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsPayLaterButtonStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsPayLaterButtonStrategy, [\n { id: 'bigcommerce_payments_paylater' },\n]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n StyleButtonColor,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsVenmoButtonInitializeOptions, {\n WithBigCommercePaymentsVenmoButtonInitializeOptions,\n} from './bigcommerce-payments-venmo-button-initialize-options';\n\nexport default class BigCommercePaymentsVenmoButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions &\n WithBigCommercePaymentsVenmoButtonInitializeOptions,\n ): Promise {\n const { bigcommerce_payments_venmo, containerId, methodId } = options;\n const { buyNowInitializeOptions, currencyCode: providedCurrencyCode } =\n bigcommerce_payments_venmo || {};\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 (!bigcommerce_payments_venmo) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_venmo\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_venmo.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.bigcommerce_payments_venmo.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.bigCommercePaymentsIntegrationService.loadPayPalSdk(\n methodId,\n currencyCode,\n false,\n );\n\n this.renderButton(containerId, methodId, bigcommerce_payments_venmo);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n bigcommerce_payments_venmo: BigCommercePaymentsVenmoButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style, onEligibilityFailure } = bigcommerce_payments_venmo;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const fundingSource = paypalSdk.FUNDING.VENMO;\n\n const defaultCallbacks = {\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_venmo',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const buttonRenderOptions: BigCommercePaymentsButtonsOptions = {\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.bigCommercePaymentsIntegrationService.removeElement(containerId);\n }\n }\n\n private getValidVenmoButtonStyles(style: PayPalButtonStyleOptions | undefined) {\n const validButtonStyle =\n this.bigCommercePaymentsIntegrationService.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 =\n await this.bigCommercePaymentsIntegrationService.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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsVenmoButtonStrategy from './bigcommerce-payments-venmo-button-strategy';\n\nconst createBigCommercePaymentsVenmoButtonStrategy: CheckoutButtonStrategyFactory<\n BigCommercePaymentsVenmoButtonStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsVenmoButtonStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsVenmoButtonStrategy, [\n { id: 'bigcommerce_payments_venmo' },\n]);\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 { isNil, omitBy } from 'lodash';\n\nimport { PaypalStyleOptions } from '@bigcommerce/checkout-sdk/braintree-utils';\n\nexport default function getValidButtonStyle(style?: PaypalStyleOptions): PaypalStyleOptions {\n const { color, fundingicons, height = 40, 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 | string): number {\n const minHeight = 25;\n const defaultHeight = 40;\n const maxHeight = 55;\n\n const currentHeight = Number(height);\n\n if (!currentHeight || Number.isNaN(currentHeight)) {\n return defaultHeight;\n }\n\n if (currentHeight > maxHeight) {\n return maxHeight;\n }\n\n if (currentHeight < minHeight) {\n return minHeight;\n }\n\n return currentHeight;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n BraintreeError,\n BraintreeHostWindow,\n BraintreeInitializationData,\n BraintreeIntegrationService,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n isBraintreeError,\n PaypalAuthorizeData,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n BuyNowCartCreationError,\n BuyNowCartRequestBody,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport getValidButtonStyle from '../get-valid-button-style';\nimport mapToBraintreeShippingAddressOverride from '../map-to-braintree-shipping-address-override';\n\nimport BraintreePaypalButtonInitializeOptions, {\n WithBraintreePaypalButtonInitializeOptions,\n} from './braintree-paypal-button-initialize-options';\n\nexport default class BraintreePaypalButtonStrategy implements CheckoutButtonStrategy {\n private buyNowCartId: string | undefined;\n\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: CheckoutButtonInitializeOptions & WithBraintreePaypalButtonInitializeOptions,\n ): Promise {\n const { braintreepaypal, 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 (!braintreepaypal) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal\" argument is not provided.`,\n );\n }\n\n let state = this.paymentIntegrationService.getState();\n let currencyCode: string;\n\n if (braintreepaypal.buyNowInitializeOptions) {\n if (!braintreepaypal.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypalcredit.currencyCode\" argument is not provided.`,\n );\n }\n\n currencyCode = braintreepaypal.currencyCode;\n } else {\n await this.paymentIntegrationService.loadDefaultCheckout();\n\n state = this.paymentIntegrationService.getState();\n currencyCode = state.getCartOrThrow().currency.code;\n }\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { clientToken, config, 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 commit: false,\n };\n\n const paypalCheckoutSuccessCallback = (\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n this.renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypal,\n containerId,\n methodId,\n !!config.testMode,\n );\n };\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this.handleError(error, containerId, braintreepaypal.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 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.braintreeHostWindow;\n\n if (paypal) {\n const paypalButtonRender = paypal.Buttons({\n env: testMode ? 'sandbox' : 'production',\n fundingSource: paypal.FUNDING.PAYPAL,\n style: getValidButtonStyle(style),\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.braintreeIntegrationService.removeElement(containerId);\n }\n }\n\n private async setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalButtonInitializeOptions,\n methodId: string,\n ): Promise {\n const { onPaymentError, shippingAddress, buyNowInitializeOptions } = braintreepaypal;\n\n try {\n const buyNowCart =\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function'\n ? await this.createBuyNowCart(\n buyNowInitializeOptions.getBuyNowCartRequestBody(),\n )\n : undefined;\n\n this.buyNowCartId = buyNowCart?.id;\n\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomer();\n const paymentMethod: PaymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n const amount = buyNowCart ? buyNowCart.cartAmount : state.getCartOrThrow().cartAmount;\n const currencyCode = buyNowCart\n ? braintreepaypal.currencyCode\n : state.getCartOrThrow().currency.code;\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: unknown) {\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 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.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: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(billingAddress),\n shipping_address: JSON.stringify(shippingAddress),\n ...(this.buyNowCartId && { cart_id: this.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 async createBuyNowCart(buyNowCardRequestBody?: BuyNowCartRequestBody | void) {\n if (!buyNowCardRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n return await this.paymentIntegrationService.createBuyNowCart(buyNowCardRequestBody);\n } catch (error) {\n throw new BuyNowCartCreationError();\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 BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreePaypalButtonStrategy from './braintree-paypal-button-strategy';\n\nconst createBraintreePaypalButtonStrategy: CheckoutButtonStrategyFactory<\n BraintreePaypalButtonStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n );\n\n return new BraintreePaypalButtonStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeIntegrationService,\n braintreeHostWindow,\n );\n};\n\nexport default toResolvableModule(createBraintreePaypalButtonStrategy, [{ id: 'braintreepaypal' }]);\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n BraintreeError,\n BraintreeHostWindow,\n BraintreeInitializationData,\n BraintreeIntegrationService,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n isBraintreeError,\n PaypalAuthorizeData,\n PaypalButtonStyleLabelOption,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n BuyNowCartCreationError,\n BuyNowCartRequestBody,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport getValidButtonStyle from '../get-valid-button-style';\nimport mapToBraintreeShippingAddressOverride from '../map-to-braintree-shipping-address-override';\n\nimport BraintreePaypalCreditButtonInitializeOptions, {\n WithBraintreePaypalCreditButtonInitializeOptions,\n} from './braintree-paypal-credit-button-initialize-options';\n\nexport default class BraintreePaypalCreditButtonStrategy implements CheckoutButtonStrategy {\n private buyNowCartId: string | undefined;\n\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: CheckoutButtonInitializeOptions & WithBraintreePaypalCreditButtonInitializeOptions,\n ): 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 = this.paymentIntegrationService.getState();\n let currencyCode: string;\n\n if (braintreepaypalcredit.buyNowInitializeOptions) {\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 await this.paymentIntegrationService.loadDefaultCheckout();\n\n state = this.paymentIntegrationService.getState();\n currencyCode = state.getCartOrThrow().currency.code;\n }\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { clientToken, config, 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 commit: false,\n };\n\n const paypalCheckoutSuccessCallback = (\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n this.renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n containerId,\n methodId,\n !!config.testMode,\n );\n };\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this.handleError(error, containerId, braintreepaypalcredit.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 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.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 const buttonStyle =\n fundingSource === paypal.FUNDING.CREDIT\n ? {\n label: PaypalButtonStyleLabelOption.CREDIT,\n ...getValidButtonStyle(style),\n }\n : getValidButtonStyle(style);\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.braintreeIntegrationService.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\n try {\n const buyNowCart =\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function'\n ? await this.createBuyNowCart(\n buyNowInitializeOptions.getBuyNowCartRequestBody(),\n )\n : undefined;\n\n this.buyNowCartId = buyNowCart?.id;\n\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomer();\n const paymentMethod: PaymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n const amount = buyNowCart ? buyNowCart.cartAmount : state.getCartOrThrow().cartAmount; // state.getCheckoutOrThrow().outstandingBalance\n const currencyCode = buyNowCart\n ? braintreepaypalcredit.currencyCode\n : state.getCartOrThrow().currency.code;\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: true,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error: unknown) {\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 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.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: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(billingAddress),\n shipping_address: JSON.stringify(shippingAddress),\n ...(this.buyNowCartId && { cart_id: this.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 async createBuyNowCart(buyNowCardRequestBody?: BuyNowCartRequestBody | void) {\n if (!buyNowCardRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n return await this.paymentIntegrationService.createBuyNowCart(buyNowCardRequestBody);\n } catch (error) {\n throw new BuyNowCartCreationError();\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 BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreePaypalCreditButtonStrategy from './braintree-paypal-credit-button-strategy';\n\nconst createBraintreePaypalCreditButtonStrategy: CheckoutButtonStrategyFactory<\n BraintreePaypalCreditButtonStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n );\n return new BraintreePaypalCreditButtonStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeIntegrationService,\n braintreeHostWindow,\n );\n};\n\nexport default toResolvableModule(createBraintreePaypalCreditButtonStrategy, [\n { id: 'braintreepaypalcredit' },\n]);\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), hostWindow, braintreeSDKVersionManager),\n );\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 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 || 40}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 await this.paymentIntegrationService.loadDefaultCheckout();\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeScriptLoader = new BraintreeScriptLoader(\n scriptLoader,\n braintreeHostWindow,\n braintreeSDKVersionManager,\n );\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 GooglePayError,\n GooglePayInitializationData,\n GooglePayPaymentDataRequest,\n GooglePayPaymentOptions,\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 this._googlePayPaymentProcessor.setIsWebViewExperimentOn(\n !!paymentMethod.initializationData?.isWebViewExperimentOn,\n );\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) => Promise {\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 if (this._googlePayPaymentProcessor.isWebViewWithRestrictions()) {\n return {};\n }\n\n return {\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({\n callbackTrigger,\n shippingAddress,\n shippingOptionData,\n offerData,\n }) => {\n const {\n availableTriggers,\n addressChangeTriggers,\n shippingOptionsChangeTriggers,\n offerChangeTriggers,\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 const { newOfferInfo = undefined, error: couponsError = undefined } =\n offerChangeTriggers.includes(callbackTrigger)\n ? await this._googlePayPaymentProcessor.handleCoupons(offerData)\n : {};\n\n // We can add another errors if needed 'couponsError || shippingError || anotherError'\n const error: GooglePayError | undefined = couponsError;\n\n if (this._buyNowInitializeOptions) {\n return this._getBuyNowTransactionInfo(\n availableShippingOptions,\n newOfferInfo,\n error,\n );\n }\n\n return this._getTransactionInfo(availableShippingOptions, newOfferInfo, error);\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(\n availableShippingOptions?: ShippingOptionParameters,\n newOfferInfo?: GooglePayPaymentDataRequest['offerInfo'],\n error?: GooglePayError,\n ) {\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 ...(newOfferInfo && {\n newOfferInfo,\n }),\n ...(error && {\n error,\n }),\n };\n }\n\n private async _getTransactionInfo(\n availableShippingOptions?: ShippingOptionParameters,\n newOfferInfo?: GooglePayPaymentDataRequest['offerInfo'],\n error?: GooglePayError,\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 ...(this._countryCode && { countryCode: this._countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n ...(availableShippingOptions && {\n newShippingOptionParameters: availableShippingOptions,\n }),\n ...(newOfferInfo && {\n newOfferInfo,\n }),\n ...(error && {\n error,\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\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';\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 PayPalCommerceSdk(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';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PayPalSdkHelper } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\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 GooglePayBigCommercePaymentsGateway from './google-pay-bigcommerce-payments-gateway';\n\nconst createGooglePayBigCommercePaymentsButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayBigCommercePaymentsGateway(\n paymentIntegrationService,\n new PayPalSdkHelper(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayBigCommercePaymentsButtonStrategy, [\n { id: 'googlepay_bigcommerce_payments' },\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';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\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';\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 StripeScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayStripeButtonStrategy, [\n { id: 'googlepaystripe' },\n { id: 'googlepaystripeupe' },\n { id: 'googlepaystripeocs' },\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 PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n PaypalButtonCreationService,\n PayPalButtonOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\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 paypalIntegrationService: PayPalIntegrationService,\n private paypalButtonCreationService: PaypalButtonCreationService,\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.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, isAppSwitchEnabled } =\n paymentMethod.initializationData || {};\n\n const buyNowFlowCallbacks = {\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const buttonOptions: PayPalButtonOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalIntegrationService.getValidButtonStyle(style),\n isAppSwitchEnabled,\n isHostedCheckoutEnabled,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && onComplete && { onPaymentComplete: () => onComplete() }),\n };\n\n const paypalButton = this.paypalButtonCreationService.createPayPalButton(\n 'paypalcommerce',\n methodId,\n buttonOptions,\n buyNowInitializeOptions,\n );\n\n if (paypalButton.isEligible()) {\n if (paypalButton.hasReturned?.() && isAppSwitchEnabled) {\n paypalButton.resume?.();\n } else {\n paypalButton.render(`#${containerId}`);\n }\n } else if (onEligibilityFailure && typeof onEligibilityFailure === 'function') {\n onEligibilityFailure();\n } else {\n this.paypalIntegrationService.removeElement(containerId);\n }\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalIntegrationService,\n PaypalButtonCreationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceButtonStrategy from './paypal-commerce-button-strategy';\n\nconst createPayPalCommerceButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceButtonStrategy\n> = (paymentIntegrationService) => {\n const paypalIntegrationService = createPayPalIntegrationService(paymentIntegrationService);\n const paypalButtonCreationService = new PaypalButtonCreationService(\n paymentIntegrationService,\n paypalIntegrationService,\n );\n\n return new PayPalCommerceButtonStrategy(\n paymentIntegrationService,\n paypalIntegrationService,\n paypalButtonCreationService,\n );\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 ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalButtonsOptions,\n PayPalBuyNowInitializeOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\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 paypalIntegrationService: PayPalIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPayPalCommerceCreditButtonInitializeOptions,\n ): Promise {\n const { paypalcommercecredit, containerId, methodId } = options;\n const { buyNowInitializeOptions, currencyCode: providedCurrencyCode } =\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.paypalIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommercecredit);\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.paypalIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, isAppSwitchEnabled } =\n paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n createOrder: () => this.paypalIntegrationService.createOrder('paypalcommercecredit'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const hostedCheckoutCallbacks = {\n ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n }),\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: PayPalButtonsOptions = {\n fundingSource,\n style: this.paypalIntegrationService.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.paypalIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalIntegrationService.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.paypalIntegrationService.getBillingAddressFromOrderDetails(orderDetails);\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalIntegrationService.getShippingAddressFromOrderDetails(orderDetails);\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalIntegrationService.updateOrder('paypalcommerce');\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalIntegrationService.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.paypalIntegrationService.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.paypalIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalIntegrationService.updateOrder('paypalcommerce');\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.paypalIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalIntegrationService.updateOrder('paypalcommerce');\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';\nimport { createPayPalIntegrationService } from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceCreditButtonStrategy from './paypal-commerce-credit-button-strategy';\n\nconst createPayPalCommerceCreditButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceCreditButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditButtonStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\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 { 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 { 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 { round } from 'lodash';\n\nimport {\n AmountTransformer,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n Payment,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n ShippingOption,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n isStripePaymentMethodLike,\n StripeAdditionalActionRequired,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeError,\n StripeEventType,\n StripeInitializationData,\n StripeIntegrationService,\n StripeLinkV2Event,\n StripeLinkV2Options,\n StripeLinkV2ShippingRate,\n StripePaymentMethodType,\n StripeResult,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport {\n expressCheckoutAllowedCountryCodes,\n stripeAllowedShippingOptionsLength,\n} from './constants';\nimport { WithStripeOCSCustomerInitializeOptions } from './stripe-ocs-customer-initialize-options';\n\nexport default class StripeLinkV2ButtonStrategy implements CheckoutButtonStrategy {\n private _stripeClient?: StripeClient;\n private _stripeElements?: StripeElements;\n private _linkV2Element?: StripeElement;\n private _amountTransformer?: AmountTransformer;\n private _onComplete?: (orderId?: number) => Promise;\n private _loadingIndicatorContainer?: string;\n private _currencyCode?: string;\n private _captureMethod?: 'automatic' | 'manual';\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n private stripeIntegrationService: StripeIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithStripeOCSCustomerInitializeOptions,\n ): Promise {\n const { stripeocs, containerId } = options || {};\n\n if (!stripeocs || !containerId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { gatewayId } = stripeocs;\n\n if (!gatewayId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const methodId = this._getMethodId(gatewayId);\n const state = await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n const paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n const { loadingContainerId, buttonHeight, onComplete } = stripeocs;\n\n this._loadingIndicatorContainer = loadingContainerId;\n\n this._onComplete = onComplete;\n\n if (!isStripePaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { initializationData } = paymentMethod;\n const { captureMethod } = initializationData;\n const stripeJsVersion =\n this.stripeIntegrationService.getStripeJsVersion(initializationData);\n\n this._captureMethod = captureMethod;\n this._stripeClient = await this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n stripeJsVersion,\n );\n\n await this.paymentIntegrationService.loadDefaultCheckout();\n\n await this._mountExpressCheckoutElement(containerId, this._stripeClient, buttonHeight);\n\n this._initializeEvents(methodId);\n }\n\n signIn() {\n return Promise.resolve();\n }\n\n signOut() {\n return Promise.resolve();\n }\n\n executePaymentMethodCheckout() {\n return Promise.resolve();\n }\n\n deinitialize() {\n return Promise.resolve();\n }\n\n private async _mountExpressCheckoutElement(\n container: string,\n stripeExpressCheckoutClient: StripeClient,\n buttonHeight = 40,\n ) {\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n const expressCheckoutOptions: StripeElementsCreateOptions = {\n shippingAddressRequired: shouldRequireShippingAddress,\n ...(shouldRequireShippingAddress\n ? { allowedShippingCountries: await this._getAvailableCountries() }\n : {}),\n ...(shouldRequireShippingAddress\n ? { shippingRates: [{ id: '_', amount: 0, displayName: 'Pending rates' }] }\n : {}),\n billingAddressRequired: true,\n emailRequired: true,\n phoneNumberRequired: true,\n paymentMethods: {\n link: StripeStringConstants.AUTO,\n applePay: StripeStringConstants.NEVER,\n googlePay: StripeStringConstants.NEVER,\n amazonPay: StripeStringConstants.NEVER,\n paypal: StripeStringConstants.NEVER,\n klarna: StripeStringConstants.NEVER,\n },\n // Minimal buttonHeight value is 40\n buttonHeight,\n };\n\n const { cartAmount = 1 } = this.paymentIntegrationService.getState().getCart() || {};\n\n const elementsOptions: StripeLinkV2Options = {\n mode: 'payment',\n amount: this._toCents(cartAmount),\n currency: this._getCurrency(),\n ...(this._captureMethod ? { captureMethod: this._captureMethod } : {}),\n };\n\n this._stripeElements = stripeExpressCheckoutClient.elements(elementsOptions);\n\n this._linkV2Element = this._stripeElements.create(\n StripeElementType.EXPRESS_CHECKOUT,\n expressCheckoutOptions,\n );\n this._linkV2Element.mount(`#${container}`);\n }\n\n /** Events * */\n\n private _initializeEvents(methodId: string): void {\n if (!this._linkV2Element) {\n return;\n }\n\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n\n if (shouldRequireShippingAddress) {\n this._linkV2Element.on(StripeElementEvent.SHIPPING_ADDRESS_CHANGE, async (event) =>\n this._onShippingAddressChange(event),\n );\n this._linkV2Element.on(StripeElementEvent.SHIPPING_RATE_CHANGE, async (event) =>\n this._onShippingRateChange(event),\n );\n }\n\n this._linkV2Element.on(StripeElementEvent.CONFIRM, async (event) =>\n this._onConfirm(event, methodId),\n );\n\n this._linkV2Element.on(StripeElementEvent.CANCEL, this._onCancel);\n }\n\n private async _onShippingAddressChange(event: StripeEventType) {\n if (!('address' in event)) {\n return;\n }\n\n const shippingAddress = event.address;\n // Depending on the country, some fields can be missing or partially redacted.\n // For example, the shipping address in the US can only contain a city, state, and ZIP code.\n // The full shipping address appears in the confirm event object after the purchase is confirmed in the browser’s payment interface.\n const result = {\n firstName: '',\n lastName: '',\n phone: '',\n company: '',\n address1: '',\n address2: '',\n city: shippingAddress?.city || '',\n countryCode: shippingAddress?.country || '',\n postalCode: shippingAddress?.postal_code || '',\n stateOrProvince: shippingAddress?.state || '',\n stateOrProvinceCode: shippingAddress?.state || '',\n customFields: [],\n };\n\n await this.paymentIntegrationService.updateShippingAddress(result);\n\n const shippingRates = await this._getAvailableShippingOptions();\n\n await this._updateDisplayedPrice();\n\n if (!shippingRates?.length) {\n event.reject();\n } else {\n event.resolve({\n shippingRates,\n });\n }\n }\n\n private _onCancel() {\n throw new PaymentMethodCancelledError();\n }\n\n private async _onShippingRateChange(event: StripeEventType) {\n if ('shippingRate' in event) {\n const { shippingRate } = event;\n\n await this._handleShippingOptionChange(shippingRate?.id);\n\n await this._updateDisplayedPrice();\n\n event.resolve({});\n }\n }\n\n /** Confirm methods * */\n private async _onConfirm(event: StripeEventType, methodId: string) {\n if (\n 'billingDetails' in event &&\n 'shippingAddress' in event &&\n this._stripeClient &&\n this._stripeElements\n ) {\n await this._updateShippingAndBillingAddress(event);\n await this.paymentIntegrationService.submitOrder();\n\n const paymentPayload = this._getPaymentPayload(methodId);\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._processAdditionalAction(error, methodId);\n }\n }\n\n return Promise.resolve();\n }\n\n private async _updateShippingAndBillingAddress(event: StripeLinkV2Event) {\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n\n const firstName =\n event.shippingAddress?.name?.split(' ')[0] ||\n event.billingDetails?.name?.split(' ')[0] ||\n '';\n const lastName =\n event.shippingAddress?.name?.split(' ')[1] ||\n event.billingDetails?.name?.split(' ')[1] ||\n '';\n\n if (shouldRequireShippingAddress) {\n const shippingAddress = this._mapShippingAddress(\n event.shippingAddress,\n event.billingDetails,\n firstName,\n lastName,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n }\n\n const billingAddress = this._mapBillingAddress(\n event.shippingAddress,\n event.billingDetails,\n firstName,\n lastName,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n private _mapShippingAddress(\n shippingAddress: StripeLinkV2Event['shippingAddress'],\n billingDetails: StripeLinkV2Event['billingDetails'],\n firstName: string,\n lastName: string,\n ) {\n return {\n firstName,\n lastName,\n phone: billingDetails?.phone || '',\n company: '',\n address1: shippingAddress?.address?.line1 || '',\n address2: shippingAddress?.address?.line2 || '',\n city: shippingAddress?.address?.city || '',\n countryCode: shippingAddress?.address?.country || '',\n postalCode: shippingAddress?.address?.postal_code || '',\n stateOrProvince: shippingAddress?.address?.state || '',\n stateOrProvinceCode: shippingAddress?.address?.state || '',\n customFields: [],\n };\n }\n\n private _mapBillingAddress(\n shippingAddress: StripeLinkV2Event['shippingAddress'],\n billingDetails: StripeLinkV2Event['billingDetails'],\n firstName: string,\n lastName: string,\n ) {\n return {\n email: billingDetails?.email || '',\n firstName,\n lastName,\n phone: billingDetails?.phone || '',\n company: '',\n address1: billingDetails?.address?.line1 || '',\n address2: '',\n city: billingDetails?.address?.city || '',\n countryCode: billingDetails?.address?.country || '',\n postalCode: billingDetails?.address?.postal_code || '',\n stateOrProvince: billingDetails?.address?.state || '',\n stateOrProvinceCode: shippingAddress?.address?.state || '',\n customFields: [],\n };\n }\n\n private async _processAdditionalAction(error: unknown, methodId: string): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n if (!this._stripeClient || !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 additionalActionData,\n methodId,\n );\n\n const paymentPayload = this._getPaymentPayload(methodId, paymentIntent?.id || token);\n\n try {\n this._toggleLoadingIndicator(true);\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n await this._completeCheckoutFlow();\n } catch (error) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n } finally {\n this._toggleLoadingIndicator(false);\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n additionalActionData: StripeAdditionalActionRequired['data'],\n methodId: string,\n ): Promise {\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeIntegrationService.mapStripePaymentData(\n this._stripeElements,\n redirect_url,\n );\n let stripeError: StripeError | undefined;\n\n try {\n const isPaymentCompleted = await this.stripeIntegrationService.isPaymentCompleted(\n methodId,\n this._stripeClient,\n );\n\n const confirmationResult = !isPaymentCompleted\n ? await this._stripeClient?.confirmPayment({\n elements: stripePaymentData.elements,\n clientSecret: token,\n redirect: StripeStringConstants.IF_REQUIRED,\n confirmParams: {\n return_url: stripePaymentData.confirmParams?.return_url,\n },\n })\n : await this._stripeClient?.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 return this.stripeIntegrationService.throwStripeError(stripeError);\n }\n }\n\n private async _completeCheckoutFlow() {\n if (typeof this._onComplete === 'function') {\n return this._onComplete();\n }\n\n window.location.replace('/checkout/order-confirmation');\n\n return Promise.resolve();\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 ...(token ? { credit_card_token: { token } } : {}),\n confirm: false,\n method: StripePaymentMethodType.Link,\n };\n\n return {\n methodId,\n paymentData: {\n formattedPayload,\n },\n };\n }\n\n /** Utils * */\n\n private _shouldRequireShippingAddress() {\n const { getCart } = this.paymentIntegrationService.getState();\n\n const { lineItems } = getCart() || {};\n\n return !!lineItems?.physicalItems.length;\n }\n\n private async _updateDisplayedPrice() {\n if (this._stripeElements) {\n this._stripeElements.update({\n currency: this._getCurrency(),\n mode: 'payment',\n amount: await this._getTotalPrice(),\n });\n }\n }\n\n private _getCurrency() {\n if (!this._currencyCode) {\n const currencyCode = this.paymentIntegrationService.getState().getCart()?.currency;\n\n if (currencyCode) {\n this._currencyCode = currencyCode.code.toLowerCase();\n }\n }\n\n return this._currencyCode;\n }\n\n private async _getTotalPrice(): Promise {\n await this.paymentIntegrationService.loadCheckout();\n\n const { getCheckoutOrThrow, getCart } = this.paymentIntegrationService.getState();\n const { decimalPlaces } = getCart()?.currency || {};\n const totalPrice = round(getCheckoutOrThrow().outstandingBalance, decimalPlaces).toFixed(\n decimalPlaces,\n );\n\n return this._toCents(+totalPrice);\n }\n\n private async _getAvailableCountries(): Promise {\n const countries = await this.paymentIntegrationService.loadShippingCountries();\n const deliverableCountries =\n countries.getShippingCountries()?.map((country) => country.code) || [];\n\n return deliverableCountries.filter((code) => {\n return expressCheckoutAllowedCountryCodes.includes(code);\n });\n }\n\n private async _getAvailableShippingOptions(): Promise {\n const state = this.paymentIntegrationService.getState();\n const consignments = state.getConsignments();\n\n if (!consignments?.[0]) {\n return;\n }\n\n const consignment = consignments[0];\n const options = (consignment.availableShippingOptions || []).map(\n this._getStripeShippingOption.bind(this),\n );\n const recommendedShippingOption = consignment.availableShippingOptions?.find(\n (shippingOption) => shippingOption.isRecommended,\n );\n const selectedId = consignment.selectedShippingOption?.id;\n const recommendedId = recommendedShippingOption?.id;\n\n if (selectedId) {\n // Set selected shipping option first in the array, as it will be selected by default\n options.sort((option) => (option.id === selectedId ? -1 : 0));\n } else if (recommendedId) {\n // Set recommended shipping option first in the array, as it will be selected by default\n options.sort((option) => (option.id === recommendedId ? -1 : 0));\n await this._handleShippingOptionChange(recommendedId);\n } else {\n await this._handleShippingOptionChange(options[0]?.id);\n }\n\n // Stripe has restricted the number of shipping rates.\n return options.slice(0, stripeAllowedShippingOptionsLength);\n }\n\n private _getStripeShippingOption({ id, cost, description }: ShippingOption) {\n return {\n id,\n displayName: description,\n amount: this._toCents(cost),\n };\n }\n\n private async _handleShippingOptionChange(optionId?: string) {\n if (!optionId || optionId === 'shipping_option_unselected') {\n return;\n }\n\n return this.paymentIntegrationService.selectShippingOption(optionId);\n }\n\n private _getAmountTransformer() {\n if (this._amountTransformer) {\n return this._amountTransformer;\n }\n\n const { getCart } = this.paymentIntegrationService.getState();\n const { currency } = getCart() || {};\n\n if (currency) {\n const amountTransformer = new AmountTransformer(currency.decimalPlaces);\n\n return amountTransformer;\n }\n }\n\n private _toCents(amount: number) {\n const fallbackValue = Math.round(amount * 100);\n const amountTransformer = this._getAmountTransformer();\n\n if (amountTransformer) {\n return amountTransformer.toInteger(amount);\n }\n\n return fallbackValue;\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 _getMethodId(gatewayId: string): string {\n const { initializationData: { checkoutSessionEnabled } = {} } =\n this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(gatewayId);\n\n return checkoutSessionEnabled\n ? StripePaymentMethodType.CHECKOUT_SESSION\n : StripePaymentMethodType.OCS;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\nimport { DEFAULT_CONTAINER_STYLES, LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport StripeLinkV2ButtonStrategy from './stripe-link-v2-button-strategy';\n\nconst createLinkV2ButtonStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n const loadingIndicator = new LoadingIndicator({\n containerStyles: DEFAULT_CONTAINER_STYLES,\n });\n\n return new StripeLinkV2ButtonStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n loadingIndicator,\n );\n};\n\nexport default toResolvableModule(createLinkV2ButtonStrategy, [{ id: 'stripeocs' }]);\n","import { uniqueId } from 'lodash';\n\nimport { InvalidArgumentError } from '../error/errors';\n\nconst getUniqId = (idPrefix?: string): string => {\n const id = uniqueId(idPrefix);\n\n return document.getElementById(id) ? getUniqId(idPrefix) : id;\n};\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 = getUniqId(idPrefix);\n }\n\n return container.id;\n });\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 { 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 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","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 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 { 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 { 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","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 = '',\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 { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { createCheckoutStore } from '../checkout';\nimport { ConfigState } from '../config';\nimport * as defaultCheckoutButtonStrategyFactories from '../generated/checkout-button-strategies';\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 } = 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(\n paymentIntegrationService,\n process.env.ESSENTIAL_BUILD ? {} : defaultCheckoutButtonStrategyFactories,\n );\n\n return new CheckoutButtonInitializer(\n store,\n new CheckoutButtonStrategyActionCreator(\n createCheckoutButtonRegistry(store, requestSender, formPoster, 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';\n\nexport interface CheckoutButtonStrategyFactories {\n [key: string]: CheckoutButtonStrategyFactory;\n}\n\nexport default function createCheckoutButtonStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n checkoutButtonStrategyFactories: CheckoutButtonStrategyFactories,\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 { CheckoutActionCreator, CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { PaypalScriptLoader } from '../payment/strategies/paypal';\n\nimport { CheckoutButtonMethodType, CheckoutButtonStrategy } from './strategies';\nimport { PaypalButtonStrategy } from './strategies/paypal';\n\nexport default function createCheckoutButtonRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\n formPoster: FormPoster,\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 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 { 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 { 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","import { FormatError, IntlMessageFormat } from 'intl-messageformat';\nimport { isObject, union } from 'lodash';\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\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 }\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._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 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 }, {});\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","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 { 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","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":["y","x","module","exports","iframeResizer","__WEBPACK_EXTERNAL_MODULE_iframe_resizer_1512d797__","__webpack_require__","d","__WEBPACK_EXTERNAL_MODULE_iframe_resizer_js_iframeResizer_contentWindow_a6cfc03f__","__webpack_module_cache__","moduleId","cachedModule","undefined","__webpack_modules__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","r","Symbol","toStringTag","value","B2B_EXTRA_FIELD_PREFIX","isExtraField","field","name","startsWith","mapExtraFieldToFormField","extraField","fieldType","type","extraFieldType","getFieldTypeInfo","options","config","numberOfRows","rows","_a","length","assign","items","map","val","label","id","custom","hidden","visibleToStorefront","required","isRequired","default","defaultValue","String","maxLength","max","maxValue","throwErrorAction","error","meta","action","__WEBPACK_EXTERNAL_MODULE_rxjs_concat__","__WEBPACK_EXTERNAL_MODULE_rxjs_of__","__WEBPACK_EXTERNAL_MODULE_rxjs_throwError__","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_createErrorAction__","payload","B2BTokenActionType","B2BTokenActionCreator","constructor","_requestSender","this","loadB2BToken","store","state","getState","storeConfig","getStoreConfigOrThrow","storeHash","storeProfile","baseUrl","b2bBaseUrl","clientId","b2bClientId","b2bApiSettings","customerId","customer","getCustomerOrThrow","channelId","checkout","getCheckoutOrThrow","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_createAction__","LoadB2BTokenRequested","__WEBPACK_EXTERNAL_MODULE_rxjs_defer__","__awaiter","body","getB2BToken","LoadB2BTokenSucceeded","token","data","pipe","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_catchError__","LoadB2BTokenFailed","SDK_VERSION_HEADERS","MissingDataErrorType","BillingAddressActionType","B2BTokenRequestSender","appClientId","jwtBody","timeout","params","app_client_id","headers","post","credentials","bcToken","StandardError","Error","message","super","setPrototypeOf","__proto__","captureStackTrace","stack","MissingDataError","subtype","MissingBillingAddress","MissingCart","MissingConsignments","MissingCheckout","MissingCustomer","MissingCheckoutConfig","MissingOrderConfig","MissingOrder","MissingOrderId","MissingPayment","MissingPaymentToken","MissingPaymentMethod","MissingPaymentProviderCustomer","MissingShippingAddress","getErrorMessage","UnableToContinueAsGuestError","ContentType","BillingAddressActionCreator","_subscriptionActionCreator","continueAsGuest","getCheckout","getCustomer","isGuest","billingAddress","getBillingAddress","billingAddressRequestBody","country","existingBillingAddressRequestBody","__rest","hasBillingAddress","__WEBPACK_EXTERNAL_MODULE_lodash_isEmpty__","__WEBPACK_EXTERNAL_MODULE_rxjs_merge__","ContinueAsGuestRequested","billing_address_action_creator_awaiter","_createOrUpdateBillingAddress","ContinueAsGuestSucceeded","ContinueAsGuestFailed","_updateCustomerConsent","updateAddress","address","__WEBPACK_EXTERNAL_MODULE_rxjs_Observable__","create","observer","next","UpdateBillingAddressRequested","email","then","UpdateBillingAddressSucceeded","complete","catch","response","UpdateBillingAddressFailed","acceptsAbandonedCartEmails","acceptsMarketingNewsletter","__WEBPACK_EXTERNAL_MODULE_rxjs_empty__","updateSubscriptions","checkoutId","createAddress","EmptyCartError","content_type","DEFAULT_PARAMS","include","join","BillingAddressRequestSender","url","Accept","JsonV1","err","billing_address_request_sender_rest","put","ProjectionActionType","ErrorActionType","createDataStoreProjection","stateTransformer","projection","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_createDataStore__","Synchronize","subscribe","dispatch","initial","ErrorActionCreator","clearError","ClearError","ExperimentAwareRequestSender","_config","sendRequest","_prefixed","patch","delete","basePath","getBasePath","getFeatures","endsWith","test","getEnvironment","e","ConsoleLogger","_console","log","messages","_logToConsole","info","warn","debug","NoopLogger","logger","isEnabled","console","createLogger","getDefaultLogger","cachableActionDecorator","_","descriptor","memoizedMethods","WeakMap","decorateMethod","method","args","lastArg","useCache","param","instanceMethods","fn","set","__WEBPACK_EXTERNAL_MODULE__bigcommerce_memoize_bf7b411a_memoize__","__WEBPACK_EXTERNAL_MODULE_rxjs_from__","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_shareReplay__","isEqual","__WEBPACK_EXTERNAL_MODULE_lodash_isEqual__","ConfigActionType","ConfigActionCreator","_configRequestSender","loadConfig","LoadConfigRequested","LoadConfigSucceeded","LoadConfigFailed","__decorate","DEFAULT_RESPONSE","status","RequestError","errors","CheckoutNotAvailableError","title","INTERNAL_USE_ONLY","ConfigRequestSender","CouponActionType","CouponActionCreator","_couponRequestSender","applyCoupon","code","ApplyCouponRequested","ApplyCouponSucceeded","ApplyCouponFailed","removeCoupon","RemoveCouponRequested","RemoveCouponSucceeded","RemoveCouponFailed","checkout_default_includes","CheckoutIncludes","GiftCertificateActionType","CartSource","CustomerActionType","joinIncludes","includes","__WEBPACK_EXTERNAL_MODULE_lodash_uniq__","CouponRequestSender","couponCode","AvailableShippingOptions","GiftCertificateActionCreator","_giftCertificateRequestSender","applyGiftCertificate","giftCertificate","ApplyGiftCertificateRequested","ApplyGiftCertificateSucceeded","ApplyGiftCertificateFailed","removeGiftCertificate","RemoveGiftCertificateRequested","RemoveGiftCertificateSucceeded","RemoveGiftCertificateFailed","GiftCertificateRequestSender","giftCertificateCode","isResolvableModule","InvalidArgumentError","Registry","_factories","_instances","_defaultToken","defaultToken","_useFallback","_b","useFallback","_tokenResolver","_c","tokenResolver","cacheToken","_getInstance","getFactory","exactMatch","resolvedToken","keys","register","factory","_hasFactory","_hasInstance","ResolveIdRegistry","_registry","_resolveToken","bind","_encodeToken","resolveId","getUseFallback","btoa","JSON","stringify","_decodeToken","parse","atob","registeredTokens","query","results","forEach","registeredToken","resolverId","result","matches","totalKeys","entries","push","matchedResults","sort","a","b","filter","queryKeyCount","exactResult","find","matched","isSpamProtectionExecuteSucceededAction","succeededAction","CustomerStrategyActionType","CheckoutActionType","CheckoutHydrateActionType","CustomerActionCreator","_customerRequestSender","_checkoutActionCreator","_spamProtectionActionCreator","createCustomer","customerAccount","isStorefrontSpamProtectionEnabled","checkoutSettings","createAccount","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_switchMap__","loadCurrentCheckout","CreateCustomerSucceeded","CreateCustomerRequested","execute","CreateCustomerFailed","customerAddress","CreateCustomerAddressRequested","customer_action_creator_awaiter","CreateCustomerAddressSucceeded","CreateCustomerAddressFailed","signInCustomer","cartId","cart","source","BuyNow","SignInCustomerRequested","persistentCartRetrievalInformation","loadCheckout","SignInCustomerSucceeded","SignInCustomerFailed","signOutCustomer","SignOutCustomerRequested","SignOutCustomerSucceeded","SignOutCustomerFailed","CustomerRequestSender","registerIntegrations","registry","integrations","paymentIntegrationService","resolveIds","CustomerStrategyActionCreator","_strategyRegistry","_strategyRegistryV2","_paymentIntegrationService","signIn","methodId","SignInRequested","_getStrategy","SignInSucceeded","SignInFailed","signOut","SignOutRequested","SignOutSucceeded","SignOutFailed","executePaymentMethodCheckout","ExecutePaymentMethodCheckoutRequested","ExecutePaymentMethodCheckoutSucceeded","ExecutePaymentMethodCheckoutFailed","initialize","customerStrategies","isInitialized","InitializeRequested","InitializeSucceeded","InitializeFailed","deinitialize","DeinitializeRequested","DeinitializeSucceeded","DeinitializeFailed","widgetInteraction","WidgetInteractionStarted","WidgetInteractionFinished","WidgetInteractionFailed","strategy","joinOrMergeIncludes","baseIncludes","includeDictionaryOrList","Array","isArray","includesDictionary","deletions","__WEBPACK_EXTERNAL_MODULE_lodash_keys__","__WEBPACK_EXTERNAL_MODULE_lodash_pickBy__","on","additions","__WEBPACK_EXTERNAL_MODULE_lodash_filter__","__WEBPACK_EXTERNAL_MODULE_lodash_difference__","mergeIncludes","CheckoutRequestSender","updateCheckout","FormFieldsActionType","CheckoutActionCreator","_checkoutRequestSender","_configActionCreator","_formFieldsActionCreator","LoadCheckoutRequested","loadFormFields","LoadCheckoutSucceeded","_transformCustomerAddresses","LoadCheckoutFailed","loadDefaultCheckout","checkout_action_creator_awaiter","context","getContextConfig","UpdateCheckoutRequested","UpdateCheckoutSucceeded","UpdateCheckoutFailed","hydrateInitialState","HydrateInitialState","addresses","shouldSaveAddress","SpamProtectionActionType","FormFieldsActionCreator","_formFieldsRequestSender","LoadFormFieldsRequested","form_fields_action_creator_awaiter","loadFields","LoadFormFieldsSucceeded","LoadFormFieldsFailed","form_fields_action_creator_decorate","FormFieldsRequestSender","SpamProtectionChallengeNotCompletedError","SpamProtectionFailedError","NotInitializedErrorType","ExtensionActionType","ExtensionInternalEventType","SpamProtectionActionCreator","_googleRecaptcha","spam_protection_action_creator_awaiter","spamProtectionElementId","containerId","document","getElementById","reset","spamProtectionElement","createElement","setAttribute","appendChild","recaptchaSitekey","googleRecaptchaSitekey","load","verifyCheckoutSpamProtection","VerifyCheckoutRequested","validate","VerifyCheckoutSucceeded","VerifyCheckoutFailed","ExecuteRequested","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_take__","ExecuteSucceeded","ExecuteFailed","MutationObserverFactory","_window","window","callback","MutationObserver","NotInitializedError","CustomerNotInitialized","PaymentNotInitialized","ShippingNotInitialized","SpamProtectionNotInitialized","not_initialized_error_getErrorMessage","SpamProtectionNotLoadedError","GoogleRecaptcha","googleRecaptchaScriptLoader","mutationObserverFactory","_memoized","recaptcha","sitekey","container","event$","__WEBPACK_EXTERNAL_MODULE_rxjs_Subject__","_widgetId","render","size","getResponse","_event$","_recaptcha","element","remove","querySelector","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_retryWhen__","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_delay__","index","TIMEOUT","_watchRecaptchaChallengeWindow","event","iframeContainer","parentElement","style","visibility","observe","attributes","attributeFilter","GoogleRecaptchaScriptLoader","_scriptLoader","_loadPromise","_loadScript","callbackName","Promise","resolve","reject","grecaptcha","loadScript","createSpamProtection","scriptLoader","SpamProtectionRequestSender","DefaultCustomerStrategy","_store","_customerActionCreator","continueWithCheckoutCallback","parseUrl","anchor","href","port","indexOf","hostname","hash","origin","protocol","pathname","search","ExtensionNotFoundError","isIframeEvent","object","IframeEventPoster","targetOrigin","_targetWindow","_context","_targetOrigin","targetWindow","__WEBPACK_EXTERNAL_MODULE_rxjs_fromEvent__","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_filter__","successType","errorType","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_map__","toPromise","postMessage","setTarget","setContext","createExtensionEventPoster","extension","iframe","contentWindow","CancellablePromise","promise","cancellable","cancel","race","UnexpectedDetachmentError","ExtensionInternalCommandType","DetachmentObserver","_mutationObserver","ensurePresence","targets","mutationsList","mutation","from","removedNodes","node","some","target","contains","childList","subtree","output","disconnect","originalIframeResizer","ExtensionNotLoadedError","ResizableIframeCreator","_options","createFrame","src","initCallback","failedCallback","border","display","width","_toResizableFrame","removeChild","timeoutInterval","detachmentObserver","setTimeout","handleMessage","ResizeIframe","iframes","autoResize","scrolling","sizeWidth","heightCalculationMethod","teardown","removeEventListener","clearTimeout","addEventListener","ExtensionIframe","_containerId","_extension","parentOrigin","_url","URL","searchParams","attach","iframeCreator","iframeResizerCallback","_iframe","toString","ExtensionReady","ExtensionFailed","detach","ExtensionActionCreator","loadExtensions","LoadExtensionsRequested","extensions","LoadExtensionsSucceeded","LoadExtensionsFailed","renderExtension","region","workerExtensionMessenger","extension_action_creator_awaiter","getCartOrThrow","links","checkoutLink","getExtensionByRegion","RenderExtensionRequested","worker","Worker","blob","createObjectURL","Blob","createExtensionWebWorker","add","RenderExtensionSucceeded","RenderExtensionFailed","ExtensionRequestSender","bind_decorator","bindMethodDecorator","decoratedTarget","getOwnPropertyNames","getOwnPropertyDescriptor","bindClassDecorator","boundMethod","ExtensionCommandType","ExtensionQueryType","WorkerEventListener","_worker","_isListening","_listeners","listen","_handleMessage","stopListen","addListener","listener","listeners","removeListener","splice","trigger","messageEvent","worker_event_listener_rest","worker_event_listener_decorate","WorkerEventPoster","UnsupportedExtensionCommandError","UnsupportedExtensionQueryError","WorkerExtensionMessenger","_workers","_commandListeners","_queryListeners","extensionId","listenForCommand","command","commandHandler","_getWorkerById","validCommandType","_validateCommand","commandHandlerProxy","listenForQuery","queryHandler","validQueryType","_validateQuery","queryHandlerProxy","clearCacheById","values","appendWww","replace","ExtensionEventType","IframeEventListener","sourceOrigin","_sourceOrigins","iframe_event_listener_rest","iframe_event_listener_decorate","ExtensionMessenger","_workerExtensionMessenger","_posters","clearCacheByRegion","_getExtensionByRegion","_getExtensionById","_getExtensions","_extensions","getExtensions","ExtensionEventBroadcaster","_extensionMessenger","_subscribers","_subscribed","_unsubscribers","eventListener","Subscribe","_handleSubscribe","Unsubscribe","_handleUnsubscribe","broadcast","eventType","subscribeConsignmentsChange","broadcaster","getConsignments","getInitialConsignments","consignments","currentConsignments","ConsignmentsChanged","previousConsignments","standard_error_StandardError","missing_data_error_MissingDataErrorType","not_initialized_error_NotInitializedErrorType","missing_data_error_MissingDataError","missing_data_error_getErrorMessage","getShippableItemsCount","lineItems","physicalItems","item","addedByPromotion","__WEBPACK_EXTERNAL_MODULE_lodash_reduce__","total","quantity","guard","errorFactory","not_initialized_error_NotInitializedError","errors_not_initialized_error_getErrorMessage","amazonPayV2Regions","de","jp","uk","us","AmazonPayV2CheckoutLanguage","AmazonPayV2Placement","AmazonPayV2LedgerCurrency","AmazonPayV2PayOptions","AmazonPayV2ButtonColor","AmazonPayV2ButtonDesign","AmazonPayV2PaymentProcessor","amazonPayV2ScriptLoader","paymentMethod","amazonPayV2SDK","buttonParentContainer","createAmazonPayButtonParentContainer","amazonPayV2Button","bindButton","buttonId","sessionId","changeAction","getAmazonPayV2SDK","Pay","bindChangeAction","amazonCheckoutSessionId","createButton","renderButton","prepareCheckout","createCheckoutSessionConfig","requestConfig","prepareRequestConfig","getAmazonPayV2Button","onClick","initCheckout","prepareCheckoutWithCreationRequestConfig","createCheckoutConfig","amazon_pay_v2_payment_processor_awaiter","estimatedOrderAmount","productType","signout","renderAmazonPayButton","buttonColor","checkoutState","decoupleCheckoutInitiation","placement","isButtonMicroTextDisabled","parentContainerId","getButtonParentContainer","design","C0001","amazonPayV2ButtonOptions","getAmazonPayV2ButtonOptions","updateBuyNowFlowFlag","isBuyNowFlow","Boolean","isPh4Enabled","features","storeCountryCode","isPh4UsOnly","publicKeyId","signedPayload","amazon_pay_v2_payment_processor_rest","isEnvironmentSpecific","uid","Math","random","substr","parentContainer","Gold","getCart","getPaymentMethodOrThrow","getCheckoutState","merchantId","testMode","initializationData","checkoutLanguage","checkoutSessionMethod","extractAmazonCheckoutSessionId","ledgerCurrency","buttonBaseConfig","sandbox","PayOnly","PayAndShip","shopPath","amount","outstandingBalance","currencyCode","currency","buttonOptions","tmpConfig","createCheckoutSession","getOrThrow","checkoutSelectors","paymentMethods","PaymentMethodClientUnavailableError","AmazonPayV2ScriptLoader","windowWithAmazonPay","amazonPayV2Region","amazon","createAmazonPayV2PaymentProcessor","__WEBPACK_EXTERNAL_MODULE__bigcommerce_script_loader_875b3e8f_getScriptLoader__","toResolvableModule","invalid_argument_error_InvalidArgumentError","NotImplementedError","AmazonPayV2CustomerStrategy","amazonPayV2PaymentProcessor","amazonpay","_e","loadPaymentMethod","Checkout","payment","getPaymentId","remoteCheckoutSignOut","providerId","create_amazon_pay_v2_customer_strategy","isExperimentEnabled","experimentName","fallbackValue","BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION","BRAINTREE_SDK_DEFAULT_VERSION","BRAINTREE_SDK_STABLE_VERSION","BraintreeSDKVersionManager","braintreeWindow","getSDKVersion","getStoreConfig","getPreloadedSDKVersion","braintree","preloadedVersion","__WEBPACK_EXTERNAL_MODULE_lodash_find__","VERSION","UnsupportedBrowserError","TotalPriceStatusType","BraintreeOrderStatus","NonInstantLocalPaymentMethods","BraintreeFastlaneAuthenticationState","BraintreeErrorType","BraintreeErrorCode","BraintreeSupportedCardBrands","isBraintreeError","BraintreeEnv","BraintreeModuleName","BraintreeFormFieldType","BraintreeSdk","braintreeScriptLoader","clientToken","setClientToken","teardownModule","dataCollector","getClient","client","getClientTokenOrThrow","clientCreator","loadClient","authorization","getDataCollectorOrThrow","emptyDataCollector","deviceData","loadDataCollector","dataCollectorConfig","kount","KountNotEnabled","getBraintreeGooglePayment","googlePayment","braintreeGooglePayment","all","loadGooglePayment","getBraintreeThreeDS","threeDS","threeDSecure","load3DS","version","getBraintreeLocalPayment","merchantAccountId","braintreeLocalPayment","localPaymentCreator","loadLocalPayment","getUsBankAccount","usBankAccount","loadUsBankAccount","getBraintreeVisaCheckout","visaCheckout","loadVisaCheckout","paypal","getVisaCheckoutSdk","visaCheckoutSDK","loadVisaCheckoutSdk","getVenmoCheckoutOrThrow","braintreeVenmo","venmoCheckout","loadVenmoCheckout","venmoCheckoutConfig","allowDesktop","paymentMethodUsage","braintreeVenmoCheckout","isBrowserSupported","BRAINTREE_SDK_SCRIPTS_INTEGRITY","Client","PaypalCheckout","Paypal","LocalPayment","DataCollector","UsBankAccount","GooglePayment","ThreeDSecure","VisaCheckout","Venmo","HostedFields","Fastlane","ApplePayGatewayType","BraintreeScriptLoader","braintreeHostWindow","braintreeSDKVersionManager","loadBraintreeModuleOrThrow","loadFastlane","loadPaypalCheckout","loadPaypal","loadHostedFields","V","async","integrity","crossorigin","braintreeModuleName","fileName","getBraintreeModule","braintreeSdkVersion","scriptPath","getIntegrityValuesByModuleName","moduleName","PaymentMethodCancelledError","DefaultLabels","ApplePayCustomerStrategy","_sessionFactory","_braintreeSdk","_applePayScriptLoader","_onAuthorizeCallback","__WEBPACK_EXTERNAL_MODULE_lodash_noop__","_onError","_onClick","_subTotalLabel","Subtotal","_shippingLabel","Shipping","_hasApplePaySession","applepay","shippingLabel","subtotalLabel","onError","onPaymentAuthorize","loadSdk","_paymentMethod","_applePayButton","_createButton","_handleWalletButtonClick","gateway","BRAINTREE","applePayButton","_createApplePayButtonElement","preventDefault","request","_getBaseRequest","applePaySession","_handleApplePayEvents","begin","storeName","decimalPlaces","merchantCapabilities","supportedNetworks","requiresShipping","requiredBillingContactFields","requiredShippingContactFields","countryCode","grandTotal","toFixed","subtotal","taxes","tax","onvalidatemerchant","apple_pay_customer_strategy_awaiter","merchantSession","_onValidateMerchant","completeMerchantValidation","onshippingcontactselected","_handleShippingContactSelected","onshippingmethodselected","_handleShippingMethodSelected","oncancel","onpaymentauthorized","_onPaymentAuthorized","shippingAddress","_transformContactToAddress","shippingContact","updateShippingAddress","abort","selectionShippingOptionId","selectedShippingOption","availableOptions","availableShippingOptions","selectedOption","unselectedOptions","option","shippingOptions","description","cost","detail","additionalDescription","identifier","isRecommended","completeShippingContactSelection","ApplePaySession","STATUS_INVALID_SHIPPING_POSTAL_ADDRESS","recommendedOption","optionId","selectedOptionId","_updateShippingOption","newShippingMethods","newTotal","newLineItems","_getUpdatedLineItems","shippingMethod","completeShippingMethodSelection","shippingCostTotal","selectShippingOption","paymentData","validationURL","location","paymentsUrl","billingContact","deviceSessionId","_getBraintreeDeviceData","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","assertApplePayWindow","isApplePayWindow","ApplePaySessionFactory","ApplePayScriptLoader","sdkVersion","isApplePaySdkWindow","create_apple_pay_customer_strategy","getHost","__WEBPACK_EXTERNAL_MODULE__bigcommerce_request_sender_01d1f546_createRequestSender__","host","__WEBPACK_EXTERNAL_MODULE__bigcommerce_script_loader_875b3e8f_ScriptLoader__","BuyNowCartCreationError","request_error_DEFAULT_RESPONSE","request_error_RequestError","LiabilityShiftEnum","BigCommercePaymentsIntent","StyleButtonLabel","StyleButtonColor","StyleButtonShape","NonInstantAlternativePaymentMethods","PayPalOrderStatus","BigCommercePaymentsIntegrationService","formPoster","bigCommercePaymentsRequestSender","bigCommercePaymentsScriptLoader","loadPayPalSdk","providedCurrencyCode","initializesOnCheckoutPage","forceLoad","paypalSdk","getPayPalSDK","getPayPalSdkOrThrow","createBuyNowCartOrThrow","buyNowInitializeOptions","cartRequestBody","getBuyNowCartRequestBody","createBuyNowCart","createOrder","requestBody","orderId","createOrderCardFields","setupToken","updateOrder","consignment","getConsignmentsOrThrow","_error","getOrderStatus","tokenizePayment","postForm","payment_type","provider","order_id","cart_id","gatewayId","vault_payment_instrument","set_as_default_stored_instrument","device_info","method_id","paypal_account","getShippingOptionOrThrow","selectedShippingOptionId","recommendedShippingOption","shippingOptionToSelect","getAddress","getBillingAddressFromOrderDetails","payer","given_name","surname","email_address","address_line_1","address_line_2","admin_area_2","country_code","postal_code","admin_area_1","phone_number","national_number","getShippingAddressFromOrderDetails","orderDetails","purchase_units","full_name","shipping","split","getValidButtonStyle","color","height","shape","validStyles","getValidHeight","__WEBPACK_EXTERNAL_MODULE_lodash_omitBy__","__WEBPACK_EXTERNAL_MODULE_lodash_isNil__","removeElement","elementId","internal_api_headers_INTERNAL_USE_ONLY","content_type_ContentType","http_request_content_type","sdk_version_headers_SDK_VERSION_HEADERS","BigCommercePaymentsRequestSender","requestSender","Json","BigCommercePaymentsScriptLoader","paypalSdkScriptConfig","getPayPalSdkScriptConfigOrThrow","loadPayPalSDK","bigCommercePaymentsPayPalSDK","transformConfig","scriptSrc","URLSearchParams","intent","buyerCountry","attributionId","isVenmoEnabled","isHostedCheckoutEnabled","isPayPalCreditAvailable","isDeveloperModeApplicable","availableAlternativePaymentMethods","enabledAlternativePaymentMethods","isGooglePayEnabled","commit","shouldEnableCard","enableCardFunding","disableCardFunding","enableCreditFunding","disableCreditFunding","enableVenmoFunding","disableVenmoFunding","disableAPMsFunding","apm","googlePayComponent","cardFieldsComponent","disableFunding","filterFundingOptions","enableFunding","components","fundingOptions","fundingTypesToBeFiltered","fundingOption","transformedConfig","create_bigcommerce_payments_integration_service","__WEBPACK_EXTERNAL_MODULE__bigcommerce_form_poster_1cd9ef62_createFormPoster__","default_checkout_button_height","BigCommercePaymentsCustomerStrategy","bigCommercePaymentsIntegrationService","bigcommerce_payments","getPaymentMethod","Buttons","onComplete","paymentButtonStyles","isAppSwitchEnabled","checkoutTopButtonStyles","defaultCallbacks","appSwitchWhenAvailable","onApprove","orderID","hostedCheckoutCallbacks","onShippingAddressChange","onShippingOptionsChange","actions","onHostedCheckoutApprove","buttonRenderOptions","fundingSource","FUNDING","PAYPAL","paypalButton","isEligible","hasReturned","resume","order","handleError","shippingOption","create_bigcommerce_payments_customer_strategy","UntrustedShippingCardVerificationType","bigcommerce_payments_types_BigCommercePaymentsIntent","bigcommerce_payments_types_LiabilityShiftEnum","TDSecureVerificationMethod","TDSecureAuthenticationState","bigcommerce_payments_types_StyleButtonLabel","bigcommerce_payments_types_StyleButtonColor","bigcommerce_payments_types_StyleButtonShape","PayPalFastlaneAuthenticationState","PayPalSdkHelper","getPayPalFastlaneSdk","bigCommercePaymentsFastlaneSdk","getPayPalFastlaneSdkConfiguration","getPayPalGooglePaySdk","bigCommercePaymentsGooglePay","getPayPalGooglePaySdkScriptConfigOrThrow","getPayPalApmsSdk","bigCommercePaymentsApms","getPayPalApmSdkConfiguration","getPayPalMessages","bigCommercePaymentsMessages","paypalSdkMessagesConfig","getPayPalSdkMessagesConfiguration","scriptOptions","scriptAttributes","enableAPMsFunding","createBigCommercePaymentsSdk","__WEBPACK_EXTERNAL_MODULE__bigcommerce_script_loader_875b3e8f_createScriptLoader__","CookieStorage","cookieKey","encodeURIComponent","cookie","firstIndex","lastIndex","decodeURIComponent","substring","secure","cookieText","expires","path","domain","toUTCString","now","Date","minutes","setTime","getTime","BigCommercePaymentsFastlaneUtils","initializePayPalFastlane","paypalFastlaneSdk","isTestModeEnabled","styles","localStorage","setItem","bigCommercePaymentsFastlane","defaultStyles","root","backgroundColorPrimary","getPayPalFastlaneOrThrow","lookupCustomerOrThrow","identity","lookupCustomerByEmail","triggerAuthenticationFlowOrThrow","customerContextId","triggerAuthenticationFlow","updateStorageSessionId","setDate","getDate","cookiesOption","removeStorageSessionId","getStorageSessionId","mapPayPalFastlaneProfileToBcCustomerData","authenticationResult","authenticationState","profileData","paypalBillingAddress","card","paymentSource","paypalShippingAddress","paypalProfileName","paypalInstrument","mapPayPalToBcAddress","instruments","mapPayPalToBcInstrument","filterAddresses","UNRECOGNIZED","instrument","brand","expiry","lastDigits","expiryYear","expiryMonth","bigpayToken","defaultInstrument","iin","last4","trustedShippingAddress","untrustedShippingCardVerificationMode","PAN","mapBcToPayPalAddress","addressLine1","addressLine2","adminArea1","adminArea2","profileName","fullName","phoneData","nationalNumber","reduce","customerAddresses","currentAddress","isEqualAddresses","firstAddress","secondAddress","normalizeAddress","__WEBPACK_EXTERNAL_MODULE_lodash_omit__","createBigCommercePaymentsFastlaneUtils","isInvalidStyleOption","styleOption","getFastlaneStyles","styleSettings","uiStyles","fastlaneStyles","input","toggle","textBody","text","textCaption","caption","branding","cleanUpFastlaneStyles","fastlaneRootSettingsBackgroundColor","errorColor","fastlaneRootSettingsErrorColor","fontFamily","fastlaneRootSettingsFontFamily","fontSizeBase","fastlaneRootSettingsFontSize","_d","padding","fastlaneRootSettingsPadding","primaryColor","fastlaneRootSettingsPrimaryColor","_f","borderRadius","fastlaneInputSettingsBorderRadius","_g","borderColor","fastlaneInputSettingsBorderColor","_h","focusBorderColor","fastlaneInputSettingsFocusBorderBase","_j","backgroundColor","fastlaneInputSettingsBackgroundColor","_k","borderWidth","fastlaneInputSettingsBorderWidth","_l","textColorBase","fastlaneInputSettingsTextColorBase","_m","colorPrimary","fastlaneToggleSettingsColorPrimary","_o","colorSecondary","fastlaneToggleSettingsColorSecondary","_p","fastlaneTextBodySettingsColor","_r","_q","fontSize","fastlaneTextBodySettingsFontSize","_t","_s","fastlaneTextCaptionSettingsColor","_v","_u","fastlaneTextCaptionSettingsFontSize","_x","_w","fastlaneBrandingSettings","mergeFastlaneStyles","BigCommercePaymentsFastlaneCustomerStrategy","bigCommercePaymentsSdk","bigCommercePaymentsFastlaneUtils","bigcommerce_payments_fastlane","updatePaymentProviderCustomer","checkoutPaymentMethodExecuted","runPayPalAuthenticationFlowOrThrow","customerEmail","isAuthenticationFlowCanceled","CANCELED","updateCustomerDataState","updatedState","isFastlaneShippingOptionAutoSelectEnabled","firstShippingOption","shippingOptionId","isFastlaneStylingEnabled","create_bigcommerce_payments_fastlane_customer_strategy","BigCommercePaymentsPayLaterCustomerStrategy","bigcommerce_payments_paylater","bigCommercePaymentsPayLater","fundingSources","PAYLATER","CREDIT","hasRenderedSmartButton","create_bigcommerce_payments_paylater_customer_strategy","BigCommercePaymentsVenmoCustomerStrategy","bigcommerce_payments_venmo","VENMO","paypalButtonRender","create_bigcommerce_payments_venmo_customer_strategy","PaymentMethodFailedError","PaymentMethodInvalidError","BoltDeveloperMode","StyleButtonSize","bolt_StyleButtonShape","BoltCustomerStrategy","boltScriptLoader","boltHostWindow","bolt","onInit","publishableKey","developerConfig","loadBoltClient","getCustomerEmail","hasBoltAccount","__WEBPACK_EXTERNAL_MODULE_rxjs_noop__","openBoltCheckoutModalOrThrow","boltClient","getBoltClientOrThrow","embeddedOneClickEnabled","callbacks","close","openCheckout","isCustomError","BoltCheckout","BoltScriptLoader","developerModeParams","storefrontApiToken","getDomainURL","getScriptOptions","loadBoltEmbedded","Bolt","developerMode","StagingMode","DevelopmentMode","developerDomain","create_bolt_customer_strategy","PaymentArgumentInvalidError","invalidFields","PaymentInvalidFormError","details","paypalSdkPromise","PAYPAL_COMPONENTS","PaypalButtonStyleLayoutOption","PaypalButtonStyleSizeOption","PaypalButtonStyleColorOption","PaypalButtonStyleLabelOption","PaypalButtonStyleShapeOption","MessagingPlacements","BraintreeIntegrationService","overlay","dataCollectors","threeDSecureOptions","getBraintreeFastlane","cardId","braintreeFastlane","getSessionId","braintreeFastlaneCreator","getPaypal","braintreePaypal","shouldSaveInstrument","braintree_integration_service_rest","newWindowFlow","__WEBPACK_EXTERNAL_MODULE__braintree_browser_detection_e7ac357c_supportsPopups__","show","focusWindow","tokenize","enableShippingAddress","flow","useraction","getPaypalCheckout","onSuccess","paypalCheckout","paypalCheckoutConfig","braintreePaypalCheckout","paypalSdkLoadConfig","isCreditEnabled","loadPayPalSDKOnce","getDataCollector","cacheKey","cached","getBraintreeEnv","isTestMode","Sandbox","Production","mapToBraintreeShippingAddressOverride","recipientName","line1","line2","mapToLegacyShippingAddress","first_name","last_name","mapToLegacyBillingAddress","riskCorrelationId","get3DS","getVenmoCheckout","venmoConfig","verifyCard","tokenizationPayload","tokenizeCard","challenge3DSVerification","creditCardInstrument","ccExpiry","ccNumber","ccName","isCreditCardInstrumentLike","getErrorsRequiredFields","requestData","mapToCreditCard","creditCards","nonce","bin","present3DSChallenge","creditCard","cardholderName","number","cvv","ccCvv","expirationDate","month","year","countryCodeAlpha2","countryName","streetAddress","endpoint","addFrame","removeFrame","challengeRequested","additionalInformation","cancelVerifyCard","braintree_integration_service_awaiter","verification","roundedAmount","Number","onLookupComplete","_data","collectDeviceData","BraintreePaypalCustomerStrategy","braintreeIntegrationService","braintreepaypal","paypalCheckoutOptions","renderPayPalButton","buttonStyles","env","setupPayment","authorizeData","shippingAddressOverride","createPayment","shippingAddressEditable","offerCredit","tokenizePayload","device_data","billing_address","shipping_address","buttonContainerId","onErrorCallback","create_braintree_paypal_customer_strategy","BraintreePaypalCreditCustomerStrategy","braintreepaypalcredit","create_braintree_paypal_credit_customer_strategy","get_fastlane_styles_isInvalidStyleOption","get_fastlane_styles_getFastlaneStyles","get_fastlane_styles_cleanUpFastlaneStyles","get_fastlane_styles_mergeFastlaneStyles","BraintreeFastlaneCustomerStrategy","braintreeFastlaneUtils","isAcceleratedCheckoutEnabled","braintreefastlane","getValidPaymentMethodOrThrow","paypalFastlaneStylesSettings","initializeBraintreeFastlaneOrThrow","shouldRunAuthenticationFlow","primaryMethodId","shouldRunAcceleratedCheckout","validPaymentMethodId","BraintreeFastlaneUtils","getDeviceSessionId","getBraintreeFastlaneOrThrow","getBraintreeFastlaneComponentOrThrow","FastlaneCardComponent","shouldSetShippingOption","getMethodIdOrThrow","saveSessionIdToCookies","removeSessionIdFromCookies","shippingAddresses","getPayPalBillingAddresses","billingAddresses","mergeShippingAndBillingAddresses","digitalItems","digitalItemBilling","setShippingOption","getSessionIdFromCookies","binDetails","phones","countries","getCountries","getCountryNameByCountryCode","matchedCountry","extendedAddress","filteredBillingAddresses","create_braintree_fastlane_customer_strategy","BraintreeVisaCheckoutCustomerStrategy","braintreeSdk","buttonClassName","braintreevisacheckout","visaCheckoutOptions","braintreeVisaCheckout","visaCheckoutInstance","initOptions","createInitOptions","paymentRequest","settings","locale","storeLanguage","collectShipping","signInButton","createSignInButton","init","paymentSuccessPayload","getShippingAddress","billing","mapToVisaCheckoutAddress","userData","cardInformation","userEmail","card_information","cardType","lastTwo","buttonClass","insertVisaCheckoutButton","visaCheckoutButton","flexDirection","className","innerHTML","create_braintree_visa_checkout_customer_strategy","hostWindow","CurrencyFormatter","currencySettings","symbolLocation","symbol","thousandsSeparator","decimalSeparator","_decimalPlaces","parseInt","_symbolLocation","_symbol","_thousandsSeparator","_decimalSeparator","format","formattedNumber","_formatNumber","formattedCurrency","_formatCurrency","positiveAmount","abs","integerAmount","decimalAmount","_toFixed","parsedIntegerAmount","toLowerCase","precision","round","CurrencyService","_storeConfig","_customerFormatter","shopperCurrency","_storeFormatter","toCustomerCurrency","exchangeRate","toStoreCurrency","currency_service_decorate","items_require_shipping","lineItem","isShippingRequired","customItems","isWebView","isReactNativeWindow","userAgent","navigator","vendor","isOperaWindow","opera","isAndroidWebView","isIOSWebView","PayPalCommerceIntent","types_StyleButtonLabel","types_StyleButtonColor","types_StyleButtonShape","types_TotalPriceStatusType","GooglePayCardNetwork","CallbackIntentsType","ErrorReasonType","CallbackTriggerType","isGooglePayCardNetworkKey","GooglePayKey","GooglePayGateway","_gatewayIdentifier","_isBuyNowFlow","_shouldRequestShipping","_isWebViewExperimentOn","mapToShippingAddressRequestBody","_mapToAddressRequestBody","mapToBillingAddressRequestBody","paymentMethodData","mapToExternalCheckoutData","tokenizationData","cardNetwork","cardDetails","getRequiredData","emailRequired","_isShippingAddressRequired","loadShippingCountries","allowedCountryCodes","getShippingCountries","shippingAddressRequired","shippingAddressParameters","phoneNumberRequired","shippingOptionRequired","getCallbackIntents","OFFER","SHIPPING_ADDRESS","SHIPPING_OPTION","getCallbackTriggers","availableTriggers","INITIALIZE","initializationTrigger","addressChangeTriggers","shippingOptionsChangeTriggers","offerChangeTriggers","getNonce","extraPaymentData","getMerchantInfo","googleMerchantName","merchantName","googleMerchantId","platformToken","authJwt","getGooglePayInitializationData","getTransactionInfo","_getCurrencyCodeOrThrow","storeCountry","isWebViewWithRestrictions","totalPrice","getTotalPrice","totalPriceStatus","ESTIMATED","setIsWebViewExperimentOn","isWebViewExperimentOn","getPaymentGatewayParameters","gatewayMerchantId","getCardParameters","allowedAuthMethods","allowedCardNetworks","supportedCards","billingAddressRequired","billingAddressParameters","_getPaymentMethodFn","_currencyCode","handleShippingAddressChange","mappedShippingAddress","_currencyService","currency_service","_getGooglePayShippingOption","handleShippingOptionChange","defaultSelectedOptionId","maxDecimalPlaces","min","__WEBPACK_EXTERNAL_MODULE_lodash_round__","handleCoupons","offerData","redemptionCodes","newCouponsState","offers","appliedCoupons","getAppliedCoupons","google_pay_gateway_awaiter","redemptionCode","appliedCouponError","coupon","newOfferInfo","coupons","displayName","reason","OFFER_INVALID","setShouldRequestShipping","getGatewayIdentifier","setGatewayIdentifier","shippingContextRequiresCheck","address3","_getFirstAndLastName","trim","nameParts","slice","isGooglePayErrorObject","isGooglePayKey","GooglePayCustomerStrategy","_googlePayPaymentProcessor","_methodId","googlePayOptions","_getMethodId","_getGooglePayClientOptions","_addPaymentButton","_paymentButton","paymentDataCallbacks","onPaymentDataChanged","callbackTrigger","shippingOptionData","google_pay_customer_strategy_awaiter","couponsError","newTransactionInfo","FINAL","newShippingOptionParameters","buttonType","addPaymentButton","_handleClick","initializeWidget","_interactWithPaymentSheet","statusCode","showPaymentSheet","siteLink","setExternalCheckoutForm","GooglePayPaymentProcessor","_gateway","_formPoster","_baseRequest","apiVersion","apiVersionMinor","googlePayPaymentOptions","_paymentsClient","getGooglePaymentsClient","_buildButtonPayloads","_buildWidgetPayloads","_determineReadinessToPay","_prefetchGooglePaymentData","paymentButton","_getPaymentsClient","allowedPaymentMethods","_getBaseCardPaymentMethod","paymentDataRequest","_getPaymentDataRequest","loadPaymentData","setExternalCheckoutXhr","_setExternalCheckout","processAdditionalAction","useFormPoster","transactionInfo","prefetchPaymentData","isReadyToPay","_getIsReadyToPayRequest","_baseCardPaymentMethod","parameters","baseCardPaymentMethod","_cardPaymentMethod","tokenizationSpecification","isWebViewLogic","callbackIntents","offerInfo","_paymentDataRequest","merchantInfo","_isReadyToPayRequest","_getOrThrow","GooglePayScriptLoader","google","payments","api","PaymentsClient","environment","createGooglePayScriptLoader","create_google_pay_adyenv2_customer_strategy","create_google_pay_adyenv3_customer_strategy","GooglePayAuthorizeNetGateway","service","_super","isGooglePayAuthorizeNetInitializationData","assertsIsGooglePayAuthorizeNetInitializationData","paymentGatewayId","create_google_pay_authorizenet_customer_strategy","is_request_error","assertIsGooglePayCheckoutComInitializationData","isGooglePayCheckoutComInitializationData","GooglePayCheckoutComGateway","_resolve","threeDSBody","three_ds_result","acs_url","isGooglePayThreeDSecureResult","isGooglePayTokenObject","assertIsGooglePayTokenObject","_tokenize","checkoutcomkey","token_data","Authorization","create_google_pay_checkoutcom_customer_strategy","GooglePayCybersourceGateway","create_google_pay_cybersource_customer_strategy","create_google_pay_bnz_customer_strategy","GooglePayOrbitalGateway","create_google_pay_orbital_customer_strategy","StripeFormMode","StripeDisplayName","StripeCheckoutSessionStatusType","StripeCheckoutSessionPaymentStatus","StripeLoadActionsResultType","StripePaymentMethodType","StripeStringConstants","StripeJsVersion","StripeElementType","StripePaymentIntentStatus","StripeElementEvent","StripeInstrumentSetupFutureUsage","StripeScriptLoader","stripeWindow","getStripeClient","stripeJsVersion","betas","bcStripeClient","stripe","stripePublishableKey","stripeConnectedAccount","stripeClient","stripeAccount","getElements","stripeElements","bcStripeElements","updateStripeElements","elements","update","fetchUpdates","getStripeCheckout","stripeCheckout","getStoredStripeCheckout","bcStripeCheckout","Stripe","getScriptUrl","V3","loadActions","logErrorToConsole","stripeCheckoutSession","getSession","stripeSessionIdFromOptions","clientSecret","STRIPE_UPE_CLIENT_BETAS","STRIPE_UPE_CLIENT_API_VERSION","assertsIsGooglePayStripeInitializationData","isGooglePayStripeInitializationData","GooglePayStripeGateway","isGooglePayStripeTokenObject","assertIsGooglePayStripeTokenObject","stripeVersion","__WEBPACK_EXTERNAL_MODULE_lodash_some__","initialization","stripeUPEClient","loadStripeJs","catchedConfirmError","confirmCardPayment","retrievePaymentIntent","__","_throwDisplayableStripeError","_isCancellationError","paymentIntent","getCartLocale","useNewStripeJsVersion","CLOVER","stripeError","payment_intent","last_payment_error","__WEBPACK_EXTERNAL_MODULE_lodash_includes__","create_google_pay_stripe_customer_strategy","create_google_pay_stripeupe_customer_strategy","GooglePayWorldpayAccessGateway","create_google_pay_worldpayaccess_customer_strategy","GooglePayBraintreeGateway","_service","_braintreeGooglePayment","isThreeDSecureEnabled","isNetworkTokenized","orderAmount","getOrderOrThrow","_braintreePresent3DSChallenge","isGooglePayBraintreeTokenObject","assertIsGooglePayBraintreeTokenObject","androidPayCards","createPaymentDataRequest","cardRequirements","billingAddressFormat","paymentMethodTokenizationParameters","create_google_pay_braintree_customer_strategy","LOADING_INDICATOR_STYLES","PAYPAL_SDK_SUPPORTED_LOCALES","transformLocaleToPayPalFormat","language","toUpperCase","PayPalCommerceSdk","paypalGooglePay","paypalApms","paypalMessages","assertsIsGooglePayPayPalCommercePaymentMethod","isGooglePayPaypalCommercePaymentMethod","GooglePayPaypalCommerceGateway","payPalCommerceSdk","googlePaySdk","getLocale","googlepayConfig","Googlepay","create_google_pay_paypal_commerce_customer_strategy","GooglePayBigCommercePaymentsGateway","payPalSdkHelper","create_google_pay_bigcommerce_payments_customer_strategy","getBrowserInfo","userLanguage","color_depth","screen","colorDepth","java_enabled","javaEnabled","screen_height","screen_width","time_zone_offset","getTimezoneOffset","GooglePayTdOnlineMartGateway","browser_info","errorBody","__WEBPACK_EXTERNAL_MODULE_lodash_isObject__","__WEBPACK_EXTERNAL_MODULE_lodash_isArray__","isTdOnlineMartAdditionalAction","threeDSResult","formUrl","payer_auth_request","threeDSSessionData","merchant_data","creq","create_google_pay_tdonlinemart_customer_strategy","PayPalIntent","paypal_types_TDSecureVerificationMethod","paypal_types_TDSecureAuthenticationState","paypal_types_LiabilityShiftEnum","paypal_types_StyleButtonLabel","paypal_types_StyleButtonColor","paypal_types_StyleButtonShape","paypal_types_PayPalFastlaneAuthenticationState","paypal_types_NonInstantAlternativePaymentMethods","paypal_types_PayPalOrderStatus","PayPalSdkScriptLoader","createPayPalSdkScriptLoader","PayPalIntegrationService","paypalRequestSender","paypalSdkLoader","PayPalRequestSender","create_paypal_integration_service","paypal_button_creation_service","paypalIntegrationService","createPayPalButton","onCancel","onPaymentComplete","paypal_button_creation_service_awaiter","buyNowCart","PayPalCommerceCustomerStrategy","paypalButtonCreationService","paypalcommerce","create_paypal_commerce_customer_strategy","paypal_commerce_types_LiabilityShiftEnum","paypal_commerce_types_PayPalCommerceIntent","paypal_commerce_types_StyleButtonLabel","paypal_commerce_types_StyleButtonColor","paypal_commerce_types_StyleButtonShape","paypal_commerce_types_NonInstantAlternativePaymentMethods","paypal_commerce_types_PayPalOrderStatus","PayPalCommerceIntegrationService","paypalCommerceRequestSender","paypalCommerceScriptLoader","PayPalCommerceRequestSender","PayPalCommerceScriptLoader","create_paypal_commerce_integration_service","PayPalCommerceCreditCustomerStrategy","paypalCommerceIntegrationService","paypalcommercecredit","paypalCommerceCredit","create_paypal_commerce_credit_customer_strategy","PayPalCommerceVenmoCustomerStrategy","paypalcommercevenmo","create_paypal_commerce_venmo_customer_strategy","PaypalFastlaneUtils","paypalFastlane","createPaypalFastlaneUtils","utils_get_fastlane_styles_isInvalidStyleOption","utils_get_fastlane_styles_getFastlaneStyles","utils_get_fastlane_styles_cleanUpFastlaneStyles","utils_get_fastlane_styles_mergeFastlaneStyles","PayPalCommerceFastlaneCustomerStrategy","paypalSdkScriptLoader","paypalFastlaneUtils","paypalcommercefastlane","create_paypal_commerce_fastlane_customer_strategy","isStripePaymentMethodLike","shopperLanguage","isStripeAcceleratedCheckoutCustomer","StripeUPECustomerStrategy","stripeupe","onEmailChange","getStyles","isLoading","paymentProviderCustomer","getPaymentProviderCustomerOrThrow","stripeLinkAuthenticationState","appearance","variables","fieldInnerShadow","colorBackground","fieldBackground","colorText","labelText","colorDanger","fieldErrorText","colorTextSecondary","colorTextPlaceholder","fieldPlaceholderText","rules","fieldBorder","fieldText","boxShadow","_stripeElements","billingEmail","defaultValues","mode","SHIPPING","linkAuthenticationElement","getElement","AUTHENTICATION","CHANGE","authenticated","deleteConsignment","mount","unmount","create_stripe_upe_customer_strategy","StripeIntegrationService","isMounted","checkoutEventsUnsubscribe","initCheckoutEventsSubscription","stripeInitializationOptions","stripe_integration_service_awaiter","paymentElement","PAYMENT","updateStripePaymentIntent","mountElement","stripeElement","mapAppearanceVariables","colorIcon","mapInputAppearanceRules","throwStripeError","throwDisplayableStripeError","isCancellationError","errorMessage","throwPaymentConfirmationProceedMessage","isPaymentCompleted","SUCCEEDED","mapStripePaymentData","returnUrl","shouldAllowRedisplay","mapStripeAddress","redirect","IF_REQUIRED","confirmParams","payment_method_data","allow_redisplay","billing_details","getShopperFullName","return_url","isAdditionalActionError","isRedirectAction","additionalAction","redirect_url","isOnPageAdditionalAction","getStripeJsVersion","DEFAULT_STYLES","DEFAULT_CONTAINER_STYLES","position","ROTATION_ANIMATION","LoadingIndicator","containerStyles","defineAnimation","buildContainer","indicator","buildIndicator","parentId","parent","opacity","hide","handleTransitionEnd","bottom","left","right","top","transition","setStyleAttribute","margin","transform","transformStyle","animation","attrs","k","setProperty","head","sheet","CSSStyleSheet","insertRule","AmountTransformer","toInteger","pow","expressCheckoutAllowedCountryCodes","StripeLinkV2CustomerStrategy","stripeIntegrationService","loadingIndicator","stripeocs","loadingContainerId","buttonHeight","_loadingIndicatorContainer","_onComplete","captureMethod","_captureMethod","_stripeClient","_mountExpressCheckoutElement","_initializeEvents","stripeExpressCheckoutClient","shouldRequireShippingAddress","_shouldRequireShippingAddress","expressCheckoutOptions","allowedShippingCountries","_getAvailableCountries","shippingRates","link","AUTO","applePay","NEVER","googlePay","amazonPay","klarna","cartAmount","elementsOptions","_toCents","_getCurrency","_linkV2Element","EXPRESS_CHECKOUT","SHIPPING_ADDRESS_CHANGE","stripe_link_v2_customer_strategy_awaiter","_onShippingAddressChange","SHIPPING_RATE_CHANGE","_onShippingRateChange","CONFIRM","_onConfirm","CANCEL","_onCancel","_getAvailableShippingOptions","_updateDisplayedPrice","shippingRate","_handleShippingOptionChange","_updateShippingAndBillingAddress","paymentPayload","_getPaymentPayload","_processAdditionalAction","billingDetails","_mapShippingAddress","_mapBillingAddress","additionalActionData","additional_action_required","_confirmStripePaymentOrThrow","_toggleLoadingIndicator","_completeCheckoutFlow","stripePaymentData","confirmationResult","confirmPayment","credit_card_token","confirm","Link","_getTotalPrice","_getStripeShippingOption","selectedId","recommendedId","_getAmountTransformer","_amountTransformer","amountTransformer","checkoutSessionEnabled","CHECKOUT_SESSION","OCS","create_stripe_link_v2_customer_strategy","stripeScriptLoader","OrderFinalizationNotRequiredError","NoPaymentDataRequiredPaymentStrategy","finalize","create_no_payment_strategy","AdyenV3ActionType","AdyenV2ActionType","AdyenComponentType","AdyenPaymentMethodType","HTTPMethod","ResultCode","AdyenCardFields","AdyenV2ScriptLoader","_stylesheetLoader","configuration","loadStylesheet","prepend","AdyenCheckout","isCardState","encryptedSecurityCode","encryptedExpiryMonth","isVaultedInstrument","instrumentId","AdyenV2PaymentStrategy","adyenv2","_paymentInitializeOptions","originKey","clientKey","paymentMethodsResponse","clientSideAuthentication","_adyenClient","translations","es","_paymentComponent","_mountPaymentComponent","CreditCard","Bancontact","_cardVerificationComponent","_mountCardVerificationComponent","adyenv2_payment_strategy_rest","shouldSetAsDefaultInstrument","_validateCardData","componentState","_componentState","encryptedCardNumber","encryptedExpiryYear","credit_card_number_confirmation","expiry_month","expiry_year","verification_value","bigpay_token","_getAdyenClient","_getPaymentInitializeOptions","_getThreeDS2ChallengeWidgetSize","additionalActionOptions","threeDS2Options","widgetSize","_handleAction","threeDS2ContainerId","onBeforeLoad","onLoad","adyenAction","additionalActionComponent","createFromAction","onAdditionalDetails","additionalActionState","paymentMethodType","ThreeDS2Challenge","QRCode","_mapAdyenPlaceholderData","prefillCardHolderName","street","houseNumberOrName","holderName","adyenClient","cardVerificationComponent","cardVerificationContainerId","SecuredFields","placeholder","caretColor","onChange","_updateComponentState","validateState","validateCardFields","onFieldValid","paymentComponent","ACH","IDEAL","SEPA","hasVaultedInstruments","AliPay","GiroPay","Sofort","Klarna","KlarnaPayNow","KlarnaAccount","Vipps","WeChatPayQR","provider_data","paymentError","cardComponent","componentRef","showValidation","isValid","issuer","props","_mapCardErrors","cardStateErrors","create_adyenv2_payment_strategy","__WEBPACK_EXTERNAL_MODULE__bigcommerce_script_loader_875b3e8f_getStylesheetLoader__","AdyenV3ScriptLoader","isHostedInstrumentLike","Adyenv3PaymentStrategy","adyenv3","paymentInitializeOptions","installmentOptions","paymentMethodsConfiguration","useKlarnaWidget","klarna_account","klarna_paynow","showInstallmentAmounts","_getLocale","showPayButton","adyenv3_payment_strategy_rest","submit","paymentToken","socialSecurityNumber","shopperName","isBoletoState","installments","plan","onActionHandled","componentType","challengeWindowSize","ThreeDS2","Sdk","_mountElement","_isOneyPaymentMethod","personalDetails","deliveryAddress","showBrandsUnderCardNumber","showEmailAddress","onSubmit","basePaymentData","tokenData","adyenComponent","_waitForMountContainer","maxAttempts","ceil","mountContainerMaxWaitMs","mountContainerPollIntervalMs","pollIntervalMs","step","poll","adyenv3_payment_strategy_awaiter","create_adyenv3_payment_strategy","AFFIRM_SCRIPTS","AffirmPaymentStrategy","affirmScriptLoader","affirm","initializeAffirmCheckout","checkout_token","getCheckoutInformation","open","onFail","failObject","successObject","ui","getOrder","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","taxTotal","first","last","full","zipcode","display_name","sku","unit_price","salePrice","qty","item_image_url","imageUrl","item_url","categories","getCategories","giftCertificates","listPrice","line","discountedAmount","discount_amount","discount_display_name","discountAmount","DISCOUNTED_AMOUNT","categoryTree","category","AffirmScriptLoader","affirmWindow","apikey","scriptURI","SANDBOX","PROD","m","g","n","h","p","getElementsByTagName","l","c","arguments","f","a1","c1","a2","c2","parentNode","insertBefore","public_api_key","script","create_affirm_payment_strategy","OrderFinalizationNotCompletedError","AfterpayPaymentStrategy","_afterpayScriptLoader","_mapCurrencyToISO2","withHttps","_afterpaySdk","applyStoreCredit","_loadPaymentMethod","validateCheckout","_redirectToAfterpay","forgetCheckout","loadPaymentMethods","AUD","NZD","CAD","USD","SCRIPTS_DEFAULT","SCRIPTS_US","AfterpayScriptLoader","_getScriptURI","isAfterpayWindow","AfterPay","HTTPS_SANDBOX","HTTPS_PROD","create_afterpay_payment_strategy","AmazonPayV2PaymentStrategy","_isReadyToPay","editButtonId","_bindEditButton","_isModalFlow","_createContainer","_amazonPayButton","_isOneTimeTransaction","_getAmazonPayButton","click","onFocus","isModalFlow","button","clone","cloneNode","replaceChild","_showLoadingSpinner","create_amazon_pay_v2_payment_strategy","apple_pay_payment_strategy_DefaultLabels","ApplePayPaymentStrategy","_storeCreditLabel","StoreCredit","storeCreditLabel","isStoreCreditApplied","storeCredit","apple_pay_payment_strategy_awaiter","create_apple_pay_payment_strategy","bigcommerce_payments_constants_LOADING_INDICATOR_STYLES","get_paypal_messages_styles_from_bnpl_config","messagesStyles","layout","logo","ratio","isBaseInstrument","BigCommercePaymentsPaymentStrategy","paypalSdkHelper","bannerContainerId","paypalBNPLConfiguration","bannerConfiguration","Messages","renderMessages","loadingIndicatorContainer","shouldRenderPayPalButtonOnInitialization","bigcommerce_payments_payment_strategy_rest","isPayPalVaultedInstrumentPaymentData","prepareVaultedInstrumentPaymentPayload","preparePaymentPayload","isProviderError","paypalOrderId","shouldConfirmInstrument","isTrustedVaultingFlow","checkoutPaymentButtonStyles","onRenderButton","onValidate","submitForm","handleClick","handleApprove","toggleLoadingIndicator","fieldsValues","getFieldsValues","getInstruments","findInstrument","paypalMessagesOptions","isBigCommercePaymentsProviderError","provider_error","create_bigcommerce_payments_payment_strategy","isPayPalFastlaneCustomer","BigCommercePaymentsFastlanePaymentStrategy","threeDSVerificationMethod","initializePayPalPaymentComponent","renderPayPalPaymentComponent","handlePayPalStoredInstrumentChange","orderRequest","bigcommerce_payments_fastlane_payment_strategy_rest","isVaultedFlow","isBigcommerceFastlaneRequestError","invalidRequestError","translationKey","getPaymentProviderCustomer","paypalFastlaneCustomer","paypalFastlaneSessionId","getBillingAddressOrThrow","cardComponentOptions","fields","prefill","enabled","paypalComponentMethods","getPayPalComponentMethodsOrThrow","isBigcommercePaymentsFastlaneThreeDSAvailable","is3dsEnabled","get3DSNonce","paypal_fastlane_token","getPaymentToken","is3DSEnabled","fastlaneToken","checkoutUrl","threeDomainSecureComponent","ThreeDomainSecureClient","threeDomainSecureParameters","threeDSRequested","Always","transactionContext","experience_context","cancel_url","isThreeDomainSecureEligible","liabilityShift","threeDSNonce","No","Unknown","Errored","Cancelled","Succeeded","Yes","Possible","paypalAxoSdk","selectionChanged","selectedCard","profile","showCardSelector","selectedInstrument","create_bigcommerce_payments_fastlane_payment_strategy","BigCommercePaymentsPayLaterPaymentStrategy","bigcommerce_payments_paylater_payment_strategy_rest","bigCommercePaymentsButtons","bigCommerceSdk","create_bigcommerce_payments_paylater_payment_strategy","TimeoutError","BigCommercePaymentsRatePayPaymentStrategy","pollingInterval","maxPollingIntervalTime","pollingTimer","stopPolling","bigcommerce_payments_ratepay","legalTextContainer","createFraudNetScript","loadFraudnetConfig","renderLegalText","bigcommerce_payments_ratepay_payment_strategy_rest","metadataId","guid","ratepayBirthDate","ratepayPhoneNumber","ratepayPhoneCountryCode","rate_pay","birth_date","normalizeDate","initializePollingMechanism","fraudNetScript","querySelectorAll","fraudNetConfig","deinitializePollingMechanism","legalTextContainerElement","date","formattedDate","formatDate","formattedMonth","getMonth","getFullYear","legalTextContainerElementId","legalTextContainerId","buttonContainer","buttonContainerParent","marginBottom","ratePayButton","Legal","PAY_UPON_INVOICE","resetPollingMechanism","scriptElement","generateGUID","s","i","floor","characters","reinitializeStrategy","resolvePromise","rejectPromise","orderStatus","useMetadata","isOrderApproved","PollingStop","isPollingError","PollingError","create_bigcommerce_payments_ratepay_payment_strategy","HostedFieldType","hosted_field_type","isCreditCardFormFields","CardNumber","CardName","CardExpiry","isCreditCardVaultedFormFields","CardNumberVerification","CardCodeVerification","CardExpiryVerification","BigCommercePaymentsCreditCardsPaymentStrategy","bigcommerce_payments_creditcards","bigCommercePaymentsInitializationOptions","form","onCreditCardFieldsRenderingError","onLoadComplete","hostedFormOptions","isCreditCardForm","isCreditCardVaultedForm","hasUndefinedValues","initializeFields","shouldInitializePayPalFastlane","initializePayPalFastlaneOrThrow","bigcommerce_payments_credit_cards_payment_strategy_rest","executionPaymentData","validateHostedFormOrThrow","submitHostedForm","getInstrumentParams","returnedOrderId","submitPaymentPayload","returnedVaultedToken","cvvField","expiryField","numberField","nameField","verification_nonce","card_with_order","formOptions","executeCallback","getExecuteCallback","cardFieldsConfig","getInputStyles","vaultSetupToken","inputEvents","onChangeHandler","onFocusHandler","onBlur","onBlurHandler","onInputSubmitRequest","cardFields","CardFields","stylizeInputContainers","renderFields","renderVaultedFields","createVaultSetupTokenCallback","createOrderCallback","createVaultSetupToken","bigcommerce_payments_credit_cards_payment_strategy_awaiter","fieldsOptions","getCardFieldsOrThrow","cardCode","CVVField","cardExpiry","ExpiryField","cardName","NameField","cardNumber","NumberField","cardCodeVerification","cardExpiryVerification","cardNumberVerification","getFieldTypeByEmittedField","emittedBy","mapFieldType","submitConfig","cardFieldsState","validationData","getValidityData","mapValidationErrors","updatedFields","cardNameField","fieldsKeys","every","fieldsErrors","getInvalidErrorByFieldType","CardCode","validationErrors","commonStyles","fontWeight","outline","background","marginLeft","onEnter","bigCommercePaymentsPaymentProviderCustomer","isBigCommercePaymentsAnalyticsV2Enabled","connectClientToken","payPalFastlaneSdk","create_bigcommerce_payments_credit_cards_payment_strategy","BigCommercePaymentsAlternativeMethodsPaymentStrategy","bigCommercePaymentsSdkHelper","isPollingEnabled","bigcommerce_payments_apms","bigCommercePaymentsAlternativeMethods","shouldRenderFields","bigcommerce_payments_alternative_methods_payment_strategy_rest","isNonInstantPaymentMethod","bigCommercePaymentsButton","Approved","deInitializePollingMechanism","paypalAmpsSdk","getPaypalAmpsSdkOrThrow","buttonStyle","onInitButton","onCreateOrder","handleFailure","bigcommerce_payments_alternative_methods_payment_strategy_awaiter","apmFieldsContainer","apmFieldsStyles","fieldContainerElement","PaymentFields","create_bigcommerce_payments_alternative_methods_payment_strategy","BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy","bigcomemrce_payments_redirect_alternative_methods_payment_strategy_rest","isRedirectError","redirectUrl","create_bigcommerce_payments_redirect_alternative_methods_payment_strategy","BigCommercePaymentsVenmoPaymentStrategy","bigcommerce_payments_venmo_payment_strategy_rest","create_bigcommerce_payments_venmo_payment_strategy","BlueSnapDirect3ds","blueSnapSdk","_blueSnapSdk","initialize3ds","cardData","_getBlueSnapSdk","threeDsPaymentsSetup","sdkResponse","threeDSecureReferenceId","threeDsPaymentsSubmitData","isHostedCardFieldOptionsMap","isHostedStoredCardFieldOptionsMap","BlueSnapDirectCardType","BlueSnapDirectEventOrigin","BlueSnapDirectErrorDescription","BlueSnapDirectErrorCode","BlueSnapDirectHostedFieldTagId","BlueSnapDirectCreditCardPaymentStrategy","_blueSnapDirectHostedForm","_blueSnapDirect3ds","_paymentFieldsToken","_shouldUseHostedFields","_getPaymentFieldsToken","pfToken","bluesnapSubmitedForm","_getBlueSnapDirectThreeDSecureData","getCardInstrumentOrThrow","previouslyUsedCard","last4Digits","ccType","cardHolderName","billingFirstName","billingLastName","billingCountry","billingCity","billingZip","shippingFirstName","shippingLastName","shippingCountry","shippingCity","shippingZip","BlueSnapHostedFieldType","CREDIT_CARD_ERRORS","empty","invalid","BlueSnapDirectHostedForm","_nameOnCardInput","_hostedInputValidator","initializeValidationFields","paymentFieldsToken","enable3DS","callbacksAndStyles","bluesnap_direct_hosted_form_rest","_onValidate","_setCustomBlueSnapAttributes","_setCustomStoredCardsBlueSnapAttributes","_getHostedPaymentFieldsOptions","hostedPaymentFieldsCreate","accessibilityLabel","threeDSecureData","shouldSendName","hostedPaymentFieldsSubmitData","_isBlueSnapDirectCallbackError","THREE_DS_AUTH_FAILED","errorDescription","getValue","onCardTypeChange","onFieldEventHandler","setupComplete","_usetUiEventCallback","_handleError","onType","_tagId","onValid","tagId","ccnPlaceHolder","cvvPlaceHolder","expPlaceHolder","_mapStyles","focus","selector","declaration","declarationBlock","property","__WEBPACK_EXTERNAL_MODULE_lodash_kebabCase__","errorCode","eventOrigin","INVALID_OR_EMPTY","EMPTY","INVALID","isBlueSnapDirectInputValidationErrorDescription","cardNumberContainer","cardExpiryContainer","cardCodeContainer","cardNameContainer","dataset","bluesnap","BlueSnapHostedInputValidator","_errors","_updateErrors","errorData","BluesnapDirectNameOnCardInput","_style","_create","_getInput","_handleFocus","_handleBlur","_handleEnter","_input","_applyStyles","HTMLInputElement","ON_BLUR","allowedStyle","styleKeys","_configureInput","autocomplete","inputMode","BlueSnapDirectSdkEnv","BlueSnapDirectScriptLoader","PRODUCTION","create_bluesnap_direct_credit_card_payment_strategy","BlueSnapDirectAPMPaymentStrategy","_formatePaymentPayload","_isBlueSnapDirectRedirectResponse","providerData","frameUrl","partialValue","merchantid","isBlueSnapDirectRedirectResponseProviderData","providerDataQuery","ecp","account_number","accountNumber","account_type","accountType","shopper_permission","shopperPermission","routing_number","routingNumber","companyName","company_name","sepa_direct_debit","iban","isIdealInstrument","ideal","bic","isPayByBankInstrument","pay_by_bank","partialResponse","partialBody","create_bluesnap_direct_apm_payment_strategy","PaymentStatusTypes","payment_status_types","BlueSnapV2PaymentStrategy","_initializeOptions","frame","_createIframe","initializeOffsitePayment","getPaymentStatus","ACKNOWLEDGE","FINALIZE","finalizeOrder","bluesnapv2","create_bluesnapv2_payment_strategy","AnalyticsExtraItemsManager","storage","saveExtraItemsData","productId","categoryNames","getStorageKey","readExtraItemsData","getItem","itemsData","hasNotExtraItems","isExtraItemsData","clearExtraItemData","removeItem","isAnalyticsTrackerWindow","isWithAccountCreation","BoltError","getError","BoltPaymentStrategy","analyticsExtraItemsManager","useBoltClient","useBoltEmbedded","onPaymentSelect","useBigCommerceCheckout","boltEmbedded","mountBoltEmbeddedField","embeddedField","setExtraItemsForAnalytics","bolt_payment_strategy_rest","isBoltPaymentData","getBoltClientPaymentPayload","getBoltEmbeddedPaymentPayload","getBoltFullCheckoutPaymentPayload","orderToken","boltTransaction","success","transaction","reference","configure","tokenizeResult","validateTokenizeResultOrThrow","last_four_digits","expiration_month","expiration","expiration_year","create_account","shouldCreateAccount","embedded_checkout","setBoltOrderId","transactionReference","getTransactionReference","getBoltEmbeddedOrThrow","setOrderId","renderSeparateFields","lastFourDigits","expirationMonth","expirationYear","isNaN","isAnalyticsEnabled","create_bolt_payment_strategy","__WEBPACK_EXTERNAL_MODULE_local_storage_fallback_5dc95480_default__","isUsBankAccountInstrumentLike","BraintreeAchPaymentStrategy","braintreeach","getMandateText","handleBraintreeError","braintree_ach_payment_strategy_rest","isSubmittingWithVaultingInstrument","tokenizePaymentForVaultedInstrument","preparePaymentDataForVaultedInstrument","preparePaymentData","getUsBankAccountOrThrow","mandateText","bankDetails","getBankDetails","isVaultingEnabled","tokenized_bank_account","masked_account_number","ownershipType","businessName","create_braintree_ach_payment_strategy","create_braintree_sdk","BraintreeMessages","messagingContainer","bannedId","CART","removeAttribute","getPaypalMessagesStylesFromBNPLConfig","Overlay","closeElement","mainElement","_createElements","_element","_closeElement","_mainElement","_registerClick","_unregisterClick","_removeAfterTransition","transitionDuration","hasCloseButton","innerHtml","classLayout","classClose","classOverlayText","overlayText","addClassLayout","innerText","getOverlayStyle","_addEventListener","_removeEventListener","onClickClose","handleTransition","propertyName","braintree_paypal_constants_LOADING_INDICATOR_STYLES","is_braintree_error_isBraintreeError","BraintreePaypalPaymentStrategy","braintreeMessages","braintreeOptions","braintreeButtonOptions","loadPaypalCheckoutInstance","braintree_paypal_payment_strategy_rest","braintreeTokenizePayload","getOutstandingBalance","vaultPaymentInstrument","paymentMethodId","shouldShowPayPalCreditBanner","renderPayPalMessages","onPaymentError","getSmartButtonContainerId","braintree_paypal_payment_strategy_awaiter","tokenizePaymentOrThrow","isBraintreePaypalProviderError","create_braintree_paypal_payment_strategy","BraintreeRequestSender","BraintreeLocalMethodsPaymentStrategy","braintreeRequestSender","isLPMsUpdateExperimentEnabled","braintreelocalmethods","braintree_local_methods_payment_strategy_rest","executeWithNotInstantLPM","executeWithInstantLPM","basicPaymentData","getLPMsBasicPaymentData","isBraintreeRedirectError","startPayment","getInstantLPMConfig","getInstantLPMCallback","paymentType","fallback","buttonText","onPaymentStart","start","braintree_local_methods_payment_strategy_awaiter","paymentId","isBraintreeOrderSavedResponse","order_id_saved_successfully","startPaymentError","payloadData","isOrderPending","Pending","Completed","Failed","create_braintree_local_methods_payment_strategy","isBraintreeAcceleratedCheckoutCustomer","BraintreeFastlanePaymentStrategy","isThreeDSExperimentEnabled","initializeCardComponent","renderBraintreeCardComponent","handleBraintreeStoredInstrumentChange","braintree_fastlane_payment_strategy_rest","braintreeCardComponent","paypalPaymentComponent","getBraintreeCardComponentOrThrow","getPayPalInstruments","threeDSToken","mapToPayPalAddress","binGuest","verifyError","braintreePaymentProviderCustomer","braintreeFastlaneCustomer","selectedInstruments","create_braintree_fastlane_payment_strategy","BraintreeVisaCheckoutPaymentStrategy","visaCheckoutSdk","braintree_visa_checkout_payment_strategy_rest","create_braintree_visa_checkout_payment_strategy","BraintreeVenmoPaymentStrategy","venmoOptions","braintreevenmo","initializeBraintreeVenmo","braintree_venmo_payment_strategy_rest","isBraintreeVenmoWebFallbackSupport","mobileWebFallBack","braintreeVenmoTokenize","create_braintree_venmo_payment_strategy","BraintreeCreditCardPaymentStrategy","braintreeHostedForm","isHostedPaymentFormEnabled","unsupportedCardBrands","isHostedFormInitialized","shouldInitializeBraintreeFastlane","braintree_credit_card_payment_strategy_rest","prepareHostedPaymentData","isPaymentMethodInitialized","commonPaymentData","isSubmittingWithStoredCard","shouldPerform3DSVerification","tokenizeForStoredCardVerification","verifyCardWithHostedForm","prepareAdditionalActionPaymentData","storedCreditCardNonce","isBraintreePaymentRequest3DSError","newPaymentData","isHostedFormEnabled","braintreeCustomer","isBraintreeFormFieldsMap","isBraintreeHostedFormError","invalidFieldKeys","BraintreeHostedFormType","BraintreeHostedForm","isInitializedHostedForm","handleBlur","mapErrors","handleFocus","handleCardTypeChange","cards","handleInputSubmitRequest","handleValidityChange","isValidForm","StoredCardVerification","mapFieldOptions","createHostedFields","mapStyleOptions","mapBillingAddress","mapTokenizeError","hostedFields","hostedFieldsOptions","preventCursorJumps","supportedCardBrands","cardBrand","is_braintree_supported_card_brand","internalLabel","mapStyles","isValidParam","isEmpty","isPotentiallyValid","fieldKey","createInvalidError","isStoredCard","createRequiredError","formFields","create_braintree_credit_card_payment_strategy","CreditCardPaymentStrategy","_isHostedPaymentFormEnabled","_shouldRenderHostedForm","_executeWithHostedForm","_executeWithoutHostedForm","_isHostedFieldAvailable","paymentSettings","bigpayBaseUrl","createHostedForm","_hostedForm","credit_card_payment_strategy_rest","__WEBPACK_EXTERNAL_MODULE_lodash_values__","CBAMPGSPaymentStrategy","cbaMGPSScriptLoader","isTestModeFlagEnabled","isCBAMPGSPaymentMethodLike","threeDSjs","isConfigured","wsVersion","retryState","storeId","transactionId","initiateAuthentication","msg","gatewayRecommendation","restApiResponse","authenticationStatus","authenticatePayer","attempt","cba_mpgs_payment_strategy_awaiter","cause","fullScreenRedirect","CBAMPGSScriptLoader","ThreeDS","create_cba_mpgs_payment_strategy","AdditionalActionType","CheckoutComCustomPaymentStrategy","checkoutcom_custom_payment_strategy_rest","_processResponse","loadCurrentOrder","additionalActionRequired","OffsiteRedirect","_performRedirect","CheckoutComFawryPaymentStrategy","checkoutcom_fawry_payment_strategy_rest","_createFormattedPayload","fawryPaymentData","customerMobile","create_checkoutcom_fawry_payment_strategy","isThreeDSecureRequiredError","CheckoutComCreditCardPaymentStrategy","checkoutcom_credit_card_payment_strategy_rest","_handleThreeDSecure","callback_url","PaReq","TermUrl","MD","create_checkoutcom_credit_card_payment_strategy","CheckoutComSEPAPaymentStrategy","checkoutcom_sepa_payment_strategy_rest","create_checkoutcom_sepa_payment_strategy","CheckoutComiDealPaymentStrategy","checkoutcom_ideal_payment_strategy_rest","create_checkoutcom_ideal_payment_strategy","DOCUMENT_SUPPORTED_APMS","CheckoutComAPMPaymentStrategy","checkoutcom_apm_payment_strategy_rest","ccDocument","create_checkoutcom_apm_payment_strategy","ClearpayPaymentStrategy","_clearpayScriptLoader","_clearpaySdk","_isCountrySupported","_redirectToClearpay","ClearpayScriptLoader","_getScriptUrl","httpsEnabled","create_clearpay_payment_strategy","create_credit_card_payment_strategy","CardinalThreeDSecureFlow","_cardinalClient","prepare","_getClientToken","hostedForm","getCardInstrument","getBin","runBinProcess","__WEBPACK_EXTERNAL_MODULE_lodash_merge__","getThreeDSecureData","_getOrderData","CardinalSignatureValidationErrors","CardinalEventType","CardinalInitializationType","CardinalValidatedAction","CardinalPaymentType","CardinalTriggerEvents","CardinalPaymentBrand","CardinalSignatureVerification","CardinalClient","_provider","_testMode","_configurationToken","_sdk","_getClientSDK","SetupCompleted","off","Validated","ActionCode","ErrorNumber","ErrorDescription","setup","Init","jwt","binNumber","BinProcess","Status","orderData","Success","NoAction","Payment","ExtendedData","SignatureVerification","Failure","continueObject","AcsUrl","Payload","partialOrder","_mapToPartialOrder","continue","CCA","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","CardinalScriptLoader","Cardinal","CyberSourcePaymentStrategy","_threeDSecureFlow","create_cybersource_payment_strategy","CardinalThreeDSecureFlowV2","xid","_getBin","_submitPayment","threeDsResult","threeDsToken","isCreditCardInstrument","hostedFormBin","CyberSourceV2PaymentStrategy","create_cybersourcev2_payment_strategy","isAdditionalActionRequiredErrorResponse","GooglePayAdyenV2","googlePayToken","GooglePayPaymentStrategy","_isDeinitializationBlocked","_loadingIndicator","walletButton","google_pay_payment_strategy_rest","extraData","_clickListener","google_pay_payment_strategy_awaiter","_isDirectPayOnClickEnabled","_interactWithPaymentSheetAndPay","_toggleBlockDeinitialization","isGooglePayDontOverrideAddresssExperimentOn","freshPaymentMethod","_getIsSignedInOrThrow","_handleOfferTrigger","isSignedIn","isBlocked","create_google_pay_adyenv2_payment_strategy","GooglePayAdyenV3","create_google_pay_adyenv3_payment_strategy","create_google_pay_authorizenet_payment_strategy","create_google_pay_checkoutcom_payment_strategy","create_google_pay_cybersource_payment_strategy","create_google_pay_orbital_payment_strategy","create_google_pay_stripe_payment_strategy","create_google_pay_worldpayaccess_payment_strategy","create_google_pay_braintree_payment_strategy","ConfirmOrderStatus","types_PayPalCommerceIntent","GooglePayPaypalCommercePaymentStrategy","_payPalCommerceSdk","getOrderId","confirmOrderData","confirmOrder","payPalSDK","PayerActionRequired","initiatePayerAction","create_google_pay_paypal_commerce_payment_strategy","types_ConfirmOrderStatus","types_BigCommercePaymentsIntent","GooglePayBigCommercePaymentsPaymentStrategy","_payPalSdkHelper","create_google_pay_bigcommerce_payments_payment_strategy","create_google_pay_tdonlinemart_payment_strategy","PaymentExecuteError","HummPaymentStrategy","humm_payment_strategy_rest","processable","isOffsiteRedirectResponse","handleOffsiteRedirectResponse","create_humm_payment_strategy","supportedCountries","supportedCountriesRequiringStates","KlarnaPaymentStrategy","klarnaScriptLoader","klarnaCredit","unsubscribe","loadWidget","klarna_payment_strategy_rest","authorization_token","authorizationToken","authorize","initializePayment","client_token","getUpdateSessionData","mapToKlarnaAddress","needsStateCode","klarnaAddress","street_address","family_name","street_address2","updateSessionData","res","approved","show_form","KlarnaScriptLoader","klarnaWindow","Credit","create_klarna_payment_strategy","KlarnaV2PaymentStrategy","klarnav2ScriptLoader","klarnav2TokenUpdater","klarnaPayments","loadPaymentsWidget","klarnav2_payment_strategy_rest","klarnaMultipleRadioButton","klarnaOrderInitialization","isKlarnaMultipleRadioButtonEnabled","authorizeOrThrow","klarnav2","updateClientToken","payment_method_category","enableBillie","organization_name","KlarnaV2ScriptLoader","Payments","KlarnaV2TokenUpdater","create_klarnav2_payment_strategy","LegacyPaymentStrategy","create_legacy_payment_strategy","MolliePaymentMethodType","methodsNotAllowedWhenDigitalOrder","MolliePaymentStrategy","mollieScriptLoader","mollie","controllers","__WEBPACK_EXTERNAL_MODULE_lodash_each__","controller","initializeOptions","isCreditCard","shouldShowTSVHostedForm","mountCardVerificationfields","mollieClient","loadMollieJs","mountElements","disableButton","loadPaymentMethodsAllowed","mollie_payment_strategy_rest","executeWithVaulted","executeWithCC","executeWithAPM","cardHolderElement","cardNumberElement","verificationCodeElement","expiryDateElement","getMollieClient","createToken","shopper_locale","getShopperLocale","CREDIT_CARD","isHostedFieldAvailable","mollie_payment_strategy_awaiter","getInitializeOptions","testmode","cardNumberId","cardCvcId","cardExpiryId","cardHolderId","createComponent","cartDigitalItems","paragraph","unsupportedMethodMessage","MollieScriptLoader","mollieHostWindow","isMollieWindow","Mollie","create_mollie_payment_strategy","moneris_payment_strategy_IFRAME_NAME","MonerisPaymentStrategy","moneris","monerisOptions","profileId","createIframe","moneris_payment_strategy_rest","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","__WEBPACK_EXTERNAL_MODULE_lodash_map__","allow","monerisResponse","responseCode","dataKey","create_moneris_payment_strategy","OfflinePaymentStrategy","create_offline_payment_strategy","OffsitePaymentStrategy","offsite_payment_strategy_rest","orderPayload","_shouldSubmitFullPayload","create_offsite_payment_strategy","utils_get_paypal_messages_styles_from_bnpl_config","PayPalCommercePaymentStrategy","payPalSdkScriptLoader","paypal_commerce_payment_strategy_rest","isRedirectActionError","isPaypalCommerceAppSwitchEnabled","isPaypalProviderError","create_paypal_commerce_payment_strategy","PayPalCommerceCreditPaymentStrategy","paypalOptions","paypal_commerce_credit_payment_strategy_rest","create_paypal_commerce_credit_payment_strategy","PayPalCommerceVenmoPaymentStrategy","paypal_commerce_venmo_payment_strategy_rest","create_paypal_commerce_venmo_payment_strategy","paypal_commerce_constants_LOADING_INDICATOR_STYLES","PayPalCommerceAlternativeMethodsPaymentStrategy","isOrderApprovedProcessing","paypalcommercealternativemethods","paypal_commerce_alternative_methods_payment_strategy_rest","paypal_commerce_alternative_methods_payment_strategy_awaiter","OXXO","bcOrderId","create_paypal_commerce_alternative_methods_payment_strategy","PayPalCommerceCreditCardsPaymentStrategy","paypalcommercecreditcards","paypalCommerceInitializationOptions","paypal_commerce_credit_cards_payment_strategy_rest","paypal_commerce_credit_cards_payment_strategy_awaiter","paypalCommercePaymentProviderCustomer","isPayPalCommerceAnalyticsV2Enabled","create_paypal_commerce_credit_cards_payment_strategy","PaypalCommerceRatepayPaymentStrategy","paypalCommerceService","paypalcommerceratepay","paypal_commerce_ratepay_payment_strategy_rest","create_paypal_commerce_ratepay_payment_strategy","is_paypal_fastlane_customer_isPayPalFastlaneCustomer","PaypalCommerceFastlanePaymentStrategy","paypal_commerce_fastlane_payment_strategy_rest","isPaypalFastlaneRequestError","create_paypal_commerce_fastlane_payment_strategy","paypal_express_types_PaypalButtonStyleLayoutOption","paypal_express_types_PaypalButtonStyleSizeOption","paypal_express_types_PaypalButtonStyleColorOption","paypal_express_types_PaypalButtonStyleLabelOption","paypal_express_types_PaypalButtonStyleShapeOption","paypal_express_types_PaymentStatusTypes","PaypalExpressPaymentStrategy","useRedirectFlow","paypalexpress","isInContextEnabled","loadPaypalSDK","closeFlow","isAcknowledgedOrFinalized","getPaymentRedirectUrl","initXO","startFlow","PaypalScriptLoader","create_paypal_express_payment_strategy","PaypalProPaymentStrategy","threeDSecureFlow","create_paypal_pro_payment_strategy","SagePayPaymentStrategy","_isThreeDSTwoExperimentOn","create_sage_pay_payment_strategy","ExternalPaymentStrategy","external_payment_strategy_rest","_isAdditionalActionRequired","SezzlePaymentStrategy","create_sezzle_payment_strategy","SquareIntent","SquareV2PaymentProcessor","applicationId","locationId","square","_payments","_formValidationSubscription","_card","destroy","initializeCard","onValidationChange","_getPayments","_subscribeToFormValidation","_getCard","verifyBuyer","CHARGE","_chargeVerifyBuyer","_storeVerifyBuyer","blacklist","Set","eventObservables","currentState","isCompletelyValid","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_distinctUntilChanged__","_mapToSquareBillingContact","STORE","SquareV2PaymentStrategy","_squareV2PaymentProcessor","squarev2","_getVaultedInstrumentPayload","_getCardPayload","shouldVerify","cardTokenizationResult","isSquareV2ApiV2Enabled","tokenForSavingCard","store_card_nonce","store_card_token","verificationToken","_getSquareCardIdOrThrow","three_d_secure","SquareV2WebPaymentsSdkEnv","SquareV2ScriptLoader","LIVE","isSquareV2Window","assertSquareV2Window","Square","create_squarev2_payment_strategy","isIndividualCardElementOptions","individualCardElementOptions","cardNumberElementOptions","cardCvcElementOptions","cardExpiryElementOptions","IconStyle","stripev3_StripeElementType","stripev3_StripePaymentMethodType","StripeV3ErrorType","StripeV3Error","AuthFailure","APM_REDIRECT","Alipay","StripeV3PaymentStrategy","stripev3","isDeinitialize","useIndividualCardFields","allowRedisplayForStoredInstruments","_allowRedisplayForStoredInstruments","stripeV3Client","mountCardVerificationFields","mountCardFields","stripev3_payment_strategy_rest","shouldSubmitOrderBeforeLoadingAPM","confirmStripePayment","buildPaymentPayload","handleEmptyPaymentIntentError","unmountElement","isAuthError","getStripeJs","confirmAlipayPayment","handleActions","confirmIdealPayment","Sepa","confirmSepaDebitPayment","getStripeCardElements","getStripeElement","mapStripeBillingDetails","createPaymentMethod","stripeCardElements","zipCodeElementOptions","isBillingAddressLike","stripePaymentMethodType","cardExpiryElement","cardCvcElement","CardCvc","needsConfirm","StripeV3ScriptLoader","create_stripev3_payment_strategy","supportedLocales","ar","bg","cs","da","el","en","et","fi","fil","fr","he","hr","hu","it","ja","ko","lt","lv","ms","mt","nb","nl","pl","pt","ro","ru","sk","sl","sv","th","tr","vi","zh","formatLocale","localeLanguage","countryLocales","formattedLocale","StripeUPEPaymentStrategy","_loadStripeElement","stripe_upe_payment_strategy_rest","_stripeUPEClient","_executeWithVaulted","_executeWithStripeConfirmation","_processAdditionalActionWithStripeConfirmation","_processVaultedAdditionalAction","initStripeElementUpdateTrigger","enableLink","_loadStripeJs","_isStripeElementUpdateEnabled","wallets","_getStripeElementTerms","READY","_updateStripeLinkStateByElementType","_updateStripeElement","sendSecondPaymentRequestOnStripeError","paymentPayloadWithError","client_side_error","shouldShowTerms","terms","paymentElementType","isStripeLinkElementType","create_stripe_upe_payment_strategy","isStripePaymentEvent","StripeOCSPaymentStrategy","_initializeStripeElement","stripe_ocs_payment_strategy_rest","customerSessionToken","fonts","paymentMethodSelect","handleClosePaymentMethod","togglePreloader","customerSessionClientSecret","savePaymentMethod","maxVisiblePaymentMethods","LOADER_START","_onStripeElementChange","_collapseStripeElement","collapse","paymentMethodOptions","us_bank_account","_shouldSaveInstrument","tokenizedOptions","_getTokenizedOptions","selectedMethodId","client_secret","paymentIntentClientSecret","payment_method_options","collapsed","setupFutureUsage","setup_future_usage","ON_SESSION","OFF_SESSION","tokenized_ach","create_stripe_ocs_payment_strategy","StripeCSPaymentStrategy","_initStripeCheckoutSession","_updateStripeShopperData","_initializePaymentElement","_initializeAdaptivePricingElement","stripe_cs_payment_strategy_rest","_updateCheckoutSessionData","getPaymentElement","currencySelectorElement","getCurrencySelectorElement","adaptivePricing","allowed","adaptivePricingEnabled","_getStripeElement","_getStripeActionsOrThrow","createPaymentElement","newVaultedStripeInstrument","existingStripeSavedPaymentMethods","_getStripeSavedPaymentMethodsOrThrow","session","_confirmStripePayment","newStripeSavedPaymentMethods","checkoutSessionId","checkoutSessionStatus","_getNewVaultedStripeInstrument","paymentStatus","Paid","stripeActions","_updateStripeEmail","_updateStripeShippingAddress","_updateStripeBillingAddress","updateEmail","savedPaymentMethods","existingMethod","currencySelectorContainerId","_getCurrencySelectorElement","_initAdaptivePricingEvents","createCurrencySelectorElement","stripe_cs_payment_strategy_awaiter","stripeCurrencyCode","isCustomerCurrencySelected","customerCurrency","create_stripe_cs_payment_strategy","FieldType","TDOnlineMartPaymentStrategy","tdOnlineMartScriptLoader","tdInputs","CARD_NUMBER","CVV","EXPIRY","tdOnlineMartClient","loadTDOnlineMartJs","mountHostedFields","td_online_mart_payment_strategy_rest","getPaymentPayloadOrThrow","processWithAdditionalAction","inputElement","digitalItemsInCart","shouldAddVerificationToken","isTrustedVaultingInstrument","getTokenOrThrow","throwTokenizationError","getHostedFieldsOptions","getTDOnlineMartClientOrThrow","inputId","isTdOnlineMartAdditionalAction_isTdOnlineMartAdditionalAction","isCreateTokenError","classes","TDOnlineMartScriptLoader","tdOnlineMartWindow","customcheckout","create_td_online_mart_payment_strategy","PAYMENT_CANNOT_CONTINUE","worldpayaccess_payment_strategy_submit","WorldpayAccessPaymentStrategy","worldpay","_submitAdditionalAction","messageEventListener","worldpayaccess_payment_strategy_awaiter","_isValidJsonWithSessionId","iframeHidden","SessionId","submitError","onLoadError","_createHiddenIframe","formId","inputBin","source_id","inputJWT","match","srcdoc","outerHTML","str","create_worldpayaccess_payment_strategy","WorldpayAccessOpenBankingPaymentStrategy","_buildOpenBankingSubmitPayment","_isWorldpayAccessRedirectResponse","open_banking","create_worldpayaccess_open_banking_payment_strategy","StorefrontPaymentRequestSender","saveExternalId","externalId","ZipPaymentStrategy","storefrontPaymentRequestSender","zip_payment_strategy_rest","_prepareForReferredRegistration","create_zip_payment_strategy","CountryActionType","OrderActionType","CountryActionCreator","_countryRequestSender","loadCountries","LoadCountriesRequested","LoadCountriesSucceeded","LoadCountriesFailed","CountryRequestSender","CartConsistencyError","CartStockPositionsChangedError","changedItemIds","OrderTaxProviderUnavailableError","MissingShippingMethodError","InvalidShippingAddressError","OrderRequestSender","loadOrder","checkoutVariant","SpamProtectionNotCompletedError","PaymentMethodActionType","OrderActionCreator","_orderRequestSender","_checkoutValidator","LoadOrderRequested","LoadOrderSucceeded","LoadOrderFailed","loadOrderPayments","LoadOrderPaymentsRequested","LoadOrderPaymentsSucceeded","LoadOrderPaymentsFailed","_getCurrentOrderId","SubmitOrderRequested","externalSource","getExternalSource","variantIdentificationToken","getVariantIdentificationToken","shouldExecuteSpamCheck","_mapToOrderRequestBody","customerMessage","SubmitOrderSucceeded","SubmitOrderFailed","FinalizeOrderRequested","FinalizeOrderSucceeded","FinalizeOrderFailed","order_action_creator_rest","createPaymentClient","paymentClient","__WEBPACK_EXTERNAL_MODULE__bigcommerce_bigpay_client_fce6db19_createClient__","setHost","isPaymentMethod","PaymentMethodActionCreator","loadPaymentMethodsById","methodIds","LoadPaymentMethodsRequested","payment_method_action_creator_awaiter","LoadPaymentMethodsSucceeded","LoadPaymentMethodsFailed","sessionHash","methods","LoadPaymentMethodRequested","LoadPaymentMethodSucceeded","LoadPaymentMethodFailed","payment_method_action_creator_decorate","PaymentMethodRequestSender","order_finalization_not_required_error_OrderFinalizationNotRequiredError","PaymentStrategyActionType","PaymentStrategyType","payment_strategy_type","PaymentStrategyWidgetActionCreator","PaymentStrategyActionCreator","_orderActionCreator","_paymentStrategyWidgetActionCreator","isPaymentDataRequired","NO_PAYMENT_DATA_REQUIRED","FinalizeRequested","_loadOrderPaymentsIfNeeded","payment_strategy_action_creator_awaiter","FinalizeSucceeded","FinalizeFailed","paymentStrategies","getByMethod","CartComparator","cartA","cartB","_normalize","itemA","itemB","variantId","localeCompare","extendedSalePrice","recipient","giftWrapping","CartChangedError","previous","updated","CheckoutValidator","comparator","_compareCoupons","_compareGiftCertificates","_getComparableCheckout","couponsA","couponsB","giftCertificatesA","giftCertificatesB","BrowserStorage","_namespace","rawValue","withNamespace","getItemOnce","CardingProtectionChallengeNotCompletedError","CardingProtectionFailedError","HostedFieldEventType","HostedInputEventType","PaymentHumanVerificationHandler","handle","errorOrId","handleWithRecaptchaSitekey","handleWithPaymentHumanVerificationRequestError","_isPaymentHumanVerificationRequest","_initialize","_performRecaptcha","payment_human_verification_handler_awaiter","human_verification_token","cardingProtectionElementId","cardingProtectionElement","mapFromPaymentErrorResponse","joinErrors","InvalidHostedFormConfigError","InvalidHostedFormError","InvalidHostedFormValueError","__WEBPACK_EXTERNAL_MODULE_lodash_flatMap__","fieldErrors","HostedField","_type","_placeholder","_accessibilityLabel","_styles","_eventPoster","_eventListener","_detachmentObserver","_checkoutId","_cardInstrument","overflow","getType","hosted_field_awaiter","AttachRequested","cardInstrument","fontUrls","_getFontUrls","AttachSucceeded","AttachFailed","SubmitRequested","SubmitSucceeded","SubmitFailed","_isSubmitErrorEvent","submitStoredCardForm","StoredCardRequested","StoredCardSucceeded","StoredCardFailed","validateForm","ValidateRequested","family","PaymentActionType","HostedForm","_fields","_payloadTransformer","_eventCallbacks","_paymentHumanVerificationHandler","hosted_form_awaiter","Blurred","CardTypeChanged","Focused","Entered","_cardType","BinChanged","_bin","getCardType","_getFirstField","otherFields","__WEBPACK_EXTERNAL_MODULE_lodash_without__","otherField","submitStoredCard","is_vaulted_instrument_isVaultedInstrument","HostedFormOrderDataTransformer","getConfig","instrumentMeta","getInstrumentsMeta","orderMeta","getOrderMeta","paymentMethodMeta","getPaymentMethodsMeta","authToken","vaultAccessToken","HostedFormFactory","fieldOptions","_getCardInstrument","__WEBPACK_EXTERNAL_MODULE_lodash_pick__","MissingPaymentInstrument","PaymentActionCreator","_paymentRequestSender","_paymentRequestTransformer","InitializeOffsitePaymentRequested","InitializeOffsitePaymentSucceeded","InitializeOffsitePaymentFailed","SubmitPaymentRequested","payment_action_creator_awaiter","SubmitPaymentSucceeded","SubmitPaymentFailed","PaymentRequestSender","_client","_transformResponse","statusText","mapToInternalAddress","addressId","is_billing_address_like_isBillingAddressLike","province","provinceCode","postCode","couponTypes","mapToInternalCoupon","discount","discountType","couponType","mapToInternalGiftCertificate","used","remainingBalance","remaining","balance","purchaseDate","mapToDiscountNotifications","promotions","notifications","promotion","banners","banner","placeholders","messageHtml","mapToInternalLineItems","itemMap","idKey","amountAfterDiscount","integerAmountAfterDiscount","integerUnitPrice","integerUnitPriceAfterDiscount","integerDiscount","sender","mapGiftCertificateToInternalLineItem","extendedListPrice","downloadsPageUrl","downloadPageUrl","mapToInternalLineItem","mapToInternalLineItemType","mapToInternalCart","sum","discountNotifications","totalDiscountedAmount","certificate","appliedGiftCertificates","__WEBPACK_EXTERNAL_MODULE_lodash_keyBy__","amountBeforeDiscount","shippingCostBeforeDiscount","integerAmountBeforeDiscount","taxSubtotal","handling","handlingCostTotal","CheckoutButtonMethodType","checkout_button_method_type","mapToInternalCustomer","customerGroupName","customerGroup","CardExpiryFormatter","RegExp","trimmedMonth","trimmedYear","toObject","CardNumberFormatter","__WEBPACK_EXTERNAL_MODULE_card_validator_0e6920dd_number__","__WEBPACK_EXTERNAL_MODULE_lodash_max__","__WEBPACK_EXTERNAL_MODULE_card_validator_0e6920dd_creditCardType__","lengths","unformattedValue","unformat","gaps","gapIndex","mapToInternalOrder","customerCanBeCreated","mapToInternalOrderPayment","baseAmount","callbackUrl","mapToGiftCertificates","socialData","mapToInternalSocialDataList","hasDigitalItems","isDownloadable","isComplete","mapToStoreCredit","orderAmountAsInteger","isDefaultOrderPayment","helpText","instructions","socialDataObject","socialMedia","image","shareText","sharingLink","channelName","channel","channelCode","mapToInternalShippingOption","isSelected","price","selected","transitTime","PaymentRequestTransformer","_cardExpiryFormatter","_cardNumberFormatter","getShippingOption","contextConfig","paymentMeta","internalCustomer","formattedInstrument","is_vaulted_instrument_isFormattedVaultedInstrument","_transformPaymentMethod","quoteMeta","geoCountryCode","transformWithHostedFormData","_transformHostedInputValues","BRAINTREE_VENMO","BRAINTREE_PAYPAL","hostedFormNonce","isBopisEnabled","bopis","requiredAddress","isPickup","selectedPickupOption","isPPSDKPaymentMethod","initializationStrategy","PPSDK","PaymentStrategyRegistry","_getToken","KLARNAV2","_hasFactoryForMethod","OFFLINE","payment_argument_invalid_error_PaymentArgumentInvalidError","credit_card_payment_strategy_CreditCardPaymentStrategy","_paymentActionCreator","_hostedFormFactory","credit_card_credit_card_payment_strategy_rest","ConvergePaymentStrategy","orderActionCreator","paymentActionCreator","hostedFormFactory","payment_method_cancelled_error_PaymentMethodCancelledError","PENDING_REDIRECT_PARAM","RedirectionState","_isRedirecting","currentUrlHasRedirectingParam","isRedirecting","setRedirecting","setRedirectingParamOnUrl","removeRedirectingParamFromUrl","getCurrentUrl","__WEBPACK_EXTERNAL_MODULE_query_string_2dcf3be8_parseUrl__","replaceCurrentUrl","history","replaceState","currentUrl","updatedUrl","__WEBPACK_EXTERNAL_MODULE_query_string_2dcf3be8_stringifyUrl__","__WEBPACK_EXTERNAL_MODULE_query_string_2dcf3be8_exclude__","isAnyContinue","__WEBPACK_EXTERNAL_MODULE_lodash_overSome__","__WEBPACK_EXTERNAL_MODULE_lodash_get__","__WEBPACK_EXTERNAL_MODULE_lodash_isString__","__WEBPACK_EXTERNAL_MODULE_lodash_isUndefined__","redirect_isParameters","availableMethods","isParameters","ContinueHandler","_humanVerificationHandler","form_fields","redirectionState","handleRedirect","available_methods","humanVerificationHandler","human_verification_awaiter","handleHumanVerification","humanVerification","StepHandler","_continueHandler","isSuccess","isContinue","isFailure","failureResponse","isError","COMPLETED_PAYMENTS_KEY","PPSDKCompletedPayments","_browserStorage","isCompleted","getCompletedPayments","setCompleted","completedPayments","setCompletedPayments","SubStrategyType","PPSDKStrategy","_subStrategyRegistry","_paymentResumer","browserStorage","_completedPayments","ppsdk_strategy_rest","_subStrategy","subStrategy","getPPSDKMethod","getToken","__WEBPACK_EXTERNAL_MODULE_lodash_cond__","__WEBPACK_EXTERNAL_MODULE_lodash_constant__","CARD","NONE","__WEBPACK_EXTERNAL_MODULE_lodash_stubTrue__","UNSUPPORTED","SubStrategyRegistry","CardSubStrategy","_ppsdkStepHandler","card_sub_strategy_awaiter","NoneSubStrategy","_stepHandler","payment_method_id","PaymentProviderCustomerType","RemoteCheckoutActionType","PaymentResumer","auth_token","CartRequestSender","PaymentProviderCustomerActionCreator","providerCustomerData","UpdatePaymentProviderCustomer","ConsignmentActionType","RemoteCheckoutActionCreator","_remoteCheckoutRequestSender","initializeBilling","InitializeRemoteBillingRequested","InitializeRemoteBillingSucceeded","InitializeRemoteBillingFailed","initializeShipping","InitializeRemoteShippingRequested","InitializeRemoteShippingSucceeded","InitializeRemoteShippingFailed","InitializeRemotePaymentRequested","InitializeRemotePaymentSucceeded","InitializeRemotePaymentFailed","loadSettings","LoadRemoteSettingsRequested","LoadRemoteSettingsSucceeded","LoadRemoteSettingsFailed","SignOutRemoteCustomerRequested","SignOutRemoteCustomerSucceeded","SignOutRemoteCustomerFailed","ForgetCheckoutRemoteCustomerRequested","remote_checkout_action_creator_awaiter","ForgetCheckoutRemoteCustomerSucceeded","ForgetCheckoutRemoteCustomerFailed","UpdateRemoteCheckout","RemoteCheckoutRequestSender","methodName","generateToken","trackAuthorizationEvent","ConsignmentActionCreator","_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","consignmentInMemory","getConsignmentById","_isUpdateConsignmentRequest","itemId","_hydrateLineItems","lineItemIds","existingItem","sharedItem","concat","DEFAULT_INCLUDES","ConsignmentRequestSender","consignment_request_sender_rest","ShippingCountryActionType","StoreCreditActionType","ShippingCountryActionCreator","_shippingCountryRequestSender","checkoutData","LoadShippingCountriesRequested","LoadShippingCountriesSucceeded","LoadShippingCountriesFailed","ShippingCountryRequestSender","SubscriptionsActionType","StoreCreditActionCreator","_storeCreditRequestSender","ApplyStoreCreditRequested","store_credit_action_creator_awaiter","checkoutVersion","removeStoreCredit","ApplyStoreCreditSucceeded","ApplyStoreCreditFailed","StoreCreditRequestSender","UpdateSubscriptionsError","SubscriptionsActionCreator","_subscriptionsRequestSender","subscriptions","UpdateSubscriptionsRequested","subscriptions_action_creator_awaiter","UpdateSubscriptionsSucceeded","UpdateSubscriptionsFailed","SubscriptionsRequestSender","isPlainObject","__WEBPACK_EXTERNAL_MODULE_lodash_isPlainObject__","cloneDeep","__WEBPACK_EXTERNAL_MODULE_lodash_memoize__","cloneDeepSafe","cache","cloneResult","createPaymentIntegrationSelectors","getPaymentTokenOrThrow","getPaymentIdOrThrow","getPaymentStatusOrThrow","getPaymentRedirectUrlOrThrow","getShippingAddressOrThrow","getShippingAddresses","getShippingAddressesOrThrow","shippingCountries","InstrumentActionType","DefaultPaymentIntegrationService","_storeProjectionFactory","_billingAddressActionCreator","_consignmentActionCreator","_paymentMethodActionCreator","_cartRequestSender","_storeCreditActionCreator","_couponActionCreator","_paymentProviderCustomerActionCreator","_shippingCountryActionCreator","_remoteCheckoutActionCreator","_storeProjection","subscriber","filters","initializeOffsitePaymentConfig","buyNowCartRequestBody","handlePaymentHumanVerification","queueId","PaymentIntegrationStoreProjectionFactory","_transformSelectors","createPaymentIntegrationService","storeProjectionFactory","checkoutActionCreator","checkoutValidator","billingAddressActionCreator","consignmentActionCreator","paymentMethodActionCreator","paymentHumanVerificationHandler","customerActionCreator","storeCreditActionCreator","applyCouponActionCreator","spamProtection","spamProtectionRequestSender","spamProtectionActionCreator","cartRequestSender","paymentProviderCustomerActionCreator","shippingCountryActionCreator","remoteCheckoutActionCreator","paymentStrategyWidgetActionCreator","InstrumentActionCreator","_instrumentRequestSender","loadInstruments","LoadInstrumentsRequested","_getSessionContext","_getCurrentAccessToken","_getShippingAddress","_getValidAccessToken","currentToken","LoadInstrumentsSucceeded","LoadInstrumentsFailed","deleteInstrument","DeleteInstrumentRequested","DeleteInstrumentSucceeded","DeleteInstrumentFailed","_isValidVaultAccessToken","newDate","setMinutes","getMinutes","addMinutes","vaultAccessExpiry","valueOf","getVaultAccessToken","isTransactional","PickupOptionActionType","ShippingStrategyActionType","InstrumentResponseTransformer","transformResponse","instrument_response_transformer_rest","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","InstrumentRequestSender","_transformer","requestContext","_loadInstrumentsWithAddress","_loadInstruments","deleteShopperInstrument","errorResponse","loadInstrumentsWithAddress","PickupOptionActionCreator","_pickupOptionRequestSender","loadPickupOptions","apiQuery","_hydrateApiQuery","LoadPickupOptionsRequested","fetchPickupOptions","LoadPickupOptionsSucceeded","LoadPickupOptionsFailed","consignmentLineItems","cartItems","searchArea","PickupOptionRequestSender","ShippingStrategyActionCreator","UpdateAddressRequested","UpdateAddressSucceeded","UpdateAddressFailed","selectOption","SelectOptionRequested","SelectOptionSucceeded","SelectOptionFailed","mergedOptions","shippingStrategies","instrument_UntrustedShippingCardVerificationType","AmazonPayV2ShippingStrategy","_amazonPayV2PaymentProcessor","_shippingStrategyActionCreator","updateAddressRequestBody","editAddressButtonId","shouldShowLoadingSpinner","_shouldShowLoadingSpinner","BraintreeFastlaneShippingStrategy","_braintreeIntegrationService","fastlane","fastlaneOptions","onPayPalFastlaneAddressChange","_shouldRunAuthenticationFlow","_runAuthenticationFlowOrThrow","_shouldUseBraintreeFastlaneShippingComponent","_handleBraintreeFastlaneShippingAddressChange","_getPayPalBillingAddress","paypalPhoneNumber","_mapPayPalToBcAddress","_mergeShippingAndBillingAddresses","_mapPayPalToBcInstrument","_getCountryNameByCountryCode","_normalizeAddress","selectedAddress","showShippingAddressSelector","paymentProviderCustomerAddresses","_filterAddresses","_isEqualAddresses","_getBraintreePaymentMethodOrThrow","isFastlaneEnabled","DefaultShippingStrategy","PayPalCommerceFastlaneShippingStrategy","_paypalSdkScriptLoader","_paypalCommerceFastlaneUtils","_shouldAuthenticateUserWithFastlane","_initializePayPalSdk","_authenticateUserWithFastlaneOtp","_shouldUsePayPalFastlaneShippingComponent","_handlePayPalShippingAddressChange","_getPayPalPaymentMethodOrThrow","_getPayPalCustomerAuthenticationState","paypalConnectSessionId","customerAuthenticationState","billingAddressEmail","SignInEmailActionType","StripeUPEShippingStrategy","_stripeScriptLoader","onChangeShipping","availableCountries","getStripeState","getShippingAddressFields","shippingFields","spacingUnit","shippingPhoneField","allowedCountries","validation","SPLIT","stripeState","shippingAddressElement","isNewAddress","sendData","phoneFieldRequired","SignInEmailActionCreator","sendSignInEmail","emailRequest","SendSignInEmailRequested","signin_email_action_creator_awaiter","SendSignInEmailSucceeded","SendSignInEmailFailed","SignInEmailRequestSender","ErrorMessageTransformer","_messageCustomizer","CheckoutService","_extensionEventBroadcaster","_b2bTokenActionCreator","_countryActionCreator","_customerStrategyActionCreator","_errorActionCreator","_giftCertificateActionCreator","_instrumentActionCreator","_paymentStrategyActionCreator","_pickupOptionActionCreator","_signInEmailActionCreator","_subscriptionsActionCreator","_extensionActionCreator","_errorTransformer","isDevelopment","isCheckoutServiceError","createCheckoutServiceErrorTransformer","notifyState","_dispatch","loadCheckoutAction","formFieldsAction","loadConfigAction","finalizeOrderIfNeeded","loadPaymentMethodByIds","deinitializePayment","loadBillingCountries","loadBillingAddressFields","loadShippingAddressFields","initializeCustomer","deinitializeCustomer","signInEmailRequest","createCustomerAccount","createCustomerAddress","deinitializeShipping","assignItemsToAddress","unassignItemsToAddress","selectConsignmentShippingOption","initializeSpamProtection","executeSpamCheck","clearExtensionCache","postMessageToExtension","handleExtensionCommand","handler","handleExtensionQuery","checkout_service_decorate","withMemoizedCombiner","creator","combiner","pop","combinerArgs","create_selector","__WEBPACK_EXTERNAL_MODULE_reselect_createSelector__","create_shallow_equal_selector","__WEBPACK_EXTERNAL_MODULE_reselect_createSelectorCreator__","__WEBPACK_EXTERNAL_MODULE_reselect_defaultMemoize__","__WEBPACK_EXTERNAL_MODULE_shallowequal_default__","UnrecoverableError","map_from_internal_error_response_joinErrors","timeout_error_TimeoutError","RequestErrorFactory","_factoryMethods","mapFromInternalErrorResponse","mapFromStorefrontErrorResponse","factoryMethod","createError","_getType","_isStorefrontErrorResponseBody","_isInternalErrorResponseBody","internalType","__WEBPACK_EXTERNAL_MODULE_lodash_last__","storefrontErrorResponse","internalErrorResponse","omitDeep","predicate","__WEBPACK_EXTERNAL_MODULE_lodash_transform__","clearErrorReducer","isClearErrorAction","objectA","objectB","isArrayEqual","isDateEqual","isRegExpEqual","keyFilter","keysA","keysB","isObjectEqual","objectSet","DEFAULT_STATE","statuses","b2bTokenReducer","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_combineReducers__","dataReducer","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_composeReducers__","errorsReducer","statusesReducer","reducer","currentValue","newValue","billing_address_state_DEFAULT_STATE","billingAddressReducer","billing_address_reducer_dataReducer","billing_address_reducer_errorsReducer","billing_address_reducer_statusesReducer","array_replace","arrayReplace","currentArray","newArray","matchObject","sameAsCurrentCount","sameAsNewCount","countSameAsReplaced","replacedValue","newItem","currentItem","object_merge","objectMerge","currentObject","newObject","cart_state_DEFAULT_STATE","cartReducer","cart_reducer_dataReducer","cart_reducer_errorsReducer","cart_reducer_statusesReducer","CheckoutButtonActionType","checkout_button_state_DEFAULT_STATE","DEFAULT_DATA_STATE","initializedContainers","DEFAULT_ERROR_STATE","DEFAULT_STATUS_STATE","checkoutButtonReducer","checkout_button_reducer_dataReducer","checkout_button_reducer_errorsReducer","checkout_button_reducer_statusesReducer","InitializeButtonSucceeded","DeinitializeButtonSucceeded","InitializeButtonRequested","InitializeButtonFailed","DeinitializeButtonRequested","DeinitializeButtonFailed","config_state_DEFAULT_STATE","configReducer","config_reducer_dataReducer","config_reducer_errorsReducer","config_reducer_statusesReducer","merged","coupon_state_DEFAULT_STATE","couponReducer","coupon_reducer_dataReducer","coupon_reducer_errorsReducer","coupon_reducer_statusesReducer","gift_certificate_state_DEFAULT_STATE","giftCertificateReducer","gift_certificate_reducer_dataReducer","gift_certificate_reducer_errorsReducer","gift_certificate_reducer_statusesReducer","customer_state_DEFAULT_STATE","customerReducer","customer_reducer_dataReducer","customer_reducer_errorsReducer","customer_reducer_statusesReducer","customer_strategy_state_DEFAULT_STATE","customerStrategyReducer","customer_strategy_reducer_dataReducer","customer_strategy_reducer_errorsReducer","customer_strategy_reducer_statusesReducer","initializeErrors","initializeMethodId","deinitializeError","deinitializeMethodId","signInError","signInMethodId","signOutError","signOutMethodId","executePaymentMethodCheckoutError","executePaymentMethodCheckoutMethodId","widgetInteractionError","widgetInteractionMethodId","isInitializing","isDeinitializing","isSigningIn","isSigningOut","isExecutingPaymentMethodCheckout","isWidgetInteracting","extension_state_DEFAULT_STATE","extensionReducer","extension_reducer_dataReducer","extension_reducer_errorsReducer","extension_reducer_statusesReducer","form_fields_state_DEFAULT_STATE","formFieldsReducer","form_fields_reducer_dataReducer","extraFields","extraFieldsReducer","form_fields_reducer_errorsReducer","form_fields_reducer_statusesReducer","country_state_DEFAULT_STATE","countryReducer","country_reducer_dataReducer","country_reducer_errorsReducer","country_reducer_statusesReducer","order_state_DEFAULT_STATE","orderReducer","order_reducer_dataReducer","order_reducer_errorsReducer","metaReducer","order_reducer_statusesReducer","order_billing_address_state_DEFAULT_STATE","orderBillingAddressReducer","order_billing_address_reducer_dataReducer","paymentReducer","payment_reducer_dataReducer","payment_method_state_DEFAULT_STATE","paymentMethodReducer","payment_method_reducer_dataReducer","payment_method_reducer_errorsReducer","payment_method_reducer_metaReducer","payment_method_reducer_statusesReducer","array","defaultPredicate","derivedPredicate","__WEBPACK_EXTERNAL_MODULE_lodash_findIndex__","mergeOrPush","methodA","methodB","loadMethodId","loadMethodError","isLoadingMethod","payment_strategy_state_DEFAULT_STATE","paymentStrategyReducer","payment_strategy_reducer_dataReducer","payment_strategy_reducer_errorsReducer","payment_strategy_reducer_statusesReducer","initializeError","executeError","executeMethodId","finalizeError","finalizeMethodId","isExecuting","isFinalizing","payment_provider_customer_state_DEFAULT_STATE","paymentProviderCustomerReducer","payment_provider_customer_reducer_dataReducer","instrument_state_DEFAULT_STATE","instrumentReducer","instrument_reducer_dataReducer","instrument_reducer_errorsReducer","instrument_reducer_metaReducer","instrument_reducer_statusesReducer","deleteError","failedInstrument","isDeleting","deletingInstrument","remote_checkout_state_DEFAULT_STATE","remoteCheckoutReducer","remote_checkout_reducer_dataReducer","consignment_state_DEFAULT_STATE","updateShippingOptionError","updateError","isUpdating","isUpdatingShippingOption","consignmentReducer","consignment_reducer_dataReducer","consignment_reducer_errorsReducer","consignment_reducer_statusesReducer","objectFlatten","flattened","keyString","objectWithSortedKeys","current","pickup_option_state_DEFAULT_STATE","pickupOptionReducer","pickup_option_reducer_dataReducer","pickup_option_reducer_errorsReducer","pickup_option_reducer_statusesReducer","sortedflattenedMeta","shipping_country_state_DEFAULT_STATE","shippingCountryReducer","shipping_country_reducer_dataReducer","shipping_country_reducer_errorsReducer","shipping_country_reducer_statusesReducer","shipping_strategy_state_DEFAULT_STATE","shippingStrategyReducer","shipping_strategy_reducer_dataReducer","shipping_strategy_reducer_errorsReducer","shipping_strategy_reducer_statusesReducer","updateAddressError","updateAddressMethodId","selectOptionError","selectOptionMethodId","isUpdatingAddress","isSelectingOption","signin_email_state_DEFAULT_STATE","signInEmailReducer","signin_email_reducer_dataReducer","signin_email_reducer_errorsReducer","signin_email_reducer_statusesReducer","store_credit_reducer_DEFAULT_STATE","storeCreditReducer","store_credit_reducer_errorsReducer","store_credit_reducer_statusesReducer","subscriptions_state_DEFAULT_STATE","subscriptionsReducer","subscriptions_reducer_errorsReducer","subscriptions_reducer_statusesReducer","checkout_state_DEFAULT_STATE","checkoutReducer","checkout_reducer_dataReducer","checkout_reducer_errorsReducer","checkout_reducer_statusesReducer","guard_guard","createFreezeProxy","proxy","iteratee","getPrototypeOf","traversePrototypeOf","charAt","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_deepFreeze__","trap","createProxy","supported_payment_instruments","authorizenet","elavon","checkoutcom","sagepay","cybersource","cybersourcev2","bnz","converge","orbital","paymetric","cba_mpgs","worldpayaccess","tdonlinemart","normalize","__WEBPACK_EXTERNAL_MODULE_lodash_identity__","store_credit_state_DEFAULT_STATE","createInternalCheckoutSelectorsFactory","createB2BTokenSelector","getLoadError","loadError","__WEBPACK_EXTERNAL_MODULE__bigcommerce_memoize_bf7b411a_memoizeOne__","createB2BTokenSelectorFactory","createBillingAddressSelector","getUpdateError","getContinueAsGuestError","continueAsGuestError","isContinuingAsGuest","createBillingAddressSelectorFactory","createCartSelector","createCartSelectorFactory","createCheckoutButtonSelector","getInitializeError","getDeinitializeError","createCheckoutButtonSelectorFactory","createConfigSelector","getFlashMessages","filterType","flashMessages","formState","createConfigSelectorFactory","createCountrySelector","createCountrySelectorFactory","createCouponSelector","getCoupons","getRemoveError","removeCouponError","getApplyError","applyCouponError","isApplying","isApplyingCoupon","isRemoving","isRemovingCoupon","createCouponSelectorFactory","createCustomerSelector","getCreateAccountError","isCreatingCustomerAccount","isCreating","getCreateAddressError","createAddressError","isCreatingCustomerAddress","isCreatingAddress","createCustomerSelectorFactory","createCustomerStrategySelector","getSignInError","getSignOutError","getExecutePaymentMethodCheckoutError","getWidgetInteractionError","createCustomerStrategySelectorFactory","createGiftCertificateSelector","getGiftCertificates","removeGiftCertificateError","applyGiftCertificateError","isApplyingGiftCertificate","isRemovingGiftCertificate","createGiftCertificateSelectorFactory","createInstrumentSelector","getInstrumentsByPaymentMethod","paymentMethodKey","currentMethod","__WEBPACK_EXTERNAL_MODULE_lodash_isMatch__","supportedProvider","getDeleteError","createInstrumentSelectorFactory","createFormSelector","selectedCountry","processField","getBillingAddressFields","getCustomerAccountFields","getAddressExtraFields","itemtype","processCountry","subdivisions","requiresState","processProvince","hasPostalCodes","processsPostCode","createFormSelectorFactory","createPaymentMethodSelector","getPaymentMethods","getLoadMethodError","createPaymentMethodSelectorFactory","createPaymentStrategySelector","getExecuteError","getFinalizeError","getWidgetInteractingError","createPaymentStrategySelectorFactory","createPickupOptionSelector","getPickupOptions","pickupOptions","sortedFlattenedParams","createPickupOptionSelectorFactory","createPaymentProviderCustomerSelector","createPaymentProviderCustomerSelectorFactory","createRemoteCheckoutSelector","createRemoteCheckoutSelectorFactory","createShippingAddressSelector","shippingConsignment","shippingConsignments","createShippingAddressSelectorFactory","createShippingCountrySelector","createShippingCountrySelectorFactory","createShippingStrategySelector","getUpdateAddressError","getSelectOptionError","createShippingStrategySelectorFactory","createConsignmentSelector","isAddressEqual","addressA","addressB","getCreateError","getLoadShippingOptionsError","loadShippingOptionsError","getUnassignedItems","assignedLineItemIds","itemIds","getItemAssignmentError","getUpdateShippingOptionError","isLoadingShippingOptions","isAssigningItems","createConsignmentSelectorFactory","createCheckoutSelector","isExecutingSpamCheck","createCheckoutSelectorFactory","createOrderSelector","getOrderBillingAddress","currentPayment","createOrderSelectorFactory","createOrderBillingAddressSelector","createOrderBillingAddressSelectorFactory","createPaymentSelector","getInternalPayment","getGatewayPayment","getHostedPayment","providerType","internalPayment","MissingPaymentId","MissingPaymentStatus","MissingPaymentRedirectUrl","isPaymentDataSubmitted","createPaymentSelectorFactory","createStoreCreditSelector","applyError","createStoreCreditSelectorFactory","createSubscriptionsSelector","createSubscriptionsSelectorFactory","createSignInEmailSelector","getEmail","signInEmail","getSendError","sendError","isSending","createSignInEmailSelectorFactory","createExtensionSelector","createExtensionSelectorFactory","b2bToken","checkoutButton","orderBillingAddress","remoteCheckout","selectors","shouldWarnMutation","createCheckoutStore","initialStoreState","actionTransformer","requestErrorFactory","createRequestErrorFactory","action$","createInternalCheckoutSelectors","createCheckoutService","checkoutVariantIdentificationToken","experimentRequestSender","orderRequestSender","checkoutRequestSender","configActionCreator","subscriptionsActionCreator","formFieldsActionCreator","registryV2","paymentStrategyFactories","createPaymentStrategy","createPaymentStrategyRegistry","payment_strategies_namespaceObject","customerRegistryV2","customerStrategyFactories","createCustomerStrategy","createCustomerStrategyRegistry","customer_strategies_namespaceObject","extensionActionCreator","extensionMessenger","storeProjection","createCheckoutStoreSelector","getShippingOptions","getSelectedShippingOption","getBillingCountries","getSelectedPaymentMethod","getSignInEmail","getUserExperienceSettings","checkoutUserExperienceSettings","createCheckoutStoreSelectorFactory","createCheckoutStoreErrorSelector","getSelectShippingOptionError","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","getLoadB2BTokenError","getCreateCustomerAccountError","getCreateCustomerAddressError","getPickupOptionsError","getLoadExtensionsError","createCheckoutStoreErrorSelectorFactory","createCheckoutStoreStatusSelector","isPending","isSelectingShippingOption","isCustomerStepPending","isShippingStepPending","isPaymentStepPending","isSubmittingOrder","isLoadingCheckout","isUpdatingCheckout","isFinalizingOrder","isLoadingOrder","isLoadingCart","isLoadingBillingCountries","isLoadingShippingCountries","isLoadingPaymentMethods","isLoadingPaymentMethod","isInitializingPayment","isInitializingCustomer","isInitializedCustomer","isUpdatingBillingAddress","isUpdatingSubscriptions","isUpdatingShippingAddress","isUpdatingConsignment","isDeletingConsignment","isCreatingConsignments","isInitializingShipping","isApplyingStoreCredit","isLoadingInstruments","isDeletingInstrument","isLoadingConfig","isSendingSignInEmail","isLoadingB2BToken","isLoadingPickupOptions","createCheckoutStoreStatusSelectorFactory","createCheckoutSelectorsFactory","checkout_service","messenger","subscribers","createExtensionEventBroadcaster","create_customer_strategy_registry_createCustomerStrategyRegistry","paymentRequestTransformer","paymentRequestSender","stepHandler","createStepHandler","CONVERGE","createSubStrategyRegistry","create_payment_strategy_registry_createPaymentStrategyRegistry","consignmentRequestSender","createShippingStrategyRegistry","AmazonPayV2ConfigCreationError","isWithBuyNowFeatures","AmazonPayV2ButtonStrategy","amazonPayV2ConfigRequestSender","initializeAmazonButtonOptions","_buyNowInitializeOptions","Cart","_getCheckoutCreationRequestConfig","_createBuyNowCartOrThrow","_createCheckoutConfig","public_key","rest","amazon_pay_v2_button_strategy_rest","payloadJSON","AmazonPayV2RequestSender","create_amazon_pay_v2_button_strategy","amazonPayV2RequestSender","apple_pay_button_strategy_DefaultLabels","ButtonStyleOption","ApplePayButtonStrategy","_requiresShipping","White","WhiteBorder","Black","getButtonStyle","_getRequestWithEmptyTotal","apple_pay_button_strategy_awaiter","onpaymentmethodselected","_createBuyNowCart","_handlePaymentMethodSelected","completePaymentMethodSelection","create_apple_pay_button_strategy","BigCommercePaymentsButtonStrategy","onEligibilityFailure","buyNowFlowCallbacks","create_bigcommerce_payments_button_strategy","BigCommercePaymentsPayLaterButtonStrategy","create_bigcommerce_payments_paylater_button_strategy","BigCommercePaymentsVenmoButtonStrategy","getValidVenmoButtonStyles","validButtonStyle","gold","create_bigcommerce_payments_venmo_button_strategy","BoltButtonStrategy","BoltConnect","setupProductPageCheckout","addButtonContainer","boltButtonContainer","boltButtonObject","getBoltObjectData","append","domainUrl","getButtonHeight","buttonBorderRadius","getButtonBorderRadius","publishable_key","variant","border_radius","buttonSize","Small","Large","Medium","buttonShape","Pill","Rect","create_bolt_button_strategy","fundingicons","tagline","currentHeight","BraintreePaypalButtonStrategy","shouldProcessPayment","onAuthorizeError","buyNowCartId","buyNowCardRequestBody","create_braintree_paypal_button_strategy","BraintreePaypalCreditButtonStrategy","create_braintree_paypal_credit_button_strategy","BraintreeVisaCheckoutButtonStrategy","braintree_visa_checkout_button_strategy_awaiter","paymentSuccess","toVisaCheckoutAddress","alignItems","create_braintree_visa_checkout_button_strategy","getVenmoButtonStyle","WHITE","backgroundPosition","backgroundSize","backgroundImage","BLUE","backgroundRepeat","cursor","minHeight","minWidth","BraintreeVenmoButtonStrategy","cartButtonStyles","renderVenmoButton","isUnsupportedBrowserError","handleInitializationVenmoError","removeVenmoContainer","venmoButton","braintree_venmo_button_strategy_awaiter","buyBowCart","handlePostForm","create_braintree_venmo_button_strategy","GooglePayButtonStrategy","_getMethodOrThrow","_countryCode","google_pay_button_strategy_awaiter","_buyNowCart","_getBuyNowTransactionInfo","_getTransactionInfo","create_google_pay_braintree_button_strategy","create_google_pay_paypal_commerce_button_strategy","create_google_pay_bigcommerce_payments_button_strategy","create_google_pay_adyenv2_button_strategy","create_google_pay_adyenv3_button_strategy","create_google_pay_authorizenet_button_strategy","create_google_pay_checkoutcom_button_strategy","create_google_pay_cybersource_button_strategy","create_google_pay_orbital_button_strategy","create_google_pay_stripe_button_strategy","create_google_pay_worldpayaccess_button_strategy","create_google_pay_tdonlinemart_button_strategy","PayPalCommerceButtonStrategy","create_paypal_commerce_button_strategy","PayPalCommerceCreditButtonStrategy","create_paypal_commerce_credit_button_strategy","PayPalCommerceVenmoButtonStrategy","create_paypal_commerce_venmo_button_strategy","PaypalButtonStrategy","paypalExpressScriptLoader","paypalSDK","allowCredit","fundingCreditOption","allowedSources","disallowedSources","Button","funding","disallowed","getStyle","onAuthorize","RECT","RESPONSIVE","CheckoutButtonNotInitialized","paymentID","payerID","getPaymentData","payerId","payerInfo","payer_info","create_paypal_express_button_strategy","StripeLinkV2ButtonStrategy","stripe_link_v2_button_strategy_awaiter","create_stripe_link_v2_button_strategy","getUniqId","idPrefix","__WEBPACK_EXTERNAL_MODULE_lodash_uniqueId__","isTerminalCacheKeyMap","CacheKeyResolver","_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","CheckoutButtonErrorSelector","_checkoutButton","getInitializeButtonError","getDeinitializeButtonError","checkout_button_error_selector_decorate","CheckoutButtonStatusSelector","isInitializingButton","isDeinitializingButton","checkout_button_status_selector_decorate","createCheckoutButtonSelectors","checkout_button_error_selector","checkout_button_status_selector","CheckoutButtonInitializer","_buttonStrategyActionCreator","_state","initializeButton","containerIds","containers","setUniqueElementId","deinitializeButton","checkout_button_initializer_decorate","CheckoutButtonStrategyActionCreator","_registryV2","paymentMethodRequestParams","paymentMethodRequestOptions","payment_method_client_unavailable_error_PaymentMethodClientUnavailableError","paypal_sdk_PaypalButtonStyleLayoutOption","paypal_sdk_PaypalButtonStyleSizeOption","paypal_sdk_PaypalButtonStyleColorOption","paypal_sdk_PaypalButtonStyleLabelOption","paypal_sdk_PaypalButtonStyleShapeOption","EmbeddedCheckoutEventType","NotEmbeddableErrorType","EmbeddedContentEventType","paypal_script_loader_PaypalScriptLoader","paypal_button_strategy_PaypalButtonStrategy","_paypalScriptLoader","_host","_setupPayment","_tokenizePayment","createCheckoutButtonInitializer","checkoutButtonStrategyFactories","createCheckoutButtonStrategy","createCheckoutButtonStrategyRegistry","checkout_button_strategies_namespaceObject","checkout_button_initializer","PAYPALEXPRESS","createCheckoutButtonRegistry","InvalidLoginTokenError","NotEmbeddableError","UnknownError","IS_COOKIE_ALLOWED_KEY","LAST_ALLOW_COOKIE_ATTEMPT_KEY","EmbeddedCheckout","_iframeCreator","_messageListener","_messagePoster","_storage","_location","_isAttached","CheckoutComplete","CheckoutError","CheckoutLoaded","onFrameLoad","FrameLoaded","onSignOut","SignedOut","_configureStyles","_allowCookie","_attemptLogin","_retryAllowCookie","FrameError","iFrameResizer","StyleConfigured","lastAttempt","MissingContent","embedded_checkout_decorate","resizable_iframe_creator_ResizableIframeCreator","MissingContainer","allowPaymentRequest","contentId","embedCheckout","handleFrameLoadedEvent","hasAttribute","custom_error_isCustomError","IframeEmbeddedCheckoutMessenger","_untargetedMessagePoster","_messageHandlers","postComplete","_postMessage","postError","_transformError","postFrameError","untargeted","postFrameLoaded","postLoaded","postSignedOut","receiveStyles","_notifyMessageHandlers","iframe_embedded_checkout_messenger_decorate","NoopEmbeddedCheckoutMessenger","noop_embedded_checkout_messenger_decorate","createEmbeddedCheckoutMessenger","parentWindow","noop_embedded_checkout_messenger","iframe_embedded_checkout_messenger","DEFAULT_LOCALE","KEY_PREFIX","LanguageService","_logger","locales","_transformConfig","_locale","_locales","_translations","_formatters","mapKeys","_hasTranslations","translate","prefixedKey","__WEBPACK_EXTERNAL_MODULE_intl_messageformat_1c4020d9_IntlMessageFormat__","_escapeSpecialCharacters","ignoreTag","_transformData","_isFormatError","originalMessage","defaultLocale","defaultTranslations","_flattenObject","fallbackTranslations","__WEBPACK_EXTERNAL_MODULE_lodash_union__","fallbackLocale","parentKey","resultKey","language_service_decorate","createLanguageService","language_service","currency_service_CurrencyService","currency_currency_service_decorate","create_currency_service_createCurrencyService","currency_currency_service","isAnalyticsTrackerWindowGA","ga","sendGoogleAnalytics","nonInteraction","isPayloadSizeLimitReached","serializeAnalyticsEventPayload","acc","AnalyticStepId","ANALYTIC_STEPS","CUSTOMER","BILLING","AnalyticsStepTracker","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","getShopperCurrency","getPaymentMethodName","shipping_method","shippingMethodId","completedStepId","getStoreProfile","toShopperCurrency","getProducts","product_id","giftCertificateItems","itemAttributes","image_url","NoopStepTracker","createStepTracker","stepTrackerConfig","isBraintreeFastlaneWindow","BraintreeAnalyticTracker","_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","PayPalCommerceAnalyticTracker","_checkoutService","paypalHostWindow","_getPayPalEventsOrThrow","createPayPalCommerceAnalyticTracker","AnalyticStepType","StoredCardHostedFormService","createStoredCardHostedFormService","AnalyticStepOrder","BodlEmitterService","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","__WEBPACK_EXTERNAL_MODULE_lodash_flatten__","retail_price","retailPrice","NoopBodlService","createBodlService","isBodlEnabled"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/esm/extension.js b/dist/esm/extension.js index 6a92e18ae2..42d9767b6c 100644 --- a/dist/esm/extension.js +++ b/dist/esm/extension.js @@ -1,2 +1,2 @@ -import*as e from"iframe-resizer";import*as t from"iframe-resizer/js/iframeResizer.contentWindow";import{fromEvent as n}from"rxjs";import{filter as r,map as s,take as i}from"rxjs/operators";import{noop as o}from"lodash";var a={785(t,n,r){var s,i;t.exports=(s={iframeResizer:()=>e.iframeResizer},i={},r.d(i,s),i)},939(e){e.exports=t}},c={};function d(e){var t=c[e];if(void 0!==t)return t.exports;var n=c[e]={exports:{}};return a[e](n,n.exports,d),n.exports}d.d=(e,t)=>{for(var n in t)d.o(t,n)&&!d.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},d.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function p(e,t,n){if("function"!=typeof n.value)return n;let r=n.value;return{get(){const e=r.bind(this);return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e},set(e){r=e}}}class h extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}class u extends h{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}function f(e){if(!/^(https?:)?\/\//.test(e))throw new u("The provided URL must be absolute.");const t=document.createElement("a");t.href=e;const n=t.port&&-1!==e.indexOf(`${t.hostname}:${t.port}`)?t.port:"";return{hash:t.hash,hostname:t.hostname,href:t.href,origin:`${t.protocol}//${t.hostname}${n?`:${n}`:""}`,pathname:t.pathname,port:n,protocol:t.protocol,search:t.search}}function l(e,t){return e.type===t}var m,E,g,w,y;class _{constructor(e){var t;this._sourceOrigins=[f(e).origin,(t=f(e),f(0===t.hostname.indexOf("www")?t.href:t.href.replace(t.hostname,`www.${t.hostname}`))).origin],this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))}addListener(e,t){let n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)}removeListener(e,t){const n=this._listeners[e];if(!n)return;const r=n.indexOf(t);r>=0&&n.splice(r,1)}trigger(e,t){const n=this._listeners[e.type];n&&n.forEach(n=>t?n(e,t):n(e))}_handleMessage(e){if(-1===this._sourceOrigins.indexOf(e.origin)||!l(e.data,e.data.type))return;const t=e.data,{context:n}=t,r=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s=0;a--)(s=e[a])&&(o=(i<3?s(o):i>3?s(t,n,o):s(t,n))||o);i>3&&o&&Object.defineProperty(t,n,o)}([function(e,t,n){return t&&n?p(0,t,n):function(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(n=>{const r=Object.getOwnPropertyDescriptor(e.prototype,n);r&&"constructor"!==n&&Object.defineProperty(t.prototype,n,p(e.prototype,n,r))}),t}(e)}],_.prototype,"_handleMessage",null);class O{constructor(e,t,n){this._targetWindow=t,this._context=n,this._targetOrigin="*"===e?"*":f(e).origin}post(e,t){const o=this._targetWindow;if(window===o)return;if(!o)throw new Error("Unable to post message because target window is not set.");const a=t&&n(window,"message").pipe(r(e=>e.origin===this._targetOrigin&&l(e.data,e.data.type)&&-1!==[t.successType,t.errorType].indexOf(e.data.type)),s(e=>{if(t.errorType===e.data.type)throw e.data;return e.data}),i(1)).toPromise();return o.postMessage(Object.assign(Object.assign({},e),{context:this._context}),this._targetOrigin),a}setTarget(e){this._targetWindow=e}setContext(e){this._context=e}}!function(e){e.ReloadCheckout="EXTENSION:RELOAD_CHECKOUT",e.ShowLoadingIndicator="EXTENSION:SHOW_LOADING_INDICATOR",e.SetIframeStyle="EXTENSION:SET_IFRAME_STYLE",e.ReRenderShippingForm="EXTENSION:RE_RENDER_SHIPPING_FORM",e.ReRenderShippingStep="EXTENSION:RE_RENDER_SHIPPING_STEP"}(m||(m={})),function(e){e.ConsignmentsChanged="EXTENSION:CONSIGNMENTS_CHANGED"}(E||(E={})),function(e){e.Subscribe="EXTENSION_INTERNAL:SUBSCRIBE",e.Unsubscribe="EXTENSION_INTERNAL:UNSUBSCRIBE",e.ResizeIframe="EXTENSION_INTERNAL:RESIZE_IFRAME"}(g||(g={})),function(e){e.ExtensionReady="EXTENSION:READY",e.ExtensionFailed="EXTENSION:FAILED"}(w||(w={})),function(e){e.GetConsignments="EXTENSION:GET_CONSIGNMENTS"}(y||(y={}));var I=function(e,t,n,r){return new(n||(n=Promise))(function(s,i){function o(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((r=r.apply(e,t||[])).next())})};class v{constructor(e,t,n,r){this._messageListener=e,this._eventListener=t,this._messagePoster=n,this._internalCommandPoster=r,this._messagePoster.setTarget(window.parent),this._internalCommandPoster.setTarget(window.parent)}initialize(e){return I(this,void 0,void 0,function*(){if(!e)throw new Error("Extension Id not found.");this._extensionId=e,this._messageListener.listen(),this._eventListener.listen(),this._messagePoster.setContext({extensionId:e});try{yield this._internalCommandPoster.post({type:g.ResizeIframe,payload:{extensionId:e}},{successType:w.ExtensionReady,errorType:w.ExtensionFailed})}catch(e){if(this._isExtensionFailedEvent(e))throw new Error("Extension failed to load within 60 seconds; please reload and try again.")}})}post(e){if(!this._isCommandOrQueryType(e.type))throw new Error(`${e.type} is not supported.`);this._messagePoster.post(e)}addListener(e,t=o){if(!this._extensionId)throw new Error("Extension is not initialized.");const n=this._extensionId;if(!Object.values(E).includes(e))throw new Error(`${e} is not supported.`);return this._internalCommandPoster.post({type:g.Subscribe,payload:{extensionId:n,eventType:e}}),this._eventListener.addListener(e,t),()=>{this._internalCommandPoster.post({type:g.Unsubscribe,payload:{extensionId:n,eventType:e}}),this._eventListener.removeListener(e,t)}}getConsignments(e=!0){return I(this,void 0,void 0,function*(){return new Promise(t=>{const n=e=>{this._messageListener.removeListener("EXTENSION:GET_CONSIGNMENTS",n),t(e.payload.consignments)};this._messageListener.addListener("EXTENSION:GET_CONSIGNMENTS",n),this.post({type:y.GetConsignments,payload:{useCache:e}})})})}_isExtensionFailedEvent(e){return e.type===w.ExtensionFailed}_isCommandOrQueryType(e){return Object.values(m).includes(e)||Object.values(y).includes(e)}}function N(e){return t=this,n=void 0,s=function*(){const{extensionId:t,parentOrigin:n,taggedElementId:r,fixedHeight:s}=e;d(939);const i=new v(new _(n),new _(n),new O(n),new O(n));return yield i.initialize(t),function(e,t){if(!function(e){return"parentIFrame"in e}(window))throw new Error("iFramerResizer window not found.");if(t)window.parentIFrame.size(t);else if(window.parentIFrame.autoResize(!0),e){const t=document.getElementById(e);if(!t)throw new Error("Element not found.");t.setAttribute("data-iframe-height",""),window.parentIFrame.setHeightCalculationMethod("taggedElement")}else window.parentIFrame.setHeightCalculationMethod("bodyOffset")}(r,s),i},new((r=void 0)||(r=Promise))(function(e,i){function o(e){try{c(s.next(e))}catch(e){i(e)}}function a(e){try{c(s.throw(e))}catch(e){i(e)}}function c(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(o,a)}c((s=s.apply(t,n||[])).next())});var t,n,r,s}export{m as ExtensionCommandType,E as ExtensionEventType,N as initializeExtensionService}; +import*as e from"iframe-resizer";import*as t from"iframe-resizer/js/iframeResizer.contentWindow";import{fromEvent as n}from"rxjs";import{filter as r,map as s,take as i}from"rxjs/operators";import{noop as o}from"lodash";var a,c,d={785(t,n,r){var s,i;t.exports=(s={iframeResizer:()=>e.iframeResizer},i={},r.d(i,s),i)},939(e){e.exports=t}},p={};function h(e){var t=p[e];if(void 0!==t)return t.exports;var n=p[e]={exports:{}};return d[e](n,n.exports,h),n.exports}h.d=(e,t)=>{for(var n in t)h.o(t,n)&&!h.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},h.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),function(e){e.ConsignmentsChanged="EXTENSION:CONSIGNMENTS_CHANGED"}(a||(a={})),function(e){e.ReloadCheckout="EXTENSION:RELOAD_CHECKOUT",e.ShowLoadingIndicator="EXTENSION:SHOW_LOADING_INDICATOR",e.SetIframeStyle="EXTENSION:SET_IFRAME_STYLE",e.ReRenderShippingForm="EXTENSION:RE_RENDER_SHIPPING_FORM",e.ReRenderShippingStep="EXTENSION:RE_RENDER_SHIPPING_STEP"}(c||(c={}));function u(e,t,n){if("function"!=typeof n.value)return n;let r=n.value;return{get(){const e=r.bind(this);return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e},set(e){r=e}}}class f extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}class l extends f{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}function m(e){if(!/^(https?:)?\/\//.test(e))throw new l("The provided URL must be absolute.");const t=document.createElement("a");t.href=e;const n=t.port&&-1!==e.indexOf(`${t.hostname}:${t.port}`)?t.port:"";return{hash:t.hash,hostname:t.hostname,href:t.href,origin:`${t.protocol}//${t.hostname}${n?`:${n}`:""}`,pathname:t.pathname,port:n,protocol:t.protocol,search:t.search}}function E(e,t){return e.type===t}var g,w,y;class _{constructor(e){var t;this._sourceOrigins=[m(e).origin,(t=m(e),m(0===t.hostname.indexOf("www")?t.href:t.href.replace(t.hostname,`www.${t.hostname}`))).origin],this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))}addListener(e,t){let n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)}removeListener(e,t){const n=this._listeners[e];if(!n)return;const r=n.indexOf(t);r>=0&&n.splice(r,1)}trigger(e,t){const n=this._listeners[e.type];n&&n.forEach(n=>t?n(e,t):n(e))}_handleMessage(e){if(-1===this._sourceOrigins.indexOf(e.origin)||!E(e.data,e.data.type))return;const t=e.data,{context:n}=t,r=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s=0;a--)(s=e[a])&&(o=(i<3?s(o):i>3?s(t,n,o):s(t,n))||o);i>3&&o&&Object.defineProperty(t,n,o)}([function(e,t,n){return t&&n?u(0,t,n):function(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(n=>{const r=Object.getOwnPropertyDescriptor(e.prototype,n);r&&"constructor"!==n&&Object.defineProperty(t.prototype,n,u(e.prototype,n,r))}),t}(e)}],_.prototype,"_handleMessage",null);class O{constructor(e,t,n){this._targetWindow=t,this._context=n,this._targetOrigin="*"===e?"*":m(e).origin}post(e,t){const o=this._targetWindow;if(window===o)return;if(!o)throw new Error("Unable to post message because target window is not set.");const a=t&&n(window,"message").pipe(r(e=>e.origin===this._targetOrigin&&E(e.data,e.data.type)&&-1!==[t.successType,t.errorType].indexOf(e.data.type)),s(e=>{if(t.errorType===e.data.type)throw e.data;return e.data}),i(1)).toPromise();return o.postMessage(Object.assign(Object.assign({},e),{context:this._context}),this._targetOrigin),a}setTarget(e){this._targetWindow=e}setContext(e){this._context=e}}!function(e){e.Subscribe="EXTENSION_INTERNAL:SUBSCRIBE",e.Unsubscribe="EXTENSION_INTERNAL:UNSUBSCRIBE",e.ResizeIframe="EXTENSION_INTERNAL:RESIZE_IFRAME"}(g||(g={})),function(e){e.ExtensionReady="EXTENSION:READY",e.ExtensionFailed="EXTENSION:FAILED"}(w||(w={})),function(e){e.GetConsignments="EXTENSION:GET_CONSIGNMENTS"}(y||(y={}));var I=function(e,t,n,r){return new(n||(n=Promise))(function(s,i){function o(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((r=r.apply(e,t||[])).next())})};class v{constructor(e,t,n,r){this._messageListener=e,this._eventListener=t,this._messagePoster=n,this._internalCommandPoster=r,this._messagePoster.setTarget(window.parent),this._internalCommandPoster.setTarget(window.parent)}initialize(e){return I(this,void 0,void 0,function*(){if(!e)throw new Error("Extension Id not found.");this._extensionId=e,this._messageListener.listen(),this._eventListener.listen(),this._messagePoster.setContext({extensionId:e});try{yield this._internalCommandPoster.post({type:g.ResizeIframe,payload:{extensionId:e}},{successType:w.ExtensionReady,errorType:w.ExtensionFailed})}catch(e){if(this._isExtensionFailedEvent(e))throw new Error("Extension failed to load within 60 seconds; please reload and try again.")}})}post(e){if(!this._isCommandOrQueryType(e.type))throw new Error(`${e.type} is not supported.`);this._messagePoster.post(e)}addListener(e,t=o){if(!this._extensionId)throw new Error("Extension is not initialized.");const n=this._extensionId;if(!Object.values(a).includes(e))throw new Error(`${e} is not supported.`);return this._internalCommandPoster.post({type:g.Subscribe,payload:{extensionId:n,eventType:e}}),this._eventListener.addListener(e,t),()=>{this._internalCommandPoster.post({type:g.Unsubscribe,payload:{extensionId:n,eventType:e}}),this._eventListener.removeListener(e,t)}}getConsignments(e=!0){return I(this,void 0,void 0,function*(){return new Promise(t=>{const n=e=>{this._messageListener.removeListener("EXTENSION:GET_CONSIGNMENTS",n),t(e.payload.consignments)};this._messageListener.addListener("EXTENSION:GET_CONSIGNMENTS",n),this.post({type:y.GetConsignments,payload:{useCache:e}})})})}_isExtensionFailedEvent(e){return e.type===w.ExtensionFailed}_isCommandOrQueryType(e){return Object.values(c).includes(e)||Object.values(y).includes(e)}}function N(e){return t=this,n=void 0,s=function*(){const{extensionId:t,parentOrigin:n,taggedElementId:r,fixedHeight:s}=e;h(939);const i=new v(new _(n),new _(n),new O(n),new O(n));return yield i.initialize(t),function(e,t){if(!function(e){return"parentIFrame"in e}(window))throw new Error("iFramerResizer window not found.");if(t)window.parentIFrame.size(t);else if(window.parentIFrame.autoResize(!0),e){const t=document.getElementById(e);if(!t)throw new Error("Element not found.");t.setAttribute("data-iframe-height",""),window.parentIFrame.setHeightCalculationMethod("taggedElement")}else window.parentIFrame.setHeightCalculationMethod("bodyOffset")}(r,s),i},new((r=void 0)||(r=Promise))(function(e,i){function o(e){try{c(s.next(e))}catch(e){i(e)}}function a(e){try{c(s.throw(e))}catch(e){i(e)}}function c(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(o,a)}c((s=s.apply(t,n||[])).next())});var t,n,r,s}export{c as ExtensionCommandType,a as ExtensionEventType,N as initializeExtensionService}; //# sourceMappingURL=extension.js.map \ No newline at end of file diff --git a/dist/esm/extension.js.map b/dist/esm/extension.js.map index dee931bba4..ab9d32be10 100644 --- a/dist/esm/extension.js.map +++ b/dist/esm/extension.js.map @@ -1 +1 @@ -{"version":3,"file":"extension.js","mappings":"6OAAA,IAAAA,EACAC,EAGAC,EAAAC,SAJAH,EAIA,CAAqBI,cAAA,IAAAC,EAAA,eAHrBJ,EAAA,GAAaK,EAAAC,EAAAN,EAAAD,GAA6BC,WCD1CC,EAAAC,QAAAK,ICCAC,EAAA,GAGA,SAAAH,EAAAI,GAEA,IAAAC,EAAAF,EAAAC,GACA,QAAAE,IAAAD,EACA,OAAAA,EAAAR,QAGA,IAAAD,EAAAO,EAAAC,GAAA,CAGAP,QAAA,IAOA,OAHAU,EAAAH,GAAAR,EAAAA,EAAAC,QAAAG,GAGAJ,EAAAC,OACA,CCrBAG,EAAAC,EAAA,CAAAJ,EAAAW,KACA,QAAAC,KAAAD,EACAR,EAAAU,EAAAF,EAAAC,KAAAT,EAAAU,EAAAb,EAAAY,IACAE,OAAAC,eAAAf,EAAAY,EAAA,CAAyCI,YAAA,EAAAC,IAAAN,EAAAC,MCJzCT,EAAAU,EAAA,CAAAK,EAAAC,IAAAL,OAAAM,UAAAC,eAAAC,KAAAJ,EAAAC,GCgDO,SAASI,EACZC,EACAZ,EACAa,GAEA,GAAgC,mBAArBA,EAAWC,MAClB,OAAOD,EAGX,IAAIE,EAAYF,EAAWC,MAE3B,MAAO,CACH,GAAAT,GAEI,MAAMW,EAAcD,EAAOE,KAAKC,MAOhC,OALAhB,OAAOC,eAAee,KAAMlB,EAAGE,OAAAiB,OAAAjB,OAAAiB,OAAA,GACxBN,GAAU,CACbC,MAAOE,KAGJA,CACX,EACA,GA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aAAaC,KAAKJ,QAIzB,GAFA9E,OAAOiF,aAAaE,YAAW,GAE3BN,EAAiB,CACjB,MAAMO,EAAU7G,SAAS8G,eAAeR,GAExC,IAAKO,EACD,MAAM,IAAI5H,MAAM,sBAGpB4H,EAAQE,aAAa,qBAAsB,IAC3CtF,OAAOiF,aAAaM,2BAA2B,sBAE/CvF,OAAOiF,aAAaM,2BAA2B,aAG3D,CFFIC,CAAmBX,EAAiBC,GAE7BC,CACX","sources":["webpack://@bigcommerce/checkout-sdk/external module \"iframe-resizer\"","webpack://@bigcommerce/checkout-sdk/external module \"iframe-resizer/js/iframeResizer.contentWindow\"","webpack://@bigcommerce/checkout-sdk/webpack/bootstrap","webpack://@bigcommerce/checkout-sdk/webpack/runtime/define property getters","webpack://@bigcommerce/checkout-sdk/webpack/runtime/hasOwnProperty shorthand","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/bind-decorator/bind-decorator.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/invalid-argument-error.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/extension/extension-commands.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-internal-commands.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-internal-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-queries.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-listener.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/append-www.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-poster.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/initialize-extension-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-resizer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/iframe-resizer-setup.ts"],"sourcesContent":["var x = (y) => {\n\tvar x = {}; __webpack_require__.d(x, y); return x\n} \nvar y = (x) => (() => (x))\nmodule.exports = x({ [\"iframeResizer\"]: () => (__WEBPACK_EXTERNAL_MODULE_iframe_resizer_1512d797__.iframeResizer) });","module.exports = __WEBPACK_EXTERNAL_MODULE_iframe_resizer_js_iframeResizer_contentWindow_a6cfc03f__;","// 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","// 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))","/**\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 { 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\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 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","export type ExtensionCommand =\n | ReloadCheckoutCommand\n | ShowLoadingIndicatorCommand\n | SetIframeStyleCommand\n | ReRenderShippingForm\n | ReRenderShippingStep;\n\nexport enum ExtensionCommandType {\n ReloadCheckout = 'EXTENSION:RELOAD_CHECKOUT',\n ShowLoadingIndicator = 'EXTENSION:SHOW_LOADING_INDICATOR',\n SetIframeStyle = 'EXTENSION:SET_IFRAME_STYLE',\n ReRenderShippingForm = 'EXTENSION:RE_RENDER_SHIPPING_FORM',\n ReRenderShippingStep = 'EXTENSION:RE_RENDER_SHIPPING_STEP',\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 ReRenderShippingForm {\n type: ExtensionCommandType.ReRenderShippingForm;\n}\n\nexport interface ReRenderShippingStep {\n type: ExtensionCommandType.ReRenderShippingStep;\n}\nexport interface ExtensionCommandMap {\n [ExtensionCommandType.ReloadCheckout]: ReloadCheckoutCommand;\n [ExtensionCommandType.ShowLoadingIndicator]: ShowLoadingIndicatorCommand;\n [ExtensionCommandType.SetIframeStyle]: SetIframeStyleCommand;\n [ExtensionCommandType.ReRenderShippingForm]: ReRenderShippingForm;\n [ExtensionCommandType.ReRenderShippingStep]: ReRenderShippingStep;\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 { 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","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","export type ExtensionQuery = GetConsignmentsQuery;\n\nexport enum ExtensionQueryType {\n GetConsignments = 'EXTENSION:GET_CONSIGNMENTS',\n}\n\nexport interface GetConsignmentsQuery {\n type: ExtensionQueryType.GetConsignments;\n payload?: {\n useCache?: boolean;\n };\n}\n\nexport interface ExtensionQueryMap {\n [ExtensionQueryType.GetConsignments]: GetConsignmentsQuery;\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\nexport type EventListeners = {\n [key in keyof TEventMap]?: Array<(event: TEventMap[key], context?: TContext) => void>;\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 { 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 { noop } from 'lodash';\n\nimport { Consignment } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\n\nimport { ExtensionCommandType } from './extension-commands';\nimport { ExtensionEventMap, ExtensionEventType } from './extension-events';\nimport {\n ExtensionInternalCommand,\n ExtensionInternalCommandType,\n} from './extension-internal-commands';\nimport { ExtensionInternalEventType } from './extension-internal-events';\nimport {\n ExtensionCommandOrQuery,\n ExtensionCommandOrQueryContext,\n ExtensionMessageMap,\n ExtensionMessageType,\n GetConsignmentsMessage,\n} from './extension-message';\nimport { ExtensionQueryType } from './extension-queries';\n\nexport default class ExtensionService {\n private _extensionId?: string;\n\n constructor(\n private _messageListener: IframeEventListener,\n private _eventListener: IframeEventListener,\n private _messagePoster: IframeEventPoster<\n ExtensionCommandOrQuery,\n ExtensionCommandOrQueryContext\n >,\n private _internalCommandPoster: IframeEventPoster,\n ) {\n this._messagePoster.setTarget(window.parent);\n this._internalCommandPoster.setTarget(window.parent);\n }\n\n async initialize(extensionId: string): Promise {\n if (!extensionId) {\n throw new Error('Extension Id not found.');\n }\n\n this._extensionId = extensionId;\n\n this._messageListener.listen();\n this._eventListener.listen();\n this._messagePoster.setContext({ extensionId });\n\n try {\n await this._internalCommandPoster.post(\n {\n type: ExtensionInternalCommandType.ResizeIframe,\n payload: { extensionId },\n },\n {\n successType: ExtensionInternalEventType.ExtensionReady,\n errorType: ExtensionInternalEventType.ExtensionFailed,\n },\n );\n } catch (event) {\n if (this._isExtensionFailedEvent(event)) {\n throw new Error(\n 'Extension failed to load within 60 seconds; please reload and try again.',\n );\n }\n }\n }\n\n post(command: ExtensionCommandOrQuery): void {\n if (!this._isCommandOrQueryType(command.type)) {\n throw new Error(`${command.type} is not supported.`);\n }\n\n this._messagePoster.post(command);\n }\n\n addListener(eventType: ExtensionEventType, callback: () => void = noop): () => void {\n if (!this._extensionId) {\n throw new Error('Extension is not initialized.');\n }\n\n const extensionId = this._extensionId;\n\n if (!Object.values(ExtensionEventType).includes(eventType)) {\n throw new Error(`${eventType} is not supported.`);\n }\n\n this._internalCommandPoster.post({\n type: ExtensionInternalCommandType.Subscribe,\n payload: { extensionId, eventType },\n });\n\n this._eventListener.addListener(eventType, callback);\n\n return () => {\n this._internalCommandPoster.post({\n type: ExtensionInternalCommandType.Unsubscribe,\n payload: { extensionId, eventType },\n });\n\n this._eventListener.removeListener(eventType, callback);\n };\n }\n\n async getConsignments(useCache = true): Promise {\n return new Promise((resolve) => {\n const callback = (event: GetConsignmentsMessage) => {\n this._messageListener.removeListener(\n ExtensionMessageType.GetConsignments,\n callback,\n );\n\n resolve(event.payload.consignments);\n };\n\n this._messageListener.addListener(ExtensionMessageType.GetConsignments, callback);\n\n this.post({ type: ExtensionQueryType.GetConsignments, payload: { useCache } });\n });\n }\n\n private _isExtensionFailedEvent(\n event: any,\n ): event is ExtensionInternalEventType.ExtensionFailed {\n return event.type === ExtensionInternalEventType.ExtensionFailed;\n }\n\n private _isCommandOrQueryType(type: any): type is ExtensionCommandOrQuery['type'] {\n return (\n Object.values(ExtensionCommandType).includes(type) ||\n Object.values(ExtensionQueryType).includes(type)\n );\n }\n}\n","import {\n IframeEventListener,\n IframeEventPoster,\n setupContentWindowForIframeResizer,\n} from '../common/iframe';\n\nimport { ExtensionCommand } from './extension-commands';\nimport { ExtensionEventMap } from './extension-events';\nimport { ExtensionInternalCommand } from './extension-internal-commands';\nimport { ExtensionCommandOrQueryContext, ExtensionMessageMap } from './extension-message';\nimport ExtensionService from './extension-service';\nimport { iframeResizerSetup } from './iframe-resizer-setup';\n\nexport interface InitializeExtensionServiceOptions {\n extensionId: string;\n parentOrigin: string;\n taggedElementId?: string;\n fixedHeight?: number;\n}\n\nexport default async function initializeExtensionService(\n options: InitializeExtensionServiceOptions,\n): Promise {\n const { extensionId, parentOrigin, taggedElementId, fixedHeight } = options;\n\n setupContentWindowForIframeResizer();\n\n const extension = new ExtensionService(\n new IframeEventListener(parentOrigin),\n new IframeEventListener(parentOrigin),\n new IframeEventPoster(parentOrigin),\n new IframeEventPoster(parentOrigin),\n );\n\n await extension.initialize(extensionId);\n\n iframeResizerSetup(taggedElementId, fixedHeight);\n\n return extension;\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","export interface IframeResizerWindow extends Window {\n parentIFrame: {\n autoResize: (isEnabled: boolean) => void;\n setHeightCalculationMethod: (id: string) => void;\n size: (height: number) => void;\n };\n}\n\nexport function isIframeResizerWindow(window: Window): window is IframeResizerWindow {\n return 'parentIFrame' in window;\n}\n\nexport function iframeResizerSetup(\n taggedElementId: string | undefined,\n fixedHeight: number | undefined,\n): void {\n if (!isIframeResizerWindow(window)) {\n throw new Error('iFramerResizer window not found.');\n }\n\n if (fixedHeight) {\n window.parentIFrame.size(fixedHeight);\n } else {\n window.parentIFrame.autoResize(true);\n\n if (taggedElementId) {\n const element = document.getElementById(taggedElementId);\n\n if (!element) {\n throw new Error(`Element not found.`);\n }\n\n element.setAttribute('data-iframe-height', '');\n window.parentIFrame.setHeightCalculationMethod('taggedElement');\n } else {\n window.parentIFrame.setHeightCalculationMethod('bodyOffset');\n }\n }\n}\n"],"names":["y","x","module","exports","iframeResizer","__WEBPACK_EXTERNAL_MODULE_iframe_resizer_1512d797__","__webpack_require__","d","__WEBPACK_EXTERNAL_MODULE_iframe_resizer_js_iframeResizer_contentWindow_a6cfc03f__","__webpack_module_cache__","moduleId","cachedModule","undefined","__webpack_modules__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","bindMethodDecorator","_","descriptor","value","method","boundMethod","bind","this","assign","set","StandardError","Error","constructor","message","super","name","type","setPrototypeOf","__proto__","captureStackTrace","stack","InvalidArgumentError","parseUrl","url","test","anchor","document","createElement","href","port","indexOf","hostname","hash","origin","protocol","pathname","search","isIframeEvent","object","ExtensionCommandType","ExtensionEventType","ExtensionInternalCommandType","ExtensionInternalEventType","ExtensionQueryType","IframeEventListener","sourceOrigin","_sourceOrigins","replace","_isListening","_listeners","listen","window","addEventListener","_handleMessage","stopListen","removeEventListener","addListener","listener","listeners","push","removeListener","index","splice","trigger","event","context","forEach","messageEvent","data","_a","__rest","__decorate","target","decoratedTarget","getOwnPropertyNames","getOwnPropertyDescriptor","bindClassDecorator","IframeEventPoster","targetOrigin","_targetWindow","_context","_targetOrigin","post","options","targetWindow","result","__WEBPACK_EXTERNAL_MODULE_rxjs_fromEvent__","pipe","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_filter__","successType","errorType","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_map__","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_take__","toPromise","postMessage","setTarget","setContext","ExtensionService","_messageListener","_eventListener","_messagePoster","_internalCommandPoster","parent","initialize","extensionId","_extensionId","ResizeIframe","payload","ExtensionReady","ExtensionFailed","_isExtensionFailedEvent","command","_isCommandOrQueryType","eventType","callback","__WEBPACK_EXTERNAL_MODULE_lodash_noop__","values","includes","Subscribe","Unsubscribe","getConsignments","useCache","Promise","resolve","consignments","GetConsignments","initializeExtensionService","parentOrigin","taggedElementId","fixedHeight","extension","isIframeResizerWindow","parentIFrame","size","autoResize","element","getElementById","setAttribute","setHeightCalculationMethod","iframeResizerSetup"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"extension.js","mappings":"+NAEYA,ECKAC,gBCPZ,IAAAC,EACAC,EAGAC,EAAAC,SAJAH,EAIA,CAAqBI,cAAA,IAAAC,EAAA,eAHrBJ,EAAA,GAAaK,EAAA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,6BAEhCsD,GAGJS,EAAQ3D,EAAM2C,QAAQiB,eAG1BnH,KAAKyF,iBAAiB1C,YAAW,6BAAuC0D,GAExEzG,KAAKyE,KAAK,CAAEhE,KAAMyB,EAAmBkF,gBAAiBlB,QAAS,CAAEc,eAEzE,GAEQ,uBAAAX,CACJ9C,GAEA,OAAOA,EAAM9C,OAASwB,EAA2BmE,eACrD,CAEQ,qBAAAG,CAAsB9F,GAC1B,OACIzB,OAAO2H,OAAO7I,GAAsB8I,SAASnG,IAC7CzB,OAAO2H,OAAOzE,GAAoB0E,SAASnG,EAEnD,ECjHW,SAAe4G,EAC1B3C,wCAEA,MAAMqB,YAAEA,EAAWuB,aAAEA,EAAYC,gBAAEA,EAAeC,YAAEA,GAAgB9C,ECmBpErG,EAAQ,KDfR,MAAMoJ,EAAY,IAAIjC,EAClB,IAAIrD,EAAyCmF,GAC7C,IAAInF,EAAuCmF,GAC3C,IAAIlD,EAAoEkD,GACxE,IAAIlD,EAA4CkD,IAOpD,aAJMG,EAAU3B,WAAWC,GEtBxB,SACHwB,EACAC,GAEA,IARG,SAA+B9E,GAClC,MAAO,iBAAkBA,CAC7B,CAMSgF,CAAsBhF,QACvB,MAAM,IAAItC,MAAM,oCAGpB,GAAIoH,EACA9E,OAAOiF,aAAaC,KAAKJ,QAIzB,GAFA9E,OAAOiF,aAAaE,YAAW,GAE3BN,EAAiB,CACjB,MAAMO,EAAU3G,SAAS4G,eAAeR,GAExC,IAAKO,EACD,MAAM,IAAI1H,MAAM,sBAGpB0H,EAAQE,aAAa,qBAAsB,IAC3CtF,OAAOiF,aAAaM,2BAA2B,sBAE/CvF,OAAOiF,aAAaM,2BAA2B,aAG3D,CFFIC,CAAmBX,EAAiBC,GAE7BC,CACX","sources":["webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-commands.ts","webpack://@bigcommerce/checkout-sdk/external module \"iframe-resizer\"","webpack://@bigcommerce/checkout-sdk/external module \"iframe-resizer/js/iframeResizer.contentWindow\"","webpack://@bigcommerce/checkout-sdk/webpack/bootstrap","webpack://@bigcommerce/checkout-sdk/webpack/runtime/define property getters","webpack://@bigcommerce/checkout-sdk/webpack/runtime/hasOwnProperty shorthand","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/bind-decorator/bind-decorator.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/invalid-argument-error.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/extension/extension-internal-commands.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-internal-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-queries.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-listener.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/append-www.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-poster.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/initialize-extension-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-resizer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/iframe-resizer-setup.ts"],"sourcesContent":["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","export type ExtensionCommand =\n | ReloadCheckoutCommand\n | ShowLoadingIndicatorCommand\n | SetIframeStyleCommand\n | ReRenderShippingForm\n | ReRenderShippingStep;\n\nexport enum ExtensionCommandType {\n ReloadCheckout = 'EXTENSION:RELOAD_CHECKOUT',\n ShowLoadingIndicator = 'EXTENSION:SHOW_LOADING_INDICATOR',\n SetIframeStyle = 'EXTENSION:SET_IFRAME_STYLE',\n ReRenderShippingForm = 'EXTENSION:RE_RENDER_SHIPPING_FORM',\n ReRenderShippingStep = 'EXTENSION:RE_RENDER_SHIPPING_STEP',\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 ReRenderShippingForm {\n type: ExtensionCommandType.ReRenderShippingForm;\n}\n\nexport interface ReRenderShippingStep {\n type: ExtensionCommandType.ReRenderShippingStep;\n}\nexport interface ExtensionCommandMap {\n [ExtensionCommandType.ReloadCheckout]: ReloadCheckoutCommand;\n [ExtensionCommandType.ShowLoadingIndicator]: ShowLoadingIndicatorCommand;\n [ExtensionCommandType.SetIframeStyle]: SetIframeStyleCommand;\n [ExtensionCommandType.ReRenderShippingForm]: ReRenderShippingForm;\n [ExtensionCommandType.ReRenderShippingStep]: ReRenderShippingStep;\n}\n","var x = (y) => {\n\tvar x = {}; __webpack_require__.d(x, y); return x\n} \nvar y = (x) => (() => (x))\nmodule.exports = x({ [\"iframeResizer\"]: () => (__WEBPACK_EXTERNAL_MODULE_iframe_resizer_1512d797__.iframeResizer) });","module.exports = __WEBPACK_EXTERNAL_MODULE_iframe_resizer_js_iframeResizer_contentWindow_a6cfc03f__;","// 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","// 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))","/**\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 { 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\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 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 { 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","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","export type ExtensionQuery = GetConsignmentsQuery;\n\nexport enum ExtensionQueryType {\n GetConsignments = 'EXTENSION:GET_CONSIGNMENTS',\n}\n\nexport interface GetConsignmentsQuery {\n type: ExtensionQueryType.GetConsignments;\n payload?: {\n useCache?: boolean;\n };\n}\n\nexport interface ExtensionQueryMap {\n [ExtensionQueryType.GetConsignments]: GetConsignmentsQuery;\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\nexport type EventListeners = {\n [key in keyof TEventMap]?: Array<(event: TEventMap[key], context?: TContext) => void>;\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 { 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 { noop } from 'lodash';\n\nimport { Consignment } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\n\nimport { ExtensionCommandType } from './extension-commands';\nimport { ExtensionEventMap, ExtensionEventType } from './extension-events';\nimport {\n ExtensionInternalCommand,\n ExtensionInternalCommandType,\n} from './extension-internal-commands';\nimport { ExtensionInternalEventType } from './extension-internal-events';\nimport {\n ExtensionCommandOrQuery,\n ExtensionCommandOrQueryContext,\n ExtensionMessageMap,\n ExtensionMessageType,\n GetConsignmentsMessage,\n} from './extension-message';\nimport { ExtensionQueryType } from './extension-queries';\n\nexport default class ExtensionService {\n private _extensionId?: string;\n\n constructor(\n private _messageListener: IframeEventListener,\n private _eventListener: IframeEventListener,\n private _messagePoster: IframeEventPoster<\n ExtensionCommandOrQuery,\n ExtensionCommandOrQueryContext\n >,\n private _internalCommandPoster: IframeEventPoster,\n ) {\n this._messagePoster.setTarget(window.parent);\n this._internalCommandPoster.setTarget(window.parent);\n }\n\n async initialize(extensionId: string): Promise {\n if (!extensionId) {\n throw new Error('Extension Id not found.');\n }\n\n this._extensionId = extensionId;\n\n this._messageListener.listen();\n this._eventListener.listen();\n this._messagePoster.setContext({ extensionId });\n\n try {\n await this._internalCommandPoster.post(\n {\n type: ExtensionInternalCommandType.ResizeIframe,\n payload: { extensionId },\n },\n {\n successType: ExtensionInternalEventType.ExtensionReady,\n errorType: ExtensionInternalEventType.ExtensionFailed,\n },\n );\n } catch (event) {\n if (this._isExtensionFailedEvent(event)) {\n throw new Error(\n 'Extension failed to load within 60 seconds; please reload and try again.',\n );\n }\n }\n }\n\n post(command: ExtensionCommandOrQuery): void {\n if (!this._isCommandOrQueryType(command.type)) {\n throw new Error(`${command.type} is not supported.`);\n }\n\n this._messagePoster.post(command);\n }\n\n addListener(eventType: ExtensionEventType, callback: () => void = noop): () => void {\n if (!this._extensionId) {\n throw new Error('Extension is not initialized.');\n }\n\n const extensionId = this._extensionId;\n\n if (!Object.values(ExtensionEventType).includes(eventType)) {\n throw new Error(`${eventType} is not supported.`);\n }\n\n this._internalCommandPoster.post({\n type: ExtensionInternalCommandType.Subscribe,\n payload: { extensionId, eventType },\n });\n\n this._eventListener.addListener(eventType, callback);\n\n return () => {\n this._internalCommandPoster.post({\n type: ExtensionInternalCommandType.Unsubscribe,\n payload: { extensionId, eventType },\n });\n\n this._eventListener.removeListener(eventType, callback);\n };\n }\n\n async getConsignments(useCache = true): Promise {\n return new Promise((resolve) => {\n const callback = (event: GetConsignmentsMessage) => {\n this._messageListener.removeListener(\n ExtensionMessageType.GetConsignments,\n callback,\n );\n\n resolve(event.payload.consignments);\n };\n\n this._messageListener.addListener(ExtensionMessageType.GetConsignments, callback);\n\n this.post({ type: ExtensionQueryType.GetConsignments, payload: { useCache } });\n });\n }\n\n private _isExtensionFailedEvent(\n event: any,\n ): event is ExtensionInternalEventType.ExtensionFailed {\n return event.type === ExtensionInternalEventType.ExtensionFailed;\n }\n\n private _isCommandOrQueryType(type: any): type is ExtensionCommandOrQuery['type'] {\n return (\n Object.values(ExtensionCommandType).includes(type) ||\n Object.values(ExtensionQueryType).includes(type)\n );\n }\n}\n","import {\n IframeEventListener,\n IframeEventPoster,\n setupContentWindowForIframeResizer,\n} from '../common/iframe';\n\nimport { ExtensionCommand } from './extension-commands';\nimport { ExtensionEventMap } from './extension-events';\nimport { ExtensionInternalCommand } from './extension-internal-commands';\nimport { ExtensionCommandOrQueryContext, ExtensionMessageMap } from './extension-message';\nimport ExtensionService from './extension-service';\nimport { iframeResizerSetup } from './iframe-resizer-setup';\n\nexport interface InitializeExtensionServiceOptions {\n extensionId: string;\n parentOrigin: string;\n taggedElementId?: string;\n fixedHeight?: number;\n}\n\nexport default async function initializeExtensionService(\n options: InitializeExtensionServiceOptions,\n): Promise {\n const { extensionId, parentOrigin, taggedElementId, fixedHeight } = options;\n\n setupContentWindowForIframeResizer();\n\n const extension = new ExtensionService(\n new IframeEventListener(parentOrigin),\n new IframeEventListener(parentOrigin),\n new IframeEventPoster(parentOrigin),\n new IframeEventPoster(parentOrigin),\n );\n\n await extension.initialize(extensionId);\n\n iframeResizerSetup(taggedElementId, fixedHeight);\n\n return extension;\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","export interface IframeResizerWindow extends Window {\n parentIFrame: {\n autoResize: (isEnabled: boolean) => void;\n setHeightCalculationMethod: (id: string) => void;\n size: (height: number) => void;\n };\n}\n\nexport function isIframeResizerWindow(window: Window): window is IframeResizerWindow {\n return 'parentIFrame' in window;\n}\n\nexport function iframeResizerSetup(\n taggedElementId: string | undefined,\n fixedHeight: number | undefined,\n): void {\n if (!isIframeResizerWindow(window)) {\n throw new Error('iFramerResizer window not found.');\n }\n\n if (fixedHeight) {\n window.parentIFrame.size(fixedHeight);\n } else {\n window.parentIFrame.autoResize(true);\n\n if (taggedElementId) {\n const element = document.getElementById(taggedElementId);\n\n if (!element) {\n throw new Error(`Element not found.`);\n }\n\n element.setAttribute('data-iframe-height', '');\n window.parentIFrame.setHeightCalculationMethod('taggedElement');\n } else {\n window.parentIFrame.setHeightCalculationMethod('bodyOffset');\n }\n }\n}\n"],"names":["ExtensionEventType","ExtensionCommandType","y","x","module","exports","iframeResizer","__WEBPACK_EXTERNAL_MODULE_iframe_resizer_1512d797__","__webpack_require__","d","__WEBPACK_EXTERNAL_MODULE_iframe_resizer_js_iframeResizer_contentWindow_a6cfc03f__","__webpack_module_cache__","moduleId","cachedModule","undefined","__webpack_modules__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","bindMethodDecorator","_","descriptor","value","method","boundMethod","bind","this","assign","set","StandardError","Error","constructor","message","super","name","type","setPrototypeOf","__proto__","captureStackTrace","stack","InvalidArgumentError","parseUrl","url","test","anchor","document","createElement","href","port","indexOf","hostname","hash","origin","protocol","pathname","search","isIframeEvent","object","ExtensionInternalCommandType","ExtensionInternalEventType","ExtensionQueryType","IframeEventListener","sourceOrigin","_sourceOrigins","replace","_isListening","_listeners","listen","window","addEventListener","_handleMessage","stopListen","removeEventListener","addListener","listener","listeners","push","removeListener","index","splice","trigger","event","context","forEach","messageEvent","data","_a","__rest","__decorate","target","decoratedTarget","getOwnPropertyNames","getOwnPropertyDescriptor","bindClassDecorator","IframeEventPoster","targetOrigin","_targetWindow","_context","_targetOrigin","post","options","targetWindow","result","__WEBPACK_EXTERNAL_MODULE_rxjs_fromEvent__","pipe","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_filter__","successType","errorType","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_map__","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_take__","toPromise","postMessage","setTarget","setContext","ExtensionService","_messageListener","_eventListener","_messagePoster","_internalCommandPoster","parent","initialize","extensionId","_extensionId","ResizeIframe","payload","ExtensionReady","ExtensionFailed","_isExtensionFailedEvent","command","_isCommandOrQueryType","eventType","callback","__WEBPACK_EXTERNAL_MODULE_lodash_noop__","values","includes","Subscribe","Unsubscribe","getConsignments","useCache","Promise","resolve","consignments","GetConsignments","initializeExtensionService","parentOrigin","taggedElementId","fixedHeight","extension","isIframeResizerWindow","parentIFrame","size","autoResize","element","getElementById","setAttribute","setHeightCalculationMethod","iframeResizerSetup"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/esm/integrations/offline.js b/dist/esm/integrations/offline.js index 51b9f3b5d3..e9d7f165da 100644 --- a/dist/esm/integrations/offline.js +++ b/dist/esm/integrations/offline.js @@ -1,2 +1,2 @@ -class e extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}class t extends e{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}class r{constructor(e){this._paymentIntegrationService=e}execute(e,t){return r=this,n=void 0,i=function*(){return yield this._paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:e.payment?{methodId:e.payment.methodId}:void 0}),t),Promise.resolve()},new((o=void 0)||(o=Promise))(function(e,t){function s(e){try{c(i.next(e))}catch(e){t(e)}}function a(e){try{c(i.throw(e))}catch(e){t(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof o?r:new o(function(e){e(r)})).then(s,a)}c((i=i.apply(r,n||[])).next())});var r,n,o,i}finalize(){return Promise.reject(new t)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const n=(o=e=>new r(e),i=[{type:"PAYMENT_TYPE_OFFLINE"}],Object.assign(o,{resolveIds:i}));var o,i;export{n as createOfflinePaymentStrategy}; +class e extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}class t extends e{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}class r{constructor(e){this._paymentIntegrationService=e}execute(e,t){return r=this,n=void 0,o=function*(){return console.log("payload =======1",e),yield this._paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:e.payment?Object.assign({methodId:e.payment.methodId},"purchaseorder"===e.payment.methodId&&{paymentData:e.payment.paymentData}):void 0}),t),Promise.resolve()},new((a=void 0)||(a=Promise))(function(e,t){function i(e){try{c(o.next(e))}catch(e){t(e)}}function s(e){try{c(o.throw(e))}catch(e){t(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a(function(e){e(r)})).then(i,s)}c((o=o.apply(r,n||[])).next())});var r,n,a,o}finalize(){return Promise.reject(new t)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const n=(a=e=>new r(e),o=[{type:"PAYMENT_TYPE_OFFLINE"}],Object.assign(a,{resolveIds:o}));var a,o;export{n as createOfflinePaymentStrategy}; //# sourceMappingURL=offline.js.map \ No newline at end of file diff --git a/dist/esm/integrations/offline.js.map b/dist/esm/integrations/offline.js.map index 7af172be03..46ae5560e9 100644 --- a/dist/esm/integrations/offline.js.map +++ b/dist/esm/integrations/offline.js.map @@ -1 +1 @@ -{"version":3,"file":"integrations/offline.js","mappings":"AAOe,MAAeA,UAAsBC,MAIhD,WAAAC,CAAYC,GCXD,IAAqCC,EDY5CC,MAAMF,GAAW,qCAJrBG,KAAAC,KAAO,gBACPD,KAAAE,KAAO,WCTyCJ,aDcZA,UCbhCK,OAAOC,eACPD,OAAOC,eDYQJ,KCZeF,GDYfE,KCVRK,UAAYP,EDYoB,mBAA5BH,MAAMW,kBACbX,MAAMW,kBAAkBN,iBAExBA,KAAKO,MAAQ,IAAIZ,MAAMK,KAAKH,SAASU,KAE7C,EEfW,MAAMC,UAA0Cd,EAC3D,WAAAE,GACIG,MAAM,kEAENC,KAAKC,KAAO,oCACZD,KAAKE,KAAO,iCAChB,ECJW,MAAMO,EACjB,WAAAb,CAAoBc,GAAAV,KAAAU,2BAAAA,CAAwD,CAEtE,OAAAC,CAAQC,EAA2BC,wCASrC,aARMb,KAAKU,2BAA2BI,YAAWX,OAAAY,OAAAZ,OAAAY,OAAA,GAEtCH,GAAO,CACVI,QAASJ,EAAQI,QAAU,CAAEC,SAAUL,EAAQI,QAAQC,eAAaC,IAExEL,GAGGM,QAAQC,SACnB,6RAEA,QAAAC,GACI,OAAOF,QAAQG,OAAO,IAAId,EAC9B,CAEA,UAAAe,GACI,OAAOJ,QAAQC,SACnB,CAEA,YAAAI,GACI,OAAOL,QAAQC,SACnB,EC1BJ,MAIAK,GCRIC,EDKAC,GACC,IAAIlB,EAAuBkB,GCL5BC,EDO4D,CAAC,CAAE1B,KAAM,yBCL9DC,OAAOY,OAAOW,EAAQ,CAAEE,gBAJpB,IACXF,EACAE","sources":["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/order-finalization-not-required-error.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/payment-integration-api/src/to-resolvable-module.ts"],"sourcesContent":["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 * 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 {\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 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"],"names":["StandardError","Error","constructor","message","prototype","super","this","name","type","Object","setPrototypeOf","__proto__","captureStackTrace","stack","OrderFinalizationNotRequiredError","OfflinePaymentStrategy","_paymentIntegrationService","execute","payload","options","submitOrder","assign","payment","methodId","undefined","Promise","resolve","finalize","reject","initialize","deinitialize","create_offline_payment_strategy","module","paymentIntegrationService","resolveIds"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"integrations/offline.js","mappings":"AAOe,MAAeA,UAAsBC,MAIhD,WAAAC,CAAYC,GCXD,IAAqCC,EDY5CC,MAAMF,GAAW,qCAJrBG,KAAAC,KAAO,gBACPD,KAAAE,KAAO,WCTyCJ,aDcZA,UCbhCK,OAAOC,eACPD,OAAOC,eDYQJ,KCZeF,GDYfE,KCVRK,UAAYP,EDYoB,mBAA5BH,MAAMW,kBACbX,MAAMW,kBAAkBN,iBAExBA,KAAKO,MAAQ,IAAIZ,MAAMK,KAAKH,SAASU,KAE7C,EEfW,MAAMC,UAA0Cd,EAC3D,WAAAE,GACIG,MAAM,kEAENC,KAAKC,KAAO,oCACZD,KAAKE,KAAO,iCAChB,ECJW,MAAMO,EACjB,WAAAb,CAAoBc,GAAAV,KAAAU,2BAAAA,CAAwD,CAEtE,OAAAC,CAAQC,EAA2BC,wCAmBrC,OAjBAC,QAAQC,IAAI,mBAAoBH,SAE1BZ,KAAKU,2BAA2BM,YAAWb,OAAAc,OAAAd,OAAAc,OAAA,GAEtCL,GAAO,CACVM,QAASN,EAAQM,QACZf,OAAAc,OAAA,CACKE,SAAUP,EAAQM,QAAQC,UACO,kBAA7BP,EAAQM,QAAQC,UAAgC,CAChDC,YAAaR,EAAQM,QAAQE,mBAGrCC,IAEVR,GAGGS,QAAQC,SACnB,6RAEA,QAAAC,GACI,OAAOF,QAAQG,OAAO,IAAIjB,EAC9B,CAEA,UAAAkB,GACI,OAAOJ,QAAQC,SACnB,CAEA,YAAAI,GACI,OAAOL,QAAQC,SACnB,ECpCJ,MAIAK,GCRIC,EDKAC,GACC,IAAIrB,EAAuBqB,GCL5BC,EDO4D,CAAC,CAAE7B,KAAM,yBCL9DC,OAAOc,OAAOY,EAAQ,CAAEE,gBAJpB,IACXF,EACAE","sources":["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/order-finalization-not-required-error.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/payment-integration-api/src/to-resolvable-module.ts"],"sourcesContent":["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 * 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 {\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\n console.log('payload =======1', payload)\n\n await this._paymentIntegrationService.submitOrder(\n {\n ...payload,\n payment: payload.payment\n ? {\n methodId: payload.payment.methodId,\n ...(payload.payment.methodId === 'purchaseorder' && {\n paymentData: payload.payment.paymentData,\n }),\n }\n : 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 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"],"names":["StandardError","Error","constructor","message","prototype","super","this","name","type","Object","setPrototypeOf","__proto__","captureStackTrace","stack","OrderFinalizationNotRequiredError","OfflinePaymentStrategy","_paymentIntegrationService","execute","payload","options","console","log","submitOrder","assign","payment","methodId","paymentData","undefined","Promise","resolve","finalize","reject","initialize","deinitialize","create_offline_payment_strategy","module","paymentIntegrationService","resolveIds"],"sourceRoot":""} \ No newline at end of file diff --git a/packages/offline-integration/src/offline-payment-strategy.ts b/packages/offline-integration/src/offline-payment-strategy.ts index 6ac32e36cf..01049921aa 100644 --- a/packages/offline-integration/src/offline-payment-strategy.ts +++ b/packages/offline-integration/src/offline-payment-strategy.ts @@ -10,10 +10,20 @@ export default class OfflinePaymentStrategy implements PaymentStrategy { constructor(private _paymentIntegrationService: PaymentIntegrationService) {} async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise { + + console.log('payload =======1', payload) + await this._paymentIntegrationService.submitOrder( { ...payload, - payment: payload.payment ? { methodId: payload.payment.methodId } : undefined, + payment: payload.payment + ? { + methodId: payload.payment.methodId, + ...(payload.payment.methodId === 'purchaseorder' && { + paymentData: payload.payment.paymentData, + }), + } + : undefined, }, options, ); From e0795585f141ca4cea8debbd4a49525efa06a2ed Mon Sep 17 00:00:00 2001 From: bc-alfreid Date: Thu, 14 May 2026 15:28:42 +1000 Subject: [PATCH 2/3] feat(payment): PAYMENTS-11577 create local interface for payment data for offline strategy --- dist/esm/checkout-sdk.js | 2 +- dist/esm/checkout-sdk.js.map | 2 +- dist/esm/extension.js | 2 +- dist/esm/extension.js.map | 2 +- dist/esm/integrations/offline.js | 2 +- dist/esm/integrations/offline.js.map | 2 +- .../src/offline-payment-strategy.spec.ts | 65 +++++++++++++++++++ .../src/offline-payment-strategy.ts | 23 +++++-- 8 files changed, 88 insertions(+), 12 deletions(-) diff --git a/dist/esm/checkout-sdk.js b/dist/esm/checkout-sdk.js index dcf3ea29cf..5919b2cf8b 100644 --- a/dist/esm/checkout-sdk.js +++ b/dist/esm/checkout-sdk.js @@ -1,2 +1,2 @@ -import*as e from"iframe-resizer";import*as t from"iframe-resizer/js/iframeResizer.contentWindow";import{createRequestSender as n,createTimeout as i}from"@bigcommerce/request-sender";import{ScriptLoader as r,createScriptLoader as o,getScriptLoader as a,getStylesheetLoader as s}from"@bigcommerce/script-loader";import{combineReducers as d,composeReducers as c,createAction as l,createDataStore as u,createErrorAction as h,deepFreeze as p}from"@bigcommerce/data-store";import{Observable as m,Subject as y,concat as g,defer as v,empty as f,from as S,fromEvent as _,merge as w,noop as I,of as C,throwError as b}from"rxjs";import{catchError as P,delay as O,distinctUntilChanged as E,filter as A,map as T,retryWhen as k,shareReplay as D,switchMap as M,take as z}from"rxjs/operators";import{cond as N,constant as x,difference as R,each as F,filter as L,find as B,findIndex as j,flatMap as U,flatten as q,get as V,identity as G,includes as H,isArray as W,isEmpty as $,isEqual as Y,isMatch as K,isNil as J,isObject as Z,isPlainObject as Q,isString as X,isUndefined as ee,kebabCase as te,keyBy as ne,keys as ie,last as re,map as oe,max as ae,memoize as se,merge as de,noop as ce,omit as le,omitBy as ue,overSome as he,pick as pe,pickBy as me,reduce as ye,round as ge,some as ve,stubTrue as fe,transform as Se,union as _e,uniq as we,uniqueId as Ie,values as Ce,without as be}from"lodash";import{memoize as Pe,memoizeOne as Oe}from"@bigcommerce/memoize";import{createFormPoster as Ee}from"@bigcommerce/form-poster";import{supportsPopups as Ae}from"@braintree/browser-detection";import{default as Te}from"local-storage-fallback";import{createClient as ke}from"@bigcommerce/bigpay-client";import{creditCardType as De,number as Me}from"card-validator";import{exclude as ze,parseUrl as Ne,stringifyUrl as xe}from"query-string";import{createSelector as Re,createSelectorCreator as Fe,defaultMemoize as Le}from"reselect";import{default as Be}from"shallowequal";import{IntlMessageFormat as je}from"intl-messageformat";var Ue={785(t,n,i){var r,o;t.exports=(r={iframeResizer:()=>e.iframeResizer},o={},i.d(o,r),o)},939(e){e.exports=t}},qe={};function Ve(e){var t=qe[e];if(void 0!==t)return t.exports;var n=qe[e]={exports:{}};return Ue[e](n,n.exports,Ve),n.exports}Ve.d=(e,t)=>{for(var n in t)Ve.o(t,n)&&!Ve.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},Ve.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ve.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var Ge={};Ve.r(Ge),Ve.d(Ge,{createAmazonPayV2CustomerStrategy:()=>Ii,createApplePayCustomerStrategy:()=>Xi,createBigCommercePaymentsCustomerStrategy:()=>br,createBigCommercePaymentsFastlaneCustomerStrategy:()=>Hr,createBigCommercePaymentsPayLaterCustomerStrategy:()=>Yr,createBigCommercePaymentsVenmoCustomerStrategy:()=>Zr,createBoltCustomerStrategy:()=>so,createBraintreeFastlaneCustomerStrategy:()=>zo,createBraintreePaypalCreditCustomerStrategy:()=>Oo,createBraintreePaypalCustomerStrategy:()=>Co,createBraintreeVisaCheckoutCustomerStrategy:()=>Ro,createGooglePayAdyenV2CustomerStrategy:()=>ca,createGooglePayAdyenV3CustomerStrategy:()=>la,createGooglePayAuthorizeDotNetCustomerStrategy:()=>ha,createGooglePayBigCommercePaymentsCustomerStrategy:()=>as,createGooglePayBnzCustomerStrategy:()=>_a,createGooglePayBraintreeCustomerStrategy:()=>Ya,createGooglePayCheckoutComCustomerStrategy:()=>va,createGooglePayCybersourceCustomerStrategy:()=>Sa,createGooglePayOrbitalCustomerStrategy:()=>Ia,createGooglePayPayPalCommerceCustomerStrategy:()=>is,createGooglePayStripeCustomerStrategy:()=>qa,createGooglePayStripeUpeCustomerStrategy:()=>Va,createGooglePayTdOnlineMartCustomerStrategy:()=>ls,createGooglePayWorldpayAccessCustomerStrategy:()=>Ha,createPayPalCommerceCreditCustomerStrategy:()=>Js,createPayPalCommerceCustomerStrategy:()=>zs,createPayPalCommerceFastlaneCustomerStrategy:()=>sd,createPayPalCommerceVenmoCustomerStrategy:()=>Xs,createStripeLinkV2CustomerStrategy:()=>Id,createStripeUPECustomerStrategy:()=>ud});var He={};Ve.r(He),Ve.d(He,{createAdyenV2PaymentStrategy:()=>Ld,createAdyenV3PaymentStrategy:()=>Vd,createAffirmPaymentStrategy:()=>Yd,createAfterpayPaymentStrategy:()=>tc,createAmazonPayV2PaymentStrategy:()=>rc,createApplePayPaymentStrategy:()=>dc,createBigCommercePaymentsAlternativeMethodsPaymentStrategy:()=>xc,createBigCommercePaymentsCreditCardsPaymentStrategy:()=>Mc,createBigCommercePaymentsFastlanePaymentStrategy:()=>fc,createBigCommercePaymentsPayLaterPaymentStrategy:()=>wc,createBigCommercePaymentsPaymentStrategy:()=>mc,createBigCommercePaymentsRatePayPayPaymentStrategy:()=>Pc,createBigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy:()=>Fc,createBigCommercePaymentsVenmoPaymentStrategy:()=>jc,createBlueSnapDirectAPMPaymentStrategy:()=>al,createBlueSnapDirectCreditCardPaymentStrategy:()=>rl,createBlueSnapV2PaymentStrategy:()=>ul,createBoltPaymentStrategy:()=>fl,createBraintreeAchPaymentStrategy:()=>Il,createBraintreeCreditCardPaymentStrategy:()=>Ql,createBraintreeFastlanePaymentStrategy:()=>Ll,createBraintreeLocalMethodsPaymentStrategy:()=>Nl,createBraintreePaypalPaymentStrategy:()=>kl,createBraintreeVenmoPaymentStrategy:()=>Gl,createBraintreeVisaCheckoutPaymentStrategy:()=>Ul,createCBAMPGSPaymentStrategy:()=>ou,createCheckoutComAPMPaymentStrategy:()=>wu,createCheckoutComCreditCardPaymentStrategy:()=>mu,createCheckoutComFawryPaymentStrategy:()=>cu,createCheckoutComIdealPaymentStrategy:()=>fu,createCheckoutComSepaPaymentStrategy:()=>gu,createClearpayPaymentStrategy:()=>Pu,createCreditCardPaymentStrategy:()=>Ou,createCyberSourcePaymentStrategy:()=>Uu,createCyberSourceV2PaymentStrategy:()=>Wu,createGooglePayAdyenV2PaymentStrategy:()=>Qu,createGooglePayAdyenV3PaymentStrategy:()=>th,createGooglePayAuthorizeNetPaymentStrategy:()=>nh,createGooglePayBigCommercePaymentsPaymentStrategy:()=>fh,createGooglePayBraintreePaymentStrategy:()=>dh,createGooglePayCheckoutComPaymentStrategy:()=>ih,createGooglePayCybersourcePaymentStrategy:()=>rh,createGooglePayOrbitalPaymentStrategy:()=>oh,createGooglePayPPCPPaymentStrategy:()=>ph,createGooglePayStripePaymentStrategy:()=>ah,createGooglePayTdOnlineMartPaymentStrategy:()=>Sh,createGooglePayWorldpayAccessPaymentStrategy:()=>sh,createHummPaymentStrategy:()=>Ih,createKlarnaPaymentStrategy:()=>Ah,createKlarnaV2PaymentStrategy:()=>zh,createLegacyPaymentStrategy:()=>xh,createMolliePaymentStrategy:()=>Uh,createMonerisPaymentStrategy:()=>Hh,createNoPaymentStrategy:()=>Pd,createOfflinePaymentStrategy:()=>$h,createOffsitePaymentStrategy:()=>Jh,createPayPalCommerceAlternativeMethodsPaymentStrategy:()=>lp,createPayPalCommerceCreditCardsPaymentStrategy:()=>pp,createPayPalCommerceCreditPaymentStrategy:()=>ip,createPayPalCommerceFastlanePaymentStrategy:()=>_p,createPayPalCommercePaymentStrategy:()=>ep,createPayPalCommerceRatePayPaymentStrategy:()=>gp,createPayPalCommerceVenmoPaymentStrategy:()=>ap,createPayPalProPaymentStrategy:()=>zp,createPaypalExpressPaymentStrategy:()=>kp,createSagePayPaymentStrategy:()=>xp,createSezzlePaymentStrategy:()=>Lp,createSquareV2PaymentStrategy:()=>Wp,createStripeCSPaymentStrategy:()=>ym,createStripeOCSPaymentStrategy:()=>hm,createStripeUPEPaymentStrategy:()=>dm,createStripeV3PaymentStrategy:()=>im,createTDOnlineMartPaymentStrategy:()=>_m,createWorldpayAccessOpenBankingPaymentStrategy:()=>Em,createWorldpayAccessPaymentStrategy:()=>Pm,createZipPaymentStrategy:()=>km});var We={};Ve.r(We),Ve.d(We,{createAmazonPayV2ButtonStrategy:()=>w_,createApplePayButtonStrategy:()=>O_,createBigCommercePaymentsButtonStrategy:()=>T_,createBigCommercePaymentsPayLaterButtonStrategy:()=>M_,createBigCommercePaymentsVenmoButtonStrategy:()=>x_,createBoltButtonStrategy:()=>F_,createBraintreePaypalButtonStrategy:()=>q_,createBraintreePaypalCreditButtonStrategy:()=>H_,createBraintreeVenmoButtonStrategy:()=>ew,createBraintreeVisaCheckoutButtonStrategy:()=>Y_,createGooglePayAdyenV2ButtonStrategy:()=>aw,createGooglePayAdyenV3ButtonStrategy:()=>sw,createGooglePayAuthorizeDotNetButtonStrategy:()=>dw,createGooglePayBigCommercePaymentsButtonStrategy:()=>ow,createGooglePayBraintreeButtonStrategy:()=>iw,createGooglePayCheckoutComButtonStrategy:()=>cw,createGooglePayCybersourceButtonStrategy:()=>lw,createGooglePayOrbitalButtonStrategy:()=>uw,createGooglePayPayPalCommerceButtonStrategy:()=>rw,createGooglePayStripeButtonStrategy:()=>hw,createGooglePayTdOnlineMartButtonStrategy:()=>mw,createGooglePayWorldpayAccessButtonStrategy:()=>pw,createLinkV2ButtonStrategy:()=>Aw,createPayPalCommerceButtonStrategy:()=>gw,createPayPalCommerceCreditButtonStrategy:()=>Sw,createPayPalCommerceVenmoButtonStrategy:()=>Iw,createPaypalExpressButtonStrategy:()=>Pw});const $e="b2bExtraField_";function Ye(e){return e.name.startsWith($e)}function Ke(e){var t;const{fieldType:n,type:i}=function(e){switch(e){case"multiline_text":return{fieldType:"multiline",type:"string"};case"number":return{fieldType:"text",type:"integer"};case"dropdown":return{fieldType:"dropdown",type:"array"};default:return{fieldType:"text",type:"string"}}}(e.type);let r;return e.config.numberOfRows&&(r={rows:e.config.numberOfRows}),(null===(t=e.config.options)||void 0===t?void 0:t.length)&&(r=Object.assign(Object.assign({},r),{items:e.config.options.map(e=>({value:e,label:e}))})),{id:`${$e}${e.id}`,name:`${$e}${e.id}`,custom:!1,label:e.name,hidden:!e.visibleToStorefront,required:e.isRequired,default:null!=e.config.defaultValue?String(e.config.defaultValue):void 0,fieldType:n,type:i,maxLength:e.config.maxLength,max:e.config.maxValue,options:r}}function Je(e,t,n){return(i=t)&&i.type&&i.error?g(C(t),b(h(e,t.payload,n))):b(h(e,t,n));var i}var Ze;!function(e){e.LoadB2BTokenRequested="LOAD_B2B_TOKEN_REQUESTED",e.LoadB2BTokenSucceeded="LOAD_B2B_TOKEN_SUCCEEDED",e.LoadB2BTokenFailed="LOAD_B2B_TOKEN_FAILED"}(Ze||(Ze={}));class Qe{constructor(e){this._requestSender=e}loadB2BToken(e){return t=>{var n;const i=t.getState(),r=i.config.getStoreConfigOrThrow(),{storeHash:o}=r.storeProfile,{baseUrl:a="",clientId:s=""}=null!==(n=r.b2bApiSettings)&&void 0!==n?n:{},{id:d}=i.customer.getCustomerOrThrow(),{channelId:c}=i.checkout.getCheckoutOrThrow();return g(C(l(Ze.LoadB2BTokenRequested)),v(()=>{return t=this,n=void 0,r=function*(){const{body:t}=yield this._requestSender.getB2BToken(s,d,o,c,a,e);return l(Ze.LoadB2BTokenSucceeded,{token:t.data.token})},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r})).pipe(P(e=>Je(Ze.LoadB2BTokenFailed,e)))}}}const Xe={"X-Checkout-SDK-Version":"1.909.5"};var et,tt;class nt{constructor(e){this._requestSender=e}getB2BToken(e,t,n,i,r,o){return a=this,s=void 0,c=function*(){const{body:a}=yield this._requestSender.get("/customer/current.jwt",{timeout:null==o?void 0:o.timeout,params:{app_client_id:e},headers:Xe});return this._requestSender.post(`${r}/api/v2/login`,{timeout:null==o?void 0:o.timeout,credentials:!1,headers:{"Content-Type":"application/json"},body:{bcToken:a.token,customerId:t,storeHash:n,channelId:i}})},new((d=void 0)||(d=Promise))(function(e,t){function n(e){try{r(c.next(e))}catch(e){t(e)}}function i(e){try{r(c.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof d?r:new d(function(e){e(r)})).then(n,i)}r((c=c.apply(a,s||[])).next())});var a,s,d,c}}class it extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}!function(e){e[e.MissingBillingAddress=0]="MissingBillingAddress",e[e.MissingCart=1]="MissingCart",e[e.MissingCheckout=2]="MissingCheckout",e[e.MissingConsignments=3]="MissingConsignments",e[e.MissingCustomer=4]="MissingCustomer",e[e.MissingCheckoutConfig=5]="MissingCheckoutConfig",e[e.MissingOrder=6]="MissingOrder",e[e.MissingOrderConfig=7]="MissingOrderConfig",e[e.MissingOrderId=8]="MissingOrderId",e[e.MissingPayment=9]="MissingPayment",e[e.MissingPaymentId=10]="MissingPaymentId",e[e.MissingPaymentInstrument=11]="MissingPaymentInstrument",e[e.MissingPaymentMethod=12]="MissingPaymentMethod",e[e.MissingPaymentProviderCustomer=13]="MissingPaymentProviderCustomer",e[e.MissingPaymentRedirectUrl=14]="MissingPaymentRedirectUrl",e[e.MissingPaymentStatus=15]="MissingPaymentStatus",e[e.MissingPaymentToken=16]="MissingPaymentToken",e[e.MissingShippingAddress=17]="MissingShippingAddress"}(et||(et={}));class rt extends it{constructor(e){super(function(e){switch(e){case et.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case et.MissingCart:return"Unable to proceed because cart data is unavailable.";case et.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case et.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case et.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case et.MissingCheckoutConfig:case et.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case et.MissingOrder:return"Unable to proceed because order data is unavailable.";case et.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case et.MissingPayment:return"Unable to proceed because payment data is unavailable.";case et.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case et.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case et.MissingPaymentProviderCustomer:return"Unable to proceed because payment provider customer is unavailable.";case et.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e)),this.subtype=e,this.name="MissingDataError",this.type="missing_data"}}!function(e){e.UpdateBillingAddressRequested="UPDATE_BILLING_ADDRESS_REQUESTED",e.UpdateBillingAddressSucceeded="UPDATE_BILLING_ADDRESS_SUCCEEDED",e.UpdateBillingAddressFailed="UPDATE_BILLING_ADDRESS_FAILED",e.ContinueAsGuestRequested="CONTINUE_AS_GUEST_REQUESTED",e.ContinueAsGuestSucceeded="CONTINUE_AS_GUEST_SUCCEEDED",e.ContinueAsGuestFailed="CONTINUE_AS_GUEST_FAILED"}(tt||(tt={}));class ot extends it{constructor(e){super(e||"Unable to continue as a guest because the customer is already signed in."),this.name="UnableToContinueAsGuestError",this.type="unable_to_continue_as_guest"}}var at;class st{constructor(e,t){this._requestSender=e,this._subscriptionActionCreator=t}continueAsGuest(e,t){return n=>{const i=n.getState(),r=i.checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);const o=i.customer.getCustomer();if(o&&!o.isGuest)throw new ot;const a=i.billingAddress.getBillingAddress();let s;if(a){const{country:t}=a,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{return e=this,n=void 0,o=function*(){const{body:e}=yield this._createOrUpdateBillingAddress(r.id,s,d,t);return l(tt.ContinueAsGuestSucceeded,e)},new((i=void 0)||(i=Promise))(function(t,r){function a(e){try{d(o.next(e))}catch(e){r(e)}}function s(e){try{d(o.throw(e))}catch(e){r(e)}}function d(e){var n;e.done?t(e.value):(n=e.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((o=o.apply(e,n||[])).next())});var e,n,i,o})).pipe(P(e=>Je(tt.ContinueAsGuestFailed,e))),this._updateCustomerConsent(e,t))}}updateAddress(e,t){return n=>m.create(i=>{const r=n.getState(),o=r.checkout.getCheckout();if(!o)throw new rt(et.MissingCheckout);i.next(l(tt.UpdateBillingAddressRequested));const a=r.billingAddress.getBillingAddress(),s=!$(a),d=Object.assign(Object.assign({},e),{email:void 0===e.email&&a?a.email:e.email});a&&a.id&&(d.id=a.id),this._createOrUpdateBillingAddress(o.id,d,s,t).then(({body:e})=>{i.next(l(tt.UpdateBillingAddressSucceeded,e)),i.complete()}).catch(e=>{i.error(h(tt.UpdateBillingAddressFailed,e))})})}_updateCustomerConsent({email:e,acceptsAbandonedCartEmails:t,acceptsMarketingNewsletter:n},i){return null==t&&null==n?f():this._subscriptionActionCreator.updateSubscriptions({email:e,acceptsMarketingNewsletter:n||!1,acceptsAbandonedCartEmails:t||!1},i)}_createOrUpdateBillingAddress(e,t,n,i){return n?this._requestSender.updateAddress(e,t,i):this._requestSender.createAddress(e,t,i)}}class dt extends it{constructor(e){super(e||"Your checkout could not be processed because your cart is empty. Please add items to your cart and try again."),this.name="EmptyCartError",this.type="empty_cart"}}!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(at||(at={}));const ct=at;const lt={include:["cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","promotions.banners"].join(",")};class ut{constructor(e){this._requestSender=e}createAddress(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/billing-address`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{body:t,params:lt,headers:r,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}updateAddress(e,t,{timeout:n}={}){const{id:i}=t,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if("empty_cart"===e.body.type)throw new dt;throw e})}}var ht,pt;function mt(e,t){const n=u((e,t)=>t.type===ht.Synchronize?t.payload:e,e.getState(),{stateTransformer:t});return e.subscribe(e=>{n.dispatch(l(ht.Synchronize,e))},{initial:!1}),n}!function(e){e.Synchronize="SYNCHRONIZE"}(ht||(ht={})),function(e){e.ClearError="CLEAR_ERROR"}(pt||(pt={}));class yt{clearError(e){return{type:pt.ClearError,payload:e}}}class gt{constructor(e,t){this._requestSender=e,this._config=t}sendRequest(e,t){return this._requestSender.sendRequest(e,t)}get(e,t){return this._requestSender.get(e,t)}post(e,t){return this._requestSender.post(this._prefixed(e),t)}put(e,t){return this._requestSender.put(this._prefixed(e),t)}patch(e,t){return this._requestSender.patch(this._prefixed(e),t)}delete(e,t){return this._requestSender.delete(this._prefixed(e),t)}_prefixed(e){const t=this._config.getBasePath();return!this._config.getFeatures()["CHECKOUT-9950.update_sf_checkout_url_for_subfolder"]||!t||t.endsWith("/checkout")||/^https?:\/\//.test(e)?e:`${t}${e}`}}function vt(){try{return"production"}catch(e){return"development"}}class ft{constructor(e){this._console=e}log(...e){this._logToConsole("log",...e)}info(...e){this._logToConsole("info",...e)}warn(...e){this._logToConsole("warn",...e)}error(...e){this._logToConsole("error",...e)}debug(...e){this._logToConsole("debug",...e)}_logToConsole(e,...t){this._console&&this._console[e]&&this._console[e].call(this._console,...t)}}class St{log(){}info(){}warn(){}error(){}debug(){}}const _t=function(e=!0){return e?new ft(console):new St}("test"!==vt());function wt(){return _t}function It(e,t,n){const i=new WeakMap;function r(e){return(...n)=>{const r=n[n.length-1],{useCache:o}=(a=r)&&"boolean"==typeof a.useCache?r:{useCache:!1};var a;if(!o)return e.call(this,...n);const s=i.get(this)||{};var d;return i.get(this)||i.set(this,s),s[t]||(s[t]=(d=e,Pe(function(...e){const t=d.call(this,...e);return t instanceof m?S(t).pipe(D()):"function"==typeof t?Pe(e=>S(t(e)).pipe(D()),{isEqual:Y}):t},{isEqual:Y}))),s[t].call(this,...n)}}return{get(){if("function"!=typeof n.value)throw new Error("Decorator should be used in functions");const e=r.call(this,n.value);return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e}}}var Ct;!function(e){e.LoadConfigRequested="LOAD_CONFIG_REQUESTED",e.LoadConfigSucceeded="LOAD_CONFIG_SUCCEEDED",e.LoadConfigFailed="LOAD_CONFIG_FAILED"}(Ct||(Ct={}));class bt{constructor(e){this._configRequestSender=e}loadConfig(e){return m.create(t=>{t.next(l(Ct.LoadConfigRequested)),this._configRequestSender.loadConfig(e).then(e=>{t.next(l(Ct.LoadConfigSucceeded,e.body)),t.complete()}).catch(e=>{t.error(h(Ct.LoadConfigFailed,e))})})}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([It],bt.prototype,"loadConfig",null);const Pt={body:{},headers:{},status:0};class Ot extends it{constructor(e,{message:t,errors:n}={}){const{body:i,headers:r,status:o}=e||Pt;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=i,this.headers=r,this.status=o,this.errors=n||[]}}class Et extends Ot{constructor(e){super(e,{message:e.body.title}),this.name="CheckoutNotAvailableError",this.type="checkout_not_available"}}const At="This API endpoint is for internal use only and may change in the future";class Tt{constructor(e){this._requestSender=e}loadConfig({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/checkout-settings",{timeout:e,headers:Object.assign({Accept:ct.JsonV1,"X-API-INTERNAL":At},Xe),params:t}).catch(e=>{if(e.status>=400&&e.status<500)throw new Et(e);throw e})}}var kt;!function(e){e.ApplyCouponRequested="APPLY_COUPON_REQUESTED",e.ApplyCouponSucceeded="APPLY_COUPON_SUCCEEDED",e.ApplyCouponFailed="APPLY_COUPON_FAILED",e.RemoveCouponRequested="REMOVE_COUPON_REQUESTED",e.RemoveCouponSucceeded="REMOVE_COUPON_SUCCEEDED",e.RemoveCouponFailed="REMOVE_COUPON_FAILED"}(kt||(kt={}));class Dt{constructor(e){this._couponRequestSender=e}applyCoupon(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l(kt.ApplyCouponRequested)),this._couponRequestSender.applyCoupon(r.id,e,t).then(({body:e})=>{i.next(l(kt.ApplyCouponSucceeded,e)),i.complete()}).catch(e=>{i.error(h(kt.ApplyCouponFailed,e))})})}removeCoupon(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l(kt.RemoveCouponRequested)),this._couponRequestSender.removeCoupon(r.id,e,t).then(({body:e})=>{i.next(l(kt.RemoveCouponSucceeded,e)),i.complete()}).catch(e=>{i.error(h(kt.RemoveCouponFailed,e))})})}}const Mt=["cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","customer.customerGroup","payments","promotions.banners"];var zt,Nt,xt,Rt;function Ft(e){return we(e).join(",")}!function(e){e.AvailableShippingOptions="consignments.availableShippingOptions",e.PhysicalItemsCategoryNames="cart.lineItems.physicalItems.categoryNames",e.DigitalItemsCategoryNames="cart.lineItems.digitalItems.categoryNames"}(zt||(zt={}));class Lt{constructor(e){this._requestSender=e}applyCoupon(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/coupons`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{headers:r,timeout:n,params:{include:Ft([...Mt,zt.AvailableShippingOptions])},body:{couponCode:t}}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}removeCoupon(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/coupons/${t}`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.delete(i,{headers:r,timeout:n,params:{include:Ft([...Mt,zt.AvailableShippingOptions])}}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}!function(e){e.ApplyGiftCertificateRequested="APPLY_GIFT_CERTIFICATE_REQUESTED",e.ApplyGiftCertificateSucceeded="APPLY_GIFT_CERTIFICATE_SUCCEEDED",e.ApplyGiftCertificateFailed="APPLY_GIFT_CERTIFICATE_FAILED",e.RemoveGiftCertificateRequested="REMOVE_GIFT_CERTIFICATE_REQUESTED",e.RemoveGiftCertificateSucceeded="REMOVE_GIFT_CERTIFICATE_SUCCEEDED",e.RemoveGiftCertificateFailed="REMOVE_GIFT_CERTIFICATE_FAILED"}(Nt||(Nt={}));class Bt{constructor(e){this._giftCertificateRequestSender=e}applyGiftCertificate(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l(Nt.ApplyGiftCertificateRequested)),this._giftCertificateRequestSender.applyGiftCertificate(r.id,e,t).then(({body:e})=>{i.next(l(Nt.ApplyGiftCertificateSucceeded,e)),i.complete()}).catch(e=>{i.error(h(Nt.ApplyGiftCertificateFailed,e))})})}removeGiftCertificate(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l(Nt.RemoveGiftCertificateRequested)),this._giftCertificateRequestSender.removeGiftCertificate(r.id,e,t).then(({body:e})=>{i.next(l(Nt.RemoveGiftCertificateSucceeded,e)),i.complete()}).catch(e=>{i.error(h(Nt.RemoveGiftCertificateFailed,e))})})}}class jt{constructor(e){this._requestSender=e}applyGiftCertificate(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/gift-certificates`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{headers:r,timeout:n,params:{include:Ft(Mt)},body:{giftCertificateCode:t}}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}removeGiftCertificate(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/gift-certificates/${t}`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.delete(i,{headers:r,timeout:n,params:{include:Ft(Mt)}}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}function Ut(e){return e&&"resolveIds"in e}class qt extends it{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class Vt{constructor(e){var t,n,i;this._factories={},this._instances={},this._defaultToken=null!==(t=null==e?void 0:e.defaultToken)&&void 0!==t?t:"default",this._useFallback=null===(n=null==e?void 0:e.useFallback)||void 0===n||n,this._tokenResolver=null!==(i=null==e?void 0:e.tokenResolver)&&void 0!==i?i:e=>e}get(e,t){try{return this._getInstance(e||this._defaultToken,t||e||this._defaultToken)}catch(e){if(!this._useFallback)throw e;return this._getInstance(this._defaultToken,t||this._defaultToken)}}getFactory(e,t){const n=this._tokenResolver(e,Object.keys(this._factories),t);return n?this._factories[n]:void 0}register(e,t){if(this._hasFactory(e))throw new qt(`'${e}' is already registered.`);this._factories[e]=t}_hasFactory(e){return!!this._factories[e]}_hasInstance(e){return!!this._instances[e]}_getInstance(e,t){if(!this._hasInstance(t)){const n=this.getFactory(e);if(!n)throw new qt(`'${e}' is not registered.`);this._instances[t]=n()}return this._instances[t]}}class Gt{constructor(e=!1){this._useFallback=e,this._registry=new Vt({tokenResolver:this._resolveToken.bind(this),defaultToken:this._encodeToken({default:!0}),useFallback:this._useFallback})}get(e){return this._registry.get(this._encodeToken(e))}getFactory(e,t){try{return this._registry.getFactory(this._encodeToken(e),t)}catch(e){return}}getUseFallback(){return this._useFallback}register(e,t){this._registry.register(this._encodeToken(e),t)}_encodeToken(e){return btoa(JSON.stringify(e))}_decodeToken(e){return JSON.parse(atob(e))}_resolveToken(e,t,n){var i;const r=this._decodeToken(e),o=[];t.forEach(e=>{const t=this._decodeToken(e),n={token:e,matches:0,default:!1,totalKeys:Object.keys(t).length};for(const[e,i]of Object.entries(t)){if(e in r&&r[e]!==i){n.matches=0;break}e in r&&r[e]===i&&n.matches++,"default"===e&&!0===i&&(n.default=!0)}o.push(n)});const a=o.sort((e,t)=>t.matches-e.matches).filter(e=>e.matches>0);a.length>1&&a[0].matches===a[1].matches&&"development"===vt()&&wt().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.");const s=Object.keys(r).length;if(n){const e=a.find(e=>e.matches===s&&e.matches===e.totalKeys);if(!e)throw new Error(`Unable to resolve to a registered token with the provided token for ${JSON.stringify(r)} with exact match.`);return e.token}const d=a[0];if(d&&d.token)return d.token;if(this._useFallback){const e=null===(i=o.find(e=>e.default))||void 0===i?void 0:i.token;if(e)return e}throw new Error(`Unable to resolve to a registered token with the provided token for ${JSON.stringify(r)}.`)}}function Ht(e){const t=e;return"object"==typeof t&&"object"==typeof t.payload&&"string"==typeof t.payload.token}!function(e){e.BuyNow="BUY_NOW"}(xt||(xt={})),function(e){e.SignInCustomerRequested="SIGN_IN_CUSTOMER_REQUESTED",e.SignInCustomerSucceeded="SIGN_IN_CUSTOMER_SUCCEEDED",e.SignInCustomerFailed="SIGN_IN_CUSTOMER_FAILED",e.SignOutCustomerRequested="SIGN_OUT_CUSTOMER_REQUESTED",e.SignOutCustomerSucceeded="SIGN_OUT_CUSTOMER_SUCCEEDED",e.SignOutCustomerFailed="SIGN_OUT_CUSTOMER_FAILED",e.CreateCustomerRequested="CREATE_CUSTOMER_REQUESTED",e.CreateCustomerSucceeded="CREATE_CUSTOMER_SUCCEEDED",e.CreateCustomerFailed="CREATE_CUSTOMER_FAILED",e.CreateCustomerAddressRequested="CREATE_CUSTOMER_ADDRESS_REQUESTED",e.CreateCustomerAddressSucceeded="CREATE_CUSTOMER_ADDRESS_SUCCEEDED",e.CreateCustomerAddressFailed="CREATE_CUSTOMER_ADDRESS_FAILED",e.StripeLinkAuthenticated="STRIPE_LINK_AUTHENTICATED"}(Rt||(Rt={}));var Wt,$t,Yt;class Kt{constructor(e,t,n){this._customerRequestSender=e,this._checkoutActionCreator=t,this._spamProtectionActionCreator=n}createCustomer(e,t){return n=>{const i=n.getState().config.getStoreConfigOrThrow(),{isStorefrontSpamProtectionEnabled:r}=i.checkoutSettings,o=i=>S(this._customerRequestSender.createAccount(Object.assign(Object.assign({},e),{token:i}),t)).pipe(M(()=>g(this._checkoutActionCreator.loadCurrentCheckout(t)(n),C(l(Rt.CreateCustomerSucceeded)))));return g(C(l(Rt.CreateCustomerRequested)),r?S(this._spamProtectionActionCreator.execute()(n)).pipe(M(e=>{var t;return Ht(e)?g(C(e),o(null===(t=e.payload)||void 0===t?void 0:t.token)):C(e)})):o()).pipe(P(e=>Je(Rt.CreateCustomerFailed,e)))}}createAddress(e,t){return g(C(l(Rt.CreateCustomerAddressRequested)),v(()=>{return n=this,i=void 0,o=function*(){const{body:n}=yield this._customerRequestSender.createAddress(e,t);return l(Rt.CreateCustomerAddressSucceeded,n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Je(Rt.CreateCustomerAddressFailed,e)))}signInCustomer(e,t){return n=>{const i=n.getState().checkout.getCheckoutOrThrow(),r=i.cart.source===xt.BuyNow?i.id:void 0;return g(C(l(Rt.SignInCustomerRequested)),S(this._customerRequestSender.signInCustomer(Object.assign(Object.assign({},e),{cartId:r}),t)).pipe(M(({body:e})=>e.data.persistentCartRetrievalInformation?g(this._checkoutActionCreator.loadCheckout(e.data.persistentCartRetrievalInformation.id,t)(n),C(l(Rt.SignInCustomerSucceeded,e.data))):g(this._checkoutActionCreator.loadCurrentCheckout(t)(n),C(l(Rt.SignInCustomerSucceeded,e.data)))))).pipe(P(e=>Je(Rt.SignInCustomerFailed,e)))}}signOutCustomer(e){return t=>{const n=t.getState().checkout.getCheckoutOrThrow(),i=n.cart.source===xt.BuyNow?n.id:void 0;return g(C(l(Rt.SignOutCustomerRequested)),S(this._customerRequestSender.signOutCustomer(e,i)).pipe(M(({body:n})=>g(this._checkoutActionCreator.loadCurrentCheckout(e)(t),C(l(Rt.SignOutCustomerSucceeded,n.data)))))).pipe(P(e=>Je(Rt.SignOutCustomerFailed,e)))}}}class Jt{constructor(e){this._requestSender=e}createAccount(e,{timeout:t}={}){return this._requestSender.post("/api/storefront/customer",{timeout:t,headers:Xe,body:e})}createAddress(e,{timeout:t}={}){return this._requestSender.post("/api/storefront/customer-address",{timeout:t,headers:Xe,body:e})}signInCustomer(e,{timeout:t}={}){return this._requestSender.post("/internalapi/v1/checkout/customer",{timeout:t,headers:Xe,body:e})}signOutCustomer({timeout:e}={},t){return this._requestSender.delete("/internalapi/v1/checkout/customer",Object.assign({timeout:e,headers:Xe},t&&{body:{cartId:t}}))}}function Zt(e,t,n){t.forEach(t=>{Ut(t)&&t.resolveIds.forEach(i=>{e.getFactory(i,!0)||e.register(i,()=>t(n))})})}!function(e){e.SignInFailed="CUSTOMER_STRATEGY_SIGN_IN_FAILED",e.SignInRequested="CUSTOMER_STRATEGY_SIGN_IN_REQUESTED",e.SignInSucceeded="CUSTOMER_STRATEGY_SIGN_IN_SUCCEEDED",e.SignOutFailed="CUSTOMER_STRATEGY_SIGN_OUT_FAILED",e.SignOutRequested="CUSTOMER_STRATEGY_SIGN_OUT_REQUESTED",e.SignOutSucceeded="CUSTOMER_STRATEGY_SIGN_OUT_SUCCEEDED",e.ExecutePaymentMethodCheckoutFailed="CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_FAILED",e.ExecutePaymentMethodCheckoutRequested="CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_REQUESTED",e.ExecutePaymentMethodCheckoutSucceeded="CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_SUCCEEDED",e.InitializeFailed="CUSTOMER_STRATEGY_INITIALIZE_FAILED",e.InitializeRequested="CUSTOMER_STRATEGY_INITIALIZE_REQUESTED",e.InitializeSucceeded="CUSTOMER_STRATEGY_INITIALIZE_SUCCEEDED",e.DeinitializeFailed="CUSTOMER_STRATEGY_DEINITIALIZE_FAILED",e.DeinitializeRequested="CUSTOMER_STRATEGY_DEINITIALIZE_REQUESTED",e.DeinitializeSucceeded="CUSTOMER_STRATEGY_DEINITIALIZE_SUCCEEDED",e.WidgetInteractionStarted="CUSTOMER_STRATEGY_WIDGET_INTERACTION_STARTED",e.WidgetInteractionFinished="CUSTOMER_STRATEGY_WIDGET_INTERACTION_FINISHED",e.WidgetInteractionFailed="CUSTOMER_STRATEGY_WIDGET_INTERACTION_FAILED"}(Wt||(Wt={}));class Qt{constructor(e,t,n){this._strategyRegistry=e,this._strategyRegistryV2=t,this._paymentIntegrationService=n}signIn(e,t){return m.create(n=>{const i=t&&t.methodId,r={methodId:i};n.next(l(Wt.SignInRequested,void 0,r)),this._getStrategy(i).signIn(e,t).then(()=>{n.next(l(Wt.SignInSucceeded,void 0,r)),n.complete()}).catch(e=>{n.error(h(Wt.SignInFailed,e,r))})})}signOut(e){return m.create(t=>{const n=e&&e.methodId,i={methodId:n};t.next(l(Wt.SignOutRequested,void 0,i)),this._getStrategy(n).signOut(e).then(()=>{t.next(l(Wt.SignOutSucceeded,void 0,i)),t.complete()}).catch(e=>{t.error(h(Wt.SignOutFailed,e,i))})})}executePaymentMethodCheckout(e){return m.create(t=>{const n=e&&e.methodId,i={methodId:n};t.next(l(Wt.ExecutePaymentMethodCheckoutRequested,void 0,i)),this._getStrategy(n).executePaymentMethodCheckout(e).then(()=>{t.next(l(Wt.ExecutePaymentMethodCheckoutSucceeded,void 0,i)),t.complete()}).catch(e=>{t.error(h(Wt.ExecutePaymentMethodCheckoutFailed,e,i))})})}initialize(e){return t=>m.create(n=>{var i;const r=t.getState(),o=e&&e.methodId,a={methodId:o};if(Zt(this._strategyRegistryV2,null!==(i=null==e?void 0:e.integrations)&&void 0!==i?i:[],this._paymentIntegrationService),o&&r.customerStrategies.isInitialized(o))return n.complete();n.next(l(Wt.InitializeRequested,void 0,a)),this._getStrategy(o).initialize(e).then(()=>{n.next(l(Wt.InitializeSucceeded,void 0,a)),n.complete()}).catch(e=>{n.error(h(Wt.InitializeFailed,e,a))})})}deinitialize(e){return t=>m.create(n=>{const i=t.getState(),r=e&&e.methodId,o={methodId:r};if(r&&!i.customerStrategies.isInitialized(r))return n.complete();n.next(l(Wt.DeinitializeRequested,void 0,o)),this._getStrategy(r).deinitialize(e).then(()=>{n.next(l(Wt.DeinitializeSucceeded,void 0,o)),n.complete()}).catch(e=>{n.error(h(Wt.DeinitializeFailed,e,o))})})}widgetInteraction(e,t){return m.create(n=>{const i={methodId:t&&t.methodId};n.next(l(Wt.WidgetInteractionStarted,void 0,i)),e().then(()=>{n.next(l(Wt.WidgetInteractionFinished,void 0,i)),n.complete()}).catch(e=>{n.error(h(Wt.WidgetInteractionFailed,e,i))})})}_getStrategy(e){let t;try{t=this._strategyRegistryV2.get({id:e||""})}catch(n){t=this._strategyRegistry.get(e)}return t}}function Xt(e,t=[]){return Array.isArray(t)?Ft([...e,...t]):function(e,t){const n=ie(me(t,e=>!e)),i=ie(L(t));return Ft([...R(e,n),...i])}(e,t)}class en{constructor(e){this._requestSender=e}loadCheckout(e,{params:{include:t}={},timeout:n}={}){const i=`/api/storefront/checkout/${e}`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.get(i,{params:{include:Xt(Mt,t)},headers:r,timeout:n}).catch(e=>{if(e.status>=400&&e.status<500)throw new Et(e);throw e})}updateCheckout(e,t,{params:{include:n}={},timeout:i}={}){const r=`/api/storefront/checkout/${e}`,o=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.put(r,{params:{include:Xt(Mt,n)},body:t,headers:o,timeout:i}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}!function(e){e.LoadCheckoutRequested="LOAD_CHECKOUT_REQUESTED",e.LoadCheckoutSucceeded="LOAD_CHECKOUT_SUCCEEDED",e.LoadCheckoutFailed="LOAD_CHECKOUT_FAILED",e.UpdateCheckoutRequested="UPDATE_CHECKOUT_REQUESTED",e.UpdateCheckoutSucceeded="UPDATE_CHECKOUT_SUCCEEDED",e.UpdateCheckoutFailed="UPDATE_CHECKOUT_FAILED"}($t||($t={})),function(e){e.HydrateInitialState="HYDRATE_INITIAL_STATE"}(Yt||(Yt={}));var tn;class nn{constructor(e,t,n){this._checkoutRequestSender=e,this._configActionCreator=t,this._formFieldsActionCreator=n}loadCheckout(e,t){return()=>g(C(l($t.LoadCheckoutRequested)),w(this._configActionCreator.loadConfig({useCache:!0,timeout:null==t?void 0:t.timeout,params:{checkoutId:e}}),this._formFieldsActionCreator.loadFormFields({useCache:!0,timeout:null==t?void 0:t.timeout})),v(()=>this._checkoutRequestSender.loadCheckout(e,t).then(({body:e})=>l($t.LoadCheckoutSucceeded,this._transformCustomerAddresses(e))))).pipe(P(e=>Je($t.LoadCheckoutFailed,e)))}loadDefaultCheckout(e){return t=>g(C(l($t.LoadCheckoutRequested)),w(this._configActionCreator.loadConfig({useCache:!0,timeout:null==e?void 0:e.timeout}),this._formFieldsActionCreator.loadFormFields({useCache:!0,timeout:null==e?void 0:e.timeout})),v(()=>{return n=this,i=void 0,o=function*(){const n=t.getState().config.getContextConfig();if(!n||!n.checkoutId)throw new rt(et.MissingCheckoutConfig);const{body:i}=yield this._checkoutRequestSender.loadCheckout(n.checkoutId,e);return l($t.LoadCheckoutSucceeded,this._transformCustomerAddresses(i))},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Je($t.LoadCheckoutFailed,e)))}updateCheckout(e,t){return n=>new m(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l($t.UpdateCheckoutRequested)),this._checkoutRequestSender.updateCheckout(r.id,e,t).then(({body:e})=>{i.next(l($t.UpdateCheckoutSucceeded,e)),i.complete()}).catch(e=>{i.error(h($t.UpdateCheckoutFailed,e))})})}loadCurrentCheckout(e){return t=>{const n=t.getState().checkout.getCheckout();if(!n)throw new rt(et.MissingCheckout);return this.loadCheckout(n.id,e)(t)}}hydrateInitialState(e){return{type:Yt.HydrateInitialState,payload:e}}_transformCustomerAddresses(e){return Object.assign(Object.assign({},e),{customer:Object.assign(Object.assign({},e.customer),{addresses:e.customer.addresses.map(e=>Object.assign(Object.assign({},e),{shouldSaveAddress:!1}))})})}}!function(e){e.LoadFormFieldsRequested="LOAD_FORM_FIELDS_REQUESTED",e.LoadFormFieldsSucceeded="LOAD_FORM_FIELDS_SUCCEEDED",e.LoadFormFieldsFailed="LOAD_FORM_FIELDS_FAILED"}(tn||(tn={}));var rn;class on{constructor(e){this._formFieldsRequestSender=e}loadFormFields(e){return g(C(l(tn.LoadFormFieldsRequested)),v(()=>{return t=this,n=void 0,r=function*(){const{body:t}=yield this._formFieldsRequestSender.loadFields(e);return l(tn.LoadFormFieldsSucceeded,t)},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r})).pipe(P(e=>Je(tn.LoadFormFieldsFailed,e)))}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([It],on.prototype,"loadFormFields",null);class an{constructor(e){this._requestSender=e}loadFields({timeout:e}={}){return this._requestSender.get("/api/storefront/form-fields",{timeout:e,headers:Object.assign({Accept:ct.JsonV1,"X-API-INTERNAL":At},Xe)})}}class sn extends it{constructor(){super("You haven't complete our spam protection challenge. Please try again."),this.name="SpamProtectionChallengeNotCompletedError",this.type="spam_protection_challenge_not_completed"}}class dn extends it{constructor(){super("We were not able to complete your spam protection verification. Please try again."),this.name="SpamProtectionFailedError",this.type="spam_protection_failed"}}!function(e){e.InitializeFailed="SPAM_PROTECTION_INITIALIZE_FAILED",e.InitializeSucceeded="SPAM_PROTECTION_INITIALIZE_SUCCEEDED",e.InitializeRequested="SPAM_PROTECTION_INITIALIZE_REQUESTED",e.VerifyCheckoutRequested="SPAM_PROTECTION_CHECKOUT_VERIFY_REQUESTED",e.VerifyCheckoutSucceeded="SPAM_PROTECTION_CHECKOUT_VERIFY_SUCCEEDED",e.VerifyCheckoutFailed="SPAM_PROTECTION_CHECKOUT_VERIFY_FAILED",e.ExecuteRequested="SPAM_PROTECTION_EXECUTE_REQUESTED",e.ExecuteSucceeded="SPAM_PROTECTION_EXECUTE_SUCCEEDED",e.ExecuteFailed="SPAM_PROTECTION_EXECUTE_FAILED"}(rn||(rn={}));var cn,ln,un,hn=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pn{constructor(e,t){this._googleRecaptcha=e,this._requestSender=t}initialize(e){return t=>g(C(l(rn.InitializeRequested,void 0)),v(()=>hn(this,void 0,void 0,function*(){const n=e?e.containerId:"spamProtectionContainer";if(document.getElementById(n)&&this._googleRecaptcha.reset(n),!e&&!document.getElementById(n)){const e=document.createElement("div");e.setAttribute("id",n),document.body.appendChild(e)}const i=t.getState().config.getStoreConfigOrThrow().checkoutSettings.googleRecaptchaSitekey;return yield this._googleRecaptcha.load(n,i),l(rn.InitializeSucceeded)}))).pipe(P(e=>Je(rn.InitializeFailed,e)))}verifyCheckoutSpamProtection(){return e=>v(()=>{const t=e.getState().checkout.getCheckout();if(!t)throw new rt(et.MissingCheckout);return g(C(l(rn.VerifyCheckoutRequested)),S(this.execute()(e)).pipe(M(e=>Ht(e)&&e.payload?S(this._requestSender.validate(t.id,e.payload.token)).pipe(M(({body:t})=>g(C(e),C(l(rn.VerifyCheckoutSucceeded,t))))):C(e)))).pipe(P(e=>Je(rn.VerifyCheckoutFailed,e)))})}execute(){return e=>g(C(l(rn.ExecuteRequested)),this.initialize()(e),this._googleRecaptcha.execute().pipe(z(1)).pipe(M(({error:e,token:t})=>hn(this,void 0,void 0,function*(){if(e instanceof sn)throw e;if(e||!t)throw new dn;return l(rn.ExecuteSucceeded,{token:t})})))).pipe(P(e=>Je(rn.ExecuteFailed,e)))}}class mn{constructor(e=window){this._window=e}create(e){return new this._window.MutationObserver(e)}}!function(e){e[e.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",e[e.CustomerNotInitialized=1]="CustomerNotInitialized",e[e.PaymentNotInitialized=2]="PaymentNotInitialized",e[e.ShippingNotInitialized=3]="ShippingNotInitialized",e[e.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(cn||(cn={}));class yn extends it{constructor(e){super(function(e){switch(e){case cn.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case cn.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case cn.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case cn.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.subtype=e,this.name="NotInitializedError",this.type="not_initialized"}}class gn extends it{constructor(){super("Spam protection is not loaded. Please try again."),this.name="SpamProtectionNotLoadedError",this.type="spam_protection_failed"}}class vn{constructor(e,t){this.googleRecaptchaScriptLoader=e,this.mutationObserverFactory=t,this._memoized=Pe((e,t,n)=>{const i=new y;if(!n)throw new Error;return this._widgetId=e.render(n.id,{sitekey:t,size:"invisible",callback:()=>{i.next({token:e.getResponse(this._widgetId)}),e.reset(this._widgetId)},"error-callback":()=>{i.next({error:new dn})}}),i},{isEqual:(e,t)=>e===t})}load(e,t){return this.googleRecaptchaScriptLoader.load().then(n=>{n&&(this._event$=this._memoized(n,t,document.getElementById(e)),this._recaptcha=n)}).catch(e=>{throw e})}reset(e){var t;const n=document.getElementById(e);null==n||n.remove(),null===(t=this._recaptcha)||void 0===t||t.reset(this._widgetId)}execute(){return v(()=>{const e=this._event$,t=this._recaptcha;if(!e||!t)throw new yn(cn.SpamProtectionNotInitialized);return v(()=>{const e=document.querySelector('iframe[src*="bframe"]');return e?C(e):b(new gn)}).pipe(k(e=>e.pipe(O(250),M((e,t)=>t<28?C(e):b(e)))),M(n=>(this._watchRecaptchaChallengeWindow(e,n),t.execute(this._widgetId),e)),P(e=>C({error:e})))})}_watchRecaptchaChallengeWindow(e,t){const n=t.parentElement;if(!n)throw new gn;const i=n.parentElement;if(!i)throw new gn;this.mutationObserverFactory.create(()=>{"hidden"===i.style.visibility&&e.next({error:new sn})}).observe(i,{attributes:!0,attributeFilter:["style"]})}}class fn{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(){return this._loadPromise||(this._loadPromise=this._loadScript()),this._loadPromise}_loadScript(){const e="initRecaptcha",t=[`onload=${e}`,"render=explicit"].join("&");return new Promise((n,i)=>{this._window[e]=()=>n(this._window.grecaptcha),this._scriptLoader.loadScript(`//www.google.com/recaptcha/api.js?${t}`).catch(e=>{this._loadPromise=void 0,i(e)})})}}function Sn(e){return new vn(new fn(e),new mn)}class _n{constructor(e){this._requestSender=e}validate(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/spam-protection`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{body:{token:t},headers:r,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}class wn{constructor(e,t){this._store=e,this._customerActionCreator=t}signIn(e,t){return this._store.dispatch(this._customerActionCreator.signInCustomer(e,t))}signOut(e){return this._store.dispatch(this._customerActionCreator.signOutCustomer(e))}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())}initialize(){return Promise.resolve(this._store.getState())}deinitialize(){return Promise.resolve(this._store.getState())}}function In(e){if(!/^(https?:)?\/\//.test(e))throw new qt("The provided URL must be absolute.");const t=document.createElement("a");t.href=e;const n=t.port&&-1!==e.indexOf(`${t.hostname}:${t.port}`)?t.port:"";return{hash:t.hash,hostname:t.hostname,href:t.href,origin:`${t.protocol}//${t.hostname}${n?`:${n}`:""}`,pathname:t.pathname,port:n,protocol:t.protocol,search:t.search}}class Cn extends it{constructor(e){super(e||"Unable to proceed due to no extension configured for this region."),this.name="ExtensionNotFoundError",this.type="extension_not_found"}}function bn(e,t){return e.type===t}!function(e){e.LoadExtensionsRequested="LOAD_EXTENSIONS_REQUESTED",e.LoadExtensionsSucceeded="LOAD_EXTENSIONS_SUCCEEDED",e.LoadExtensionsFailed="LOAD_EXTENSIONS_FAILED",e.RenderExtensionRequested="RENDER_EXTENSION_REQUESTED",e.RenderExtensionSucceeded="RENDER_EXTENSION_SUCCEEDED",e.RenderExtensionFailed="RENDER_EXTENSION_FAILED"}(ln||(ln={}));class Pn{constructor(e,t,n){this._targetWindow=t,this._context=n,this._targetOrigin="*"===e?"*":In(e).origin}post(e,t){const n=this._targetWindow;if(window===n)return;if(!n)throw new Error("Unable to post message because target window is not set.");const i=t&&_(window,"message").pipe(A(e=>e.origin===this._targetOrigin&&bn(e.data,e.data.type)&&-1!==[t.successType,t.errorType].indexOf(e.data.type)),T(e=>{if(t.errorType===e.data.type)throw e.data;return e.data}),z(1)).toPromise();return n.postMessage(Object.assign(Object.assign({},e),{context:this._context}),this._targetOrigin),i}setTarget(e){this._targetWindow=e}setContext(e){this._context=e}}function On(e){var t;const n=null===(t=document.querySelector(`[data-extension-id="${e.id}"]`))||void 0===t?void 0:t.querySelector("iframe");if(!(null==n?void 0:n.contentWindow))throw new Cn(`Unable to post due to no extension rendered for ID: ${e.id}.`);return new Pn(e.url,n.contentWindow)}!function(e){e.ExtensionReady="EXTENSION:READY",e.ExtensionFailed="EXTENSION:FAILED"}(un||(un={}));class En{constructor(e){const t=new Promise((e,t)=>{this.cancel=t});this.promise=Promise.race([e,t])}}class An extends it{constructor(e){super(e||"Unable to proceed because the required element is unexpectedly detached from the page."),this.name="UnexpectedDetachmentError",this.type="unexpected_detachment"}}var Tn;class kn{constructor(e){this._mutationObserver=e}ensurePresence(e,t){return n=this,i=void 0,o=function*(){const n=new En(t),i=this._mutationObserver.create(t=>{t.forEach(t=>{0!==Array.from(t.removedNodes).filter(t=>e.some(e=>t===e||t.contains(e))).length&&n.cancel(new An)})});i.observe(document.body,{childList:!0,subtree:!0});try{const e=yield n.promise;return i.disconnect(),e}catch(e){throw i.disconnect(),e}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}function Dn(e,t){const{iframeResizer:n}=Ve(785);return n(e,t)}class Mn extends it{constructor(e){super(e||"Unable to load an extension"),this.name="ExtensionNotLoadedError",this.type="extension_not_loaded"}}!function(e){e.Subscribe="EXTENSION_INTERNAL:SUBSCRIBE",e.Unsubscribe="EXTENSION_INTERNAL:UNSUBSCRIBE",e.ResizeIframe="EXTENSION_INTERNAL:RESIZE_IFRAME"}(Tn||(Tn={}));class zn{constructor(e){this._options=e}createFrame(e,t,n,i){const r=document.getElementById(t),{timeout:o=6e4}=this._options||{};if(!r)throw new Mn("Unable to embed the iframe because the container element could not be found.");const a=document.createElement("iframe");return a.src=e,a.style.border="none",a.style.display="none",a.style.width="100%",r.appendChild(a),this._toResizableFrame(a,o,n,i).catch(e=>{throw r.removeChild(a),e})}_toResizableFrame(e,t,n,i){return r=this,o=void 0,s=function*(){const r=new kn(new mn),o=new Promise((r,o)=>{const a=window.setTimeout(()=>{try{i()}catch(e){e instanceof Error&&console.error(`Extension rendering timed out after ${t}ms, and the callback function could not be executed. Error: ${e.message}`)}o(new Mn("Unable to load the extension because the content could not be loaded."))},t),s=t=>{if(t.origin===In(e.src).origin&&bn(t.data,Tn.ResizeIframe)){e.style.display="";const t=Dn({autoResize:!1,scrolling:!1,sizeWidth:!1,heightCalculationMethod:"bodyOffset",initCallback:n},e);d(),r(t[t.length-1])}},d=()=>{window.removeEventListener("message",s),window.clearTimeout(a)};window.addEventListener("message",s)});return r.ensurePresence([e],o)},new((a=void 0)||(a=Promise))(function(e,t){function n(e){try{d(s.next(e))}catch(e){t(e)}}function i(e){try{d(s.throw(e))}catch(e){t(e)}}function d(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a(function(e){e(r)})).then(n,i)}d((s=s.apply(r,o||[])).next())});var r,o,a,s}}class Nn{constructor(e,t,n){this._containerId=e,this._extension=t,this._config=n;const{cartId:i,parentOrigin:r}=this._config;this._url=new URL(this._extension.url),this._url.searchParams.set("extensionId",this._extension.id),this._url.searchParams.set("cartId",i),this._url.searchParams.set("parentOrigin",r)}attach(){var e,t,n,i,r;return t=this,n=void 0,r=function*(){if(null===(e=document.querySelector(`[data-extension-id="${this._extension.id}"]`))||void 0===e?void 0:e.querySelector("iframe"))return;const t=new zn,n=e=>{On(this._extension).post({type:e})};this._iframe=yield t.createFrame(this._url.toString(),this._containerId,()=>{n(un.ExtensionReady)},()=>{n(un.ExtensionFailed)});const i=document.getElementById(this._containerId);null==i||i.setAttribute("data-extension-id",this._extension.id)},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())})}detach(){this._iframe&&this._iframe.parentElement&&this._iframe.parentElement.removeChild(this._iframe)}}class xn{constructor(e){this._requestSender=e}loadExtensions(e){return()=>m.create(t=>{t.next(l(ln.LoadExtensionsRequested)),this._requestSender.loadExtensions(e).then(e=>{const n=e.body;t.next(l(ln.LoadExtensionsSucceeded,n)),t.complete()}).catch(e=>{t.error(h(ln.LoadExtensionsFailed,e))})})}renderExtension(e,t,n){return i=>m.create(r=>{return o=this,a=void 0,d=function*(){const o=i.getState(),{id:a}=o.cart.getCartOrThrow(),{links:{checkoutLink:s}}=o.config.getStoreConfigOrThrow(),d=o.extensions.getExtensionByRegion(t);try{if(!d)throw new Cn(`Unable to proceed due to no extension configured for the region: ${t}.`);if(r.next(l(ln.RenderExtensionRequested)),"worker"===d.type){const e=function(e){if(!window.Worker)throw new Error("Unable to load the extension's web worker: your browser does not support Web Workers.");try{const t=URL.createObjectURL(new Blob([`importScripts=((i)=>(...a)=>i(...a.map((u)=>''+new URL(u,"${e}"))))(importScripts);importScripts("${e}")`],{type:"text/javascript"}));return new Worker(t)}catch(e){throw new Error("Unable to load the extension's web worker")}}(d.url);n.add(d.id,e)}else{const t=new Nn(e,d,{cartId:a,parentOrigin:In(s).origin});yield t.attach()}r.next(l(ln.RenderExtensionSucceeded)),r.complete()}catch(e){r.error(h(ln.RenderExtensionFailed,e))}},new((s=void 0)||(s=Promise))(function(e,t){function n(e){try{r(d.next(e))}catch(e){t(e)}}function i(e){try{r(d.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof s?r:new s(function(e){e(r)})).then(n,i)}r((d=d.apply(o,a||[])).next())});var o,a,s,d})}}class Rn{constructor(e){this._requestSender=e}loadExtensions({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/checkout-extensions",{timeout:e,headers:Object.assign({Accept:ct.JsonV1},Xe),params:t})}}const Fn=function(e,t,n){return t&&n?Ln(0,t,n):function(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(n=>{const i=Object.getOwnPropertyDescriptor(e.prototype,n);i&&"constructor"!==n&&Object.defineProperty(t.prototype,n,Ln(e.prototype,n,i))}),t}(e)};function Ln(e,t,n){if("function"!=typeof n.value)return n;let i=n.value;return{get(){const e=i.bind(this);return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e},set(e){i=e}}}var Bn,jn;class Un{constructor(e){this._worker=e,this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,this._worker.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,this._worker.removeEventListener("message",this._handleMessage))}addListener(e,t){let n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)}removeListener(e,t){const n=this._listeners[e];if(!n)return;const i=n.indexOf(t);i>=0&&n.splice(i,1)}trigger(e,t){const n=this._listeners[e.type];n&&n.forEach(n=>t?n(e,t):n(e))}_handleMessage(e){const t=e.data,{context:n}=t,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([Fn],Un.prototype,"_handleMessage",null);class qn{constructor(e,t){this._worker=e,this._context=t}post(e){if(!this._worker)throw new Error("WorkerPoster: Worker is not initialized or creation failed. Cannot post message.");this._worker.postMessage(Object.assign(Object.assign({},e),{context:this._context}))}}class Vn extends it{constructor(e){super(e||"Unable to proceed due to unsupported extension command."),this.name="UnsupportedExtensionCommandError",this.type="unsupported_extension_command_error"}}class Gn extends it{constructor(e){super(e||"Unable to proceed due to unsupported extension query."),this.name="UnsupportedExtensionQueryError",this.type="unsupported_extension_query_error"}}!function(e){e.ReloadCheckout="EXTENSION:RELOAD_CHECKOUT",e.ShowLoadingIndicator="EXTENSION:SHOW_LOADING_INDICATOR",e.SetIframeStyle="EXTENSION:SET_IFRAME_STYLE",e.ReRenderShippingForm="EXTENSION:RE_RENDER_SHIPPING_FORM",e.ReRenderShippingStep="EXTENSION:RE_RENDER_SHIPPING_STEP"}(Bn||(Bn={})),function(e){e.GetConsignments="EXTENSION:GET_CONSIGNMENTS"}(jn||(jn={}));class Hn{constructor(e={},t={},n={}){this._workers=e,this._commandListeners=t,this._queryListeners=n}add(e,t){this._workers[e]=t}listenForCommand(e,t,n){const i=this._getWorkerById(e);this._commandListeners[e]||(this._commandListeners[e]=new Un(i));const r=this._commandListeners[e];r.listen();const o=this._validateCommand(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}listenForQuery(e,t,n){const i=this._getWorkerById(e);this._queryListeners[e]||(this._queryListeners[e]=new Un(i));const r=this._queryListeners[e];r.listen();const o=this._validateQuery(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}stopListen(e){this._commandListeners[e]&&this._commandListeners[e].stopListen(),this._queryListeners[e]&&this._queryListeners[e].stopListen()}post(e,t){if(!this._workers[e])throw new Error(`Worker with extensionId ${e} not found`);new qn(this._workers[e],e).post(t)}clearCacheById(e){delete this._workers[e]}_getWorkerById(e){const t=this._workers[e];if(!t)throw new Cn(`Worker with extensionId ${e} not found`);return t}_validateCommand(e){if(Object.values(Bn).includes(e))return e;throw new Vn}_validateQuery(e){if(Object.values(jn).includes(e))return e;throw new Gn}}function Wn(e){return In(0===e.hostname.indexOf("www")?e.href:e.href.replace(e.hostname,`www.${e.hostname}`))}var $n;class Yn{constructor(e){this._sourceOrigins=[In(e).origin,Wn(In(e)).origin],this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))}addListener(e,t){let n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)}removeListener(e,t){const n=this._listeners[e];if(!n)return;const i=n.indexOf(t);i>=0&&n.splice(i,1)}trigger(e,t){const n=this._listeners[e.type];n&&n.forEach(n=>t?n(e,t):n(e))}_handleMessage(e){if(-1===this._sourceOrigins.indexOf(e.origin)||!bn(e.data,e.data.type))return;const t=e.data,{context:n}=t,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([Fn],Yn.prototype,"_handleMessage",null);class Kn{constructor(e,t,n={},i={},r={}){this._store=e,this._workerExtensionMessenger=t,this._commandListeners=n,this._queryListeners=i,this._posters=r}clearCacheByRegion(e){const t=this._getExtensionByRegion(e);"worker"!==t.type?this.clearCacheById(t.id):this._workerExtensionMessenger.clearCacheById(t.id)}clearCacheById(e){const t=this._getExtensionById(e);"worker"!==t.type?(this._commandListeners[e]&&delete this._commandListeners[e],this._queryListeners[e]&&delete this._queryListeners[e],this._posters[e]&&delete this._posters[e]):this._workerExtensionMessenger.clearCacheById(t.id)}listenForCommand(e,t,n){const i=this._getExtensionById(e);if("worker"===i.type)return this._workerExtensionMessenger.listenForCommand(e,t,n);this._commandListeners[e]||(this._commandListeners[e]=new Yn(i.url));const r=this._commandListeners[e];r.listen();const o=this._validateCommand(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}listenForQuery(e,t,n){const i=this._getExtensionById(e);if("worker"===i.type)return this._workerExtensionMessenger.listenForQuery(e,t,n);this._queryListeners[e]||(this._queryListeners[e]=new Yn(i.url));const r=this._queryListeners[e];r.listen();const o=this._validateQuery(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}stopListen(e){"worker"!==this._getExtensionById(e).type?(this._commandListeners[e]&&this._commandListeners[e].stopListen(),this._queryListeners[e]&&this._queryListeners[e].stopListen()):this._workerExtensionMessenger.stopListen(e)}post(e,t){try{const n=this._getExtensionById(e);if("worker"===n.type)return void this._workerExtensionMessenger.post(e,t);this._posters[e]||(this._posters[e]=On(n)),this._posters[e].post(t)}catch(n){this.clearCacheById(e),console.log(`Unable to post event to extension(${e}) because extension iframe is not mounted.\nThe event that could not be delivered:`,t)}}_getExtensionById(e){var t;this._getExtensions();const n=null===(t=this._extensions)||void 0===t?void 0:t.find(t=>t.id===e);if(!n)throw new Cn(`Unable to proceed due to no extension found for ID: ${e}.`);return n}_getExtensionByRegion(e){var t;this._getExtensions();const n=null===(t=this._extensions)||void 0===t?void 0:t.find(t=>t.region===e);if(!n)throw new Cn(`Unable to proceed due to no extension found for region: ${e}.`);return n}_getExtensions(){if(this._extensions)return;const{extensions:{getExtensions:e}}=this._store.getState();if(this._extensions=e(),!this._extensions)throw new Cn("Extension configurations not found.")}_validateCommand(e){if(Object.values(Bn).includes(e))return e;throw new Vn}_validateQuery(e){if(Object.values(jn).includes(e))return e;throw new Gn}}class Jn{constructor(e,t,n){this._store=e,this._extensionMessenger=t,this._subscribers=n,this._subscribed={},this._unsubscribers={},this._listeners={}}listen(){var e;const{data:{getExtensions:t}}=this._store.getState();null===(e=t())||void 0===e||e.forEach(e=>{if(this._listeners[e.id])return;const t=new Yn(e.url);t.addListener(Tn.Subscribe,this._handleSubscribe.bind(this)),t.addListener(Tn.Unsubscribe,this._handleUnsubscribe.bind(this)),t.listen(),this._listeners[e.id]=t})}broadcast(e){var t;const{data:{getExtensions:n}}=this._store.getState();null===(t=n())||void 0===t||t.forEach(t=>{this._subscribed[t.id]&&this._extensionMessenger.post(t.id,e)})}_handleSubscribe({payload:{eventType:e,extensionId:t}}){this._subscribed[t]=!0,this._unsubscribers[e]||(this._unsubscribers[e]=this._subscribers[e](this._store,this))}_handleUnsubscribe({payload:{eventType:e,extensionId:t}}){var n,i;delete this._subscribed[t],Object.keys(this._subscribed).length||(null===(i=(n=this._unsubscribers)[e])||void 0===i||i.call(n),delete this._unsubscribers[e])}}!function(e){e.ConsignmentsChanged="EXTENSION:CONSIGNMENTS_CHANGED"}($n||($n={}));const Zn=(e,t)=>{var n;const{data:{getConsignments:i}}=e.getState();let r=null!==(n=i())&&void 0!==n?n:[];return e.subscribe(({data:{getConsignments:e}})=>{var n;const i=null!==(n=e())&&void 0!==n?n:[];i!==r&&(t.broadcast({type:$n.ConsignmentsChanged,payload:{consignments:i,previousConsignments:r}}),r=i)},({data:{getConsignments:e}})=>e())};class Qn extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}var Xn,ei;!function(e){e[e.MissingBillingAddress=0]="MissingBillingAddress",e[e.MissingCart=1]="MissingCart",e[e.MissingCheckout=2]="MissingCheckout",e[e.MissingConsignments=3]="MissingConsignments",e[e.MissingCustomer=4]="MissingCustomer",e[e.MissingCheckoutConfig=5]="MissingCheckoutConfig",e[e.MissingOrder=6]="MissingOrder",e[e.MissingOrderConfig=7]="MissingOrderConfig",e[e.MissingOrderId=8]="MissingOrderId",e[e.MissingPayment=9]="MissingPayment",e[e.MissingPaymentId=10]="MissingPaymentId",e[e.MissingPaymentInstrument=11]="MissingPaymentInstrument",e[e.MissingPaymentMethod=12]="MissingPaymentMethod",e[e.MissingPaymentRedirectUrl=13]="MissingPaymentRedirectUrl",e[e.MissingPaymentStatus=14]="MissingPaymentStatus",e[e.MissingPaymentToken=15]="MissingPaymentToken",e[e.MissingShippingAddress=16]="MissingShippingAddress"}(Xn||(Xn={}));class ti extends Qn{constructor(e){super(function(e){switch(e){case Xn.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case Xn.MissingCart:return"Unable to proceed because cart data is unavailable.";case Xn.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case Xn.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case Xn.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case Xn.MissingCheckoutConfig:case Xn.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case Xn.MissingOrder:return"Unable to proceed because order data is unavailable.";case Xn.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case Xn.MissingPayment:return"Unable to proceed because payment data is unavailable.";case Xn.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case Xn.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case Xn.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e)),this.subtype=e,this.name="MissingDataError",this.type="missing_data"}}function ni(e){return t=e.lineItems.physicalItems.filter(e=>!e.addedByPromotion),ye(t,(e,t)=>e+t.quantity,0);var t}function ii(e,t){if(null==e)throw t?t():new Error("An unexpected error has occurred.");return e}!function(e){e[e.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",e[e.CustomerNotInitialized=1]="CustomerNotInitialized",e[e.PaymentNotInitialized=2]="PaymentNotInitialized",e[e.ShippingNotInitialized=3]="ShippingNotInitialized",e[e.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(ei||(ei={}));class ri extends Qn{constructor(e){super(function(e){switch(e){case ei.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case ei.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case ei.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case ei.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.subtype=e,this.name="NotInitializedError",this.type="not_initialized"}}const oi={de:"eu",jp:"fe",uk:"eu",us:"na"};var ai,si,di,ci,li,ui;!function(e){e.en_US="en_US",e.en_GB="en_GB",e.de_DE="de_DE",e.fr_FR="fr_FR",e.it_IT="it_IT",e.es_ES="es_ES",e.ja_JP="ja_JP"}(ai||(ai={})),function(e){e.Home="Home",e.Product="Product",e.Cart="Cart",e.Checkout="Checkout",e.Other="Other"}(si||(si={})),function(e){e.USD="USD",e.EUR="EUR",e.GBP="GBP",e.JPY="JPY"}(di||(di={})),function(e){e.PayAndShip="PayAndShip",e.PayOnly="PayOnly"}(ci||(ci={})),function(e){e.Gold="Gold",e.LightGray="LightGray",e.DarkGray="DarkGray"}(li||(li={})),function(e){e.C0001="C0001"}(ui||(ui={}));var hi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pi{constructor(e){this.amazonPayV2ScriptLoader=e}initialize(e){return hi(this,void 0,void 0,function*(){this.amazonPayV2SDK=yield this.amazonPayV2ScriptLoader.load(e),this.buttonParentContainer=this.buttonParentContainer||this.createAmazonPayButtonParentContainer()})}deinitialize(){var e;return this.amazonPayV2Button=void 0,null===(e=this.buttonParentContainer)||void 0===e||e.remove(),this.buttonParentContainer=void 0,this.amazonPayV2SDK=void 0,Promise.resolve()}bindButton(e,t,n){this.getAmazonPayV2SDK().Pay.bindChangeAction(`#${e}`,{amazonCheckoutSessionId:t,changeAction:n})}createButton(e,t){this.amazonPayV2Button=this.getAmazonPayV2SDK().Pay.renderButton(`#${e}`,t)}prepareCheckout(e){const t=this.prepareRequestConfig(e);this.getAmazonPayV2Button().onClick(()=>{this.getAmazonPayV2Button().initCheckout(t)})}prepareCheckoutWithCreationRequestConfig(e){this.getAmazonPayV2Button().onClick(()=>hi(this,void 0,void 0,function*(){const t=yield e();if(t){const e=this.prepareRequestConfig(t.createCheckoutSessionConfig,t.estimatedOrderAmount,t.productType);this.getAmazonPayV2Button().initCheckout(e)}}))}signout(){return hi(this,void 0,void 0,function*(){return this.amazonPayV2SDK&&this.amazonPayV2SDK.Pay.signout(),Promise.resolve()})}renderAmazonPayButton({buttonColor:e,checkoutState:t,containerId:n,decoupleCheckoutInitiation:i=!1,methodId:r,options:o,placement:a,isButtonMicroTextDisabled:s=!1}){const d=document.querySelector(`#${n}`);if(!d)return;const{id:c}=d.appendChild(this.getButtonParentContainer());o&&s&&(o.design=ui.C0001);const l=null!=o?o:this.getAmazonPayV2ButtonOptions(t,r,a,i,e);return this.createButton(c,l),this.getButtonParentContainer()}updateBuyNowFlowFlag(e){this.isBuyNowFlow=Boolean(e)}isPh4Enabled(e,t){const n=!!e["PROJECT-3483.amazon_pay_ph4"],i=!!e["INT-6885.amazon_pay_ph4_us_only"];return n&&i?"US"===t:n}prepareRequestConfig(e,t,n){const{publicKeyId:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew ri(ei.PaymentNotInitialized))}getCheckoutState(e){return"object"==typeof(t=e)&&null!==t&&"cart"in t&&"checkout"in t&&"config"in t&&"paymentMethods"in t?{getCart:e.cart.getCart,getCheckout:e.checkout.getCheckout,getStoreConfigOrThrow:e.config.getStoreConfigOrThrow,getPaymentMethodOrThrow:t=>e.paymentMethods.getPaymentMethodOrThrow(t)}:e;var t}}class mi extends Qn{constructor(e){super(e||"Unable to proceed because the client library of a payment method is not loaded or ready to be used."),this.name="PaymentMethodClientUnavailableError",this.type="payment_method_client_unavailable"}}class yi{constructor(e,t=window){this.scriptLoader=e,this.windowWithAmazonPay=t}load(e){return t=this,n=void 0,r=function*(){const{initializationData:t}=e,n=(null==t?void 0:t.region)||"us",i=oi[n];if(yield this.scriptLoader.loadScript(`https://static-${i}.payments-amazon.com/checkout.js`),!this.windowWithAmazonPay.amazon)throw new mi;return this.windowWithAmazonPay.amazon},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}function gi(){return new pi(new yi(a()))}function vi(e,t){return Object.assign(e,{resolveIds:t})}class fi extends Qn{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class Si extends Qn{constructor(e){super(e||"Not implemented."),this.name="NotImplementedError",this.type="not_implemented"}}var _i=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class wi{constructor(e,t){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t}initialize(e){return _i(this,void 0,void 0,function*(){const{methodId:t,amazonpay:n}=e;if(!t||!(null==n?void 0:n.container))throw new fi('Unable to proceed because "methodId" or "containerId" argument is not provided.');let i;try{i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)}catch(e){yield this.paymentIntegrationService.loadPaymentMethod(t),i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)}yield this.amazonPayV2PaymentProcessor.initialize(i),this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:this.paymentIntegrationService.getState(),containerId:n.container,methodId:t,placement:si.Checkout})})}deinitialize(){return _i(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize()})}signIn(){throw new Si('In order to sign in via Amazon, the shopper must click on "Amazon Pay" button.')}signOut(e){return _i(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getPaymentId();t&&(yield this.amazonPayV2PaymentProcessor.signout(),yield this.paymentIntegrationService.remoteCheckoutSignOut(t.providerId,e))})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}}const Ii=vi(e=>new wi(e,gi()),[{id:"amazonpay"}]);function Ci(e,t,n=!0){var i;return null!==(i=e[t])&&void 0!==i?i:n}const bi="3.128.0",Pi="3.123.2",Oi="3.106.0";class Ei{constructor(e){this.paymentIntegrationService=e,this.braintreeWindow=window}getSDKVersion(){const e=this.paymentIntegrationService.getState().getStoreConfig(),t=(null==e?void 0:e.checkoutSettings.features)||{};return this.getPreloadedSDKVersion()||(Ci(t,"PAYPAL-5809.braintree_hosted_fields_fix_version")?bi:Ci(t,"PAYPAL-5636.update_braintree_sdk_version")?Pi:Oi)}getPreloadedSDKVersion(){const e=this.braintreeWindow.braintree;if(e){const t=B(Object.values(e),e=>!!e.VERSION);return null==t?void 0:t.VERSION}}}class Ai extends Qn{constructor(e){super(e||"Unsupported browser error"),this.name="UnsupportedBrowserError",this.type="unsupported_browser"}}var Ti,ki,Di,Mi,zi,Ni,xi;function Ri(e){return Boolean("object"==typeof e&&null!==e&&("type"in e||"message"in e||"code"in e))}!function(e){e.ESTIMATED="ESTIMATED",e.FINAL="FINAL",e.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(Ti||(Ti={})),function(e){e.Completed="COMPLETED",e.Pending="PENDING",e.Failed="FAILED"}(ki||(ki={})),function(e){e.TRUSTLY="trustly"}(Di||(Di={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="cancelled",e.UNRECOGNIZED="unrecognized"}(Mi||(Mi={})),function(e){e.Customer="CUSTOMER",e.Merchant="MERCHANT",e.Network="NETWORK",e.Internal="INTERNAL",e.Unknown="UNKNOWN"}(zi||(zi={})),function(e){e.KountNotEnabled="DATA_COLLECTOR_KOUNT_NOT_ENABLED"}(Ni||(Ni={})),function(e){e.Visa="visa",e.Mastercard="mastercard",e.AmericanExpress="american-express",e.DinersClub="diners-club",e.Discover="discover",e.Jcb="jcb",e.UnionPay="union-pay",e.Maestro="maestro",e.Elo="elo",e.Mir="mir",e.Hiper="hiper",e.Hipercard="hipercard"}(xi||(xi={}));var Fi,Li,Bi,ji=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ui{constructor(e){this.braintreeScriptLoader=e}initialize(e){this.setClientToken(e)}deinitialize(){return ji(this,void 0,void 0,function*(){yield this.teardownModule(this.dataCollector),this.dataCollector=void 0})}getClient(){return ji(this,void 0,void 0,function*(){if(!this.client){const e=this.getClientTokenOrThrow(),t=yield this.braintreeScriptLoader.loadClient();this.client=yield t.create({authorization:e})}return this.client})}getDataCollectorOrThrow(e){return ji(this,void 0,void 0,function*(){const t={deviceData:void 0,teardown:()=>Promise.resolve()};if(!this.dataCollector)try{const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadDataCollector(),i=Object.assign({client:t,kount:!0},e);this.dataCollector=yield n.create(i)}catch(e){if(Ri(e)&&e.code===Ni.KountNotEnabled)return t;throw e}return this.dataCollector})}getBraintreeGooglePayment(){return ji(this,void 0,void 0,function*(){if(!this.googlePayment){const[e,t]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.loadGooglePayment()]);this.googlePayment=yield t.create({client:e})}return this.googlePayment})}getBraintreeThreeDS(){return ji(this,void 0,void 0,function*(){if(!this.threeDS){const[e,t]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.load3DS()]);this.threeDS=yield t.create({client:e,version:2})}return this.threeDS})}getBraintreeLocalPayment(e){return ji(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment){const[t,n]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.loadLocalPayment()]);this.braintreeLocalPayment=yield new Promise((i,r)=>{n.create({client:t,merchantAccountId:e},(e,t)=>{e&&r(e),i(t)})})}return this.braintreeLocalPayment})}getUsBankAccount(){return ji(this,void 0,void 0,function*(){if(!this.usBankAccount){const e=yield this.getClient(),t=yield this.braintreeScriptLoader.loadUsBankAccount();this.usBankAccount=yield t.create({client:e})}return this.usBankAccount})}getBraintreeVisaCheckout(){return this.visaCheckout||(this.visaCheckout=Promise.all([this.getClient(),this.braintreeScriptLoader.loadVisaCheckout()]).then(([e,t])=>t.create({client:e}))),this.visaCheckout}getVisaCheckoutSdk(e){return ji(this,void 0,void 0,function*(){return this.visaCheckoutSDK||(this.visaCheckoutSDK=yield this.braintreeScriptLoader.loadVisaCheckoutSdk(e)),this.visaCheckoutSDK})}getVenmoCheckoutOrThrow(){return ji(this,void 0,void 0,function*(){if(!this.braintreeVenmo){const e=yield this.getClient(),t=yield this.braintreeScriptLoader.loadVenmoCheckout(),n={client:e,allowDesktop:!0,paymentMethodUsage:"multi_use"},i=yield t.create(n);if(!i.isBrowserSupported())throw new Ai;this.braintreeVenmo=i}return this.braintreeVenmo})}setClientToken(e){this.clientToken=e}getClientTokenOrThrow(){if(!this.clientToken)throw new ri(ei.PaymentNotInitialized);return this.clientToken}teardownModule(e){return e?e.teardown():Promise.resolve()}}!function(e){e.Sandbox="sandbox",e.Production="production"}(Fi||(Fi={})),function(e){e.Client="client",e.DataCollector="dataCollector",e.Fastlane="fastlane",e.GooglePayment="googlePayment",e.HostedFields="hostedFields",e.LocalPayment="localPayment",e.Paypal="paypal",e.PaypalCheckout="paypalCheckout",e.ThreeDSecure="threeDSecure",e.UsBankAccount="usBankAccount",e.Venmo="venmo",e.VisaCheckout="visaCheckout"}(Li||(Li={})),function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification"}(Bi||(Bi={}));const qi={[Oi]:{[Li.Client]:"sha384-26BXDNnJI23JYRyFBj4xe4sVNrUSSiSSu11kxVXNM/vEPONm4LuL00w6ZaTgQewt",[Li.PaypalCheckout]:"sha384-B+vzbZwnQtzWBthpkT4TXKUibO65tyeK7eCxSvpblgprTep2+IAXB2Cxxjrn710O",[Li.Paypal]:"sha384-uyAGL1/3+XJAHnGoNy4eCoXdzJ4f7Ilzp+6w9PNnEjs6DCCz9WMyJjMN1gzc78U+",[Li.LocalPayment]:"sha384-LIvOEMkIVEwVuYBdVOQc1AC5YbGGlwyfUheS0ACK218D2STuVYQlZ4FyEPowAEfT",[Li.DataCollector]:"sha384-1bo9JDz+Kscthc085cCKWur8CLwUoBpoNyxsDi7932mCl0zFq3A5mv+FQLw9GHpV",[Li.UsBankAccount]:"sha384-xmHBVaU+w74V+OebD3AaPONFxHUGMf+QRs8G/JxVPXNNP7MDa2jL0ICWHIe2tTfJ",[Li.GooglePayment]:"sha384-WKDJl8mqoP82qZpMGH6AbZxnvXnSW8ILV4M64CyMLiugGMwu7LyP89wjCkHqsiBe",[Li.ThreeDSecure]:"sha384-VQUlpGHzsGvs5XeiGFip7EXRsvoHWEXDVmgCacfbyieZI9mdBOqq3NSoyo28OCOB",[Li.VisaCheckout]:"sha384-yx7mADfzTN0T43Q6rlH49LIg1EJ0iUZgBp/EczX9LXsUGkySgxrD+nWHQRBkyfoT",[Li.Venmo]:"sha384-QX4rPjoj1ZDhuG0aSyKs56lEKDqTMTcjYxUHY1SzO5VZDsqIE2NTkqot7KNSCyov",[Li.HostedFields]:"sha384-VvYBACfSu0Cr/J32uKmxG7AXcNOJE1AzIIL3kbikyS7YKp5fz5Is+NzNP/lyauNy",[Li.Fastlane]:"sha384-9oGsZMRZwpGtDEDYa/dFt76dECqj1xAni9gIKgc3KfMIiRnR73nEeeUDLiBzxhFa"},[Pi]:{[Li.Client]:"sha384-o+nbQGcwNNxIBeXeu3+XmbSq+Cg8R3EN3N0l5hXCgMMU2RGY0t1z0LroSEIAbfAO",[Li.PaypalCheckout]:"sha384-WrfbWPBS4mH86GAoycPSgiH8hQ8KH7A67C93Hjhunv/xhNk2YpBn3wbFA4Fhg9U/",[Li.Paypal]:"sha384-VF389nvvrRUgDsTXMxTYORDtVegB9IQa3Cxr//DyJnLYnz8/X8VCzEvck2c+Megt",[Li.LocalPayment]:"sha384-tZKx2rEQbfmZpoPSY5VPmJEhaq4X75dLvwHMs3VE9U+C8lPyw+hWTIL1+GPvWCIH",[Li.DataCollector]:"sha384-E6k3wOpP7syCDDwaRDLF06942Y00NkbwJvWi2OQXwwKzGwG5fd3E7RFUvCCecfvO",[Li.UsBankAccount]:"sha384-258FON8LZGG0W9Qaz4Jij83pZHu30YnKjJA7gNulLBh6CclkucgF+tHDQuYFRYfW",[Li.GooglePayment]:"sha384-taJ2p/0+n0VH328POAoBiuEbL3tnHUTE9S42hK1V+Txs3X+QYjZOyKW35JgHRFfO",[Li.ThreeDSecure]:"sha384-+NSZH4Zj3sO5bdWvPKhU5N16QDxeueTVTnUVeleeESkhLSaz4Ob1hh/5myecc9Ym",[Li.VisaCheckout]:"sha384-66DiBjghxk1OmBj8aksN8gbQ+CwoQcx1vPfiXUN08g1iQVM+BwewF0p7toM3i7SS",[Li.Venmo]:"sha384-B5UwY42kE4RoLoWbQ7YpqosUlUad2/DlGWiw0HhoZbSPk30CQAaSA10ohyLDTkDU",[Li.HostedFields]:"sha384-Aw9EesSaUeWxe36PqEHiOyOyOq8M6CIb1gw7/yHNVPRzGtFXXcd2OQ8qXrIlOj2P",[Li.Fastlane]:"sha384-rhBL1hpZ71JqG+2TsT0Dih47mbjx8cjJCpeZjk9tw3df1gFMKfCTmMyZunhr7H4Y"},[bi]:{[Li.Client]:"sha384-0WNxksIpRP+fYZiIdr12g6DBUQfLDzYCQJZtR/C8KkcwSGhPHfcFp3tTaGcMyFTq",[Li.PaypalCheckout]:"sha384-lWM1jk4BOxoDNV6Kop7tVNvQgINlmEVz0c/OwM+HNHK3QC8xqwd54Ovrt2QRDTjh",[Li.Paypal]:"sha384-fXUmVxC2EMZBDXZ7eTHSTL/LFBrHej/MSXT/vTBXvra4lzgLNGvREAp+x0GYObuH",[Li.LocalPayment]:"sha384-pha1xGuGSkmZH5x9aqHvRaO4xLea7rmQ/79PFj9zxNzxuFcOWZg7gOP7FibygOEC",[Li.DataCollector]:"sha384-Q6PI2F9eekWbAxhroybl+aEcvqhdowN/EQlGwBUyJOzPFn9982u9xl6SU6XfGKzc",[Li.UsBankAccount]:"sha384-W3RLQSKJL1tQ3+Y7mP6tmkamtZ8bV4Yw/XxL9Jj5JtXHraD8loMF8hAIG5m2zK7F",[Li.GooglePayment]:"sha384-TITQMsFWA3elDNGP2mWz2oKBo4qjt+TlqzovcaPoeBiAh/wPBi6nae50ADdgU1/i",[Li.ThreeDSecure]:"sha384-YiycYN89ZlL/Evcaq4y1ajW1mhd7JYfZBDuOwHtIn4/Jnm20GL+/XCM+zYAwWD8D",[Li.VisaCheckout]:"sha384-/OdaTv9qrkKzjObtUe6yzfDhHozFW/+uXlrSl736sOZRJpjGQETvpYXqMFFg69xv",[Li.Venmo]:"sha384-dA+ojdW9vbJS4JavcXyOs9d5uZHJg5dNtYupoPSH2zsXIiYDVS5amLb/u8qmQ6oz",[Li.HostedFields]:"sha384-31ZkS58+iaWsW06ftW52zzVZFp43WPd7pNYRiddYynSNg6Oh7WGbSFGorAUH6T1z",[Li.Fastlane]:"sha384-jlbrwNvL3HvLAUCtLSmrnQ2GH1udCUrRS/bVmReAS5fuIVvcW8Pko/Gkg82tlgtr"}};var Vi,Gi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Hi{constructor(e,t,n){this.scriptLoader=e,this.braintreeHostWindow=t,this.braintreeSDKVersionManager=n}loadClient(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.Client,"client.min.js")})}loadFastlane(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.Fastlane,"fastlane.min.js")})}loadPaypalCheckout(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.PaypalCheckout,"paypal-checkout.min.js")})}loadPaypal(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.Paypal,"paypal.min.js")})}loadLocalPayment(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.LocalPayment,"local-payment.min.js")})}loadDataCollector(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.DataCollector,"data-collector.min.js")})}loadUsBankAccount(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.UsBankAccount,"us-bank-account.min.js")})}loadGooglePayment(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.GooglePayment,"google-payment.min.js")})}load3DS(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.ThreeDSecure,"three-d-secure.min.js")})}loadVisaCheckout(){return this.loadBraintreeModuleOrThrow(Li.VisaCheckout,"visa-checkout.min.js")}loadVenmoCheckout(){return this.loadBraintreeModuleOrThrow(Li.Venmo,"venmo.min.js")}loadHostedFields(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.HostedFields,"hosted-fields.min.js")})}loadVisaCheckoutSdk(e){return Gi(this,void 0,void 0,function*(){if(this.braintreeHostWindow.V)return this.braintreeHostWindow.V;const t=e?"sha384-0eu1s1GtqzXlL9DtLgmwzC5WWlEH/ADRM0n38cVQkvtT+W/gey96rcb1LwuUOPDm":"sha384-1f1csvP3ZFxg4dILH1GaY4LHlZ0oX7Rk83rxmLlwbnIi4TM0NYzXoev1VoEiVDS6";return this.scriptLoader.loadScript(`//${e?"sandbox-":""}assets.secure.checkout.visa.com/checkout-widget/resources/js/integration/v1/sdk.js`,{async:!0,attributes:{integrity:t,crossorigin:"anonymous"}}).then(()=>{if(!this.braintreeHostWindow.V)throw new mi;return this.braintreeHostWindow.V})})}loadBraintreeModuleOrThrow(e,t){return Gi(this,void 0,void 0,function*(){let n=this.getBraintreeModule(e);if(n)return n;const i=this.braintreeSDKVersionManager.getSDKVersion(),r=`//js.braintreegateway.com/web/${i}/js/${t}`,o=i in qi?this.getIntegrityValuesByModuleName(e,i):void 0;if(yield this.scriptLoader.loadScript(r,o?{async:!0,attributes:{integrity:o,crossorigin:"anonymous"}}:void 0),n=this.getBraintreeModule(e),!n)throw new mi;return n})}getBraintreeModule(e){var t;return null===(t=this.braintreeHostWindow.braintree)||void 0===t?void 0:t[e]}getIntegrityValuesByModuleName(e,t){const n=qi[t][e];if(!n)throw new Error("Unexpected fileName value");return n}}class Wi extends Qn{constructor(e){super(e||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}!function(e){e.BRAINTREE="braintree",e.BRAINTREE_FASTLANE="braintreeacceleratedcheckout"}(Vi||(Vi={}));var $i,Yi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}($i||($i={}));class Ki{constructor(e,t,n,i,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._braintreeSdk=i,this._applePayScriptLoader=r,this._onAuthorizeCallback=ce,this._onError=ce,this._onClick=ce,this._subTotalLabel=$i.Subtotal,this._shippingLabel=$i.Shipping,this._hasApplePaySession=!1}initialize(e){var t;return Yi(this,void 0,void 0,function*(){const{methodId:n,applepay:i}=e;if(!n||!i)throw new ti(Xn.MissingPaymentMethod);const{container:r,shippingLabel:o,subtotalLabel:a,onError:s=ce,onClick:d=ce,onPaymentAuthorize:c}=i;this._shippingLabel=o||$i.Shipping,this._subTotalLabel=a||$i.Subtotal,this._onAuthorizeCallback=c,this._onError=s,this._onClick=d;let l=this._paymentIntegrationService.getState();yield this._applePayScriptLoader.loadSdk();try{this._paymentMethod=l.getPaymentMethodOrThrow(n)}catch(e){l=yield this._paymentIntegrationService.loadPaymentMethod(n),this._paymentMethod=l.getPaymentMethodOrThrow(n)}yield this._paymentIntegrationService.verifyCheckoutSpamProtection(),this._applePayButton=this._createButton(r),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),(null===(t=this._paymentMethod.initializationData)||void 0===t?void 0:t.gateway)===Vi.BRAINTREE&&this._paymentMethod.clientToken&&this._braintreeSdk.initialize(this._paymentMethod.clientToken)})}deinitialize(){return Promise.resolve()}signIn(){throw new Si('In order to sign in via Apple, the shopper must click on "Apple Pay" button.')}signOut(){throw new Si("Need to do signout via apple.")}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}_createButton(e){const t=document.getElementById(e);if(!t)throw new fi("Unable to create sign-in button without valid container ID.");const n=this._createApplePayButtonElement();return t.appendChild(n),n}_createApplePayButtonElement(){const e=document.createElement("apple-pay-button");return e.setAttribute("buttonstyle","black"),e.setAttribute("type","plain"),e.setAttribute("style","--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;"),e}_handleWalletButtonClick(e){if(e.preventDefault(),this._hasApplePaySession)return;this._onClick();const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getStoreConfigOrThrow(),r=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new ti(Xn.MissingPaymentMethod);const o=this._getBaseRequest(n,r,i,this._paymentMethod),a=this._sessionFactory.create(o);this._handleApplePayEvents(a,this._paymentMethod,i),a.begin(),this._hasApplePaySession=!0}_getBaseRequest(e,t,n,i){var r;const{storeProfile:{storeCountryCode:o,storeName:a}}=n,{currency:{code:s,decimalPlaces:d}}=e,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=i,u=e.lineItems.physicalItems.length>0,h={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:o,currencyCode:s,merchantCapabilities:c,supportedNetworks:l,lineItems:[],total:u?{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"pending"}:{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"final"}};if(u)null===(r=h.requiredShippingContactFields)||void 0===r||r.push("postalAddress");else{const e=[{label:this._subTotalLabel,amount:`${t.subtotal.toFixed(d)}`}];t.taxes.forEach(t=>e.push({label:t.name,amount:`${t.amount.toFixed(d)}`})),h.lineItems=e}return h}_handleApplePayEvents(e,t,n){e.onvalidatemerchant=n=>Yi(this,void 0,void 0,function*(){try{const{body:i}=yield this._onValidateMerchant(t,n);e.completeMerchantValidation(i)}catch(e){this._onError(e)}}),e.onshippingcontactselected=t=>Yi(this,void 0,void 0,function*(){return this._handleShippingContactSelected(e,n,t)}),e.onshippingmethodselected=t=>Yi(this,void 0,void 0,function*(){return this._handleShippingMethodSelected(e,n,t)}),e.oncancel=()=>Yi(this,void 0,void 0,function*(){this._hasApplePaySession=!1;try{const e=`/remote-checkout/${t.id}/signout`;return yield this._requestSender.get(e),yield this._paymentIntegrationService.loadCheckout()}catch(e){return this._onError(new Wi)}}),e.onpaymentauthorized=n=>Yi(this,void 0,void 0,function*(){return this._onPaymentAuthorized(n,e,t)})}_handleShippingContactSelected(e,t,n){var i;return Yi(this,void 0,void 0,function*(){const r=this._transformContactToAddress(n.shippingContact);try{yield this._paymentIntegrationService.updateShippingAddress(r)}catch(t){return e.abort(),this._hasApplePaySession=!1,this._onError(t)}const{storeProfile:{storeName:o}}=t;let a=this._paymentIntegrationService.getState();const{currency:{decimalPlaces:s}}=a.getCartOrThrow();let d=a.getCheckoutOrThrow();const c=null===(i=d.consignments[0].selectedShippingOption)||void 0===i?void 0:i.id,l=d.consignments[0].availableShippingOptions,u=null==l?void 0:l.find(({id:e})=>e===c),h=null==l?void 0:l.filter(e=>e.id!==c),p=u?[{label:u.description,amount:`${u.cost.toFixed(s)}`,detail:u.additionalDescription,identifier:u.id}]:[];if(h&&[...h.filter(e=>e.isRecommended),...h.filter(e=>!e.isRecommended)].forEach(e=>p.push({label:e.description,amount:`${e.cost.toFixed(s)}`,detail:e.additionalDescription,identifier:e.id})),!(l instanceof Array))throw new Error("Shipping options not available.");if(0===l.length)return void e.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:o,amount:`${d.grandTotal.toFixed(s)}`},[]);const m=l.find(e=>e.isRecommended),y=m?m.id:l[0].id,g=u?u.id:y;try{yield this._updateShippingOption(g)}catch(e){return this._onError(e)}a=this._paymentIntegrationService.getState(),d=a.getCheckoutOrThrow(),e.completeShippingContactSelection({newShippingMethods:p,newTotal:{type:"final",label:o,amount:`${d.grandTotal.toFixed(s)}`},newLineItems:this._getUpdatedLineItems(d,s)})})}_handleShippingMethodSelected(e,t,n){return Yi(this,void 0,void 0,function*(){const{storeProfile:{storeName:i}}=t,{shippingMethod:{identifier:r}}=n;try{yield this._updateShippingOption(r)}catch(t){return e.abort(),this._hasApplePaySession=!1,this._onError(t)}const o=this._paymentIntegrationService.getState(),{currency:{decimalPlaces:a}}=o.getCartOrThrow(),s=o.getCheckoutOrThrow();e.completeShippingMethodSelection({newTotal:{type:"final",label:i,amount:`${s.grandTotal.toFixed(a)}`},newLineItems:this._getUpdatedLineItems(s,a)})})}_getUpdatedLineItems(e,t){const n=[{label:this._subTotalLabel,amount:`${e.subtotal.toFixed(t)}`}];return e.taxes.forEach(e=>n.push({label:e.name,amount:`${e.amount.toFixed(t)}`})),n.push({label:this._shippingLabel,amount:`${e.shippingCostTotal.toFixed(t)}`}),n}_updateShippingOption(e){return Yi(this,void 0,void 0,function*(){return this._paymentIntegrationService.selectShippingOption(e)})}_onValidateMerchant(e,t){return Yi(this,void 0,void 0,function*(){const n=[`validationUrl=${t.validationURL}`,`merchantIdentifier=${e.initializationData.merchantId}`,`displayName=${e.initializationData.storeName}`,`domainName=${window.location.hostname}`].join("&");return this._requestSender.post(`${e.initializationData.paymentsUrl}/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})})}_onPaymentAuthorized(e,t,n){var i;return Yi(this,void 0,void 0,function*(){const{token:r,billingContact:o,shippingContact:a}=e.payment,s=this._paymentIntegrationService.getState().getCartOrThrow().lineItems.physicalItems.length>0;let d;(null===(i=n.initializationData)||void 0===i?void 0:i.gateway)===Vi.BRAINTREE&&(d=yield this._getBraintreeDeviceData());const c={methodId:n.id,paymentData:{deviceSessionId:d,formattedPayload:{apple_pay_token:{payment_data:r.paymentData,payment_method:r.paymentMethod,transaction_id:r.transactionIdentifier}}}},l=this._transformContactToAddress(o),u=this._transformContactToAddress(a),h=null==a?void 0:a.emailAddress,p=(null==a?void 0:a.phoneNumber)||"";try{return yield this._paymentIntegrationService.updateBillingAddress(Object.assign(Object.assign({},l),{email:h,phone:p})),s&&(yield this._paymentIntegrationService.updateShippingAddress(u)),yield this._paymentIntegrationService.submitOrder({useStoreCredit:!1}),yield this._paymentIntegrationService.submitPayment(c),t.completePayment(ApplePaySession.STATUS_SUCCESS),this._onAuthorizeCallback()}catch(e){return t.completePayment(ApplePaySession.STATUS_FAILURE),this._onError(e)}})}_transformContactToAddress(e){return{firstName:(null==e?void 0:e.givenName)||"",lastName:(null==e?void 0:e.familyName)||"",city:(null==e?void 0:e.locality)||"",company:"",address1:(null==e?void 0:e.addressLines)&&e.addressLines[0]||"",address2:(null==e?void 0:e.addressLines)&&e.addressLines[1]||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||"",phone:(null==e?void 0:e.phoneNumber)||"",stateOrProvince:(null==e?void 0:e.administrativeArea)||"",stateOrProvinceCode:(null==e?void 0:e.administrativeArea)||"",customFields:[]}}_getBraintreeDeviceData(){return Yi(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}function Ji(e){if(!function(e){return"ApplePaySession"in e}(e))throw new Error("Apple pay is not supported")}class Zi{create(e){return Ji(window),new ApplePaySession(1,e)}}class Qi{constructor(e){this.scriptLoader=e,this.sdkVersion="1.latest"}loadSdk(){return e=this,t=void 0,i=function*(){(function(e){return"ApplePaySDK"in e})(window)||(yield this.scriptLoader.loadScript(`https://applepay.cdn-apple.com/jsapi/${this.sdkVersion}/apple-pay-sdk.js`),Ji(window))},new((n=void 0)||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())});var e,t,n,i}}const Xi=vi(e=>{const{getHost:t}=e.getState(),i=new Ei(e);return new Ki(n({host:t()}),e,new Zi,new Ui(new Hi(a(),window,i)),new Qi(new r))},[{id:"applepay"}]);class er extends Qn{constructor(e){super(e||"An unexpected error has occurred during buy now cart creation process. Please try again later."),this.name="BuyNowCartCreationError",this.type="buy_now_cart_creation_error"}}const tr={body:{},headers:{},status:0};class nr extends Qn{constructor(e,{message:t,errors:n}={}){const{body:i,headers:r,status:o}=e||tr;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=i,this.headers=r,this.status=o,this.errors=n||[]}}var ir,rr,or,ar,sr,dr,cr;!function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(ir||(ir={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(rr||(rr={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(or||(or={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(ar||(ar={})),function(e){e.pill="pill",e.rect="rect"}(sr||(sr={})),function(e){e.OXXO="oxxo"}(dr||(dr={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(cr||(cr={}));var lr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ur{constructor(e,t,n,i){this.formPoster=e,this.paymentIntegrationService=t,this.bigCommercePaymentsRequestSender=n,this.bigCommercePaymentsScriptLoader=i}loadPayPalSdk(e,t,n,i){return lr(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e);return this.paypalSdk=yield this.bigCommercePaymentsScriptLoader.getPayPalSDK(a,o,n,i),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new mi;return this.paypalSdk}createBuyNowCartOrThrow(e){return lr(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}})}createOrder(e,t){return lr(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:n},t));return i})}createOrderCardFields(e,t){return lr(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i,setupToken:r}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:n},t));return Object.assign({orderId:i},r?{setupToken:r}:{})})}updateOrder(){return lr(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getConsignmentsOrThrow()[0];try{yield this.bigCommercePaymentsRequestSender.updateOrder({availableShippingOptions:n.availableShippingOptions,cartId:t.id,selectedShippingOption:n.selectedShippingOption})}catch(e){throw new nr}})}getOrderStatus(e,t){return lr(this,void 0,void 0,function*(){try{const{status:n}=yield this.bigCommercePaymentsRequestSender.getOrderStatus(e,t);return n}catch(e){throw new nr}})}tokenizePayment(e,t){const n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new ti(Xn.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===xt.BuyNow&&{cart_id:n.id}))}submitPayment(e,t,n){return lr(this,void 0,void 0,function*(){const i={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}};yield this.paymentIntegrationService.submitPayment(Object.assign({methodId:e,paymentData:i},n?{gatewayId:n}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],i=n.find(e=>e.isRecommended),r=(e?n.find(t=>t.id===e):n.find(e=>{var n;return e.id===(null===(n=t.selectedShippingOption)||void 0===n?void 0:n.id)}))||i||n[0];if(!r)throw new Error("Your order can't be shipped to this address");return r}getAddress(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:(null==e?void 0:e.phone)||"",company:"",address1:(null==e?void 0:e.address1)||"",address2:(null==e?void 0:e.address2)||"",city:(null==e?void 0:e.city)||"",countryCode:(null==e?void 0:e.countryCode)||"",postalCode:(null==e?void 0:e.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==e?void 0:e.stateOrProvinceCode)||"",customFields:[]}}getBillingAddressFromOrderDetails({payer:e}){var t,n;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,address2:e.address.address_line_2,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1,phone:null===(n=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===n?void 0:n.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:n}=e,{address:i,name:{full_name:r}}=n[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:i.address_line_1,address2:i.address_line_2,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})}getValidButtonStyle(e){const{color:t,height:n,label:i,shape:r}=e||{},o={color:t&&ar[t]?t:void 0,height:this.getValidHeight(n),label:i&&or[i]?i:void 0,shape:r&&sr[r]?r:void 0};return ue(o,J)}getValidHeight(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40}removeElement(e){const t=e&&document.getElementById(e);t&&(t.style.display="none")}}const hr="This API endpoint is for internal use only and may change in the future";var pr;!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(pr||(pr={}));const mr=pr,yr={"X-Checkout-SDK-Version":"1.909.5"};var gr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vr{constructor(e){this.requestSender=e}createOrder(e,t){return gr(this,void 0,void 0,function*(){const n=`/api/storefront/payment/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.post(n,{headers:r,body:i})).body})}updateOrder(e){return gr(this,void 0,void 0,function*(){const t=e,n=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.put("/api/storefront/initialization/bigcommerce_payments",{headers:n,body:t})).body})}getOrderStatus(e="bigcommerce_payments",t){return gr(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body})}}var fr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Sr{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,n,i){return fr(this,void 0,void 0,function*(){const r=this.getPayPalSdkScriptConfigOrThrow(e,t,n);return this.loadPayPalSDK(r,i)})}loadPayPalSDK(e,t=!1){return fr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsPayPalSDK||t){const t=this.transformConfig(e.options),n=this.transformConfig(e.attributes),i=`https://www.paypal.com/sdk/js?${new URLSearchParams(t).toString()}`;yield this.scriptLoader.loadScript(i,{async:!0,attributes:n})}if(!this.window.bigCommercePaymentsPayPalSDK)throw new mi;return this.window.bigCommercePaymentsPayPalSDK})}getPayPalSdkScriptConfigOrThrow(e,t,n=!0){const{id:i,clientToken:r,initializationData:o}=e;if(!(null==o?void 0:o.clientId))throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:c,attributionId:l,isVenmoEnabled:u,isHostedCheckoutEnabled:h,isPayPalCreditAvailable:p,isDeveloperModeApplicable:m,availableAlternativePaymentMethods:y=[],enabledAlternativePaymentMethods:g=[],isGooglePayEnabled:v}=o,f=h||n,S="bigcommerce_payments_creditcards"===i,_=S?["card"]:[],w=S?[]:["card"],I=p?["credit","paylater"]:[],C=p?[]:["credit","paylater"],b=u?["venmo"]:[],P=u?[]:["venmo"],O=y.filter(e=>!g.includes(e)),E=v?["googlepay"]:[],A=n?["card-fields"]:[],T=this.filterFundingOptions([...w,...C,...P,...O]),k=this.filterFundingOptions([..._,...I,...b,...g]);return{options:Object.assign({"client-id":s,"merchant-id":d,"enable-funding":k.length>0?k:void 0,"disable-funding":T.length>0?T:void 0,commit:f,components:["buttons","hosted-fields","payment-fields","legal",...E,...A],currency:t,intent:a},m&&{"buyer-country":c}),attributes:{"data-partner-attribution-id":l,"data-client-token":r,"data-namespace":"bigCommercePaymentsPayPalSDK"}}}filterFundingOptions(e){const t=["klarna","afterpay"];return e?e.filter(e=>!t.includes(e)):[]}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}const _r=e=>{const{getHost:t}=e.getState();return new ur(Ee(),e,new vr(n({host:t()})),new Sr(a()))},wr=40;var Ir=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Cr{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=ce}initialize(e){return Ir(this,void 0,void 0,function*(){const{bigcommerce_payments:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.bigcommerce_payments.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.bigcommerce_payments.onClick" argument is not a function.');this.onError=t.onError||ce,this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Ir(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return Ir(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){var n,i;const{container:r,onClick:o,onComplete:a}=t,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:c,paymentButtonStyles:l,isAppSwitchEnabled:u=!1}=d.initializationData||{},{checkoutTopButtonStyles:h}=l||{},p=Object.assign(Object.assign(Object.assign({},u&&{appSwitchWhenAvailable:!0}),{createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)}),o&&{onClick:()=>o()}),m=Object.assign(Object.assign({},!u&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(t,n)=>this.onHostedCheckoutApprove(t,n,e,a)}),y=Object.assign(Object.assign({fundingSource:s.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},h),{height:wr}))},p),c&&m),g=s.Buttons(y);g.isEligible()?(null===(n=g.hasReturned)||void 0===n?void 0:n.call(g))&&u?null===(i=g.resume)||void 0===i||i.call(g):g.render(`#${r}`):this.bigCommercePaymentsIntegrationService.removeElement(r)}onHostedCheckoutApprove(e,t,n,i){return Ir(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Ir(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}onShippingOptionsChange(e){return Ir(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const br=vi(e=>new Cr(e,_r(e)),[{id:"bigcommerce_payments"}]);var Pr,Or,Er,Ar,Tr,kr,Dr,Mr,zr,Nr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class xr{constructor(e){this.scriptLoader=e,this.window=window}getPayPalFastlaneSdk(e,t,n){return Nr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsFastlaneSdk){const i=this.getPayPalFastlaneSdkConfiguration(e,t,n);if(yield this.loadPayPalSdk(i),!this.window.bigCommercePaymentsFastlaneSdk)throw new mi}return this.window.bigCommercePaymentsFastlaneSdk})}getPayPalGooglePaySdk(e,t,n,i){return Nr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsGooglePay||i){const i=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n);yield this.loadPayPalSdk(i)}if(!this.window.bigCommercePaymentsGooglePay)throw new mi;return this.window.bigCommercePaymentsGooglePay})}getPayPalApmsSdk(e,t){return Nr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsApms){const n=this.getPayPalApmSdkConfiguration(e,t);if(yield this.loadPayPalSdk(n),!this.window.bigCommercePaymentsApms)throw new mi}return this.window.bigCommercePaymentsApms})}getPayPalMessages(e,t){return Nr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsMessages){const n=this.getPayPalSdkMessagesConfiguration(e,t);yield this.loadPayPalSdk(n)}if(!this.window.bigCommercePaymentsMessages)throw new mi;return this.window.bigCommercePaymentsMessages})}loadPayPalSdk({options:e,attributes:t}){return Nr(this,void 0,void 0,function*(){const n=this.transformConfig(e),i=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(n).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:i})})}getPayPalFastlaneSdkConfiguration(e,t,n){const{clientToken:i,initializationData:r}=e;if(!r||!r.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,attributionId:d}=r;return{options:{"client-id":a,"merchant-id":s,commit:!0,components:["fastlane","three-domain-secure"],currency:t,intent:o},attributes:{"data-client-metadata-id":n.replace(/-/g,""),"data-namespace":"bigCommercePaymentsFastlaneSdk","data-partner-attribution-id":d,"data-sdk-client-token":i}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n=!0){const{clientToken:i,initializationData:r}=e;if(!r||!r.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,buyerCountry:d,attributionId:c,isHostedCheckoutEnabled:l,isDeveloperModeApplicable:u}=r,h=l||n;return{options:Object.assign({"client-id":a,"merchant-id":s,commit:h,components:["googlepay"],currency:t,intent:o},u&&{"buyer-country":d}),attributes:{"data-partner-attribution-id":c,"data-client-token":i,"data-namespace":"bigCommercePaymentsGooglePay"}}}getPayPalApmSdkConfiguration(e,t){const{initializationData:n}=e;if(!n||!n.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:i,clientId:r,merchantId:o,buyerCountry:a,attributionId:s,isDeveloperModeApplicable:d,availableAlternativePaymentMethods:c=[],enabledAlternativePaymentMethods:l=[]}=n,u=this.filterFundingOptions(l),h=this.filterFundingOptions(c.filter(e=>!l.includes(e)));return{options:Object.assign({"client-id":r,"merchant-id":o,"enable-funding":u.length>0?u:void 0,"disable-funding":h.length>0?h:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:i},d&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":s,"data-namespace":"bigCommercePaymentsApms"}}}getPayPalSdkMessagesConfiguration(e,t){const{initializationData:n}=e;if(!n||!n.clientId)throw new ti(Xn.MissingPaymentMethod);const{clientId:i,merchantId:r,attributionId:o,isDeveloperModeApplicable:a,buyerCountry:s}=n;return{options:Object.assign({"client-id":i,"merchant-id":r,components:["messages"],currency:t},a&&{"buyer-country":s}),attributes:{"data-namespace":"bigCommercePaymentsMessages","data-partner-attribution-id":o}}}filterFundingOptions(e){const t=["klarna","afterpay"];return e?e.filter(e=>!t.includes(e)):[]}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}function Rr(){return new xr(o())}!function(e){e.CVV="cvv",e.PAN="pan"}(Pr||(Pr={}));class Fr{static get(e){const t=`${encodeURIComponent(`${e}`)}=`,n=document.cookie;let i=null;const r=n.indexOf(t);if(r>-1){let e=n.indexOf(";",r);-1===e&&(e=n.length),i=decodeURIComponent(n.substring(r+t.length,e))}return i}static set(e,t,n={secure:!0}){let i=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;const{expires:r,path:o,domain:a,secure:s}=n;if(r)i+=`; expires=${r.toUTCString()}`;else{const e=new Date,t=60;e.setTime(e.getTime()+60*t*1e3),i+=`; expires=${e.toUTCString()}`}o&&(i+=`; path=${o}`),a&&(i+=`; domain=${a}`),s&&(i+="; secure"),document.cookie=i}static remove(e,t){Fr.set(e,"",Object.assign({expires:new Date(0)},t))}}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Or||(Or={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(Er||(Er={})),function(e){e.Always="SCA_ALWAYS"}(Ar||(Ar={})),function(e){e.Succeeded="succeeded",e.Cancelled="cancelled",e.Errored="errored"}(Tr||(Tr={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(kr||(kr={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(Dr||(Dr={})),function(e){e.pill="pill",e.rect="rect"}(Mr||(Mr={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="canceled",e.UNRECOGNIZED="unrecognized"}(zr||(zr={}));var Lr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Br{constructor(){this.window=window}initializePayPalFastlane(e,t,n){return Lr(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("fastlaneEnv","sandbox"),window.localStorage.setItem("axoEnv","sandbox")),!this.window.bigCommercePaymentsFastlane){const t={root:{backgroundColorPrimary:"transparent"}};this.window.bigCommercePaymentsFastlane=yield e.Fastlane({styles:n||t})}return this.window.bigCommercePaymentsFastlane})}getPayPalFastlaneOrThrow(){if(!this.window.bigCommercePaymentsFastlane)throw new mi;return this.window.bigCommercePaymentsFastlane}lookupCustomerOrThrow(e){return Lr(this,void 0,void 0,function*(){return this.getPayPalFastlaneOrThrow().identity.lookupCustomerByEmail(e)})}triggerAuthenticationFlowOrThrow(e){return Lr(this,void 0,void 0,function*(){return e?this.getPayPalFastlaneOrThrow().identity.triggerAuthenticationFlow(e):{}})}updateStorageSessionId(e){const t=new Date;t.setDate(t.getDate()+14);const n={expires:t,secure:!0};Fr.set("bc-fastlane-sessionId",e,n)}removeStorageSessionId(){Fr.remove("bc-fastlane-sessionId")}getStorageSessionId(){return Fr.get("bc-fastlane-sessionId")||""}mapPayPalFastlaneProfileToBcCustomerData(e,t){var n,i,r;const{authenticationState:o,profileData:a}=t,s=null===(r=null===(i=null===(n=null==a?void 0:a.card)||void 0===n?void 0:n.paymentSource)||void 0===i?void 0:i.card)||void 0===r?void 0:r.billingAddress,d=null==a?void 0:a.shippingAddress,c=null==a?void 0:a.name,l=null==a?void 0:a.card,u=d?this.mapPayPalToBcAddress(d.address,d.name,d.phoneNumber):void 0,h=s&&c?this.mapPayPalToBcAddress(s,c,null==d?void 0:d.phoneNumber):void 0,p=l?this.mapPayPalToBcInstrument(e,l):[],m=this.filterAddresses([u,h]);return{authenticationState:o||zr.UNRECOGNIZED,addresses:m,billingAddress:h,shippingAddress:u,instruments:p}}mapPayPalToBcInstrument(e,t){const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a}=i.card,[s,d]=o.split("-");return[{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:Pr.PAN,type:"card"}]}mapBcToPayPalAddress(e){return{company:(null==e?void 0:e.company)||"",addressLine1:(null==e?void 0:e.address1)||"",addressLine2:(null==e?void 0:e.address2)||"",adminArea1:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",adminArea2:(null==e?void 0:e.city)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||""}}mapPayPalToBcAddress(e,t,n,i){const[r,o]=t.fullName.split(" "),a=(null==n?void 0:n.nationalNumber)||"",s=(null==n?void 0:n.countryCode)||"";return{id:Date.now(),type:"paypal-address",firstName:t.firstName||r||"",lastName:t.lastName||o||"",company:e.company||"",address1:e.addressLine1,address2:e.addressLine2||"",city:e.adminArea2,stateOrProvince:e.adminArea1,stateOrProvinceCode:e.adminArea1,country:e.countryCode||"",countryCode:e.countryCode||"",postalCode:e.postalCode,phone:s+a,customFields:i||[]}}filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this.isEqualAddresses(e,t))?e:[...e,t]:e,[])}isEqualAddresses(e,t){return Y(this.normalizeAddress(e),this.normalizeAddress(t))}normalizeAddress(e){return le(e,["id","phone"])}}function jr(){return new Br}function Ur(e){return"string"!=typeof e}function qr(e,t){if(t||e)return function(e){var t,n;const i={},r=ue(e.root,Ur),o=ue(e.input,Ur),a=ue(e.toggle,Ur),s=ue(null===(t=e.text)||void 0===t?void 0:t.body,Ur),d=ue(null===(n=e.text)||void 0===n?void 0:n.caption,Ur),c=e.branding;return Object.keys(r).length&&(i.root=r),Object.keys(o).length&&(i.input=o),Object.keys(a).length&&(i.toggle=a),Object.keys(s).length&&(i.text={},i.text.body=s),Object.keys(d).length&&(i.text=Object.assign({},i.text),i.text.caption=d),c&&(i.branding=c),i}(function(e,t){var n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,_,w,I,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(c=null==t?void 0:t.input)||void 0===c?void 0:c.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.focusBorderColor),backgroundColor:(null==e?void 0:e.fastlaneInputSettingsBackgroundColor)||(null===(u=null==t?void 0:t.input)||void 0===u?void 0:u.backgroundColor),borderWidth:(null==e?void 0:e.fastlaneInputSettingsBorderWidth)||(null===(h=null==t?void 0:t.input)||void 0===h?void 0:h.borderWidth),textColorBase:(null==e?void 0:e.fastlaneInputSettingsTextColorBase)||(null===(p=null==t?void 0:t.input)||void 0===p?void 0:p.textColorBase)},toggle:{colorPrimary:(null==e?void 0:e.fastlaneToggleSettingsColorPrimary)||(null===(m=null==t?void 0:t.toggle)||void 0===m?void 0:m.colorPrimary),colorSecondary:(null==e?void 0:e.fastlaneToggleSettingsColorSecondary)||(null===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(S=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===S?void 0:S.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(w=null===(_=null==t?void 0:t.text)||void 0===_?void 0:_.caption)||void 0===w?void 0:w.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(I=null==t?void 0:t.text)||void 0===I?void 0:I.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var Vr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Gr{constructor(e,t,n){this.paymentIntegrationService=e,this.bigCommercePaymentsSdk=t,this.bigCommercePaymentsFastlaneUtils=n}initialize(e){var t;return Vr(this,void 0,void 0,function*(){const{methodId:n,bigcommerce_payments_fastlane:i}=e;if(!n)throw new fi('Unable to proceed because "methodId" argument is not provided.');try{yield this.paymentIntegrationService.loadPaymentMethod(n);const e=this.paymentIntegrationService.getState(),r=e.getCartOrThrow(),o=e.getPaymentMethodOrThrow(n),a=!!(null===(t=o.initializationData)||void 0===t?void 0:t.isDeveloperModeApplicable),s=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(o,r.currency.code,r.id);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(s,a,this.getFastlaneStyles(n,i))}catch(e){}return Promise.resolve()})}deinitialize(){return Vr(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return Vr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:void 0,addresses:void 0,instruments:void 0}),this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId()})}signOut(e){return Vr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return Vr(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:n,methodId:i}=e||{};if(!i)throw new fi('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof n)throw new fi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(this.paymentIntegrationService.getState().getCustomerOrThrow().isGuest){t&&"function"==typeof t&&t();try{yield this.runPayPalAuthenticationFlowOrThrow(i)}catch(e){}}n()})}runPayPalAuthenticationFlowOrThrow(e){return Vr(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow().id,i=t.getCustomer(),r=t.getBillingAddress(),o=(null==i?void 0:i.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(a),d=s.authenticationState===zr.CANCELED;yield this.updateCustomerDataState(e,s),d?this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId():this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(n)})}updateCustomerDataState(e,t){var n;return Vr(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow(),{authenticationState:r,addresses:o,billingAddress:a,shippingAddress:s,instruments:d}=this.bigCommercePaymentsFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,t);if(yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:r,addresses:o,instruments:d}),a&&(yield this.paymentIntegrationService.updateBillingAddress(a)),s&&i.lineItems.physicalItems.length>0){const t=yield this.paymentIntegrationService.updateShippingAddress(s),i=t.getPaymentMethodOrThrow(e),{isFastlaneShippingOptionAutoSelectEnabled:r}=i.initializationData||{},o=t.getConsignments()||[],a=(null===(n=o[0])||void 0===n?void 0:n.availableShippingOptions)||[],d=a[0],c=a.find(e=>e.isRecommended);if((c||d)&&r){const e=(null==c?void 0:c.id)||d.id;yield this.paymentIntegrationService.selectShippingOption(e)}}})}getFastlaneStyles(e,t){const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{fastlaneStyles:i,isFastlaneStylingEnabled:r}=n.initializationData||{};return qr(r?i:{},null==t?void 0:t.styles)}}const Hr=vi(e=>new Gr(e,Rr(),jr()),[{id:"bigcommerce_payments_fastlane"},{id:"bigcommerce_payments_creditcards"}]);var Wr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class $r{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=ce}initialize(e){return Wr(this,void 0,void 0,function*(){const{bigcommerce_payments_paylater:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater.onClick" argument is not a function.');this.onError=t.onError||ce,this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC BigCommercePayments PayLater]: button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Wr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Wr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){const{container:n,onComplete:i,onClick:r}=t,o=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:s,paymentButtonStyles:d}=a.initializationData||{},{checkoutTopButtonStyles:c}=d||{},l=Object.assign({createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},r&&{onClick:()=>r()}),u={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(t,n)=>this.onHostedCheckoutApprove(t,n,e,i)},h=[o.FUNDING.PAYLATER,o.FUNDING.CREDIT];let p=!1;h.forEach(e=>{if(!p){const t=Object.assign(Object.assign({fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},c),{height:wr}))},l),s&&u),i=o.Buttons(t);i.isEligible()&&(i.render(`#${n}`),p=!0)}}),p||this.bigCommercePaymentsIntegrationService.removeElement(n)}onHostedCheckoutApprove(e,t,n,i){return Wr(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Wr(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}onShippingOptionsChange(e){return Wr(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const Yr=vi(e=>new $r(e,_r(e)),[{id:"bigcommerce_payments_paylater"}]);var Kr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Jr{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return Kr(this,void 0,void 0,function*(){const{bigcommerce_payments_venmo:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC Payments Venmo]: Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Kr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Kr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){const{container:n,onClick:i}=t,r=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:a}=o.initializationData||{},{checkoutTopButtonStyles:s}=a||{},d=Object.assign({fundingSource:r.FUNDING.VENMO,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},s),{height:wr})),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},i&&{onClick:()=>i()}),c=r.Buttons(d);c.isEligible()?c.render(`#${n}`):this.bigCommercePaymentsIntegrationService.removeElement(n)}}const Zr=vi(e=>new Jr(e,_r(e)),[{id:"bigcommerce_payments_venmo"}]);class Qr extends Qn{constructor(e){super(e||"Unable to proceed because the client library of a payment method has thrown an unexpected error."),this.name="PaymentMethodFailedError",this.type="payment_method_client_invalid"}}class Xr extends nr{constructor(e){super(e,{message:"There is a problem processing your payment. Please try again later."}),this.name="PaymentMethodInvalidError",this.type="payment_method_invalid"}}var eo,to,no,io=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ro{constructor(e,t){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=window}initialize(e){var t;return io(this,void 0,void 0,function*(){const{methodId:n,bolt:i}=e,{onInit:r}=i||{};if(!n)throw new fi('Unable to proceed because "methodId" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n);if(!(null===(t=o.initializationData)||void 0===t?void 0:t.publishableKey))throw new ti(Xn.MissingPaymentMethod);const{developerConfig:a,publishableKey:s}=o.initializationData;if(yield this.boltScriptLoader.loadBoltClient(s,o.config.testMode,a),r&&"function"==typeof r){const e=this.getCustomerEmail();r(yield this.hasBoltAccount(e),e)}})}deinitialize(){return Promise.resolve()}signIn(e,t){return io(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return io(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){return io(this,void 0,void 0,function*(){const{continueWithCheckoutCallback:t=I,checkoutPaymentMethodExecuted:n,methodId:i}=e||{},r=this.getCustomerEmail();if(!i)throw new fi('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof t)throw new fi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(r)return this.openBoltCheckoutModalOrThrow(r,i,t,n);t()})}openBoltCheckoutModalOrThrow(e,t,n,i){var r;return io(this,void 0,void 0,function*(){const o=this.getBoltClientOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethod(t);try{if(null===(r=null==a?void 0:a.initializationData)||void 0===r?void 0:r.embeddedOneClickEnabled){const t=yield this.hasBoltAccount(e);if(t){const t={close:()=>{n()}};yield o.openCheckout(e,t)}else n();"function"==typeof i&&i({hasBoltAccount:t})}else n()}catch(e){if(function(e){return"string"==typeof e.message&&"string"==typeof e.type&&("string"==typeof e.subtype||!e.subtype)&&e instanceof Error}(e)&&"MissingDataError"!==e.name&&"NotInitializedError"!==e.name)throw new Qr(e.message);throw e}})}getBoltClientOrThrow(){const e=this.boltHostWindow.BoltCheckout;if(!e)throw new ri(ei.PaymentNotInitialized);return e}hasBoltAccount(e){return io(this,void 0,void 0,function*(){const t=this.getBoltClientOrThrow();try{return yield t.hasBoltAccount(e)}catch(e){throw new Xr}})}getCustomerEmail(){const e=this.paymentIntegrationService.getState(),t=e.getCustomer(),n=e.getBillingAddress();return(null==t?void 0:t.email)||(null==n?void 0:n.email)||""}}!function(e){e.SandboxMode="bolt_sandbox",e.StagingMode="bolt_staging",e.DevelopmentMode="bolt_development"}(eo||(eo={})),function(e){e.Small="small",e.Medium="medium",e.Large="large"}(to||(to={})),function(e){e.Pill="pill",e.Rect="rect"}(no||(no={}));var oo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ao{constructor(e,t=window){this.scriptLoader=e,this.boltHostWindow=t}loadBoltClient(e,t,n,i,r){return oo(this,void 0,void 0,function*(){if(this.boltHostWindow.BoltCheckout)return this.boltHostWindow.BoltCheckout;if(!e)throw new fi('Unable to initialize payment because "publishableKey" argument is not provided.');if(yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,n)}/connect-bigcommerce.js`,this.getScriptOptions("bolt-connect",e,i,r)),yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,n)}/track.js`,this.getScriptOptions("bolt-track",e)),!this.boltHostWindow.BoltCheckout)throw new mi;return this.boltHostWindow.BoltCheckout})}loadBoltEmbedded(e,t,n){return oo(this,void 0,void 0,function*(){if(yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,n)}/embed.js`,{async:!0,attributes:{id:"bolt-embedded"}}),!this.boltHostWindow.Bolt)throw new mi;return this.boltHostWindow.Bolt(e)})}getDomainURL(e,t){if(!e)return"connect.bolt.com";if(t)switch(t.developerMode){case eo.StagingMode:return"connect-staging.bolt.com";case eo.DevelopmentMode:return`connect.${t.developerDomain}`}return"connect-sandbox.bolt.com"}getScriptOptions(e,t,n,i){return{async:!0,attributes:Object.assign(Object.assign({id:e,"data-publishable-key":t},n&&{"data-shopping-cart-id":n}),i&&{"data-storefront-api-token":i})}}}const so=vi(e=>new ro(e,new ao(a())),[{id:"bolt"}]);class co extends fi{constructor(e){let t="Unable to submit payment for the order because the payload is invalid.";e&&(t=`${t} Make sure the following fields are provided correctly: ${e.join(", ")}.`),super(t),this.name="PaymentArgumentInvalidError"}}class lo extends Qn{constructor(e,t){super(t||"Unable to proceed because the payment form contains invalid data."),this.details=e,this.name="PaymentInvalidFormError",this.type="payment_invalid_form"}}let uo=null;const ho=["buttons","messages"];var po,mo,yo,go,vo,fo;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(po||(po={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(mo||(mo={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black",e.WHITE="white"}(yo||(yo={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(go||(go={})),function(e){e.PILL="pill",e.RECT="rect"}(vo||(vo={})),function(e){e.CART="cart",e.HOME="homepage",e.PAYMENT="payment",e.PRODUCT="product"}(fo||(fo={}));var So=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class _o{constructor(e,t,n){this.braintreeScriptLoader=e,this.braintreeHostWindow=t,this.overlay=n,this.dataCollectors={}}initialize(e,t){this.clientToken=e,this.threeDSecureOptions=t}getBraintreeFastlane(e,t,n){return So(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("axoEnv","sandbox"),window.localStorage.setItem("fastlaneEnv","sandbox")),!this.braintreeHostWindow.braintreeFastlane){const t=this.getClientTokenOrThrow(),i=yield this.getClient(),r=yield this.getSessionId(e),o=yield this.braintreeScriptLoader.loadFastlane(),a={root:{backgroundColorPrimary:"transparent"}};this.braintreeHostWindow.braintreeFastlane=yield o.create({authorization:t,client:i,deviceData:r,styles:n||a})}return this.braintreeHostWindow.braintreeFastlane})}getClient(){return So(this,void 0,void 0,function*(){if(!this.client){const e=this.getClientTokenOrThrow(),t=yield this.braintreeScriptLoader.loadClient();this.client=t.create({authorization:e})}return this.client})}getPaypal(){return this.braintreePaypal||(this.braintreePaypal=Promise.all([this.getClient(),this.braintreeScriptLoader.loadPaypal()]).then(([e,t])=>t.create({client:e}))),this.braintreePaypal}paypal(e){var{shouldSaveInstrument:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{var r;return i&&(null===(r=this.overlay)||void 0===r||r.show({onClick:()=>e.focusWindow()})),e.tokenize(Object.assign({enableShippingAddress:!0,flow:t?"vault":"checkout",useraction:"commit"},n))}).then(e=>{var t;return null===(t=this.overlay)||void 0===t||t.remove(),e}).catch(e=>{var t;throw null===(t=this.overlay)||void 0===t||t.remove(),e})}getPaypalCheckout(e,t,n){return So(this,void 0,void 0,function*(){const i=yield this.getClient(),r=yield this.braintreeScriptLoader.loadPaypalCheckout(),o={client:i};return this.paypalCheckout=yield r.create(o,(i,r)=>{var o;if(i)return n(i);const a=Object.assign(Object.assign({currency:e.currency},e.isCreditEnabled&&{"enable-funding":"paylater"}),{components:ho.toString(),intent:e.intent,commit:null===(o=e.commit)||void 0===o||o});this.braintreeHostWindow.paypal?t(r):function(e,t){return uo||(uo=new Promise((n,i)=>{e.loadPayPalSDK(t,t=>{t?(uo=null,i(t)):n(e)})})),uo}(r,a).then(()=>t(r))}),this.paypalCheckout})}getDataCollector(e){return So(this,void 0,void 0,function*(){const t=(null==e?void 0:e.paypal)?"paypal":"default";let n=this.dataCollectors[t];if(!n){try{const t=yield this.getClient(),i=yield this.braintreeScriptLoader.loadDataCollector(),r=Object.assign({client:t,kount:!0},e);n=yield i.create(r)}catch(e){if(!Ri(e)||"DATA_COLLECTOR_KOUNT_NOT_ENABLED"!==e.code)throw e;n={deviceData:void 0,teardown:()=>Promise.resolve()}}this.dataCollectors[t]=n}return n})}getBraintreeEnv(e=!1){return e?Fi.Sandbox:Fi.Production}mapToBraintreeShippingAddressOverride(e){return{recipientName:`${e.firstName} ${e.lastName}`,line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,postalCode:e.postalCode,countryCode:e.countryCode,phone:e.phone}}mapToLegacyShippingAddress(e){const{email:t,phone:n,shippingAddress:i}=e,r=(null==i?void 0:i.recipientName)||"",[o,a]=r.split(" ");return{email:t,first_name:o||"",last_name:a||"",phone_number:n,address_line_1:null==i?void 0:i.line1,address_line_2:null==i?void 0:i.line2,city:null==i?void 0:i.city,state:null==i?void 0:i.state,country_code:null==i?void 0:i.countryCode,postal_code:null==i?void 0:i.postalCode}}mapToLegacyBillingAddress(e){const{billingAddress:t,email:n,firstName:i,lastName:r,phone:o,shippingAddress:a}=e,s=t||a;return{email:n,first_name:i,last_name:r,phone_number:o,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}}removeElement(e){const t=e&&document.getElementById(e);t&&t.remove()}getSessionId(e){return So(this,void 0,void 0,function*(){const{deviceData:t}=yield this.getDataCollector({riskCorrelationId:e});return t})}teardown(){return So(this,void 0,void 0,function*(){yield this.teardownModule(this.dataCollectors.default),yield this.teardownModule(this.dataCollectors.paypal),this.dataCollectors={},yield this.teardownModule(this.paypalCheckout),this.paypalCheckout=void 0})}get3DS(){return So(this,void 0,void 0,function*(){return this.threeDS||(this.threeDS=Promise.all([this.getClient(),this.braintreeScriptLoader.load3DS()]).then(([e,t])=>t.create({client:e,version:2}))),this.threeDS})}getVenmoCheckout(e){return So(this,void 0,void 0,function*(){if(!this.venmoCheckout){const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadVenmoCheckout(),i=Object.assign({client:t,allowDesktop:!0,paymentMethodUsage:"multi_use"},e||{});this.venmoCheckout=yield new Promise((e,t)=>{n.create(i,(n,i)=>n?t(n):i.isBrowserSupported()?void e(i):t(new Ai))})}return this.venmoCheckout})}verifyCard(e,t,n){return So(this,void 0,void 0,function*(){const i=yield this.tokenizeCard(e,t);return this.challenge3DSVerification(i,n)})}tokenizeCard(e,t){return So(this,void 0,void 0,function*(){const{paymentData:n}=e;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"object"==typeof t.ccExpiry&&null!==t.ccExpiry&&"string"==typeof t.ccNumber&&"string"==typeof t.ccName}(n))throw new co(["payment.paymentData"]);const i=this.getErrorsRequiredFields(n);if(!$(i))throw new lo(i);const r=this.mapToCreditCard(n,t),o=yield this.getClient(),{creditCards:a}=yield o.request(r);return{nonce:a[0].nonce,bin:a[0].details.bin}})}challenge3DSVerification(e,t){return So(this,void 0,void 0,function*(){const n=yield this.get3DS();return this.present3DSChallenge(n,t,e)})}teardownModule(e){return e?e.teardown():Promise.resolve()}getClientTokenOrThrow(){if(!this.clientToken)throw new ri(ei.PaymentNotInitialized);return this.clientToken}getErrorsRequiredFields(e){const{ccNumber:t,ccExpiry:n}=e,i={};return t||(i.ccNumber=[{message:"Credit card number is required",type:"required"}]),n||(i.ccExpiry=[{message:"Expiration date is required",type:"required"}]),i}mapToCreditCard(e,t){return{data:{creditCard:{cardholderName:e.ccName,number:e.ccNumber,cvv:e.ccCvv,expirationDate:`${e.ccExpiry.month}/${e.ccExpiry.year}`,options:{validate:!1},billingAddress:t&&{countryCodeAlpha2:t.countryCode,locality:t.city,countryName:t.country,postalCode:t.postalCode,streetAddress:t.address2?`${t.address1} ${t.address2}`:t.address1}}},endpoint:"payment_methods/credit_cards",method:"post"}}present3DSChallenge(e,t,n){const{nonce:i,bin:r}=n;if(!this.threeDSecureOptions||!i)throw new ri(ei.PaymentNotInitialized);const{addFrame:o,removeFrame:a,challengeRequested:s=!0,additionalInformation:d}=this.threeDSecureOptions,c=()=>So(this,void 0,void 0,function*(){const t=yield e.cancelVerifyCard();return u.cancel(new Wi),t}),l=t.toFixed(2),u=new En(e.verifyCard({addFrame:(e,t)=>{o&&o(e,t,c)},amount:Number(l),bin:r,challengeRequested:s,nonce:i,removeFrame:a,onLookupComplete:(e,t)=>{t()},collectDeviceData:!0,additionalInformation:d}));return u.promise}}var wo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Io{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return wo(this,void 0,void 0,function*(){const{braintreepaypal:t,methodId:n}=e,{container:i,onError:r}=t||{};if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.braintreepaypal.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(n),!o.clientToken)throw new ti(Xn.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(n),o=a.getPaymentMethodOrThrow(n)}const{clientToken:s,config:d,initializationData:c}=o,{paymentButtonStyles:l}=c||{},{checkoutTopButtonStyles:u}=l||{};if(!s||!c)throw new ti(Xn.MissingPaymentMethod);const h={currency:a.getCartOrThrow().currency.code,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{this.renderPayPalButton(e,t,n,Boolean(d.testMode),u)},e=>this.handleError(e,i,r))})}deinitialize(){return wo(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}signIn(e,t){return wo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return wo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderPayPalButton(e,t,n,i,r){const{container:o,onClick:a=ce}=t,{paypal:s}=this.braintreeHostWindow,d=null==s?void 0:s.FUNDING.PAYPAL;if(s&&d){const c=s.Buttons({env:this.braintreeIntegrationService.getBraintreeEnv(i),fundingSource:d,style:Object.assign(Object.assign({},r),{height:wr}),createOrder:()=>this.setupPayment(e,t,n),onApprove:i=>this.tokenizePayment(i,e,n,t),onClick:a});c.isEligible()&&c.render(`#${o}`)}else this.braintreeIntegrationService.removeElement(o)}setupPayment(e,t,n){var i;return wo(this,void 0,void 0,function*(){try{yield this.paymentIntegrationService.loadDefaultCheckout();const t=this.paymentIntegrationService.getState(),r=t.getCheckoutOrThrow().outstandingBalance,o=t.getCartOrThrow().currency.code,a=t.getCustomer(),s=t.getPaymentMethodOrThrow(n),d=null==a?void 0:a.addresses[0],c=d?this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(d):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:c,amount:r,currency:o,offerCredit:!1,intent:null===(i=s.initializationData)||void 0===i?void 0:i.intent})}catch(e){const{container:n,onError:i}=t;this.handleError(e,n,i)}})}tokenizePayment(e,t,n,i){return wo(this,void 0,void 0,function*(){try{const{deviceData:i}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),r=yield t.tokenizePayment(e),{details:o,nonce:a}=r,s=this.braintreeIntegrationService.mapToLegacyBillingAddress(o),d=this.braintreeIntegrationService.mapToLegacyShippingAddress(o);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:n,action:"set_external_checkout",nonce:a,device_data:i,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:n}=i;this.handleError(e,t,n)}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const Co=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t);return new Io(e,Ee(),i,t)},[{id:"braintreepaypal"}]);var bo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Po{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return bo(this,void 0,void 0,function*(){const{braintreepaypalcredit:t,methodId:n}=e,{container:i,onError:r}=t||{};if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(n),!o.clientToken)throw new ti(Xn.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(n),o=a.getPaymentMethodOrThrow(n)}const{clientToken:s,config:d,initializationData:c}=o,{paymentButtonStyles:l}=c||{},{checkoutTopButtonStyles:u}=l||{};if(!s||!c)throw new ti(Xn.MissingPaymentMethod);const h={currency:a.getCartOrThrow().currency.code,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{this.renderPayPalButton(e,t,n,Boolean(d.testMode),Object.assign(Object.assign({},u),{height:wr}))},e=>this.handleError(e,i,r))})}deinitialize(){return bo(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}signIn(e,t){return bo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return bo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderPayPalButton(e,t,n,i,r){const{container:o,onClick:a=ce}=t,{paypal:s}=this.braintreeHostWindow;let d=!1;s&&[s.FUNDING.PAYLATER,s.FUNDING.CREDIT].forEach(c=>{if(!d){const l=s.Buttons({env:i?"sandbox":"production",fundingSource:c,style:r,createOrder:()=>this.setupPayment(e,t,n),onApprove:i=>this.tokenizePayment(i,e,n,t),onClick:a});l.isEligible()&&(l.render(`#${o}`),d=!0)}}),s&&d||this.braintreeIntegrationService.removeElement(o)}setupPayment(e,t,n){var i;return bo(this,void 0,void 0,function*(){try{yield this.paymentIntegrationService.loadDefaultCheckout();const t=this.paymentIntegrationService.getState(),r=t.getCheckoutOrThrow().outstandingBalance,o=t.getCartOrThrow().currency.code,a=t.getCustomer(),s=t.getPaymentMethodOrThrow(n),d=null==a?void 0:a.addresses[0],c=d?this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(d):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:c,amount:r,currency:o,offerCredit:!0,intent:null===(i=s.initializationData)||void 0===i?void 0:i.intent})}catch(e){const{container:n,onError:i}=t;this.handleError(e,n,i)}})}tokenizePayment(e,t,n,i){return bo(this,void 0,void 0,function*(){try{const{deviceData:i}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),r=yield t.tokenizePayment(e),{details:o,nonce:a}=r,s=this.braintreeIntegrationService.mapToLegacyBillingAddress(o),d=this.braintreeIntegrationService.mapToLegacyShippingAddress(o);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:n,action:"set_external_checkout",nonce:a,device_data:i,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:n}=i;this.handleError(e,t,n)}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const Oo=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t);return new Po(e,Ee(),i,t)},[{id:"braintreepaypalcredit"}]);function Eo(e){return"string"!=typeof e}function Ao(e,t){if(t||e)return function(e){var t,n;const i={},r=ue(e.root,Eo),o=ue(e.input,Eo),a=ue(e.toggle,Eo),s=ue(null===(t=e.text)||void 0===t?void 0:t.body,Eo),d=ue(null===(n=e.text)||void 0===n?void 0:n.caption,Eo),c=e.branding;return Object.keys(r).length&&(i.root=r),Object.keys(o).length&&(i.input=o),Object.keys(a).length&&(i.toggle=a),Object.keys(s).length&&(i.text={},i.text.body=s),Object.keys(d).length&&(i.text=Object.assign({},i.text),i.text.caption=d),c&&(i.branding=c),i}(function(e,t){var n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,_,w,I,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(c=null==t?void 0:t.input)||void 0===c?void 0:c.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.focusBorderColor),backgroundColor:(null==e?void 0:e.fastlaneInputSettingsBackgroundColor)||(null===(u=null==t?void 0:t.input)||void 0===u?void 0:u.backgroundColor),borderWidth:(null==e?void 0:e.fastlaneInputSettingsBorderWidth)||(null===(h=null==t?void 0:t.input)||void 0===h?void 0:h.borderWidth),textColorBase:(null==e?void 0:e.fastlaneInputSettingsTextColorBase)||(null===(p=null==t?void 0:t.input)||void 0===p?void 0:p.textColorBase)},toggle:{colorPrimary:(null==e?void 0:e.fastlaneToggleSettingsColorPrimary)||(null===(m=null==t?void 0:t.toggle)||void 0===m?void 0:m.colorPrimary),colorSecondary:(null==e?void 0:e.fastlaneToggleSettingsColorSecondary)||(null===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(S=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===S?void 0:S.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(w=null===(_=null==t?void 0:t.text)||void 0===_?void 0:_.caption)||void 0===w?void 0:w.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(I=null==t?void 0:t.text)||void 0===I?void 0:I.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var To=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ko{constructor(e,t){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.isAcceleratedCheckoutEnabled=!1}initialize({methodId:e,braintreefastlane:t}){var n;return To(this,void 0,void 0,function*(){if(!e)throw new fi('Unable to proceed because "methodId" argument is not provided.');const i=yield this.getValidPaymentMethodOrThrow(e),{isAcceleratedCheckoutEnabled:r,isFastlaneStylingEnabled:o}=i.initializationData||{},a=o?null===(n=i.initializationData)||void 0===n?void 0:n.fastlaneStyles:void 0;this.isAcceleratedCheckoutEnabled=!!r;try{if(this.isAcceleratedCheckoutEnabled){const e=Ao(a,null==t?void 0:t.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(i.id,e)}}catch(e){}return Promise.resolve()})}deinitialize(){return To(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return To(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return To(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return To(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:n}=e||{};if("function"!=typeof n)throw new fi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');const i=this.paymentIntegrationService.getState().getCustomerOrThrow();if(this.isAcceleratedCheckoutEnabled&&i.isGuest){const e=yield this.shouldRunAuthenticationFlow();t&&"function"==typeof t&&t(),e&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow(void 0,!0))}n()})}shouldRunAuthenticationFlow(){var e;return To(this,void 0,void 0,function*(){const t="braintreeacceleratedcheckout";try{yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t);return(null===(e=n.initializationData)||void 0===e?void 0:e.shouldRunAcceleratedCheckout)||!1}catch(e){return!1}})}getValidPaymentMethodOrThrow(e){return To(this,void 0,void 0,function*(){let t=e;try{yield this.paymentIntegrationService.loadPaymentMethod(t)}catch(n){t="braintree"===e?"braintreeacceleratedcheckout":"braintree",yield this.paymentIntegrationService.loadPaymentMethod(t)}return this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)})}}var Do=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Mo{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}getDeviceSessionId(){return Do(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getCart();return this.braintreeIntegrationService.getSessionId(null==e?void 0:e.id)})}initializeBraintreeFastlaneOrThrow(e,t){return Do(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getCart(),{clientToken:r,config:o}=n.getPaymentMethodOrThrow(e);if(!r)throw new ti(Xn.MissingPaymentMethod);this.methodId=e,this.braintreeIntegrationService.initialize(r),this.braintreeFastlane=yield this.braintreeIntegrationService.getBraintreeFastlane(null==i?void 0:i.id,o.testMode,t)})}getBraintreeFastlaneOrThrow(){if(!this.braintreeFastlane)throw new mi;return this.braintreeFastlane}getBraintreeFastlaneComponentOrThrow(){return this.getBraintreeFastlaneOrThrow().FastlaneCardComponent}runPayPalAuthenticationFlowOrThrow(e,t){var n;return Do(this,void 0,void 0,function*(){try{const i=this.getMethodIdOrThrow(),r=this.getBraintreeFastlaneOrThrow(),{lookupCustomerByEmail:o,triggerAuthenticationFlow:a}=r.identity,s=this.paymentIntegrationService.getState(),d=s.getCartOrThrow(),c=s.getCustomer(),l=s.getBillingAddress(),{isFastlaneShippingOptionAutoSelectEnabled:u}=s.getPaymentMethodOrThrow(i).initializationData||{},h=e||(null==c?void 0:c.email)||(null==l?void 0:l.email)||"",{customerContextId:p}=yield o(h);if(!p)return yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:Mi.UNRECOGNIZED,addresses:[],instruments:[]}),void this.saveSessionIdToCookies(d.id);const{authenticationState:m,profileData:y}=yield a(p),g=(null===(n=null==y?void 0:y.shippingAddress)||void 0===n?void 0:n.phoneNumber)||"";if(m===Mi.CANCELED)return yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:[],instruments:[]}),void this.removeSessionIdFromCookies();const v=this.mapPayPalToBcAddress([y.shippingAddress],[g])||[],f=this.getPayPalBillingAddresses(y),S=f?this.mapPayPalToBcAddress([f],[g]):[],_=y.card?this.mapPayPalToBcInstrument(i,[y.card]):[],w=this.mergeShippingAndBillingAddresses(v,S);if(this.saveSessionIdToCookies(d.id),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:w,instruments:_}),S.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateBillingAddress(S[0])),S.length>0&&d.lineItems.digitalItems.length>0&&0===d.lineItems.physicalItems.length){const{firstName:e,lastName:t}=w[0],n=Object.assign(Object.assign({},S[0]),{firstName:e,lastName:t});yield this.paymentIntegrationService.updateBillingAddress(n)}v.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateShippingAddress(v[0]),t&&u&&(yield this.setShippingOption()))}catch(e){}})}getSessionIdFromCookies(){return Fr.get("bc-fastlane-sessionId")||""}saveSessionIdToCookies(e){const t=new Date;t.setDate(t.getDate()+14),Fr.set("bc-fastlane-sessionId",e,{expires:t,secure:!0})}removeSessionIdFromCookies(){Fr.remove("bc-fastlane-sessionId")}mapPayPalToBcInstrument(e,t){if(t)return t.map(t=>{const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a,binDetails:s}=i.card,[d,c]=o.split("-");return{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:c,expiryYear:d,iin:(null==s?void 0:s.bin)||"",last4:a,method:e,provider:e,trustedShippingAddress:!1,type:"card",untrustedShippingCardVerificationMode:Pr.PAN}})}mapPayPalToBcAddress(e,t){if(!e)return[];const n=this.paymentIntegrationService.getState().getCountries()||[],i=e=>{const t=n.find(t=>t.code===e);return(null==t?void 0:t.name)||""};return e.map(e=>({id:Date.now(),type:"paypal-address",firstName:e.firstName||"",lastName:e.lastName||"",company:e.company||"",address1:e.streetAddress,address2:e.extendedAddress||"",city:e.locality,stateOrProvince:e.region,stateOrProvinceCode:e.region,country:i(e.countryCodeAlpha2),countryCode:e.countryCodeAlpha2,postalCode:e.postalCode,phone:t&&t[0]||"",customFields:[]}))}getPayPalBillingAddresses(e){const{card:t,name:n}=e||{};if(!t)return;const{firstName:i,lastName:r}=t.paymentSource.card.billingAddress,{firstName:o,lastName:a}=n||{},{shippingAddress:s}=e||{},d=Object.assign(Object.assign({},t.paymentSource.card.billingAddress),{firstName:i||o,lastName:r||a});return s&&Y(this.normalizeAddress(d),this.normalizeAddress(s))?s:d}normalizeAddress(e){return le(e,["id"])}mergeShippingAndBillingAddresses(e,t){const n=t.filter(t=>!e.some(e=>Y(this.normalizeAddress(e),this.normalizeAddress(t))));return[...e,...n]}getMethodIdOrThrow(){if(!this.methodId)throw new fi('Unable to proceed because "methodId" argument is not provided.');return this.methodId}setShippingOption(){var e;return Do(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getConsignments()||[],n=(null===(e=t[0])||void 0===e?void 0:e.availableShippingOptions)||[],i=n.find(e=>e.isRecommended);if(i||n.length){const e=i||n[0];yield this.paymentIntegrationService.selectShippingOption(e.id)}})}}const zo=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t),r=new Mo(e,i);return new ko(e,r)},[{id:"braintreeacceleratedcheckout"},{id:"braintree"}]);var No=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class xo{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n,this.buttonClassName="visa-checkout-wrapper",this.onError=ce}initialize(e){return No(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:n}=e;if(!n)throw new fi('Unable to proceed because "methodId" argument is not provided.');if(!t)throw new fi('Unable to proceed because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState(),r=i.getCheckoutOrThrow(),{clientToken:o,config:a}=i.getPaymentMethodOrThrow(n),s=i.getStoreConfigOrThrow();if(!o)throw new ti(Xn.MissingPaymentMethod);this.braintreeSdk.initialize(o);const d=yield this.braintreeSdk.getBraintreeVisaCheckout(),c=yield this.braintreeSdk.getVisaCheckoutSdk(a.testMode),{container:l,onError:u}=t;this.onError=u||ce;const h=d.createInitOptions({paymentRequest:{currencyCode:s.currency.code,subtotal:String(r.subtotal)},settings:{locale:s.storeProfile.storeLanguage,shipping:{collectShipping:!0}}}),p=this.createSignInButton(l,this.buttonClassName);yield c.init(h),c.on("payment.success",e=>this.tokenizePayment(d,e).then(()=>this.paymentIntegrationService.loadCheckout()).catch(e=>this.handleError(e))),c.on("payment.error",(e,t)=>this.handleError(t)),p.style.visibility="visible"})}deinitialize(){return No(this,void 0,void 0,function*(){yield this.braintreeSdk.deinitialize()})}signIn(){throw new Si('In order to sign in via VisaCheckout, the shopper must click on "Visa Checkout" button.')}signOut(e){return No(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}tokenizePayment(e,t){return No(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const n=this.paymentIntegrationService.getState(),i=n.getShippingAddress(),r=n.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(i),billingAddress:a=this.mapToVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}postForm(e,t){const{userData:n,billingAddress:i,shippingAddress:r,details:o}=e,{userEmail:a}=n,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,i)),shipping_address:JSON.stringify(this.getAddress(a,r))})}mapToVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}createSignInButton(e,t){const n=document.querySelector(`#${e}`);if(!n)throw new Error("Unable to proceed because the provided container ID is not valid.");return this.insertVisaCheckoutButton(n,t)}insertVisaCheckoutButton(e,t){const n=document.createElement("div");return n.style.display="flex",n.style.flexDirection="column",n.style.visibility="hidden",n.style.width="max-content",n.className=t,n.innerHTML='\n \n Tell Me More',e.appendChild(n),n}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const Ro=vi(e=>{const t=window,n=new Ei(e),i=new Ui(new Hi(a(),t,n));return new xo(e,Ee(),i)},[{id:"braintreevisacheckout"}]);class Fo{constructor(e){if(!e)throw new Error("Currency settings missing");const{decimalPlaces:t,symbolLocation:n,symbol:i,thousandsSeparator:r,decimalSeparator:o}=e;if("string"!=typeof n||"string"!=typeof i||"string"!=typeof r||"string"!=typeof o||"string"!=typeof t)throw new fi("Invalid currency settings provided");this._decimalPlaces=parseInt(t,10),this._symbolLocation=n,this._symbol=i,this._thousandsSeparator=r,this._decimalSeparator=o}format(e){if("number"!=typeof e)throw new fi("Invalid amount provided");const t=this._formatNumber(e),n=this._formatCurrency(t);return e<0?`-${n}`:n}_formatNumber(e){const t=Math.abs(e),[n,i=""]=this._toFixed(t,this._decimalPlaces).split("."),r=n.replace(/\B(?=(\d{3})+(?!\d))/g,this._thousandsSeparator);return this._decimalPlaces<1?r:[r,i].join(this._decimalSeparator)}_formatCurrency(e){return"left"===this._symbolLocation.toLowerCase()?`${this._symbol}${e}`:`${e}${this._symbol}`}_toFixed(e,t){return(+`${Math.round(+`${e}e${t}`)}e${-t}`).toFixed(t)}}let Lo=class{constructor(e){this._storeConfig=e,this._customerFormatter=new Fo(this._storeConfig.shopperCurrency),this._storeFormatter=new Fo(this._storeConfig.currency)}toCustomerCurrency(e){const t=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(e*t)}toStoreCurrency(e){return this._storeFormatter.format(e)}};Lo=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],Lo);const Bo=Lo,jo=(e,t)=>!!e&&(!!e.lineItems.physicalItems.some(e=>e.isShippingRequired)||!(!t||!e.lineItems.customItems)&&e.lineItems.customItems.length>0);function Uo(){if("undefined"==typeof window)return!1;if(function(e){return"ReactNativeWebView"in e}(window))return!0;const e=navigator.userAgent||navigator.vendor||(function(e){return"opera"in e}(window)?window.opera:""),t=/android.+; wv/i.test(e),n=/iPhone|iPod|iPad/i.test(e)&&/AppleWebKit/i.test(e)&&!/Safari/i.test(e);return t||n}var qo,Vo,Go,Ho,Wo,$o,Yo,Ko,Jo;function Zo(e){return e in $o}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(qo||(qo={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Vo||(Vo={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(Go||(Go={})),function(e){e.pill="pill",e.rect="rect"}(Ho||(Ho={})),function(e){e.ESTIMATED="ESTIMATED",e.FINAL="FINAL",e.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(Wo||(Wo={})),function(e){e.AMEX="AMEX",e.DISCOVER="DISCOVER",e.INTERAC="INTERAC",e.JCB="JCB",e.MC="MASTERCARD",e.VISA="VISA"}($o||($o={})),function(e){e.OFFER="OFFER",e.PAYMENT_AUTHORIZATION="PAYMENT_AUTHORIZATION",e.SHIPPING_ADDRESS="SHIPPING_ADDRESS",e.SHIPPING_OPTION="SHIPPING_OPTION"}(Yo||(Yo={})),function(e){e.OFFER_INVALID="OFFER_INVALID",e.PAYMENT_DATA_INVALID="PAYMENT_DATA_INVALID",e.SHIPPING_ADDRESS_INVALID="SHIPPING_ADDRESS_INVALID",e.SHIPPING_ADDRESS_UNSERVICEABLE="SHIPPING_ADDRESS_UNSERVICEABLE",e.SHIPPING_OPTION_INVALID="SHIPPING_OPTION_INVALID",e.OTHER_ERROR="OTHER_ERROR"}(Ko||(Ko={})),function(e){e.INITIALIZE="INITIALIZE",e.SHIPPING_OPTION="SHIPPING_OPTION",e.SHIPPING_ADDRESS="SHIPPING_ADDRESS",e.OFFER="OFFER"}(Jo||(Jo={}));var Qo,Xo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ea{constructor(e,t){this._gatewayIdentifier=e,this._paymentIntegrationService=t,this._isBuyNowFlow=!1,this._shouldRequestShipping=!0,this._isWebViewExperimentOn=null}mapToShippingAddressRequestBody({shippingAddress:e}){if(!e)return;const{company:t="",phone:n=""}=this._paymentIntegrationService.getState().getShippingAddress()||{};return this._mapToAddressRequestBody(e,t,n)}mapToBillingAddressRequestBody(e){const{billingAddress:t}=e.paymentMethodData.info;if(!t)return;const{company:n="",phone:i="",email:r,customFields:o=[]}=this._paymentIntegrationService.getState().getBillingAddress()||{};return Object.assign(Object.assign({},this._mapToAddressRequestBody(t,n,i,o)),{email:r||e.email})}mapToExternalCheckoutData(e){var t;const{paymentMethodData:{tokenizationData:{token:n},info:{cardNetwork:i,cardDetails:r}}}=e;if(!n)throw new ti(Xn.MissingPaymentToken);return Promise.resolve(Object.assign({nonce:n,card_information:{type:i,number:r}},this._isBuyNowFlow&&{cart_id:null===(t=this._paymentIntegrationService.getState().getCart())||void 0===t?void 0:t.id}))}getRequiredData(){var e;return Xo(this,void 0,void 0,function*(){const t={emailRequired:!0};if(!this._isShippingAddressRequired())return t;const n=yield this._paymentIntegrationService.loadShippingCountries(),i=null===(e=n.getShippingCountries())||void 0===e?void 0:e.map(e=>e.code);return Object.assign(Object.assign({},t),{shippingAddressRequired:!0,shippingAddressParameters:Object.assign({phoneNumberRequired:!0},i&&{allowedCountryCodes:i}),shippingOptionRequired:!0})})}getCallbackIntents(){return this._isShippingAddressRequired()?[Yo.OFFER,Yo.SHIPPING_ADDRESS,Yo.SHIPPING_OPTION]:[Yo.OFFER]}getCallbackTriggers(){return{availableTriggers:[Jo.INITIALIZE,Jo.SHIPPING_ADDRESS,Jo.SHIPPING_OPTION,Jo.OFFER],initializationTrigger:[Jo.INITIALIZE],addressChangeTriggers:[Jo.INITIALIZE,Jo.SHIPPING_ADDRESS],shippingOptionsChangeTriggers:[Jo.SHIPPING_OPTION],offerChangeTriggers:[Jo.OFFER]}}getNonce(e){var t;const n=null===(t=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.nonce;if(!n)throw new ti(Xn.MissingPaymentToken);return Promise.resolve(n)}extraPaymentData(){return Promise.resolve(void 0)}getMerchantInfo(){const{googleMerchantName:e,googleMerchantId:t,platformToken:n}=this.getGooglePayInitializationData();return{merchantName:e,merchantId:t,authJwt:n}}getTransactionInfo(){let e;const{getCartOrThrow:t}=this._paymentIntegrationService.getState();e=this._isBuyNowFlow?this._getCurrencyCodeOrThrow():t().currency.code;const n=this.getGooglePayInitializationData().storeCountry;if(this.isWebViewWithRestrictions()){const t=this.getTotalPrice();return Object.assign(Object.assign({},n&&{countryCode:n}),{currencyCode:e,totalPrice:t,totalPriceStatus:Wo.ESTIMATED})}return Object.assign(Object.assign({},n&&{countryCode:n}),{currencyCode:e,totalPriceStatus:Wo.ESTIMATED,totalPrice:"0"})}isWebViewWithRestrictions(){return null!==this._isWebViewExperimentOn?this._isWebViewExperimentOn&&Uo():Uo()}setIsWebViewExperimentOn(e){this._isWebViewExperimentOn=e}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData().gatewayMerchantId;if(!e)throw new fi("Unable to proceed, gatewayMerchantId is missing.");return{gateway:this._gatewayIdentifier,gatewayMerchantId:e}}getCardParameters(){return{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:this.getPaymentMethod().supportedCards.filter(Zo).map(e=>$o[e]),billingAddressRequired:!0,billingAddressParameters:{format:"FULL",phoneNumberRequired:!0}}}initialize(e,t,n){return this._getPaymentMethodFn=e,this._isBuyNowFlow=Boolean(t),this._currencyCode=n,this._isBuyNowFlow&&this._getCurrencyCodeOrThrow(),Promise.resolve()}handleShippingAddressChange(e){var t,n,i,r;return Xo(this,void 0,void 0,function*(){e&&(e.name=e.name||"",e.address1=e.address1||"");const o=this.mapToShippingAddressRequestBody({shippingAddress:e});o&&(yield this._paymentIntegrationService.updateShippingAddress(o));const a=this._paymentIntegrationService.getState(),s=a.getConsignments();if(!(null==s?void 0:s[0]))return;const d=s[0],c=a.getStoreConfigOrThrow();this._currencyService||(this._currencyService=new Bo(c));const l=(d.availableShippingOptions||[]).map(this._getGooglePayShippingOption.bind(this)),u=null===(t=d.availableShippingOptions)||void 0===t?void 0:t.find(e=>e.isRecommended);if(l.length){const e=(null===(n=d.selectedShippingOption)||void 0===n?void 0:n.id)||(null==u?void 0:u.id)||(null===(i=l[0])||void 0===i?void 0:i.id);return!(null===(r=d.selectedShippingOption)||void 0===r?void 0:r.id)&&l[0]&&(yield this.handleShippingOptionChange((null==u?void 0:u.id)||l[0].id)),{defaultSelectedOptionId:e,shippingOptions:l}}})}handleShippingOptionChange(e){return Xo(this,void 0,void 0,function*(){if("shipping_option_unselected"!==e)return this._paymentIntegrationService.selectShippingOption(e)})}getTotalPrice(){const{getCheckoutOrThrow:e,getCartOrThrow:t,getStoreConfigOrThrow:n}=this._paymentIntegrationService.getState(),{decimalPlaces:i}=t().currency,r=Ci(n().checkoutSettings.features,"PI-5075.google_pay_round_total_price_to_max_2_decimal_places")?Math.min(i,2):i;return ge(e().outstandingBalance,r).toFixed(r)}handleCoupons(e){return Xo(this,void 0,void 0,function*(){const{redemptionCodes:t=[]}=e,{offers:n}=this.getAppliedCoupons()||{};let i;return yield t.reduce((e,t)=>Xo(this,void 0,void 0,function*(){if(yield e,(n||[]).some(({redemptionCode:e})=>e===t))return;const r=yield this.applyCoupon(t);r&&(i=r)}),Promise.resolve()),yield(n||[]).reduce((e,n)=>Xo(this,void 0,void 0,function*(){yield e,t.includes(n.redemptionCode)||(yield this._paymentIntegrationService.removeCoupon(n.redemptionCode))}),Promise.resolve()),{newOfferInfo:this.getAppliedCoupons(),error:i}})}getAppliedCoupons(){const e=this._paymentIntegrationService.getState(),{coupons:t}=e.getCheckout()||{};return{offers:(t||[]).map(e=>{const{displayName:t,code:n}=e;return{redemptionCode:n,description:t}})}}applyCoupon(e){return Xo(this,void 0,void 0,function*(){let t;try{yield this._paymentIntegrationService.applyCoupon(e)}catch(e){return e instanceof Error&&(t={reason:Ko.OFFER_INVALID,message:e.message,intent:Jo.OFFER}),t}})}setShouldRequestShipping(e){this._shouldRequestShipping=e}getGooglePayInitializationData(){return ii(this.getPaymentMethod().initializationData,()=>new fi("Missing initialization data."))}getPaymentMethod(){return ii(this._getPaymentMethodFn,()=>new ri(ei.PaymentNotInitialized))()}getGatewayIdentifier(){return this._gatewayIdentifier}setGatewayIdentifier(e){this._gatewayIdentifier=e||this.getGatewayIdentifier()}_isShippingAddressRequired(){const{getCartOrThrow:e,getStoreConfigOrThrow:t,getShippingAddress:n}=this._paymentIntegrationService.getState(),i=t();let r;return r=Ci(i.checkoutSettings.features,"PI-4290.google_pay_require_shipping_address")?this._shouldRequestShipping:void 0===n(),r&&jo(e(),i)}_mapToAddressRequestBody(e,t,n,i){const{name:r,address1:o,address2:a,address3:s,locality:d,administrativeArea:c,countryCode:l,postalCode:u,phoneNumber:h}=e,[p,m]=this._getFirstAndLastName(r);return{firstName:p,lastName:m,company:t,address1:o,address2:`${a} ${s}`.trim(),city:d||c,stateOrProvince:c,stateOrProvinceCode:c,countryCode:l,postalCode:u,phone:h||n,customFields:i||[]}}_getFirstAndLastName(e){const t=e.split(" ");return 1===t.length?[e,""]:[t.slice(0,-1).join(" "),t[t.length-1]]}_getCurrencyCodeOrThrow(){return ii(this._currencyCode,()=>new fi('Unable to initialize payment because "options.currencyCode" argument is not provided.'))}_getGooglePayShippingOption({id:e,cost:t,description:n,additionalDescription:i}){var r;return{id:e,label:`${(null===(r=this._currencyService)||void 0===r?void 0:r.toCustomerCurrency(t))||t} ${n}`,description:i}}}function ta(e){return"object"==typeof e&&null!==e&&"statusCode"in e}function na(e){return Object.values(Qo).includes(e)}!function(e){e.ADYEN_V2="googlepayadyenv2",e.ADYEN_V3="googlepayadyenv3",e.AUTHORIZE_NET="googlepayauthorizenet",e.BNZ="googlepaybnz",e.BRAINTREE="googlepaybraintree",e.PAYPAL_COMMERCE="googlepaypaypalcommerce",e.BIGCOMMERCE_PAYMENTS="googlepay_bigcommerce_payments",e.CHECKOUT_COM="googlepaycheckoutcom",e.CYBERSOURCE_V2="googlepaycybersourcev2",e.ORBITAL="googlepayorbital",e.STRIPE="googlepaystripe",e.STRIPE_UPE="googlepaystripeupe",e.STRIPE_OCS="googlepaystripeocs",e.WORLDPAY_ACCESS="googlepayworldpayaccess",e.TD_ONLINE_MART="googlepaytdonlinemart"}(Qo||(Qo={}));var ia=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ra{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t}initialize(e){var t,n;return ia(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId)||!na(e.methodId))throw new fi('Unable to proceed because "methodId" is not a valid key.');this._methodId=e.methodId;const i=e[this._getMethodId()];if(!i)throw new fi("Unable to proceed without valid options.");let r,o=this._paymentIntegrationService.getState();try{r=o.getPaymentMethodOrThrow(this._getMethodId())}catch(e){o=yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodId()),r=o.getPaymentMethodOrThrow(this._getMethodId())}try{this._googlePayPaymentProcessor.setIsWebViewExperimentOn(!!(null===(t=r.initializationData)||void 0===t?void 0:t.isWebViewExperimentOn)),yield this._googlePayPaymentProcessor.initialize(()=>r,this._getGooglePayClientOptions(null===(n=r.initializationData)||void 0===n?void 0:n.storeCountry))}catch(e){return}this._addPaymentButton(i)})}signIn(){return Promise.reject(new Si('In order to sign in via Google Pay, the shopper must click on "Google Pay" button.'))}signOut(){var e;return ia(this,void 0,void 0,function*(){const t=null===(e=this._paymentIntegrationService.getState().getPaymentId())||void 0===e?void 0:e.providerId;t&&(yield this._googlePayPaymentProcessor.signOut(t))})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}deinitialize(){var e;return null===(e=this._paymentButton)||void 0===e||e.remove(),this._paymentButton=void 0,this._methodId=void 0,Promise.resolve()}_getGooglePayClientOptions(e){return this._googlePayPaymentProcessor.isWebViewWithRestrictions()?{}:{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:t,shippingAddress:n,shippingOptionData:i,offerData:r})=>ia(this,void 0,void 0,function*(){const{availableTriggers:o,addressChangeTriggers:a,shippingOptionsChangeTriggers:s,offerChangeTriggers:d}=this._googlePayPaymentProcessor.getCallbackTriggers();if(!o.includes(t))return;const c=a.includes(t)?yield this._googlePayPaymentProcessor.handleShippingAddressChange(n):void 0;s.includes(t)&&(yield this._googlePayPaymentProcessor.handleShippingOptionChange(i.id));const{newOfferInfo:l,error:u}=d.includes(t)?yield this._googlePayPaymentProcessor.handleCoupons(r):{},h=u;yield this._paymentIntegrationService.loadCheckout();const p=this._googlePayPaymentProcessor.getTotalPrice(),{code:m}=this._paymentIntegrationService.getState().getCartOrThrow().currency;return Object.assign(Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},e&&{countryCode:e}),{currencyCode:m,totalPriceStatus:Wo.FINAL,totalPrice:p})},c&&{newShippingOptionParameters:c}),l&&{newOfferInfo:l}),h&&{error:h})})}}}_addPaymentButton({container:e,buttonColor:t,buttonType:n,onClick:i,onError:r}){var o;this._paymentButton=null!==(o=this._paymentButton)&&void 0!==o?o:this._googlePayPaymentProcessor.addPaymentButton(e,{buttonColor:null!=t?t:"default",buttonType:null!=n?n:"plain",onClick:this._handleClick(r,i)})}_handleClick(e,t){return n=>ia(this,void 0,void 0,function*(){n.preventDefault(),t&&"function"==typeof t&&t();try{yield this._googlePayPaymentProcessor.initializeWidget(),yield this._interactWithPaymentSheet()}catch(t){let n=t;if(ta(t)){if("CANCELED"===t.statusCode)throw new Wi;n=new Qr(JSON.stringify(t))}throw null==e||e(new Qr("An error occurred while requesting your Google Pay payment details.")),n}})}_interactWithPaymentSheet(){return ia(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet(),t=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e),n=this._googlePayPaymentProcessor.mapToShippingAddressRequestBody(e),i="/embedded-checkout"===window.location.pathname?this._paymentIntegrationService.getState().getStoreConfigOrThrow().links.siteLink:void 0;t&&(yield this._paymentIntegrationService.updateBillingAddress(t)),n&&(yield this._paymentIntegrationService.updateShippingAddress(n)),yield this._googlePayPaymentProcessor.setExternalCheckoutForm(this._getMethodId(),e,i)})}_getMethodId(){return ii(this._methodId,()=>new ri(ei.PaymentNotInitialized))}}var oa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class aa{constructor(e,t,n,i){this._scriptLoader=e,this._gateway=t,this._requestSender=n,this._formPoster=i,this._baseRequest={apiVersion:2,apiVersionMinor:0}}initialize(e,t,n,i){return oa(this,void 0,void 0,function*(){this._paymentsClient=yield this._scriptLoader.getGooglePaymentsClient(e().config.testMode,t),yield this._gateway.initialize(e,n,i),this._buildButtonPayloads()})}initializeWidget(){return oa(this,void 0,void 0,function*(){yield this._buildWidgetPayloads(),yield this._determineReadinessToPay(),this._prefetchGooglePaymentData()})}getNonce(e){return this._gateway.getNonce(e)}extraPaymentData(){return oa(this,void 0,void 0,function*(){return this._gateway.extraPaymentData()})}addPaymentButton(e,t){const n=document.querySelector(`#${e}`);if(!n)return;const i=this._getPaymentsClient().createButton(Object.assign(Object.assign({},t),{allowedPaymentMethods:[this._getBaseCardPaymentMethod()]}));return n.appendChild(i)}showPaymentSheet(){return oa(this,void 0,void 0,function*(){const e=this._getPaymentDataRequest();return this._getPaymentsClient().loadPaymentData(e)})}setExternalCheckoutXhr(e,t){return oa(this,void 0,void 0,function*(){return this._setExternalCheckout(e,t)})}setExternalCheckoutForm(e,t,n){return oa(this,void 0,void 0,function*(){return this._setExternalCheckout(e,t,!0,n)})}mapToBillingAddressRequestBody(e){return this._gateway.mapToBillingAddressRequestBody(e)}mapToShippingAddressRequestBody(e){return this._gateway.mapToShippingAddressRequestBody(e)}processAdditionalAction(e,t){return"processAdditionalAction"in this._gateway?this._gateway.processAdditionalAction(e,t):Promise.reject(e)}signOut(e){return oa(this,void 0,void 0,function*(){yield this._requestSender.get(`/remote-checkout/${e}/signout`)})}getCallbackTriggers(){return this._gateway.getCallbackTriggers()}setShouldRequestShipping(e){return this._gateway.setShouldRequestShipping(e)}handleShippingAddressChange(e){return oa(this,void 0,void 0,function*(){return this._gateway.handleShippingAddressChange(e)})}handleShippingOptionChange(e){return oa(this,void 0,void 0,function*(){yield this._gateway.handleShippingOptionChange(e)})}handleCoupons(e){return oa(this,void 0,void 0,function*(){return this._gateway.handleCoupons(e)})}getTotalPrice(){return this._gateway.getTotalPrice()}_setExternalCheckout(e,t,n=!1,i){return oa(this,void 0,void 0,function*(){const r="/checkout.php",o=Object.assign({action:"set_external_checkout",provider:e},yield this._gateway.mapToExternalCheckoutData(t));if(n)return new Promise(e=>{this._formPoster.postForm(i?`${i}/checkout`:r,Object.assign(Object.assign({},o),{card_information:JSON.stringify(o.card_information)}),e)});yield this._requestSender.post(r,{headers:Object.assign({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded"},yr),body:o})})}isWebViewWithRestrictions(){return this._gateway.isWebViewWithRestrictions()}setIsWebViewExperimentOn(e){return this._gateway.setIsWebViewExperimentOn(e)}_prefetchGooglePaymentData(){const e=this._getPaymentDataRequest();e.transactionInfo=this._gateway.getTransactionInfo(),this._getPaymentsClient().prefetchPaymentData(e)}_determineReadinessToPay(){return oa(this,void 0,void 0,function*(){try{const{result:e}=yield this._getPaymentsClient().isReadyToPay(this._getIsReadyToPayRequest());if(!1===e)throw new Qr("Google Pay is not supported by the current device and browser, please try another payment method.")}catch(e){if(e instanceof Qr)throw e;throw new Qr}})}_buildButtonPayloads(){this._baseCardPaymentMethod={type:"CARD",parameters:this._gateway.getCardParameters()}}_buildWidgetPayloads(){return oa(this,void 0,void 0,function*(){const e=this._getBaseCardPaymentMethod();this._cardPaymentMethod=Object.assign(Object.assign({},e),{tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:yield this._gateway.getPaymentGatewayParameters()}});const t=this._gateway.isWebViewWithRestrictions()?{shippingOptionRequired:!1}:{callbackIntents:this._gateway.getCallbackIntents(),offerInfo:this._gateway.getAppliedCoupons()};this._paymentDataRequest=Object.assign(Object.assign(Object.assign(Object.assign({},this._baseRequest),{allowedPaymentMethods:[this._cardPaymentMethod],transactionInfo:this._gateway.getTransactionInfo(),merchantInfo:this._gateway.getMerchantInfo()}),yield this._gateway.getRequiredData()),t),this._isReadyToPayRequest=Object.assign(Object.assign({},this._baseRequest),{allowedPaymentMethods:[e]})})}_getBaseCardPaymentMethod(){return this._getOrThrow(this._baseCardPaymentMethod)}_getPaymentDataRequest(){return this._getOrThrow(this._paymentDataRequest)}_getIsReadyToPayRequest(){return this._getOrThrow(this._isReadyToPayRequest)}_getPaymentsClient(){return this._getOrThrow(this._paymentsClient)}_getOrThrow(e){return ii(e,()=>new ri(ei.PaymentNotInitialized))}}class sa{constructor(e){this._scriptLoader=e,this._window=window}getGooglePaymentsClient(e=!1,t){return n=this,i=void 0,o=function*(){if(yield this._scriptLoader.loadScript("https://pay.google.com/gp/p/js/pay.js"),!this._window.google)throw new mi;return void 0===this._paymentsClient&&(this._paymentsClient=new this._window.google.payments.api.PaymentsClient(Object.assign({environment:e?"TEST":"PRODUCTION"},null!=t?t:{}))),this._paymentsClient},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}function da(){return new sa(a())}const ca=vi(e=>{const t=n();return new ra(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv2"}]),la=vi(e=>{const t=n();return new ra(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv3"}]);class ua extends ea{constructor(e){super("authorizenet",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();return function(e){if(!function(e){return"paymentGatewayId"in e}(e))throw new ti(Xn.MissingPaymentMethod)}(e),{gateway:this.getGatewayIdentifier(),gatewayMerchantId:e.paymentGatewayId}}}const ha=vi(e=>new ra(e,new aa(da(),new ua(e),n(),Ee())),[{id:"googlepayauthorizenet"}]),pa=e=>"object"==typeof e&&null!==e&&"body"in e;function ma(e){if(!function(e){return"checkoutcomkey"in e}(e))throw new ti(Xn.MissingPaymentMethod)}var ya=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ga extends ea{constructor(e,t){super("checkoutltd",e),this._requestSender=t}processAdditionalAction(e){return new Promise((t,n)=>{if(pa(e)&&function(e){var t;if("object"!=typeof e||null===e)return!1;const n=e;return"string"==typeof(null===(t=n.three_ds_result)||void 0===t?void 0:t.acs_url)&&"string"==typeof n.three_ds_result.code}(e.body)&&"three_d_secure_required"===e.body.three_ds_result.code)return window.location.assign(e.body.three_ds_result.acs_url);n(e)})}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ya(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);let i;try{i=JSON.parse(n.nonce)}catch(e){throw new fi("Unable to parse response from Google Pay.")}return function(e){if(!function(e){return"object"==typeof e&&null!==e&&"protocolVersion"in e&&"signature"in e&&"signedMessage"in e}(e))throw new ti(Xn.MissingPaymentToken)}(i),n.nonce=yield this._tokenize(i),n})}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();return ma(e),{gateway:this.getGatewayIdentifier(),gatewayMerchantId:e.checkoutcomkey}}_tokenize(e){return ya(this,void 0,void 0,function*(){const t=this.getPaymentMethod().config.testMode?"https://api.sandbox.checkout.com/tokens":"https://api.checkout.com/tokens",n=this.getGooglePayInitializationData();ma(n);const{body:i}=yield this._requestSender.post(t,{credentials:!1,body:{type:"googlepay",token_data:e},headers:{Authorization:n.checkoutcomkey,"Content-Type":mr.Json,"X-XSRF-TOKEN":null}});return i.token})}}const va=vi(e=>{const t=n();return new ra(e,new aa(da(),new ga(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]);class fa extends ea{constructor(e){super("cybersource",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const Sa=vi(e=>new ra(e,new aa(da(),new fa(e),n(),Ee())),[{id:"googlepaycybersourcev2"}]),_a=vi(e=>new ra(e,new aa(da(),new fa(e),n(),Ee())),[{id:"googlepaybnz"}]);class wa extends ea{constructor(e){super("chase",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const Ia=vi(e=>new ra(e,new aa(da(),new wa(e),n(),Ee())),[{id:"googlepayorbital"}]);var Ca,ba,Pa,Oa,Ea,Aa,Ta,ka,Da,Ma,za,Na;!function(e){e.SHIPPING="shipping",e.BILLING="billing"}(Ca||(Ca={})),function(e){e.SPLIT="split",e.FULL="full",e.ORGANIZATION="organization"}(ba||(ba={})),function(e){e.Open="open",e.Expired="expired",e.Complete="complete"}(Pa||(Pa={})),function(e){e.Paid="paid",e.UnPaid="unpaid",e.NoPaymentRequired="no_payment_required"}(Oa||(Oa={})),function(e){e.SUCCESS="success",e.ERROR="error"}(Ea||(Ea={})),function(e){e.CreditCard="card",e.ACH="us_bank_account",e.Link="link",e.EPS="eps",e.GRABPAY="grabpay",e.BANCONTACT="bancontact",e.IDEAL="ideal",e.ALIPAY="alipay",e.KLARNA="klarna",e.OCS="optimized_checkout",e.CHECKOUT_SESSION="checkout_session"}(Aa||(Aa={})),function(e){e.NEVER="never",e.AUTO="auto",e.ALWAYS="always",e.PAYMENT="payment",e.IF_REQUIRED="if_required"}(Ta||(Ta={})),function(e){e.V3="v3",e.ACACIA="acacia",e.BASIL="basil",e.CLOVER="clover"}(ka||(ka={})),function(e){e.PAYMENT="payment",e.AUTHENTICATION="linkAuthentication",e.SHIPPING="address",e.EXPRESS_CHECKOUT="expressCheckout"}(Da||(Da={})),function(e){e.REQUIRES_PAYMENT_METHOD="requires_payment_method",e.REQUIRES_CONFIRMATION="requires_confirmation",e.REQUIRES_ACTION="requires_action",e.PROCESSING="processing",e.SUCCEEDED="succeeded",e.CANCELED="canceled"}(Ma||(Ma={})),function(e){e.CLICK="click",e.CHANGE="change",e.READY="ready",e.SHIPPING_ADDRESS_CHANGE="shippingaddresschange",e.SHIPPING_RATE_CHANGE="shippingratechange",e.CONFIRM="confirm",e.CANCEL="cancel",e.LOADER_START="loaderstart"}(za||(za={})),function(e){e.ON_SESSION="on_session",e.OFF_SESSION="off_session"}(Na||(Na={}));var xa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ra{constructor(e,t=window){this.scriptLoader=e,this.stripeWindow=t}getStripeClient(e,t,n,i,r){return xa(this,void 0,void 0,function*(){if(this.stripeWindow.bcStripeClient)return this.stripeWindow.bcStripeClient;const o=yield this.load(n),{stripePublishableKey:a,stripeConnectedAccount:s}=e,d=o(a,Object.assign(Object.assign(Object.assign(Object.assign({},s?{stripeAccount:s}:{}),t?{locale:t}:{}),i?{betas:i}:{}),r?{apiVersion:r}:{}));return Object.assign(this.stripeWindow,{bcStripeClient:d}),d})}getElements(e,t){return xa(this,void 0,void 0,function*(){let n=this.stripeWindow.bcStripeElements;return n?yield this.updateStripeElements(t):(n=e.elements(t),Object.assign(this.stripeWindow,{bcStripeElements:n})),n})}updateStripeElements(e){return xa(this,void 0,void 0,function*(){const t=this.stripeWindow.bcStripeElements;t&&(t.update(e),yield t.fetchUpdates())})}getStripeCheckout(e,t){return xa(this,void 0,void 0,function*(){let n=yield this.getStoredStripeCheckout(t);return n||(n=yield e.initCheckout(t),Object.assign(this.stripeWindow,{bcStripeCheckout:n})),n})}load(e){return xa(this,void 0,void 0,function*(){if(!this.stripeWindow.Stripe&&(yield this.scriptLoader.loadScript(this.getScriptUrl(e)),!this.stripeWindow.Stripe))throw new mi;return this.stripeWindow.Stripe})}getScriptUrl(e){return e&&e!==ka.V3?`https://js.stripe.com/${e}/stripe.js`:"https://js.stripe.com/v3/"}getStoredStripeCheckout(e){return xa(this,void 0,void 0,function*(){const t=this.stripeWindow.bcStripeCheckout;if(t)try{const{actions:n,error:i}=yield t.loadActions();if(i||!n)return void this.logErrorToConsole(i);const r=yield n.getSession(),o=e.clientSecret.split("_secret_")[0];if(r.id===o)return t}catch(e){return void this.logErrorToConsole(e)}})}logErrorToConsole(e){e?console.error(e):console.error("No stripe checkout actions available on loadActions().")}}const Fa=["payment_element_beta_2","alipay_pm_beta_1","link_default_integration_beta_1","shipping_address_element_beta_1","address_element_beta_1"],La="2020-03-02;alipay_beta=v1;link_beta=v1";function Ba(e){if(!function(e){return"stripeConnectedAccount"in e&&"stripePublishableKey"in e&&"stripeVersion"in e}(e))throw new ti(Xn.MissingPaymentMethod)}var ja=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ua extends ea{constructor(e,t){super("stripe",e),this.paymentIntegrationService=e,this.scriptLoader=t}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ja(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);let i;try{i=JSON.parse(n.nonce)}catch(e){throw new fi("Unable to parse response from Google Pay.")}return function(e){if(!function(e){return"object"==typeof e&&null!==e&&"id"in e}(e))throw new ti(Xn.MissingPaymentToken)}(i),n.nonce=i.id,n})}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();Ba(e);const{stripeVersion:t,stripePublishableKey:n,stripeConnectedAccount:i}=e;return{gateway:this.getGatewayIdentifier(),"stripe:version":t,"stripe:publishableKey":`${n}/${i}`}}processAdditionalAction(e,t){var n;return ja(this,void 0,void 0,function*(){if(!t)throw new co(["payment"]);if(!pa(e)||("object"!=typeof(i=e.body)||null===i||!("three_ds_result"in i)||!("errors"in i)))throw e;var i;if(ve(e.body.errors,{code:"three_d_secure_required"})){const i=this.getGooglePayInitializationData();Ba(i),this.stripeUPEClient=yield this.loadStripeJs(i,t);const r=e.body.three_ds_result.token;let o,a=!1;try{o=yield this.stripeUPEClient.confirmCardPayment(r)}catch(e){try{o=yield this.stripeUPEClient.retrievePaymentIntent(r)}catch(e){a=!0}}if(null==o?void 0:o.error){if(this._throwDisplayableStripeError(o.error),this._isCancellationError(o.error))throw new Wi;throw new Qr}if(!(null==o?void 0:o.paymentIntent)&&!a)throw new nr;return this.paymentIntegrationService.submitPayment({methodId:t,paymentData:{nonce:(null===(n=null==o?void 0:o.paymentIntent)||void 0===n?void 0:n.id)||r}})}throw e})}loadStripeJs(e,t){return ja(this,void 0,void 0,function*(){if(this.stripeUPEClient)return this.stripeUPEClient;const n=this.paymentIntegrationService.getState().getCartLocale();return"googlepaystripeocs"===t&&e.useNewStripeJsVersion?this.scriptLoader.getStripeClient(e,n,ka.CLOVER):this.scriptLoader.getStripeClient(e,n,ka.V3,Fa,La)})}_isCancellationError(e){var t,n;return e&&-1!==(null===(n=null===(t=e.payment_intent.last_payment_error)||void 0===t?void 0:t.message)||void 0===n?void 0:n.indexOf("canceled"))}_throwDisplayableStripeError(e){if(H(["card_error","invalid_request_error","validation_error"],e.type))throw new Error(e.message)}}const qa=vi(e=>new ra(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeocs"}]),Va=vi(e=>new ra(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripeupe"}]);class Ga extends ea{constructor(e){super("worldpay",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const Ha=vi(e=>new ra(e,new aa(da(),new Ga(e),n(),Ee())),[{id:"googlepayworldpayaccess"}]);var Wa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class $a extends ea{constructor(e,t){super("braintree",e),this._braintreeSdk=t,this._methodId=Qo.BRAINTREE,this._service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Wa(this,void 0,void 0,function*(){yield i.initialize.call(this,e,t,n);let r=i.getPaymentMethod.call(this);if(r.clientToken||(r=(yield this._service.loadPaymentMethod(this._methodId)).getPaymentMethodOrThrow(this._methodId)),!r.clientToken||!r.initializationData)throw new ti(Xn.MissingPaymentMethod);return this._braintreeSdk.initialize(r.clientToken),this._braintreeGooglePayment=yield this._braintreeSdk.getBraintreeGooglePayment(),Promise.resolve()})}getNonce(e){const t=Object.create(null,{getNonce:{get:()=>super.getNonce},getPaymentMethod:{get:()=>super.getPaymentMethod}});var n;return Wa(this,void 0,void 0,function*(){const i=yield t.getNonce.call(this,e),{clientToken:r,initializationData:o}=t.getPaymentMethod.call(this);if(!r||!o||!(null===(n=o.card_information)||void 0===n?void 0:n.bin))throw new ti(Xn.MissingPaymentMethod);const{isThreeDSecureEnabled:a,card_information:{bin:s,isNetworkTokenized:d}}=o;if(a&&!d){const e=yield this._braintreeSdk.getBraintreeThreeDS(),{orderAmount:t}=this._service.getState().getOrderOrThrow();return(yield this._braintreePresent3DSChallenge(e,t,i,s)).nonce}return i})}extraPaymentData(){return Wa(this,void 0,void 0,function*(){return{deviceSessionId:yield this._getBraintreeDeviceData()}})}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return Wa(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);let i;try{i=JSON.parse(n.nonce)}catch(e){throw new fi("Unable to parse response from Google Pay.")}return function(e){if(!function(e){return"object"==typeof e&&null!==e&&"androidPayCards"in e}(e))throw new ti(Xn.MissingPaymentToken)}(i),n.nonce=i.androidPayCards[0].nonce,n.card_information.bin=i.androidPayCards[0].details.bin,n.card_information.isNetworkTokenized=i.androidPayCards[0].details.isNetworkTokenized,n})}getCardParameters(){return super.getCardParameters()}getPaymentGatewayParameters(){const e=Object.create(null,{getMerchantInfo:{get:()=>super.getMerchantInfo},getTransactionInfo:{get:()=>super.getTransactionInfo},getRequiredData:{get:()=>super.getRequiredData}});return Wa(this,void 0,void 0,function*(){return this.getBraintreeGooglePayment().createPaymentDataRequest(Object.assign({merchantInfo:e.getMerchantInfo.call(this),transactionInfo:e.getTransactionInfo.call(this),cardRequirements:{billingAddressRequired:!0,billingAddressFormat:"FULL"}},yield e.getRequiredData.call(this))).paymentMethodTokenizationParameters.parameters})}getBraintreeGooglePayment(){if(!this._braintreeGooglePayment)throw new ti(Xn.MissingPaymentMethod);return this._braintreeGooglePayment}_getBraintreeDeviceData(){return Wa(this,void 0,void 0,function*(){const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e})}_braintreePresent3DSChallenge(e,t,n,i){return new En(e.verifyCard({amount:t,bin:i,nonce:n,onLookupComplete:(e,t)=>{t()}})).promise}}const Ya=vi(e=>{const t=n(),i=window,r=new Ei(e),o=new Ui(new Hi(a(),i,r));return new ra(e,new aa(da(),new $a(e,o),t,Ee()))},[{id:"googlepaybraintree"}]),Ka={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},Ja=["ar_BH","ar_DZ","ar_EG","ar_JO","ar_KW","ar_MA","ar_OM","ar_QA","ar_SA","ar_TN","ar_YE","ar_AE","bg_BG","cs_CZ","da_DK","da_FO","da_GL","de_AT","de_CH","de_DE","de_LU","el_GR","en_AD","en_AE","en_AG","en_AI","en_AL","en_AM","en_AN","en_AO","en_AT","en_AU","en_AW","en_AZ","en_BB","en_BE","en_BH","en_BJ","en_BM","en_BN","en_BS","en_BT","en_BW","en_BY","en_BZ","en_C2","en_CA","en_CD","en_CG","en_CH","en_CI","en_CK","en_CL","en_CM","en_CN","en_CO","en_CR","en_CV","en_CY","en_CZ","en_DE","en_DJ","en_DK","en_DM","en_DO","en_DZ","en_EC","en_EE","en_EG","en_ER","en_ES","en_ET","en_FI","en_FJ","en_FK","en_FM","en_FO","en_FR","en_GA","en_GB","en_GD","en_GE","en_GF","en_GI","en_GL","en_GM","en_GN","en_GP","en_GR","en_GT","en_GW","en_GY","en_HK","en_HN","en_HR","en_HU","en_ID","en_IE","en_IL","en_IN","en_IS","en_IT","en_JM","en_JO","en_JP","en_KE","en_KG","en_KH","en_KI","en_KM","en_KN","en_KR","en_KW","en_KY","en_KZ","en_LA","en_LC","en_LI","en_LK","en_LS","en_LT","en_LU","en_LV","en_MA","en_MC","en_MD","en_ME","en_MG","en_MH","en_MK","en_ML","en_MN","en_MQ","en_MR","en_MS","en_MT","en_MU","en_MV","en_MW","en_MY","en_MZ","en_NA","en_NC","en_NE","en_NF","en_NG","en_NI","en_NL","en_NO","en_NP","en_NR","en_NU","en_NZ","en_OM","en_PA","en_PE","en_PF","en_PG","en_PH","en_PL","en_PM","en_PN","en_PT","en_PW","en_PY","en_QA","en_RE","en_RO","en_RS","en_RU","en_RW","en_SA","en_SB","en_SC","en_SE","en_SG","en_SH","en_SI","en_SJ","en_SK","en_SL","en_SM","en_SN","en_SO","en_SR","en_ST","en_SV","en_SZ","en_TC","en_TD","en_TG","en_TH","en_TJ","en_TM","en_TN","en_TO","en_TR","en_TT","en_TV","en_TW","en_TZ","en_UA","en_UG","en_US","en_UY","en_VA","en_VC","en_VE","en_VG","en_VN","en_VU","en_WF","en_WS","en_YE","en_YT","en_ZA","en_ZM","en_ZW","es_AD","es_AI","es_AO","es_AR","es_AW","es_BB","es_BJ","es_BM","es_BO","es_BS","es_BZ","es_CD","es_CG","es_CK","es_CL","es_CO","es_CR","es_CV","es_DJ","es_DM","es_DO","es_DZ","es_EC","es_EG","es_ER","es_ES","es_ET","es_FJ","es_FK","es_FO","es_GA","es_GD","es_GE","es_GI","es_GL","es_GM","es_GN","es_GT","es_GW","es_GY","es_HN","es_IE","es_JM","es_JO","es_KE","es_KG","es_KI","es_KM","es_KN","es_KW","es_KY","es_KZ","es_LC","es_LI","es_LS","es_LU","es_MA","es_MG","es_MH","es_ML","es_MR","es_MS","es_MU","es_MW","es_MX","es_MZ","es_NA","es_NC","es_NE","es_NF","es_NI","es_NR","es_NU","es_NZ","es_OM","es_PA","es_PE","es_PF","es_PG","es_PM","es_PN","es_PW","es_PY","es_QA","es_RS","es_RW","es_SA","es_SB","es_SC","es_SH","es_SJ","es_SL","es_SM","es_SN","es_SO","es_SR","es_ST","es_SV","es_SZ","es_TC","es_TD","es_TG","es_TJ","es_TM","es_TN","es_TT","es_TV","es_UA","es_UG","es_US","es_UY","es_VA","es_VC","es_VE","es_VG","es_VU","es_WF","es_YE","es_ZM","et_EE","fi_FI","fr_AD","fr_AE","fr_AI","fr_AM","fr_AO","fr_AW","fr_AZ","fr_BB","fr_BE","fr_BF","fr_BI","fr_BJ","fr_BM","fr_BS","fr_BZ","fr_CA","fr_CD","fr_CG","fr_CH","fr_CI","fr_CK","fr_CM","fr_CV","fr_DJ","fr_DM","fr_DO","fr_DZ","fr_EC","fr_ER","fr_ET","fr_FJ","fr_FK","fr_FO","fr_FR","fr_GA","fr_GD","fr_GE","fr_GF","fr_GI","fr_GL","fr_GM","fr_GN","fr_GP","fr_GT","fr_GW","fr_GY","fr_HN","fr_IE","fr_JM","fr_JO","fr_KE","fr_KG","fr_KI","fr_KM","fr_KN","fr_KW","fr_KY","fr_KZ","fr_LC","fr_LI","fr_LS","fr_LU","fr_MA","fr_MC","fr_MG","fr_MH","fr_ML","fr_MQ","fr_MR","fr_MS","fr_MU","fr_MW","fr_MZ","fr_NA","fr_NC","fr_NE","fr_NF","fr_NI","fr_NR","fr_NU","fr_NZ","fr_OM","fr_PA","fr_PE","fr_PF","fr_PG","fr_PM","fr_PN","fr_PW","fr_QA","fr_RE","fr_RS","fr_RW","fr_SA","fr_SB","fr_SC","fr_SH","fr_SJ","fr_SL","fr_SM","fr_SN","fr_SO","fr_SR","fr_ST","fr_SV","fr_SZ","fr_TC","fr_TD","fr_TG","fr_TJ","fr_TM","fr_TN","fr_TT","fr_TV","fr_UA","fr_UG","fr_US","fr_UY","fr_VA","fr_VC","fr_VE","fr_VG","fr_VU","fr_WF","fr_YE","fr_YT","fr_ZA","fr_ZM","he_IL","hu_HU","id_ID","it_IT","ja_JP","ko_KR","lv_LV","lt_LT","ms_BN","ms_MY","nl_BE","nl_NL","pl_PL","pt_BR","pt_PT","ro_RO","ru_EE","ru_LT","ru_LV","ru_RU","ru_UA","si_LK","sk_SK","sl_SI","sq_AL","sv_SE","tl_PH","th_TH","tr_TR","vi_VN","zh_C2","zh_CN","zh_HK","zh_TW","zh_AD","zh_AE","zh_AI","zh_AO","zh_AW","zh_BB","zh_BH","zh_BJ","zh_BM","zh_BS","zh_BZ","zh_CD","zh_CG","zh_CK","zh_CL","zh_CO","zh_CV","zh_DJ","zh_DM","zh_DO","zh_DZ","zh_EC","zh_EG","zh_ER","zh_ET","zh_FJ","zh_FK","zh_FO","zh_GA","zh_GD","zh_GE","zh_GI","zh_GL","zh_GM","zh_GN","zh_GT","zh_GW","zh_GY","zh_HN","zh_IE","zh_JM","zh_JO","zh_KE","zh_KG","zh_KI","zh_KM","zh_KN","zh_KW","zh_KY","zh_KZ","zh_LC","zh_LI","zh_LS","zh_LT","zh_LU","zh_MA","zh_MG","zh_MH","zh_ML","zh_MR","zh_MS","zh_MU","zh_MW","zh_MZ","zh_NA","zh_NC","zh_NE","zh_NF","zh_NI","zh_NR","zh_NU","zh_NZ","zh_OM","zh_PA","zh_PE","zh_PF","zh_PG","zh_PM","zh_PN","zh_PW","zh_QA","zh_RS","zh_RW","zh_SA","zh_SB","zh_SC","zh_SH","zh_SJ","zh_SL","zh_SM","zh_SN","zh_SO","zh_SR","zh_ST","zh_SV","zh_SZ","zh_TC","zh_TD","zh_TG","zh_TJ","zh_TM","zh_TN","zh_TT","zh_TV","zh_UA","zh_UG","zh_US","zh_UY","zh_VA","zh_VC","zh_VE","zh_VG","zh_VU","zh_WF","zh_YE","zh_ZA","zh_ZM"];function Za(e){if(!e)return;let t;if(e.includes("-")){const[n,i]=e.split("-");t=`${n}_${i.toUpperCase()}`}else t=`${e}_${e.toUpperCase()}`;return Ja.includes(t)?t:void 0}var Qa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Xa{constructor(e){this.scriptLoader=e,this.window=window}getPayPalFastlaneSdk(e,t,n,i){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const r=this.getPayPalFastlaneSdkConfiguration(e,t,n,i);if(yield this.loadPayPalSdk(r),!this.window.paypalFastlaneSdk)throw new mi}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,n,i,r){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||r){const r=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i);yield this.loadPayPalSdk(r)}if(!this.window.paypalGooglePay)throw new mi;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t,n){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t,n);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new mi}return this.window.paypalApms})}getPayPalMessages(e,t,n){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t,n);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new mi;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return Qa(this,void 0,void 0,function*(){const n=this.transformConfig(e),i=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(n).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:i})})}getPayPalFastlaneSdkConfiguration(e,t,n,i){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,attributionId:c}=o,l=Za(i);return{options:Object.assign({"client-id":s,"merchant-id":d,commit:!0,components:["fastlane","buttons","payment-fields","hosted-fields","three-domain-secure"],currency:t,intent:a},l&&{locale:l}),attributes:{"data-client-metadata-id":n.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":c,"data-sdk-client-token":r}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i=!0){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:c,attributionId:l,isHostedCheckoutEnabled:u,isDeveloperModeApplicable:h}=o,p=u||i,m=Za(n);return{options:Object.assign(Object.assign({"client-id":s,"merchant-id":d,commit:p,components:["googlepay"],currency:t,intent:a},h&&{"buyer-country":c}),m&&{locale:m}),attributes:{"data-partner-attribution-id":l,"data-client-token":r,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:r,clientId:o,merchantId:a,buyerCountry:s,attributionId:d,isDeveloperModeApplicable:c,availableAlternativePaymentMethods:l=[],enabledAlternativePaymentMethods:u=[]}=i,h=u,p=l.filter(e=>!u.includes(e)),m=Za(n);return{options:Object.assign(Object.assign({"client-id":o,"merchant-id":a,"enable-funding":h.length>0?h:void 0,"disable-funding":p.length>0?p:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:r},c&&{"buyer-country":s}),m&&{locale:m}),attributes:{"data-partner-attribution-id":d,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ti(Xn.MissingPaymentMethod);const{clientId:r,merchantId:o,attributionId:a,isDeveloperModeApplicable:s,buyerCountry:d}=i,c=Za(n);return{options:Object.assign(Object.assign({"client-id":r,"merchant-id":o,components:["messages"],currency:t},s&&{"buyer-country":d}),c&&{locale:c}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":a}}}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}function es(e){if(!function(e){return!!e.initializationData&&"attributionId"in e.initializationData&&"isVenmoEnabled"in e.initializationData&&"isGooglePayEnabled"in e.initializationData&&"isPayPalCreditAvailable"in e.initializationData}(e))throw new ti(Xn.MissingPaymentMethod)}var ts=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ns extends ea{constructor(e,t){super("paypalsb",e),this.payPalCommerceSdk=t,this.service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});var r,o,a,s,d;return ts(this,void 0,void 0,function*(){const c=this.service.getState(),l=null!==(o=null===(r=c.getStoreConfig())||void 0===r?void 0:r.currency.code)&&void 0!==o?o:n;if(!l)throw new ti(Xn.MissingPaymentMethod);yield i.initialize.call(this,e,t,l);const u=i.getPaymentMethod.call(this);if(!u.initializationData)throw new ti(Xn.MissingPaymentMethod);es(u);const h=yield this.payPalCommerceSdk.getPayPalGooglePaySdk(u,l,c.getLocale());this.googlepayConfig=yield h.Googlepay().config();const{allowedPaymentMethods:p}=this.googlepayConfig;this.setGatewayIdentifier(null===(d=null===(s=null===(a=p[0])||void 0===a?void 0:a.tokenizationSpecification)||void 0===s?void 0:s.parameters)||void 0===d?void 0:d.gateway)})}getPaymentGatewayParameters(){if(this.googlepayConfig){const{allowedPaymentMethods:e}=this.googlepayConfig,{gatewayMerchantId:t}=e[0].tokenizationSpecification.parameters;return{gateway:this.getGatewayIdentifier(),gatewayMerchantId:t}}return{gateway:this.getGatewayIdentifier()}}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ts(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n})}}const is=vi(e=>new ra(e,new aa(da(),new ns(e,new Xa(a())),n(),Ee())),[{id:"googlepaypaypalcommerce"}]);var rs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class os extends ea{constructor(e,t){super("googlepay_bigcommerce_payments",e),this.payPalSdkHelper=t,this.service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});var r,o,a,s,d;return rs(this,void 0,void 0,function*(){const c=null!==(o=null===(r=this.service.getState().getStoreConfig())||void 0===r?void 0:r.currency.code)&&void 0!==o?o:n;if(!c)throw new ti(Xn.MissingPaymentMethod);yield i.initialize.call(this,e,t,c);const l=i.getPaymentMethod.call(this);if(!l.initializationData)throw new ti(Xn.MissingPaymentMethod);es(l);const u=yield this.payPalSdkHelper.getPayPalGooglePaySdk(l,c);this.googlepayConfig=yield u.Googlepay().config();const{allowedPaymentMethods:h}=this.googlepayConfig;this.setGatewayIdentifier(null===(d=null===(s=null===(a=h[0])||void 0===a?void 0:a.tokenizationSpecification)||void 0===s?void 0:s.parameters)||void 0===d?void 0:d.gateway)})}getPaymentGatewayParameters(){if(this.googlepayConfig){const{allowedPaymentMethods:e}=this.googlepayConfig,{gatewayMerchantId:t}=e[0].tokenizationSpecification.parameters;return{gateway:this.getGatewayIdentifier(),gatewayMerchantId:t}}return{gateway:this.getGatewayIdentifier()}}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return rs(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n})}}const as=vi(e=>new ra(e,new aa(da(),new os(e,new xr(a())),n(),Ee())),[{id:"googlepay_bigcommerce_payments"}]);function ss(){const{navigator:e}=window;let t;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 ds=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class cs extends ea{constructor(e,t){super("worldlinena",e),this.formPoster=t}extraPaymentData(){return ds(this,void 0,void 0,function*(){return Promise.resolve({browser_info:ss()})})}processAdditionalAction(e){return ds(this,void 0,void 0,function*(){if(!function(e){return pa(e)&&(t=e.body,Z(t)&&"object"==typeof t&&"errors"in t&&"three_ds_result"in t&&W(t.errors)&&ve(t.errors,{code:"three_d_secure_required"}));var t}(e))throw e;const{three_ds_result:t}=e.body,{acs_url:n,payer_auth_request:i,merchant_data:r}=t||{};if(!n||!i||!r)throw new co(["formUrl","threeDSSessionData","creq"]);return new Promise(e=>{this.formPoster.postForm(n,{threeDSSessionData:i,creq:r},e,"_top")})})}}const ls=vi(e=>new ra(e,new aa(da(),new cs(e,Ee()),n(),Ee())),[{id:"googlepaytdonlinemart"}]);var us,hs,ps,ms,ys,gs,vs,fs,Ss,_s,ws=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Is{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,n,i,r){return ws(this,void 0,void 0,function*(){if(!this.window.paypal||r){const r=this.getPayPalSdkScriptConfigOrThrow(e,t,n,i);if(yield this.loadPayPalSdk(r),!this.window.paypal)throw new mi}return this.window.paypal})}getPayPalFastlaneSdk(e,t,n,i){return ws(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const r=this.getPayPalFastlaneSdkConfiguration(e,t,n,i);if(yield this.loadPayPalSdk(r),!this.window.paypalFastlaneSdk)throw new mi}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,n,i,r){return ws(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||r){const r=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i);yield this.loadPayPalSdk(r)}if(!this.window.paypalGooglePay)throw new mi;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t,n){return ws(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t,n);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new mi}return this.window.paypalApms})}getPayPalMessages(e,t,n){return ws(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t,n);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new mi;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return ws(this,void 0,void 0,function*(){const n=this.transformConfig(e),i=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(n).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:i})})}getPayPalSdkScriptConfigOrThrow(e,t,n,i=!0){const{id:r,clientToken:o,initializationData:a}=e;if(!a||!a.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:s,clientId:d,merchantId:c,buyerCountry:l,attributionId:u,isVenmoEnabled:h,isHostedCheckoutEnabled:p,isPayPalCreditAvailable:m,isDeveloperModeApplicable:y,availableAlternativePaymentMethods:g=[],enabledAlternativePaymentMethods:v=[],isGooglePayEnabled:f}=a,S=p||i,_="paypalcommercecreditcards"===r||"bigcommerce_payments_creditcards"===r,w=_?["card"]:[],I=m?["credit","paylater"]:[],C=h?["venmo"]:[],b=f?["googlepay"]:[],P=i?["card-fields"]:[],O=[..._?[]:["card"],...m?[]:["credit","paylater"],...h?[]:["venmo"],...g.filter(e=>!v.includes(e))],E=[...w,...I,...C,...v],A=Za(n);return{options:Object.assign(Object.assign({"client-id":d,"merchant-id":c,"enable-funding":E.length>0?E:void 0,"disable-funding":O.length>0?O:void 0,commit:S,components:["buttons","hosted-fields","payment-fields","legal",...b,...P],currency:t,intent:s},y&&{"buyer-country":l}),A&&{locale:A}),attributes:{"data-partner-attribution-id":u,"data-client-token":o}}}getPayPalFastlaneSdkConfiguration(e,t,n,i){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,attributionId:c}=o,l=Za(i);return{options:Object.assign(Object.assign({"client-id":s,"merchant-id":d,commit:!0,components:["fastlane","buttons","payment-fields","hosted-fields","three-domain-secure"],currency:t},l&&{locale:l}),{intent:a}),attributes:{"data-client-metadata-id":n.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":c,"data-sdk-client-token":r}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i=!0){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:c,attributionId:l,isHostedCheckoutEnabled:u,isDeveloperModeApplicable:h}=o,p=u||i,m=Za(n);return{options:Object.assign(Object.assign({"client-id":s,"merchant-id":d,commit:p,components:["googlepay"],currency:t,intent:a},h&&{"buyer-country":c}),m&&{locale:m}),attributes:{"data-partner-attribution-id":l,"data-client-token":r,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:r,clientId:o,merchantId:a,buyerCountry:s,attributionId:d,isDeveloperModeApplicable:c,availableAlternativePaymentMethods:l=[],enabledAlternativePaymentMethods:u=[]}=i,h=u,p=l.filter(e=>!u.includes(e)),m=Za(n);return{options:Object.assign(Object.assign({"client-id":o,"merchant-id":a,"enable-funding":h.length>0?h:void 0,"disable-funding":p.length>0?p:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:r},c&&{"buyer-country":s}),m&&{locale:m}),attributes:{"data-partner-attribution-id":d,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ti(Xn.MissingPaymentMethod);const{clientId:r,merchantId:o,attributionId:a,isDeveloperModeApplicable:s,buyerCountry:d}=i,c=Za(n);return{options:Object.assign(Object.assign({"client-id":r,"merchant-id":o,components:["messages"],currency:t},s&&{"buyer-country":d}),c&&{locale:c}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":a}}}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}function Cs(){return new Is(a())}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(us||(us={})),(hs||(hs={})).Always="SCA_ALWAYS",function(e){e.Succeeded="succeeded",e.Cancelled="cancelled",e.Errored="errored"}(ps||(ps={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(ms||(ms={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(ys||(ys={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(gs||(gs={})),function(e){e.pill="pill",e.rect="rect"}(vs||(vs={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="canceled",e.UNRECOGNIZED="unrecognized"}(fs||(fs={})),(Ss||(Ss={})).OXXO="oxxo",function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(_s||(_s={}));var bs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ps{constructor(e,t,n,i){this.formPoster=e,this.paymentIntegrationService=t,this.paypalRequestSender=n,this.paypalSdkLoader=i}loadPayPalSdk(e,t,n,i){return bs(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e),s=r.getLocale();return this.paypalSdk=yield this.paypalSdkLoader.getPayPalSDK(a,o,s,n,i),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new mi;return this.paypalSdk}createBuyNowCartOrThrow(e){return bs(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}})}createOrder(e,t){return bs(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i}=yield this.paypalRequestSender.createOrder(e,Object.assign({cartId:n},t));return i})}createOrderCardFields(e,t){return bs(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i,setupToken:r}=yield this.paypalRequestSender.createOrder(e,Object.assign({cartId:n},t));return Object.assign({orderId:i},r?{setupToken:r}:{})})}updateOrder(e,t,n){return bs(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),r=i.getCartOrThrow(),o=i.getConsignmentsOrThrow()[0];try{yield this.paypalRequestSender.updateOrder(e,Object.assign(Object.assign({availableShippingOptions:o.availableShippingOptions,cartId:r.id,selectedShippingOption:o.selectedShippingOption},t?{methodId:t}:{}),n?{orderId:n}:{}))}catch(e){throw new nr}})}getOrderStatus(e,t){return bs(this,void 0,void 0,function*(){try{const{status:n}=yield this.paypalRequestSender.getOrderStatus(e,t);return n}catch(e){throw new nr}})}tokenizePayment(e,t){const n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new ti(Xn.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===xt.BuyNow&&{cart_id:n.id}))}submitPayment(e,t,n){return bs(this,void 0,void 0,function*(){const i={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}};yield this.paymentIntegrationService.submitPayment(Object.assign({methodId:e,paymentData:i},n?{gatewayId:n}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],i=n.find(e=>e.isRecommended),r=(e?n.find(t=>t.id===e):n.find(e=>{if(t.selectedShippingOption){const n=t.selectedShippingOption.id;return e.id===n}return!1}))||i||n[0];if(!r)throw new Error("Your order can't be shipped to this address");return r}getAddress(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:(null==e?void 0:e.phone)||"",company:"",address1:(null==e?void 0:e.address1)||"",address2:(null==e?void 0:e.address2)||"",city:(null==e?void 0:e.city)||"",countryCode:(null==e?void 0:e.countryCode)||"",postalCode:(null==e?void 0:e.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==e?void 0:e.stateOrProvinceCode)||"",customFields:[]}}getBillingAddressFromOrderDetails({payer:e}){var t,n;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,address2:e.address.address_line_2,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1,phone:null===(n=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===n?void 0:n.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:n}=e,{address:i,name:{full_name:r}}=n[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:i.address_line_1,address2:i.address_line_2,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})}getValidButtonStyle(e={}){const{color:t,height:n,label:i,shape:r}=e,o={color:t&&gs[t]?t:void 0,height:this.getValidHeight(n),label:i&&ys[i]?i:void 0,shape:r&&vs[r]?r:void 0};return ue(o,J)}getValidHeight(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40}removeElement(e){const t=e&&document.getElementById(e);t&&(t.style.display="none")}}var Os=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Es{constructor(e){this.requestSender=e}createOrder(e,t){return Os(this,void 0,void 0,function*(){const n=`/api/storefront/payment/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.post(n,{headers:r,body:i})).body})}updateOrder(e,t){return Os(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.put(n,{headers:r,body:i})).body})}getOrderStatus(e,t){return Os(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body})}}const As=e=>{const{getHost:t}=e.getState();return new Ps(Ee(),e,new Es(n({host:t()})),Cs())};var Ts=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const ks=class{constructor(e,t){this.paymentIntegrationService=e,this.paypalIntegrationService=t}createPayPalButton(e,t,n,i){const{style:r,fundingSource:o,isAppSwitchEnabled:a,isHostedCheckoutEnabled:s,onClick:d,onCancel:c,onPaymentComplete:l,onError:u}=n;this.onError=u;const h=this.paypalIntegrationService.getPayPalSdkOrThrow();if(!Object.values(h.FUNDING).includes(o))throw new fi('Unable to initialize PayPal button because "fundingSource" argument is not valid funding source.');const p=Object.assign(Object.assign({},!a&&{onShippingAddressChange:t=>this.onShippingAddressChange(t,e),onShippingOptionsChange:t=>this.onShippingOptionsChange(t,e)}),{onApprove:(n,i)=>this.onHostedCheckoutApprove(n,i,t,e,l)});return h.Buttons(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({fundingSource:o,style:this.paypalIntegrationService.getValidButtonStyle(r)},a&&{appSwitchWhenAvailable:!0}),{createOrder:()=>Ts(this,void 0,void 0,function*(){if(i){const e=yield this.paypalIntegrationService.createBuyNowCartOrThrow(i);yield this.paymentIntegrationService.loadCheckout(e.id)}return this.paypalIntegrationService.createOrder(e)}),onApprove:({orderID:e})=>this.paypalIntegrationService.tokenizePayment(t,e)}),d?{onClick:d}:{}),c?{onCancel:c}:{}),s&&p))}onHostedCheckoutApprove(e,t,n,i,r){return Ts(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const o=this.paymentIntegrationService.getState().getCartOrThrow(),a=yield t.order.get();try{const t=this.paypalIntegrationService.getBillingAddressFromOrderDetails(a);if(yield this.paymentIntegrationService.updateBillingAddress(t),o.lineItems.physicalItems.length>0){const e=this.paypalIntegrationService.getShippingAddressFromOrderDetails(a);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.paypalIntegrationService.updateOrder(i)}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.paypalIntegrationService.submitPayment(n,e.orderID),r&&"function"==typeof r&&r()}catch(e){this.handleError(e)}})}onShippingAddressChange(e,t){return Ts(this,void 0,void 0,function*(){const n=this.paypalIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(n),yield this.paymentIntegrationService.updateShippingAddress(n);const e=this.paypalIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.paypalIntegrationService.updateOrder(t)}catch(e){this.handleError(e)}})}onShippingOptionsChange(e,t){return Ts(this,void 0,void 0,function*(){const n=this.paypalIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(n.id),yield this.paypalIntegrationService.updateOrder(t)}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}};var Ds=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ms{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.paypalButtonCreationService=n}initialize(e){return Ds(this,void 0,void 0,function*(){const{paypalcommerce:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.paypalcommerce.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.paypalcommerce.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.paypalIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Ds(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return Ds(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){var n,i;const{container:r,onClick:o,onComplete:a,onError:s}=t,d=this.paypalIntegrationService.getPayPalSdkOrThrow(),c=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:l,paymentButtonStyles:u,isAppSwitchEnabled:h}=c.initializationData||{},{checkoutTopButtonStyles:p}=u||{},m=Object.assign(Object.assign(Object.assign({fundingSource:d.FUNDING.PAYPAL,isAppSwitchEnabled:h,isHostedCheckoutEnabled:l,style:Object.assign(Object.assign({},p),{height:wr})},o&&{onClick:()=>o()}),l&&a&&{onPaymentComplete:()=>a()}),{onError:s}),y=this.paypalButtonCreationService.createPayPalButton("paypalcommerce",e,m);y.isEligible()?(null===(n=y.hasReturned)||void 0===n?void 0:n.call(y))&&h?null===(i=y.resume)||void 0===i||i.call(y):y.render(`#${r}`):this.paypalIntegrationService.removeElement(r)}}const zs=vi(e=>{const t=As(e),n=new ks(e,t);return new Ms(e,t,n)},[{id:"paypalcommerce"}]);var Ns,xs,Rs,Fs,Ls,Bs,js;!function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(Ns||(Ns={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(xs||(xs={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Rs||(Rs={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(Fs||(Fs={})),function(e){e.pill="pill",e.rect="rect"}(Ls||(Ls={})),function(e){e.OXXO="oxxo",e.IDEAL="ideal"}(Bs||(Bs={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(js||(js={}));var Us=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class qs{constructor(e,t,n,i){this.formPoster=e,this.paymentIntegrationService=t,this.paypalCommerceRequestSender=n,this.paypalCommerceScriptLoader=i}loadPayPalSdk(e,t,n,i){return Us(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e);return this.paypalSdk=yield this.paypalCommerceScriptLoader.getPayPalSDK(a,o,r.getLocale(),n,i),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new mi;return this.paypalSdk}createBuyNowCartOrThrow(e){return Us(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}})}createOrder(e,t){return Us(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i}=yield this.paypalCommerceRequestSender.createOrder(e,Object.assign({cartId:n},t));return i})}createOrderCardFields(e,t){return Us(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i,setupToken:r}=yield this.paypalCommerceRequestSender.createOrder(e,Object.assign({cartId:n},t));return Object.assign({orderId:i},r?{setupToken:r}:{})})}updateOrder(){return Us(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getConsignmentsOrThrow()[0];try{yield this.paypalCommerceRequestSender.updateOrder({availableShippingOptions:n.availableShippingOptions,cartId:t.id,selectedShippingOption:n.selectedShippingOption})}catch(e){throw new nr}})}getOrderStatus(e,t){return Us(this,void 0,void 0,function*(){try{const{status:n}=yield this.paypalCommerceRequestSender.getOrderStatus(e,t);return n}catch(e){throw new nr}})}tokenizePayment(e,t){const n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new ti(Xn.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===xt.BuyNow&&{cart_id:n.id}))}submitPayment(e,t,n){return Us(this,void 0,void 0,function*(){const i={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}};yield this.paymentIntegrationService.submitPayment(Object.assign({methodId:e,paymentData:i},n?{gatewayId:n}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],i=n.find(e=>e.isRecommended),r=(e?n.find(t=>t.id===e):n.find(e=>{var n;return e.id===(null===(n=t.selectedShippingOption)||void 0===n?void 0:n.id)}))||i||n[0];if(!r)throw new Error("Your order can't be shipped to this address");return r}getAddress(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:(null==e?void 0:e.phone)||"",company:"",address1:(null==e?void 0:e.address1)||"",address2:(null==e?void 0:e.address2)||"",city:(null==e?void 0:e.city)||"",countryCode:(null==e?void 0:e.countryCode)||"",postalCode:(null==e?void 0:e.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==e?void 0:e.stateOrProvinceCode)||"",customFields:[]}}getBillingAddressFromOrderDetails({payer:e}){var t,n;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,address2:e.address.address_line_2,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1,phone:null===(n=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===n?void 0:n.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:n}=e,{address:i,name:{full_name:r}}=n[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:i.address_line_1,address2:i.address_line_2,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})}getValidButtonStyle(e){const{color:t,height:n,label:i,shape:r}=e||{},o={color:t&&Fs[t]?t:void 0,height:this.getValidHeight(n),label:i&&Rs[i]?i:void 0,shape:r&&Ls[r]?r:void 0};return ue(o,J)}getValidHeight(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40}removeElement(e){const t=e&&document.getElementById(e);t&&(t.style.display="none")}}var Vs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Gs{constructor(e){this.requestSender=e}createOrder(e,t){return Vs(this,void 0,void 0,function*(){const n=`/api/storefront/payment/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.post(n,{headers:r,body:i})).body})}updateOrder(e){return Vs(this,void 0,void 0,function*(){const t=e,n=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.put("/api/storefront/initialization/paypalcommerce",{headers:n,body:t})).body})}getOrderStatus(e="paypalcommerce",t){return Vs(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body})}}var Hs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ws{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,n,i,r){return Hs(this,void 0,void 0,function*(){const o=this.getPayPalSdkScriptConfigOrThrow(e,t,n,i);return this.loadPayPalSDK(o,r)})}loadPayPalSDK(e,t=!1){return Hs(this,void 0,void 0,function*(){if(!this.window.paypal||t){const t=this.transformConfig(e.options),n=this.transformConfig(e.attributes),i=`https://www.paypal.com/sdk/js?${new URLSearchParams(t).toString()}`;yield this.scriptLoader.loadScript(i,{async:!0,attributes:n})}if(!this.window.paypal)throw new mi;return this.window.paypal})}getPayPalSdkScriptConfigOrThrow(e,t,n,i=!0){const{id:r,clientToken:o,initializationData:a}=e;if(!(null==a?void 0:a.clientId))throw new ti(Xn.MissingPaymentMethod);const{intent:s,clientId:d,merchantId:c,buyerCountry:l,attributionId:u,isVenmoEnabled:h,isHostedCheckoutEnabled:p,isPayPalCreditAvailable:m,isDeveloperModeApplicable:y,availableAlternativePaymentMethods:g=[],enabledAlternativePaymentMethods:v=[],isGooglePayEnabled:f}=a,S=p||i,_="paypalcommercecreditcards"===r,w=_?["card"]:[],I=m?["credit","paylater"]:[],C=h?["venmo"]:[],b=f?["googlepay"]:[],P=i?["card-fields"]:[],O=[..._?[]:["card"],...m?[]:["credit","paylater"],...h?[]:["venmo"],...g.filter(e=>!v.includes(e))],E=[...w,...I,...C,...v],A=Za(n);return{options:Object.assign(Object.assign({"client-id":d,"merchant-id":c,"enable-funding":E.length>0?E:void 0,"disable-funding":O.length>0?O:void 0,commit:S,components:["buttons","hosted-fields","payment-fields","legal",...b,...P],currency:t,intent:s},y&&{"buyer-country":l}),A&&{locale:A}),attributes:{"data-partner-attribution-id":u,"data-client-token":o}}}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}const $s=e=>{const{getHost:t}=e.getState();return new qs(Ee(),e,new Gs(n({host:t()})),new Ws(a()))};var Ys=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ks{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.onError=ce}initialize(e){return Ys(this,void 0,void 0,function*(){const{paypalcommercecredit:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.paypalcommercecredit.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.paypalcommercecredit.onClick" argument is not a function.');this.onError=t.onError||ce,this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.paypalCommerceIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Ys(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Ys(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){const{container:n,onComplete:i,onClick:r}=t,o=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:s,paymentButtonStyles:d,isAppSwitchEnabled:c}=a.initializationData||{},{checkoutTopButtonStyles:l}=d||{},u=Object.assign({createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercecredit"),onApprove:({orderID:t})=>this.paypalCommerceIntegrationService.tokenizePayment(e,t)},r&&{onClick:()=>r()}),h=Object.assign(Object.assign({},!c&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(t,n)=>this.onHostedCheckoutApprove(t,n,e,i)}),p=[o.FUNDING.PAYLATER,o.FUNDING.CREDIT];let m=!1;p.forEach(e=>{if(!m){const t=Object.assign(Object.assign({fundingSource:e,style:this.paypalCommerceIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},l),{height:wr}))},u),s&&h),i=o.Buttons(t);i.isEligible()&&(i.render(`#${n}`),m=!0)}}),m||this.paypalCommerceIntegrationService.removeElement(n)}onHostedCheckoutApprove(e,t,n,i){return Ys(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.paypalCommerceIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.paypalCommerceIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Ys(this,void 0,void 0,function*(){const t=this.paypalCommerceIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.paypalCommerceIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}onShippingOptionsChange(e){return Ys(this,void 0,void 0,function*(){const t=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.paypalCommerceIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const Js=vi(e=>new Ks(e,$s(e)),[{id:"paypalcommercecredit"}]);var Zs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Qs{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}initialize(e){return Zs(this,void 0,void 0,function*(){const{paypalcommercevenmo:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.paypalCommerceIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Zs(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Zs(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){const{container:n,onClick:i}=t,r=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:a}=o.initializationData||{},{checkoutTopButtonStyles:s}=a||{},d=Object.assign({fundingSource:r.FUNDING.VENMO,style:this.paypalCommerceIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},s),{height:wr})),createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo"),onApprove:({orderID:t})=>this.paypalCommerceIntegrationService.tokenizePayment(e,t)},i&&{onClick:()=>i()}),c=r.Buttons(d);c.isEligible()?c.render(`#${n}`):this.paypalCommerceIntegrationService.removeElement(n)}}const Xs=vi(e=>new Qs(e,$s(e)),[{id:"paypalcommercevenmo"}]);var ed=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class td{constructor(){this.window=window}initializePayPalFastlane(e,t,n){return ed(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("fastlaneEnv","sandbox"),window.localStorage.setItem("axoEnv","sandbox")),!this.window.paypalFastlane){const t={root:{backgroundColorPrimary:"transparent"}};this.window.paypalFastlane=yield e.Fastlane({styles:n||t})}return this.window.paypalFastlane})}getPayPalFastlaneOrThrow(){if(!this.window.paypalFastlane)throw new mi;return this.window.paypalFastlane}lookupCustomerOrThrow(e){return ed(this,void 0,void 0,function*(){return this.getPayPalFastlaneOrThrow().identity.lookupCustomerByEmail(e)})}triggerAuthenticationFlowOrThrow(e){return ed(this,void 0,void 0,function*(){return e?this.getPayPalFastlaneOrThrow().identity.triggerAuthenticationFlow(e):{}})}updateStorageSessionId(e){const t=new Date;t.setDate(t.getDate()+14);const n={expires:t,secure:!0};Fr.set("bc-fastlane-sessionId",e,n)}removeStorageSessionId(){Fr.remove("bc-fastlane-sessionId")}getStorageSessionId(){return Fr.get("bc-fastlane-sessionId")||""}mapPayPalFastlaneProfileToBcCustomerData(e,t){var n,i,r;const{authenticationState:o,profileData:a}=t,s=null===(r=null===(i=null===(n=null==a?void 0:a.card)||void 0===n?void 0:n.paymentSource)||void 0===i?void 0:i.card)||void 0===r?void 0:r.billingAddress,d=null==a?void 0:a.shippingAddress,c=null==a?void 0:a.name,l=null==a?void 0:a.card,u=d?this.mapPayPalToBcAddress(d.address,d.name,d.phoneNumber):void 0,h=s&&c?this.mapPayPalToBcAddress(s,c,null==d?void 0:d.phoneNumber):void 0,p=l?this.mapPayPalToBcInstrument(e,l):[],m=this.filterAddresses([u,h]);return{authenticationState:o||fs.UNRECOGNIZED,addresses:m,billingAddress:h,shippingAddress:u,instruments:p}}mapPayPalToBcInstrument(e,t){const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a}=i.card,[s,d]=o.split("-");return[{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:Pr.PAN,type:"card"}]}mapBcToPayPalAddress(e){return{company:(null==e?void 0:e.company)||"",addressLine1:(null==e?void 0:e.address1)||"",addressLine2:(null==e?void 0:e.address2)||"",adminArea1:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",adminArea2:(null==e?void 0:e.city)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||""}}mapPayPalToBcAddress(e,t,n,i){const[r,o]=t.fullName.split(" "),a=(null==n?void 0:n.nationalNumber)||"",s=(null==n?void 0:n.countryCode)||"";return{id:Date.now(),type:"paypal-address",firstName:t.firstName||r||"",lastName:t.lastName||o||"",company:e.company||"",address1:e.addressLine1,address2:e.addressLine2||"",city:e.adminArea2,stateOrProvince:e.adminArea1,stateOrProvinceCode:e.adminArea1,country:e.countryCode||"",countryCode:e.countryCode||"",postalCode:e.postalCode,phone:s+a,customFields:i||[]}}filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this.isEqualAddresses(e,t))?e:[...e,t]:e,[])}isEqualAddresses(e,t){return Y(this.normalizeAddress(e),this.normalizeAddress(t))}normalizeAddress(e){return le(e,["id","phone"])}}function nd(){return new td}function id(e){return"string"!=typeof e}function rd(e,t){if(t||e)return function(e){var t,n;const i={},r=ue(e.root,id),o=ue(e.input,id),a=ue(e.toggle,id),s=ue(null===(t=e.text)||void 0===t?void 0:t.body,id),d=ue(null===(n=e.text)||void 0===n?void 0:n.caption,id),c=e.branding;return Object.keys(r).length&&(i.root=r),Object.keys(o).length&&(i.input=o),Object.keys(a).length&&(i.toggle=a),Object.keys(s).length&&(i.text={},i.text.body=s),Object.keys(d).length&&(i.text=Object.assign({},i.text),i.text.caption=d),c&&(i.branding=c),i}(function(e,t){var n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,_,w,I,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(c=null==t?void 0:t.input)||void 0===c?void 0:c.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.focusBorderColor),backgroundColor:(null==e?void 0:e.fastlaneInputSettingsBackgroundColor)||(null===(u=null==t?void 0:t.input)||void 0===u?void 0:u.backgroundColor),borderWidth:(null==e?void 0:e.fastlaneInputSettingsBorderWidth)||(null===(h=null==t?void 0:t.input)||void 0===h?void 0:h.borderWidth),textColorBase:(null==e?void 0:e.fastlaneInputSettingsTextColorBase)||(null===(p=null==t?void 0:t.input)||void 0===p?void 0:p.textColorBase)},toggle:{colorPrimary:(null==e?void 0:e.fastlaneToggleSettingsColorPrimary)||(null===(m=null==t?void 0:t.toggle)||void 0===m?void 0:m.colorPrimary),colorSecondary:(null==e?void 0:e.fastlaneToggleSettingsColorSecondary)||(null===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(S=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===S?void 0:S.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(w=null===(_=null==t?void 0:t.text)||void 0===_?void 0:_.caption)||void 0===w?void 0:w.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(I=null==t?void 0:t.text)||void 0===I?void 0:I.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var od=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ad{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalSdkScriptLoader=t,this.paypalFastlaneUtils=n}initialize(e){var t;return od(this,void 0,void 0,function*(){const{methodId:n,paypalcommercefastlane:i}=e;if(!n)throw new fi('Unable to proceed because "methodId" argument is not provided.');try{yield this.paymentIntegrationService.loadPaymentMethod(n);const e=this.paymentIntegrationService.getState(),r=e.getCartOrThrow(),o=e.getPaymentMethodOrThrow(n),a=!!(null===(t=o.initializationData)||void 0===t?void 0:t.isDeveloperModeApplicable),s=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(o,r.currency.code,r.id,e.getLocale());yield this.paypalFastlaneUtils.initializePayPalFastlane(s,a,this.getFastlaneStyles(n,i))}catch(e){}return Promise.resolve()})}deinitialize(){return od(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return od(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:void 0,addresses:void 0,instruments:void 0}),this.paypalFastlaneUtils.removeStorageSessionId()})}signOut(e){return od(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return od(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:n,methodId:i}=e||{};if(!i)throw new fi('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof n)throw new fi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(this.paymentIntegrationService.getState().getCustomerOrThrow().isGuest){t&&"function"==typeof t&&t();try{yield this.runPayPalAuthenticationFlowOrThrow(i)}catch(e){}}n()})}runPayPalAuthenticationFlowOrThrow(e){return od(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow().id,i=t.getCustomer(),r=t.getBillingAddress(),o=(null==i?void 0:i.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.paypalFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.paypalFastlaneUtils.triggerAuthenticationFlowOrThrow(a),d=s.authenticationState===fs.CANCELED;yield this.updateCustomerDataState(e,s),d?this.paypalFastlaneUtils.removeStorageSessionId():this.paypalFastlaneUtils.updateStorageSessionId(n)})}updateCustomerDataState(e,t){var n;return od(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow(),{authenticationState:r,addresses:o,billingAddress:a,shippingAddress:s,instruments:d}=this.paypalFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,t);if(yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:r,addresses:o,instruments:d}),a&&(yield this.paymentIntegrationService.updateBillingAddress(a)),s&&i.lineItems.physicalItems.length>0){const t=yield this.paymentIntegrationService.updateShippingAddress(s),i=t.getPaymentMethodOrThrow(e),{isFastlaneShippingOptionAutoSelectEnabled:r}=i.initializationData||{},o=t.getConsignments()||[],a=(null===(n=o[0])||void 0===n?void 0:n.availableShippingOptions)||[],d=a[0],c=a.find(e=>e.isRecommended);if((c||d)&&r){const e=(null==c?void 0:c.id)||d.id;yield this.paymentIntegrationService.selectShippingOption(e)}}})}getFastlaneStyles(e,t){const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{fastlaneStyles:i,isFastlaneStylingEnabled:r}=n.initializationData||{};return rd(r?i:{},null==t?void 0:t.styles)}}const sd=vi(e=>new ad(e,Cs(),nd()),[{id:"paypalcommerceacceleratedcheckout"},{id:"paypalcommercecreditcards"}]);function dd(e){return"object"==typeof e&&null!==e&&"initializationData"in e&&void 0!==e.initializationData&&null!==e.initializationData&&"object"==typeof e.initializationData&&"stripePublishableKey"in e.initializationData&&"stripeConnectedAccount"in e.initializationData&&"shopperLanguage"in e.initializationData&&void 0!==e.initializationData.stripePublishableKey&&void 0!==e.initializationData.stripeConnectedAccount&&void 0!==e.initializationData.shopperLanguage}function cd(e){return"stripeLinkAuthenticationState"in e}class ld{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){var t,n,i,r,o;return n=this,i=void 0,o=function*(){let n;if(!e.stripeupe)throw new fi('Unable to proceed because "options" argument is not provided.');const{container:i,gatewayId:r,methodId:o,onEmailChange:a,getStyles:s,isLoading:d}=e.stripeupe;Object.entries(e.stripeupe).forEach(([e,t])=>{if(!t)throw new fi(`Unable to proceed because "${e}" argument is not provided.`)}),yield this.paymentIntegrationService.loadPaymentMethod(r,{params:{method:o}});const c=this.paymentIntegrationService.getState(),l=c.getPaymentMethodOrThrow(o,r),{clientToken:u}=l;if(!dd(l)||!u)throw new ti(Xn.MissingPaymentToken);const{email:h}=c.getCustomerOrThrow(),p=c.getPaymentProviderCustomerOrThrow(),m=(cd(p)?p:{}).stripeLinkAuthenticationState;if(!h){let e;const r="function"==typeof s&&s();e=r?{variables:{colorPrimary:r.fieldInnerShadow,colorBackground:r.fieldBackground,colorText:r.labelText,colorDanger:r.fieldErrorText,colorTextSecondary:r.labelText,colorTextPlaceholder:r.fieldPlaceholderText},rules:{".Input":{borderColor:r.fieldBorder,color:r.fieldText,boxShadow:r.fieldInnerShadow}}}:{},n=yield this.scriptLoader.getStripeClient(l.initializationData,c.getCartLocale(),ka.V3,Fa,La),this._stripeElements=yield this.scriptLoader.getElements(n,{clientSecret:u,appearance:e});const{getBillingAddress:o,getConsignments:h}=this.paymentIntegrationService.getState(),p=h(),y=null===(t=null==p?void 0:p[0])||void 0===t?void 0:t.id,{email:g}=o()||{},v=g?{defaultValues:{mode:Ca.SHIPPING,email:g}}:{},f=this._stripeElements.getElement(Da.AUTHENTICATION)||this._stripeElements.create(Da.AUTHENTICATION,v);f.on(za.CHANGE,e=>{if(!("authenticated"in e))throw new ti(Xn.MissingCustomer);this.paymentIntegrationService.updatePaymentProviderCustomer({stripeLinkAuthenticationState:e.authenticated}),e.complete?a(e.authenticated,e.value.email):a(!1,""),d&&d(!1),void 0===m&&e.authenticated&&y&&this.paymentIntegrationService.deleteConsignment(y)}),f.mount(`#${i}`)}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}deinitialize(){var e,t;return null===(t=null===(e=this._stripeElements)||void 0===e?void 0:e.getElement(Da.AUTHENTICATION))||void 0===t||t.unmount(),Promise.resolve()}signIn(e,t){return this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()}signOut(e){return this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}}const ud=vi(e=>new ld(e,new Ra(a())),[{id:"stripeupe"}]);var hd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pd{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t,this.isMounted=!1}deinitialize(){var e;null===(e=this.checkoutEventsUnsubscribe)||void 0===e||e.call(this),this.isMounted=!1}initCheckoutEventsSubscription(e,t,n,i){this.checkoutEventsUnsubscribe=this.paymentIntegrationService.subscribe(()=>hd(this,void 0,void 0,function*(){var r;const o=null==i?void 0:i.getElement(Da.PAYMENT);if(o){try{yield this.updateStripePaymentIntent(e,t)}catch(e){return this.isMounted&&(o.unmount(),this.isMounted=!1),void(e instanceof Error&&(null===(r=n.onError)||void 0===r||r.call(n,e)))}this.isMounted||(yield null==i?void 0:i.fetchUpdates(),this.mountElement(o,n.containerId))}}),e=>{var t;return null===(t=e.getCheckout())||void 0===t?void 0:t.outstandingBalance},e=>{var t;return null===(t=e.getCheckout())||void 0===t?void 0:t.coupons})}mountElement(e,t){document.getElementById(t)&&(e.mount(`#${t}`),this.isMounted=!0)}mapAppearanceVariables(e){return{colorPrimary:e.fieldInnerShadow,colorBackground:e.fieldBackground,colorText:e.labelText,colorDanger:e.fieldErrorText,colorTextSecondary:e.labelText,colorTextPlaceholder:e.fieldPlaceholderText,colorIcon:e.fieldPlaceholderText}}mapInputAppearanceRules(e){return{borderColor:e.fieldBorder,color:e.fieldText,boxShadow:e.fieldInnerShadow}}throwStripeError(e){if("object"==typeof(t=e)&&null!==t&&"type"in t&&(this.throwDisplayableStripeError(e),this.isCancellationError(e)))throw new Wi;var t;throw new Qr}throwDisplayableStripeError(e){if(H(["card_error","invalid_request_error","validation_error"],e.type))throw new Error(e.message)}isCancellationError(e){var t;const n=null===(t=null==e?void 0:e.payment_intent.last_payment_error)||void 0===t?void 0:t.message;return!!n&&-1!==n.indexOf("canceled")}throwPaymentConfirmationProceedMessage(){throw new Qr("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.")}isPaymentCompleted(e,t){return hd(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getPaymentMethodOrThrow(e),{features:r}=n.getStoreConfigOrThrow().checkoutSettings;if(!i.clientToken||!t||!r["PI-626.Block_unnecessary_payment_confirmation_for_StripeUPE"])return!1;const{paymentIntent:o}=yield t.retrievePaymentIntent(i.clientToken);return(null==o?void 0:o.status)===Ma.SUCCEEDED})}mapStripePaymentData(e,t,n=!1){const i=this.paymentIntegrationService.getState().getBillingAddress(),{firstName:r="",lastName:o="",email:a=""}=i||{},s=this.mapStripeAddress(i);if(!e)throw new ri(ei.PaymentNotInitialized);if(!(a&&s&&s.city&&s.country&&r&&o))throw new ti(Xn.MissingBillingAddress);return{elements:e,redirect:Ta.IF_REQUIRED,confirmParams:Object.assign({payment_method_data:Object.assign(Object.assign({},n?{allow_redisplay:"always"}:{}),{billing_details:{email:a,address:s,name:this.getShopperFullName(i)}})},t&&{return_url:t})}}isAdditionalActionError(e){return ve(e,{code:"additional_action_required"})}isRedirectAction(e){const{type:t,data:{redirect_url:n}}=e;return"redirect_to_url"===t&&!!n}isOnPageAdditionalAction(e){const{type:t,data:{token:n}}=e;return"additional_action_requires_payment_method"===t&&!!n}updateStripePaymentIntent(e,t){return hd(this,void 0,void 0,function*(){const n=yield this.paymentIntegrationService.loadPaymentMethod(e,{params:{method:t}}),{clientToken:i}=n.getPaymentMethodOrThrow(t);i&&this.scriptLoader.updateStripeElements({clientSecret:i})})}getStripeJsVersion(e){return e.useNewStripeJsVersion?ka.CLOVER:ka.V3}mapStripeAddress(e){if(e){const{city:t,address1:n,address2:i,countryCode:r,postalCode:o,stateOrProvinceCode:a}=e;return Object.assign({city:t,country:r,postal_code:o,line1:n,line2:i},a?{state:a}:{})}throw new ti(Xn.MissingBillingAddress)}getShopperFullName(e){const{firstName:t="",lastName:n=""}=e||{};return`${t} ${n}`.trim()}}const md={size:70,color:"#d9d9d9",backgroundColor:"#ffffff"},yd={position:"fixed","background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},gd="embedded-checkout-loading-indicator-rotation";class vd{constructor(e){this.styles=Object.assign(Object.assign({},md),e&&e.styles),this.containerStyles=Object.assign({},e&&e.containerStyles),this.defineAnimation(),this.container=this.buildContainer(),this.indicator=this.buildIndicator(),this.container.appendChild(this.indicator)}show(e){if(e){const t=document.getElementById(e);if(!t)throw new Error("Unable to attach the loading indicator because the parent ID is not valid.");t.appendChild(this.container)}this.container.style.visibility="visible",this.container.style.opacity="1"}hide(){const e=()=>{this.container.style.visibility="hidden",this.container.removeEventListener("transitionend",e)};this.container.addEventListener("transitionend",e),this.container.style.opacity="0"}buildContainer(){const e=document.createElement("div");return e.style.display="block",e.style.bottom="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.position="absolute",e.style.right="0",e.style.top="0",e.style.transition="all 250ms ease-out",e.style.opacity="0",this.setStyleAttribute(e,this.containerStyles),e}buildIndicator(){const e=document.createElement("div");return e.style.display="block",e.style.width=`${this.styles.size}px`,e.style.height=`${this.styles.size}px`,e.style.borderRadius=`${this.styles.size}px`,e.style.border="solid 1px",e.style.borderColor=`${this.styles.backgroundColor} ${this.styles.backgroundColor} ${this.styles.color} ${this.styles.color}`,e.style.margin="0 auto",e.style.position="absolute",e.style.left="0",e.style.right="0",e.style.top="50%",e.style.transform="translateY(-50%) rotate(0deg)",e.style.transformStyle="preserve-3d",e.style.animation=`${gd} 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)`,e}setStyleAttribute(e,t){Object.keys(t).forEach(n=>{e.style.setProperty(n,t[n])})}defineAnimation(){var e;if(document.getElementById(gd))return;const t=document.createElement("style");t.id=gd,null===(e=document.head)||void 0===e||e.appendChild(t),t.sheet instanceof CSSStyleSheet&&t.sheet.insertRule(`\n @keyframes ${gd} {\n 0% { transform: translateY(-50%) rotate(0deg); }\n 100% { transform: translateY(-50%) rotate(360deg); }\n }\n `,0)}}class fd{constructor(e){this._decimalPlaces=e}toInteger(e){return Math.round(e*Math.pow(10,this._decimalPlaces))}}const Sd=["AC","AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CV","CW","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MK","ML","MM","MN","MO","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SZ","TA","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","US","UY","UZ","VA","VC","VE","VG","VN","VU","WF","WS","XK","YE","YT","ZA","ZM","ZW","ZZ"];var _d=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class wd{constructor(e,t,n,i){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n,this.loadingIndicator=i}initialize(e){return _d(this,void 0,void 0,function*(){const{stripeocs:t}=e||{};if(!t)throw new fi('Unable to proceed because "options" argument is not provided.');const{gatewayId:n,container:i}=t;if(!i||!n)throw new ri(ei.PaymentNotInitialized);const r=this._getMethodId(n),o=yield this.paymentIntegrationService.loadPaymentMethod(n,{params:{method:r}}),a=o.getPaymentMethodOrThrow(r,n),{loadingContainerId:s,buttonHeight:d,onComplete:c}=t;if(this._loadingIndicatorContainer=s,this._onComplete=c,!dd(a))throw new ti(Xn.MissingPaymentMethod);const{initializationData:l}=a,{captureMethod:u}=l,h=this.stripeIntegrationService.getStripeJsVersion(l);this._captureMethod=u,this._stripeClient=yield this.scriptLoader.getStripeClient(l,o.getCartLocale(),h),yield this._mountExpressCheckoutElement(i,this._stripeClient,d),this._initializeEvents(r)})}signIn(){return Promise.resolve()}signOut(){return Promise.resolve()}executePaymentMethodCheckout(){return Promise.resolve()}deinitialize(){return Promise.resolve()}_mountExpressCheckoutElement(e,t,n=40){return _d(this,void 0,void 0,function*(){const i=this._shouldRequireShippingAddress(),r=Object.assign(Object.assign(Object.assign({shippingAddressRequired:i},i?{allowedShippingCountries:yield this._getAvailableCountries()}:{}),i?{shippingRates:[{id:"_",amount:0,displayName:"Pending rates"}]}:{}),{billingAddressRequired:!0,emailRequired:!0,phoneNumberRequired:!0,paymentMethods:{link:Ta.AUTO,applePay:Ta.NEVER,googlePay:Ta.NEVER,amazonPay:Ta.NEVER,paypal:Ta.NEVER,klarna:Ta.NEVER},buttonHeight:n}),{cartAmount:o}=this.paymentIntegrationService.getState().getCartOrThrow(),a=Object.assign({mode:"payment",amount:this._toCents(o),currency:this._getCurrency()},this._captureMethod?{captureMethod:this._captureMethod}:{});return this._stripeElements=t.elements(a),this._linkV2Element=this._stripeElements.create(Da.EXPRESS_CHECKOUT,r),this._linkV2Element.mount(`#${e}`),this._linkV2Element})}_initializeEvents(e){this._linkV2Element&&(this._shouldRequireShippingAddress()&&(this._linkV2Element.on(za.SHIPPING_ADDRESS_CHANGE,e=>_d(this,void 0,void 0,function*(){return this._onShippingAddressChange(e)})),this._linkV2Element.on(za.SHIPPING_RATE_CHANGE,e=>_d(this,void 0,void 0,function*(){return this._onShippingRateChange(e)}))),this._linkV2Element.on(za.CONFIRM,t=>_d(this,void 0,void 0,function*(){return this._onConfirm(t,e)})),this._linkV2Element.on(za.CANCEL,this._onCancel))}_onShippingAddressChange(e){return _d(this,void 0,void 0,function*(){if(!("address"in e))return;const t=e.address,n={firstName:"",lastName:"",phone:"",company:"",address1:"",address2:"",city:(null==t?void 0:t.city)||"",countryCode:(null==t?void 0:t.country)||"",postalCode:(null==t?void 0:t.postal_code)||"",stateOrProvince:(null==t?void 0:t.state)||"",stateOrProvinceCode:(null==t?void 0:t.state)||"",customFields:[]};yield this.paymentIntegrationService.updateShippingAddress(n);const i=yield this._getAvailableShippingOptions();yield this._updateDisplayedPrice(),(null==i?void 0:i.length)?e.resolve({shippingRates:i}):e.reject()})}_onCancel(){throw new Wi}_onShippingRateChange(e){return _d(this,void 0,void 0,function*(){if("shippingRate"in e){const{shippingRate:t}=e;yield this._handleShippingOptionChange(null==t?void 0:t.id),yield this._updateDisplayedPrice(),e.resolve({})}})}_onConfirm(e,t){return _d(this,void 0,void 0,function*(){if("billingDetails"in e&&"shippingAddress"in e&&this._stripeClient&&this._stripeElements){yield this._updateShippingAndBillingAddress(e),yield this.paymentIntegrationService.submitOrder();const n=this._getPaymentPayload(t);try{yield this.paymentIntegrationService.submitPayment(n)}catch(e){yield this._processAdditionalAction(e,t)}}return Promise.resolve()})}_updateShippingAndBillingAddress(e){var t,n,i,r,o,a,s,d;return _d(this,void 0,void 0,function*(){const c=this._shouldRequireShippingAddress(),l=(null===(n=null===(t=e.shippingAddress)||void 0===t?void 0:t.name)||void 0===n?void 0:n.split(" ")[0])||(null===(r=null===(i=e.billingDetails)||void 0===i?void 0:i.name)||void 0===r?void 0:r.split(" ")[0])||"",u=(null===(a=null===(o=e.shippingAddress)||void 0===o?void 0:o.name)||void 0===a?void 0:a.split(" ")[1])||(null===(d=null===(s=e.billingDetails)||void 0===s?void 0:s.name)||void 0===d?void 0:d.split(" ")[1])||"";if(c){const t=this._mapShippingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateShippingAddress(t)}const h=this._mapBillingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateBillingAddress(h)})}_mapShippingAddress(e,t,n,i){var r,o,a,s,d,c,l;return{firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==e?void 0:e.address)||void 0===r?void 0:r.line1)||"",address2:(null===(o=null==e?void 0:e.address)||void 0===o?void 0:o.line2)||"",city:(null===(a=null==e?void 0:e.address)||void 0===a?void 0:a.city)||"",countryCode:(null===(s=null==e?void 0:e.address)||void 0===s?void 0:s.country)||"",postalCode:(null===(d=null==e?void 0:e.address)||void 0===d?void 0:d.postal_code)||"",stateOrProvince:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",stateOrProvinceCode:(null===(l=null==e?void 0:e.address)||void 0===l?void 0:l.state)||"",customFields:[]}}_mapBillingAddress(e,t,n,i){var r,o,a,s,d,c;return{email:(null==t?void 0:t.email)||"",firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==t?void 0:t.address)||void 0===r?void 0:r.line1)||"",address2:"",city:(null===(o=null==t?void 0:t.address)||void 0===o?void 0:o.city)||"",countryCode:(null===(a=null==t?void 0:t.address)||void 0===a?void 0:a.country)||"",postalCode:(null===(s=null==t?void 0:t.address)||void 0===s?void 0:s.postal_code)||"",stateOrProvince:(null===(d=null==t?void 0:t.address)||void 0===d?void 0:d.state)||"",stateOrProvinceCode:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",customFields:[]}}_processAdditionalAction(e,t){return _d(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeClient||!this._stripeElements)throw new ri(ei.PaymentNotInitialized);const{data:n}=e.body.additional_action_required,{token:i}=n,{paymentIntent:r}=yield this._confirmStripePaymentOrThrow(n,t),o=this._getPaymentPayload(t,(null==r?void 0:r.id)||i);try{this._toggleLoadingIndicator(!0),yield this.paymentIntegrationService.submitPayment(o),yield this._completeCheckoutFlow()}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}finally{this._toggleLoadingIndicator(!1)}})}_confirmStripePaymentOrThrow(e,t){var n,i,r;return _d(this,void 0,void 0,function*(){const{token:o,redirect_url:a}=e,s=this.stripeIntegrationService.mapStripePaymentData(this._stripeElements,a);let d;try{const e=(yield this.stripeIntegrationService.isPaymentCompleted(t,this._stripeClient))?yield null===(r=this._stripeClient)||void 0===r?void 0:r.retrievePaymentIntent(o||""):yield null===(n=this._stripeClient)||void 0===n?void 0:n.confirmPayment({elements:s.elements,clientSecret:o,redirect:Ta.IF_REQUIRED,confirmParams:{return_url:null===(i=s.confirmParams)||void 0===i?void 0:i.return_url}});if(d=null==e?void 0:e.error,d||!(null==e?void 0:e.paymentIntent))throw new Qr;return e}catch(e){return this.stripeIntegrationService.throwStripeError(d)}})}_completeCheckoutFlow(){return _d(this,void 0,void 0,function*(){return"function"==typeof this._onComplete?this._onComplete():(window.location.replace("/order-confirmation"),Promise.resolve())})}_getPaymentPayload(e,t){var n;const i=(null===(n=this.paymentIntegrationService.getState().getCart())||void 0===n?void 0:n.id)||"";return{methodId:e,paymentData:{formattedPayload:Object.assign(Object.assign({cart_id:i},t?{credit_card_token:{token:t}}:{}),{confirm:!1,method:Aa.Link})}}}_shouldRequireShippingAddress(){const{getCartOrThrow:e}=this.paymentIntegrationService.getState(),{lineItems:t}=e();return!!t.physicalItems.length}_updateDisplayedPrice(){return _d(this,void 0,void 0,function*(){this._stripeElements&&this._stripeElements.update({currency:this._getCurrency(),mode:"payment",amount:yield this._getTotalPrice()})})}_getCurrency(){if(!this._currencyCode){const{code:e}=this.paymentIntegrationService.getState().getCartOrThrow().currency;this._currencyCode=e.toLowerCase()}return this._currencyCode}_getTotalPrice(){return _d(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const{getCheckoutOrThrow:e,getCartOrThrow:t}=this.paymentIntegrationService.getState(),{decimalPlaces:n}=t().currency,i=ge(e().outstandingBalance,n).toFixed(n);return this._toCents(+i)})}_getAvailableCountries(){var e;return _d(this,void 0,void 0,function*(){const t=yield this.paymentIntegrationService.loadShippingCountries();return((null===(e=t.getShippingCountries())||void 0===e?void 0:e.map(e=>e.code))||[]).filter(e=>Sd.includes(e))})}_getAvailableShippingOptions(){var e,t,n;return _d(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getConsignments();if(!(null==i?void 0:i[0]))return;const r=i[0],o=(r.availableShippingOptions||[]).map(this._getStripeShippingOption.bind(this)),a=null===(e=r.availableShippingOptions)||void 0===e?void 0:e.find(e=>e.isRecommended),s=null===(t=r.selectedShippingOption)||void 0===t?void 0:t.id,d=null==a?void 0:a.id;return s?o.sort(e=>e.id===s?-1:0):d?(o.sort(e=>e.id===d?-1:0),yield this._handleShippingOptionChange(d)):yield this._handleShippingOptionChange(null===(n=o[0])||void 0===n?void 0:n.id),o.slice(0,9)})}_getStripeShippingOption({id:e,cost:t,description:n}){return{id:e,displayName:n,amount:this._toCents(t)}}_handleShippingOptionChange(e){return _d(this,void 0,void 0,function*(){if(e&&"shipping_option_unselected"!==e)return this.paymentIntegrationService.selectShippingOption(e)})}_getAmountTransformer(){if(this._amountTransformer)return this._amountTransformer;const{getCart:e}=this.paymentIntegrationService.getState(),{currency:t}=e()||{};return t?new fd(t.decimalPlaces):void 0}_toCents(e){const t=Math.round(100*e),n=this._getAmountTransformer();return n?n.toInteger(e):t}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this.loadingIndicator.show(this._loadingIndicatorContainer):this.loadingIndicator.hide()}_getMethodId(e){const{initializationData:{checkoutSessionEnabled:t}={}}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e);return t?Aa.CHECKOUT_SESSION:Aa.OCS}}const Id=vi(e=>{const t=new Ra(a()),n=new vd({containerStyles:yd});return new wd(e,t,new pd(e,t),n)},[{id:"stripeocs"}]);class Cd extends Qn{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}class bd{constructor(e){this._paymentIntegrationService=e}execute(e,t){return n=this,i=void 0,o=function*(){yield this._paymentIntegrationService.submitOrder(le(e,"payment"),t)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const Pd=vi(e=>new bd(e),[{id:"nopaymentdatarequired"}]);var Od,Ed,Ad,Td,kd,Dd,Md;class zd{constructor(e,t,n=window){this._scriptLoader=e,this._stylesheetLoader=t,this._window=n}load(e){var t,n,i,r,o,a;return i=this,r=void 0,a=function*(){if(yield Promise.all([this._stylesheetLoader.loadStylesheet(`https://checkoutshopper-${null!==(t=e.environment)&&void 0!==t?t:""}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.css`,{prepend:!1,attributes:{integrity:"sha384-8ofgICZZ/k5cC5N7xegqFZOA73H9RQ7H13439JfAZW8Gj3qjuKL2isaTD3GMIhDE",crossorigin:"anonymous"}}),this._scriptLoader.loadScript(`https://checkoutshopper-${null!==(n=e.environment)&&void 0!==n?n:""}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.js`,{async:!0,attributes:{integrity:"sha384-wG2z9zSQo61EIvyXmiFCo+zB3y0ZB4hsrXVcANmpP8HLthjoQJQPBh7tZKJSV8jA",crossorigin:"anonymous"}})]),!this._window.AdyenCheckout)throw new mi;return new this._window.AdyenCheckout(e)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}}function Nd(e){return"object"==typeof e&&"string"==typeof e.data.paymentMethod.encryptedSecurityCode||"string"==typeof e.data.paymentMethod.encryptedExpiryMonth}function xd(e){return Boolean(e.instrumentId)}!function(e){e.ThreeDS2Fingerprint="threeDS2Fingerprint",e.ThreeDS2="threeDS2",e.Redirect="redirect",e.QRCode="qrCode",e.Voucher="voucher",e.Sdk="sdk"}(Od||(Od={})),function(e){e.ThreeDS2Fingerprint="threeDS2Fingerprint",e.ThreeDS2Challenge="threeDS2Challenge",e.Redirect="redirect",e.QRCode="qrCode",e.Voucher="voucher"}(Ed||(Ed={})),function(e){e.SecuredFields="securedfields"}(Ad||(Ad={})),function(e){e.ACH="ach",e.AliPay="alipay",e.Bancontact="bcmc",e.CreditCard="scheme",e.Klarna="klarna",e.KlarnaPayNow="klarna_paynow",e.KlarnaAccount="klarna_account",e.IDEAL="ideal",e.GiroPay="giropay",e.GooglePay="paywithgoogle",e.SEPA="sepadirectdebit",e.Sofort="directEbanking",e.Vipps="vipps",e.WeChatPayQR="wechatpayQR"}(Td||(Td={})),function(e){e.POST="POST"}(kd||(kd={})),function(e){e.ChallengeShopper="ChallengeShopper",e.Error="Error",e.IdentifyShopper="IdentifyShopper"}(Dd||(Dd={})),function(e){e.CardNumber="encryptedCardNumber",e.SecurityCode="encryptedSecurityCode",e.ExpiryDate="encryptedExpiryDate"}(Md||(Md={}));var Rd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Fd{constructor(e,t){this._paymentIntegrationService=e,this._scriptLoader=t}initialize(e){return Rd(this,void 0,void 0,function*(){const{adyenv2:t}=e;if(!t)throw new fi('Unable to initialize payment because "options.adyenv2" argument is not provided.');this._paymentInitializeOptions=t;const n=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{originKey:i,clientKey:r,environment:o,paymentMethodsResponse:a}=n.initializationData||{},s={key:"",value:""};return i?(s.key="originKey",s.value=i):(s.key="clientKey",s.value=r||""),this._adyenClient=yield this._scriptLoader.load({environment:o,locale:this._paymentIntegrationService.getState().getLocale(),[s.key]:s.value,paymentMethodsResponse:a,translations:{es:{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-AR":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-ES":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-MX":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CL":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CO":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-PE":{"creditCard.expiryDateField.title":"Fecha de caducidad"}}}),this._paymentComponent=yield this._mountPaymentComponent(n),n.method!==Td.CreditCard&&n.method!==Td.Bancontact||(this._cardVerificationComponent=yield this._mountCardVerificationComponent()),Promise.resolve()})}execute(e,t){return Rd(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const{threeDS2ContainerId:i,additionalActionOptions:r}=this._getPaymentInitializeOptions(),{onBeforeLoad:o,containerId:a,onLoad:s,onComplete:d}=r,c=JSON.parse(e.action),l=this._getAdyenClient().createFromAction(c,{onAdditionalDetails:e=>{const n={methodId:c.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};d&&d(),t(n)},size:this._getThreeDS2ChallengeWidgetSize(),onError:e=>n(e)});o&&o(c.type===Ed.ThreeDS2Challenge||c.type===Ed.QRCode),l.mount(`#${a||i}`),s&&s(()=>{n(new Wi),l.unmount()})})}_mapAdyenPlaceholderData(e,t){if(!e)return{};const{firstName:n,lastName:i,address1:r,address2:o,postalCode:a,city:s,stateOrProvinceCode:d,countryCode:c}=e;return{holderName:t?`${n} ${i}`:"",billingAddress:{street:r,houseNumberOrName:o,postalCode:a,city:s,stateOrProvince:d,country:c}}}_mountCardVerificationComponent(){const e=this._getPaymentInitializeOptions(),t=this._getAdyenClient();let n;return new Promise((i,r)=>{var o,a,s;if(e.cardVerificationContainerId){n=t.create(Ad.SecuredFields,Object.assign(Object.assign({},e.options),{styles:Object.assign(Object.assign({},null===(o=e.options)||void 0===o?void 0:o.styles),{placeholder:Object.assign({color:"transparent",caretColor:"#000"},null===(s=null===(a=e.options)||void 0===a?void 0:a.styles)||void 0===s?void 0:s.placeholder)}),onChange:e=>this._updateComponentState(e),onError:t=>e.validateCardFields(t),onFieldValid:t=>e.validateCardFields(t)}));try{n.mount(`#${e.cardVerificationContainerId}`)}catch(e){r(new ri(ei.PaymentNotInitialized))}}i(n)})}_mountPaymentComponent(e){let t;const n=this._getPaymentInitializeOptions(),i=this._getAdyenClient();return new Promise((r,o)=>{switch(e.method){case Td.CreditCard:case Td.ACH:case Td.Bancontact:{const r=this._paymentIntegrationService.getState().getBillingAddress(),{prefillCardHolderName:a}=e.initializationData;t=i.create(e.method,Object.assign(Object.assign({},n.options),{onChange:e=>this._updateComponentState(e),data:this._mapAdyenPlaceholderData(r,a)}));try{t.mount(`#${n.containerId}`)}catch(e){o(new ri(ei.PaymentNotInitialized))}break}case Td.IDEAL:case Td.SEPA:if(n.hasVaultedInstruments)this._updateComponentState({data:{paymentMethod:{type:e.method}}});else{t=i.create(e.method,Object.assign(Object.assign({},n.options),{onChange:e=>this._updateComponentState(e)}));try{t.mount(`#${n.containerId}`)}catch(e){o(new ri(ei.PaymentNotInitialized))}}break;case Td.AliPay:case Td.GiroPay:case Td.Sofort:case Td.Klarna:case Td.KlarnaPayNow:case Td.KlarnaAccount:case Td.Vipps:case Td.WeChatPayQR:this._updateComponentState({data:{paymentMethod:{type:e.method}}})}r(t)})}_processAdditionalAction(e,t,n){return Rd(this,void 0,void 0,function*(){if(!pa(e)||!ve(e.body.errors,{code:"additional_action_required"}))throw e;const i=yield this._handleAction(e.body.provider_data);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:Object.assign(Object.assign({},i.paymentData),{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n})}))}catch(e){return this._processAdditionalAction(e,t,n)}})}_updateComponentState(e){this._componentState=e}_validateCardData(){var e,t;const n=this._getPaymentInitializeOptions().hasVaultedInstruments?this._cardVerificationComponent:this._paymentComponent;if((null===(e=null==n?void 0:n.componentRef)||void 0===e?void 0:e.showValidation)&&n.state&&(n.componentRef.showValidation(),0===Object.keys(n.state).length||!n.state.isValid&&!n.state.issuer||"sepadirectdebit"===(null===(t=n.props)||void 0===t?void 0:t.type)&&n.state.data&&Object.values(n.state.data).some(e=>0===e.toString().trim().length)))throw new lo(this._mapCardErrors(n.state.errors))}_mapCardErrors(e={}){const t={};return Object.keys(e).forEach(n=>{t[n]=[{message:e[n],type:n}]}),t}}const Ld=vi(e=>new Fd(e,new zd(a(),s())),[{gateway:"adyenv2"}]);class Bd{constructor(e,t,n=window){this._scriptLoader=e,this._stylesheetLoader=t,this._window=n}load(e){var t,n,i,r,o,a;return i=this,r=void 0,a=function*(){if(yield Promise.all([this._stylesheetLoader.loadStylesheet(`https://checkoutshopper-${null!==(t=e.environment)&&void 0!==t?t:""}.adyen.com/checkoutshopper/sdk/5.71.1/adyen.css`,{prepend:!1,attributes:{integrity:"sha384-5MvB4RnzvviA3VBT4KYABZ4HXNZG5LRqREEgd41xt/pf/QvKmsj2O9GuNuywRXx9",crossorigin:"anonymous"}}),this._scriptLoader.loadScript(`https://checkoutshopper-${null!==(n=e.environment)&&void 0!==n?n:""}.adyen.com/checkoutshopper/sdk/5.71.1/adyen.js`,{async:!0,attributes:{integrity:"sha384-yvY2yFNR4WqIjPqP9MzjI+gJimmaJnAvj4rLHKvgJbgFD5fMuf8zIJrFJOW8Lhhf",crossorigin:"anonymous"}})]),!this._window.AdyenCheckout)throw new mi;return yield this._window.AdyenCheckout(e)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}}function jd(e){return!("object"!=typeof e||null===e||void 0!==e.shouldSaveInstrument&&"boolean"!=typeof e.shouldSaveInstrument||void 0!==e.shouldSetAsDefaultInstrument&&"boolean"!=typeof e.shouldSetAsDefaultInstrument)}var Ud=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class qd{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){return Ud(this,void 0,void 0,function*(){const{adyenv3:t}=e;if(!t)throw new fi('Unable to initialize payment because "options.adyenv3" argument is not provided.');this.paymentInitializeOptions=t;const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{environment:i,clientKey:r,paymentMethodsResponse:o,installmentOptions:a}=n.initializationData||{};return this.adyenClient=yield this.scriptLoader.load({paymentMethodsConfiguration:Object.assign({klarna:{useKlarnaWidget:!0},klarna_account:{useKlarnaWidget:!0},klarna_paynow:{useKlarnaWidget:!0}},a?{card:{installmentOptions:Object.assign({showInstallmentAmounts:!0},a)}}:{}),environment:i,locale:this._getLocale(),clientKey:r,paymentMethodsResponse:o,showPayButton:!1,translations:{es:{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-AR":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-ES":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-MX":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CL":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CO":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-PE":{"creditCard.expiryDateField.title":"Fecha de caducidad"}}}),this.paymentComponent=yield this._mountPaymentComponent(n),n.method!==Td.CreditCard&&n.method!==Td.Bancontact||(this.cardVerificationComponent=yield this._mountCardVerificationComponent()),Promise.resolve()})}execute(e,t){var n;return Ud(this,void 0,void 0,function*(){const{payment:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const{additionalActionOptions:i}=this._getPaymentInitializeOptions(),{onBeforeLoad:r,containerId:o,onLoad:a,onComplete:s,widgetSize:d,onActionHandled:c}=i,l=JSON.parse(e.action),u=this._getAdyenClient().createFromAction(l,{onActionHandled:e=>{c&&"function"==typeof c&&"3DS2Fingerprint"!==e.componentType&&c()},onAdditionalDetails:e=>{const n={methodId:l.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};s&&"function"==typeof s&&s(),t(n)},challengeWindowSize:d||"05",onError:e=>n(e)});r&&"function"==typeof r&&r(l.type===Od.ThreeDS2||l.type===Od.QRCode||l.type===Od.Sdk),this._mountElement(u,o).then(()=>{a&&"function"==typeof a&&a(()=>{n(new Wi),u.unmount()})}).catch(n)})}_mapAdyenPlaceholderData(e,t){if(!e)return{};const{firstName:n,lastName:i,address1:r,address2:o,postalCode:a,city:s,stateOrProvinceCode:d,countryCode:c}=e;return{holderName:t?`${n} ${i}`:"",firstName:t?n:"",lastName:t?i:"",billingAddress:{street:r,houseNumberOrName:o,postalCode:a,city:s,stateOrProvince:d,country:c}}}_mountCardVerificationComponent(){var e,t,n;return Ud(this,void 0,void 0,function*(){const i=this._getPaymentInitializeOptions(),r=this._getAdyenClient();if(!i.cardVerificationContainerId)return;const o=r.create(Ad.SecuredFields,Object.assign(Object.assign({},i.options),{styles:Object.assign(Object.assign({},null===(e=i.options)||void 0===e?void 0:e.styles),{placeholder:Object.assign({color:"transparent",caretColor:"#000"},null===(n=null===(t=i.options)||void 0===t?void 0:t.styles)||void 0===n?void 0:n.placeholder)}),onChange:e=>this._updateComponentState(e),onError:e=>i.validateCardFields(e),onFieldValid:e=>i.validateCardFields(e)}));try{yield this._mountElement(o,i.cardVerificationContainerId)}catch(e){throw new ri(ei.PaymentNotInitialized)}return o})}_mountPaymentComponent(e){return Ud(this,void 0,void 0,function*(){const t=this._getPaymentInitializeOptions(),n=this._getAdyenClient(),i=this.paymentIntegrationService.getState().getBillingAddress(),{prefillCardHolderName:r}=e.initializationData,o=n.create(e.method,Object.assign(Object.assign(Object.assign(Object.assign({},this._isOneyPaymentMethod(e.method)?{visibility:{personalDetails:"hidden",billingAddress:"hidden",deliveryAddress:"hidden"}}:{}),t.options),{showBrandsUnderCardNumber:!1,billingAddressRequired:!1,showEmailAddress:!1,onChange:e=>this._updateComponentState(e),onSubmit:e=>this._updateComponentState(e)}),i?{data:this._mapAdyenPlaceholderData(i,r)}:{}));try{yield this._mountElement(o,t.containerId)}catch(e){throw new ri(ei.PaymentNotInitialized)}return o})}_isOneyPaymentMethod(e){return e.startsWith("facilypay")}_processAdditionalAction(e,t,n,i,r){return Ud(this,void 0,void 0,function*(){if(!pa(e)||!ve(e.body.errors,{code:"additional_action_required"}))throw e;const o=yield this._handleAction(e.body.provider_data);try{const e=Object.assign(Object.assign({},o.paymentData),{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n}),a=n&&!t?{instrumentId:i,formattedPayload:{bigpay_token:Object.assign(Object.assign({},r),{token:i})}}:{};yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},o),{paymentData:Object.assign(Object.assign({},e),a)}))}catch(e){return this._processAdditionalAction(e,t,n,i,r)}})}_validateCardData(){var e;const t=this._getPaymentInitializeOptions().hasVaultedInstruments?this.cardVerificationComponent:this.paymentComponent;if((null===(e=null==t?void 0:t.componentRef)||void 0===e?void 0:e.showValidation)&&t.state&&(t.componentRef.showValidation(),0===Object.keys(t.state).length||!t.state.isValid))throw new lo(this._mapCardErrors(t.state.errors))}_mapCardErrors(e={}){const t={};return Object.keys(e).forEach(n=>{t[n]=[{message:e[n],type:n}]}),t}_mountElement(e,t){return Ud(this,void 0,void 0,function*(){yield this._waitForMountContainer(t);try{e.mount(`#${t}`)}catch(e){throw new ri(ei.PaymentNotInitialized)}})}_waitForMountContainer(e){return Ud(this,void 0,void 0,function*(){const t=Math.ceil(qd.mountContainerMaxWaitMs/qd.mountContainerPollIntervalMs),n=qd.mountContainerPollIntervalMs;let i=0;const r=()=>Ud(this,void 0,void 0,function*(){if(i===t)throw new ri(ei.PaymentNotInitialized);document.getElementById(e)||(yield new Promise(e=>{setTimeout(e,n)}),i+=1,yield r())});yield r()})}}qd.mountContainerMaxWaitMs=5e3,qd.mountContainerPollIntervalMs=50;const Vd=vi(e=>new qd(e,new Bd(a(),s())),[{gateway:"adyenv3"}]);var Gd,Hd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Wd{constructor(e,t){this.paymentIntegrationService=e,this.affirmScriptLoader=t}initialize(e){return Hd(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadPaymentMethod(e.methodId);const t=this.paymentIntegrationService.getState(),{clientToken:n,config:{testMode:i}}=t.getPaymentMethodOrThrow(e.methodId);if(!n)throw new ti(Xn.MissingPaymentMethod);this.affirm=yield this.affirmScriptLoader.load(n,i)})}execute(e,t){var n;return Hd(this,void 0,void 0,function*(){const i=null===(n=e.payment)||void 0===n?void 0:n.methodId,{useStoreCredit:r}=e;if(!this.affirm)throw new ri(ei.PaymentNotInitialized);if(!i)throw new co(["payment.methodId"]);yield this.paymentIntegrationService.submitOrder({useStoreCredit:r},t);const o={methodId:i,paymentData:{nonce:(yield this.initializeAffirmCheckout()).checkout_token}};yield this.paymentIntegrationService.submitPayment(o)})}deinitialize(){return this.affirm&&(this.affirm=void 0),Promise.resolve()}finalize(){return Promise.reject(new Cd)}initializeAffirmCheckout(){var e;return null===(e=this.affirm)||void 0===e||e.checkout(this.getCheckoutInformation()),new Promise((e,t)=>{var n,i;null===(n=this.affirm)||void 0===n||n.checkout.open({onFail:e=>{"canceled"===e.reason?t(new Wi):t(new Xr)},onSuccess:t=>{e(t)}}),null===(i=this.affirm)||void 0===i||i.ui.error.on("close",()=>{t(new Wi)})})}getCheckoutInformation(){const e=this.paymentIntegrationService.getState(),t=e.getStoreConfig(),n=e.getConsignments(),i=e.getOrder(),r=e.getCart();if(!t)throw new ti(Xn.MissingCheckoutConfig);if(!i)throw new ti(Xn.MissingCheckout);const o=new fd(i.currency.decimalPlaces),a=this.getBillingAddress(),s=this.getShippingAddress(),d=jo(r,t)&&s?s:a;return{merchant:{user_confirmation_url:t.links.checkoutLink,user_cancel_url:t.links.checkoutLink,user_confirmation_url_action:"POST"},shipping:d,billing:a,items:this.getItems(o,i),metadata:{shipping_type:this.getShippingType(n),mode:"modal",platform_type:"BigCommerce",platform_version:"",platform_affirm:""},discounts:this.getDiscounts(o,i),order_id:i.orderId?i.orderId.toString():"",shipping_amount:o.toInteger(i.shippingCostTotal),tax_amount:o.toInteger(i.taxTotal),total:o.toInteger(i.orderAmount)}}getShippingType(e){if(!e)return"";const t=e[0];return(null==t?void 0:t.selectedShippingOption)?t.selectedShippingOption.type:""}getBillingAddress(){const e=this.paymentIntegrationService.getState().getBillingAddress();if(!e)throw new ti(Xn.MissingBillingAddress);return{name:{first:e.firstName,last:e.lastName,full:`${e.firstName} ${e.lastName}`},address:{line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,zipcode:e.postalCode,country:e.countryCode},phone_number:e.phone,email:e.email}}getShippingAddress(){const e=this.paymentIntegrationService.getState().getShippingAddress();if(e)return{name:{first:e.firstName,last:e.lastName,full:`${e.firstName} ${e.lastName}`},address:{line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,zipcode:e.postalCode,country:e.countryCode},phone_number:e.phone}}getItems(e,t){const n=[];return t.lineItems.physicalItems.forEach(t=>{n.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.salePrice),qty:t.quantity,item_image_url:t.imageUrl,item_url:t.url,categories:this.getCategories(t.categories)})}),t.lineItems.digitalItems.forEach(t=>{n.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.salePrice),qty:t.quantity,item_image_url:t.imageUrl,item_url:t.url,categories:this.getCategories(t.categories)})}),t.lineItems.giftCertificates.forEach(t=>{n.push({display_name:t.name,sku:"",unit_price:e.toInteger(t.amount),qty:1,item_image_url:"",item_url:""})}),t.lineItems.customItems&&t.lineItems.customItems.forEach(t=>{n.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.listPrice),qty:t.quantity,item_image_url:"",item_url:""})}),n}getDiscounts(e,t){const n={};return t.coupons.forEach(t=>{t.discountedAmount>0&&(n[t.code]={discount_amount:e.toInteger(t.discountedAmount),discount_display_name:t.displayName})}),t.discountAmount>0&&(n.DISCOUNTED_AMOUNT={discount_amount:e.toInteger(t.discountAmount),discount_display_name:"discount"}),n}getCategories(e){return e?e.map(e=>e.map(e=>e.name)):[[]]}}!function(e){e.PROD="//cdn1.affirm.com/js/v2/affirm.js",e.SANDBOX="//cdn1-sandbox.affirm.com/js/v2/affirm.js"}(Gd||(Gd={}));class $d{constructor(e=window){this.affirmWindow=e}load(e="",t){const n=t?Gd.SANDBOX:Gd.PROD;if(function(e,t,n,i,r,o,a){const s=e[n]||{},d=document.createElement(o),c=document.getElementsByTagName(o)[0],l=function(e,t,n){return function(){e[t]._.push([n,arguments])}};s[i]=l(s,i,"set");const u=s[i];s[r]={},s[r]._=[],u._=[],s._=[],s[r][a]=l(s,r,a),s.jsReady=function(){s._.push([a,arguments])};let h=0;for(const e="set add save post open empty reset on off trigger ready setProduct".split(" ");hnew Wd(e,new $d),[{id:"affirm"}]);class Kd extends Qn{constructor(e){super(e||"The current order could not be finalized successfully"),this.name="OrderFinalizationNotCompletedError",this.type="order_finalization_not_completed"}}var Jd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Zd{constructor(e,t){this._paymentIntegrationService=e,this._afterpayScriptLoader=t}initialize(e){var t;return Jd(this,void 0,void 0,function*(){const n=this._paymentIntegrationService.getState(),i=n.getPaymentMethod(e.methodId,e.gatewayId),r=(null===(t=n.getCart())||void 0===t?void 0:t.currency.code)||"",o=this._mapCurrencyToISO2(r),a=Ci(n.getStoreConfigOrThrow().checkoutSettings.features,"PI-4789.afterpay_script_use_https",!1);if(!i)throw new ti(Xn.MissingPaymentMethod);this._afterpaySdk=yield this._afterpayScriptLoader.load(i,o,a)})}deinitialize(){return this._afterpaySdk&&(this._afterpaySdk=void 0),Promise.resolve()}execute(e,t){var n;return Jd(this,void 0,void 0,function*(){if(!e.payment)throw new co(["payment.gatewayId","payment.methodId"]);const{gatewayId:i,methodId:r}=e.payment;if(!i||!r)throw new co(["payment.gatewayId","payment.methodId"]);const{useStoreCredit:o}=e;void 0!==o&&(yield this._paymentIntegrationService.applyStoreCredit(o)),yield this._loadPaymentMethod(i,r,t);const a=this._paymentIntegrationService.getState();yield this._paymentIntegrationService.validateCheckout(a.getCheckout(),t);const s=(null===(n=a.getCart())||void 0===n?void 0:n.currency.code)||"",d=this._mapCurrencyToISO2(s);return this._redirectToAfterpay(d,a.getPaymentMethod(r,i)),new Promise(()=>{})})}finalize(e){var t,n,i;return Jd(this,void 0,void 0,function*(){const r=this._paymentIntegrationService.getState(),o=r.getPaymentId(),a=r.getContextConfig();if(!o)throw new ti(Xn.MissingCheckout);if(!(null==a?void 0:a.payment.token))throw new ti(Xn.MissingCheckoutConfig);const s={methodId:o.providerId,paymentData:{nonce:a.payment.token}};yield this._paymentIntegrationService.submitOrder({},e);try{yield this._paymentIntegrationService.submitPayment(s)}catch(e){if(yield this._paymentIntegrationService.forgetCheckout(o.providerId),yield this._paymentIntegrationService.loadPaymentMethods(),pa(e))throw new Kd(null===(i=null===(n=null===(t=e.body)||void 0===t?void 0:t.errors)||void 0===n?void 0:n[0])||void 0===i?void 0:i.message)}})}_redirectToAfterpay(e,t){if(!this._afterpaySdk||!(null==t?void 0:t.clientToken))throw new ri(ei.PaymentNotInitialized);this._afterpaySdk.initialize({countryCode:e}),this._afterpaySdk.redirect({token:t.clientToken})}_mapCurrencyToISO2(e){return{AUD:"AU",NZD:"NZ",CAD:"CA",USD:"US"}[e]||"AU"}_loadPaymentMethod(e,t,n){var i;return Jd(this,void 0,void 0,function*(){try{return yield this._paymentIntegrationService.loadPaymentMethod(e,Object.assign(Object.assign({},n),{params:Object.assign(Object.assign({},null==n?void 0:n.params),{method:t})}))}catch(e){if(e instanceof nr&&422===(null===(i=e.body)||void 0===i?void 0:i.status))throw new fi("Afterpay can't process your payment for this order, please try another payment method");throw e}})}}var Qd,Xd;!function(e){e.PROD="//portal.afterpay.com/afterpay-async.js",e.SANDBOX="//portal.sandbox.afterpay.com/afterpay.js",e.HTTPS_PROD="https://portal.afterpay.com/afterpay-async.js",e.HTTPS_SANDBOX="https://portal.sandbox.afterpay.com/afterpay.js"}(Qd||(Qd={})),function(e){e.PROD="//portal.afterpay.com/afterpay-async.js",e.SANDBOX="//portal.sandbox.afterpay.com/afterpay.js",e.HTTPS_PROD="https://portal.afterpay.com/afterpay-async.js",e.HTTPS_SANDBOX="https://portal.sandbox.afterpay.com/afterpay.js"}(Xd||(Xd={}));class ec{constructor(e){this._scriptLoader=e}load(e,t,n=!1){return i=this,r=void 0,a=function*(){const i=e.config.testMode||!1,r=this._getScriptURI(t,i,n);return this._scriptLoader.loadScript(r).then(()=>{if(!function(e){return"AfterPay"in e}(window))throw new mi;return window.AfterPay})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a}_getScriptURI(e,t,n=!1){return"US"===e?n?t?Xd.HTTPS_SANDBOX:Xd.HTTPS_PROD:t?Xd.SANDBOX:Xd.PROD:n?t?Qd.HTTPS_SANDBOX:Qd.HTTPS_PROD:t?Qd.SANDBOX:Qd.PROD}}const tc=vi(e=>new Zd(e,new ec(o())),[{gateway:"afterpay"},{id:"afterpay"}]);var nc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ic{constructor(e,t){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t}initialize(e){return nc(this,void 0,void 0,function*(){const{methodId:t,amazonpay:n}=e;if(!t)throw new fi('Unable to proceed because "methodId" argument is not provided.');const i=this.paymentIntegrationService.getState(),{features:r}=i.getStoreConfigOrThrow().checkoutSettings,o=i.getPaymentMethodOrThrow(t),a=o.initializationData||{},{paymentToken:s="",region:d="",isButtonMicroTextDisabled:c}=a;if(yield this.amazonPayV2PaymentProcessor.initialize(o),this._isReadyToPay(s))(null==n?void 0:n.editButtonId)&&this._bindEditButton(n.editButtonId,s,"changePayment",this._isModalFlow(d));else{const{id:e}=this._createContainer();if(this._amazonPayButton=this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:i,containerId:e,decoupleCheckoutInitiation:this._isOneTimeTransaction(r,d.toUpperCase()),methodId:t,placement:si.Checkout,isButtonMicroTextDisabled:c}),!this._amazonPayButton)throw new fi("Unable to render the Amazon Pay button to an invalid HTML container element.")}})}execute(e,t){return nc(this,void 0,void 0,function*(){const{payment:n}=e;if(!n)throw new co(["payment"]);const{methodId:i}=n,r=this.paymentIntegrationService.getState(),{features:o}=r.getStoreConfigOrThrow().checkoutSettings,a=r.getPaymentMethodOrThrow(i).initializationData||{},{paymentToken:s="",region:d=""}=a;if(this._isReadyToPay(s)||this._isOneTimeTransaction(o,d.toUpperCase())){const n={methodId:i,paymentData:{nonce:s||"apb"}};yield this.paymentIntegrationService.submitOrder(e,t);try{return void(yield this.paymentIntegrationService.submitPayment(n))}catch(e){if(!(pa(e)&&(c=e.body,"object"==typeof c&&null!==c&&"status"in c&&"additional_action_required"in c&&"additional_action_required"===c.status&&"data"in c.additional_action_required&&"redirect_url"in c.additional_action_required.data&&"string"==typeof c.additional_action_required.data.redirect_url)))throw e;const{additional_action_required:t}=e.body,{redirect_url:n}=t.data;if(s)return new Promise(()=>window.location.assign(n));this.amazonPayV2PaymentProcessor.prepareCheckout(JSON.parse(n))}}var c;return this._getAmazonPayButton().click(),this._isModalFlow(d)?new Promise((e,t)=>{const n=()=>{window.removeEventListener("focus",n),t(new Wi("Shopper needs to login to Amazonpay to continue"))};window.addEventListener("focus",n)}):new Promise(ce)})}finalize(){return Promise.reject(new Cd)}deinitialize(){return nc(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize(),this._amazonPayButton=void 0})}_bindEditButton(e,t,n,i){const r=document.getElementById(e);if(r&&r.parentNode){if(!i){const e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener("click",()=>{this._showLoadingSpinner()})}this.amazonPayV2PaymentProcessor.bindButton(e,t,n)}}_isModalFlow(e){return"us"===e}_showLoadingSpinner(){return nc(this,void 0,void 0,function*(){yield this.paymentIntegrationService.widgetInteraction(()=>new Promise(ce))})}_createContainer(){let e=document.getElementById("AmazonPayButton");return e||(e=document.createElement("div"),e.id="AmazonPayButton",e.style.display="none",document.body.appendChild(e))}_getAmazonPayButton(){return ii(this._amazonPayButton,()=>new ri(ei.PaymentNotInitialized))}_isOneTimeTransaction(e,t){return this.amazonPayV2PaymentProcessor.isPh4Enabled(e,t)&&e["INT-6399.amazon_pay_apb"]}_isReadyToPay(e){return!!e}}const rc=vi(e=>new ic(e,gi()),[{id:"amazonpay"}]);var oc,ac=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.Shipping="Shipping",e.Subtotal="Subtotal",e.StoreCredit="Store Credit"}(oc||(oc={}));class sc{constructor(e,t,n,i,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._braintreeSdk=i,this._applePayScriptLoader=r,this._shippingLabel=oc.Shipping,this._subTotalLabel=oc.Subtotal,this._storeCreditLabel=oc.StoreCredit}initialize(e){var t,n,i,r;return ac(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new fi('Unable to submit payment because "options.methodId" argument is not provided.');const{methodId:o}=e;yield this._applePayScriptLoader.loadSdk(),this._shippingLabel=(null===(t=e.applepay)||void 0===t?void 0:t.shippingLabel)||oc.Shipping,this._subTotalLabel=(null===(n=e.applepay)||void 0===n?void 0:n.subtotalLabel)||oc.Subtotal,this._storeCreditLabel=(null===(i=e.applepay)||void 0===i?void 0:i.storeCreditLabel)||oc.StoreCredit;const a=(yield this._paymentIntegrationService.loadPaymentMethod(o)).getPaymentMethodOrThrow(o);(null===(r=a.initializationData)||void 0===r?void 0:r.gateway)===Vi.BRAINTREE&&a.clientToken&&this._braintreeSdk.initialize(a.clientToken)})}execute(e,t){return ac(this,void 0,void 0,function*(){const{payment:n}=e,i=this._paymentIntegrationService.getState();if(!n)throw new co(["payment"]);const{methodId:r}=n,o=i.getPaymentMethodOrThrow(r),a=this._getBaseRequest(i,o),s=this._sessionFactory.create(a);return yield this._paymentIntegrationService.submitOrder({useStoreCredit:e.useStoreCredit},t),s.begin(),new Promise((e,t)=>{this._handleApplePayEvents(s,o,{resolve:e,reject:t})})})}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_getBaseRequest(e,t){const n=e.getCheckoutOrThrow(),i=e.getCartOrThrow(),r=e.getStoreConfigOrThrow(),{storeProfile:{storeCountryCode:o,storeName:a}}=r,{currency:{code:s,decimalPlaces:d}}=i,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=t,{grandTotal:u,isStoreCreditApplied:h,outstandingBalance:p}=n,m=[{label:this._subTotalLabel,amount:`${n.subtotal.toFixed(d)}`}];if(n.taxes.forEach(e=>m.push({label:e.name,amount:`${e.amount.toFixed(d)}`})),m.push({label:this._shippingLabel,amount:`${n.shippingCostTotal.toFixed(d)}`}),h){const{storeCredit:t}=e.getCustomerOrThrow();m.push({label:this._storeCreditLabel,amount:`-${Math.min(u,t).toFixed(d)}`})}return{countryCode:o,currencyCode:s,merchantCapabilities:c,supportedNetworks:l,lineItems:m,total:{label:a,amount:`${p.toFixed(d)}`,type:"final"}}}_handleApplePayEvents(e,t,n){e.onvalidatemerchant=n=>ac(this,void 0,void 0,function*(){try{const{body:i}=yield this._onValidateMerchant(t,n);e.completeMerchantValidation(i)}catch(e){throw new Error("Merchant validation failed")}}),e.oncancel=()=>ac(this,void 0,void 0,function*(){return n.reject(new Wi("Continue with applepay"))}),e.onpaymentauthorized=i=>this._onPaymentAuthorized(i,e,t,n)}_onValidateMerchant(e,t){return ac(this,void 0,void 0,function*(){const n=[`validationUrl=${t.validationURL}`,`merchantIdentifier=${e.initializationData.merchantId}`,`displayName=${e.initializationData.storeName}`,`domainName=${window.location.hostname}`].join("&");return this._requestSender.post(`${e.initializationData.paymentsUrl}/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})})}_onPaymentAuthorized(e,t,n,i){var r;return ac(this,void 0,void 0,function*(){const{token:o}=e.payment;let a;(null===(r=n.initializationData)||void 0===r?void 0:r.gateway)===Vi.BRAINTREE&&(a=yield this._getBraintreeDeviceData());const s={methodId:n.id,paymentData:{deviceSessionId:a,formattedPayload:{apple_pay_token:{payment_data:o.paymentData,payment_method:o.paymentMethod,transaction_id:o.transactionIdentifier}}}};try{return yield this._paymentIntegrationService.submitPayment(s),t.completePayment(ApplePaySession.STATUS_SUCCESS),i.resolve()}catch(e){return t.completePayment(ApplePaySession.STATUS_FAILURE),i.reject(new ri(ei.PaymentNotInitialized))}})}_getBraintreeDeviceData(){return ac(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}const dc=vi(e=>{const{getHost:t}=e.getState(),i=new Ei(e);return new sc(n({host:t()}),e,new Zi,new Ui(new Hi(a(),window,i)),new Qi(new r))},[{id:"applepay"}]),cc={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},lc=function({styles:e}){const t={};return e.color&&(t.color=e.color),e.layout&&(t.layout=e.layout),(e["logo-type"]||e["logo-position"])&&(t.logo={},e["logo-type"]&&(t.logo.type=e["logo-type"]),e["logo-position"]&&(t.logo.position=e["logo-position"])),e.ratio&&(t.ratio=e.ratio),(e["text-color"]||e["text-size"])&&(t.text={},e["text-color"]&&(t.text.color=e["text-color"]),e["text-size"]&&(t.text.size=+e["text-size"])),t};function uc(e){return"object"==typeof e&&null!==e&&"bigpayToken"in e&&"defaultInstrument"in e&&"provider"in e&&"trustedShippingAddress"in e&&"method"in e&&"type"in e}var hc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.paypalSdkHelper=n,this.loadingIndicator=i}initialize(e){return hc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments:n}=e||{};if(this.bigcommerce_payments=n,!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(t),{container:o,bannerContainerId:a}=n,{orderId:s,paypalBNPLConfiguration:d=[],isPayPalCreditAvailable:c}=r.initializationData||{};if(void 0!==a){if(!document.getElementById(a))return void console.error("Unable to create banner without valid banner container ID.");const e=null==d?void 0:d.find(({id:e})=>"checkout"===e);if(c||!(null==e?void 0:e.status))return;const t=yield this.paypalSdkHelper.getPayPalMessages(r,i.getCartOrThrow().currency.code);return t&&"function"==typeof(null==t?void 0:t.Messages)?this.renderMessages(t,a,e):void console.error("[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK")}s?this.orderId=s:(this.loadingIndicatorContainer=null==o?void 0:o.split("#")[1],yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t),n.onInit&&"function"==typeof n.onInit&&n.onInit(()=>this.renderButton(t,n)),(void 0===n.shouldRenderPayPalButtonOnInitialization||n.shouldRenderPayPalButtonOnInitialization)&&this.renderButton(t,n))})}execute(e,t){return hc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{var i;this.bigcommerce_payments&&(null===(i=this.paypalButton)||void 0===i||i.close(),this.renderButton(n.methodId,this.bigcommerce_payments),this.handleError(new Error("INSTRUMENT_DECLINED"),r)),t()})),this.handleError(e,r),Promise.reject()}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}prepareVaultedInstrumentPaymentPayload(e,t,n){const{instrumentId:i,shouldSetAsDefaultInstrument:r}=n,o=!this.isTrustedVaultingFlow(n);return o?{methodId:e,paymentData:{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}:{methodId:e,paymentData:{instrumentId:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t},bigpay_token:{token:i}}}}}preparePaymentPayload(e,t,n){const{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:r=!1}=jd(n)?n:{};return{methodId:e,paymentData:{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}}renderButton(e,t){var n,i,r,o;const a=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:d}=s.initializationData||{},{checkoutPaymentButtonStyles:c}=d||{},{container:l,onError:u,onRenderButton:h,onValidate:p,submitForm:m}=t;if(!l)throw new fi('Unable to initialize payment because "container" argument is not provided.');const y=Object.assign(Object.assign({},this.isAppSwitchEnabled(e)&&{appSwitchWhenAvailable:!0}),{fundingSource:a.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(c),createOrder:()=>this.createOrder(),onClick:(e,t)=>this.handleClick(t,p),onApprove:e=>this.handleApprove(e,m),onError:e=>this.handleError(e,u),onCancel:()=>this.toggleLoadingIndicator(!1)});this.paypalButton=a.Buttons(y),this.paypalButton.isEligible()&&(h&&"function"==typeof h&&h(),(null===(i=(n=this.paypalButton).hasReturned)||void 0===i?void 0:i.call(n))&&this.isAppSwitchEnabled(e)?null===(o=(r=this.paypalButton).resume)||void 0===o||o.call(r):this.paypalButton.render(l))}handleClick(e,t){return hc(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;yield null==t?void 0:t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,null==t||t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createOrder(){return hc(this,void 0,void 0,function*(){const e=this.getFieldsValues();return this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_paymentscheckout",{shouldSaveInstrument:(null==e?void 0:e.shouldSaveInstrument)||!1})})}getFieldsValues(){const{getFieldsValues:e}=this.bigcommerce_payments||{};return"function"==typeof e?e():void 0}isTrustedVaultingFlow(e){if(e&&xd(e)){const t=this.paymentIntegrationService.getState().getInstruments(),n=null==t?void 0:t.find(t=>uc(t)&&t.bigpayToken===e.instrumentId);return!(uc(n)&&!n.trustedShippingAddress)}return!1}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isPayPalVaultedInstrumentPaymentData(e){return!!e&&xd(e)&&jd(e)}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:lc(n)};e.Messages(i).render(`#${t}`)}isProviderError(e){var t,n,i;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"INSTRUMENT_DECLINED"===(null===(i=null===(n=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===n?void 0:n.provider_error)||void 0===i?void 0:i.code)}isAppSwitchEnabled(e){var t,n;return null!==(n=null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)&&void 0!==n&&n}}const mc=vi(e=>new pc(e,_r(e),Rr(),new vd({containerStyles:cc})),[{id:"bigcommerce_payments"}]);function yc(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var gc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsRequestSender=t,this.bigCommercePaymentsSdk=n,this.bigCommercePaymentsFastlaneUtils=i}initialize(e){var t,n;return gc(this,void 0,void 0,function*(){const{methodId:i,bigcommerce_payments_fastlane:r}=e;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(this.methodId=i,!r)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_fastlane" argument is not provided.');if(this.bigcommerce_payments_fastlane=r,!r.onInit||"function"!=typeof r.onInit)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_fastlane.onInit" argument is not provided or it is not a function.');if(!r.onChange||"function"!=typeof r.onChange)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_fastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState(),a=o.getCartOrThrow(),s=o.getPaymentMethodOrThrow(i),{isDeveloperModeApplicable:d,isFastlaneStylingEnabled:c}=s.initializationData||{};this.threeDSVerificationMethod=null===(t=s.initializationData)||void 0===t?void 0:t.threeDSVerificationMethod,this.paypalFastlaneSdk=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(s,a.currency.code,a.id);const l=qr(c?null===(n=null==s?void 0:s.initializationData)||void 0===n?void 0:n.fastlaneStyles:{},null==r?void 0:r.styles);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(this.paypalFastlaneSdk,!!d,l),this.shouldRunAuthenticationFlow()&&(yield this.runPayPalAuthenticationFlowOrThrow(i)),yield this.initializePayPalPaymentComponent(),r.onInit(e=>this.renderPayPalPaymentComponent(e)),r.onChange(()=>this.handlePayPalStoredInstrumentChange(i))})}execute(e,t){return gc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const{getHost:t}=e.getState();return new vc(e,new vr(n({host:t()})),Rr(),jr())},[{id:"bigcommerce_payments_fastlane"}]);var Sc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class _c{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=n,this.paypalSdkHelper=i}initialize(e){return Sc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_paylater:n}=e||{};if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(t),{paypalBNPLConfiguration:o=[],orderId:a}=r.initializationData||{},{bannerContainerId:s,container:d}=n;if(void 0!==s){if(!document.getElementById(s))return void console.error("Unable to create banner without valid banner container ID.");const e=o&&o.find(({id:e})=>"checkout"===e);if(!(null==e?void 0:e.status))return;const t=yield this.paypalSdkHelper.getPayPalMessages(r,i.getCartOrThrow().currency.code);return this.renderMessages(t,s,e)}a?this.orderId=a:(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t),this.loadingIndicatorContainer=null==d?void 0:d.split("#")[1],this.renderButton(t,n))})}execute(e,t){return Sc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(h)return;const t={fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.bigCommercePaymentsButtons=n.Buttons(t),this.bigCommercePaymentsButtons.isEligible()||e!==n.FUNDING.PAYLATER){if(!this.bigCommercePaymentsButtons.isEligible()&&e===n.FUNDING.CREDIT)throw new Si(`BigCommercePayments ${e} is not available for your region. Please use BigCommercePayments Checkout instead.`);d&&"function"==typeof d&&d(),this.bigCommercePaymentsButtons.render(a),h=!0}})}handleClick(e,t){return Sc(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;t&&"function"==typeof t&&(yield t(()=>(this.toggleLoadingIndicator(!0),n()),i))})}handleApprove({orderID:e},t){this.orderId=e,t&&"function"==typeof t&&t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:lc(n)};e.Messages(i).render(`#${t}`)}}const wc=vi(e=>new _c(e,_r(e),new vd({containerStyles:cc}),Rr()),[{id:"bigcommerce_payments_paylater"}]);class Ic extends nr{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}var Cc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class bc{constructor(e,t,n,i=3e3,r=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=n,this.pollingInterval=i,this.maxPollingIntervalTime=r,this.pollingTimer=0,this.stopPolling=ce}initialize(e){return Cc(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,bigcommerce_payments_ratepay:i}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_ratepay" argument is not provided.');const{legalTextContainer:r,container:o,loadingContainerId:a}=i;if(!o)throw new fi('Unable to initialize payment because "options.container" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.legalTextContainer" argument is not provided.');if(!a)throw new fi('Unable to initialize payment because "options.loadingContainerId" argument is not provided.');this.loadingIndicatorContainer=a;const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t),{merchantId:d}=s.initializationData||{};if(!d)throw new fi("Unable to initialize payment because merchantId argument is not provided.");this.bigcommerce_payments_ratepay=i,yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n),this.createFraudNetScript(d,n,t),this.loadFraudnetConfig(),this.renderLegalText(r,o)})}execute(e,t){return Cc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.initializePollingMechanism(n.methodId,e,t,n.gatewayId)})}catch(e){return this.handleError(e),new Promise((e,t)=>t())}})}finalize(){return Promise.reject(new Cd)}deinitialize(){const{legalTextContainer:e}=this.bigcommerce_payments_ratepay||{},t=document.querySelectorAll('[data-id="fraudnetScript"]')[0],n=document.querySelectorAll('[data-id="fraudnetConfig"]')[0];if(this.deinitializePollingMechanism(),t.remove(),n.remove(),e){const t=document.getElementById(e);null==t||t.remove()}return Promise.resolve()}normalizeDate(e){const t=this.formatDate(e.getDate()),n=this.formatDate(e.getMonth()+1);return`${e.getFullYear()}-${n}-${t}`}formatDate(e){return`${e<10?0:""}${e}`}renderLegalText(e,t){const n=e,i=t.split("#")[1],r=document.getElementById(i),o=null==r?void 0:r.parentNode,a=document.createElement("div");a.style.marginBottom="20px",a.setAttribute("id",n),null==o||o.prepend(a);const s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=s.Legal({fundingSource:s.Legal.FUNDING.PAY_UPON_INVOICE});if(!document.getElementById(n))throw new fi('Unable to initialize payment because "legalTextContainerElement" argument is not found.');d.render(`#${n}`)}handleError(e){const{onError:t}=this.bigcommerce_payments_ratepay||{};this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createFraudNetScript(e,t,n){const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{testMode:r}=i.config,o=document.createElement("script");o.setAttribute("type","application/json"),o.setAttribute("fncls","fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99"),o.setAttribute("data-id","fraudnetScript"),this.guid=this.generateGUID();const a={f:this.guid,s:`${e}_checkout-page`,sandbox:r};o.innerHTML=JSON.stringify(a),document.body.appendChild(o)}generateGUID(){let e="";for(let t=0;t<32;t+=1)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(62*Math.random())];return e}loadFraudnetConfig(){const e=document.createElement("script");e.setAttribute("data-id","fraudnetConfig"),e.src="https://c.paypal.com/da/r/fb.js",document.body.appendChild(e)}reinitializeStrategy(e){return Cc(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}initializePollingMechanism(e,t,n,i){return Cc(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.bigCommercePaymentsIntegrationService.getOrderStatus("bigcommerce_payments_apms",{params:{useMetadata:!0}}),o=r===cr.PollingStop,a=r===cr.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimernew bc(e,_r(e),new vd({containerStyles:Object.assign(Object.assign({},cc),{position:"fixed"})})),[{gateway:"bigcommerce_payments_apms",id:"ratepay"}]);var Oc;!function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification",e.CardExpiryVerification="cardExpiryVerification"}(Oc||(Oc={}));const Ec=Oc;function Ac(e){return Ec.CardNumber in e&&Ec.CardName in e&&Ec.CardExpiry in e}function Tc(e){return Ec.CardNumberVerification in e&&Ec.CardCodeVerification in e&&Ec.CardExpiryVerification in e}var kc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Dc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdk=n,this.bigCommercePaymentsFastlaneUtils=i}initialize(e){return kc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_creditcards:n}=e,i=n,{form:r,onCreditCardFieldsRenderingError:o,onLoadComplete:a}=i||{};if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new fi('Unable to proceed because "options.bigcommerce_payments_creditcards.form" argument is not provided.');this.hostedFormOptions=r,this.isCreditCardForm=Ac(r.fields),this.isCreditCardVaultedForm=Tc(r.fields)&&!this.hasUndefinedValues(),yield this.paymentIntegrationService.loadPaymentMethod(t),yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t,void 0,!0,!0),(this.isCreditCardForm||this.isCreditCardVaultedForm)&&(yield this.initializeFields(r,o)),null==a||a(),this.shouldInitializePayPalFastlane(t)&&(yield this.initializePayPalFastlaneOrThrow(t))})}execute(e,t){return kc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(n===ir.No||n===ir.Unknown)throw new Error;return this.handleApprove({orderID:e,vaultSetupToken:t})},onError:()=>{throw new Qr},inputEvents:{onChange:t=>this.onChangeHandler(e,t),onFocus:t=>this.onFocusHandler(e,t),onBlur:t=>this.onBlurHandler(e,t),onInputSubmitRequest:t=>this.onInputSubmitRequest(e,t)}},o);if(this.cardFields=yield r.CardFields(a),!this.cardFields.isEligible())throw new ri(ei.PaymentNotInitialized);try{this.stylizeInputContainers(n),Ac(n)&&(yield this.renderFields(n)),Tc(n)&&(yield this.renderVaultedFields(n))}catch(e){"function"==typeof t&&t(e)}})}getExecuteCallback(e){return Tc(e)?this.createVaultSetupTokenCallback():this.createOrderCallback()}createVaultSetupTokenCallback(){return{createVaultSetupToken:()=>kc(this,void 0,void 0,function*(){const{setupToken:e}=(yield this.bigCommercePaymentsIntegrationService.createOrderCardFields("bigcommerce_payments_creditcardscheckout",Object.assign(Object.assign({},this.getInstrumentParams()),{setupToken:!0})))||{};return e})}}createOrderCallback(){return{createOrder:()=>kc(this,void 0,void 0,function*(){const{orderId:e}=(yield this.bigCommercePaymentsIntegrationService.createOrderCardFields("bigcommerce_payments_creditcardscheckout",this.getInstrumentParams()))||{};return e})}}handleApprove({orderID:e,vaultSetupToken:t}){e&&(this.returnedOrderId=e),t&&(this.returnedVaultedToken=t)}renderFields(e){var t,n,i,r;return kc(this,void 0,void 0,function*(){const o=this.getCardFieldsOrThrow();(null===(t=e.cardCode)||void 0===t?void 0:t.containerId)&&(this.cvvField=o.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCode.containerId}`)),(null===(n=e.cardExpiry)||void 0===n?void 0:n.containerId)&&(this.expiryField=o.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiry.containerId}`)),(null===(i=e.cardName)||void 0===i?void 0:i.containerId)&&(this.nameField=o.NameField({placeholder:""}),yield this.nameField.render(`#${e.cardName.containerId}`)),(null===(r=e.cardNumber)||void 0===r?void 0:r.containerId)&&(this.numberField=o.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumber.containerId}`))})}renderVaultedFields(e){var t,n,i;return kc(this,void 0,void 0,function*(){const r=this.getCardFieldsOrThrow();(null===(t=e.cardCodeVerification)||void 0===t?void 0:t.containerId)&&(this.cvvField=r.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCodeVerification.containerId}`)),(null===(n=e.cardExpiryVerification)||void 0===n?void 0:n.containerId)&&(this.expiryField=r.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiryVerification.containerId}`)),(null===(i=e.cardNumberVerification)||void 0===i?void 0:i.containerId)&&(this.numberField=r.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumberVerification.containerId}`))})}getInstrumentParams(){if(!this.executionPaymentData)return{};if(jd(this.executionPaymentData)){const{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}=this.executionPaymentData;return{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}}if(xd(this.executionPaymentData)){const{instrumentId:e}=this.executionPaymentData;return{instrumentId:e}}return{}}getFieldTypeByEmittedField({emittedBy:e}){return{fieldType:this.mapFieldType(e)}}submitHostedForm(){return kc(this,void 0,void 0,function*(){const e=this.getCardFieldsOrThrow(),t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),n={billingAddress:{company:t.company,addressLine1:t.address1,addressLine2:t.address2,adminArea1:t.stateOrProvinceCode,adminArea2:t.city,postalCode:t.postalCode,countryCode:t.countryCode}};try{this.isCreditCardVaultedForm?yield e.submit():yield e.submit(n)}catch(e){throw new Qr("Failed authentication. Please try to authorize again.")}})}validateHostedFormOrThrow(){var e,t;return kc(this,void 0,void 0,function*(){const n=this.getCardFieldsOrThrow(),i=yield n.getState().then(e=>e),r=this.getValidityData(i);if(!r.isValid)throw null===(t=null===(e=this.hostedFormOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,r),new lo(this.mapValidationErrors(r.errors))})}getValidityData({fields:e}){const t=Object.assign({},e);delete t.cardNameField;const n=Object.keys(t);return{isValid:n.every(e=>{var n;return null===(n=t[e])||void 0===n?void 0:n.isValid}),errors:n.reduce((e,n)=>{var i;const r=this.mapFieldType(n);return Object.assign(Object.assign({},e),{[r]:(null===(i=t[n])||void 0===i?void 0:i.isValid)?void 0:[this.getInvalidErrorByFieldType(r)]})},{})}}getInvalidErrorByFieldType(e){switch(e){case Ec.CardCode:case Ec.CardCodeVerification:return{fieldType:e,message:"Invalid card code",type:"invalid_card_code"};case Ec.CardNumber:case Ec.CardNumberVerification:return{fieldType:e,message:"Invalid card number",type:"invalid_card_number"};case Ec.CardExpiry:case Ec.CardExpiryVerification:return{fieldType:e,message:"Invalid card expiry",type:"invalid_card_expiry"};default:return{fieldType:e,message:"Invalid field",type:"invalid"}}}mapValidationErrors(e={}){const t={};return Object.keys(e).forEach(n=>{var i,r;t[n]=[{message:(null===(r=null===(i=e[n])||void 0===i?void 0:i[0])||void 0===r?void 0:r.message)||"",type:n}]}),t}mapFieldType(e){switch(e){case"name":return Ec.CardName;case"cardNumberField":case"number":return this.isCreditCardForm?Ec.CardNumber:Ec.CardNumberVerification;case"cardExpiryField":case"expiry":return this.isCreditCardForm?Ec.CardExpiry:Ec.CardExpiryVerification;case"cardCvvField":case"cvv":return this.isCreditCardForm?Ec.CardCode:Ec.CardCodeVerification;default:throw new Error("Unexpected field type")}}getCardFieldsOrThrow(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);return this.cardFields}getInputStyles(e){var t,n,i;const r={"font-size":(null===(t=null==e?void 0:e.default)||void 0===t?void 0:t.fontSize)||"1rem","font-family":(null===(n=null==e?void 0:e.default)||void 0===n?void 0:n.fontFamily)||"Montserrat, Arial, Helvetica, sans-serif","font-weight":(null===(i=null==e?void 0:e.default)||void 0===i?void 0:i.fontWeight)||"400",outline:"none",padding:"9px 13px"},o=Object.assign(Object.assign({},r),{color:"#333333"});return{input:o,".invalid":Object.assign(Object.assign({},r),{color:"red"}),".valid":o,":focus":o}}stylizeInputContainers(e){Object.values(e||{}).forEach(e=>{const t=document.getElementById(`${(null==e?void 0:e.containerId)||""}`);t&&(t.style.padding="0px",t.style.boxShadow="none",t.style.border="none",t.style.background="transparent",t.style.marginBottom="10px",t.style.marginLeft="-5px")})}hasUndefinedValues(){return!this.hostedFormOptions||Object.values(this.hostedFormOptions.fields).some(e=>void 0===e)}onChangeHandler(e,t){var n;null===(n=null==e?void 0:e.onValidate)||void 0===n||n.call(e,this.getValidityData(t))}onFocusHandler(e,t){var n;null===(n=null==e?void 0:e.onFocus)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onBlurHandler(e,t){var n;null===(n=null==e?void 0:e.onBlur)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onInputSubmitRequest(e,t){var n;null===(n=null==e?void 0:e.onEnter)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}shouldInitializePayPalFastlane(e){var t,n;const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(e),o=i.getPaymentProviderCustomer(),a=(s=o)&&("authenticationState"in s||"addresses"in s||"instruments"in s)?o:{};var s;return(null===(t=null==r?void 0:r.initializationData)||void 0===t?void 0:t.isAcceleratedCheckoutEnabled)&&(null===(n=null==r?void 0:r.initializationData)||void 0===n?void 0:n.isBigCommercePaymentsAnalyticsV2Enabled)&&!(null==a?void 0:a.authenticationState)}initializePayPalFastlaneOrThrow(e){return kc(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getPaymentMethodOrThrow(e),{initializationData:r}=i;if(!(null==r?void 0:r.connectClientToken))return;const o=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(i,n.currency.code,n.id);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(o,!!(null==r?void 0:r.isDeveloperModeApplicable))}catch(e){}})}}const Mc=vi(e=>new Dc(e,_r(e),Rr(),jr()),[{id:"bigcommerce_payments_creditcards"}]);var zc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Nc{constructor(e,t,n,i,r=3e3,o=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdkHelper=n,this.loadingIndicator=i,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.pollingTimer=0,this.stopPolling=ce,this.isPollingEnabled=!1}initialize(e){return zc(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,bigcommerce_payments_apms:i}=e;if(this.bigCommercePaymentsAlternativeMethods=i,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_apms" argument is not provided.');const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(n,t),{orderId:a,shouldRenderFields:s}=o.initializationData||{},d=r.getStoreConfigOrThrow().checkoutSettings.features;this.isPollingEnabled=Ci(d,"PAYPAL-5624.bcp_ideal_polling"),a?this.orderId=a:(this.paypalApms=yield this.bigCommercePaymentsSdkHelper.getPayPalApmsSdk(o,r.getCartOrThrow().currency.code),this.loadingIndicatorContainer=i.container.split("#")[1],this.renderButton(n,t,i),s&&this.renderFields(n,i))})}execute(e,t){return zc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.initializePollingMechanism(r,e,t,o)})),this.isNonInstantPaymentMethod(r)||(yield this.paymentIntegrationService.submitOrder(i,t)),yield this.bigCommercePaymentsIntegrationService.submitPayment(r,this.orderId,o)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,this.isPollingEnabled&&this.resetPollingMechanism(),null===(e=this.bigCommercePaymentsButton)||void 0===e||e.close(),Promise.resolve()}initializePollingMechanism(e,t,n,i){return zc(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.bigCommercePaymentsIntegrationService.getOrderStatus(i),o=r===cr.Approved,a=r===cr.PollingError;if(o)return this.deInitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimern.onInitButton(t),createOrder:()=>this.onCreateOrder(e,t,n),onApprove:e=>this.handleApprove(e,c),onCancel:()=>{this.toggleLoadingIndicator(!1),this.deInitializePollingMechanism()},onError:e=>{this.deInitializePollingMechanism(),this.handleFailure(e,s)},onClick:(e,t)=>zc(this,void 0,void 0,function*(){return n.onValidate(t.resolve,t.reject)})};this.bigCommercePaymentsButton=i.Buttons(l),this.bigCommercePaymentsButton.isEligible()&&(d&&"function"==typeof d&&d(),this.bigCommercePaymentsButton.render(a))}onCreateOrder(e,t,n){return zc(this,void 0,void 0,function*(){const{onValidate:i}=n;yield i(()=>(this.toggleLoadingIndicator(!0),()=>Promise.resolve()),ce);const r=yield this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apms");if(this.isNonInstantPaymentMethod(e)){const n={useStoreCredit:!1},i={params:{methodId:e,gatewayId:t}};yield this.paymentIntegrationService.submitOrder(n,i),yield this.bigCommercePaymentsIntegrationService.submitPayment(e,r,t)}return r})}handleApprove({orderID:e},t){this.orderId=e,t()}handleFailure(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderFields(e,t){const n=this.getPaypalAmpsSdkOrThrow(),i=this.paymentIntegrationService.getState(),{firstName:r,lastName:o,email:a}=i.getBillingAddressOrThrow(),{apmFieldsContainer:s,apmFieldsStyles:d}=t;if(!s)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_apms" argument should contain "apmFieldsContainer".');const c=document.querySelector(s);c&&(c.innerHTML="");const l={fundingSource:e,style:d||{},fields:{name:{value:`${r} ${o}`},email:{value:a}}};n.PaymentFields(l).render(s)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isNonInstantPaymentMethod(e){return e.toUpperCase()in dr}getPaypalAmpsSdkOrThrow(){if(!this.paypalApms)throw new mi;return this.paypalApms}}const xc=vi(e=>new Nc(e,_r(e),Rr(),new vd({containerStyles:cc})),[{gateway:"bigcommerce_payments_apms"}]);class Rc{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){const{gatewayId:t,methodId:n,bigcommerce_payments_apms:i}=e;if(this.bigCommercePaymentsAlternativeMethods=i,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');return Promise.resolve()}execute(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{window.location.replace(t),n()})}return this.handleError(e),Promise.reject(e)}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}handleError(e){const{onError:t}=this.bigCommercePaymentsAlternativeMethods||{};t&&"function"==typeof t&&t(e)}}const Fc=vi(e=>new Rc(e,_r(e)),[{gateway:"bigcommerce_payments_apms",id:"klarna"},{gateway:"bigcommerce_payments_apms",id:"afterpay"}]);var Lc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Bc{constructor(e,t,n){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=n}initialize(e){var t,n;return Lc(this,void 0,void 0,function*(){const{methodId:i,bigcommerce_payments_venmo:r}=e||{};if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i);(null===(t=o.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(n=o.initializationData)||void 0===n?void 0:n.orderId:(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i),this.loadingIndicatorContainer=r.container.split("#")[1],this.renderButton(i,r))})}execute(e,t){return Lc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rthis.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmocheckout"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=n.Buttons(u),!this.paypalButton.isEligible())throw new Si("Venmo is not available for your region. Please another payment method instead.");d&&"function"==typeof d&&d(),this.paypalButton.render(a)}handleClick(e,t){return Lc(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;yield t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,t(),this.toggleLoadingIndicator(!1)}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const jc=vi(e=>new Bc(e,_r(e),new vd({styles:{backgroundColor:"black"}})),[{id:"bigcommerce_payments_venmo"}]);class Uc{initialize(e){this._blueSnapSdk=e}initialize3ds(e,t){return n=this,i=void 0,o=function*(){const n=this._getBlueSnapSdk();return new Promise((i,r)=>{n.threeDsPaymentsSetup(e,e=>"1"===e.code?i(e.threeDSecure.threeDSecureReferenceId):r(new Qr)),n.threeDsPaymentsSubmitData(t)})},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_getBlueSnapSdk(){return ii(this._blueSnapSdk,()=>new ri(ei.PaymentNotInitialized))}}function qc(e){return Ec.CardNumber in e}function Vc(e){return Ec.CardCodeVerification in e||Ec.CardNumberVerification in e}var Gc,Hc,Wc,$c,Yc,Kc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Jc{constructor(e,t,n,i){this._scriptLoader=e,this._paymentIntegrationService=t,this._blueSnapDirectHostedForm=n,this._blueSnapDirect3ds=i}initialize(e){return Kc(this,void 0,void 0,function*(){const{methodId:t,gatewayId:n,creditCard:i}=e;if(!n||!i)throw new fi;const r=yield this._paymentIntegrationService.loadPaymentMethod(n,{params:{method:t,bigpayToken:i.bigpayToken}}),{config:{testMode:o,is3dsEnabled:a},clientToken:s}=r.getPaymentMethodOrThrow(t,n);if(this._blueSnapSdk=yield this._scriptLoader.load(o),this._paymentFieldsToken=s,this._shouldUseHostedFields=qc(i.form.fields)||Vc(i.form.fields)&&!!i.form.fields.cardNumberVerification,this._shouldUseHostedFields){this._blueSnapDirectHostedForm.initialize(this._blueSnapSdk,i.form.fields);try{yield this._blueSnapDirectHostedForm.attach(this._getPaymentFieldsToken(),i,a)}catch(e){if(e instanceof fi)return;throw e}}})}execute(e){return Kc(this,void 0,void 0,function*(){if(!e.payment)throw new co(["payment"]);if(!this._blueSnapSdk)throw new co(["payment"]);const{paymentData:t}=e.payment,{shouldSaveInstrument:n,shouldSetAsDefaultInstrument:i}=jd(t)?t:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},r=this._getPaymentFieldsToken();let o;const{is3dsEnabled:a}=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.payment.methodId,e.payment.gatewayId).config,s=this._shouldUseHostedFields?yield this._blueSnapDirectHostedForm.validate().submit(a?this._getBlueSnapDirectThreeDSecureData():void 0,!(jd(t)&&xd(t))):void 0;if(yield this._paymentIntegrationService.submitOrder(),jd(t)&&xd(t)&&this._paymentFieldsToken&&t.instrumentId){if(a){this._blueSnapDirect3ds.initialize(this._blueSnapSdk);const{last4:e,brand:n}=this._paymentIntegrationService.getState().getCardInstrumentOrThrow(t.instrumentId),i=Object.assign({last4Digits:e,ccType:n.toUpperCase()},this._getBlueSnapDirectThreeDSecureData());o=yield this._blueSnapDirect3ds.initialize3ds(this._paymentFieldsToken,i)}yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e.payment),{paymentData:Object.assign(Object.assign(Object.assign({instrumentId:t.instrumentId},this._shouldUseHostedFields?{nonce:r}:{}),o?{deviceSessionId:o}:{}),{shouldSetAsDefaultInstrument:!!i})}))}else yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e.payment),{paymentData:{formattedPayload:{credit_card_token:{token:JSON.stringify({pfToken:r,cardHolderName:s&&s.cardHolderName})},vault_payment_instrument:n,set_as_default_stored_instrument:i}}}))})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this._shouldUseHostedFields&&this._blueSnapDirectHostedForm.detach(),Promise.resolve()}_getBlueSnapDirectThreeDSecureData(){var e;const{getBillingAddress:t,getShippingAddress:n,getCustomer:i,getCheckoutOrThrow:r,getCartOrThrow:o}=this._paymentIntegrationService.getState(),a=t(),s=n(),d=(null===(e=i())||void 0===e?void 0:e.email)||(null==a?void 0:a.email),c=(null==a?void 0:a.phone)||(null==s?void 0:s.phone);return Object.assign(Object.assign(Object.assign(Object.assign({amount:r().outstandingBalance,currency:o().currency.code},d&&{email:d}),c&&{phone:c}),a&&{billingFirstName:a.firstName,billingLastName:a.lastName,billingCountry:a.countryCode,billingCity:a.city,billingAddress:`${a.address1} ${a.address2}`.trim(),billingZip:a.postalCode}),s&&{shippingFirstName:s.firstName,shippingLastName:s.lastName,shippingCountry:s.countryCode,shippingCity:s.city,shippingAddress:`${s.address1} ${s.address2}`.trim(),shippingZip:s.postalCode})}_getPaymentFieldsToken(){return ii(this._paymentFieldsToken,()=>new ti(Xn.MissingPaymentToken))}}!function(e){e.AMEX="american-express",e.CHINA_UNION_PAY="unionpay",e.DINERS="diners-club",e.DISCOVER="discover",e.JCB="jcb",e.MASTERCARD="mastercard",e.UNKNOWN="unknown",e.VISA="visa"}(Gc||(Gc={})),function(e){e.ON_BLUR="onBlur",e.ON_SUBMIT="onSubmit"}(Hc||(Hc={})),function(e){e.EMPTY="empty",e.INVALID="invalid",e.THREE_DS_NOT_ENABLED="3D Secure is not enabled"}(Wc||(Wc={})),function(e){e.CC_NOT_SUPORTED="22013",e.ERROR_403="403",e.ERROR_404="404",e.ERROR_500="500",e.INVALID_OR_EMPTY="10",e.SESSION_EXPIRED="400",e.THREE_DS_AUTH_FAILED="14101",e.THREE_DS_CLIENT_ERROR="14103",e.THREE_DS_MISSING_FIELDS="14102",e.THREE_DS_NOT_ENABLED="14100",e.TOKEN_EXPIRED="14040",e.TOKEN_NOT_ASSOCIATED="14042",e.TOKEN_NOT_FOUND="14041"}($c||($c={})),function(e){e.CardCode="cvv",e.CardExpiry="exp",e.CardName="noc",e.CardNumber="ccn"}(Yc||(Yc={}));const Zc={[Yc.CardNumber]:Ec.CardNumber,[Yc.CardExpiry]:Ec.CardExpiry,[Yc.CardName]:Ec.CardName,[Yc.CardCode]:Ec.CardCode},Qc={empty:{[Ec.CardNumber]:{fieldType:"cardNumber",message:"Credit card number is required",type:"required"},[Ec.CardNumberVerification]:{fieldType:"cardNumber",message:"Credit card number is required",type:"required"},[Ec.CardExpiry]:{fieldType:"cardExpiry",message:"Expiration date is required",type:"required"},[Ec.CardCode]:{fieldType:"cardCode",message:"CVV is required",type:"required"},[Ec.CardName]:{fieldType:"cardName",message:"Full name is required",type:"required"}},invalid:{[Ec.CardNumber]:{fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},[Ec.CardNumberVerification]:{fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},[Ec.CardExpiry]:{fieldType:"cardExpiry",message:"Expiration date must be a valid future date in MM / YY format",type:"invalid_card_expiry"},[Ec.CardCode]:{fieldType:"cardCode",message:"CVV must be valid",type:"invalid_card_code"},[Ec.CardName]:{fieldType:"cardName",message:"Full name is required",type:"required"}}};class Xc{constructor(e,t){this._nameOnCardInput=e,this._hostedInputValidator=t}initialize(e,t){this._blueSnapSdk=e,t&&(qc(t)?this._hostedInputValidator.initialize():Vc(t)&&t.cardNumberVerification&&this._hostedInputValidator.initializeValidationFields())}attach(e,t,n){var i,r,o,a,s=t.form,{fields:d}=s,c=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const r=this._getHostedPaymentFieldsOptions(e,d,c,i,n);t.hostedPaymentFieldsCreate(r),qc(d)&&this._nameOnCardInput.attach(r,d.cardName.accessibilityLabel,d.cardName.placeholder)})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}validate(){var e;const t=this._hostedInputValidator.validate();if(null===(e=this._onValidate)||void 0===e||e.call(this,t),!t.isValid){const e=Object.entries(t.errors).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n.map(({message:e,type:t})=>({message:e,type:t}))}),{});throw new lo(e)}return this}submit(e,t=!1){return new Promise((n,i)=>this._getBlueSnapSdk().hostedPaymentFieldsSubmitData(e=>this._isBlueSnapDirectCallbackError(e)?i(new Qr(e.statusCode===$c.THREE_DS_AUTH_FAILED?e.error[0].errorDescription:`Submission failed with status: ${e.statusCode} and errors: ${JSON.stringify(e.error)}`)):n(Object.assign(Object.assign({},e.cardData),t?{cardHolderName:this._nameOnCardInput.getValue()}:{})),e))}detach(){this._nameOnCardInput.detach()}_isBlueSnapDirectCallbackError(e){return"error"in e}_getHostedPaymentFieldsOptions(e,t,{onFocus:n,onBlur:i,onValidate:r,onCardTypeChange:o,onEnter:a,styles:s},d,c){var l;return Object.assign(Object.assign(Object.assign({token:e,onFieldEventHandler:{setupComplete:()=>d(),onFocus:this._usetUiEventCallback(n),onBlur:this._usetUiEventCallback(i),onError:this._handleError(r),onType:(e,t)=>null==o?void 0:o({cardType:Gc[t]}),onEnter:this._usetUiEventCallback(a),onValid:e=>null==r?void 0:r(this._hostedInputValidator.validate({tagId:e}))}},qc(t)&&{ccnPlaceHolder:t.cardNumber.placeholder||"",cvvPlaceHolder:(null===(l=t.cardCode)||void 0===l?void 0:l.placeholder)||"",expPlaceHolder:t.cardExpiry.placeholder||"MM / YY"}),s&&{style:this._mapStyles(s)}),{"3DS":c})}_mapStyles({default:e,error:t,focus:n}){return Object.entries(Object.assign(Object.assign(Object.assign({},e&&{input:e}),t&&{".invalid":t}),n&&{":focus":n})).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:Object.entries(n).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[te(t)]:n}),{})}),{})}_handleError(e){return(t,n,i,r)=>{if(n===$c.INVALID_OR_EMPTY&&t&&function(e){return void 0!==e&&[Wc.EMPTY,Wc.INVALID].includes(e)}(i))return null==e?void 0:e(this._hostedInputValidator.validate({tagId:t,errorDescription:i}));throw new Qr(`An unexpected error has occurred: ${JSON.stringify({tagId:t,errorCode:n,errorDescription:i,eventOrigin:r})}`)}}_usetUiEventCallback(e){return t=>{e&&e({fieldType:Zc[t]})}}_getBlueSnapSdk(){return ii(this._blueSnapSdk,()=>new ri(ei.PaymentNotInitialized))}_setCustomBlueSnapAttributes(e){const{cardNumber:t,cardExpiry:n,cardCode:i,cardName:r}=e,o=document.getElementById(t.containerId),a=document.getElementById(n.containerId),s=i&&document.getElementById(i.containerId),d=document.getElementById(r.containerId);if(!(o&&a&&s&&d))throw new fi("Unable to create hosted payment fields to invalid HTML container elements.");o.dataset.bluesnap=Yc.CardNumber,a.dataset.bluesnap=Yc.CardExpiry,s.dataset.bluesnap=Yc.CardCode,d.dataset.bluesnap=Yc.CardName}_setCustomStoredCardsBlueSnapAttributes(e){const{cardNumberVerification:t,cardCodeVerification:n}=e,i=t&&document.getElementById(t.containerId),r=n&&document.getElementById(n.containerId);(i||r)&&(i&&(i.dataset.bluesnap=Yc.CardNumber),r&&(r.dataset.bluesnap=Yc.CardCode))}}class el{constructor(){this._errors={}}initialize(){this._errors={cardNumber:[Qc.empty.cardNumber],cardExpiry:[Qc.empty.cardExpiry],cardCode:[Qc.empty.cardCode],cardName:[Qc.empty.cardName]}}initializeValidationFields(){this._errors={cardNumberVerification:[Qc.empty.cardNumber]}}validate(e){return e&&this._updateErrors(e.tagId,e.errorDescription),{isValid:Object.values(this._errors).every(e=>0===e.length),errors:this._errors}}_updateErrors(e,t){const n=this._errors.cardNumberVerification?Ec.CardNumberVerification:Zc[e];this._errors[n]=t?[Qc[t][n]]:[]}}class tl{attach({style:e,onFieldEventHandler:{onFocus:t,onBlur:n,onValid:i,onError:r,onEnter:o}={}},a,s){var d;this._style=e,this._create(),this._getInput().addEventListener("focus",this._handleFocus(t)),this._getInput().addEventListener("blur",this._handleBlur(n,i,r)),this._getInput().addEventListener("enter",this._handleEnter(o)),a&&this._getInput().setAttribute("aria-label",a),s&&(this._getInput().placeholder=s),null===(d=document.querySelector('[data-bluesnap="noc"]'))||void 0===d||d.appendChild(this._getInput())}getValue(){return this._getInput().value}detach(){this._input&&(this._input.remove(),this._input=void 0)}_handleFocus(e){return()=>{var t;this._applyStyles(null===(t=this._style)||void 0===t?void 0:t[":focus"]),null==e||e(Yc.CardName)}}_handleBlur(e,t,n){return({target:i})=>{var r,o;null==e||e(Yc.CardName),i instanceof HTMLInputElement&&(/\w{1,200}/.test(i.value)?(this._applyStyles(null===(r=this._style)||void 0===r?void 0:r.input),null==t||t(Yc.CardName)):(this._applyStyles(null===(o=this._style)||void 0===o?void 0:o[".invalid"]),null==n||n(Yc.CardName,$c.INVALID_OR_EMPTY,Wc.EMPTY,Hc.ON_BLUR)))}}_handleEnter(e){return()=>null==e?void 0:e(Yc.CardName)}_applyStyles(e={}){const t={color:e.color,fontFamily:e["font-family"],fontSize:e["font-size"],fontWeight:e["font-weight"]},n=Object.keys(t);n.every(e=>["color","fontFamily","fontSize","fontWeight"].includes(e))&&n.forEach(e=>{t[e]&&(this._getInput().style[e]=t[e]||"")})}_configureInput(){this._getInput().autocomplete="cc-name",this._getInput().id=Yc.CardName,this._getInput().inputMode="text",this._getInput().maxLength=200,this._getInput().style.backgroundColor="transparent",this._getInput().style.border="0",this._getInput().style.height="100%",this._getInput().style.margin="0",this._getInput().style.outline="none",this._getInput().style.padding="0",this._getInput().style.width="100%",this._getInput().type="text"}_getInput(){return ii(this._input,()=>new ri(ei.PaymentNotInitialized))}_create(){var e;this._input=document.createElement("input"),this._configureInput(),this._applyStyles(null===(e=this._style)||void 0===e?void 0:e.input)}}var nl;!function(e){e.PRODUCTION="https://pay.bluesnap.com/web-sdk/5/bluesnap.js",e.SANDBOX="https://sandpay.bluesnap.com/web-sdk/5/bluesnap.js"}(nl||(nl={}));class il{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e=!1){return t=this,n=void 0,r=function*(){if(this._window.bluesnap)return this._window.bluesnap;if(yield this._scriptLoader.loadScript(e?nl.SANDBOX:nl.PRODUCTION),!this._window.bluesnap)throw new mi;return this._window.bluesnap},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const rl=vi(e=>new Jc(new il(a()),e,new Xc(new tl,new el),new Uc),[{id:"credit_card",gateway:"bluesnapdirect"}]);class ol{constructor(e){this._paymentIntegrationService=e}execute(e){return t=this,n=void 0,r=function*(){const t=this._formatePaymentPayload(e);yield this._paymentIntegrationService.submitOrder();try{yield this._paymentIntegrationService.submitPayment(t)}catch(e){if(this._isBlueSnapDirectRedirectResponse(e)){const t=e.body.provider_data&&JSON.parse(e.body.provider_data);let n=e.body.additional_action_required.data.redirect_url;if(function(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!t.merchantid&&"string"==typeof t.merchantid}(t)){const e=new URLSearchParams(t).toString();n=`${n}&${e}`}return new Promise(()=>window.location.replace(n))}return Promise.reject(e)}},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}initialize(){return Promise.resolve()}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_formatePaymentPayload({payment:e}){if(!e)throw new co(["payment"]);return e.paymentData&&xd(e.paymentData)&&jd(e.paymentData)?Object.assign(Object.assign({},e),{paymentData:{instrumentId:e.paymentData.instrumentId,shouldSetAsDefaultInstrument:!!e.paymentData.shouldSetAsDefaultInstrument}}):(t=e.paymentData,Boolean("object"==typeof t&&null!==t&&"accountNumber"in t&&"accountType"in t&&"shopperPermission"in t&&"routingNumber"in t)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{ecp:Object.assign({account_number:e.paymentData.accountNumber,account_type:e.paymentData.accountType,shopper_permission:e.paymentData.shopperPermission,routing_number:e.paymentData.routingNumber},e.paymentData.companyName?{company_name:e.paymentData.companyName}:{}),vault_payment_instrument:e.paymentData.shouldSaveInstrument,set_as_default_stored_instrument:e.paymentData.shouldSetAsDefaultInstrument}}}):(n=e.paymentData,Boolean("object"==typeof n&&null!==n&&"iban"in n&&"firstName"in n&&"lastName"in n&&"shopperPermission"in n)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{sepa_direct_debit:{iban:e.paymentData.iban,first_name:e.paymentData.firstName,last_name:e.paymentData.lastName,shopper_permission:e.paymentData.shopperPermission},vault_payment_instrument:e.paymentData.shouldSaveInstrument,set_as_default_stored_instrument:e.paymentData.shouldSetAsDefaultInstrument}}}):function(e){return Boolean("object"==typeof e&&null!==e&&"bic"in e)}(e.paymentData)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{ideal:{bic:e.paymentData.bic}}}}):function(e){return Boolean("object"==typeof e&&null!==e&&"iban"in e&&!("firstName"in e)&&!("lastName"in e)&&!("shopperPermission"in e))}(e.paymentData)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{pay_by_bank:{iban:e.paymentData.iban}}}}):{methodId:e.methodId}));var t,n}_isBlueSnapDirectRedirectResponse(e){var t;if("object"!=typeof e||null===e)return!1;const n=e;if(!n.body)return!1;const i=n.body;return"additional_action_required"===i.status&&!!(null===(t=i.additional_action_required)||void 0===t?void 0:t.data.redirect_url)}}const al=vi(e=>new ol(e),[{gateway:"bluesnapdirect"}]);var sl;!function(e){e.ACKNOWLEDGE="ACKNOWLEDGE",e.FINALIZE="FINALIZE",e.INITIALIZE="INITIALIZE"}(sl||(sl={}));const dl=sl;var cl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ll{constructor(e){this._paymentIntegrationService=e}execute(e,t){return cl(this,void 0,void 0,function*(){const{payment:n}=e;if(!n)throw new co(["payment"]);if(!this._initializeOptions)throw new ri(ei.PaymentNotInitialized);const{onLoad:i,style:r}=this._initializeOptions,o=this._createIframe("bluesnapv2_hosted_payment_page",r),a=new En(new Promise(ce));i(o,()=>a.cancel(new Wi)),yield this._paymentIntegrationService.submitOrder(e,t),yield this._paymentIntegrationService.initializeOffsitePayment({methodId:n.methodId,gatewayId:n.gatewayId,shouldSaveInstrument:!1,target:o.name,promise:a.promise})})}finalize(e){return cl(this,void 0,void 0,function*(){const t=this._paymentIntegrationService.getState(),n=t.getOrder(),i=t.getPaymentStatus();if(!n||i!==dl.ACKNOWLEDGE&&i!==dl.FINALIZE)return Promise.reject(new Cd);yield this._paymentIntegrationService.finalizeOrder(e)})}initialize(e){return cl(this,void 0,void 0,function*(){this._initializeOptions=e&&e.bluesnapv2,yield Promise.resolve()})}deinitialize(){return Promise.resolve()}_createIframe(e,t){const n=document.createElement("iframe");if(n.setAttribute("sandbox","allow-top-navigation allow-scripts allow-forms allow-same-origin"),n.name=e,t){const{border:e,height:i,width:r}=t;n.style.border=null!=e?e:"",n.style.height=null!=i?i:"",n.style.width=null!=r?r:""}return n}}const ul=vi(e=>new ll(e),[{gateway:"bluesnapv2"}]);class hl{constructor(e){this.storage=e}saveExtraItemsData(e,t){const n=[...t.physicalItems,...t.digitalItems].reduce((e,t)=>(e[t.productId]={brand:t.brand?t.brand:"",category:t.categoryNames?t.categoryNames.join(", "):""},e),{});try{return this.storage.setItem(this.getStorageKey(e),JSON.stringify(n)),n}catch(e){return{}}}readExtraItemsData(e){try{const t=this.storage.getItem(this.getStorageKey(e));if(!t)return null;const n=JSON.parse(t);return function(e){if(!Z(e))return!1;const t=Object.values(e).some(e=>!Z(e)||!("brand"in e)||!("category"in e));return Boolean(!t)}(n)?n:null}catch(e){return null}}clearExtraItemData(e){try{this.storage.removeItem(this.getStorageKey(e))}catch(e){}}getStorageKey(e){return e?`ORDER_ITEMS_${e}`:""}}function pl(e){return Boolean(e.hasOwnProperty("analytics"))}function ml(e){return"object"==typeof e&&null!==e&&"shouldCreateAccount"in e}class yl extends Qn{constructor(e){super(),this.errorCode=e,this.name="BoltPaymentsFieldError",this.type="bolt_payments_field_error",this.body={errors:[yl.getError(e)]}}static getError(e){switch(e){case"1000":case"2000":case"3000":return{code:"invalid_number"};case"1001":case"2001":case"3001":return{code:"invalid_expiry_date"};case"1002":case"2002":return{code:"invalid_cvc"};case"1003":return{code:"invalid_zip"};case"2003":return{code:"incorrect_zip"};default:return{code:"general_error"}}}}var gl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vl{constructor(e,t,n){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.analyticsExtraItemsManager=n,this.useBoltClient=!1,this.useBoltEmbedded=!1}initialize(e){return gl(this,void 0,void 0,function*(){const{bolt:t,methodId:n}=e,{containerId:i,onPaymentSelect:r,useBigCommerceCheckout:o}=t||{};if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)return void(this.boltClient=yield this.boltScriptLoader.loadBoltClient());const a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{initializationData:s,config:d}=a,{publishableKey:c,developerConfig:l,embeddedOneClickEnabled:u}=s||{},{testMode:h}=d;if(!c)throw new ti(Xn.MissingPaymentMethod);if(this.boltClient=yield this.boltScriptLoader.loadBoltClient(c,h,l),this.useBoltClient=!u,this.useBoltEmbedded=!!u,this.useBoltEmbedded){if(!i)throw new fi('Unable to initialize payment because "options.bolt.containerId" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.bolt.onPaymentSelect" argument is not provided.');this.boltEmbedded=yield this.boltScriptLoader.loadBoltEmbedded(c,h,l),this.mountBoltEmbeddedField(i),r(yield this.hasBoltAccount())}})}deinitialize(){var e;return null===(e=this.embeddedField)||void 0===e||e.unmount(),this.boltClient=void 0,this.boltEmbedded=void 0,Promise.resolve()}finalize(){return Promise.reject(new Cd)}execute(e,t){return gl(this,void 0,void 0,function*(){this.setExtraItemsForAnalytics();const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const n={success:(n,i)=>{n.reference?e(n):t(new Qr("Unable to proceed because transaction reference is unavailable. Please try again later.")),i()},close:()=>{t(new Wi)}};s.configure({orderToken:r},{},n).open()});return{methodId:e,paymentData:{nonce:d.reference,shouldSaveInstrument:a}}})}getBoltEmbeddedPaymentPayload(e,t){var n;return gl(this,void 0,void 0,function*(){if(!ml(t))throw new ti(Xn.MissingPayment);const i=this.validateTokenizeResultOrThrow(yield null===(n=this.embeddedField)||void 0===n?void 0:n.tokenize());return{methodId:e,paymentData:{formattedPayload:{credit_card_token:{token:i.token,last_four_digits:i.last4,iin:i.bin,expiration_month:+i.expiration.split("-")[1],expiration_year:+i.expiration.split("-")[0]},provider_data:{create_account:!!t.shouldCreateAccount,embedded_checkout:!0}}}}})}getBoltFullCheckoutPaymentPayload(e,t){return gl(this,void 0,void 0,function*(){yield this.setBoltOrderId();const n=this.getBoltClientOrThrow(),i=yield n.getTransactionReference();if(!i)throw new Xr;return{methodId:e,paymentData:Object.assign(Object.assign({},t),{nonce:i})}})}getBoltClientOrThrow(){if(!this.boltClient)throw new ri(ei.PaymentNotInitialized);return this.boltClient}getBoltEmbeddedOrThrow(){if(!this.boltEmbedded)throw new ri(ei.PaymentNotInitialized);return this.boltEmbedded}hasBoltAccount(){return gl(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCustomer(),n=e.getBillingAddress(),i=(null==t?void 0:t.email)||(null==n?void 0:n.email)||"",r=this.getBoltClientOrThrow();try{return yield r.hasBoltAccount(i)}catch(e){throw new Xr}})}setBoltOrderId(){return gl(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getOrderOrThrow(),t=this.getBoltClientOrThrow();try{yield t.setOrderId(e.orderId)}catch(e){throw new Xr}})}mountBoltEmbeddedField(e){const t=this.getBoltEmbeddedOrThrow().create("payment_field",{styles:{backgroundColor:"#fff"},renderSeparateFields:!0});t.mount(`#${e}`),this.embeddedField=t}validateTokenizeResultOrThrow(e){if(!e)throw new Xr;if(e instanceof Error)throw new yl(e.message);const{token:t,last4:n,bin:i,expiration:r}=e,o=+n,a=+i,s=+`${r}`.split("-")[1],d=+`${r}`.split("-")[0];if(!t||Number.isNaN(o)||Number.isNaN(a)||Number.isNaN(s)||Number.isNaN(d))throw new co;return e}setExtraItemsForAnalytics(){const e=this.paymentIntegrationService.getState(),t=e.getStoreConfigOrThrow(),n=e.getCartOrThrow();if(t.checkoutSettings.isAnalyticsEnabled&&pl(window)){const{id:e,lineItems:t}=n;this.analyticsExtraItemsManager.saveExtraItemsData(e,t)}}}const fl=vi(e=>new vl(e,new ao(a()),new hl(Te)),[{id:"bolt"}]);function Sl(e){return!!e&&"accountNumber"in e&&"routingNumber"in e&&"ownershipType"in e&&"accountType"in e}var _l=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class wl{constructor(e,t){this.paymentIntegrationService=e,this.braintreeSdk=t}initialize(e){return _l(this,void 0,void 0,function*(){const{methodId:t,braintreeach:n}=e||{};if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');this.getMandateText=null==n?void 0:n.getMandateText,yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{clientToken:r,initializationData:o}=i;if(!r||!o)throw new ti(Xn.MissingPaymentMethod);this.braintreeSdk.initialize(r);try{this.usBankAccount=yield this.braintreeSdk.getUsBankAccount()}catch(e){this.handleBraintreeError(e)}})}execute(e,t){return _l(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew wl(e,(e=>{const t=new Ei(e),n=new Hi(a(),window,t);return new Ui(n)})(e)),[{id:"braintreeach"}]);class Cl{constructor(e){this.paymentIntegrationService=e,this.braintreeHostWindow=window}render(e,t,n){const i=t&&document.getElementById(t);if(this.braintreeHostWindow.paypal&&i){const r=this.paymentIntegrationService.getState(),o=r.getCartOrThrow(),a=r.getBillingAddressOrThrow(),s=r.getPaymentMethodOrThrow(e);if(!s.initializationData)return;const{paypalBNPLConfiguration:d=[]}=s.initializationData,c=n===fo.PAYMENT?"checkout":n,l=d&&d.find(({id:e})=>e===c);if(!l||!l.status)return;n===fo.CART&&(i.removeAttribute("data-pp-style-logo-type"),i.removeAttribute("data-pp-style-logo-position"),i.removeAttribute("data-pp-style-text-color"),i.removeAttribute("data-pp-style-text-size")),this.braintreeHostWindow.paypal.Messages({amount:o.cartAmount,buyerCountry:a.countryCode,placement:n,style:this.getPaypalMessagesStylesFromBNPLConfig(l)}).render(`#${t}`)}}getPaypalMessagesStylesFromBNPLConfig({styles:e}){const t={};return e.color&&(t.color=e.color),e.layout&&(t.layout=e.layout),(e["logo-type"]||e["logo-position"])&&(t.logo={},e["logo-type"]&&(t.logo.type=e["logo-type"]),e["logo-position"]&&(t.logo.position=e["logo-position"])),e.ratio&&(t.ratio=e.ratio),(e["text-color"]||e["text-size"])&&(t.text={},e["text-color"]&&(t.text.color=e["text-color"]),e["text-size"]&&(t.text.size=+e["text-size"])),t}}class bl{constructor(e){const{element:t,closeElement:n,mainElement:i}=this._createElements(e);this._element=t,this._closeElement=n,this._mainElement=i}show(e){this._mainElement.parentElement||(this._registerClick(e),document.body.appendChild(this._mainElement),setTimeout(()=>this._element.style.opacity="1"))}remove(){this._mainElement.parentElement&&(this._unregisterClick&&this._unregisterClick(),this._removeAfterTransition(),setTimeout(()=>this._element.style.opacity="0"))}_createElements(e){const t=document.createElement("div"),{background:n="rgba(0, 0, 0, 0.8)",id:i="checkoutOverlay",transitionDuration:r=400,hasCloseButton:o=!1,innerHtml:a=null}=e||{};let s,d,c,l,u=t;if(i&&(t.id=i),a){const e=document.createElement("div");l=`${i}--overlayText`,e.className=l,e.appendChild(a),t.appendChild(e)}return o&&(c=`${i}--close`,s=document.createElement("div"),s.className=c,d=`${i}--layout`,u=document.createElement("div"),u.className=d,u.appendChild(t),u.appendChild(s)),u.appendChild(function(e){const{id:t,background:n,transitionDuration:i,classLayout:r,classOverlayText:o,classClose:a}=e,s=document.createElement("style"),d=r?`, .${r}`:"";return s.id=`${t}--styles`,s.type="text/css",s.innerText=`\n #${t}${d} {\n display: block;\n height: 100%;\n width: 100%;\n left: 0;\n top: 0;\n position: fixed;\n z-index: 2147483647;\n }\n #${t} {\n transition: opacity ${i}ms ease-out;\n background: ${n};\n opacity: 0;\n }\n `,o&&(s.innerText+=`\n #${t} {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n #${t} .${o} {\n color: white;\n max-width: 330px;\n font-size: 1.2em;\n text-align: center;\n }\n `),a&&(s.innerText+=`\n #${t} {\n opacity: 1;\n }\n .${r} .${a} {\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 .${r} .${a}::after, .${r} .${a}::before {\n position: absolute;\n left: 8px;\n content: '';\n height: 16px;\n width: 2px;\n background-color: #fff;\n }\n .${r} .${a}::after {\n transform: rotate(-45deg);\n }\n .${r} .${a}::before {\n transform: rotate(45deg);\n }\n `),s}({id:i,background:n,transitionDuration:r,classLayout:d,classOverlayText:l,classClose:c})),{element:t,closeElement:s,mainElement:u}}_addEventListener(e,t){e&&t&&e.addEventListener("click",t)}_removeEventListener(e,t){e&&t&&e.removeEventListener("click",t)}_registerClick(e){if(this._unregisterClick&&this._unregisterClick(),e){const{onClick:t,onClickClose:n}=e;this._addEventListener(this._element,t),this._addEventListener(this._closeElement,n),this._unregisterClick=()=>{this._removeEventListener(this._element,t),this._removeEventListener(this._closeElement,n),this._unregisterClick=void 0}}}_removeAfterTransition(){const e=t=>{"opacity"===t.propertyName&&(this._mainElement.parentElement&&this._mainElement.remove(),this._element.removeEventListener("transitionend",e))};this._element.addEventListener("transitionend",e)}}const Pl={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"};function Ol(e){return"object"==typeof e&&null!==e&&"name"in e&&"BraintreeError"===e.name}function El(e){return{recipientName:`${e.firstName} ${e.lastName}`,line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,postalCode:e.postalCode,countryCode:e.countryCode,phone:e.phone}}var Al=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Tl{constructor(e,t,n,i){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeMessages=n,this.loadingIndicator=i,this.braintreeHostWindow=window}initialize(e){return Al(this,void 0,void 0,function*(){const{braintree:t,methodId:n}=e;if((null==t?void 0:t.containerId)&&(this.braintreeButtonOptions=t),this.paymentMethod&&this.paymentMethod.nonce||(this.paymentMethod=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n)),this.paymentMethod.clientToken&&(null==t?void 0:t.bannerContainerId))return yield this.loadPaypal(),this.loadPaypalCheckoutInstance(t);if(this.paymentMethod.clientToken)return this.loadPaypal();const i=yield this.paymentIntegrationService.loadPaymentMethod(n);if(this.paymentMethod=i.getPaymentMethodOrThrow(n),null==t?void 0:t.bannerContainerId)return this.loadPaypalCheckoutInstance(t);if(!this.paymentMethod.clientToken)throw new ti(Xn.MissingPaymentMethod);return this.loadPaypal()})}execute(e,t){var n;return Al(this,void 0,void 0,function*(){const{payment:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{o&&"function"==typeof o&&o(new Error("INSTRUMENT_DECLINED")),t()})),this.handleError(e)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.braintreeTokenizePayload=void 0,null===(e=this.paypalButtonRender)||void 0===e||e.close(),this.braintreeIntegrationService.teardown()}preparePaymentData(e,t){var n;return Al(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),r=i.getOutstandingBalance(t),o=i.getStoreConfig();if(!r)throw new ti(Xn.MissingCheckout);if(!o)throw new ti(Xn.MissingCheckoutConfig);if(!this.paymentMethod)throw new ri(ei.PaymentNotInitialized);const{currency:a,storeProfile:{storeLanguage:s}}=o,{nonce:d,config:{isVaultingEnabled:c}}=this.paymentMethod,{methodId:l,paymentData:u={}}=e,h=(null===(n=this.braintreeTokenizePayload)||void 0===n?void 0:n.nonce)||d;if(h){const t=yield this.paymentIntegrationService.loadPaymentMethod(l);return this.paymentMethod=t.getPaymentMethod(l),Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(h)})}if(xd(u)||(p=u,Boolean(p.instrumentId)&&!Object.prototype.hasOwnProperty.call(p,"ccNumber")&&!Object.prototype.hasOwnProperty.call(p,"ccCvv"))){if(!c)throw new fi("Vaulting is disabled but a vaulted instrument was being used for this transaction");return Promise.resolve(e)}var p;if(!jd(u))throw new ti(Xn.MissingPayment);const{shouldSaveInstrument:m,shouldSetAsDefaultInstrument:y}=u;if(m&&!c)throw new fi("Vaulting is disabled but shouldSaveInstrument is set to true");const g=i.getShippingAddress(),v=g?El(g):void 0;return Promise.all([this.braintreeIntegrationService.paypal({amount:r,locale:s,currency:a.code,offerCredit:"braintreepaypalcredit"===this.paymentMethod.id,shippingAddressOverride:v,shouldSaveInstrument:m||!1,shippingAddressEditable:!1}),this.braintreeIntegrationService.getSessionId()]).then(([{nonce:t,details:n}={},i])=>Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(t,n&&n.email,i,m,y)}))})}formattedPayload(e,t,n,i,r){return{formattedPayload:{vault_payment_instrument:i||null,set_as_default_stored_instrument:r||null,device_info:n||null,paypal_account:{token:e,email:t||null}}}}loadPaypalCheckoutInstance(e){return Al(this,void 0,void 0,function*(){const{clientToken:t,initializationData:n,id:i}=this.paymentMethod||{};if(!t)throw new ti(Xn.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(t);const r={currency:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,intent:null==n?void 0:n.intent,isCreditEnabled:null==n?void 0:n.isCreditEnabled},o="braintreepaypalcredit"===i||!(null==n?void 0:n.isCreditEnabled);yield this.braintreeIntegrationService.getPaypalCheckout(r,t=>{o&&i&&(null==e?void 0:e.bannerContainerId)&&this.renderPayPalMessages(i,e.bannerContainerId),this.renderPayPalButton(t,e)},this.handleError)}catch(e){this.handleError(e)}})}renderPayPalMessages(e,t){this.braintreeMessages.render(e,t,fo.PAYMENT)}renderPayPalButton(e,t){const{onPaymentError:n,submitForm:i,onRenderButton:r,containerId:o,onError:a}=t||{};if(!o)return;const s=this.getSmartButtonContainerId(o);if(!document.getElementById(s))throw new fi(`Unable to initialize payment because element with id ${o} does not exist.`);if(!this.paymentMethod)throw new ri(ei.PaymentNotInitialized);this.loadingIndicatorContainer=o.split("#")[1];const{id:d,config:{testMode:c}}=this.paymentMethod,{paypal:l}=this.braintreeHostWindow,u=null==l?void 0:l.FUNDING.PAYPAL;l&&u?(this.paypalButtonRender=l.Buttons({env:c?"sandbox":"production",commit:!1,fundingSource:u,onClick:()=>{this.toggleLoadingIndicator(!0)},createOrder:()=>this.setupPayment(e,d,n),onApprove:t=>Al(this,void 0,void 0,function*(){this.braintreeTokenizePayload=yield this.tokenizePaymentOrThrow(t,e),i&&"function"==typeof i&&i()}),onCancel:()=>{this.toggleLoadingIndicator(!1)},onError:e=>{this.toggleLoadingIndicator(!1),null==a||a(e)}}),r&&"function"==typeof r&&r(),this.paypalButtonRender.isEligible()&&this.paypalButtonRender.render(`${o}`)):this.removeElement(o.split("#")[1])}setupPayment(e,t,n){return Al(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState();try{const n=i.getCustomer(),r=i.getPaymentMethodOrThrow(t),o=i.getCheckoutOrThrow().outstandingBalance,a=i.getStoreConfigOrThrow().currency.code,s=i.getShippingAddress()||(null==n?void 0:n.addresses[0]),d=s?El(s):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:d,amount:o,currency:a,offerCredit:!1,intent:r.initializationData.intent})}catch(e){throw n&&(Ol(e)||e instanceof Qn)&&n(e),e}})}tokenizePaymentOrThrow(e,t,n){return Al(this,void 0,void 0,function*(){try{return yield t.tokenizePayment(e)}catch(e){throw n&&(Ol(e)||e instanceof Qn)&&n(e),e}})}loadPaypal(){return Al(this,void 0,void 0,function*(){const{clientToken:e,initializationData:t}=this.paymentMethod||{};if(!e||!t)throw new ti(Xn.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(e),yield this.braintreeIntegrationService.getPaypal()}catch(e){this.handleError(e)}return Promise.resolve()})}handleError(e){if(!Ol(e))throw e;if("PAYPAL_POPUP_CLOSED"===e.code)throw new Wi(e.message);throw new Qr(e.message)}isProviderError(e){var t,n,i;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"2046"===(null===(i=null===(n=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===n?void 0:n.provider_error)||void 0===i?void 0:i.code)}removeElement(e){const t=e&&document.getElementById(e);t&&t.remove()}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}getSmartButtonContainerId(e){var t;return null!==(t=e.split("#")[1])&&void 0!==t?t:e}}const kl=vi(e=>{const t=window,n=new bl,i=new Ei(e),r=new _o(new Hi(a(),t,i),t,n),o=new Cl(e);return new Tl(e,r,o,new vd({containerStyles:Pl}))},[{id:"braintreepaypal"},{id:"braintreepaypalcredit"}]);class Dl{constructor(e){this.requestSender=e}getOrderStatus(e="braintreelocalmethods",t){return n=this,i=void 0,o=function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}var Ml=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class zl{constructor(e,t,n,i,r=3e3,o=3e5){this.paymentIntegrationService=e,this.braintreeSdk=t,this.braintreeRequestSender=n,this.loadingIndicator=i,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.isLPMsUpdateExperimentEnabled=!1,this.pollingTimer=0,this.stopPolling=ce,this.isPollingEnabled=!1}initialize(e){return Ml(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,braintreelocalmethods:i}=e;if(this.gatewayId=t,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.braintreelocalmethods" argument is not provided.');this.braintreelocalmethods=i,this.loadingIndicatorContainer=i.container.split("#")[1],yield this.paymentIntegrationService.loadPaymentMethod(t);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(t),{clientToken:a,config:s,initializationData:d}=o,c=r.getStoreConfigOrThrow().checkoutSettings.features;if(this.isPollingEnabled=Ci(c,"PAYPAL-5258.braintree_local_methods_polling"),this.isLPMsUpdateExperimentEnabled=Ci(c,"PAYPAL-4853.add_new_payment_flow_for_braintree_lpms"),!a||!d||!s.merchantId)throw new ti(Xn.MissingPaymentMethod);try{this.braintreeSdk.initialize(a),this.isNonInstantPaymentMethod(n)||(this.braintreeLocalPayment=yield this.braintreeSdk.getBraintreeLocalPayment(s.merchantId))}catch(e){this.handleError(e)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return Ml(this,void 0,void 0,function*(){return this.toggleLoadingIndicator(!1),Promise.resolve()})}execute(e,t){return Ml(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{window.location.replace(t),this.toggleLoadingIndicator(!1),n()})}return this.handleError(e),Promise.reject(e)}})}executeWithInstantLPM(e,t,n){return Ml(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment)throw new Xr;yield new Promise((i,r)=>{var o;null===(o=this.braintreeLocalPayment)||void 0===o||o.startPayment(this.getInstantLPMConfig(e,t,n),this.getInstantLPMCallback(i,r,e,t,n))})})}getLPMsBasicPaymentData(){return Ml(this,void 0,void 0,function*(){const{deviceData:e}=yield this.braintreeSdk.getDataCollectorOrThrow();return{deviceSessionId:e}})}getInstantLPMConfig(e,t,n){const i=this.paymentIntegrationService.getState(),r=i.getCartOrThrow(),o=i.getBillingAddressOrThrow(),{firstName:a,lastName:s,countryCode:d}=o,{currency:c,email:l,lineItems:u}=r,h=u.physicalItems.length>0,p=i.getCheckoutOrThrow().outstandingBalance,m=i.getStoreConfigOrThrow().links.checkoutLink;return{paymentType:e,amount:p,fallback:{url:m,buttonText:"Complete Payment"},currencyCode:c.code,shippingAddressRequired:h,email:l,givenName:a,surname:s,address:{countryCode:d},onPaymentStart:(i,r)=>Ml(this,void 0,void 0,function*(){if(!this.isLPMsUpdateExperimentEnabled)return this.orderId=i.paymentId,void r();const o=yield this.getLPMsBasicPaymentData(),a=Object.assign(Object.assign({},o),{formattedPayload:{method:e,[`${e}_account`]:{order_id:i.paymentId}}});try{yield this.paymentIntegrationService.submitOrder(t,n),yield this.paymentIntegrationService.submitPayment({methodId:e,paymentData:a})}catch(t){if(this.isBraintreeOrderSavedResponse(t)&&t.body.additional_action_required.data.order_id_saved_successfully)return r(),this.isPollingEnabled?new Promise((t,n)=>{this.initializePollingMechanism(e,t,n,this.gatewayId)}):void 0;throw t}})}}getInstantLPMCallback(e,t,n,i,r){const o=this.paymentIntegrationService.getState().getCartOrThrow();return(a,s)=>Ml(this,void 0,void 0,function*(){if(a)return"LOCAL_PAYMENT_WINDOW_CLOSED"===a.code?(this.toggleLoadingIndicator(!1),this.resetPollingMechanism(),t()):(this.isPollingEnabled&&this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t(new Xr));const d=yield this.getLPMsBasicPaymentData(),c=Object.assign(Object.assign({},d),{formattedPayload:{method:n,[`${n}_account`]:Object.assign({email:o.email,token:s.nonce},this.isLPMsUpdateExperimentEnabled?{}:{order_id:this.orderId})}});try{return this.isLPMsUpdateExperimentEnabled||(yield this.paymentIntegrationService.submitOrder(i,r)),yield this.paymentIntegrationService.submitPayment({methodId:n,paymentData:c}),e(void 0)}catch(e){return this.handleError(e),t(e)}})}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}handleError(e){const{onError:t}=this.braintreelocalmethods||{};this.isPollingEnabled&&this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}isNonInstantPaymentMethod(e){return e.toUpperCase()in Di}isBraintreeRedirectError(e){var t;if("object"!=typeof e||null===e)return!1;const{body:n}=e;return!!n&&!!(null===(t=n.additional_action_required)||void 0===t?void 0:t.data.redirect_url)}isBraintreeOrderSavedResponse(e){var t;if("object"!=typeof e||null===e)return!1;const{body:n}=e;return!!n&&(null===(t=n.additional_action_required)||void 0===t?void 0:t.data.hasOwnProperty("order_id_saved_successfully"))}initializePollingMechanism(e,t,n,i){return Ml(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.braintreeRequestSender.getOrderStatus(i,{params:{useMetadata:!1}}),o=r.status===ki.Pending,a=r.status===ki.Completed,s=r.status===ki.Failed;if(a)return this.deinitializePollingMechanism(),t();if(s)return n();if(!a&&o&&this.pollingTimer{const t=window,i=new Ei(e),r=new Ui(new Hi(a(),t,i)),o=n(),s=new Dl(o);return new zl(e,r,s,new vd({styles:{backgroundColor:"black"}}))},[{gateway:"braintreelocalmethods"}]);function xl(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var Rl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Fl{constructor(e,t,n){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.braintreeSdk=n}initialize(e){var t;return Rl(this,void 0,void 0,function*(){const{methodId:n,braintreefastlane:i}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.braintreefastlane" argument is not provided.');if(!i.onInit||"function"!=typeof i.onInit)throw new fi('Unable to initialize payment because "options.braintreefastlane.onInit" argument is not provided or it is not a function.');if(!i.onChange||"function"!=typeof i.onChange)throw new fi('Unable to initialize payment because "options.braintreefastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(n);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(n),{initializationData:a,clientToken:s}=o||{},{isFastlaneStylingEnabled:d}=a||{},c=Ci(r.getStoreConfigOrThrow().checkoutSettings.features,"PROJECT-7080.braintree_fastlane_three_ds");this.is3DSEnabled=o.config.is3dsEnabled,s&&c&&this.braintreeSdk.initialize(s);const l=Ao(d?null===(t=o.initializationData)||void 0===t?void 0:t.fastlaneStyles:void 0,i.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(n,l),this.shouldRunAuthenticationFlow()&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow()),yield this.initializeCardComponent(),this.onError=i.onError,i.onInit(e=>this.renderBraintreeCardComponent(e)),i.onChange(()=>this.handleBraintreeStoredInstrumentChange(n))})}execute(e,t){return Rl(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{i.verifyCard({amount:null==r?void 0:r.orderAmount,nonce:e,bin:t,onLookupComplete:(e,t)=>{i.on("customer-canceled",()=>{"function"==typeof this.onError&&this.onError(new Wi),o(new Wi)}),t()}},(e,t)=>(e&&"THREEDS_VERIFY_CARD_CANCELED_BY_MERCHANT"===e.code&&("function"==typeof this.onError&&this.onError(new Wi),o(new Wi)),n(t.nonce)))})})}mapToPayPalAddress(e){return{streetAddress:(null==e?void 0:e.address1)||"",locality:(null==e?void 0:e.city)||"",region:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCodeAlpha2:(null==e?void 0:e.countryCode)||""}}shouldRunAuthenticationFlow(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getCustomerOrThrow(),i=e.getPaymentProviderCustomer(),r=xl(i)?i:{},o=this.braintreeFastlaneUtils.getSessionIdFromCookies();return!(!n.isGuest||(null==r?void 0:r.authenticationState)===Mi.CANCELED||(null==r?void 0:r.authenticationState)||o!==t.id)}getBraintreeCardComponentOrThrow(){if(!this.braintreeCardComponent)throw new mi;return this.braintreeCardComponent}getPayPalInstruments(){const e=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow();return(xl(e)?e:{}).instruments||[]}handleBraintreeStoredInstrumentChange(e){return Rl(this,void 0,void 0,function*(){const t=this.braintreeFastlaneUtils.getBraintreeFastlaneOrThrow(),{selectionChanged:n,selectedCard:i}=yield t.profile.showCardSelector();if(n){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),n=xl(t)?t:{},r=this.braintreeFastlaneUtils.mapPayPalToBcInstrument(e,[i]);if(r&&r.length>0)return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},n),{instruments:[...r]})),r[0]}})}}const Ll=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t),r=new Mo(e,i),o=new Hi(a(),t,n),s=new Ui(o);return new Fl(e,r,s)},[{id:"braintreeacceleratedcheckout"}]);var Bl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class jl{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n}initialize(e){return Bl(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:n}=e;if(!t)throw new fi('Unable to initialize payment because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState();this.paymentMethod=i.getPaymentMethodOrThrow(n);const r=i.getCheckoutOrThrow(),o=i.getStoreConfigOrThrow(),{clientToken:a,config:s}=this.paymentMethod||{};if(!a)throw new ti(Xn.MissingPaymentMethod);const{onError:d=ce,onPaymentSelect:c=ce}=t;this.braintreeSdk.initialize(a);const l=yield this.braintreeSdk.getBraintreeVisaCheckout(),u=yield this.braintreeSdk.getVisaCheckoutSdk(null==s?void 0:s.testMode),h=l.createInitOptions({settings:{locale:o.storeProfile.storeLanguage,shipping:{collectShipping:!1}},paymentRequest:{currencyCode:o.currency.code,subtotal:String(r.subtotal)}});yield u.init(h),u.on("payment.success",e=>this.tokenizePayment(l,e).then(()=>Promise.all([this.paymentIntegrationService.loadCheckout(),this.paymentIntegrationService.loadPaymentMethod(n)])).then(()=>c()).catch(e=>d(e))),u.on("payment.error",(e,t)=>d(t))})}execute(e,t){var n,i;return Bl(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const n=this.paymentIntegrationService.getState(),i=n.getShippingAddress(),r=n.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(i),billingAddress:a=this.mapToVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}mapToVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}postForm(e,t){const{userData:n,billingAddress:i,shippingAddress:r,details:o}=e,{userEmail:a}=n,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,i)),shipping_address:JSON.stringify(this.getAddress(a,r))})}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}handleError(e){if(e instanceof Error&&"BraintreeError"===e.name)throw new Qr(e.message);throw e}}const Ul=vi(e=>{const t=window,n=new Ei(e),i=new Ui(new Hi(a(),t,n));return new jl(e,Ee(),i)},[{id:"braintreevisacheckout"}]);var ql=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vl{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}initialize(e){return ql(this,void 0,void 0,function*(){const{methodId:t}=e;yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState();this.venmoOptions=e.braintreevenmo;const i=n.getPaymentMethodOrThrow(t);yield this.initializeBraintreeVenmo(i)})}execute(e){return ql(this,void 0,void 0,function*(){const{payment:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{var n;null===(n=this.braintreeVenmoCheckout)||void 0===n||n.tokenize((n,i)=>{if(n)return t(n);e(i)})})}}const Gl=vi(e=>{const t=window,n=a(),i=new Ei(e),r=new Hi(n,t,i),o=new _o(r,t);return new Vl(e,o)},[{id:"braintreevenmo"}]);var Hl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Wl{constructor(e,t,n){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeHostedForm=n}initialize(e){return Hl(this,void 0,void 0,function*(){const{methodId:t,gatewayId:n,braintree:i}=e;yield this.paymentIntegrationService.loadPaymentMethod(t);const r=this.paymentIntegrationService.getState();this.paymentMethod=r.getPaymentMethodOrThrow(t);const{clientToken:o}=this.paymentMethod;if(!o)throw new ti(Xn.MissingPaymentMethod);this.threeDSecure=null==i?void 0:i.threeDSecure,this.onPaymentError=null==i?void 0:i.onPaymentError;try{this.braintreeIntegrationService.initialize(o,this.threeDSecure),this.isHostedPaymentFormEnabled(t,n)&&(null==i?void 0:i.form)&&(yield this.braintreeHostedForm.initialize(i.form,i.unsupportedCardBrands,o),this.isHostedFormInitialized=this.braintreeHostedForm.isInitialized()),this.is3dsEnabled=this.paymentMethod.config.is3dsEnabled,this.deviceSessionId=yield this.braintreeIntegrationService.getSessionId(),this.shouldInitializeBraintreeFastlane()&&(yield this.initializeBraintreeFastlaneOrThrow(t))}catch(e){return this.handleError(e,t)}})}execute(e){return Hl(this,void 0,void 0,function*(){const{payment:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r"string"==typeof e));var n}var Kl,Jl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e[e.CreditCard=0]="CreditCard",e[e.StoredCardVerification=1]="StoredCardVerification"}(Kl||(Kl={}));class Zl{constructor(e,t){this.braintreeScriptLoader=e,this.braintreeSDKVersionManager=t,this.isInitializedHostedForm=!1,this.handleBlur=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onBlur)||void 0===n||n.call(t,{fieldType:this.mapFieldType(e.emittedBy),errors:this.mapErrors(e.fields)})},this.handleFocus=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onFocus)||void 0===n||n.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleCardTypeChange=e=>{var t,n;const i=1===e.cards.length?e.cards[0].type.replace(/^master-card$/,"mastercard"):void 0;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onCardTypeChange)||void 0===n||n.call(t,{cardType:i})},this.handleInputSubmitRequest=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onEnter)||void 0===n||n.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleValidityChange=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===n||n.call(t,{isValid:this.isValidForm(e),errors:this.mapValidationErrors(e.fields)})}}initialize(e,t,n){var i,r,o,a,s;return Jl(this,void 0,void 0,function*(){this.clientToken=n,this.formOptions=e,this.type=$l(e.fields)?Kl.CreditCard:Kl.StoredCardVerification;const d=this.mapFieldOptions(e.fields,t);$(d)?this.isInitializedHostedForm=!1:(this.cardFields=yield this.createHostedFields({fields:d,styles:e.styles&&this.mapStyleOptions(e.styles)}),null===(i=this.cardFields)||void 0===i||i.on("blur",this.handleBlur),null===(r=this.cardFields)||void 0===r||r.on("focus",this.handleFocus),null===(o=this.cardFields)||void 0===o||o.on("cardTypeChange",this.handleCardTypeChange),null===(a=this.cardFields)||void 0===a||a.on("validityChange",this.handleValidityChange),null===(s=this.cardFields)||void 0===s||s.on("inputSubmitRequest",this.handleInputSubmitRequest),this.isInitializedHostedForm=!0)})}isInitialized(){return!!this.isInitializedHostedForm}deinitialize(){var e;return Jl(this,void 0,void 0,function*(){this.isInitializedHostedForm&&(this.isInitializedHostedForm=!1,yield null===(e=this.cardFields)||void 0===e?void 0:e.teardown())})}validate(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);const e=this.cardFields.getState();if(!this.isValidForm(e)){this.handleValidityChange(e);const t=this.mapValidationErrors(e.fields);throw new lo(t)}}tokenize(e){var t,n,i,r,o;return Jl(this,void 0,void 0,function*(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);try{const r=yield this.cardFields.tokenize(ue({billingAddress:e&&this.mapBillingAddress(e)},J));return null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===n||n.call(t,{isValid:!0,errors:{}}),{nonce:r.nonce,bin:null===(i=r.details)||void 0===i?void 0:i.bin}}catch(e){if(Yl(e)){const t=this.mapTokenizeError(e);if(t)throw null===(o=null===(r=this.formOptions)||void 0===r?void 0:r.onValidate)||void 0===o||o.call(r,{isValid:!1,errors:t}),new lo(t)}throw e}})}tokenizeForStoredCardVerification(){var e,t,n,i,r;return Jl(this,void 0,void 0,function*(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);try{const i=yield this.cardFields.tokenize();return null===(t=null===(e=this.formOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,{isValid:!0,errors:{}}),{nonce:i.nonce,bin:null===(n=i.details)||void 0===n?void 0:n.bin}}catch(e){if(Yl(e)){const t=this.mapTokenizeError(e,!0);if(t)throw null===(r=null===(i=this.formOptions)||void 0===i?void 0:i.onValidate)||void 0===r||r.call(i,{isValid:!1,errors:t}),new lo(t)}throw e}})}createHostedFields(e){return Jl(this,void 0,void 0,function*(){const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadHostedFields(),i=this.braintreeSDKVersionManager.getSDKVersion()===bi?Object.assign(Object.assign({},e),{preventCursorJumps:!0}):e;return n.create(Object.assign(Object.assign({},i),{client:t}))})}getClient(){return Jl(this,void 0,void 0,function*(){if(!this.clientToken)throw new ri(ei.PaymentNotInitialized);if(!this.client){const e=yield this.braintreeScriptLoader.loadClient();this.client=e.create({authorization:this.clientToken})}return this.client})}mapBillingAddress(e){return{countryName:e.country,postalCode:e.postalCode,streetAddress:e.address2?`${e.address1} ${e.address2}`:e.address1}}mapFieldOptions(e,t){if($l(e)){const n={};return null==t||t.forEach(e=>{(e=>Object.values(xi).includes(e))(e)&&(n[e]=!1)}),ue({number:Object.assign({container:`#${e.cardNumber.containerId}`,placeholder:e.cardNumber.placeholder,internalLabel:e.cardNumber.accessibilityLabel},Object.keys(n).length>0?{supportedCardBrands:n}:{}),expirationDate:{container:`#${e.cardExpiry.containerId}`,placeholder:e.cardExpiry.placeholder,internalLabel:e.cardExpiry.accessibilityLabel},cvv:e.cardCode&&{container:`#${e.cardCode.containerId}`,placeholder:e.cardCode.placeholder,internalLabel:e.cardCode.accessibilityLabel},cardholderName:{container:`#${e.cardName.containerId}`,placeholder:e.cardName.placeholder,internalLabel:e.cardName.accessibilityLabel}},J)}return ue({number:e.cardNumberVerification&&{container:`#${e.cardNumberVerification.containerId}`,placeholder:e.cardNumberVerification.placeholder},cvv:e.cardCodeVerification&&{container:`#${e.cardCodeVerification.containerId}`,placeholder:e.cardCodeVerification.placeholder}},J)}mapStyleOptions(e){const t=(e={})=>ue({color:e.color,"font-family":e.fontFamily,"font-size":e.fontSize,"font-weight":e.fontWeight},J);return{input:t(e.default),".invalid":t(e.error),":focus":t(e.focus)}}mapFieldType(e){switch(e){case"number":return this.type===Kl.StoredCardVerification?Bi.CardNumberVerification:Bi.CardNumber;case"expirationDate":return Bi.CardExpiry;case"cvv":return this.type===Kl.StoredCardVerification?Bi.CardCodeVerification:Bi.CardCode;case"cardholderName":return Bi.CardName;default:throw new Error("Unexpected field type")}}mapErrors(e){const t={};if(e)for(const[n,i]of Object.entries(e))if(i&&this.isValidParam(n)){const{isValid:e,isEmpty:r,isPotentiallyValid:o}=i;t[n]={isValid:e,isEmpty:r,isPotentiallyValid:o}}return t}mapValidationErrors(e){return Object.keys(e).reduce((t,n)=>{var i;return Object.assign(Object.assign({},t),{[this.mapFieldType(n)]:(null===(i=e[n])||void 0===i?void 0:i.isValid)?void 0:[this.createInvalidError(this.mapFieldType(n))]})},{})}mapTokenizeError(e,t=!1){var n,i;if("HOSTED_FIELDS_FIELDS_EMPTY"===e.code){const e=[this.createRequiredError(this.mapFieldType("cvv"))];return t?{[this.mapFieldType("cvv")]:e}:{[this.mapFieldType("cvv")]:e,[this.mapFieldType("expirationDate")]:[this.createRequiredError(this.mapFieldType("expirationDate"))],[this.mapFieldType("number")]:[this.createRequiredError(this.mapFieldType("number"))],[this.mapFieldType("cardholderName")]:[this.createRequiredError(this.mapFieldType("cardholderName"))]}}return null===(i=null===(n=e.details)||void 0===n?void 0:n.invalidFieldKeys)||void 0===i?void 0:i.reduce((e,t)=>{const n=this.mapFieldType(t);return Object.assign(Object.assign({},e),{[n]:[this.createInvalidError(n)]})},{})}createRequiredError(e){var t;return{fieldType:e,message:null!==(t={[Bi.CardCode]:"CVV is required",[Bi.CardCodeVerification]:"CVV is required",[Bi.CardNumber]:"Credit card number is required",[Bi.CardNumberVerification]:"Credit card number is required",[Bi.CardExpiry]:"Expiration date is required",[Bi.CardName]:"Full name is required"}[e])&&void 0!==t?t:"Field is required",type:"required"}}createInvalidError(e){var t,n,i,r;const o={[Bi.CardCode]:{message:"Invalid card code",type:"invalid_card_code"},[Bi.CardCodeVerification]:{message:"Invalid card code",type:"invalid_card_code"},[Bi.CardNumber]:{message:"Invalid card number",type:"invalid_card_number"},[Bi.CardNumberVerification]:{message:"Invalid card number",type:"invalid_card_number"},[Bi.CardExpiry]:{message:"Invalid card expiry",type:"invalid_card_expiry"},[Bi.CardName]:{message:"Invalid card name",type:"invalid_card_name"}};return{fieldType:e,message:null!==(n=null===(t=o[e])||void 0===t?void 0:t.message)&&void 0!==n?n:"Invalid field",type:null!==(r=null===(i=o[e])||void 0===i?void 0:i.type)&&void 0!==r?r:"invalid"}}isValidForm(e){return Object.keys(e.fields).every(t=>{var n;return null===(n=e.fields[t])||void 0===n?void 0:n.isValid})}isValidParam(e){return["number","cvv","expirationDate","postalCode","cardholderName","cardType"].includes(e)}}const Ql=vi(e=>{const t=window,n=new Ei(e),i=new Hi(a(),t,n),r=new _o(i,t),o=new Zl(i,n);return new Wl(e,r,o)},[{id:"braintree"}]);var Xl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})},eu=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r(this._shouldRenderHostedForm=!0,this._hostedForm=r,Promise.resolve()))}deinitialize(){return this._hostedForm&&this._hostedForm.detach(),Promise.resolve()}finalize(){return Promise.reject(new Cd)}_executeWithoutHostedForm(e,t){return Xl(this,void 0,void 0,function*(){const{payment:n}=e,i=eu(e,["payment"]),r=n&&n.paymentData;if(!n||!r)throw new co(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(i,t),yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:r}))})}_executeWithHostedForm(e,t){return Xl(this,void 0,void 0,function*(){const{payment:n}=e,i=eu(e,["payment"]),r=this._hostedForm;if(!r)throw new ri(ei.PaymentNotInitialized);if(!n||!n.methodId)throw new co(["payment.methodId"]);yield this._paymentIntegrationService.submitOrder(i,t),yield r.validate().then(()=>r.submit(n))})}_isHostedPaymentFormEnabled(e,t){return!!e&&!0===this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t).config.isHostedFormEnabled}_isHostedFieldAvailable(e){return!Ce(e&&e.creditCard&&e.creditCard.form.fields).every(J)}}var nu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class iu extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this.cbaMGPSScriptLoader=t,this.sessionId=""}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return nu(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{methodId:n}=e;yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(n);if(!function(e){return"object"==typeof e&&null!==e&&"initializationData"in e&&"object"==typeof e.initializationData&&null!==e.initializationData&&"merchantId"in e.initializationData&&"string"==typeof e.initializationData.merchantId&&("boolean"==typeof e.initializationData.isTestModeFlagEnabled||void 0===e.initializationData.isTestModeFlagEnabled)}(r))throw new ti(Xn.MissingPaymentMethod);const{clientToken:o,initializationData:{isTestModeFlagEnabled:a=!1,merchantId:s},config:{is3dsEnabled:d}}=r;if(d){if(this.threeDSjs=yield this.cbaMGPSScriptLoader.load(a),!this.threeDSjs)throw new ri(ei.PaymentNotInitialized);if(!o||!s)throw new ti(Xn.MissingPaymentMethod);if(this.sessionId=o,this.locale=i.getLocale(),!this.locale)throw new ti(Xn.MissingCart);yield this.threeDSjs.configure({merchantId:s,sessionId:this.sessionId,callback:()=>{var e;if(null===(e=this.threeDSjs)||void 0===e?void 0:e.isConfigured())return this.paymentIntegrationService.getState();throw new Qr("Failed to configure 3DS API.")},configuration:{userLanguage:this.locale,wsVersion:62}})}return Promise.resolve()})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return nu(this,void 0,void 0,function*(){const{payment:i}=e,r=i&&i.paymentData;if(!i||!r)throw new co(["payment.paymentData"]);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i.methodId),{is3dsEnabled:a}=o.config;if(a){const t=Object.assign(Object.assign({},r),{threeDSecure:{token:this.sessionId}});e.payment&&(e.payment.paymentData=t)}return n.execute.call(this,e,t).catch(e=>{if(!a||!pa(e)||!ve(e.body.errors,{code:"three_d_secure_required"}))return Promise.reject(e);const t=this.paymentIntegrationService.getState(),n=t.getOrder(),{storeProfile:{storeId:i}}=t.getStoreConfigOrThrow();if(!n||!this.sessionId)throw new ti(Xn.MissingCheckout);const r=`${i}_${n.orderId}`;if("object"!=typeof(o=e.body)||null===o||!("three_ds_result"in o)||"object"!=typeof o.three_ds_result||null===o.three_ds_result||!("token"in o.three_ds_result)||"string"!=typeof o.three_ds_result.token)throw new nr;var o;const{three_ds_result:{token:s}}=e.body;return s?this.initiateAuthentication(r,s):Promise.reject(e)})})}finalize(e){return nu(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE?(yield this.paymentIntegrationService.finalizeOrder(e),Promise.resolve()):Promise.reject(new Cd)})}deinitialize(){return this.threeDSjs=void 0,this.sessionId="",super.deinitialize()}initiateAuthentication(e,t){return nu(this,void 0,void 0,function*(){const n=yield new Promise((n,i)=>{if(!this.threeDSjs)throw new ri(ei.PaymentNotInitialized);this.threeDSjs.initiateAuthentication(e,t,e=>{const t=e.error;return t?i(new Qr(t.msg)):this.threeDSjs&&"PROCEED"===e.gatewayRecommendation?n(e.restApiResponse):i(new Qr)})});if(n.transaction&&"AUTHENTICATION_AVAILABLE"===n.transaction.authenticationStatus)return this.authenticatePayer(e,t);throw new Qr})}authenticatePayer(e,t,n=1){return nu(this,void 0,void 0,function*(){return new Promise((i,r)=>{if(!this.threeDSjs)return r(new ri(ei.PaymentNotInitialized));this.threeDSjs.authenticatePayer(e,t,i=>nu(this,void 0,void 0,function*(){const o=i.error;return o?o.cause&&"SERVER_BUSY"===o.cause&&n<5?(yield new Promise(e=>setTimeout(e,3e3)),this.authenticatePayer(e,t,++n)):r(new Qr):new Promise(ce)}),{fullScreenRedirect:!0})})})}}class ru{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e){return t=this,n=void 0,r=function*(){if(yield this._scriptLoader.loadScript(`//${e?"test":"ap"}-gateway.mastercard.com/static/threeDS/1.3.0/three-ds.min.js`),!this._window.ThreeDS)throw new mi;return this._window.ThreeDS},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const ou=vi(e=>new iu(e,new ru(a())),[{id:"cba_mpgs"}]);var au;!function(e){e.OffsiteRedirect="offsite_redirect"}(au||(au={}));class su extends tu{constructor(e){super(e),this.paymentIntegrationService=e}finalize(e){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),Promise.reject(new Cd)}_executeWithHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{window.location.replace(e.data.redirect_url)})}}class du extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew du(e),[{gateway:"checkoutcom",id:"fawry"}]);function lu(e){return pa(e)&&ve(e.body.errors,{code:"three_d_secure_required"})}var uu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})},hu=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rthis.formPoster.postForm(t,{PaReq:n||null,TermUrl:i||null,MD:r||null}))}}const mu=vi(e=>new pu(e,Ee()),[{gateway:"checkoutcom",id:"credit_card"},{gateway:"checkoutcom",id:"card"}]);class yu extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew yu(e),[{gateway:"checkoutcom",id:"sepa"}]);class vu extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew vu(e),[{gateway:"checkoutcom",id:"ideal"}]);const Su=["boleto","oxxo","qpay","ideal"];class _u extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew _u(e),[{gateway:"checkoutcom"}]);var Iu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Cu{constructor(e,t){this._paymentIntegrationService=e,this._clearpayScriptLoader=t}initialize(e){return Iu(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:t}=this._paymentIntegrationService.getState(),n=t(e.methodId,e.gatewayId),i=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features;this._clearpaySdk=yield this._clearpayScriptLoader.load(n,i)})}deinitialize(){return this._clearpaySdk=void 0,Promise.resolve()}execute(e,t){return Iu(this,void 0,void 0,function*(){const{gatewayId:n,methodId:i}=e.payment||{};if(!n||!i)throw new co(["payment.gatewayId","payment.methodId"]);const r=this._paymentIntegrationService.getState(),{isStoreCreditApplied:o}=r.getCheckoutOrThrow();yield this._paymentIntegrationService.applyStoreCredit(o),yield this._paymentIntegrationService.validateCheckout(r.getCheckout(),t);const{countryCode:a}=r.getBillingAddressOrThrow();if(!this._isCountrySupported(a))throw new fi("Unable to proceed because billing country is not supported.");return yield this._loadPaymentMethod(n,i,t),yield this._redirectToClearpay(a,this._paymentIntegrationService.getState().getPaymentMethod(i,n)),new Promise(ce)})}finalize(e){var t,n,i;return Iu(this,void 0,void 0,function*(){const r=this._paymentIntegrationService.getState(),o=r.getPaymentId(),a=r.getContextConfig();if(!o)throw new ti(Xn.MissingCheckout);if(!a||!a.payment.token)throw new ti(Xn.MissingCheckoutConfig);const s={methodId:o.providerId,paymentData:{nonce:a.payment.token}};yield this._paymentIntegrationService.submitOrder({},e);try{yield this._paymentIntegrationService.submitPayment(s)}catch(e){if(yield this._paymentIntegrationService.forgetCheckout(o.providerId),yield this._paymentIntegrationService.loadPaymentMethods(),pa(e))throw new Kd(null===(i=null===(n=null===(t=e.body)||void 0===t?void 0:t.errors)||void 0===n?void 0:n[0])||void 0===i?void 0:i.message)}})}_redirectToClearpay(e,t){return Iu(this,void 0,void 0,function*(){if(!this._clearpaySdk||!t||!t.clientToken)throw new ri(ei.PaymentNotInitialized);return this._clearpaySdk.initialize({countryCode:e}),this._clearpaySdk.redirect({token:t.clientToken}),Promise.resolve()})}_isCountrySupported(e){return"GB"===e}_loadPaymentMethod(e,t,n){var i;return Iu(this,void 0,void 0,function*(){try{return yield this._paymentIntegrationService.loadPaymentMethod(e,Object.assign(Object.assign({},n),{params:Object.assign(Object.assign({},null==n?void 0:n.params),{method:t})}))}catch(e){if(e instanceof nr&&422===(null===(i=e.body)||void 0===i?void 0:i.status))throw new fi("Clearpay can't process your payment for this order, please try another payment method");throw e}})}}class bu{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e,t={}){return n=this,i=void 0,o=function*(){if(yield this._scriptLoader.loadScript(this._getScriptUrl(e.config.testMode,t)),!this._window.AfterPay)throw new mi;return this._window.AfterPay},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_getScriptUrl(e,t={}){const n=Ci(t,"PI-4555.clearpay_add_https_to_prod_script",!1);return e?n?"https://portal.sandbox.clearpay.co.uk/afterpay-async.js":"//portal.sandbox.clearpay.co.uk/afterpay-async.js":n?"https://portal.clearpay.co.uk/afterpay-async.js":"//portal.clearpay.co.uk/afterpay-async.js"}}const Pu=vi(e=>new Cu(e,new bu(a())),[{gateway:"clearpay"},{id:"clearpay"}]),Ou=vi(e=>new tu(e),[{default:!0}]);var Eu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Au{constructor(e,t){this._paymentIntegrationService=e,this._cardinalClient=t}prepare(e){return Eu(this,void 0,void 0,function*(){yield this._cardinalClient.load(e.id,e.config.testMode),yield this._cardinalClient.configure(yield this._getClientToken(e))})}start(e,t,n,i){return Eu(this,void 0,void 0,function*(){const{getCardInstrument:r,getPaymentMethodOrThrow:o}=this._paymentIntegrationService.getState(),{payment:{methodId:a="",paymentData:s={}}={}}=t,d=xd(s)&&r(s.instrumentId),c=d?d.iin:i&&i.getBin();c&&(yield this._cardinalClient.runBinProcess(c));try{return yield e(de(t,{payment:{paymentData:{threeDSecure:{token:o(a).clientToken}}}}),n)}catch(e){if(!pa(e)||!ve(e.body.errors,{code:"three_d_secure_required"}))throw e;const n=yield this._cardinalClient.getThreeDSecureData(e.body.three_ds_result,this._getOrderData());if(!i)return void(yield this._paymentIntegrationService.submitPayment(de(t.payment,{paymentData:{threeDSecure:n}})));yield i.submit(de(t.payment,{paymentData:{threeDSecure:n}}))}})}_getClientToken(e){return Eu(this,void 0,void 0,function*(){return e.clientToken?e.clientToken:(yield this._paymentIntegrationService.loadPaymentMethod(e.id),this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.id).clientToken||"")})}_getOrderData(){const e=this._paymentIntegrationService.getState(),t=e.getBillingAddressOrThrow(),n=e.getShippingAddress(),i=e.getCheckoutOrThrow(),r=e.getOrderOrThrow();return{billingAddress:t,shippingAddress:n,currencyCode:i.cart.currency.code,id:r.orderId.toString(),amount:i.cart.cartAmount}}}const Tu=[100004,1010,1011,1020];var ku,Du,Mu,zu,Nu,xu,Ru;!function(e){e.SetupCompleted="payments.setupComplete",e.Validated="payments.validated"}(ku||(ku={})),function(e){e.Init="init",e.Complete="complete",e.Confirm="confirm"}(Du||(Du={})),function(e){e.Success="SUCCESS",e.NoAction="NOACTION",e.Failure="FAILURE",e.Error="ERROR"}(Mu||(Mu={})),function(e){e.CCA="CCA",e.Paypal="Paypal",e.Wallet="Wallet",e.VisaCheckout="VisaCheckout",e.ApplePay="ApplePay",e.DiscoverWallet="DiscoverWallet"}(zu||(zu={})),function(e){e.BinProcess="bin.process"}(Nu||(Nu={})),function(e){e.CCA="cca"}(xu||(xu={})),function(e){e.Yes="Y",e.No="N"}(Ru||(Ru={}));class Fu{constructor(e){this._scriptLoader=e,this._provider="",this._testMode=!1,this._configurationToken=""}load(e,t=!1){return this._provider=e,this._testMode=t,this._sdk||(this._sdk=this._scriptLoader.load(e,t)),this._sdk.then(ce)}configure(e){if(this._configurationToken){if(this._configurationToken===e)return Promise.resolve();this._sdk=this._scriptLoader.load(`${this._provider}.${Date.now()}`,this._testMode)}return this._getClientSDK().then(t=>new Promise((n,i)=>{t.on(ku.SetupCompleted,()=>{t.off(ku.SetupCompleted),t.off(ku.Validated),this._configurationToken=e,n()}),t.on(ku.Validated,e=>{t.off(ku.SetupCompleted),t.off(ku.Validated),e.ActionCode===Mu.Error&&(H(Tu,e.ErrorNumber)&&i(new ti(Xn.MissingPaymentMethod)),i(new Qr(e.ErrorDescription)))}),t.setup(Du.Init,{jwt:e})}))}runBinProcess(e){return this._getClientSDK().then(t=>t.trigger(Nu.BinProcess,e).catch(ce)).then(e=>{if(!e||!e.Status)throw new ri(ei.PaymentNotInitialized)})}getThreeDSecureData(e,t){return this._getClientSDK().then(n=>new Promise((i,r)=>{n.on(ku.Validated,(e,t)=>{if(n.off(ku.Validated),!t)return r(new Qr(e.ErrorDescription?e.ErrorDescription:"An error was encountered while processing the transaction."));if(!e.ActionCode)return i({token:t});switch(e.ActionCode){case Mu.Success:return i({token:t});case Mu.NoAction:return e.ErrorNumber>0?r(new Qr(e.ErrorDescription)):e.Payment&&e.Payment.ExtendedData&&e.Payment.ExtendedData.SignatureVerification===Ru.Yes?i({token:t}):r(new Qr("Transaction signature could not be validated."));case Mu.Failure:return r(new Qr("User failed authentication or an error was encountered while processing the transaction."));case Mu.Error:return r(new Qr(e.ErrorDescription))}});const o={AcsUrl:e.acs_url,Payload:e.merchant_data},a=this._mapToPartialOrder(t,e.payer_auth_request);n.continue(xu.CCA,o,a)}))}_mapToPartialOrder(e,t){const n={BillingAddress:this._mapToCardinalAddress(e.billingAddress)};return e.paymentData&&(n.Account=this._mapToCardinalAccount(e.paymentData)),e.billingAddress.email&&(n.Email1=e.billingAddress.email),e.shippingAddress&&(n.ShippingAddress=this._mapToCardinalAddress(e.shippingAddress)),{Consumer:n,OrderDetails:{OrderNumber:e.id,Amount:e.amount,CurrencyCode:e.currencyCode,OrderChannel:"S",TransactionId:t}}}_mapToCardinalAccount(e){return{AccountNumber:Number(e.ccNumber),ExpirationMonth:Number(e.ccExpiry.month),ExpirationYear:Number(e.ccExpiry.year),NameOnAccount:e.ccName,CardCode:Number(e.ccCvv)}}_mapToCardinalAddress(e){const t={FirstName:e.firstName,LastName:e.lastName,Address1:e.address1,City:e.city,State:e.stateOrProvince,PostalCode:e.postalCode,CountryCode:e.countryCode};return e.address2&&(t.Address2=e.address2),e.phone&&(t.Phone1=e.phone),t}_getClientSDK(){if(!this._sdk)throw new ri(ei.PaymentNotInitialized);return this._sdk}}class Lu{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e,t){const n=t?"https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js":"https://static.client.cardinaltrusted.com/songbird/v2.0.0/songbird.js";return this._scriptLoader.loadScript(`${n}?v=${e}`).then(()=>{if(!this._window.Cardinal)throw new mi;return this._window.Cardinal})}}var Bu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ju extends tu{constructor(e,t){super(e),this._threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Bu(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),i=n(e.methodId);i.config.is3dsEnabled&&(yield this._threeDSecureFlow.prepare(i))})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return Bu(this,void 0,void 0,function*(){const{payment:{methodId:i=""}={}}=e,{getPaymentMethodOrThrow:r}=this._paymentIntegrationService.getState();return r(i).config.is3dsEnabled?this._threeDSecureFlow.start(n.execute.bind(this),e,t,this._hostedForm):n.execute.call(this,e,t)})}}const Uu=vi(e=>new ju(e,new Au(e,new Fu(new Lu(a())))),[{id:"cybersource"}]);var qu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vu{constructor(e,t){this._paymentIntegrationService=e,this._cardinalClient=t}prepare(e){return qu(this,void 0,void 0,function*(){yield this._cardinalClient.load(e.id,e.config.testMode)})}start(e,t,n,i){var r,o,a,s;return qu(this,void 0,void 0,function*(){const{getCardInstrument:d}=this._paymentIntegrationService.getState(),{payment:c={methodId:""}}=t,{paymentData:l={}}=c;try{return yield e(t,n)}catch(e){if(pa(e)&&"additional_action_required"===(null===(r=e.body)||void 0===r?void 0:r.status)){const t=null===(a=null===(o=e.body.additional_action_required)||void 0===o?void 0:o.data)||void 0===a?void 0:a.token,n=null===(s=e.body.three_ds_result)||void 0===s?void 0:s.payer_auth_request;yield this._cardinalClient.configure(t);const r=this._getBin(l,d,i);r&&(yield this._cardinalClient.runBinProcess(r));try{return yield this._submitPayment(c,{xid:n},i)}catch(e){if(pa(e)&&ve(e.body.errors,{code:"three_d_secure_required"})){const t=e.body.three_ds_result,n=null==t?void 0:t.payer_auth_request;return yield this._cardinalClient.getThreeDSecureData(t,this._getOrderData()),this._submitPayment(c,{token:n},i)}throw e}}throw e}})}_getOrderData(){const e=this._paymentIntegrationService.getState(),t=e.getBillingAddressOrThrow(),n=e.getShippingAddress(),{cart:{currency:{code:i},cartAmount:r}}=e.getCheckoutOrThrow();return{billingAddress:t,shippingAddress:n,currencyCode:i,id:e.getOrderOrThrow().orderId.toString(),amount:r}}_submitPayment(e,t,n){return qu(this,void 0,void 0,function*(){const i=de({},e,{paymentData:{threeDSecure:t}});n||(yield this._paymentIntegrationService.submitPayment(i)),yield null==n?void 0:n.submit(i)})}_getBin(e,t,n){const i=xd(e)&&t(e.instrumentId),r=function(e){const t=e;return!xd(t)&&"string"==typeof t.ccName&&"string"==typeof t.ccNumber&&"object"==typeof t.ccExpiry&&"string"==typeof t.ccExpiry.month&&"string"==typeof t.ccExpiry.year}(e)&&e.ccNumber,o=n?n.getBin():r;return(i?i.iin:o)||""}}var Gu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Hu extends tu{constructor(e,t){super(e),this._threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Gu(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),i=n(e.methodId);i.config.is3dsEnabled&&(yield this._threeDSecureFlow.prepare(i))})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return Gu(this,void 0,void 0,function*(){const{payment:{methodId:i=""}={}}=e,{getPaymentMethodOrThrow:r}=this._paymentIntegrationService.getState();return r(i).config.is3dsEnabled?this._threeDSecureFlow.start(n.execute.bind(this),e,t,this._hostedForm):n.execute.call(this,e,t)})}}const Wu=vi(e=>new Hu(e,new Vu(e,new Fu(new Lu(a())))),[{id:"cybersourcev2"},{id:"bnz"}]);function $u(e){return"object"==typeof e&&null!==e&&"errors"in e&&Array.isArray(e.errors)&&"code"in e.errors[0]&&"string"==typeof e.errors[0].code&&"provider_data"in e&&"object"==typeof e.provider_data}var Yu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ku extends ea{constructor(e,t){super("adyen",e),this._scriptLoader=t,this._service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Yu(this,void 0,void 0,function*(){yield i.initialize.call(this,e,t,n);const r=i.getPaymentMethod.call(this),o=this._service.getState().getStoreConfig();if(!o)throw new ti(Xn.MissingCheckoutConfig);return this._adyenClient=yield this._scriptLoader.load({environment:r.config.testMode?"test":"live",locale:o.storeProfile.storeLanguage}),Promise.resolve()})}getNonce(e){const t=Object.create(null,{getNonce:{get:()=>super.getNonce},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Yu(this,void 0,void 0,function*(){const n=yield t.getNonce.call(this,e),i=t.getPaymentMethod.call(this);return JSON.stringify({type:i.method,googlePayToken:n,browser_info:ss()})})}processAdditionalAction(e){return Yu(this,void 0,void 0,function*(){if(!pa(e)||!$u(e.body))throw e;const t=yield this._handleAction(e.body.provider_data);try{return yield this._service.submitPayment(t)}catch(e){return this.processAdditionalAction(e)}})}_handleAction(e){return new Promise((t,n)=>{const i=JSON.parse(e.action);this._getAdyenClient().createFromAction(i,{onAdditionalDetails:e=>{const n={methodId:i.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};t(n)},size:"05",onError:e=>n(e)}).mount("body"),n(new Wi)})}_getAdyenClient(){if(!this._adyenClient)throw new ri(ei.PaymentNotInitialized);return this._adyenClient}}var Ju=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Zu{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t,this._isDeinitializationBlocked=!1,this._loadingIndicator=new vd({containerStyles:yd})}initialize(e){var t,n;return Ju(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId)||!na(e.methodId))throw new fi('Unable to proceed because "methodId" is not a valid key.');this._methodId=e.methodId;const i=e[this._getMethodId()];if(!(null==i?void 0:i.walletButton))throw new fi("Unable to proceed without valid options.");const{walletButton:r,loadingContainerId:o}=i,a=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rs,this._getGooglePayClientOptions(null===(n=s.initializationData)||void 0===n?void 0:n.storeCountry)),this._addPaymentButton(r,a)})}execute({payment:e}){return Ju(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new co(["payment"]);yield this._paymentIntegrationService.submitOrder();const t=yield this._googlePayPaymentProcessor.getNonce(e.methodId),n=yield this._googlePayPaymentProcessor.extraPaymentData();try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:Object.assign({nonce:t},n)}))}catch(t){yield this._googlePayPaymentProcessor.processAdditionalAction(t,e.methodId)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this._isDeinitializationBlocked||(this._clickListener&&(null===(e=this._paymentButton)||void 0===e||e.removeEventListener("click",this._clickListener)),this._paymentButton=void 0,this._clickListener=void 0,this._methodId=void 0),Promise.resolve()}_addPaymentButton(e,t){if(this._paymentButton)return;const n=document.getElementById(e);if(!n)throw new fi("Unable to proceed without a walletButton.");this._paymentButton=n,this._clickListener=this._handleClick(t),this._paymentButton.addEventListener("click",this._clickListener)}_handleClick({onPaymentSelect:e,onError:t}){return n=>Ju(this,void 0,void 0,function*(){n.preventDefault();try{this._googlePayPaymentProcessor.setShouldRequestShipping(!1),yield this._googlePayPaymentProcessor.initializeWidget(),this._isDirectPayOnClickEnabled()?yield this._interactWithPaymentSheetAndPay():yield this._interactWithPaymentSheet()}catch(e){let n=e;if(this._toggleLoadingIndicator(!1),ta(e)){if("CANCELED"===e.statusCode)throw new Wi;n=new Qr(JSON.stringify(e))}throw null==t||t(new Qr("An error occurred while requesting your Google Pay payment details.")),n}finally{this._toggleBlockDeinitialization(!1)}null==e||e()})}_interactWithPaymentSheetAndPay(){return Ju(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet();this._toggleBlockDeinitialization(!0),this._toggleLoadingIndicator(!0);const t=this._getMethodId(),n=this._paymentIntegrationService.getState(),{features:i}=n.getStoreConfigOrThrow().checkoutSettings,r=Ci(i,"PI-5031.google_pay_dont_override_address"),o=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e);o&&!r&&(yield this._paymentIntegrationService.updateBillingAddress(o)),yield this._googlePayPaymentProcessor.setExternalCheckoutXhr(t,e),yield this._paymentIntegrationService.loadCheckout(),yield this._paymentIntegrationService.loadPaymentMethod(t);const a=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(t);yield this._googlePayPaymentProcessor.initialize(()=>a),yield this.execute({useStoreCredit:!1,payment:{methodId:t}}),this._completeCheckoutFlow()})}_completeCheckoutFlow(){window.location.replace("/checkout/order-confirmation"),this._toggleLoadingIndicator(!1),this._toggleBlockDeinitialization(!1)}_interactWithPaymentSheet(){return Ju(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet(),t=this._paymentIntegrationService.getState(),{features:n}=t.getStoreConfigOrThrow().checkoutSettings,i=Ci(n,"PI-5031.google_pay_dont_override_address");this._toggleBlockDeinitialization(!0),this._toggleLoadingIndicator(!0);const r=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e);r&&!i&&(yield this._paymentIntegrationService.updateBillingAddress(r)),yield this._googlePayPaymentProcessor.setExternalCheckoutXhr(this._getMethodId(),e),yield this._paymentIntegrationService.loadCheckout(),yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodId()),this._toggleLoadingIndicator(!1),this._toggleBlockDeinitialization(!1)})}_getMethodId(){return ii(this._methodId,()=>new ri(ei.PaymentNotInitialized))}_getIsSignedInOrThrow(){return Ju(this,void 0,void 0,function*(){try{return!!(yield this._googlePayPaymentProcessor.getNonce(this._getMethodId()))}catch(e){if(e instanceof ti&&e.subtype===Xn.MissingPaymentToken)return!1;throw e}})}_handleOfferTrigger(e){return Ju(this,void 0,void 0,function*(){let t=!1,n="Sign in to Google Pay first to apply or remove promo codes.";try{t=yield this._getIsSignedInOrThrow()}catch(e){e instanceof ti&&(n=e.message)}if(t){const{newOfferInfo:t,error:n}=yield this._googlePayPaymentProcessor.handleCoupons(e);return{newOfferInfo:t,error:n}}return{error:{reason:Ko.OFFER_INVALID,message:n,intent:Jo.OFFER}}})}_getGooglePayClientOptions(e){return this._googlePayPaymentProcessor.isWebViewWithRestrictions()?{}:{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:t,offerData:n})=>Ju(this,void 0,void 0,function*(){if(t!==Jo.INITIALIZE&&t!==Jo.OFFER)return;const{offerChangeTriggers:i}=this._googlePayPaymentProcessor.getCallbackTriggers(),{newOfferInfo:r,error:o}=i.includes(t)?yield this._handleOfferTrigger(n):{},a=o;yield this._paymentIntegrationService.loadCheckout();const{code:s}=this._paymentIntegrationService.getState().getCartOrThrow().currency,d=this._googlePayPaymentProcessor.getTotalPrice();return Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},e&&{countryCode:e}),{currencyCode:s,totalPriceStatus:Wo.FINAL,totalPrice:d})},r&&{newOfferInfo:r}),a&&{error:a})})}}}_isDirectPayOnClickEnabled(){const{features:e}=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings;return Ci(e,"PI-5111.google_pay_direct_pay_on_click")}_toggleBlockDeinitialization(e){this._isDeinitializationBlocked=e}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this._loadingIndicator.show(this._loadingIndicatorContainer):this._loadingIndicator.hide()}}const Qu=vi(e=>new Zu(e,new aa(da(),new Ku(e,new zd(a(),s())),n(),Ee())),[{id:"googlepayadyenv2"}]);var Xu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class eh extends ea{constructor(e,t){super("adyen",e),this._scriptLoader=t,this._service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Xu(this,void 0,void 0,function*(){yield i.initialize.call(this,e,t,n);const r=i.getPaymentMethod.call(this),o=this._service.getState().getStoreConfig();if(!o)throw new ti(Xn.MissingCheckoutConfig);return this._adyenClient=yield this._scriptLoader.load({environment:r.config.testMode?"test":"live",locale:o.storeProfile.storeLanguage}),Promise.resolve()})}processAdditionalAction(e){return Xu(this,void 0,void 0,function*(){if(!pa(e)||!$u(e.body))throw e;const t=yield this._handleAction(e.body.provider_data);try{return yield this._service.submitPayment(t)}catch(e){return this.processAdditionalAction(e)}})}getNonce(e){const t=Object.create(null,{getNonce:{get:()=>super.getNonce},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Xu(this,void 0,void 0,function*(){const n=yield t.getNonce.call(this,e),i=t.getPaymentMethod.call(this);return JSON.stringify({type:i.method,googlePayToken:n,browser_info:ss()})})}_handleAction(e){return new Promise((t,n)=>{const i=JSON.parse(e.action);this._getAdyenClient().createFromAction(i,{onAdditionalDetails:e=>{const n={methodId:i.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};t(n)},size:"05",onError:e=>n(e)}).mount("body"),n(new Wi)})}_getAdyenClient(){if(!this._adyenClient)throw new ri(ei.PaymentNotInitialized);return this._adyenClient}}const th=vi(e=>new Zu(e,new aa(da(),new eh(e,new Bd(a(),s())),n(),Ee())),[{id:"googlepayadyenv3"}]),nh=vi(e=>new Zu(e,new aa(da(),new ua(e),n(),Ee())),[{id:"googlepayauthorizenet"}]),ih=vi(e=>{const t=n();return new Zu(e,new aa(da(),new ga(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]),rh=vi(e=>new Zu(e,new aa(da(),new fa(e),n(),Ee())),[{id:"googlepaycybersourcev2"},{id:"googlepaybnz"}]),oh=vi(e=>new Zu(e,new aa(da(),new wa(e),n(),Ee())),[{id:"googlepayorbital"}]),ah=vi(e=>new Zu(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeupe"},{id:"googlepaystripeocs"}]),sh=vi(e=>new Zu(e,new aa(da(),new Ga(e),n(),Ee())),[{id:"googlepayworldpayaccess"}]),dh=vi(e=>{const t=n(),i=window,r=new Ei(e),o=new Ui(new Hi(a(),i,r));return new Zu(e,new aa(da(),new $a(e,o),t,Ee()))},[{id:"googlepaybraintree"}]);var ch,lh;!function(e){e.Approved="APPROVED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(ch||(ch={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(lh||(lh={}));var uh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class hh extends Zu{constructor(e,t,n,i){super(e,t),this._payPalCommerceSdk=n,this._requestSender=i}execute({payment:e}){return uh(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new co(["payment"]);const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow().id,{initializationData:i}=t.getPaymentMethodOrThrow(this._getMethodId()),{orderId:r}=yield this.getOrderId(n),{card_information:o}=i||{},a=yield this._googlePayPaymentProcessor.getNonce(e.methodId),s={tokenizationData:{type:"PAYMENT_GATEWAY",token:atob(a)},info:{cardNetwork:(null==o?void 0:o.type)||"",cardDetails:(null==o?void 0:o.number)||""},type:"CARD"};yield this.confirmOrder(r,s),yield this._paymentIntegrationService.submitOrder();try{const t={formattedPayload:{method_id:e.methodId,paypal_account:{order_id:r}}};yield this._paymentIntegrationService.submitPayment({methodId:e.methodId,paymentData:t})}catch(e){yield this._googlePayPaymentProcessor.processAdditionalAction(e)}})}confirmOrder(e,t){return uh(this,void 0,void 0,function*(){const n=this._paymentIntegrationService.getState(),i=n.getPaymentMethodOrThrow(this._getMethodId());if(!i.initializationData)throw new ti(Xn.MissingPaymentMethod);const r=n.getCartOrThrow().currency.code,o=yield this._payPalCommerceSdk.getPayPalGooglePaySdk(i,r,n.getLocale(),!0),{status:a}=yield o.Googlepay().confirmOrder({orderId:e,paymentMethodData:t});if(a===ch.PayerActionRequired)return yield o.Googlepay().initiatePayerAction({orderId:e}),Promise.resolve();if(a!==ch.Approved)throw new fi("Payment is not approved.");return Promise.resolve()})}getOrderId(e){return uh(this,void 0,void 0,function*(){const t={cartId:e,shouldSaveInstrument:!1},{body:n}=yield this._requestSender.post("/api/storefront/payments/googlepaypaypalcommercecheckout",{headers:Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr),body:t});return n})}}const ph=vi(e=>{const t=new Xa(a());return new hh(e,new aa(da(),new ns(e,t),n(),Ee()),t,n())},[{id:"googlepaypaypalcommerce"}]);var mh,yh;!function(e){e.Approved="APPROVED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(mh||(mh={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(yh||(yh={}));var gh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vh extends Zu{constructor(e,t,n,i){super(e,t),this._payPalSdkHelper=n,this._requestSender=i}execute({payment:e}){return gh(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new co(["payment"]);const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow().id,{initializationData:i}=t.getPaymentMethodOrThrow(this._getMethodId()),{orderId:r}=yield this.getOrderId(n),{card_information:o}=i||{},a=yield this._googlePayPaymentProcessor.getNonce(e.methodId),s={tokenizationData:{type:"PAYMENT_GATEWAY",token:atob(a)},info:{cardNetwork:(null==o?void 0:o.type)||"",cardDetails:(null==o?void 0:o.number)||""},type:"CARD"};yield this.confirmOrder(r,s),yield this._paymentIntegrationService.submitOrder();try{const t={formattedPayload:{method_id:e.methodId,paypal_account:{order_id:r}}};yield this._paymentIntegrationService.submitPayment({methodId:e.methodId,paymentData:t})}catch(e){yield this._googlePayPaymentProcessor.processAdditionalAction(e)}})}confirmOrder(e,t){return gh(this,void 0,void 0,function*(){const n=this._paymentIntegrationService.getState(),i=n.getPaymentMethodOrThrow(this._getMethodId());if(!i.initializationData)throw new ti(Xn.MissingPaymentMethod);const r=n.getCartOrThrow().currency.code,o=yield this._payPalSdkHelper.getPayPalGooglePaySdk(i,r,!0),{status:a}=yield o.Googlepay().confirmOrder({orderId:e,paymentMethodData:t});if(a===mh.PayerActionRequired)return yield o.Googlepay().initiatePayerAction({orderId:e}),Promise.resolve();if(a!==mh.Approved)throw new fi("Payment is not approved.");return Promise.resolve()})}getOrderId(e){return gh(this,void 0,void 0,function*(){const t={cartId:e,shouldSaveInstrument:!1},{body:n}=yield this._requestSender.post("/api/storefront/payments/googlepay_bigcommerce_paymentscheckout",{headers:Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr),body:t});return n})}}const fh=vi(e=>{const t=new xr(a());return new vh(e,new aa(da(),new os(e,t),n(),Ee()),t,n())},[{id:"googlepay_bigcommerce_payments"}]),Sh=vi(e=>new Zu(e,new aa(da(),new cs(e,Ee()),n(),Ee())),[{id:"googlepaytdonlinemart"}]);class _h extends Qn{constructor(e,t,n){super(n||"Payment cannot be processed for this order, please select another payment method"),this.type="custom_provider_execute_error",this.name=t,this.subtype=e}}class wh{constructor(e,t){this.paymentIntegrationService=e,this.formPoster=t}execute(e,t){var n,i,r,o,a;return i=this,r=void 0,a=function*(){const{payment:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.formPoster.postForm(t,JSON.parse(n),e)})}isOffsiteRedirectResponse(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!t.body)return!1;const n=t.body;return"additional_action_required"===n.status&&!!n.additional_action_required&&"offsite_redirect"===n.additional_action_required.type&&"string"==typeof n.provider_data}}const Ih=vi(e=>new wh(e,Ee()),[{id:"humm"}]),Ch=["AT","BE","CA","CH","CZ","DE","DK","ES","FI","FR","GB","GR","IE","IT","NL","NO","NZ","PL","PT","SE"],bh=["AU"];var Ph=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Oh{constructor(e,t){this.paymentIntegrationService=e,this.klarnaScriptLoader=t}initialize(e){return Ph(this,void 0,void 0,function*(){this.klarnaCredit=yield this.klarnaScriptLoader.load(),this.unsubscribe=this.paymentIntegrationService.subscribe(t=>{t.isPaymentMethodInitialized({methodId:e.methodId,gatewayId:e.gatewayId})&&this.loadWidget(e)},e=>{const t=e.getCheckout();return t&&t.outstandingBalance},e=>{const t=e.getCheckout();return t&&t.coupons}),yield this.loadWidget(e)})}deinitialize(){return this.unsubscribe&&this.unsubscribe(),Promise.resolve()}execute(e,t){return Ph(this,void 0,void 0,function*(){if(!e.payment)throw new fi('Unable to proceed because "payload.payment" argument is not provided.');const n=e.payment,{paymentData:i}=n,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const r=this.paymentIntegrationService.getState().getPaymentMethod(t);if(!r)throw new ti(Xn.MissingPaymentMethod);if(!this.klarnaCredit||!r.clientToken)throw new ri(ei.PaymentNotInitialized);this.klarnaCredit.init({client_token:r.clientToken}),this.klarnaCredit.load({container:n},t=>{i&&i(t),e(t)})})})}getUpdateSessionData(e,t){if(!H([...Ch,...bh],e.countryCode))return{};const n={billing_address:this.mapToKlarnaAddress(e,e.email)};return t&&(n.shipping_address=this.mapToKlarnaAddress(t,e.email)),n}needsStateCode(e){return H(bh,e)}mapToKlarnaAddress(e,t){const n={street_address:e.address1,city:e.city,country:e.countryCode,given_name:e.firstName,family_name:e.lastName,postal_code:e.postalCode,region:this.needsStateCode(e.countryCode)?e.stateOrProvinceCode:e.stateOrProvince,email:t};return e.address2&&(n.street_address2=e.address2),e.phone&&(n.phone=e.phone),n}authorize(){return new Promise((e,t)=>{const n=this.paymentIntegrationService.getState(),i=n.getBillingAddress(),r=n.getShippingAddress();if(!i)throw new ti(Xn.MissingBillingAddress);if(!this.klarnaCredit)throw new ri(ei.PaymentNotInitialized);const o=this.getUpdateSessionData(i,r);this.klarnaCredit.authorize(o,n=>n.approved?e(n):n.show_form?t(new Wi):void t(new Xr))})}}class Eh{constructor(e,t=window){this.scriptLoader=e,this.klarnaWindow=t}load(){var e,t,n,i,r,o;return n=this,i=void 0,o=function*(){if((null===(e=this.klarnaWindow.Klarna)||void 0===e?void 0:e.Credit)||(yield this.scriptLoader.loadScript("//credit.klarnacdn.net/lib/v1/api.js")),!(null===(t=this.klarnaWindow.Klarna)||void 0===t?void 0:t.Credit))throw new mi;return this.klarnaWindow.Klarna.Credit},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}}const Ah=vi(e=>new Oh(e,new Eh(a())),[{id:"klarna"}]);var Th=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class kh{constructor(e,t,n){this.paymentIntegrationService=e,this.klarnav2ScriptLoader=t,this.klarnav2TokenUpdater=n}initialize(e){return Th(this,void 0,void 0,function*(){this.klarnaPayments=yield this.klarnav2ScriptLoader.load(),this.unsubscribe=this.paymentIntegrationService.subscribe(t=>{t.isPaymentMethodInitialized({methodId:e.methodId,gatewayId:e.gatewayId})&&this.loadPaymentsWidget(e)},e=>{const t=e.getCheckout();return t&&t.outstandingBalance},e=>{const t=e.getCheckout();return t&&t.coupons}),yield this.loadPaymentsWidget(e)})}deinitialize(){return this.unsubscribe&&this.unsubscribe(),Promise.resolve()}execute(e,t){return Th(this,void 0,void 0,function*(){if(!e.payment)throw new fi('Unable to proceed because "payload.payment" argument is not provided.');const n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{throw new ti(Xn.MissingPaymentMethod)}),new Promise(e=>{const a=o.getPaymentMethodOrThrow(t),{klarnaMultipleRadioButton:s}=a.initializationData||{};if(!this.klarnaPayments||!a.clientToken)throw new ri(ei.PaymentNotInitialized);this.klarnaPayments.init({client_token:a.clientToken}),this.klarnaPayments.load({container:i,payment_method_category:this.isKlarnaMultipleRadioButtonEnabled(s,n,t)},t=>{r&&r(t),e(t)})})})}getUpdateSessionData(e,t,n){if(!H([...Ch,...bh],t.countryCode))return{};const i={billing_address:this.mapToKlarnaAddress(e,t,t.email)};return n&&(i.shipping_address=this.mapToKlarnaAddress(e,n,t.email)),i}needsStateCode(e){return H(bh,e)}isKlarnaMultipleRadioButtonEnabled(e,t,n){return e?n:t}mapToKlarnaAddress(e,t,n){const i=this.paymentIntegrationService.getState(),{checkoutSettings:r}=i.getStoreConfigOrThrow(),o=i.getPaymentMethodOrThrow(e),{enableBillie:a}=o.initializationData||{},s={street_address:t.address1,city:t.city,country:t.countryCode,given_name:t.firstName,family_name:t.lastName,postal_code:t.postalCode,region:this.needsStateCode(t.countryCode)?t.stateOrProvinceCode:t.stateOrProvince,email:n};return t.address2&&(s.street_address2=t.address2),t.phone&&(s.phone=t.phone),t.company&&a&&Ci(r.features,"PI-3915.b2b_payment_session_for_klarna")&&(s.organization_name=t.company),s}authorizeOrThrow(e,t){return Th(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const n=this.paymentIntegrationService.getState(),i=n.getBillingAddressOrThrow(),r=n.getShippingAddress(),o=this.getUpdateSessionData(t,i,r);return new Promise((t,n)=>{if(!this.klarnaPayments)return n(new ri(ei.PaymentNotInitialized));this.klarnaPayments.authorize({payment_method_category:e},o,e=>e.approved?t(e):e.show_form?n(new Wi):void n(new Xr))})})}}class Dh{constructor(e,t=window){this.scriptLoader=e,this.klarnaWindow=t}load(){var e,t,n,i,r,o;return n=this,i=void 0,o=function*(){if((null===(e=this.klarnaWindow.Klarna)||void 0===e?void 0:e.Payments)||(yield this.scriptLoader.loadScript("https://x.klarnacdn.net/kp/lib/v1/api.js")),!(null===(t=this.klarnaWindow.Klarna)||void 0===t?void 0:t.Payments))throw new mi;return this.klarnaWindow.Klarna.Payments},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}}class Mh{constructor(e){this.requestSender=e}updateClientToken(e,{timeout:t,params:n}={}){const i=`/api/storefront/payments/${e}`;return this.requestSender.get(i,{timeout:t,headers:Object.assign({Accept:mr.JsonV1,"X-API-INTERNAL":hr},yr),params:n})}klarnaOrderInitialization(e,t){return n=this,i=void 0,o=function*(){const n={headers:Object.assign({Accept:mr.JsonV1,"X-API-INTERNAL":hr},yr),body:{cartId:e,clientToken:t}};yield this.requestSender.put("/api/storefront/initialization/klarna",n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const zh=vi(e=>{const{getHost:t}=e.getState(),i=n({host:t()});return new kh(e,new Dh(a()),new Mh(i))},[{gateway:"klarna"}]);class Nh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return n=this,i=void 0,o=function*(){return yield this._paymentIntegrationService.submitOrder(e,t),Promise.resolve()},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const xh=vi(e=>new Nh(e),[{id:"testgateway"}]);var Rh,Fh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.CREDIT_CARD="credit_card"}(Rh||(Rh={}));const Lh=["klarnapaylater","klarnasliceit"];class Bh{constructor(e,t){this.mollieScriptLoader=e,this.paymentIntegrationService=t}initialize(e){return Fh(this,void 0,void 0,function*(){const{mollie:t,methodId:n,gatewayId:i}=e;if(!t)throw new fi('Unable to initialize payment because "options.mollie" argument is not provided.');if(!n||!i)throw new fi('Unable to initialize payment because "methodId" and/or "gatewayId" argument is not provided.');const r=document.querySelectorAll(".mollie-components-controller");F(r,e=>e.remove());const o=this.paymentIntegrationService.getState(),a=o.getStoreConfigOrThrow();this.initializeOptions=t;const s=o.getPaymentMethodOrThrow(n,i),{config:{merchantId:d,testMode:c}}=s;if(this.locale=o.getLocale(),!d)throw new ti(Xn.MissingPaymentMethod);return this.isCreditCard(n)&&t.form&&this.shouldShowTSVHostedForm(n,i)?this.hostedForm=yield this.mountCardVerificationfields(t.form):this.isCreditCard(n)&&(this.mollieClient=yield this.loadMollieJs(d,a.storeProfile.storeLanguage,c),this.mountElements()),this.unsubscribe=()=>{if(this.paymentIntegrationService.getState().isPaymentMethodInitialized({methodId:e.methodId,gatewayId:e.gatewayId})){const e=document.getElementById(`${i}-${n}-paragraph`);e&&e.remove(),t.disableButton(!1),this.loadPaymentMethodsAllowed(t,n,i)}},this.unsubscribe(),this.loadPaymentMethodsAllowed(t,n,i),Promise.resolve()})}execute(e,t){return Fh(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rFh(this,void 0,void 0,function*(){try{const n=this.paymentIntegrationService.getState().getStoreConfig(),i=null==n?void 0:n.paymentSettings.bigpayBaseUrl;if(!i)throw new ti(Xn.MissingCheckoutConfig);const r=this.paymentIntegrationService.createHostedForm(i,e);yield r.attach(),t(r)}catch(e){n(e)}}))}isHostedPaymentFormEnabled(e,t){const{getPaymentMethodOrThrow:n}=this.paymentIntegrationService.getState();return!0===n(e,t).config.isHostedFormEnabled}isHostedFieldAvailable(){var e;return!!(null===(e=this.getInitializeOptions().form)||void 0===e?void 0:e.fields)}processAdditionalAction(e){if(!pa(e))return Promise.reject(e);if(ve(e.body.errors,{code:"additional_action_required"})){const{additional_action_required:{data:{redirect_url:t}}}=e.body;return new Promise(()=>window.location.replace(t))}return Promise.reject(e)}getInitializeOptions(){if(!this.initializeOptions)throw new ri(ei.PaymentNotInitialized);return this.initializeOptions}loadMollieJs(e,t,n=!1){return this.mollieClient?Promise.resolve(this.mollieClient):this.mollieScriptLoader.load(e,t,n)}getMollieClient(){if(!this.mollieClient)throw new ri(ei.PaymentNotInitialized);return this.mollieClient}getShopperLocale(){if(!this.locale)throw new ri(ei.PaymentNotInitialized);return this.locale}mountElements(){const{containerId:e,cardNumberId:t,cardCvcId:n,cardExpiryId:i,cardHolderId:r,styles:o}=this.getInitializeOptions();let a;e&&(a=document.getElementById(e)),setTimeout(()=>{if(!e||"none"!==(null==a?void 0:a.style.display)){const e=this.getMollieClient();this.cardHolderElement=e.createComponent("cardHolder",{styles:o}),this.cardHolderElement.mount(`#${r}`),this.cardNumberElement=e.createComponent("cardNumber",{styles:o}),this.cardNumberElement.mount(`#${t}`),this.verificationCodeElement=e.createComponent("verificationCode",{styles:o}),this.verificationCodeElement.mount(`#${n}`),this.expiryDateElement=e.createComponent("expiryDate",{styles:o}),this.expiryDateElement.mount(`#${i}`)}},0)}loadPaymentMethodsAllowed(e,t,n){var i;if(Lh.includes(t)){const r=null===(i=this.paymentIntegrationService.getState().getCartOrThrow().lineItems)||void 0===i?void 0:i.digitalItems;if(r&&r.length>0){const{containerId:i}=this.getInitializeOptions();if(i){const r=document.getElementById(i);if(r){const i=document.createElement("p");i.setAttribute("id",`${n}-${t}-paragraph`),e.unsupportedMethodMessage&&(i.innerText=e.unsupportedMethodMessage,r.appendChild(i),e.disableButton(!0))}}}}}}class jh{constructor(e,t=window){this.scriptLoader=e,this.mollieHostWindow=t}load(e,t,n){return i=this,r=void 0,a=function*(){if(yield this.scriptLoader.loadScript("https://js.mollie.com/v1/mollie.js"),!function(e){return"Mollie"in e}(this.mollieHostWindow))throw new mi;return this.mollieHostWindow.Mollie(e,{locale:t,testmode:n})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a}}const Uh=vi(e=>new Bh(new jh(a()),e),[{gateway:"mollie"},{gateway:"mollie",id:"applepay"}]);var qh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const Vh="moneris-payment-iframe";class Gh{constructor(e){this.paymentIntegrationService=e}initialize(e){return qh(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),{moneris:n,methodId:i}=e;if(!i)throw new fi('Unable to initialize payment because "methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.moneris" argument is not provided.');this.initializeOptions=n;const{config:r,initializationData:o}=t.getPaymentMethodOrThrow(i);if(!(null==o?void 0:o.profileId))throw new ti(Xn.MissingPaymentMethod);return n.form&&this.shouldShowTSVHostedForm(i)&&(this.hostedForm=yield this.mountCardVerificationfields(n.form)),this.iframe||(this.iframe=this.createIframe(n.containerId,o,!!r.testMode)),Promise.resolve()})}execute(e,t){return qh(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(!this.iframe)throw new ri(ei.PaymentNotInitialized);const i=this.iframe.contentWindow;if(null===i)throw new ri(ei.PaymentNotInitialized);i.postMessage("tokenize",this.monerisURL(!!t)),this.windowEventListener=i=>{if("string"==typeof i.data&&i.origin===`https://${t?"esqa":"www3"}.moneris.com`)try{e(this.handleMonerisResponse(i))}catch(e){n(e)}},window.addEventListener("message",this.windowEventListener)});void 0!==a&&(yield this.paymentIntegrationService.submitPayment({methodId:e.methodId,paymentData:{nonce:a,shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o}}))})}executeWithVaulted(e){return qh(this,void 0,void 0,function*(){if(this.hostedForm){const t=this.hostedForm;return yield t.validate(),yield t.submit(e),this.paymentIntegrationService.loadCurrentOrder()}return this.paymentIntegrationService.submitPayment(e)})}shouldShowTSVHostedForm(e){return this.isHostedPaymentFormEnabled(e)&&this.isHostedFieldAvailable()}isHostedPaymentFormEnabled(e){const t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e);return Boolean(t.config.isHostedFormEnabled)}isHostedFieldAvailable(){var e;const t=this.getInitializeOptions(),n=ue(null===(e=t.form)||void 0===e?void 0:e.fields,$);return!$(n)}getInitializeOptions(){if(!this.initializeOptions)throw new ri(ei.PaymentNotInitialized);return this.initializeOptions}mountCardVerificationfields(e){var t;return qh(this,void 0,void 0,function*(){const n=null===(t=this.paymentIntegrationService.getState().getStoreConfig())||void 0===t?void 0:t.paymentSettings.bigpayBaseUrl;if(!n)throw new ti(Xn.MissingCheckoutConfig);const i=this.paymentIntegrationService.createHostedForm(n,e);return yield i.attach(),i})}createIframe(e,t,n,i){const r=document.getElementById(e);if(!r)throw new fi("Unable to create iframe without valid container ID.");const o=document.createElement("iframe"),a={id:t.profileId,pmmsg:!0,display_labels:1,enable_exp:1,enable_cvd:1,css_body:(null==i?void 0:i.cssBody)||"font-family: Arial, Helvetica,sans-serif;background: transparent;",css_textbox:(null==i?void 0:i.cssTextbox)||"border-radius:4px;border: 2px solid rgb(00,00,00);width: 100%;font-weight: 600;padding: 8px 8px;outline: 0;",css_textbox_pan:(null==i?void 0:i.cssTextboxCardNumber)||"width: 240px;",css_textbox_exp:(null==i?void 0:i.cssTextboxExpiryDate)||"margin-bottom: 0;width: calc(30% - 12px);",css_textbox_cvd:(null==i?void 0:i.cssTextboxCVV)||"margin-bottom: 0;width: calc(30% - 12px);",css_input_label:(null==i?void 0:i.cssInputLabel)||"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;",pan_label:t.creditCardLabel||"Credit Card Number",exp_label:t.expiryDateLabel||"Expiration",cvd_label:t.cvdLabel||"CVD"},s=oe(a,(e,t)=>`${t}=${e}`).join("&");return o.width="100%",o.height="100%",o.name=Vh,o.id=Vh,o.style.border="none",o.src=`${this.monerisURL(n)}?${s}`,o.allow="payment",r.appendChild(o),o}handleMonerisResponse(e){const t=JSON.parse(e.data);if("001"!==t.responseCode[0])throw new Error(t.errorMessage);return t.dataKey}monerisURL(e){return`https://${e?"esqa":"www3"}.moneris.com/HPPtoken/index.php`}}const Hh=vi(e=>new Gh(e),[{id:"moneris"}]);class Wh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return n=this,i=void 0,o=function*(){return console.log("payload =======1",e),yield this._paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:e.payment?Object.assign({methodId:e.payment.methodId},"purchaseorder"===e.payment.methodId&&{paymentData:e.payment.paymentData}):void 0}),t),Promise.resolve()},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const $h=vi(e=>new Wh(e),[{type:"PAYMENT_TYPE_OFFLINE"}]);var Yh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Kh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return Yh(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew Kh(e),[{type:"PAYMENT_TYPE_HOSTED"}]),Zh=function({styles:e}){const t={};return e.color&&(t.color=e.color),e.layout&&(t.layout=e.layout),(e["logo-type"]||e["logo-position"])&&(t.logo={},e["logo-type"]&&(t.logo.type=e["logo-type"]),e["logo-position"]&&(t.logo.position=e["logo-position"])),e.ratio&&(t.ratio=e.ratio),(e["text-color"]||e["text-size"])&&(t.text={},e["text-color"]&&(t.text.color=e["text-color"]),e["text-size"]&&(t.text.size=+e["text-size"])),t};var Qh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Xh{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.payPalSdkScriptLoader=n,this.loadingIndicator=i}initialize(e){var t;return Qh(this,void 0,void 0,function*(){const{methodId:n,paypalcommerce:i}=e||{};if(this.paypalcommerce=i,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(n),{container:a,bannerContainerId:s}=i,{orderId:d,paypalBNPLConfiguration:c=[],isPayPalCreditAvailable:l}=o.initializationData||{};if(void 0!==s){if(!document.getElementById(s))return void console.error("Unable to create banner without valid banner container ID.");const e=null==c?void 0:c.find(({id:e})=>"checkout"===e);if(l||!(null==e?void 0:e.status))return;const t=yield this.payPalSdkScriptLoader.getPayPalMessages(o,r.getCartOrThrow().currency.code,r.getLocale());return t&&"function"==typeof(null==t?void 0:t.Messages)?this.renderMessages(t,s,e):void console.error("[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK")}d?this.orderId=null===(t=o.initializationData)||void 0===t?void 0:t.orderId:(this.loadingIndicatorContainer=null==a?void 0:a.split("#")[1],yield this.paypalIntegrationService.loadPayPalSdk(n),i.onInit&&"function"==typeof i.onInit&&i.onInit(()=>this.renderButton(n,i)),(void 0===i.shouldRenderPayPalButtonOnInitialization||i.shouldRenderPayPalButtonOnInitialization)&&this.renderButton(n,i))})}execute(e,t){var n,i;return Qh(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rwindow.location.replace(t))}return this.isProviderError(e)&&(yield this.paypalIntegrationService.loadPayPalSdk(r.methodId),yield new Promise((e,t)=>{var n;this.paypalcommerce&&(null===(n=this.paypalButton)||void 0===n||n.close(),this.renderButton(r.methodId,this.paypalcommerce),this.handleError(new Error("INSTRUMENT_DECLINED"),a)),t()})),this.handleError(e,a),Promise.reject()}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}prepareVaultedInstrumentPaymentPayload(e,t,n){const{instrumentId:i,shouldSetAsDefaultInstrument:r}=n,o=!this.isTrustedVaultingFlow(n);return o?{methodId:e,paymentData:{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}:{methodId:e,paymentData:{instrumentId:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t},bigpay_token:{token:i}}}}}preparePaymentPayload(e,t,n){const{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:r=!1}=jd(n)?n:{};return{methodId:e,paymentData:{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}}renderButton(e,t){var n,i,r,o;const a=this.paypalIntegrationService.getPayPalSdkOrThrow(),s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:d}=s.initializationData||{},{checkoutPaymentButtonStyles:c}=d||{},{container:l,onError:u,onRenderButton:h,onValidate:p,submitForm:m}=t;if(!l)throw new fi('Unable to initialize payment because "container" argument is not provided.');const y=this.getSmartButtonContainerId(l);if(!document.getElementById(y))throw new fi(`Unable to initialize payment because element with id ${y} does not exist.`);const g=Object.assign(Object.assign({},this.isPaypalCommerceAppSwitchEnabled(e)&&{appSwitchWhenAvailable:!0}),{fundingSource:a.FUNDING.PAYPAL,style:this.paypalIntegrationService.getValidButtonStyle(c),createOrder:()=>this.createOrder(),onClick:(e,t)=>this.handleClick(t,p),onApprove:e=>this.handleApprove(e,m),onError:e=>this.handleError(e,u),onCancel:()=>this.toggleLoadingIndicator(!1)});this.paypalButton=a.Buttons(g),this.paypalButton.isEligible()&&(h&&"function"==typeof h&&h(),(null===(i=(n=this.paypalButton).hasReturned)||void 0===i?void 0:i.call(n))&&this.isPaypalCommerceAppSwitchEnabled(e)?null===(o=(r=this.paypalButton).resume)||void 0===o||o.call(r):this.paypalButton.render(l))}handleClick(e,t){return Qh(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;return null==t?void 0:t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,null==t||t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createOrder(){return Qh(this,void 0,void 0,function*(){const e=this.getFieldsValues();return this.paypalIntegrationService.createOrder("paypalcommercecheckout",{shouldSaveInstrument:(null==e?void 0:e.shouldSaveInstrument)||!1})})}getFieldsValues(){const{getFieldsValues:e}=this.paypalcommerce||{};return"function"==typeof e?e():void 0}isTrustedVaultingFlow(e){if(e&&xd(e)){const t=this.paymentIntegrationService.getState().getInstruments(),n=null==t?void 0:t.find(t=>uc(t)&&t.bigpayToken===e.instrumentId);return!(uc(n)&&!n.trustedShippingAddress)}return!1}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isPayPalVaultedInstrumentPaymentData(e){return!!e&&xd(e)&&jd(e)}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:Zh(n)};e.Messages(i).render(`#${t}`)}isProviderError(e){var t,n,i;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"INSTRUMENT_DECLINED"===(null===(i=null===(n=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===n?void 0:n.provider_error)||void 0===i?void 0:i.code)}isPaypalCommerceAppSwitchEnabled(e){var t;return(null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)||!1}getSmartButtonContainerId(e){var t;return null!==(t=e.split("#")[1])&&void 0!==t?t:e}}const ep=vi(e=>new Xh(e,As(e),new Is(a()),new vd({containerStyles:Ka})),[{id:"paypalcommerce"}]);var tp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class np{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.loadingIndicator=n,this.payPalSdkScriptLoader=i}initialize(e){return tp(this,void 0,void 0,function*(){const{methodId:t,paypalcommerce:n,paypalcommercecredit:i}=e||{},r=i||n;if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const o=this.paymentIntegrationService.getState(),a=o.getPaymentMethodOrThrow(t),{paypalBNPLConfiguration:s=[],orderId:d}=a.initializationData||{},{bannerContainerId:c,container:l}=r;if(void 0!==c){if(!document.getElementById(c))return void console.error("Unable to create banner without valid banner container ID.");const e=s&&s.find(({id:e})=>"checkout"===e);if(!(null==e?void 0:e.status))return;const t=yield this.payPalSdkScriptLoader.getPayPalMessages(a,o.getCartOrThrow().currency.code,o.getLocale());return this.renderMessages(t,c,e)}d?this.orderId=d:(yield this.paypalIntegrationService.loadPayPalSdk(t),this.loadingIndicatorContainer=null==l?void 0:l.split("#")[1],this.renderButton(t,r))})}execute(e,t){return tp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(h)return;const t={fundingSource:e,style:this.paypalIntegrationService.getValidButtonStyle(o),createOrder:()=>this.paypalIntegrationService.createOrder("paypalcommercecreditcheckout"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=n.Buttons(t),this.paypalButton.isEligible()||e!==n.FUNDING.PAYLATER){if(!this.paypalButton.isEligible()&&e===n.FUNDING.CREDIT)throw new Si(`PayPal ${e} is not available for your region. Please use PayPal Checkout instead.`);d&&"function"==typeof d&&d(),this.paypalButton.render(a),h=!0}})}handleClick(e,t){return tp(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;if(t&&"function"==typeof t)return t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,t&&"function"==typeof t&&t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:Zh(n)};e.Messages(i).render(`#${t}`)}}const ip=vi(e=>new np(e,As(e),new vd({containerStyles:Ka}),Cs()),[{id:"paypalcommercecredit"}]);var rp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class op{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.loadingIndicator=n}initialize(e){var t,n;return rp(this,void 0,void 0,function*(){const{methodId:i,paypalcommerce:r,paypalcommercevenmo:o}=e||{},a=o||r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!a)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i);(null===(t=s.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(n=s.initializationData)||void 0===n?void 0:n.orderId:(yield this.paypalIntegrationService.loadPayPalSdk(i),this.loadingIndicatorContainer=a.container.split("#")[1],this.renderButton(i,a))})}execute(e,t){return rp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rthis.paypalIntegrationService.createOrder("paypalcommercevenmocheckout"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=n.Buttons(u),!this.paypalButton.isEligible())throw new Si("PayPal Venmo is not available for your region. Please use PayPal Checkout instead.");d&&"function"==typeof d&&d(),this.paypalButton.render(a)}handleClick(e,t){return rp(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;return t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,t(),this.toggleLoadingIndicator(!1)}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const ap=vi(e=>new op(e,As(e),new vd({styles:{backgroundColor:"black"}})),[{id:"paypalcommercevenmo"}]),sp={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"};var dp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class cp{constructor(e,t,n,i,r=3e3,o=3e5){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.paypalSdkScriptLoader=n,this.loadingIndicator=i,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.pollingTimer=0,this.stopPolling=ce,this.isOrderApprovedProcessing=!1}initialize(e){return dp(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,paypalcommerce:i,paypalcommercealternativemethods:r}=e,o=r||i;if(this.paypalcommercealternativemethods=r,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!o)throw new fi('Unable to initialize payment because "options.paypalcommercealternativemethods" argument is not provided.');const a=this.paymentIntegrationService.getState(),s=a.getPaymentMethodOrThrow(n,t),{orderId:d,shouldRenderFields:c}=s.initializationData||{},l=a.getStoreConfigOrThrow().checkoutSettings.features;this.isOrderApprovedProcessing=Ci(l,"PAYPAL-5431.order_approved_processing",!1),d?this.orderId=d:(this.paypalApms=yield this.paypalSdkScriptLoader.getPayPalApmsSdk(s,a.getCartOrThrow().currency.code,a.getLocale()),this.loadingIndicatorContainer=o.container.split("#")[1],this.renderButton(n,t,o),c&&this.renderFields(n,o))})}execute(e,t){return dp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.initializePollingMechanism(r,e,t,o)})),this.isNonInstantPaymentMethod(r)&&(r!==Bs.IDEAL||this.isOrderApprovedProcessing)||(yield this.paymentIntegrationService.submitOrder(i,t)),yield this.paypalCommerceIntegrationService.submitPayment(r,this.orderId,o)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,this.isOrderApprovedProcessing||this.resetPollingMechanism(),null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}initializePollingMechanism(e,t,n,i){return dp(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.paypalCommerceIntegrationService.getOrderStatus(null!=i?i:"paypalcommerce"),o=r===js.Approved,a=r===js.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimern.onInitButton(t),createOrder:()=>this.onCreateOrder(e,t,n),onApprove:e=>this.handleApprove(e,c),onCancel:()=>{this.toggleLoadingIndicator(!1),this.deinitializePollingMechanism()},onError:e=>{this.deinitializePollingMechanism(),this.handleFailure(e,s)},onClick:(e,t)=>dp(this,void 0,void 0,function*(){return n.onValidate(t.resolve,t.reject)})};this.paypalButton=i.Buttons(l),this.paypalButton.isEligible()&&(d&&"function"==typeof d&&d(),this.paypalButton.render(a))}onCreateOrder(e,t,n){var i;return dp(this,void 0,void 0,function*(){const{onValidate:r}=n;yield r(()=>(this.toggleLoadingIndicator(!0),()=>Promise.resolve()),ce);const o=yield this.paypalCommerceIntegrationService.createOrder("paypalcommercealternativemethodscheckout");if(this.isNonInstantPaymentMethod(e)&&(e===Bs.IDEAL&&this.isOrderApprovedProcessing||e===Bs.OXXO)){const n={useStoreCredit:!1},r={params:{methodId:e,gatewayId:t}};if(yield this.paymentIntegrationService.submitOrder(n,r),e===Bs.IDEAL){const t=this.paymentIntegrationService.getState(),n=null===(i=t.getOrder())||void 0===i?void 0:i.orderId;yield this.paypalCommerceIntegrationService.updateOrder("paypalcommercealternativemethods",e,n)}yield this.paypalCommerceIntegrationService.submitPayment(e,o,t)}return o})}handleApprove({orderID:e},t){this.orderId=e,t()}handleFailure(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderFields(e,t){const n=this.getPaypalAmpsSdkOrThrow(),i=this.paymentIntegrationService.getState(),{firstName:r,lastName:o,email:a}=i.getBillingAddressOrThrow(),{apmFieldsContainer:s,apmFieldsStyles:d}=t;if(!s)throw new fi('Unable to initialize payment because "options.paypalcommercealternativemethods" argument should contain "apmFieldsContainer".');const c=document.querySelector(s);c&&(c.innerHTML="");const l={fundingSource:e,style:d||{},fields:{name:{value:`${r} ${o}`},email:{value:a}}};n.PaymentFields(l).render(s)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isNonInstantPaymentMethod(e){return e.toUpperCase()in Bs}getPaypalAmpsSdkOrThrow(){if(!this.paypalApms)throw new mi;return this.paypalApms}}const lp=vi(e=>new cp(e,As(e),Cs(),new vd({containerStyles:sp})),[{gateway:"paypalcommercealternativemethods"}]);var up=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class hp{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.paypalSdkScriptLoader=n,this.paypalFastlaneUtils=i}initialize(e){return up(this,void 0,void 0,function*(){const{methodId:t,paypalcommercecreditcards:n,paypalcommerce:i}=e,r=n||i,{form:o,onCreditCardFieldsRenderingError:a,onLoadComplete:s}=r||{};if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)throw new fi('Unable to proceed because "options.paypalcommercecreditcards.form" argument is not provided.');this.hostedFormOptions=o,this.isCreditCardForm=Ac(o.fields),this.isCreditCardVaultedForm=Tc(o.fields)&&!this.hasUndefinedValues(),yield this.paymentIntegrationService.loadPaymentMethod(t),yield this.paypalIntegrationService.loadPayPalSdk(t,void 0,!0,!0),(this.isCreditCardForm||this.isCreditCardVaultedForm)&&(yield this.initializeFields(o,a)),null==s||s(),this.shouldInitializePayPalFastlane(t)&&(yield this.initializePayPalFastlaneOrThrow(t))})}execute(e,t){return up(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(n===Ns.No||n===Ns.Unknown)throw new Error;return this.handleApprove({orderID:e,vaultSetupToken:t})},onError:()=>{throw new Qr},inputEvents:{onChange:t=>this.onChangeHandler(e,t),onFocus:t=>this.onFocusHandler(e,t),onBlur:t=>this.onBlurHandler(e,t),onInputSubmitRequest:t=>this.onInputSubmitRequest(e,t)}},o);if(this.cardFields=yield r.CardFields(a),!this.cardFields.isEligible())throw new ri(ei.PaymentNotInitialized);try{this.stylizeInputContainers(n),Ac(n)&&(yield this.renderFields(n)),Tc(n)&&(yield this.renderVaultedFields(n))}catch(e){"function"==typeof t&&t(e)}})}getExecuteCallback(e){return Tc(e)?this.createVaultSetupTokenCallback():this.createOrderCallback()}createVaultSetupTokenCallback(){return{createVaultSetupToken:()=>up(this,void 0,void 0,function*(){const{setupToken:e}=(yield this.paypalIntegrationService.createOrderCardFields("paypalcommercecreditcardscheckout",Object.assign(Object.assign({},this.getInstrumentParams()),{setupToken:!0})))||{};return e})}}createOrderCallback(){return{createOrder:()=>up(this,void 0,void 0,function*(){const{orderId:e}=(yield this.paypalIntegrationService.createOrderCardFields("paypalcommercecreditcardscheckout",this.getInstrumentParams()))||{};return e})}}handleApprove({orderID:e,vaultSetupToken:t}){e&&(this.returnedOrderId=e),t&&(this.returnedVaultedToken=t)}renderFields(e){var t,n,i,r;return up(this,void 0,void 0,function*(){const o=this.getCardFieldsOrThrow();(null===(t=e.cardCode)||void 0===t?void 0:t.containerId)&&(this.cvvField=o.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCode.containerId}`)),(null===(n=e.cardExpiry)||void 0===n?void 0:n.containerId)&&(this.expiryField=o.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiry.containerId}`)),(null===(i=e.cardName)||void 0===i?void 0:i.containerId)&&(this.nameField=o.NameField({placeholder:""}),yield this.nameField.render(`#${e.cardName.containerId}`)),(null===(r=e.cardNumber)||void 0===r?void 0:r.containerId)&&(this.numberField=o.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumber.containerId}`))})}renderVaultedFields(e){var t,n,i;return up(this,void 0,void 0,function*(){const r=this.getCardFieldsOrThrow();(null===(t=e.cardCodeVerification)||void 0===t?void 0:t.containerId)&&(this.cvvField=r.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCodeVerification.containerId}`)),(null===(n=e.cardExpiryVerification)||void 0===n?void 0:n.containerId)&&(this.expiryField=r.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiryVerification.containerId}`)),(null===(i=e.cardNumberVerification)||void 0===i?void 0:i.containerId)&&(this.numberField=r.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumberVerification.containerId}`))})}getInstrumentParams(){if(!this.executionPaymentData)return{};if(jd(this.executionPaymentData)){const{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}=this.executionPaymentData;return{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}}if(xd(this.executionPaymentData)){const{instrumentId:e}=this.executionPaymentData;return{instrumentId:e}}return{}}getFieldTypeByEmittedField({emittedBy:e}){return{fieldType:this.mapFieldType(e)}}submitHostedForm(){return up(this,void 0,void 0,function*(){const e=this.getCardFieldsOrThrow(),t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),n={billingAddress:{company:t.company,addressLine1:t.address1,addressLine2:t.address2,adminArea1:t.stateOrProvinceCode,adminArea2:t.city,postalCode:t.postalCode,countryCode:t.countryCode}};try{this.isCreditCardVaultedForm?yield e.submit():yield e.submit(n)}catch(e){throw new Qr("Failed authentication. Please try to authorize again.")}})}validateHostedFormOrThrow(){var e,t;return up(this,void 0,void 0,function*(){const n=this.getCardFieldsOrThrow(),i=yield n.getState().then(e=>e),r=this.getValidityData(i);if(!r.isValid)throw null===(t=null===(e=this.hostedFormOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,r),new lo(this.mapValidationErrors(r.errors))})}getValidityData({fields:e}){const t=Object.assign({},e);delete t.cardNameField;const n=Object.keys(t);return{isValid:n.every(e=>{var n;return null===(n=t[e])||void 0===n?void 0:n.isValid}),errors:n.reduce((e,n)=>{var i;const r=this.mapFieldType(n);return Object.assign(Object.assign({},e),{[r]:(null===(i=t[n])||void 0===i?void 0:i.isValid)?void 0:[this.getInvalidErrorByFieldType(r)]})},{})}}getInvalidErrorByFieldType(e){switch(e){case Ec.CardCode:case Ec.CardCodeVerification:return{fieldType:e,message:"Invalid card code",type:"invalid_card_code"};case Ec.CardNumber:case Ec.CardNumberVerification:return{fieldType:e,message:"Invalid card number",type:"invalid_card_number"};case Ec.CardExpiry:case Ec.CardExpiryVerification:return{fieldType:e,message:"Invalid card expiry",type:"invalid_card_expiry"};default:return{fieldType:e,message:"Invalid field",type:"invalid"}}}mapValidationErrors(e={}){const t={};return Object.keys(e).forEach(n=>{var i,r;t[n]=[{message:(null===(r=null===(i=e[n])||void 0===i?void 0:i[0])||void 0===r?void 0:r.message)||"",type:n}]}),t}mapFieldType(e){switch(e){case"name":return Ec.CardName;case"cardNumberField":case"number":return this.isCreditCardForm?Ec.CardNumber:Ec.CardNumberVerification;case"cardExpiryField":case"expiry":return this.isCreditCardForm?Ec.CardExpiry:Ec.CardExpiryVerification;case"cardCvvField":case"cvv":return this.isCreditCardForm?Ec.CardCode:Ec.CardCodeVerification;default:throw new Error("Unexpected field type")}}getCardFieldsOrThrow(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);return this.cardFields}getInputStyles(e){var t,n,i;const r={"font-size":(null===(t=null==e?void 0:e.default)||void 0===t?void 0:t.fontSize)||"1rem","font-family":(null===(n=null==e?void 0:e.default)||void 0===n?void 0:n.fontFamily)||"Montserrat, Arial, Helvetica, sans-serif","font-weight":(null===(i=null==e?void 0:e.default)||void 0===i?void 0:i.fontWeight)||"400",outline:"none",padding:"9px 13px"},o=Object.assign(Object.assign({},r),{color:"#333333"});return{input:o,".invalid":Object.assign(Object.assign({},r),{color:"red"}),".valid":o,":focus":o}}stylizeInputContainers(e){Object.values(e||{}).forEach(e=>{const t=document.getElementById(`${(null==e?void 0:e.containerId)||""}`);t&&(t.style.padding="0px",t.style.boxShadow="none",t.style.border="none",t.style.background="transparent",t.style.marginBottom="10px",t.style.marginLeft="-5px")})}hasUndefinedValues(){return!this.hostedFormOptions||Object.values(this.hostedFormOptions.fields).some(e=>void 0===e)}onChangeHandler(e,t){var n;null===(n=null==e?void 0:e.onValidate)||void 0===n||n.call(e,this.getValidityData(t))}onFocusHandler(e,t){var n;null===(n=null==e?void 0:e.onFocus)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onBlurHandler(e,t){var n;null===(n=null==e?void 0:e.onBlur)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onInputSubmitRequest(e,t){var n;null===(n=null==e?void 0:e.onEnter)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}shouldInitializePayPalFastlane(e){var t,n;const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(e),o=i.getPaymentProviderCustomer(),a=(s=o)&&("authenticationState"in s||"addresses"in s||"instruments"in s)?o:{};var s;return(null===(t=null==r?void 0:r.initializationData)||void 0===t?void 0:t.isAcceleratedCheckoutEnabled)&&(null===(n=null==r?void 0:r.initializationData)||void 0===n?void 0:n.isPayPalCommerceAnalyticsV2Enabled)&&!(null==a?void 0:a.authenticationState)}initializePayPalFastlaneOrThrow(e){return up(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getPaymentMethodOrThrow(e),{initializationData:r}=i;if(!(null==r?void 0:r.connectClientToken))return;const o=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(i,n.currency.code,n.id,t.getLocale());yield this.paypalFastlaneUtils.initializePayPalFastlane(o,!!(null==r?void 0:r.isDeveloperModeApplicable))}catch(e){}})}}const pp=vi(e=>new hp(e,As(e),Cs(),nd()),[{id:"paypalcommercecreditcards"}]);var mp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class yp{constructor(e,t,n,i=3e3,r=3e5){this.paymentIntegrationService=e,this.paypalCommerceService=t,this.loadingIndicator=n,this.pollingInterval=i,this.maxPollingIntervalTime=r,this.pollingTimer=0,this.stopPolling=ce}initialize(e){return mp(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,paypalcommerceratepay:i}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.paypalcommerceratepay" argument is not provided.');const{legalTextContainer:r,container:o,loadingContainerId:a}=i;if(!o)throw new fi('Unable to initialize payment because "options.container" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.legalTextContainer" argument is not provided.');if(!a)throw new fi('Unable to initialize payment because "options.loadingContainerId" argument is not provided.');this.loadingIndicatorContainer=a;const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t),{merchantId:d}=s.initializationData||{};if(!d)throw new fi("Unable to initialize payment because merchantId argument is not provided.");this.paypalcommerceratepay=i,yield this.paypalCommerceService.loadPayPalSdk(n),this.createFraudNetScript(d,n,t),this.loadFraudnetConfig(),this.renderLegalText(r,o)})}execute(e,t){return mp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.initializePollingMechanism(n.methodId,e,t,n.gatewayId)})}catch(e){return this.handleError(e),new Promise((e,t)=>t())}})}finalize(){return Promise.reject(new Cd)}deinitialize(){const{legalTextContainer:e}=this.paypalcommerceratepay||{},t=document.querySelectorAll('[data-id="fraudnetScript"]')[0],n=document.querySelectorAll('[data-id="fraudnetConfig"]')[0];if(this.deinitializePollingMechanism(),t.remove(),n.remove(),e){const t=document.getElementById(e);null==t||t.remove()}return Promise.resolve()}normalizeDate(e){const t=this.formatDate(e.getDate()),n=this.formatDate(e.getMonth()+1);return`${e.getFullYear()}-${n}-${t}`}formatDate(e){return`${e<10?0:""}${e}`}renderLegalText(e,t){const n=e,i=t.split("#")[1],r=document.getElementById(i),o=null==r?void 0:r.parentNode,a=document.createElement("div");a.style.marginBottom="20px",a.setAttribute("id",n),null==o||o.prepend(a);const s=this.paypalCommerceService.getPayPalSdkOrThrow(),d=s.Legal({fundingSource:s.Legal.FUNDING.PAY_UPON_INVOICE});if(!document.getElementById(n))throw new fi('Unable to initialize payment because "legalTextContainerElement" argument is not found.');d.render(`#${n}`)}handleError(e){const{onError:t}=this.paypalcommerceratepay||{};this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createFraudNetScript(e,t,n){const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{testMode:r}=i.config,o=document.createElement("script");o.setAttribute("type","application/json"),o.setAttribute("fncls","fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99"),o.setAttribute("data-id","fraudnetScript"),this.guid=this.generateGUID();const a={f:this.guid,s:`${e}_checkout-page`,sandbox:r};o.innerHTML=JSON.stringify(a),document.body.appendChild(o)}generateGUID(){let e="";for(let t=0;t<32;t+=1)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(62*Math.random())];return e}loadFraudnetConfig(){const e=document.createElement("script");e.setAttribute("data-id","fraudnetConfig"),e.src="https://c.paypal.com/da/r/fb.js",document.body.appendChild(e)}reinitializeStrategy(e){return mp(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}initializePollingMechanism(e,t,n,i){return mp(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.paypalCommerceService.getOrderStatus("paypalcommercealternativemethods",{params:{useMetadata:!0}}),o=r===_s.PollingStop,a=r===_s.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimernew yp(e,As(e),new vd({containerStyles:Object.assign(Object.assign({},Ka),{position:"fixed"})})),[{gateway:"paypalcommercealternativemethods",id:"ratepay"}]);function vp(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var fp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Sp{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalCommerceRequestSender=t,this.paypalSdkScriptLoader=n,this.paypalFastlaneUtils=i}initialize(e){var t,n;return fp(this,void 0,void 0,function*(){const{methodId:i,paypalcommercefastlane:r}=e;if(this.methodId=i,this.paypalcommercefastlane=r,!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.paypalcommercefastlane" argument is not provided.');if(!r.onInit||"function"!=typeof r.onInit)throw new fi('Unable to initialize payment because "options.paypalcommercefastlane.onInit" argument is not provided or it is not a function.');if(!r.onChange||"function"!=typeof r.onChange)throw new fi('Unable to initialize payment because "options.paypalcommercefastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState(),a=o.getCartOrThrow(),s=o.getPaymentMethodOrThrow(i),{isDeveloperModeApplicable:d,isFastlaneStylingEnabled:c}=s.initializationData||{};this.threeDSVerificationMethod=null===(t=s.initializationData)||void 0===t?void 0:t.threeDSVerificationMethod,this.paypalFastlaneSdk=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(s,a.currency.code,a.id,o.getLocale());const l=rd(c?null===(n=null==s?void 0:s.initializationData)||void 0===n?void 0:n.fastlaneStyles:{},null==r?void 0:r.styles);yield this.paypalFastlaneUtils.initializePayPalFastlane(this.paypalFastlaneSdk,!!d,l),this.shouldRunAuthenticationFlow()&&(yield this.runPayPalAuthenticationFlowOrThrow(i)),yield this.initializePayPalPaymentComponent(),r.onInit(e=>this.renderPayPalPaymentComponent(e)),r.onChange(()=>this.handlePayPalStoredInstrumentChange(i))})}execute(e,t){return fp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const{getHost:t}=e.getState();return new Sp(e,new Gs(n({host:t()})),Cs(),nd())},[{id:"paypalcommerceacceleratedcheckout"}]);var wp,Ip,Cp,bp,Pp,Op;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(wp||(wp={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(Ip||(Ip={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black"}(Cp||(Cp={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(bp||(bp={})),function(e){e.PILL="pill",e.RECT="rect"}(Pp||(Pp={})),function(e){e.ACKNOWLEDGE="ACKNOWLEDGE",e.FINALIZE="FINALIZE",e.INITIALIZE="INITIALIZE"}(Op||(Op={}));var Ep=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ap{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t,this.useRedirectFlow=!1,this.window=window}initialize(e){return Ep(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState();this.paymentMethod=t.getPaymentMethodOrThrow(e.methodId),this.useRedirectFlow=!0===(e.paypalexpress&&e.paypalexpress.useRedirectFlow);const n=this.paymentMethod.config.merchantId;if(!this.isInContextEnabled()||!n)throw new ti(Xn.MissingPaymentMethod);const i=yield this.scriptLoader.loadPaypalSDK();this.paypalSdk=i,this.paypalSdk.checkout.setup(n,{button:"paypal-button",environment:this.paymentMethod.config.testMode?"sandbox":"production"})})}deinitialize(){return this.isInContextEnabled()&&this.paypalSdk&&(this.paypalSdk.checkout.closeFlow(),this.paypalSdk=void 0),Promise.resolve()}execute(e,t){return Ep(this,void 0,void 0,function*(){let n,i;const r=this.paypalSdk;if(!this.isAcknowledgedOrFinalized()){if(!this.isInContextEnabled()||this.useRedirectFlow)return n=yield this.paymentIntegrationService.submitOrder(e,t),i=n.getPaymentRedirectUrl(),i&&this.window.top&&(this.window.top.location.href=i),new Promise(ce);if(!r)throw new ri(ei.PaymentNotInitialized);r.checkout.initXO();try{n=yield this.paymentIntegrationService.submitOrder(e,t)}catch(e){return r.checkout.closeFlow(),Promise.reject(e)}return i=n.getPaymentRedirectUrl(),i&&r.checkout.startFlow(i),new Promise(ce)}yield this.paymentIntegrationService.submitOrder(e,t)})}finalize(e){return Ep(this,void 0,void 0,function*(){return this.paymentIntegrationService.getState().getOrder()&&this.isAcknowledgedOrFinalized()?(yield this.paymentIntegrationService.finalizeOrder(e),Promise.resolve()):Promise.reject(new Cd)})}isAcknowledgedOrFinalized(){const e=this.paymentIntegrationService.getState();return e.getPaymentStatus()===Op.ACKNOWLEDGE||e.getPaymentStatus()===Op.FINALIZE}isInContextEnabled(){return!(!this.paymentMethod||!this.paymentMethod.config.merchantId)}}class Tp{constructor(e){this.scriptLoader=e,this.window=window}loadPaypalSDK(e=""){return t=this,n=void 0,r=function*(){const t=Object.assign({async:!0,attributes:{"data-merchant-id":e}},e&&{attributes:{"data-merchant-id":e}});if(yield this.scriptLoader.loadScript("//www.paypalobjects.com/api/checkout.min.js",t),!this.window.paypal)throw new mi;return this.window.paypal},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const kp=vi(e=>new Ap(e,new Tp(a())),[{id:"paypalexpress",type:"PAYMENT_TYPE_HOSTED"},{id:"paypalexpresscredit",type:"PAYMENT_TYPE_HOSTED"}]);var Dp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Mp extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this.threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Dp(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);n.config.is3dsEnabled&&(yield this.threeDSecureFlow.prepare(n))})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return Dp(this,void 0,void 0,function*(){const{payment:{methodId:i=""}={}}=e,r=this.paymentIntegrationService.getState();return r.getPaymentStatus()===dl.ACKNOWLEDGE?(yield this.paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:{methodId:i}}),t),Promise.resolve()):r.getPaymentMethodOrThrow(i).config.is3dsEnabled?this.threeDSecureFlow.start(n.execute.bind(this),e,t,this._hostedForm):n.execute.call(this,e,t)})}}const zp=vi(e=>new Mp(e,new Au(e,new Fu(new Lu(a())))),[{id:"paypal"}]);class Np extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this._formPoster=t}execute(e,t){const{payment:n}=e;if(!n)throw new ri(ei.PaymentNotInitialized);const{paymentData:i}=n;if(!i)throw new ti(Xn.MissingPayment);if(this._isThreeDSTwoExperimentOn()){const t=Object.assign(Object.assign({},i),{browser_info:ss()});e.payment&&(e.payment.paymentData=t)}return super.execute(e,t).catch(e=>pa(e)&&ve(e.body.errors,{code:"three_d_secure_required"})?new Promise(()=>{let t;t=this._isThreeDSTwoExperimentOn()&&!e.body.three_ds_result.merchant_data?{creq:e.body.three_ds_result.payer_auth_request}:{PaReq:e.body.three_ds_result.payer_auth_request,TermUrl:e.body.three_ds_result.callback_url,MD:e.body.three_ds_result.merchant_data},this._formPoster.postForm(e.body.three_ds_result.acs_url,t,void 0,"_top")}):Promise.reject(e))}finalize(e){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),super.finalize()}_isThreeDSTwoExperimentOn(){return!0===this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features["INT-4994.Opayo_3DS2"]}}const xp=vi(e=>new Np(e,Ee()),[{id:"sagepay"}]);class Rp{constructor(e,t){this._formPoster=e,this._paymentIntegrationService=t}execute(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.redirectUrl(t)})}var o},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}redirectUrl(e){return this._formPoster.postForm(e,{})}_isAdditionalActionRequired(e){const{additional_action_required:t,status:n}=e;return"additional_action_required"===n&&t&&"offsite_redirect"===t.type}}class Fp extends Rp{redirectUrl(e){window.location.replace(e)}}const Lp=vi(e=>new Fp(Ee(),e),[{id:"sezzle"}]);var Bp;!function(e){e.CHARGE="CHARGE",e.STORE="STORE"}(Bp||(Bp={}));var jp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Up{constructor(e,t){this._scriptLoader=e,this._paymentIntegrationService=t}initialize({testMode:e,applicationId:t,locationId:n}){return jp(this,void 0,void 0,function*(){const i=yield this._scriptLoader.load(e);this._payments=i.payments(t,n)})}deinitialize(){return jp(this,void 0,void 0,function*(){this._formValidationSubscription&&this._formValidationSubscription.unsubscribe(),this._card&&(yield this._card.destroy()),this._formValidationSubscription=void 0,this._card=void 0,this._payments=void 0})}initializeCard({containerId:e,style:t,onValidationChange:n}){return jp(this,void 0,void 0,function*(){const{postalCode:i}=this._paymentIntegrationService.getState().getBillingAddress()||{};this._card=yield this._getPayments().card(),yield this._card.attach(`#${e}`);try{yield this._card.configure({postalCode:i,style:t})}catch(e){}n&&(this._formValidationSubscription=this._subscribeToFormValidation(this._card,n))})}tokenize(){return jp(this,void 0,void 0,function*(){const e=yield this._getCard().tokenize();if("OK"!==e.status||!e.token){let t=`Tokenization failed with status: ${e.status}`;throw"errors"in e&&e.errors&&(t+=` and errors: ${JSON.stringify(e.errors)}`),new _h("payment.errors.card_error","SquareV2TokenizationError",t)}return e.token})}verifyBuyer(e,t){return jp(this,void 0,void 0,function*(){return t===Bp.CHARGE?this._chargeVerifyBuyer(e):this._storeVerifyBuyer(e)})}_getPayments(){return ii(this._payments,()=>new ri(ei.PaymentNotInitialized))}_subscribeToFormValidation(e,t){const n=["cardNumber","cvv"],i=new Set(n),r=["focusClassAdded","focusClassRemoved","errorClassAdded","errorClassRemoved","cardBrandChanged","postalCodeChanged"].map(t=>_(e,t));return w(...r).pipe(T(e=>{const{detail:{field:t,currentState:{isCompletelyValid:r}}}=e;return n.includes(t)&&i[r?"delete":"add"](t),0===i.size}),E()).subscribe(t)}_getCard(){return ii(this._card,()=>new ri(ei.PaymentNotInitialized))}_mapToSquareBillingContact({firstName:e,lastName:t,address1:n,address2:i,city:r,stateOrProvinceCode:o,postalCode:a,countryCode:s,email:d,phone:c}){return{givenName:e,familyName:t,addressLines:[n,i],city:r,state:o,postalCode:a,countryCode:s,email:d,phone:c}}_chargeVerifyBuyer(e){return jp(this,void 0,void 0,function*(){const{getCheckoutOrThrow:t,getBillingAddressOrThrow:n}=this._paymentIntegrationService.getState(),{outstandingBalance:i,cart:r}=t(),o={amount:i.toString(),billingContact:this._mapToSquareBillingContact(n()),currencyCode:r.currency.code,intent:Bp.CHARGE},a=yield this._getPayments().verifyBuyer(e,o);return a?a.token:""})}_storeVerifyBuyer(e){return jp(this,void 0,void 0,function*(){const{getBillingAddressOrThrow:t}=this._paymentIntegrationService.getState(),n={billingContact:this._mapToSquareBillingContact(t()),intent:Bp.STORE},i=yield this._getPayments().verifyBuyer(e,n);return i?i.token:""})}}var qp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vp{constructor(e,t){this._paymentIntegrationService=e,this._squareV2PaymentProcessor=t}initialize(e){var t;return qp(this,void 0,void 0,function*(){if(!(null===(t=null==e?void 0:e.squarev2)||void 0===t?void 0:t.containerId))throw new fi('Unable to proceed because "containerId" argument is not provided.');const{methodId:n,squarev2:i}=e,{config:{testMode:r},initializationData:o}=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(n),{applicationId:a,locationId:s}=o||{};if(!a)throw new Xr;yield this._squareV2PaymentProcessor.initialize({applicationId:a,locationId:s,testMode:r}),yield this._squareV2PaymentProcessor.initializeCard(i)})}execute({payment:e}){return qp(this,void 0,void 0,function*(){if(!e)throw new co(["payment"]);const{methodId:t,paymentData:n}=e,{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r}=jd(n)?n:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1};yield this._paymentIntegrationService.submitOrder();const o=n&&xd(n)?yield this._getVaultedInstrumentPayload(t,n):yield this._getCardPayload(t,i);yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:{formattedPayload:Object.assign(Object.assign({},o),{vault_payment_instrument:i||!1,set_as_default_stored_instrument:r||!1})}}))})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this._squareV2PaymentProcessor.deinitialize()}shouldVerify(){const{features:e}=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings;return e["PROJECT-3828.add_3ds_support_on_squarev2"]}_getCardPayload(e,t){return qp(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),{initializationData:i}=n(e),r=yield this._squareV2PaymentProcessor.tokenize();if(i&&"isSquareV2ApiV2Enabled"in i?!i.isSquareV2ApiV2Enabled:!this.shouldVerify())return{credit_card_token:{token:r}};let o={nonce:r,token:yield this._squareV2PaymentProcessor.verifyBuyer(r,Bp.CHARGE)};if(t){const e=yield this._squareV2PaymentProcessor.tokenize();o=Object.assign(Object.assign({},o),{store_card_nonce:e,store_card_token:yield this._squareV2PaymentProcessor.verifyBuyer(e,Bp.STORE)})}return{credit_card_token:{token:JSON.stringify(o)}}})}_getVaultedInstrumentPayload(e,t){return qp(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),{initializationData:i}=n(e),{instrumentId:r}=t,o=(i&&"isSquareV2ApiV2Enabled"in i?i.isSquareV2ApiV2Enabled:this.shouldVerify())?yield this._squareV2PaymentProcessor.verifyBuyer(yield this._getSquareCardIdOrThrow(e,r),Bp.CHARGE):void 0;return{bigpay_token:Object.assign({token:r},o&&{three_d_secure:{token:o}})}})}_getSquareCardIdOrThrow(e,t){return qp(this,void 0,void 0,function*(){const n=yield this._paymentIntegrationService.loadPaymentMethod(e,{params:{method:e,bigpayToken:t}}),{initializationData:i}=n.getPaymentMethodOrThrow(e),{cardId:r}=i||{};if(!r)throw new co(["cardId"]);return r})}}var Gp;!function(e){e.LIVE="https://web.squarecdn.com/v1/square.js",e.SANDBOX="https://sandbox.web.squarecdn.com/v1/square.js"}(Gp||(Gp={}));class Hp{constructor(e){this._scriptLoader=e}load(e=!1){return t=this,n=void 0,r=function*(){return yield this._scriptLoader.loadScript(e?Gp.SANDBOX:Gp.LIVE),function(e){if(!function(e){return"Square"in e}(e))throw new mi}(window),window.Square},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const Wp=vi(e=>new Vp(e,new Up(new Hp(a()),e)),[{id:"squarev2"}]);function $p(e){return null!==e&&"object"==typeof e&&"cardNumberElementOptions"in e&&"cardCvcElementOptions"in e&&"cardExpiryElementOptions"in e&&void 0!==e.cardNumberElementOptions&&void 0!==e.cardCvcElementOptions&&void 0!==e.cardExpiryElementOptions}var Yp,Kp,Jp,Zp;!function(e){e.Solid="solid",e.Default="default"}(Yp||(Yp={})),function(e){e.Alipay="alipay",e.CardCvc="cardCvc",e.CardExpiry="cardExpiry",e.CardNumber="cardNumber",e.CreditCard="card",e.IDEAL="idealBank",e.Sepa="iban"}(Kp||(Kp={})),function(e){e.Alipay="alipay",e.CreditCard="card",e.IDEAL="ideal",e.Sepa="sepa_debit"}(Jp||(Jp={})),function(e){e.AuthFailure="auth_failure"}(Zp||(Zp={}));class Qp extends Qn{constructor(e){super(e===Zp.AuthFailure?"User did not authenticate":"There was an error while processing your payment. Please try again or contact us."),this.type="stripev3_error",this.subtype=e}}var Xp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const em=[Kp.Alipay,Kp.IDEAL];class tm{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){return Xp(this,void 0,void 0,function*(){const{stripev3:t,methodId:n,gatewayId:i}=e;if(!i)throw new fi('Unable to initialize payment because "gatewayId" argument is not provided.');this.initializeOptions=t,this.isDeinitialize=!1;const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n),{initializationData:{stripePublishableKey:o,stripeConnectedAccount:a,useIndividualCardFields:s,allowRedisplayForStoredInstruments:d}}=r;this._allowRedisplayForStoredInstruments=d;const c=this.getInitializeOptions().form;this.useIndividualCardFields=s,this.stripeV3Client=yield this.loadStripeJs(o,a),this.isCreditCard(n)&&this.shouldShowTSVHostedForm(n,i)&&c?this.hostedForm=yield this.mountCardVerificationFields(c):this.stripeElement=yield this.mountCardFields(n)})}execute(e,t){var n,i;return Xp(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{switch(this.stripeElements||(this.stripeElements=this.getStripeJs().elements()),e){case Kp.CreditCard:if(this.useIndividualCardFields&&$p(t)){const{cardNumberElementOptions:e,cardExpiryElementOptions:n,cardCvcElementOptions:r}=t,a=this.stripeElements.getElement(Kp.CardNumber)||this.stripeElements.create(Kp.CardNumber,e),s=this.stripeElements.getElement(Kp.CardExpiry)||this.stripeElements.create(Kp.CardExpiry,n),d=this.stripeElements.getElement(Kp.CardCvc)||this.stripeElements.create(Kp.CardCvc,r);this.stripeCardElements=[a,s,d],i=this.stripeCardElements[0];try{a.mount(`#${e.containerId}`),s.mount(`#${n.containerId}`),d.mount(`#${r.containerId}`)}catch(e){this.isDeinitialize||o(new fi("Unable to mount Stripe component without valid container ID."))}}else{i=this.stripeElements.getElement(e)||this.stripeElements.create(e,t);try{i.mount(`#${n}`)}catch(e){this.isDeinitialize||o(new fi("Unable to mount Stripe component without valid container ID."))}}break;case Kp.IDEAL:case Kp.Sepa:i=this.stripeElements.getElement(e)||this.stripeElements.create(e,t);try{i.mount(`#${n}`)}catch(e){this.isDeinitialize||o(new fi("Unable to mount Stripe component without valid container ID."))}case Kp.Alipay:}r(i)})}mountCardVerificationFields(e){return Xp(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getStoreConfig();if(!t)throw new ti(Xn.MissingCheckoutConfig);const n=t.paymentSettings.bigpayBaseUrl,i=this.paymentIntegrationService.createHostedForm(n,e);return yield i.attach(),i})}processAdditionalAction(e,t,n=!1,i=!1){return Xp(this,void 0,void 0,function*(){if(!pa(e))throw e;const r=ve(e.body.errors,{code:"additional_action_required"}),o=ve(e.body.errors,{code:"three_d_secure_required"});if(r){const t=e.body.additional_action_required;if(t&&"redirect_to_url"===t.type)return new Promise(()=>{t.data.redirect_url&&window.location.replace(t.data.redirect_url)})}if(o){const r=e.body.three_ds_result.token,o=!1;let a,s=!1;try{a=yield this.getStripeJs().confirmCardPayment(r)}catch(e){s=!0}if(null==a?void 0:a.error){if(this.isCancellationError(a.error))throw new Wi;if(this.isAuthError(a.error))throw new Qp(Zp.AuthFailure);throw new Error(a.error.message)}const d={credit_card_token:{token:this.getPaymentToken(null==a?void 0:a.paymentIntent,r,s)},vault_payment_instrument:n,confirm:o},c=this.buildPaymentPayload(t,d,i);try{return yield this.paymentIntegrationService.submitPayment(c)}catch(e){throw this.handleEmptyPaymentIntentError(e,null==a?void 0:a.error)}}throw e})}getPaymentToken(e,t,n){return!e||n?t:e.id}shouldShowTSVHostedForm(e,t){return this.isHostedFieldAvailable()&&this.isHostedPaymentFormEnabled(e,t)}unmountElement(){this.stripeElement&&(this.stripeElement.unmount(),this.stripeElement=void 0)}}class nm{constructor(e,t=window){this.scriptLoader=e,this.stripeWindow=t}load(e,t,n){return this.scriptLoader.loadScript("https://js.stripe.com/v3/").then(()=>{if(!this.stripeWindow.Stripe)throw new mi;return this.stripeWindow.Stripe(e,{stripeAccount:t,locale:n,betas:["payment_intent_beta_3","alipay_pm_beta_1"],apiVersion:"2020-03-02;alipay_beta=v1"})})}}const im=vi(e=>new tm(e,new nm(a())),[{gateway:"stripev3"}]),rm={ar:["ar"],bg:["bg"],cs:["cs"],da:["da"],de:["de"],el:["el"],en:["en","en-GB"],es:["es","es-419"],et:["et"],fi:["fi"],fil:["fil"],fr:["fr","fr-CA"],he:["he"],hr:["hr"],hu:["hu"],id:["id"],it:["it"],ja:["ja"],ko:["ko"],lt:["lt"],lv:["lv"],ms:["ms"],mt:["mt"],nb:["nb"],nl:["nl"],pl:["pl"],pt:["pt","pt-BR"],ro:["ro"],ru:["ru"],sk:["sk"],sl:["sl"],sv:["sv"],th:["th"],tr:["tr"],vi:["vi"],zh:["zh","zh-HK","zh-TW"]};function om(e){const[t,n]=e.replace(/_/g,"-").toLowerCase().split("-"),i=rm[t];if(!i)return"auto";const r=n?`${t}-${n.toUpperCase()}`:t;return i.indexOf(r)>-1?r:i[0]}var am=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class sm{constructor(e,t,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n}initialize(e){return am(this,void 0,void 0,function*(){const{stripeupe:t,methodId:n,gatewayId:i}=e;if(!(null==t?void 0:t.containerId))throw new ri(ei.PaymentNotInitialized);if(!i)throw new fi('Unable to initialize payment because "gatewayId" argument is not provided.');return this._loadStripeElement(t,i,n).catch(e=>{var n;return null===(n=t.onError)||void 0===n?void 0:n.call(t,e)}),this.stripeIntegrationService.initCheckoutEventsSubscription(i,n,t,this._stripeElements),Promise.resolve()})}execute(e,t){return am(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{o()}),f.on(za.CHANGE,e=>{(null==e?void 0:e.value)&&"type"in e.value&&this._updateStripeLinkStateByElementType(e.value.type)}),this._isStripeElementUpdateEnabled&&(null==a||a(this._updateStripeElement.bind(this)))})}_processAdditionalActionWithStripeConfirmation(e,t,n,i=!1,r=!1){return am(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new ri(ei.PaymentNotInitialized);const{data:o}=e.body.additional_action_required,{token:a}=o,{paymentIntent:s,error:d}=yield this._confirmStripePaymentOrThrow(t,o),c=this._getPaymentPayload(t,(null==s?void 0:s.id)||a,i,r);if(d||!s){const{initializationData:e}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{sendSecondPaymentRequestOnStripeError:i}=e||{};if(i)try{const e=de({},c,{paymentData:{formattedPayload:{client_side_error:!0}}});yield this.paymentIntegrationService.submitPayment(e)}catch(e){}this.stripeIntegrationService.throwStripeError(d)}try{yield this.paymentIntegrationService.submitPayment(c)}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}})}_confirmStripePaymentOrThrow(e,t){return am(this,void 0,void 0,function*(){if(!this._stripeUPEClient)throw new ri(ei.PaymentNotInitialized);const{token:n,redirect_url:i}=t,r=this.stripeIntegrationService.mapStripePaymentData(this._stripeElements,i,!!this._allowRedisplayForStoredInstruments);return(yield this.stripeIntegrationService.isPaymentCompleted(e,this._stripeUPEClient))?this._stripeUPEClient.retrievePaymentIntent(n||""):this._stripeUPEClient.confirmPayment(r)})}_processVaultedAdditionalAction(e,t,n=!1){var i;return am(this,void 0,void 0,function*(){if(!t||!pa(e)||!ve(e.body.errors,{code:"three_d_secure_required"}))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new ri(ei.PaymentNotInitialized);const r=e.body.three_ds_result.token;let o,a=!1;try{o=yield this._stripeUPEClient.confirmCardPayment(r)}catch(e){try{o=yield this._stripeUPEClient.retrievePaymentIntent(r)}catch(e){a=!0}}if((null==o?void 0:o.error)&&this.stripeIntegrationService.throwStripeError(o.error),!(null==o?void 0:o.paymentIntent)&&!a)throw new nr;const s=this._getPaymentPayload(t,a?r:null===(i=null==o?void 0:o.paymentIntent)||void 0===i?void 0:i.id,!1,n);return this.paymentIntegrationService.submitPayment(s)})}_loadStripeJs(e){return am(this,void 0,void 0,function*(){if(this._stripeUPEClient)return this._stripeUPEClient;const t=this.paymentIntegrationService.getState();return this.scriptLoader.getStripeClient(e,t.getCartLocale(),ka.V3,Fa,La)})}_getPaymentPayload(e,t,n=!1,i=!1){var r;return{methodId:e,paymentData:{formattedPayload:{cart_id:(null===(r=this.paymentIntegrationService.getState().getCart())||void 0===r?void 0:r.id)||"",credit_card_token:{token:t},confirm:!1,vault_payment_instrument:n,set_as_default_stored_instrument:i}}}}_updateStripeElement({shouldShowTerms:e}){var t;const n=null===(t=this._stripeElements)||void 0===t?void 0:t.getElement(Da.PAYMENT);null==n||n.update(Object.assign({},this._getStripeElementTerms(e)))}_getStripeElementTerms(e){let t=Ta.AUTO;return this._isStripeElementUpdateEnabled&&(t=e?Ta.AUTO:Ta.NEVER),{terms:{card:t}}}_updateStripeLinkStateByElementType(e){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow(),n=e===Aa.Link;!cd(t)&&n&&this.paymentIntegrationService.updatePaymentProviderCustomer({stripeLinkAuthenticationState:n})}}const dm=vi(e=>{const t=new Ra(a());return new sm(e,t,new pd(e,t))},[{gateway:"stripeupe"},{gateway:"stripeupe",id:"klarna"}]),cm=e=>"object"==typeof e&&null!==e&&"value"in e&&"collapsed"in e;var lm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class um{constructor(e,t,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n}initialize(e){var t;return lm(this,void 0,void 0,function*(){const{stripeocs:n,methodId:i,gatewayId:r}=e;if(!(null==n?void 0:n.containerId))throw new ri(ei.PaymentNotInitialized);if(!r)throw new fi('Unable to initialize payment because "gatewayId" argument is not provided.');try{yield this._initializeStripeElement(n,r,i)}catch(e){e instanceof Error&&(null===(t=n.onError)||void 0===t||t.call(n,e))}this.stripeIntegrationService.initCheckoutEventsSubscription(r,i,n,this.stripeElements)})}execute(e,t){return lm(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{null==y||y(!1)}),_.on(za.READY,()=>{h()}),_.on(za.CHANGE,e=>{this._onStripeElementChange(e,t,n,p)}),null==m||m(this._collapseStripeElement.bind(this))})}_loadStripeJs(e){return lm(this,void 0,void 0,function*(){if(this.stripeClient)return this.stripeClient;const t=this.paymentIntegrationService.getState(),n=this.stripeIntegrationService.getStripeJsVersion(e);return this.scriptLoader.getStripeClient(e,t.getCartLocale(),n)})}_collapseStripeElement(){var e;const t=null===(e=this.stripeElements)||void 0===e?void 0:e.getElement(Da.PAYMENT);null==t||t.collapse()}_getPaymentPayload(e,t,n){var i;const r=(null===(i=this.paymentIntegrationService.getState().getCart())||void 0===i?void 0:i.id)||"",{card:o,us_bank_account:a}=n||{},s=this._shouldSaveInstrument(o)||this._shouldSaveInstrument(a),d=this._getTokenizedOptions(t,n);return{methodId:e,paymentData:{formattedPayload:Object.assign({cart_id:r,confirm:!1,method:this.selectedMethodId,vault_payment_instrument:s},d)}}}_processAdditionalAction(e,t,n){return lm(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this.stripeClient||!this.stripeElements)throw new ri(ei.PaymentNotInitialized);const{data:i}=e.body.additional_action_required,{token:r}=i,{paymentIntent:o,error:a}=yield this._confirmStripePaymentOrThrow(t,i),{client_secret:s,payment_method_options:d}=o||{},c=this._getPaymentPayload(t,s||r,d);if(a||!o){const{initializationData:e}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{sendSecondPaymentRequestOnStripeError:i}=e||{};if(i)try{const e=de({},c,{paymentData:{formattedPayload:{client_side_error:!0}}});yield this.paymentIntegrationService.submitPayment(e)}catch(e){}this.stripeIntegrationService.throwStripeError(a)}try{return yield this.paymentIntegrationService.submitPayment(c)}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}})}_confirmStripePaymentOrThrow(e,t){return lm(this,void 0,void 0,function*(){if(!this.stripeClient)throw new ri(ei.PaymentNotInitialized);const{token:n,redirect_url:i}=t,r=this.stripeIntegrationService.mapStripePaymentData(this.stripeElements,i);return(yield this.stripeIntegrationService.isPaymentCompleted(e,this.stripeClient))?this.stripeClient.retrievePaymentIntent(n||""):this.stripeClient.confirmPayment(r)})}_onStripeElementChange(e,t,n,i){cm(e)&&!e.collapsed&&(this.selectedMethodId=e.value.type,null==i||i(`${t}-${n}`))}_shouldSaveInstrument(e){const t=null==e?void 0:e.setup_future_usage;return t===Na.ON_SESSION||t===Na.OFF_SESSION}_getTokenizedOptions(e,t){return this._shouldSaveInstrument(null==t?void 0:t.us_bank_account)?{tokenized_ach:{token:e}}:{credit_card_token:{token:e}}}}const hm=vi(e=>{const t=new Ra(a());return new um(e,t,new pd(e,t))},[{gateway:"stripeocs",id:"optimized_checkout"}]);var pm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class mm{constructor(e,t,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n}initialize(e){var t;return pm(this,void 0,void 0,function*(){const{stripeocs:n,methodId:i,gatewayId:r}=e;if(!(null==n?void 0:n.containerId)||!r)throw new ri(ei.PaymentNotInitialized);let o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,r);(null==o?void 0:o.clientToken)||(yield this.paymentIntegrationService.loadPaymentMethod(r,{params:{method:i}}),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,r));try{yield this._initStripeCheckoutSession(n,o),yield this._updateStripeShopperData(),this._initializePaymentElement(n,o),this._initializeAdaptivePricingElement(n,o)}catch(e){e instanceof Error&&(null===(t=n.onError)||void 0===t||t.call(n,e))}})}execute(e,t){return pm(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{null==u||u(!1)}),h.on(za.READY,()=>{d()}),h.on(za.CHANGE,e=>{this._onStripeElementChange(e,r,i,c)}),null==l||l(this._collapseStripeElement.bind(this))}_loadStripeJs(e){return pm(this,void 0,void 0,function*(){if(this.stripeClient)return this.stripeClient;const t=this.paymentIntegrationService.getState();return this.scriptLoader.getStripeClient(e,t.getCartLocale(),ka.CLOVER)})}_getStripeActionsOrThrow(){return pm(this,void 0,void 0,function*(){if(!this.stripeCheckout)throw new ri(ei.PaymentNotInitialized);const{actions:e,error:t}=yield this.stripeCheckout.loadActions();if(!e||t)throw new Qr(null==t?void 0:t.message);return e})}_getStripeElement(e){var t,n;return(null===(t=this.stripeCheckout)||void 0===t?void 0:t.getPaymentElement())||(null===(n=this.stripeCheckout)||void 0===n?void 0:n.createPaymentElement(e))}_onStripeElementChange(e,t,n,i){cm(e)&&!e.collapsed&&(this.selectedMethodId=e.value.type,null==i||i(`${t}-${n}`))}_collapseStripeElement(){var e;const t=null===(e=this.stripeCheckout)||void 0===e?void 0:e.getPaymentElement();null==t||t.collapse()}_updateCheckoutSessionData(e,t){return pm(this,void 0,void 0,function*(){yield this._updateStripeShopperData(),yield this.paymentIntegrationService.loadPaymentMethod(e,{params:{method:t}})})}_getPaymentPayload(e,t,n){var i;const r=(null===(i=this.paymentIntegrationService.getState().getCart())||void 0===i?void 0:i.id)||"",o=this._getTokenizedOptions(t,n);return{methodId:e,paymentData:{formattedPayload:Object.assign({cart_id:r,confirm:!1,method:this.selectedMethodId,vault_payment_instrument:!!n},o)}}}_processAdditionalAction(e,t,n){var i;return pm(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;const{data:r}=(null===(i=e.body)||void 0===i?void 0:i.additional_action_required)||{},{token:o}=r||{},a=yield this._getStripeSavedPaymentMethodsOrThrow(),{session:s,error:d}=yield this._confirmStripePayment(r),c=yield this._getStripeSavedPaymentMethodsOrThrow(s),{id:l,status:u}=s||{},h=this._getNewVaultedStripeInstrument(a,c),p=this._getPaymentPayload(n,l||o,h),{initializationData:m}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t),{sendSecondPaymentRequestOnStripeError:y}=m||{};if(d||!s){if(y)try{const e=de({},p,{paymentData:{formattedPayload:{client_side_error:!0}}});yield this.paymentIntegrationService.submitPayment(e)}catch(e){}throw new Qr(null==d?void 0:d.message)}try{return yield this.paymentIntegrationService.submitPayment(p)}catch(e){throw(null==u?void 0:u.paymentStatus)===Oa.Paid&&this.stripeIntegrationService.throwPaymentConfirmationProceedMessage(),e}})}_confirmStripePayment(e){return pm(this,void 0,void 0,function*(){const{redirect_url:t}=e||{};if(!this.stripeCheckout)throw new ri(ei.PaymentNotInitialized);return(yield this._getStripeActionsOrThrow()).confirm({redirect:Ta.IF_REQUIRED,returnUrl:t})})}_updateStripeShopperData(){return pm(this,void 0,void 0,function*(){const e=yield this._getStripeActionsOrThrow();yield this._updateStripeEmail(e),yield this._updateStripeShippingAddress(e),yield this._updateStripeBillingAddress(e)})}_updateStripeEmail(e){return pm(this,void 0,void 0,function*(){if((yield e.getSession()).email)return;const{getBillingAddress:t}=this.paymentIntegrationService.getState(),n=t();yield e.updateEmail((null==n?void 0:n.email)||"")})}_updateStripeShippingAddress(e){return pm(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getShippingAddress();t&&(yield e.updateShippingAddress({name:this.stripeIntegrationService.getShopperFullName(t),address:this.stripeIntegrationService.mapStripeAddress(t)}))})}_updateStripeBillingAddress(e){return pm(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getBillingAddress();t&&(yield e.updateBillingAddress({name:this.stripeIntegrationService.getShopperFullName(t),address:this.stripeIntegrationService.mapStripeAddress(t)}))})}_getStripeSavedPaymentMethodsOrThrow(e){return pm(this,void 0,void 0,function*(){if(null==e?void 0:e.savedPaymentMethods)return e.savedPaymentMethods;const t=yield this._getStripeActionsOrThrow(),{savedPaymentMethods:n}=yield t.getSession();return n||[]})}_getNewVaultedStripeInstrument(e,t){return t.find(t=>!e.some(e=>e.id===t.id))}_getTokenizedOptions(e,t){return(null==t?void 0:t.type)===Aa.ACH?{tokenized_ach:{token:e}}:{credit_card_token:{token:e}}}_initializeAdaptivePricingElement(e,t){const{initializationData:n}=t,{currencySelectorContainerId:i}=e;if(!(null==n?void 0:n.adaptivePricingEnabled))return;if(!i)throw new ri(ei.PaymentNotInitialized);const r=this._getCurrencySelectorElement();r&&(r.mount(`#${i}`),this._initAdaptivePricingEvents(r))}_getCurrencySelectorElement(){var e,t;return(null===(e=this.stripeCheckout)||void 0===e?void 0:e.getCurrencySelectorElement())||(null===(t=this.stripeCheckout)||void 0===t?void 0:t.createCurrencySelectorElement())}_initAdaptivePricingEvents(e){e.on(za.CHANGE,e=>pm(this,void 0,void 0,function*(){if(!e.value||!("currency"in e.value))return;const{currency:t}=this.paymentIntegrationService.getState().getCartOrThrow(),n=t.code.toLowerCase(),i=e.value.currency.toLowerCase();yield this.paymentIntegrationService.updatePaymentProviderCustomer({isCustomerCurrencySelected:n!==i,customerCurrency:i})}))}}const ym=vi(e=>{const t=new Ra(a());return new mm(e,t,new pd(e,t))},[{gateway:"stripeocs",id:"checkout_session"}]);var gm;!function(e){e.CARD_NUMBER="card-number",e.CVV="cvv",e.EXPIRY="expiry"}(gm||(gm={}));var vm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class fm{constructor(e,t,n){this.paymentIntegrationService=e,this.tdOnlineMartScriptLoader=t,this.formPoster=n,this.tdInputs=[{id:"ccNumber",fieldType:gm.CARD_NUMBER},{id:"ccCvv",fieldType:gm.CVV},{id:"ccExpiry",fieldType:gm.EXPIRY}]}initialize(e){return vm(this,void 0,void 0,function*(){const{methodId:t}=e;if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');this.tdOnlineMartClient=yield this.loadTDOnlineMartJs(),this.mountHostedFields(t)})}execute(e,t){return vm(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{null==e||e.unmount()}),Promise.resolve()}getPaymentPayloadOrThrow(e){return vm(this,void 0,void 0,function*(){const{methodId:t,paymentData:n}=e,{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:r=!1}=jd(n)?n:{},o={browser_info:ss(),shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r};if(jd(n)&&xd(n)&&n.instrumentId){const e=!!this.paymentIntegrationService.getState().getCartOrThrow().lineItems.digitalItems.length,i=!this.isTrustedVaultingInstrument(n.instrumentId)||e;return{methodId:t,paymentData:Object.assign(Object.assign(Object.assign({},o),{instrumentId:n.instrumentId}),i?{nonce:n.instrumentId}:{})}}let a;try{a=yield this.getTokenOrThrow()}catch(e){this.throwTokenizationError(e)}return{methodId:t,paymentData:Object.assign(Object.assign({},o),{nonce:a})}})}mountHostedFields(e){const t=this.getHostedFieldsOptions(),n=this.getTDOnlineMartClientOrThrow();this.tdInputs.forEach(i=>{const r=`${e}-${i.id}`;document.getElementById(r)&&(i.inputElement=n.create(i.fieldType,t),i.inputElement.mount(`#${r}`))})}loadTDOnlineMartJs(){return vm(this,void 0,void 0,function*(){return this.tdOnlineMartClient?this.tdOnlineMartClient:this.tdOnlineMartScriptLoader.load()})}getTokenOrThrow(){return new Promise((e,t)=>{this.getTDOnlineMartClientOrThrow().createToken(n=>{const{error:i,token:r}=n;if(i||!r)return t(i);e(r)})})}getTDOnlineMartClientOrThrow(){if(!this.tdOnlineMartClient)throw new ri(ei.PaymentNotInitialized);return this.tdOnlineMartClient}processWithAdditionalAction(e){return vm(this,void 0,void 0,function*(){if(!function(e){return pa(e)&&(t=e.body,Z(t)&&"object"==typeof t&&"errors"in t&&"three_ds_result"in t&&W(t.errors)&&ve(t.errors,{code:"three_d_secure_required"}));var t}(e))throw e;const{three_ds_result:t}=e.body,{acs_url:n,payer_auth_request:i,merchant_data:r}=t||{};if(!n||!i||!r)throw new co(["formUrl","threeDSSessionData","creq"]);return new Promise(e=>{this.formPoster.postForm(n,{threeDSSessionData:i,creq:r},e,"_top")})})}throwTokenizationError(e){if(!function(e){return"object"==typeof e&&null!==e&&"field"in e&&"type"in e&&"message"in e}(e))throw new ti(Xn.MissingPaymentToken);throw new Error(e.message)}getHostedFieldsOptions(){return{style:{error:{color:"#d14343"}},classes:{error:"form-input--error"}}}isTrustedVaultingInstrument(e){const t=this.paymentIntegrationService.getState().getInstruments(),n=null==t?void 0:t.find(t=>uc(t)&&t.bigpayToken===e);return!(uc(n)&&!n.trustedShippingAddress)}}class Sm{constructor(e,t=window){this.scriptLoader=e,this.tdOnlineMartWindow=t}load(){return e=this,t=void 0,i=function*(){if(this.tdOnlineMartWindow.customcheckout||(yield this.scriptLoader.loadScript("https://libs.na.bambora.com/customcheckout/1/customcheckout.js")),!this.tdOnlineMartWindow.customcheckout)throw new mi;return this.tdOnlineMartWindow.customcheckout()},new((n=void 0)||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())});var e,t,n,i}}const _m=vi(e=>new fm(e,new Sm(a()),Ee()),[{id:"tdonlinemart"}]);var wm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const Im="Payment cannot continue";let Cm;class bm extends tu{initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return wm(this,void 0,void 0,function*(){if(this._initializeOptions=e&&e.worldpay,!this._initializeOptions)throw new ri(ei.PaymentNotInitialized);return t.initialize.call(this,e)})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return wm(this,void 0,void 0,function*(){const{payment:i}=e;if(Cm=this._submitAdditionalAction(),!i)throw new co(["payment"]);try{return yield n.execute.call(this,e,t)}catch(e){return this._processAdditionalAction(e,i)}})}_processAdditionalAction(e,t){return wm(this,void 0,void 0,function*(){return pa(e)&&ve(e.body.errors,{code:"additional_action_required"})?new Promise((n,i)=>{const r=e=>wm(this,void 0,void 0,function*(){if(-1===e.origin.indexOf("cardinalcommerce.com"))return;if("string"!=typeof e.data||!this._isValidJsonWithSessionId(e.data))return i(new Error(Im));window.removeEventListener("message",r),o.remove();const a=JSON.parse(e.data),s=de({},t,{paymentData:{threeDSecure:{token:a.SessionId}}});try{n(yield Cm(s))}catch(e){if(!pa(e)||!ve(e.body.errors,{code:"three_d_secure_required"}))return i(e);if(!this._initializeOptions)return i(new ri(ei.PaymentNotInitialized));const{onLoad:t}=this._initializeOptions,n=this._createIframe(e.body.three_ds_result);try{t(n,()=>i(new Error("Payment was cancelled")))}catch(e){i(new Error(Im))}}});let o;window.addEventListener("message",r);try{o=this._createHiddenIframe(e.body)}catch(e){throw window.removeEventListener("message",r),new Error(Im)}}):Promise.reject(e)})}_createHiddenIframe(e){const t=document.createElement("iframe");if(document.body.appendChild(t),!t.contentWindow)throw new Error;t.id="worldpay_hosted_hidden_payment_page",t.height="0px",t.width="0px";const n=document.createElement("form"),i="collectionForm";n.id=i,n.name="devicedata",n.method="post";const r=e.additional_action_required.data.redirect_url;n.action=r;const o=document.createElement("input");o.name="Bin",o.type="hidden",o.value=e.provider_data.source_id,n.appendChild(o);const a=document.createElement("input");a.name="JWT",a.type="hidden",a.value=e.provider_data.data,n.appendChild(a);const s=document.createElement("button");s.type="submit",s.id="btnsubmit",n.appendChild(s),navigator.userAgent.match("Firefox")?t.srcdoc=n.outerHTML:t.contentWindow.document.body.appendChild(n);const d=document.createElement("script");return d.innerHTML=`\n document.getElementById('${i}').submit();\n `,t.contentWindow.document.body.appendChild(d),t}_createIframe(e){const t=document.createElement("form");t.id="challengeForm",t.method="POST",t.action=e.acs_url;const n=document.createElement("input");n.name="JWT",n.type="hidden",n.value=e.payer_auth_request,t.appendChild(n);const i=document.createElement("input");i.name="MD",i.type="hidden",i.value=`merchantSessionId=${e.merchant_data}`,t.appendChild(i);const r=document.createElement("script");r.type="text/javascript",r.innerHTML="window.onload = function() { document.getElementById('challengeForm').submit(); }";const o=document.createElement("iframe");return o.name="worldpay_hosted_payment_page",o.height="400",o.width="100%",o.srcdoc=`${t.outerHTML} ${r.outerHTML}`,o}_submitAdditionalAction(){if(this._shouldRenderHostedForm){if(!this._hostedForm)throw new ri(ei.PaymentNotInitialized);const e=this._hostedForm;return t=>wm(this,void 0,void 0,function*(){yield e.submit(t)})}return e=>wm(this,void 0,void 0,function*(){yield this._paymentIntegrationService.submitPayment(e)})}_isValidJsonWithSessionId(e){try{const t=JSON.parse(e);return!(!t.SessionId||!t.Status)}catch(e){return!1}}}const Pm=vi(e=>new bm(e),[{gateway:"worldpayaccess",id:"credit_card"},{id:"worldpayaccess"}]);class Om{constructor(e){this._paymentIntegrationService=e}execute({payment:e}){return t=this,n=void 0,r=function*(){if(!e)throw new co(["payment"]);yield this._paymentIntegrationService.submitOrder();try{yield this._paymentIntegrationService.submitPayment(this._buildOpenBankingSubmitPayment(e))}catch(e){if(this._isWorldpayAccessRedirectResponse(e)){const t=e.body.additional_action_required.data.redirect_url;return new Promise(()=>window.location.replace(t))}return Promise.reject(e)}},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}initialize(){return Promise.resolve()}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_buildOpenBankingSubmitPayment(e){const{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n}=jd(e.paymentData)?e.paymentData:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1};return Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{open_banking:{},vault_payment_instrument:t||!1,set_as_default_stored_instrument:n||!1}}})}_isWorldpayAccessRedirectResponse(e){var t,n;if("object"!=typeof e||null===e)return!1;const i=e;if(!i.body)return!1;const r=i.body;return"additional_action_required"===r.status&&!!(null===(n=null===(t=r.additional_action_required)||void 0===t?void 0:t.data)||void 0===n?void 0:n.redirect_url)}}const Em=vi(e=>new Om(e),[{id:"open_banking",gateway:"worldpayaccess"}]);class Am{constructor(e){this._requestSender=e}saveExternalId(e,t){return n=this,i=void 0,o=function*(){const n=`/api/storefront/payment/${e}/save-external-id`,i={headers:Object.assign({Accept:mr.JsonV1,"X-API-INTERNAL":hr},yr),body:{externalId:t,provider:e}};yield this._requestSender.post(n,i)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}class Tm{constructor(e,t){this.paymentIntegrationService=e,this.storefrontPaymentRequestSender=t}initialize(){return Promise.resolve()}execute(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rwindow.location.replace(d));throw e}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_prepareForReferredRegistration(e,t){return this.storefrontPaymentRequestSender.saveExternalId(e,t)}}const km=vi(e=>{const{getHost:t}=e.getState(),i=n({host:t()}),r=new Am(i);return new Tm(e,r)},[{id:"zip"},{id:"quadpay"}]);var Dm,Mm;!function(e){e.LoadCountriesRequested="LOAD_COUNTRIES_REQUESTED",e.LoadCountriesSucceeded="LOAD_COUNTRIES_SUCCEEDED",e.LoadCountriesFailed="LOAD_COUNTRIES_FAILED"}(Dm||(Dm={}));class zm{constructor(e){this._countryRequestSender=e}loadCountries(e){return m.create(t=>{t.next(l(Dm.LoadCountriesRequested)),this._countryRequestSender.loadCountries(e).then(e=>{t.next(l(Dm.LoadCountriesSucceeded,e.body.data)),t.complete()}).catch(e=>{t.error(h(Dm.LoadCountriesFailed,e))})})}}class Nm{constructor(e,t){this._requestSender=e,this._config=t}loadCountries({timeout:e}={}){const t=Object.assign({"Accept-Language":this._config.locale},Xe);return this._requestSender.get("/internalapi/v1/store/countries",{headers:t,timeout:e})}}class xm extends it{constructor(e){super(e||"Your checkout could not be processed because some details have changed. Please review your order and try again."),this.name="CartConsistencyError",this.type="cart_consistency"}}class Rm extends it{constructor(e,t){super(t||"At least one item changed stock position. Please review your cart and try again."),this.name="CartStockPositionsChangedError",this.type="cart_stock_positions_changed",this.changedItemIds=e}}class Fm extends it{constructor(e){super(e||"The tax provider is unavailable."),this.name="OrderTaxProviderUnavailableError",this.type="tax_provider_unavailable"}}class Lm extends it{constructor(e){super(e),this.name="MissingShippingMethodError",this.type="missing_shipping_method"}}class Bm extends it{constructor(e){super(e),this.name="InvalidShippingAddressError",this.type="invalid_shipping_address"}}class jm{constructor(e){this._requestSender=e}loadOrder(e,{timeout:t}={}){const n=`/api/storefront/orders/${e}`,i=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.get(n,{params:{include:Ft(["payments","lineItems.physicalItems.socialMedia","lineItems.physicalItems.options","lineItems.physicalItems.categories","lineItems.digitalItems.socialMedia","lineItems.digitalItems.options","lineItems.digitalItems.categories"])},headers:i,timeout:t})}submitOrder(e,{headers:t,timeout:n}={}){return this._requestSender.post("/internalapi/v1/checkout/order",{body:e,headers:ue(Object.assign({"X-Checkout-Variant":t&&t.checkoutVariant},Xe),J),timeout:n}).catch(e=>{var t,n;if("tax_provider_unavailable"===e.body.type)throw new Fm;if("cart_has_changed"===e.body.type)throw new xm;if("cart_stock_positions_changed"===e.body.type){const i=null!==(n=null===(t=e.body.errors)||void 0===t?void 0:t.changedItemIds)&&void 0!==n?n:[];throw new Rm(i)}if("missing_shipping_method"===e.body.type)throw new Lm(e.body.detail);if("invalid_shipping_address"===e.body.type)throw new Bm(e.body.detail);if("empty_cart"===e.body.type)throw new dt;throw e})}finalizeOrder(e,{timeout:t}={}){const n=`/internalapi/v1/checkout/order/${e}`;return this._requestSender.post(n,{timeout:t,headers:Xe})}}class Um extends it{constructor(){super("You haven't complete our spam check. Please try again."),this.name="SpamProtectionNotCompletedError",this.type="spam_protection_not_completed"}}!function(e){e.LoadOrderRequested="LOAD_ORDER_REQUESTED",e.LoadOrderSucceeded="LOAD_ORDER_SUCCEEDED",e.LoadOrderFailed="LOAD_ORDER_FAILED",e.LoadOrderPaymentsRequested="LOAD_ORDER_PAYMENTS_REQUESTED",e.LoadOrderPaymentsSucceeded="LOAD_ORDER_PAYMENTS_SUCCEEDED",e.LoadOrderPaymentsFailed="LOAD_ORDER_PAYMENTS_FAILED",e.SubmitOrderRequested="SUBMIT_ORDER_REQUESTED",e.SubmitOrderSucceeded="SUBMIT_ORDER_SUCCEEDED",e.SubmitOrderFailed="SUBMIT_ORDER_FAILED",e.FinalizeOrderRequested="FINALIZE_ORDER_REQUESTED",e.FinalizeOrderSucceeded="FINALIZE_ORDER_SUCCEEDED",e.FinalizeOrderFailed="FINALIZE_ORDER_FAILED"}(Mm||(Mm={}));var qm;class Vm{constructor(e,t){this._orderRequestSender=e,this._checkoutValidator=t}loadOrder(e,t){return new m(n=>{n.next(l(Mm.LoadOrderRequested)),this._orderRequestSender.loadOrder(e,t).then(e=>{n.next(l(Mm.LoadOrderSucceeded,e.body)),n.complete()}).catch(e=>{n.error(h(Mm.LoadOrderFailed,e))})})}loadOrderPayments(e,t){return new m(n=>{n.next(l(Mm.LoadOrderPaymentsRequested)),this._orderRequestSender.loadOrder(e,t).then(e=>{n.next(l(Mm.LoadOrderPaymentsSucceeded,e.body)),n.complete()}).catch(e=>{n.error(h(Mm.LoadOrderPaymentsFailed,e))})})}loadCurrentOrder(e){return t=>v(()=>{const n=this._getCurrentOrderId(t.getState());if(!n)throw new rt(et.MissingOrderId);return this.loadOrder(n,e)})}submitOrder(e,t){return n=>g(C(l(Mm.SubmitOrderRequested)),v(()=>{const i=n.getState(),r=i.config.getExternalSource(),o=i.config.getVariantIdentificationToken(),a=i.checkout.getCheckout();if(!a)throw new rt(et.MissingCheckout);if(a.shouldExecuteSpamCheck)throw new Um;return S(this._checkoutValidator.validate(a,t).then(()=>this._orderRequestSender.submitOrder(this._mapToOrderRequestBody(null!=e?e:{},a.id,a.customerMessage,r),Object.assign(Object.assign({},t),{headers:{checkoutVariant:o}})))).pipe(M(e=>g(this.loadOrder(e.body.data.order.orderId,t),C(l(Mm.SubmitOrderSucceeded,e.body.data,Object.assign(Object.assign({},e.body.meta),{token:e.headers.token}))))))}).pipe(P(e=>Je(Mm.SubmitOrderFailed,e))))}finalizeOrder(e,t){return g(C(l(Mm.FinalizeOrderRequested)),S(this._orderRequestSender.finalizeOrder(e,t)).pipe(M(n=>g(this.loadOrder(e,t),C(l(Mm.FinalizeOrderSucceeded,n.body.data)))))).pipe(P(e=>Je(Mm.FinalizeOrderFailed,e)))}_getCurrentOrderId(e){const t=e.order.getOrder(),n=e.checkout.getCheckout();return t&&t.orderId||n&&n.orderId}_mapToOrderRequestBody(e,t,n,i){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const n=e.config.getStoreConfig();n&&t.setHost(n.paymentSettings.bigpayBaseUrl)},e=>e.config.getStoreConfig()),t}!function(e){e.LoadPaymentMethodRequested="LOAD_PAYMENT_METHOD_REQUESTED",e.LoadPaymentMethodSucceeded="LOAD_PAYMENT_METHOD_SUCCEEDED",e.LoadPaymentMethodFailed="LOAD_PAYMENT_METHOD_FAILED",e.LoadPaymentMethodsRequested="LOAD_PAYMENT_METHODS_REQUESTED",e.LoadPaymentMethodsSucceeded="LOAD_PAYMENT_METHODS_SUCCEEDED",e.LoadPaymentMethodsFailed="LOAD_PAYMENT_METHODS_FAILED"}(qm||(qm={}));const Hm=e=>!!e;class Wm{constructor(e){this._requestSender=e}loadPaymentMethodsById(e,t){return n=>new m(i=>{var r;const o=null===(r=n.getState().cart.getCart())||void 0===r?void 0:r.id,a=o?Object.assign(Object.assign({},null==t?void 0:t.params),{cartId:o}):Object.assign({},null==t?void 0:t.params);i.next(l(qm.LoadPaymentMethodsRequested)),Promise.all(e.map(e=>{return n=this,i=void 0,o=function*(){try{return(yield this._requestSender.loadPaymentMethod(e,Object.assign(Object.assign({},t),{params:a}))).body}catch(e){return}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).then(e=>{const t=e.filter(Hm);i.next(l(qm.LoadPaymentMethodsSucceeded,t)),i.complete()}).catch(e=>{i.next(l(qm.LoadPaymentMethodsFailed,e)),i.complete()})})}loadPaymentMethods(e){return t=>m.create(n=>{const i=t.getState().cart.getCartOrThrow();n.next(l(qm.LoadPaymentMethodsRequested)),this._requestSender.loadPaymentMethods(Object.assign(Object.assign({},e),{params:Object.assign(Object.assign({},null==e?void 0:e.params),{cartId:i.id})})).then(e=>{const t={deviceSessionId:e.headers["x-device-session-id"],sessionHash:e.headers["x-session-hash"]},i=e.body;n.next(l(qm.LoadPaymentMethodsSucceeded,i,t)),n.complete()}).catch(e=>{n.error(h(qm.LoadPaymentMethodsFailed,e))})})}loadPaymentMethod(e,t){return n=>m.create(i=>{var r;const o=null===(r=n.getState().cart.getCart())||void 0===r?void 0:r.id,a=o?Object.assign(Object.assign({},null==t?void 0:t.params),{cartId:o}):Object.assign({},null==t?void 0:t.params);i.next(l(qm.LoadPaymentMethodRequested,void 0,{methodId:e})),this._requestSender.loadPaymentMethod(e,Object.assign(Object.assign({},t),{params:a})).then(t=>{i.next(l(qm.LoadPaymentMethodSucceeded,t.body,{methodId:e})),i.complete()}).catch(t=>{i.error(h(qm.LoadPaymentMethodFailed,t,{methodId:e}))})})}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([It],Wm.prototype,"loadPaymentMethod",null);class $m{constructor(e){this._requestSender=e}loadPaymentMethods({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/payments",{timeout:e,headers:Object.assign({Accept:ct.JsonV1,"X-API-INTERNAL":At},Xe),params:t})}loadPaymentMethod(e,{timeout:t,params:n}={}){const i=`/api/storefront/payments/${e}`;return this._requestSender.get(i,{timeout:t,headers:Object.assign({Accept:ct.JsonV1,"X-API-INTERNAL":At},Xe),params:n})}}class Ym extends it{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}var Km,Jm;!function(e){e.ExecuteFailed="PAYMENT_STRATEGY_EXECUTE_FAILED",e.ExecuteRequested="PAYMENT_STRATEGY_EXECUTE_REQUESTED",e.ExecuteSucceeded="PAYMENT_STRATEGY_EXECUTE_SUCCEEDED",e.FinalizeFailed="PAYMENT_STRATEGY_FINALIZE_FAILED",e.FinalizeRequested="PAYMENT_STRATEGY_FINALIZE_REQUESTED",e.FinalizeSucceeded="PAYMENT_STRATEGY_FINALIZE_SUCCEEDED",e.InitializeFailed="PAYMENT_STRATEGY_INITIALIZE_FAILED",e.InitializeRequested="PAYMENT_STRATEGY_INITIALIZE_REQUESTED",e.InitializeSucceeded="PAYMENT_STRATEGY_INITIALIZE_SUCCEEDED",e.DeinitializeFailed="PAYMENT_STRATEGY_DEINITIALIZE_FAILED",e.DeinitializeRequested="PAYMENT_STRATEGY_DEINITIALIZE_REQUESTED",e.DeinitializeSucceeded="PAYMENT_STRATEGY_DEINITIALIZE_SUCCEEDED",e.WidgetInteractionStarted="PAYMENT_STRATEGY_WIDGET_INTERACTION_STARTED",e.WidgetInteractionFinished="PAYMENT_STRATEGY_WIDGET_INTERACTION_FINISHED",e.WidgetInteractionFailed="PAYMENT_STRATEGY_WIDGET_INTERACTION_FAILED"}(Km||(Km={})),function(e){e.ADYENV2="adyenv2",e.ADYENV2_GOOGLEPAY="googlepayadyenv2",e.ADYENV3="adyenv3",e.ADYENV3_GOOGLEPAY="googlepayadyenv3",e.AFFIRM="affirm",e.AFTERPAY="afterpay",e.AUTHORIZENET_GOOGLE_PAY="googlepayauthorizenet",e.AMAZONPAY="amazonpay",e.APPLEPAY="applepay",e.BLUESNAPV2="bluesnapv2",e.BOLT="bolt",e.CBA_MPGS="cba_mpgs",e.CHECKOUTCOM="checkoutcom",e.CHECKOUTCOM_APM="checkoutcomapm",e.CHECKOUTCOM_FAWRY="checkoutcomfawry",e.CHECKOUTCOM_SEPA="checkoutcomsepa",e.CHECKOUTCOM_IDEAL="checkoutcomideal",e.CREDIT_CARD="creditcard",e.CHECKOUTCOM_GOOGLE_PAY="googlepaycheckoutcom",e.CLEARPAY="clearpay",e.CONVERGE="converge",e.CYBERSOURCE="cybersource",e.CYBERSOURCEV2="cybersourcev2",e.BNZ="bnz",e.BNZ_GOOGLEPAY="googlepaybnz",e.CYBERSOURCEV2_GOOGLE_PAY="googlepaycybersourcev2",e.HUMM="humm",e.KLARNA="klarna",e.KLARNAV2="klarnav2",e.LEGACY="legacy",e.MOLLIE="mollie",e.MONERIS="moneris",e.NO_PAYMENT_DATA_REQUIRED="nopaymentdatarequired",e.OFFLINE="offline",e.OFFSITE="offsite",e.ORBITAL_GOOGLE_PAY="googlepayorbital",e.PAYPAL_EXPRESS="paypalexpress",e.PAYPAL_EXPRESS_CREDIT="paypalexpresscredit",e.PAYPAL_COMMERCE="paypalcommerce",e.PAYPAL_COMMERCE_CREDIT="paypalcommercecredit",e.PAYPAL_COMMERCE_CREDIT_CARD="paypalcommercecreditcards",e.PAYPAL_COMMERCE_ALTERNATIVE_METHODS="paypalcommercealternativemethods",e.PAYPAL_COMMERCE_VENMO="paypalcommercevenmo",e.PPSDK="PAYMENT_TYPE_SDK",e.QUADPAY="quadpay",e.SAGE_PAY="sagepay",e.SQUARE="squarev2",e.STRIPEV3="stripev3",e.STRIPE_UPE="stripeupe",e.STRIPE_UPE_GOOGLE_PAY="googlepaystripeupe",e.BRAINTREE="braintree",e.BRAINTREE_PAYPAL="braintreepaypal",e.BRAINTREE_VENMO="braintreevenmo",e.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",e.BRAINTREE_VISA_CHECKOUT="braintreevisacheckout",e.BRAINTREE_GOOGLE_PAY="googlepaybraintree",e.WORLDPAYACCESS="worldpayaccess",e.WORLDPAYACCESS_GOOGLE_PAY="googlepayworldpayaccess",e.STRIPE_GOOGLE_PAY="googlepaystripe",e.SEZZLE="sezzle",e.ZIP="zip"}(Jm||(Jm={}));const Zm=Jm;class Qm{widgetInteraction(e,t){const n={methodId:t&&t.methodId};return g(C(l(Km.WidgetInteractionStarted,void 0,n)),v(()=>e().then(()=>l(Km.WidgetInteractionFinished,void 0,n)))).pipe(P(e=>Je(Km.WidgetInteractionFailed,e,n)))}}class Xm{constructor(e,t,n,i,r){this._strategyRegistry=e,this._strategyRegistryV2=t,this._orderActionCreator=n,this._spamProtectionActionCreator=i,this._paymentIntegrationService=r,this._paymentStrategyWidgetActionCreator=new Qm}execute(e,t){const{payment:n={},useStoreCredit:i}=e,r={methodId:n.methodId};return o=>{const{checkout:a}=o.getState(),{shouldExecuteSpamCheck:s}=a.getCheckoutOrThrow();return g(s?this._spamProtectionActionCreator.verifyCheckoutSpamProtection()(o):f(),C(l(Km.ExecuteRequested,void 0,r)),v(()=>{const a=o.getState();let s;if(a.payment.isPaymentDataRequired(i)){const e=a.paymentMethods.getPaymentMethod(n.methodId,n.gatewayId);if(!e)throw new rt(et.MissingPaymentMethod);s=this._getStrategy(e)}else s=this._strategyRegistryV2.get({id:Zm.NO_PAYMENT_DATA_REQUIRED});return s.execute(e,Object.assign(Object.assign({},t),{methodId:n.methodId,gatewayId:n.gatewayId})).then(()=>l(Km.ExecuteSucceeded,void 0,r))})).pipe(P(e=>Je(Km.ExecuteFailed,e,r)))}}finalize(e){const{integrations:t}=null!=e?e:{};return n=>g(C(l(Km.FinalizeRequested)),this._loadOrderPaymentsIfNeeded(n,e),v(()=>{return i=this,r=void 0,a=function*(){const i=n.getState(),{providerId:r="",gatewayId:o=""}=i.payment.getPaymentId()||{},a=i.paymentMethods.getPaymentMethod(r,o);if(!a)throw new Ym;let s;Zt(this._strategyRegistryV2,null!=t?t:[],this._paymentIntegrationService);try{s=this._getStrategy(a)}catch(e){throw new Ym}return yield s.finalize(Object.assign(Object.assign({},e),{methodId:a.id,gatewayId:a.gateway})),l(Km.FinalizeSucceeded,void 0,{methodId:a.id})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a})).pipe(P(e=>{const t=n.getState().payment.getPaymentId();return Je(Km.FinalizeFailed,e,{methodId:t&&t.providerId})}))}initialize(e){const{methodId:t,gatewayId:n,integrations:i}=e;return r=>v(()=>{const o=r.getState(),a=o.paymentMethods.getPaymentMethod(t,n);if(!a)throw new rt(et.MissingPaymentMethod);if(t&&o.paymentStrategies.isInitialized({methodId:t,gatewayId:n}))return f();Zt(this._strategyRegistryV2,null!=i?i:[],this._paymentIntegrationService);const s=this._getStrategy(a).initialize(Object.assign(Object.assign({},e),{methodId:t,gatewayId:n}));return g(C(l(Km.InitializeRequested,void 0,{methodId:t,gatewayId:n})),s.then(()=>l(Km.InitializeSucceeded,void 0,{methodId:t,gatewayId:n})))}).pipe(P(e=>Je(Km.InitializeFailed,e,{methodId:t,gatewayId:n})))}deinitialize(e){const{methodId:t,gatewayId:n}=e;return i=>v(()=>{const r=i.getState(),o=r.paymentMethods.getPaymentMethod(t,n);if(!o)throw new rt(et.MissingPaymentMethod);if(t&&!r.paymentStrategies.isInitialized({methodId:t,gatewayId:n}))return f();const a=this._getStrategy(o).deinitialize(Object.assign(Object.assign({},e),{methodId:t,gatewayId:n}));return g(C(l(Km.DeinitializeRequested,void 0,{methodId:t,gatewayId:n})),a.then(()=>l(Km.DeinitializeSucceeded,void 0,{methodId:t,gatewayId:n})))}).pipe(P(e=>Je(Km.DeinitializeFailed,e,{methodId:t,gatewayId:n})))}widgetInteraction(e,t){return this._paymentStrategyWidgetActionCreator.widgetInteraction(e,t)}_getStrategy(e){let t;try{t=this._strategyRegistry.getByMethod(e)}catch(n){try{t=this._strategyRegistryV2.get({id:e.id,gateway:e.gateway,type:e.type})}catch(t){throw wt().error(`[PaymentStrategyActionCreator] Unable to resolve V2 strategy for id: ${e.id}, gateway: ${e.gateway}, type: ${e.type}`),t}}return t}_loadOrderPaymentsIfNeeded(e,t){const n=e.getState().checkout.getCheckout();return n&&n.orderId?this._orderActionCreator.loadOrderPayments(n.orderId,t):f()}}class ey{isEqual(e,t){return Y(this._normalize(e),this._normalize(t))}_normalize(e){return{cartAmount:e.cartAmount,currency:e.currency,id:e.id,lineItems:{digitalItems:e.lineItems.digitalItems.slice().sort((e,t)=>`${e.productId}${e.variantId}`.localeCompare(`${t.productId}${t.variantId}`)).map(e=>({extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId})),giftCertificates:e.lineItems.giftCertificates.slice().sort((e,t)=>`${e.id}`.localeCompare(`${t.id}`)).map(e=>({amount:e.amount,recipient:e.recipient})),physicalItems:e.lineItems.physicalItems.slice().sort((e,t)=>`${e.productId}${e.variantId}`.localeCompare(`${t.productId}${t.variantId}`)).map(e=>({extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId,giftWrapping:e.giftWrapping}))}}}}class ty extends it{constructor(e,t){super("An update to your shopping cart has been detected and your available shipping costs have been updated."),this.name="CartChangedError",this.type="cart_changed",this.data={previous:e,updated:t}}}class ny{constructor(e){this._checkoutRequestSender=e}validate(e,t){if(!e)throw new rt(et.MissingCheckout);return this._checkoutRequestSender.loadCheckout(e.id,t).then(t=>{const n=new ey;if(!(e.outstandingBalance===t.body.outstandingBalance&&this._compareCoupons(e.coupons,t.body.coupons)&&this._compareGiftCertificates(e.giftCertificates,t.body.giftCertificates)&&n.isEqual(e.cart,t.body.cart)))throw new ty(this._getComparableCheckout(e),this._getComparableCheckout(t.body))})}_compareCoupons(e,t){return Y(oe(e,"code"),oe(t,"code"))}_compareGiftCertificates(e,t){return Y(oe(e,"code"),oe(t,"code"))}_getComparableCheckout(e){const{cart:t,coupons:n,giftCertificates:i,outstandingBalance:r}=e;return{cart:{cartAmount:t.cartAmount,currency:t.currency,lineItems:t.lineItems},coupons:n,giftCertificates:i,outstandingBalance:r}}}class iy{constructor(e){this._namespace=e}getItem(e){const t=Te.getItem(this.withNamespace(e));if(null===t)return null;try{return JSON.parse(t)}catch(t){return this.removeItem(this.withNamespace(e)),null}}getItemOnce(e){const t=this.getItem(e);return this.removeItem(e),t}setItem(e,t){return Te.setItem(this.withNamespace(e),JSON.stringify(t))}removeItem(e){return Te.removeItem(this.withNamespace(e))}withNamespace(e){return`${this._namespace}.${e}`}}class ry extends it{constructor(){super("Please complete our human verification challenge and try again."),this.name="CardingProtectionChallengeNotCompletedError",this.type="carding_protection_challenge_not_completed"}}class oy extends it{constructor(){super("We were not able to verify that you are not a robot. Please try again."),this.name="CardingProtectionFailedError",this.type="carding_protection_failed"}}var ay,sy,dy=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class cy{constructor(e){this._googleRecaptcha=e}handle(e,t){return dy(this,void 0,void 0,function*(){return"string"==typeof e?this.handleWithRecaptchaSitekey(e,t):this.handleWithPaymentHumanVerificationRequestError(e)})}handleWithPaymentHumanVerificationRequestError(e){return dy(this,void 0,void 0,function*(){if(!this._isPaymentHumanVerificationRequest(e))throw e;return yield this._initialize(e.body.additional_action_required.data.key),this._performRecaptcha()})}handleWithRecaptchaSitekey(e,t){return dy(this,void 0,void 0,function*(){if("recaptcha_v2"!==e)throw Error("Human verification method is not supported.");if(!t)throw Error("Recaptcha site key is missing.");return yield this._initialize(t),this._performRecaptcha()})}_performRecaptcha(){return this._googleRecaptcha.execute().pipe(z(1)).pipe(M(({error:e,token:t})=>dy(this,void 0,void 0,function*(){if(e instanceof sn)throw new ry;if(e||!t)throw new oy;return{type:"recaptcha_v2_verification",data:{human_verification_token:t}}}))).toPromise()}_initialize(e){const t="cardingProtectionContainer";let n=document.getElementById(t);return n&&n.parentNode&&n.parentNode.removeChild(n),n=document.createElement("div"),n.setAttribute("id",t),document.body.appendChild(n),this._googleRecaptcha.load(t,e)}_isPaymentHumanVerificationRequest(e){const{additional_action_required:t,status:n}=e.body||{};return"additional_action_required"===n&&t&&"recaptcha_v2_verification"===t.type}}function ly(e,t){const{body:n}=e,{errors:i=[]}=n;return new Ot(e,{message:uy(i)||t,errors:i})}function uy(e){if(Array.isArray(e))return e.reduce((e,t)=>t&&t.message?[...e,t.message]:e,[]).join(" ")}class hy extends it{constructor(e){super(e||"Unable to proceed due to invalid configuration provided for the hosted payment form."),this.name="InvalidHostedFormConfigError",this.type="invalid_hosted_form_config"}}class py extends it{constructor(e){super(e||"Unable to proceed due to an unknown error with the hosted payment form."),this.name="InvalidHostedFormError",this.type="invalid_hosted_form"}}class my extends it{constructor(e){super(["Unable to proceed due to invalid user input values",...U(Ce(e),e=>oe(e,({message:e})=>e))].join(". ")),this.errors=e,this.name="InvalidHostedFormValueError",this.type="invalid_hosted_form_value"}}!function(e){e.AttachRequested="HOSTED_FIELD:ATTACH_REQUESTED",e.SubmitRequested="HOSTED_FIELD:SUBMITTED_REQUESTED",e.ValidateRequested="HOSTED_FIELD:VALIDATE_REQUESTED",e.StoredCardRequested="HOSTED_FIELD:STORED_CARD_REQUESTED"}(ay||(ay={})),function(e){e.AttachSucceeded="HOSTED_INPUT:ATTACH_SUCCEEDED",e.AttachFailed="HOSTED_INPUT:ATTACH_FAILED",e.BinChanged="HOSTED_INPUT:BIN_CHANGED",e.Blurred="HOSTED_INPUT:BLURRED",e.Changed="HOSTED_INPUT:CHANGED",e.CardTypeChanged="HOSTED_INPUT:CARD_TYPE_CHANGED",e.Entered="HOSTED_INPUT:ENTERED",e.Focused="HOSTED_INPUT:FOCUSED",e.SubmitSucceeded="HOSTED_INPUT:SUBMIT_SUCCEEDED",e.SubmitFailed="HOSTED_INPUT:SUBMIT_FAILED",e.Validated="HOSTED_INPUT:VALIDATED",e.StoredCardSucceeded="HOSTED_INPUT:STORED_CARD_SUCCEEDED",e.StoredCardFailed="HOSTED_INPUT:STORED_CARD_FAILED"}(sy||(sy={}));var yy=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class gy{constructor(e,t,n,i,r,o,a,s,d,c){this._type=e,this._containerId=t,this._placeholder=n,this._accessibilityLabel=i,this._styles=r,this._eventPoster=o,this._eventListener=a,this._detachmentObserver=s,this._checkoutId=d,this._cardInstrument=c,this._iframe=document.createElement("iframe");const l=this._checkoutId?`/checkout/payment/hosted-field?version=1.909.5&checkoutId=${this._checkoutId}`:"/checkout/payment/hosted-field?version=1.909.5";this._iframe.src=l,this._iframe.style.border="none",this._iframe.style.height="100%",this._iframe.style.overflow="hidden",this._iframe.style.width="100%"}getType(){return this._type}attach(){return yy(this,void 0,void 0,function*(){const e=document.getElementById(this._containerId);if(!e)throw new hy("Unable to proceed because the provided container ID is not valid.");e.appendChild(this._iframe),this._eventListener.listen();const t=_(this._iframe,"load").pipe(M(({target:e})=>yy(this,void 0,void 0,function*(){const t=e&&e.contentWindow;if(!t)throw new Error("The content window of the iframe cannot be accessed.");this._eventPoster.setTarget(t),yield this._eventPoster.post({type:ay.AttachRequested,payload:{accessibilityLabel:this._accessibilityLabel,cardInstrument:this._cardInstrument,fontUrls:this._getFontUrls(),placeholder:this._placeholder,styles:this._styles,origin:document.location.origin,type:this._type}},{successType:sy.AttachSucceeded,errorType:sy.AttachFailed})})),z(1)).toPromise();yield this._detachmentObserver.ensurePresence([this._iframe],t)})}detach(){this._iframe.parentElement&&(this._iframe.parentElement.removeChild(this._iframe),this._eventListener.stopListen())}submitForm(e,t){return yy(this,void 0,void 0,function*(){try{const n=this._eventPoster.post({type:ay.SubmitRequested,payload:{fields:e,data:t}},{successType:sy.SubmitSucceeded,errorType:sy.SubmitFailed});return yield this._detachmentObserver.ensurePresence([this._iframe],n)}catch(e){if(this._isSubmitErrorEvent(e)){if("hosted_form_error"===e.payload.error.code)throw new py(e.payload.error.message);if(e.payload.response)throw ly(e.payload.response);throw new Error(e.payload.error.message)}throw e}})}submitStoredCardForm(e,t){return yy(this,void 0,void 0,function*(){const n=this._eventPoster.post({type:ay.StoredCardRequested,payload:{fields:e,data:t}},{successType:sy.StoredCardSucceeded,errorType:sy.StoredCardFailed});return this._detachmentObserver.ensurePresence([this._iframe],n)})}validateForm(){return yy(this,void 0,void 0,function*(){const e=this._eventPoster.post({type:ay.ValidateRequested},{successType:sy.Validated}),{payload:t}=yield this._detachmentObserver.ensurePresence([this._iframe],e);if(!t.isValid)throw new my(t.errors)})}_getFontUrls(){const e="fonts.googleapis.com",t=document.querySelectorAll(`link[href*='${e}'][rel='stylesheet']`);return Array.prototype.slice.call(t).filter(t=>In(t.href).hostname===e).filter(e=>Ce(this._styles).map(e=>e&&e.fontFamily).filter(e=>"string"==typeof e).some(t=>t.split(/,\s/).some(t=>-1!==e.href.indexOf(t.replace(" ","+"))))).map(e=>e.href)}_isSubmitErrorEvent(e){return e.type===sy.SubmitFailed}}var vy,fy=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Sy{constructor(e,t,n,i,r){this._fields=e,this._eventListener=t,this._payloadTransformer=n,this._eventCallbacks=i,this._paymentHumanVerificationHandler=r,this._handleEnter=({payload:e})=>fy(this,void 0,void 0,function*(){try{yield this.validate()}catch(e){if(e instanceof Error&&"InvalidHostedFormValueError"!==e.name)throw e}const{onEnter:t=ce}=this._eventCallbacks;t(e)});const{onBlur:o=ce,onCardTypeChange:a=ce,onFocus:s=ce,onValidate:d=ce}=this._eventCallbacks;this._eventListener.addListener(sy.Blurred,({payload:e})=>o(e)),this._eventListener.addListener(sy.CardTypeChanged,({payload:e})=>a(e)),this._eventListener.addListener(sy.Focused,({payload:e})=>s(e)),this._eventListener.addListener(sy.Validated,({payload:e})=>d(e)),this._eventListener.addListener(sy.Entered,this._handleEnter),this._eventListener.addListener(sy.CardTypeChanged,({payload:e})=>this._cardType=e.cardType),this._eventListener.addListener(sy.BinChanged,({payload:e})=>this._bin=e.bin)}getBin(){return this._bin}getCardType(){return this._cardType}attach(){return fy(this,void 0,void 0,function*(){this._eventListener.listen();const e=this._getFirstField(),t=be(this._fields,e);yield e.attach(),yield Promise.all(t.map(e=>e.attach()))})}detach(){this._eventListener.stopListen(),this._fields.forEach(e=>{e.detach()})}submit(e,t){return fy(this,void 0,void 0,function*(){try{return yield this._getFirstField().submitForm(this._fields.map(e=>e.getType()),this._payloadTransformer.transform(e,t))}catch(t){const n=yield this._paymentHumanVerificationHandler.handle(t);return yield this._getFirstField().submitForm(this._fields.map(e=>e.getType()),this._payloadTransformer.transform(e,n))}})}submitStoredCard(e){return fy(this,void 0,void 0,function*(){return this._getFirstField().submitStoredCardForm(e.fields,e.data)})}validate(){return fy(this,void 0,void 0,function*(){return this._getFirstField().validateForm()})}_getFirstField(){const e=this._fields[0];if(!e)throw new hy("Unable to proceed because the payment form has no field defined.");return e}}function _y(e){return Boolean(e.instrumentId)}class wy{constructor(e){this._store=e}transform(e,t){const n=this._store.getState(),i=n.checkout.getCheckout(),r=n.config.getConfig(),o=n.instruments.getInstrumentsMeta(),a=n.order.getOrder(),s=n.order.getOrderMeta(),d=le(e.paymentData,"ccExpiry","ccName","ccNumber","ccCvv");let c=n.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId);"worldpayaccess"===(null==c?void 0:c.gateway)&&"credit_card"===(null==c?void 0:c.id)&&(c=Object.assign(Object.assign({},c),{id:"worldpayaccess",method:"credit-card"}));const l=n.paymentMethods.getPaymentMethodsMeta(),u=o&&d&&_y(d)?`${n.payment.getPaymentToken()}, ${o.vaultAccessToken}`:n.payment.getPaymentToken();if(!u)throw new rt(et.MissingPaymentToken);return{additionalAction:t,authToken:u,checkout:i,config:r,order:a,orderMeta:s,payment:d,paymentMethod:c,paymentMethodMeta:l}}}class Iy{constructor(e){this._store=e}create(e,t,n){const i=Object.keys(t.fields).reduce((i,r)=>{const o=t.fields[r];return o?[...i,new gy(r,o.containerId,o.placeholder||"",o.accessibilityLabel||"",t.styles||{},new Pn(e),new Yn(e),new kn(new mn),n,"instrumentId"in o?this._getCardInstrument(o.instrumentId):void 0)]:i},[]);return new Sy(i,new Yn(e),new wy(this._store),pe(t,"onBlur","onEnter","onFocus","onCardTypeChange","onValidate"),new cy(Sn(o())))}_getCardInstrument(e){const{instruments:{getCardInstrument:t}}=this._store.getState(),n=t(e);if(!n)throw new rt(et.MissingPaymentInstrument);return n}}!function(e){e.SubmitPaymentRequested="SUBMIT_PAYMENT_REQUESTED",e.SubmitPaymentSucceeded="SUBMIT_PAYMENT_SUCCEEDED",e.SubmitPaymentFailed="SUBMIT_PAYMENT_FAILED",e.InitializeOffsitePaymentRequested="INITIALIZE_OFFSITE_PAYMENT_REQUESTED",e.InitializeOffsitePaymentSucceeded="INITIALIZE_OFFSITE_PAYMENT_SUCCEEDED",e.InitializeOffsitePaymentFailed="INITIALIZE_OFFSITE_PAYMENT_FAILED"}(vy||(vy={}));class Cy{constructor(e,t,n,i){this._paymentRequestSender=e,this._orderActionCreator=t,this._paymentRequestTransformer=n,this._paymentHumanVerificationHandler=i,this.initializeOffsitePayment=({methodId:e,gatewayId:t,instrumentId:n,target:i,promise:r,shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a})=>s=>{let d;n?d={formattedPayload:{bigpay_token:n}}:o&&(d={formattedPayload:{vault_payment_instrument:o,set_as_default_stored_instrument:a||null}});const c=this._paymentRequestTransformer.transform({gatewayId:t,methodId:e,paymentData:d},s.getState());return g(C(l(vy.InitializeOffsitePaymentRequested)),Promise.race([this._paymentRequestSender.initializeOffsitePayment(c,i),r].filter(Boolean)).then(()=>l(vy.InitializeOffsitePaymentSucceeded))).pipe(P(e=>Je(vy.InitializeOffsitePaymentFailed,e)))}}submitPayment(e){return t=>g(C(l(vy.SubmitPaymentRequested)),v(()=>{return n=this,i=void 0,o=function*(){try{return yield this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(e,t.getState()))}catch(n){const i=yield this._paymentHumanVerificationHandler.handle(n);return yield this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(Object.assign(Object.assign({},e),{additionalAction:i}),t.getState()))}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}).pipe(M(({body:e})=>g(this._orderActionCreator.loadCurrentOrder()(t),C(l(vy.SubmitPaymentSucceeded,e)))))).pipe(P(e=>Je(vy.SubmitPaymentFailed,e)))}}class by{constructor(e){this._client=e}submitPayment(e){return new Promise((t,n)=>{this._client.submitPayment(e,(e,i)=>{e?n(this._transformResponse(e)):t(this._transformResponse(i))})})}initializeOffsitePayment(e,t){return new Promise(()=>{this._client.initializeOffsitePayment(e,null,t)})}_transformResponse(e){return{headers:e.headers,body:e.data,status:e.status,statusText:e.statusText}}}function Py(e,t){let n;return function(e){return void 0!==e.id}(e)?n=e.id:t&&t.length&&(n=t[0].id),{id:n,firstName:e.firstName,lastName:e.lastName,company:e.company,addressLine1:e.address1,addressLine2:e.address2,city:e.city,province:e.stateOrProvince,provinceCode:e.stateOrProvinceCode,postCode:e.postalCode,country:e.country,countryCode:e.countryCode,phone:e.phone,customFields:e.customFields}}const Oy=["per_item_discount","percentage_discount","per_total_discount","shipping_discount","free_shipping"];function Ey(e){return{code:e.code,discount:e.displayName,discountType:Oy.indexOf(e.couponType)}}function Ay(e){return{code:e.code,discountedAmount:e.used,remainingBalance:e.remaining,giftCertificate:{balance:e.balance,code:e.code,purchaseDate:e.purchaseDate}}}function Ty(e){const t=[];return(e||[]).forEach(e=>{(e.banners||[]).forEach(e=>{t.push({placeholders:[],discountType:null,message:"",messageHtml:e.text})})}),t}function ky(e,t,n="id"){return Object.keys(e).reduce((i,r)=>[...i,...e[r].map(e=>"giftCertificates"===r?function(e,t){const n=new fd(t);return{id:e.id,imageUrl:"",name:e.name,amount:e.amount,amountAfterDiscount:e.amount,discount:0,integerAmount:n.toInteger(e.amount),integerAmountAfterDiscount:n.toInteger(e.amount),integerUnitPrice:n.toInteger(e.amount),integerUnitPriceAfterDiscount:n.toInteger(e.amount),integerDiscount:0,quantity:1,sender:e.sender,recipient:e.recipient,type:"ItemGiftCertificateEntity",attributes:[],variantId:null}}(e,t):function(e,t,n,i="id"){const r=new fd(n);return{id:e[i],imageUrl:e.imageUrl,amount:e.extendedListPrice,amountAfterDiscount:e.extendedSalePrice,discount:e.discountAmount,integerAmount:r.toInteger(e.extendedListPrice),integerAmountAfterDiscount:r.toInteger(e.extendedSalePrice),integerDiscount:r.toInteger(e.discountAmount),integerUnitPrice:r.toInteger(e.listPrice),integerUnitPriceAfterDiscount:r.toInteger(e.salePrice),downloadsPageUrl:e.downloadPageUrl,name:e.name,quantity:e.quantity,brand:e.brand,sku:e.sku,categoryNames:e.categoryNames,variantId:e.variantId,productId:e.productId,attributes:(e.options||[]).map(e=>({name:e.name,value:e.value})),addedByPromotion:e.addedByPromotion,type:t}}(e,function(e){switch(e){case"physicalItems":return"ItemPhysicalEntity";case"digitalItems":return"ItemDigitalEntity";case"giftCertificates":return"ItemGiftCertificateEntity";default:return""}}(r),t,n))],[])}function Dy(e){const t=e.cart.currency.decimalPlaces,n=new fd(t);return{id:e.cart.id,items:ky(e.cart.lineItems,t),currency:e.cart.currency.code,coupon:{discountedAmount:ye(e.cart.coupons,(e,t)=>e+t.discountedAmount,0),coupons:e.cart.coupons.map(Ey)},discount:{amount:e.cart.discountAmount,integerAmount:n.toInteger(e.cart.discountAmount)},discountNotifications:Ty(e.promotions),giftCertificate:{totalDiscountedAmount:ye(e.giftCertificates,(e,t)=>e+t.used,0),appliedGiftCertificates:ne(e.giftCertificates.map(Ay),"code")},shipping:{amount:e.shippingCostTotal,integerAmount:n.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:n.toInteger(e.shippingCostBeforeDiscount),required:ve(e.cart.lineItems.physicalItems,e=>e.isShippingRequired)},subtotal:{amount:e.subtotal,integerAmount:n.toInteger(e.subtotal)},storeCredit:{amount:e.customer?e.customer.storeCredit:0},taxSubtotal:{amount:e.taxTotal,integerAmount:n.toInteger(e.taxTotal)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:n.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:n.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.grandTotal,integerAmount:n.toInteger(e.grandTotal)}}}var My;!function(e){e.APPLEPAY="applepay",e.AMAZON_PAY_V2="amazonpay",e.BRAINTREE_PAYPAL="braintreepaypal",e.BRAINTREE_VENMO="braintreevenmo",e.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",e.GOOGLEPAY_ADYENV2="googlepayadyenv2",e.GOOGLEPAY_ADYENV3="googlepayadyenv3",e.GOOGLEPAY_AUTHORIZENET="googlepayauthorizenet",e.GOOGLEPAY_BNZ="googlepaybnz",e.GOOGLEPAY_BRAINTREE="googlepaybraintree",e.GOOGLEPAY_CHECKOUTCOM="googlepaycheckoutcom",e.GOOGLEPAY_CYBERSOURCEV2="googlepaycybersourcev2",e.GOOGLEPAY_ORBITAL="googlepayorbital",e.GOOGLEPAY_STRIPE="googlepaystripe",e.GOOGLEPAY_STRIPEUPE="googlepaystripeupe",e.GOOGLEPAY_WORLDPAYACCESS="googlepayworldpayaccess",e.PAYPALEXPRESS="paypalexpress"}(My||(My={}));const zy=My;function Ny(e,t){const n=e.firstName||t.firstName||"",i=e.lastName||t.lastName||"";return{addresses:(e.addresses||[]).map(e=>Py(e)),customerId:e.id,isGuest:e.isGuest,storeCredit:e.storeCredit,email:e.email||t.email||"",firstName:n,lastName:i,name:e.fullName||[n,i].join(" "),customerGroupName:e.customerGroup&&e.customerGroup.name}}class xy{format(e){const[t="",n=""]=e.split(new RegExp("\\s*/\\s*")),i=t.slice(0,2),r=4===n.length?n.slice(-2):n?n.slice(0,2):t.slice(2);return e.length<2?t:e.length>3&&!r?i:`${i} / ${r}`}toObject(e){const[t="",n=""]=e.split(new RegExp("\\s*/\\s*"));return/^\d+$/.test(t)&&/^\d+$/.test(n)?{month:1===t.length?`0${t}`:t.slice(0,2),year:2===n.length?`20${n}`:n.slice(0,4)}:{month:"",year:""}}}class Ry{format(e){const{card:t}=Me(e);if(!t)return e;const n=ae(De(e).map(e=>ae(e.lengths))),i=this.unformat(e).slice(0,n);return t.gaps.filter(e=>i.length>e).reduce((e,t,n)=>[e.slice(0,t+n),e.slice(t+n)].join(" "),i)}unformat(e){const{card:t}=Me(e);return t?e.replace(new RegExp(" ","g"),""):e}}function Fy(e,t={}){const n=e.currency.decimalPlaces,i=new fd(n);return{id:e.orderId,items:ky(e.lineItems,e.currency.decimalPlaces,"productId"),orderId:e.orderId,currency:e.currency.code,customerCanBeCreated:e.customerCanBeCreated,payment:jy(e.payments,t.payment),subtotal:{amount:e.baseAmount,integerAmount:i.toInteger(e.baseAmount)},coupon:{discountedAmount:ye(e.coupons,(e,t)=>e+t.discountedAmount,0),coupons:e.coupons.map(Ey)},discount:{amount:e.discountAmount,integerAmount:i.toInteger(e.discountAmount)},token:t.orderToken,callbackUrl:t.callbackUrl,discountNotifications:[],giftCertificate:By(e.payments),socialData:qy(e),status:e.status,hasDigitalItems:e.hasDigitalItems,isDownloadable:e.isDownloadable,isComplete:e.isComplete,shipping:{amount:e.shippingCostTotal,integerAmount:i.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:i.toInteger(e.shippingCostBeforeDiscount)},storeCredit:{amount:Ly(e.payments)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:i.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:i.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.orderAmount,integerAmount:e.orderAmountAsInteger}}}function Ly(e){const t=B(e,{providerId:"storecredit"});return t?t.amount:0}function By(e){const t=L(e,{providerId:"giftcertificate"});return{totalDiscountedAmount:ye(t,(e,t)=>t.amount+e,0),appliedGiftCertificates:ne(t.map(e=>({code:e.detail.code,discountedAmount:e.amount,remainingBalance:e.detail.remaining,giftCertificate:{balance:e.amount+e.detail.remaining,code:e.detail.code,purchaseDate:""}})),"code")}}function jy(e,t={}){const n=B(e,Uy);return n?{id:n.providerId,status:(i=n.detail.step,`PAYMENT_STATUS_${i}`),helpText:n.detail.instructions,returnUrl:t.returnUrl}:{};var i}function Uy(e){return"giftcertificate"!==e.providerId&&"storecredit"!==e.providerId}function qy(e){const t={};return[...e.lineItems.physicalItems,...e.lineItems.digitalItems].forEach(e=>{var n;t[e.id]=(n=e,["fb","tw","gp"].reduce((e,t)=>{const i=n.socialMedia&&B(n.socialMedia,e=>e.code===t);return i?(e[t]={name:n.name,description:n.name,image:n.imageUrl,url:i.link,shareText:i.text,sharingLink:i.link,channelName:i.channel,channelCode:i.code},e):e},{}))}),t}function Vy(e,t){return{description:e.description,module:e.type,price:e.cost,id:e.id,selected:t,isRecommended:e.isRecommended,imageUrl:e.imageUrl,transitTime:e.transitTime}}class Gy{constructor(){this._cardExpiryFormatter=new xy,this._cardNumberFormatter=new Ry}transform(e,t){const n=t.billingAddress.getBillingAddress(),i=t.checkout.getCheckout(),r=t.customer.getCustomer(),o=t.order.getOrder(),a=t.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId),s=this._mapShippingAddress(t,a),d=t.consignments.getConsignments(),c=t.consignments.getShippingOption(),l=t.config.getStoreConfig(),u=t.config.getContextConfig(),h=t.instruments.getInstrumentsMeta(),p=t.paymentMethods.getPaymentMethodsMeta(),m=t.order.getOrderMeta(),y=r&&n&&Ny(r,n),g=h&&e.paymentData&&(_y(e.paymentData)||function(e){const t=e.formattedPayload;return!!t&&("string"==typeof t.bigpay_token||Boolean(t.bigpay_token&&t.bigpay_token.token))}(e.paymentData))?`${t.payment.getPaymentToken()}, ${h.vaultAccessToken}`:t.payment.getPaymentToken();if(!g)throw new rt(et.MissingPaymentToken);return{additionalAction:e.additionalAction,authToken:g,customer:y,billingAddress:n&&Py(n),shippingAddress:s&&Py(s,d),shippingOption:c&&Vy(c,!0),cart:i&&Dy(i),order:o&&Fy(o,m),orderMeta:m,payment:e.paymentData,paymentMethod:a&&this._transformPaymentMethod(a),quoteMeta:{request:Object.assign(Object.assign({},p),{geoCountryCode:u&&u.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:pe(l&&l.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}}transformWithHostedFormData(e,t,n){const{additionalAction:i,authToken:r,checkout:o,config:a,order:s,orderMeta:d,payment:c={},paymentMethod:l,paymentMethodMeta:u}=t,h=o&&o.consignments[0],p=h&&h.shippingAddress,m=h&&h.selectedShippingOption;return{additionalAction:i,authToken:r,paymentMethod:l&&this._transformPaymentMethod(l),customer:s&&s.billingAddress&&o&&Ny(o.customer,s.billingAddress),billingAddress:s&&s.billingAddress&&Py(s.billingAddress),shippingAddress:p&&o&&Py(p,o.consignments),shippingOption:m&&Vy(m,!0),cart:o&&Dy(o),order:s&&Fy(s,d),orderMeta:d,payment:this._transformHostedInputValues(e,c,n),quoteMeta:{request:Object.assign(Object.assign({},u),{geoCountryCode:a&&a.context.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:a&&pe(a.storeConfig.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}}_transformPaymentMethod(e){if("multi-option"===e.method&&!e.gateway)return Object.assign(Object.assign({},e),{gateway:e.id});if(e.initializationData&&e.initializationData.gateway)return Object.assign(Object.assign({},e),{id:e.initializationData.gateway});if("worldpayaccess"===e.gateway){if("credit_card"===e.id)return Object.assign(Object.assign({},e),{id:"worldpayaccess",method:"credit-card"});if("open_banking"===e.id)return Object.assign(Object.assign({},e),{id:"worldpayaccess",method:"open_banking"})}return e.id===zy.BRAINTREE_VENMO?Object.assign(Object.assign({},e),{id:zy.BRAINTREE_PAYPAL}):e}_transformHostedInputValues(e,t,n){return"instrumentId"in t?Object.assign(Object.assign({},t),{ccCvv:e.cardCodeVerification,ccNumber:e.cardNumberVerification&&this._cardNumberFormatter.unformat(e.cardNumberVerification),hostedFormNonce:n}):Object.assign(Object.assign({},t),{ccCvv:e.cardCode,ccExpiry:this._cardExpiryFormatter.toObject(e.cardExpiry||""),ccName:e.cardName||"",ccNumber:this._cardNumberFormatter.unformat(e.cardNumber||""),hostedFormNonce:n})}_mapShippingAddress(e,t){var n,i,r,o;if(t){const a=null===(i=null===(n=t.initializationData)||void 0===n?void 0:n.bopis)||void 0===i?void 0:i.enabled,s=null===(o=null===(r=t.initializationData)||void 0===r?void 0:r.bopis)||void 0===o?void 0:o.requiredAddress,d=e.consignments.getConsignments(),c=null==d?void 0:d.every(e=>e.selectedPickupOption);if(a&&c&&"none"===s)return}return e.shippingAddress.getShippingAddress()}}const Hy=e=>{const{type:t,initializationStrategy:n}=e;return t===Zm.PPSDK&&"string"==typeof(null==n?void 0:n.type)};class Wy extends Vt{getByMethod(e){if(!e)return this.get();const t=this._getToken(e),n=[e.gateway,e.id].filter(e=>null!=e).join("-");return this.get(t,n)}_getToken(e){if(Hy(e))return Zm.PPSDK;if("klarna"===e.gateway)return Zm.KLARNAV2;const t=e.gateway||e.id;if(this._hasFactoryForMethod(t))return t;if("PAYMENT_TYPE_OFFLINE"===e.type)return Zm.OFFLINE;throw new qt(`'${t}' is not registered.`)}_hasFactoryForMethod(e){return this._hasFactory(e)}}const $y="FINALIZE";class Yy extends qt{constructor(e){let t="Unable to submit payment for the order because the payload is invalid.";e&&(t=`${t} Make sure the following fields are provided correctly: ${e.join(", ")}.`),super(t),this.name="PaymentArgumentInvalidError"}}var Ky=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r(this._shouldRenderHostedForm=!0,this._hostedForm=r,this._store.getState()))}deinitialize(e){return this._hostedForm&&this._hostedForm.detach(),Promise.resolve(this._store.getState())}_executeWithoutHostedForm(e,t){const{payment:n}=e,i=Ky(e,["payment"]),r=n&&n.paymentData;if(!n||!r)throw new Yy(["payment.paymentData"]);return this._store.dispatch(this._orderActionCreator.submitOrder(i,t)).then(()=>this._store.dispatch(this._paymentActionCreator.submitPayment(Object.assign(Object.assign({},n),{paymentData:r}))))}_executeWithHostedForm(e,t){const{payment:n}=e,i=Ky(e,["payment"]),r=this._hostedForm;if(!r)throw new yn(cn.PaymentNotInitialized);if(!n||!n.methodId)throw new Yy(["payment.methodId"]);return r.validate().then(()=>this._store.dispatch(this._orderActionCreator.submitOrder(i,t))).then(()=>r.submit(n)).then(()=>this._store.dispatch(this._orderActionCreator.loadCurrentOrder()))}_isHostedPaymentFormEnabled(e,t){if(!e)return!1;const{paymentMethods:{getPaymentMethodOrThrow:n}}=this._store.getState();return!0===n(e,t).config.isHostedFormEnabled}_isHostedFieldAvailable(e){return!Ce(e&&e.creditCard&&e.creditCard.form.fields).every(J)}}class Zy extends Jy{constructor(e,t,n,i,r){super(e,t,n,i),this._formPoster=r}execute(e,t){return super.execute(e,t).catch(e=>e instanceof Ot&&ve(e.body.errors,{code:"three_d_secure_required"})?new Promise(()=>{this._formPoster.postForm(e.body.three_ds_result.acs_url,{PaReq:e.body.three_ds_result.payer_auth_request,TermUrl:e.body.three_ds_result.callback_url,MD:e.body.three_ds_result.merchant_data})}):Promise.reject(e))}finalize(e){const t=this._store.getState(),n=t.order.getOrder();return n&&t.payment.getPaymentStatus()===$y?this._store.dispatch(this._orderActionCreator.finalizeOrder(n.orderId,e)):Promise.reject(new Ym)}}class Qy extends it{constructor(e){super(e||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}const Xy="redirecting";class eg{constructor(){this._isRedirecting=this.currentUrlHasRedirectingParam()}isRedirecting(){return this._isRedirecting}setRedirecting(e){e?this.setRedirectingParamOnUrl():this.removeRedirectingParamFromUrl(),this._isRedirecting=e}currentUrlHasRedirectingParam(){return Xy in this.getCurrentUrl().query}getCurrentUrl(){return Ne(window.location.href)}replaceCurrentUrl(e){window.history.replaceState(null,"",e)}setRedirectingParamOnUrl(){if(this.currentUrlHasRedirectingParam())return;const e=this.getCurrentUrl(),t=Object.assign(Object.assign({},e),{query:Object.assign(Object.assign({},e.query),{[Xy]:"true"})});this.replaceCurrentUrl(xe(t))}removeRedirectingParamFromUrl(){this.currentUrlHasRedirectingParam()&&this.replaceCurrentUrl(ze(window.location.href,[Xy]))}}const tg=he([e=>"continue"===V(e,"type")&&"redirect"===V(e,"code")&&(e=>{const t=V(e,"form_fields");return X(V(e,"url"))&&(ee(t)||Z(t))})(V(e,"parameters")),e=>"continue"===V(e,"type")&&"resubmit_with_human_verification"===V(e,"code")&&(e=>{const t=V(e,"available_methods");return W(t)})(V(e,"parameters"))]);class ng{constructor(e,t){this._formPoster=e,this._humanVerificationHandler=t}handle(e,t){switch(e.code){case"redirect":return(({url:e,form_fields:t},n)=>{const i=new eg;return i.isRedirecting()?(i.setRedirecting(!1),Promise.reject(new Qy)):(i.setRedirecting(!0),t?n.postForm(e,t):window.location.assign(e),new Promise(ce))})(e.parameters,this._formPoster);case"resubmit_with_human_verification":return(({available_methods:e},t,n)=>{return i=void 0,r=void 0,a=function*(){if(!n)throw new Error("PPSDK human verification callback function is missing.");if(!t)throw new Error("PPSDK human verification handler is missing.");if(0===e.length)throw Error("Human verification method is missing.");const{id:i,parameters:r}=e[0],o=yield t.handle(i,r.key);return n(o)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a})(e.parameters,this._humanVerificationHandler,null==t?void 0:t.humanVerification)}}}class ig{constructor(e){this._continueHandler=e}handle(e,t){const{body:n}=e;return(e=>"success"===V(e,"type"))(n)?Promise.resolve():(e=>tg(e))(n)?this._continueHandler.handle(n,null==t?void 0:t.continue):(e=>"failure"===V(e.body,"type")&&X(V(e.body,"code")))(e)?(e=>{return Promise.reject(new Ot((t=e,Object.assign(Object.assign({},t),{body:{errors:[{code:t.body.code}]}}))));var t})(e):((e=>{V(e.body,"type")})(e),(e=>Promise.reject(new Ot(e)))(e))}}const rg="completed-payments";class og{constructor(e){this._browserStorage=e}isCompleted(e){return this.getCompletedPayments().indexOf(e)>=0}setCompleted(e){const t=this.getCompletedPayments();t.push(e),this.setCompletedPayments(t)}getCompletedPayments(){return this._browserStorage.getItem(rg)||[]}setCompletedPayments(e){this._browserStorage.setItem(rg,e)}}var ag,sg=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class dg{constructor(e,t,n,i,r){this._store=e,this._orderActionCreator=t,this._subStrategyRegistry=n,this._paymentResumer=i,this._completedPayments=new og(r)}execute(e,t){var n;return sg(this,void 0,void 0,function*(){const{bigpayBaseUrl:i}=this._store.getState().config.getStoreConfigOrThrow().paymentSettings;if(!(null==t?void 0:t.methodId))throw new qt('Unable to submit payment because "options.methodId" argument is not provided.');const{methodId:r}=t,{payment:o}=e,a=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{throw this._completedPayments.setCompleted(i),e}),this._store.getState()})}initialize(e){return sg(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new qt('Unable to submit payment because "options.methodId" argument is not provided.');const t=((e,t)=>{const n=e.getState().paymentMethods.getPaymentMethod(t);if(n&&Hy(n))return n})(this._store,e.methodId);if(!t)throw new yn(cn.PaymentNotInitialized);if(this._subStrategy=this._subStrategyRegistry.getByMethod(t),!this._subStrategy)throw new yn(cn.PaymentNotInitialized);return yield this._subStrategy.initialize(e),this._store.getState()})}deinitialize(e){var t;return sg(this,void 0,void 0,function*(){return null===(t=this._subStrategy)||void 0===t||t.deinitialize(),this._store.getState()})}}!function(e){e.CARD="card_ui",e.NONE="none",e.UNSUPPORTED="unsupported"}(ag||(ag={}));const cg=N([[e=>"card_ui"===e.type,x(ag.CARD)],[e=>"none"===e.type,x(ag.NONE)],[fe,x(ag.UNSUPPORTED)]]);class lg extends Vt{getByMethod(e){const t=cg(e.initializationStrategy);return this.get(t)}}var ug=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class hg{constructor(e,t,n,i){this._store=e,this._orderActionCreator=t,this._hostedFormFactory=n,this._ppsdkStepHandler=i}execute(e){return ug(this,void 0,void 0,function*(){const t=this._hostedForm;if(!t)throw new yn(cn.PaymentNotInitialized);const{additionalAction:n,payment:i}=e;if(!i||!i.methodId)throw new Yy(["payment.methodId"]);yield t.validate();const{payload:r}=yield t.submit(i,n),{response:o}=r;yield this._ppsdkStepHandler.handle(o,{continue:{humanVerification:t=>ug(this,void 0,void 0,function*(){return this.execute(Object.assign({additionalAction:t},e))})}}),yield this._store.dispatch(this._orderActionCreator.loadCurrentOrder())})}initialize(e){return ug(this,void 0,void 0,function*(){const t=e&&e.creditCard&&e.creditCard.form,{config:n,checkout:i}=this._store.getState(),{paymentSettings:{bigpayBaseUrl:r=""}={}}=n.getStoreConfig()||{},o=i.getCheckoutOrThrow().id;if(!t)throw new qt;const a=t&&this._hostedFormFactory.create(r,t,o);yield a.attach(),this._hostedForm=a})}deinitialize(){this._hostedForm&&this._hostedForm.detach()}}class pg{constructor(e,t){this._requestSender=e,this._stepHandler=t}execute({methodId:e,bigpayBaseUrl:t,token:n}){const i={credentials:!1,body:{payment_method_id:e},headers:{authorization:n,"X-XSRF-TOKEN":null}};return this._requestSender.post(`${t}/payments`,i).then(e=>this._stepHandler.handle(e))}initialize(){return Promise.resolve()}deinitialize(){}}var mg,yg,gg=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vg{constructor(e,t){this._requestSender=e,this._stepHandler=t}resume({paymentId:e,bigpayBaseUrl:t,orderId:n}){return gg(this,void 0,void 0,function*(){const i={credentials:!1,headers:{authorization:yield this._getToken(n).catch(()=>{throw new Ym}),"X-XSRF-TOKEN":null}};return this._requestSender.get(`${t}/payments/${e}`,i).then(e=>this._stepHandler.handle(e))})}_getToken(e){return gg(this,void 0,void 0,function*(){const t={params:{order_id:e}};return this._requestSender.get("/api/storefront/payments/auth-token",t).then(({body:e})=>e.auth_token)})}}class fg{constructor(e){this._requestSender=e}createBuyNowCart(e,{timeout:t}={}){const n=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post("/api/storefront/carts",{body:e,headers:n,timeout:t})}}!function(e){e.UpdatePaymentProviderCustomer="UPDATE_PAYMENT_PROVIDER_CUSTOMER"}(mg||(mg={}));class Sg{updatePaymentProviderCustomer(e){return C(l(mg.UpdatePaymentProviderCustomer,e))}}!function(e){e.ForgetCheckoutRemoteCustomerRequested="FORGET_CHECKOUT_REMOTE_CUSTOMER_REQUESTED",e.ForgetCheckoutRemoteCustomerSucceeded="FORGET_CHECKOUT_REMOTE_CUSTOMER_SUCCEEDED",e.ForgetCheckoutRemoteCustomerFailed="FORGET_CHECKOUT_REMOTE_CUSTOMER_FAILED",e.InitializeRemoteBillingRequested="INITIALIZE_REMOTE_BILLING_REQUESTED",e.InitializeRemoteBillingSucceeded="INITIALIZE_REMOTE_BILLING_SUCCEEDED",e.InitializeRemoteBillingFailed="INITIALIZE_REMOTE_BILLING_FAILED",e.InitializeRemoteShippingRequested="INITIALIZE_REMOTE_SHIPPING_REQUESTED",e.InitializeRemoteShippingSucceeded="INITIALIZE_REMOTE_SHIPPING_SUCCEEDED",e.InitializeRemoteShippingFailed="INITIALIZE_REMOTE_SHIPPING_FAILED",e.InitializeRemotePaymentRequested="INITIALIZE_REMOTE_PAYMENT_REQUESTED",e.InitializeRemotePaymentSucceeded="INITIALIZE_REMOTE_PAYMENT_SUCCEEDED",e.InitializeRemotePaymentFailed="INITIALIZE_REMOTE_PAYMENT_FAILED",e.LoadRemoteSettingsRequested="LOAD_REMOTE_SETTINGS_REQUESTED",e.LoadRemoteSettingsSucceeded="LOAD_REMOTE_SETTINGS_SUCCEEDED",e.LoadRemoteSettingsFailed="LOAD_REMOTE_SETTINGS_FAILED",e.SignOutRemoteCustomerRequested="SIGN_OUT_REMOTE_CUSTOMER_REQUESTED",e.SignOutRemoteCustomerSucceeded="SIGN_OUT_REMOTE_CUSTOMER_SUCCEEDED",e.SignOutRemoteCustomerFailed="SIGN_OUT_REMOTE_CUSTOMER_FAILED",e.UpdateRemoteCheckout="UPDATE_REMOTE_CHECKOUT"}(yg||(yg={}));var _g;class wg{constructor(e,t){this._remoteCheckoutRequestSender=e,this._checkoutActionCreator=t}initializeBilling(e,t,n){return m.create(i=>{i.next(l(yg.InitializeRemoteBillingRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializeBilling(e,t,n).then(({body:t={}})=>{i.next(l(yg.InitializeRemoteBillingSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(yg.InitializeRemoteBillingFailed,t,{methodId:e}))})})}initializeShipping(e,t,n){return m.create(i=>{i.next(l(yg.InitializeRemoteShippingRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializeShipping(e,t,n).then(({body:t={}})=>{i.next(l(yg.InitializeRemoteShippingSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(yg.InitializeRemoteShippingFailed,t,{methodId:e}))})})}initializePayment(e,t,n){return m.create(i=>{i.next(l(yg.InitializeRemotePaymentRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializePayment(e,t,n).then(({body:t={}})=>{i.next(l(yg.InitializeRemotePaymentSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(yg.InitializeRemotePaymentFailed,t,{methodId:e}))})})}loadSettings(e,t){return m.create(n=>{n.next(l(yg.LoadRemoteSettingsRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.loadSettings(e,t).then(({body:t})=>{n.next(l(yg.LoadRemoteSettingsSucceeded,t,{methodId:e})),n.complete()}).catch(t=>{n.error(h(yg.LoadRemoteSettingsFailed,t,{methodId:e}))})})}signOut(e,t){return m.create(n=>{n.next(l(yg.SignOutRemoteCustomerRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.signOut(e,t).then(()=>{n.next(l(yg.SignOutRemoteCustomerSucceeded,void 0,{methodId:e})),n.complete()}).catch(t=>{n.error(h(yg.SignOutRemoteCustomerFailed,t,{methodId:e}))})})}forgetCheckout(e,t){return g(C(l(yg.ForgetCheckoutRemoteCustomerRequested,void 0,{methodId:e})),v(()=>{return n=this,i=void 0,o=function*(){return yield this._remoteCheckoutRequestSender.forgetCheckout(t),yield this._checkoutActionCreator.loadCurrentCheckout(),l(yg.ForgetCheckoutRemoteCustomerSucceeded,void 0,{methodId:e})},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(t=>Je(yg.ForgetCheckoutRemoteCustomerFailed,t,{methodId:e})))}updateCheckout(e,t){return l(yg.UpdateRemoteCheckout,t,{methodId:e})}}class Ig{constructor(e){this._requestSender=e}initializeBilling(e,t,{timeout:n}={}){const i=`/remote-checkout/${e}/billing`;return this._requestSender.get(i,{params:t,timeout:n,headers:Xe})}initializeShipping(e,t,{timeout:n}={}){const i=`/remote-checkout/${e}/shipping`;return this._requestSender.get(i,{params:t,timeout:n,headers:Xe})}initializePayment(e,t,{timeout:n}={}){const i=`/remote-checkout/${e}/payment`;return this._requestSender.get(i,{params:t,timeout:n,headers:Xe})}loadSettings(e,{timeout:t}={}){const n=`/remote-checkout/${e}/settings`;return this._requestSender.get(n,{timeout:t,headers:Xe})}signOut(e,{timeout:t}={}){const n=`/remote-checkout/${e}/signout`;return this._requestSender.get(n,{timeout:t,headers:Xe})}generateToken({timeout:e}={}){return this._requestSender.get("/remote-checkout-token",{timeout:e,headers:Xe})}trackAuthorizationEvent({timeout:e}={}){return this._requestSender.post("/remote-checkout/events/shopper-checkout-service-provider-authorization-requested",{timeout:e,headers:Xe})}forgetCheckout({timeout:e}={}){return this._requestSender.post("/remote-checkout/forget-checkout",{timeout:e,headers:Xe})}}!function(e){e.CreateConsignmentsRequested="CREATE_CONSIGNMENTS_REQUESTED",e.CreateConsignmentsSucceeded="CREATE_CONSIGNMENTS_SUCCEEDED",e.CreateConsignmentsFailed="CREATE_CONSIGNMENTS_FAILED",e.UpdateConsignmentRequested="UPDATE_CONSIGNMENT_REQUESTED",e.UpdateConsignmentSucceeded="UPDATE_CONSIGNMENT_SUCCEEDED",e.UpdateConsignmentFailed="UPDATE_CONSIGNMENT_FAILED",e.DeleteConsignmentRequested="DELETE_CONSIGNMENT_REQUESTED",e.DeleteConsignmentSucceeded="DELETE_CONSIGNMENT_SUCCEEDED",e.DeleteConsignmentFailed="DELETE_CONSIGNMENT_FAILED",e.UpdateShippingOptionRequested="UPDATE_SHIPPING_OPTION_REQUESTED",e.UpdateShippingOptionSucceeded="UPDATE_SHIPPING_OPTION_SUCCEEDED",e.UpdateShippingOptionFailed="UPDATE_SHIPPING_OPTION_FAILED",e.LoadShippingOptionsRequested="LOAD_SHIPPING_OPTIONS_REQUESTED",e.LoadShippingOptionsSucceeded="LOAD_SHIPPING_OPTIONS_SUCCEEDED",e.LoadShippingOptionsFailed="LOAD_SHIPPING_OPTIONS_FAILED"}(_g||(_g={}));class Cg{constructor(e,t){this._consignmentRequestSender=e,this._checkoutRequestSender=t}unassignItemsByAddress(e,t){return n=>{const i=n.getState();if(!i.checkout.getCheckout())throw new rt(et.MissingCheckout);const r=this._consignmentHasAddress(e)?e.address:e.shippingAddress,o=i.consignments.getConsignmentByAddress(r);if(!o)throw new qt("No consignment found for the specified address");const a=this._removeLineItems(e.lineItems,o,i.cart.getCart());return a.length?this.updateConsignment({id:o.id,address:r,lineItems:a},t)(n):this.deleteConsignment(o.id,t)(n)}}assignItemsByAddress(e,t){return n=>{const i=n.getState(),r=this._consignmentHasAddress(e)?e.address:e.shippingAddress,o=i.consignments.getConsignmentByAddress(r);return this._createOrUpdateConsignment({id:o&&o.id,address:r,lineItems:this._addLineItems(e.lineItems,o,i.cart.getCart())},t)(n)}}selectShippingOption(e,t){return n=>m.create(i=>{const r=n.getState(),o=r.checkout.getCheckout(),a=r.consignments.getConsignments();if(!o)throw new rt(et.MissingCheckout);if(!a||!a.length)throw new rt(et.MissingConsignments);const s={id:a[0].id,shippingOptionId:e},d={id:a[0].id};i.next(l(_g.UpdateShippingOptionRequested,void 0,d)),this._consignmentRequestSender.updateConsignment(o.id,s,t).then(({body:e})=>{i.next(l(_g.UpdateShippingOptionSucceeded,e,d)),i.complete()}).catch(e=>{i.error(h(_g.UpdateShippingOptionFailed,e,d))})})}loadShippingOptions(e){return t=>m.create(n=>{const i=t.getState().checkout.getCheckout();if(!i)throw new rt(et.MissingCheckout);n.next(l(_g.LoadShippingOptionsRequested)),this._checkoutRequestSender.loadCheckout(i.id,Object.assign(Object.assign({},e),{params:{include:[zt.AvailableShippingOptions]}})).then(({body:e})=>{n.next(l(_g.LoadShippingOptionsSucceeded,e)),n.complete()}).catch(e=>{n.error(h(_g.LoadShippingOptionsFailed,e))})})}updateAddress(e,t){return n=>{const i=this._getUpdateAddressRequestBody(e,n),r=n.getState().consignments.getConsignments();return r&&r.length&&(i.id=r[0].id),this._createOrUpdateConsignment(i,t)(n)}}createConsignments(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r||!r.id)throw new rt(et.MissingCheckout);i.next(l(_g.CreateConsignmentsRequested)),this._consignmentRequestSender.createConsignments(r.id,e,t).then(({body:e})=>{i.next(l(_g.CreateConsignmentsSucceeded,e)),i.complete()}).catch(e=>{i.error(h(_g.CreateConsignmentsFailed,e))})})}updateConsignment(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r||!r.id)throw new rt(et.MissingCheckout);const o={id:e.id};i.next(l(_g.UpdateConsignmentRequested,void 0,o)),this._consignmentRequestSender.updateConsignment(r.id,e,t).then(({body:e})=>{i.next(l(_g.UpdateConsignmentSucceeded,e,o)),i.complete()}).catch(e=>{i.error(h(_g.UpdateConsignmentFailed,e,o))})})}deleteConsignment(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout(),o={id:e};if(!r||!r.id)throw new rt(et.MissingCheckout);i.next(l(_g.DeleteConsignmentRequested,void 0,o)),this._consignmentRequestSender.deleteConsignment(r.id,e,t).then(({body:e})=>{i.next(l(_g.DeleteConsignmentSucceeded,e,o)),i.complete()}).catch(e=>{i.error(h(_g.DeleteConsignmentFailed,e,o))})})}updateShippingOption(e,t){return n=>m.create(i=>{var r;const o=n.getState().checkout.getCheckout(),a=n.getState().consignments.getConsignmentById(e.id);if((null===(r=null==a?void 0:a.selectedShippingOption)||void 0===r?void 0:r.id)===e.shippingOptionId)return void i.complete();if(!o||!o.id)throw new rt(et.MissingCheckout);const s={id:e.id};i.next(l(_g.UpdateShippingOptionRequested,void 0,s)),this._consignmentRequestSender.updateConsignment(o.id,e,t).then(({body:e})=>{i.next(l(_g.UpdateShippingOptionSucceeded,e,s)),i.complete()}).catch(e=>{i.error(h(_g.UpdateShippingOptionFailed,e,s))})})}_createOrUpdateConsignment(e,t){return n=>{const i=n.getState().checkout.getCheckout();if(!i||!i.id)throw new rt(et.MissingCheckout);return this._isUpdateConsignmentRequest(e)?this.updateConsignment(e,t)(n):this.createConsignments([e],t)(n)}}_getUpdateAddressRequestBody(e,t){const n=t.getState().cart.getCart();if(!n)throw new rt(et.MissingCart);const{physicalItems:i,customItems:r=[]}=n.lineItems;return{address:e,lineItems:[...i,...r].map(e=>({itemId:e.id,quantity:e.quantity}))}}_removeLineItems(e,t,n){if(!n)throw new rt(et.MissingCart);return this._hydrateLineItems(t.lineItemIds,n).map(t=>{const n=B(e,e=>e.itemId===t.itemId);return Object.assign(Object.assign({},t),{quantity:n?t.quantity-n.quantity:t.quantity})}).filter(e=>e.quantity>0)}_addLineItems(e,t,n){if(!t)return e;if(!n)throw new rt(et.MissingCart);return e.concat(this._hydrateLineItems(t.lineItemIds,n)).filter(e=>e.quantity>0)}_hydrateLineItems(e,t){return e.map(e=>{const n=B(t.lineItems.physicalItems,t=>t.id===e);return{itemId:e,quantity:n?n.quantity:0}})}_isUpdateConsignmentRequest(e){return!!e.id}_consignmentHasAddress(e){return"object"==typeof e&&"address"in e}}const bg=["consignments.availableShippingOptions","cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","promotions.banners"];class Pg{constructor(e){this._requestSender=e}createConsignments(e,t,{timeout:n,params:{include:i}={}}={}){const r=`/api/storefront/checkouts/${e}/consignments`,o=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(r,{body:t,params:{include:Xt(bg,i)},headers:o,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}updateConsignment(e,t,{timeout:n,params:{include:i}={}}={}){const{id:r}=t,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if("empty_cart"===e.body.type)throw new dt;throw e})}deleteConsignment(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/consignments/${t}`,r=Object.assign({Accept:ct.JsonV1},Xe),o=Ft(bg);return this._requestSender.delete(i,{params:{include:o},headers:r,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}var Og,Eg;!function(e){e.LoadShippingCountriesRequested="LOAD_SHIPPING_COUNTRIES_REQUESTED",e.LoadShippingCountriesSucceeded="LOAD_SHIPPING_COUNTRIES_SUCCEEDED",e.LoadShippingCountriesFailed="LOAD_SHIPPING_COUNTRIES_FAILED"}(Og||(Og={}));class Ag{constructor(e,t){this._shippingCountryRequestSender=e,this._store=t}loadCountries(e){const{checkout:t}=this._store.getState(),n=t.getCheckout(),i=n?n.channelId:null;return m.create(t=>{t.next(l(Og.LoadShippingCountriesRequested)),this._shippingCountryRequestSender.loadCountries(i,e).then(e=>{t.next(l(Og.LoadShippingCountriesSucceeded,e.body.data)),t.complete()}).catch(e=>{t.error(h(Og.LoadShippingCountriesFailed,e))})})}}class Tg{constructor(e,t){this._requestSender=e,this._config=t}loadCountries(e,{timeout:t}={}){const n="/internalapi/v1/shipping/countries"+(e?`?channel_id=${e}`:""),i=Object.assign({"Accept-Language":this._config.locale},Xe);return this._requestSender.get(n,{headers:i,timeout:t})}}!function(e){e.ApplyStoreCreditRequested="APPLY_STORE_CREDIT_REQUESTED",e.ApplyStoreCreditSucceeded="APPLY_STORE_CREDIT_SUCCEEDED",e.ApplyStoreCreditFailed="APPLY_STORE_CREDIT_FAILED"}(Eg||(Eg={}));var kg;class Dg{constructor(e){this._storeCreditRequestSender=e}applyStoreCredit(e,t){return n=>g(C(l(Eg.ApplyStoreCreditRequested)),v(()=>{return i=this,r=void 0,a=function*(){var i;const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);const{id:o}=r,a=null!==(i=null==t?void 0:t.version)&&void 0!==i?i:r.version,{body:s}=yield e?this._storeCreditRequestSender.applyStoreCredit(o,Object.assign(Object.assign({},t),{version:a})):this._storeCreditRequestSender.removeStoreCredit(o,Object.assign(Object.assign({},t),{version:a}));return l(Eg.ApplyStoreCreditSucceeded,s)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a})).pipe(P(e=>Je(Eg.ApplyStoreCreditFailed,e)))}}class Mg{constructor(e){this._requestSender=e}applyStoreCredit(e,{timeout:t,version:n}={}){const i=`/api/storefront/checkouts/${e}/store-credit`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{headers:r,timeout:t,params:{include:Ft(Mt)},body:{version:n}})}removeStoreCredit(e,{timeout:t,version:n}={}){const i=`/api/storefront/checkouts/${e}/store-credit`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.delete(i,{headers:r,timeout:t,params:{include:Ft(Mt)},body:{version:n}})}}!function(e){e.UpdateSubscriptionsRequested="UPDATE_SUBSCRIPTIONS_REQUESTED",e.UpdateSubscriptionsSucceeded="UPDATE_SUBSCRIPTIONS_SUCCEEDED",e.UpdateSubscriptionsFailed="UPDATE_SUBSCRIPTIONS_FAILED"}(kg||(kg={}));class zg extends Ot{constructor(e){super(e),this.name="UpdateSubscriptionsError",this.type="update_subscriptions"}}class Ng{constructor(e){this._subscriptionsRequestSender=e}updateSubscriptions(e,t){return g(C(l(kg.UpdateSubscriptionsRequested)),v(()=>{return n=this,i=void 0,o=function*(){const{body:n}=yield this._subscriptionsRequestSender.updateSubscriptions(e,t);return l(kg.UpdateSubscriptionsSucceeded,n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Je(kg.UpdateSubscriptionsFailed,new zg(e))))}}class xg{constructor(e){this._requestSender=e}updateSubscriptions(e,{timeout:t}={}){const n=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post("/api/storefront/subscriptions",{body:e,headers:n,timeout:t})}}function Rg(e){return Q(e)}const Fg=se(e=>Array.isArray(e)?e.map(e=>Lg(e)):Rg(e)?Object.keys(e).reduce((t,n)=>Object.assign(Object.assign({},t),{[n]:Lg(e[n])}),{}):e);Fg.cache=new WeakMap;const Lg=e=>"object"==typeof e&&null!==e?Fg(e):e;function Bg(e){return(...t)=>Lg(e(...t))}function jg({billingAddress:{getBillingAddress:e,getBillingAddressOrThrow:t},cart:{getCart:n,getCartOrThrow:i,getLocale:r},checkout:{getCheckout:o,getCheckoutOrThrow:a,getOutstandingBalance:s},config:{getContextConfig:d,getHost:c,getLocale:l,getStoreConfig:u,getStoreConfigOrThrow:h,getConfig:p},consignments:{getConsignments:m,getConsignmentsOrThrow:y},countries:{getCountries:g},customer:{getCustomer:v,getCustomerOrThrow:f},instruments:{getCardInstrument:S,getCardInstrumentOrThrow:_,getInstruments:w,getInstrumentsMeta:I},order:{getOrder:C,getOrderOrThrow:b,getOrderMeta:P},payment:{getPaymentToken:O,getPaymentTokenOrThrow:E,getPaymentId:A,getPaymentIdOrThrow:T,getPaymentStatus:k,getPaymentStatusOrThrow:D,getPaymentRedirectUrl:M,getPaymentRedirectUrlOrThrow:z,isPaymentDataRequired:N},paymentMethods:{getPaymentMethod:x,getPaymentMethodOrThrow:R,getPaymentMethodsMeta:F},paymentProviderCustomer:{getPaymentProviderCustomer:L,getPaymentProviderCustomerOrThrow:B},paymentStrategies:{isInitialized:j},shippingAddress:{getShippingAddress:U,getShippingAddressOrThrow:q,getShippingAddresses:V,getShippingAddressesOrThrow:G},shippingCountries:{getShippingCountries:H}}){return{getHost:Bg(c),getLocale:Bg(l),getCartLocale:Bg(r),getBillingAddress:Bg(e),getBillingAddressOrThrow:Bg(t),getCart:Bg(n),getCartOrThrow:Bg(i),getCheckout:Bg(o),getCheckoutOrThrow:Bg(a),getCountries:Bg(g),getStoreConfig:Bg(u),getStoreConfigOrThrow:Bg(h),getConfig:Bg(p),getConsignments:Bg(m),getConsignmentsOrThrow:Bg(y),getContextConfig:Bg(d),getCustomer:Bg(v),getCustomerOrThrow:Bg(f),getCardInstrument:Bg(S),getInstruments:Bg(w),getCardInstrumentOrThrow:Bg(_),getOrder:Bg(C),getOrderOrThrow:Bg(b),getOrderMeta:Bg(P),getInstrumentsMeta:Bg(I),getPaymentToken:O,getPaymentTokenOrThrow:E,getPaymentId:A,getPaymentIdOrThrow:T,getPaymentStatus:k,getPaymentStatusOrThrow:D,getPaymentRedirectUrl:M,getPaymentRedirectUrlOrThrow:z,getPaymentMethod:Bg(x),getPaymentMethodOrThrow:Bg(R),getPaymentMethodsMeta:Bg(F),getPaymentProviderCustomer:Bg(L),getPaymentProviderCustomerOrThrow:Bg(B),getShippingAddress:Bg(U),getShippingAddressOrThrow:Bg(q),getShippingAddresses:Bg(V),getShippingAddressesOrThrow:Bg(G),getShippingCountries:Bg(H),getOutstandingBalance:Bg(s),isPaymentDataRequired:N,isPaymentMethodInitialized:j}}var Ug,qg=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vg{constructor(e,t,n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S){this._store=e,this._storeProjectionFactory=t,this._checkoutActionCreator=n,this._checkoutValidator=i,this._hostedFormFactory=r,this._orderActionCreator=o,this._billingAddressActionCreator=a,this._consignmentActionCreator=s,this._paymentMethodActionCreator=d,this._paymentActionCreator=c,this._paymentHumanVerificationHandler=l,this._customerActionCreator=u,this._cartRequestSender=h,this._storeCreditActionCreator=p,this._couponActionCreator=m,this._spamProtectionActionCreator=y,this._paymentProviderCustomerActionCreator=g,this._shippingCountryActionCreator=v,this._remoteCheckoutActionCreator=f,this._paymentStrategyWidgetActionCreator=S,this._storeProjection=this._storeProjectionFactory.create(this._store)}createHostedForm(e,t){const n=this._storeProjection.getState().getCheckoutOrThrow().id;return this._hostedFormFactory.create(e,t,n)}subscribe(e,...t){return this._storeProjection.subscribe(e,...t)}getState(){return this._storeProjection.getState()}initializeOffsitePayment(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentActionCreator.initializeOffsitePayment(e)),this._storeProjection.getState()})}loadCheckout(e){return qg(this,void 0,void 0,function*(){return e?yield this._store.dispatch(this._checkoutActionCreator.loadCheckout(e)):yield this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),this._storeProjection.getState()})}loadDefaultCheckout(){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()),this._storeProjection.getState()})}loadPaymentMethod(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e,t)),this._storeProjection.getState()})}loadPaymentMethods(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethods(e)),this._storeProjection.getState()})}submitOrder(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._orderActionCreator.submitOrder(e,t)),this._storeProjection.getState()})}submitPayment(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentActionCreator.submitPayment(e)),this._storeProjection.getState()})}finalizeOrder(e){return qg(this,void 0,void 0,function*(){const{order:{getOrderOrThrow:t}}=this._store.getState();return yield this._store.dispatch(this._orderActionCreator.finalizeOrder(t().orderId,e)),this._storeProjection.getState()})}updateBillingAddress(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(e)),this._storeProjection.getState()})}updateShippingAddress(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.updateAddress(e)),this._storeProjection.getState()})}selectShippingOption(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t)),this._storeProjection.getState()})}signInCustomer(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._customerActionCreator.signInCustomer(e,t)),this._storeProjection.getState()})}signOutCustomer(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._customerActionCreator.signOutCustomer(e)),this._storeProjection.getState()})}createBuyNowCart(e,t){return qg(this,void 0,void 0,function*(){const{body:n}=yield this._cartRequestSender.createBuyNowCart(e,t);return n})}applyStoreCredit(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(e,t)),this._storeProjection.getState()})}applyCoupon(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._couponActionCreator.applyCoupon(e,t)),this._storeProjection.getState()})}removeCoupon(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._couponActionCreator.removeCoupon(e,t)),this._storeProjection.getState()})}verifyCheckoutSpamProtection(){return qg(this,void 0,void 0,function*(){const{checkout:e}=this._store.getState(),{shouldExecuteSpamCheck:t}=e.getCheckoutOrThrow();return t&&(yield this._store.dispatch(this._spamProtectionActionCreator.verifyCheckoutSpamProtection())),this._storeProjection.getState()})}loadCurrentOrder(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._orderActionCreator.loadCurrentOrder(e)),this._storeProjection.getState()})}updatePaymentProviderCustomer(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(e)),this._storeProjection.getState()})}loadShippingCountries(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._shippingCountryActionCreator.loadCountries(e)),this._storeProjection.getState()})}deleteConsignment(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.deleteConsignment(e,t)),this._storeProjection.getState()})}initializePayment(e,t,n){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.initializePayment(e,t,n)),this._storeProjection.getState()})}forgetCheckout(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.forgetCheckout(e,t)),this._storeProjection.getState()})}remoteCheckoutSignOut(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.signOut(e,t)),this._storeProjection.getState()})}validateCheckout(e,t){return qg(this,void 0,void 0,function*(){yield this._checkoutValidator.validate(e,t)})}handlePaymentHumanVerification(e,t){return qg(this,void 0,void 0,function*(){return"string"==typeof e?this._paymentHumanVerificationHandler.handle(e,null!=t?t:""):this._paymentHumanVerificationHandler.handle(e)})}widgetInteraction(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentStrategyWidgetActionCreator.widgetInteraction(e),{queueId:"widgetInteraction"}),this._storeProjection.getState()})}}class Gg{constructor(e){this._transformSelectors=e}create(e){return mt(e,this._transformSelectors)}}function Hg(e,t){const{config:{getHost:i,getLocale:r}}=e.getState();t||(t=n({host:i()}));const a=new Gg(jg),s=new nn(new en(t),new bt(new Tt(t)),new on(new an(t))),d=new ny(new en(t)),c=new Iy(e),l=new Vm(new jm(t),new ny(new en(t))),u=new st(new ut(t),new Ng(new xg(t))),h=new Cg(new Pg(t),new en(t)),p=new Wm(new $m(t)),m=new Cy(new by(Gm(e)),l,new Gy,new cy(Sn(o()))),y=new cy(Sn(o())),g=new Kt(new Jt(t),s,new pn(Sn(o()),new _n(t))),v=new Dg(new Mg(t)),f=new Dt(new Lt(t)),S=Sn(o()),_=new _n(t),w=new pn(S,_),I=new fg(t),C=new Sg,b=new Ag(new Tg(t,{locale:r()}),e),P=new wg(new Ig(t),s),O=new Qm;return new Vg(e,a,s,d,c,l,u,h,p,m,y,g,I,v,f,w,C,b,P,O)}!function(e){e.LoadInstrumentsRequested="LOAD_INSTRUMENTS_REQUESTED",e.LoadInstrumentsSucceeded="LOAD_INSTRUMENTS_SUCCEEDED",e.LoadInstrumentsFailed="LOAD_INSTRUMENTS_FAILED",e.DeleteInstrumentRequested="DELETE_INSTRUMENT_REQUESTED",e.DeleteInstrumentSucceeded="DELETE_INSTRUMENT_SUCCEEDED",e.DeleteInstrumentFailed="DELETE_INSTRUMENT_FAILED"}(Ug||(Ug={}));class Wg{constructor(e){this._instrumentRequestSender=e}loadInstruments(){return e=>m.create(t=>{t.next(l(Ug.LoadInstrumentsRequested));const n=this._getSessionContext(e),i=this._getCurrentAccessToken(e),r=this._getShippingAddress(e);return this._getValidAccessToken(i).then(e=>this._instrumentRequestSender.loadInstruments(Object.assign(Object.assign({},n),{authToken:e.vaultAccessToken}),r).then(({body:n})=>{t.next(l(Ug.LoadInstrumentsSucceeded,n,e)),t.complete()})).catch(e=>{t.error(h(Ug.LoadInstrumentsFailed,e))})})}deleteInstrument(e){return t=>m.create(n=>{n.next(l(Ug.DeleteInstrumentRequested,void 0,{instrumentId:e}));const i=this._getSessionContext(t),r=this._getCurrentAccessToken(t);return this._getValidAccessToken(r).then(t=>this._instrumentRequestSender.deleteInstrument(Object.assign(Object.assign({},i),{authToken:t.vaultAccessToken}),e).then(({body:i})=>{n.next(l(Ug.DeleteInstrumentSucceeded,i,Object.assign({instrumentId:e},t))),n.complete()})).catch(t=>{n.error(h(Ug.DeleteInstrumentFailed,t,{instrumentId:e}))})})}_isValidVaultAccessToken(e){if(!e||!e.vaultAccessToken)return!1;return function(e){const t=new Date(e.getTime());return t.setMinutes(e.getMinutes()+2),t}(new Date(e.vaultAccessExpiry)).valueOf()>Date.now()}_getCurrentAccessToken(e){const{instruments:t}=e.getState(),n=t.getInstrumentsMeta();if(n)return{vaultAccessToken:n.vaultAccessToken,vaultAccessExpiry:n.vaultAccessExpiry}}_getValidAccessToken(e){return e&&this._isValidVaultAccessToken(e)?Promise.resolve(e):this._instrumentRequestSender.getVaultAccessToken().then(({body:e})=>e)}_getShippingAddress(e){const t=e.getState(),n=t.shippingAddress.getShippingAddresses();return n.length>1?n:t.shippingAddress.getShippingAddress()}_getSessionContext(e){const t=e.getState(),n=t.config.getStoreConfig(),i=t.cart.getCart();if(!n)throw new rt(et.MissingCheckoutConfig);if(!i)throw new rt(et.MissingCart);const{customerId:r}=i,{storeId:o}=n.storeProfile,{code:a}=n.shopperCurrency.isTransactional?n.shopperCurrency:n.currency;return{customerId:r,storeId:o,currencyCode:a}}}var $g,Yg,Kg=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rthis._isPayPalInstrument(e)?function(e){return{bigpayToken:e.bigpay_token,defaultInstrument:e.default_instrument,provider:e.provider,externalId:e.external_id,trustedShippingAddress:e.trusted_shipping_address,method:"paypal",type:"account"}}(e):this._isBankInstrument(e)?function(e){return{bigpayToken:e.bigpay_token,defaultInstrument:e.default_instrument,provider:e.provider,trustedShippingAddress:e.trusted_shipping_address,accountNumber:e.account_number,issuer:e.issuer,iban:e.iban,method:e.method,type:"bank"}}(e):function(e){return{bigpayToken:e.bigpay_token,defaultInstrument:e.default_instrument,provider:e.provider,iin:e.iin,last4:e.last_4,expiryMonth:e.expiry_month,expiryYear:e.expiry_year,brand:e.brand,trustedShippingAddress:e.trusted_shipping_address,untrustedShippingCardVerificationMode:e.untrusted_shipping_address_card_verification_mode,method:e.method,type:"card"}}(e))}_isPayPalInstrument(e){return"paypal"===e.method_type}_isBankInstrument(e){return"bank"===e.method_type}_transformResponse(e){const{data:t}=e,n=Kg(e,["data"]);return Object.assign(Object.assign({},n),{body:t})}}class Zg{constructor(e,t){this._client=e,this._requestSender=t,this._transformer=new Jg}getVaultAccessToken({timeout:e}={}){return this._requestSender.get("/internalapi/v1/checkout/payments/vault-access-token",{timeout:e}).then(e=>Object.assign(Object.assign({},e),{body:{vaultAccessToken:e.body.data.token,vaultAccessExpiry:e.body.data.expires_at}}))}loadInstruments(e,t){return t?this._loadInstrumentsWithAddress(e,t):this._loadInstruments(e)}deleteInstrument(e,t){const n=Object.assign(Object.assign({},e),{instrumentId:t});return new Promise((e,t)=>{this._client.deleteShopperInstrument(n,(n,i)=>n?t(this._transformer.transformErrorResponse(n)):e(this._transformer.transformResponse(i)))})}_loadInstruments(e){return new Promise((t,n)=>{this._client.loadInstruments(e,(e,i)=>e?n(this._transformer.transformErrorResponse(e)):t(this._transformer.transformResponse(i)))})}_loadInstrumentsWithAddress(e,t){const n=Object.assign(Object.assign({},e),{shippingAddress:Array.isArray(t)?t.map(e=>Py(e)):Py(t)});return new Promise((e,t)=>{this._client.loadInstrumentsWithAddress(n,(n,i)=>n?t(this._transformer.transformErrorResponse(n)):e(this._transformer.transformResponse(i)))})}}!function(e){e.LoadPickupOptionsRequested="LOAD_PICKUP_OPTIONS_REQUESTED",e.LoadPickupOptionsSucceeded="LOAD_PICKUP_OPTIONS_SUCCEEDED",e.LoadPickupOptionsFailed="LOAD_PICKUP_OPTIONS_FAILED"}($g||($g={}));class Qg{constructor(e){this._pickupOptionRequestSender=e}loadPickupOptions(e){return t=>new m(n=>{const i=this._hydrateApiQuery(t,e);n.next(l($g.LoadPickupOptionsRequested)),this._pickupOptionRequestSender.fetchPickupOptions(i).then(t=>{n.next(l($g.LoadPickupOptionsSucceeded,t.body.results,e)),n.complete()}).catch(e=>{n.error(h($g.LoadPickupOptionsFailed,e))})})}_hydrateApiQuery(e,t){const n=e.getState(),i=n.cart.getCartOrThrow();if(!i)throw new rt(et.MissingCart);const r=n.consignments.getConsignmentById(t.consignmentId);if(!r)throw new rt(et.MissingConsignments);const o=r.lineItemIds,a=i.lineItems.physicalItems.filter(e=>H(o,e.id)).map(e=>({variantId:e.variantId,quantity:e.quantity}));return{searchArea:t.searchArea,items:a}}}class Xg{constructor(e){this._requestSender=e}fetchPickupOptions(e){return this._requestSender.post("/api/storefront/pickup-options",{headers:Object.assign({Accept:ct.Json},Xe),body:e})}}!function(e){e.UpdateAddressFailed="SHIPPING_STRATEGY_UPDATE_ADDRESS_FAILED",e.UpdateAddressRequested="SHIPPING_STRATEGY_UPDATE_ADDRESS_REQUESTED",e.UpdateAddressSucceeded="SHIPPING_STRATEGY_UPDATE_ADDRESS_SUCCEEDED",e.SelectOptionFailed="SHIPPING_STRATEGY_SELECT_OPTION_FAILED",e.SelectOptionRequested="SHIPPING_STRATEGY_SELECT_OPTION_REQUESTED",e.SelectOptionSucceeded="SHIPPING_STRATEGY_SELECT_OPTION_SUCCEEDED",e.InitializeFailed="SHIPPING_STRATEGY_INITIALIZE_FAILED",e.InitializeRequested="SHIPPING_STRATEGY_INITIALIZE_REQUESTED",e.InitializeSucceeded="SHIPPING_STRATEGY_INITIALIZE_SUCCEEDED",e.DeinitializeFailed="SHIPPING_STRATEGY_DEINITIALIZE_FAILED",e.DeinitializeRequested="SHIPPING_STRATEGY_DEINITIALIZE_REQUESTED",e.DeinitializeSucceeded="SHIPPING_STRATEGY_DEINITIALIZE_SUCCEEDED",e.WidgetInteractionStarted="SHIPPING_STRATEGY_WIDGET_INTERACTION_STARTED",e.WidgetInteractionFinished="SHIPPING_STRATEGY_WIDGET_INTERACTION_FINISHED",e.WidgetInteractionFailed="SHIPPING_STRATEGY_WIDGET_INTERACTION_FAILED"}(Yg||(Yg={}));class ev{constructor(e){this._strategyRegistry=e}updateAddress(e,t){return n=>m.create(i=>{const r=n.getState().payment.getPaymentId(),o=t&&t.methodId||r&&r.providerId;i.next(l(Yg.UpdateAddressRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).updateAddress(e,Object.assign(Object.assign({},t),{methodId:o})).then(()=>{i.next(l(Yg.UpdateAddressSucceeded,void 0,{methodId:o})),i.complete()}).catch(e=>{i.error(h(Yg.UpdateAddressFailed,e,{methodId:o}))})})}selectOption(e,t){return n=>m.create(i=>{const r=n.getState().payment.getPaymentId(),o=t&&t.methodId||r&&r.providerId;i.next(l(Yg.SelectOptionRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).selectOption(e,Object.assign(Object.assign({},t),{methodId:o})).then(()=>{i.next(l(Yg.SelectOptionSucceeded,void 0,{methodId:o})),i.complete()}).catch(e=>{i.error(h(Yg.SelectOptionFailed,e,{methodId:o}))})})}initialize(e){return t=>m.create(n=>{const i=t.getState(),r=i.payment.getPaymentId(),o=e&&e.methodId||r&&r.providerId,a=Object.assign(Object.assign({},e),{methodId:o});if(o&&i.shippingStrategies.isInitialized(o))return n.complete();n.next(l(Yg.InitializeRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).initialize(a).then(()=>{n.next(l(Yg.InitializeSucceeded,void 0,{methodId:o})),n.complete()}).catch(e=>{n.error(h(Yg.InitializeFailed,e,{methodId:o}))})})}deinitialize(e){return t=>m.create(n=>{const i=t.getState(),r=i.payment.getPaymentId(),o=e&&e.methodId||r&&r.providerId;if(o&&!i.shippingStrategies.isInitialized(o))return n.complete();n.next(l(Yg.DeinitializeRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).deinitialize(Object.assign(Object.assign({},e),{methodId:o})).then(()=>{n.next(l(Yg.DeinitializeSucceeded,void 0,{methodId:o})),n.complete()}).catch(e=>{n.error(h(Yg.DeinitializeFailed,e,{methodId:o}))})})}widgetInteraction(e,t){return m.create(n=>{const i={methodId:t&&t.methodId};n.next(l(Yg.WidgetInteractionStarted,void 0,i)),e().then(()=>{n.next(l(Yg.WidgetInteractionFinished,void 0,i)),n.complete()}).catch(e=>{n.error(h(Yg.WidgetInteractionFailed,e,i))})})}}var tv,nv=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class iv{constructor(e,t,n,i,r){this._store=e,this._consignmentActionCreator=t,this._paymentMethodActionCreator=n,this._amazonPayV2PaymentProcessor=i,this._shippingStrategyActionCreator=r}updateAddress(e,t){const n=this._store.getState().shippingAddress.getShippingAddress();if(!n)throw new rt(et.MissingShippingAddress);const i=Object.assign(Object.assign({},n),{customFields:e.customFields});return this._store.dispatch(this._consignmentActionCreator.updateAddress(i,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(e){return nv(this,void 0,void 0,function*(){const{amazonpay:t,methodId:n}=e;if(!t||!n)throw new qt('Unable to proceed because "options.amazonpay" argument is not provided.');const i=(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n))).paymentMethods.getPaymentMethodOrThrow(n);yield this._amazonPayV2PaymentProcessor.initialize(i);const{paymentToken:r,region:o}=i.initializationData,a=t.editAddressButtonId;if(r&&a){const e=this._shouldShowLoadingSpinner(o);this._bindEditButton(a,r,"changeAddress",e)}return this._store.getState()})}deinitialize(){return nv(this,void 0,void 0,function*(){return yield this._amazonPayV2PaymentProcessor.deinitialize(),Promise.resolve(this._store.getState())})}_bindEditButton(e,t,n,i){const r=document.getElementById(e);if(r&&r.parentNode){if(i){const e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener("click",()=>this._showLoadingSpinner())}this._amazonPayV2PaymentProcessor.bindButton(e,t,n)}}_showLoadingSpinner(){return this._store.dispatch(this._shippingStrategyActionCreator.widgetInteraction(()=>new Promise(I)),{queueId:"widgetInteraction"})}_shouldShowLoadingSpinner(e){return"us"!==e}}!function(e){e.CVV="cvv",e.PAN="pan"}(tv||(tv={}));var rv=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ov{constructor(e,t,n,i,r,o){this._store=e,this._billingAddressActionCreator=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=i,this._paymentProviderCustomerActionCreator=r,this._braintreeIntegrationService=o}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}deinitialize(){return Promise.resolve(this._store.getState())}initialize(e){var t;return rv(this,void 0,void 0,function*(){const{methodId:n,braintreefastlane:i,fastlane:r}=e||{},o=r||i,{onPayPalFastlaneAddressChange:a}=o||{};if(!n)throw new qt('Unable to proceed because "methodId" argument is not provided.');const s=this._store.getState();if(!s.customer.getCustomerOrThrow().isGuest)return Promise.resolve(this._store.getState());try{if(this._shouldRunAuthenticationFlow()){const e=s.paymentMethods.getPaymentMethod(n),{clientToken:i,isFastlaneStylingEnabled:r}=(null==e?void 0:e.initializationData)||{};i||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n)));const a=Ao(r?null===(t=null==e?void 0:e.initializationData)||void 0===t?void 0:t.fastlaneStyles:void 0,null==o?void 0:o.styles);yield this._runAuthenticationFlowOrThrow(n,a)}"function"==typeof a&&(yield this._shouldUseBraintreeFastlaneShippingComponent(n))&&a(()=>this._handleBraintreeFastlaneShippingAddressChange())}catch(e){}return Promise.resolve(this._store.getState())})}_shouldRunAuthenticationFlow(){var e;const t=this._store.getState(),n=null===(e=t.cart.getCart())||void 0===e?void 0:e.id,i=Fr.get("bc-fastlane-sessionId")||"",r=t.paymentProviderCustomer.getPaymentProviderCustomer(),o=xl(r)?r:{};return(null==o?void 0:o.authenticationState)!==Mi.CANCELED&&!(null==o?void 0:o.authenticationState)&&i===n}_runAuthenticationFlowOrThrow(e,t){var n,i;return rv(this,void 0,void 0,function*(){const r=this._store.getState(),o=r.cart.getCartOrThrow(),a=r.countries.getCountries()||[],s=r.paymentMethods.getPaymentMethodOrThrow(e),{clientToken:d,config:c}=s;if(!d)throw new rt(et.MissingPaymentMethod);this._braintreeIntegrationService.initialize(d);const l=yield this._braintreeIntegrationService.getBraintreeFastlane(null==o?void 0:o.id,null==c?void 0:c.testMode,t),u=(null===(n=r.customer.getCustomer())||void 0===n?void 0:n.email)||(null===(i=r.billingAddress.getBillingAddress())||void 0===i?void 0:i.email);if(!u)return;const{lookupCustomerByEmail:h,triggerAuthenticationFlow:p}=l.identity,{customerContextId:m}=yield h(u);if(!m)return;const{authenticationState:y,profileData:g}=yield p(m);if(y===Mi.CANCELED)return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:y,addresses:[],instruments:[]})),void Fr.remove("bc-fastlane-sessionId");const v=this._getPayPalBillingAddress(g),f=g.shippingAddress,S=g.shippingAddress.phoneNumber,_=this._mapPayPalToBcAddress(f,a,S),w=this._mapPayPalToBcAddress(v,a,S);if(w&&_){const t=this._mergeShippingAndBillingAddresses(_,w),n=this._mapPayPalToBcInstrument(e,g.card),i=n?[n]:[];yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:y,addresses:t,instruments:i})),w&&(yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(Object.assign(Object.assign({},w),{id:String(w.id)})))),_&&o.lineItems.physicalItems.length>0&&(yield this._store.dispatch(this._consignmentActionCreator.updateAddress(_)))}})}_getPayPalBillingAddress(e){const{name:t,card:n}=e,i=n.paymentSource.card.billingAddress;return Object.assign(Object.assign({},i),{firstName:i.firstName||(null==t?void 0:t.firstName),lastName:i.lastName||(null==t?void 0:t.lastName)})}_getCountryNameByCountryCode(e,t){const n=t.find(t=>t.code===e);return(null==n?void 0:n.name)||""}_mapPayPalToBcAddress(e,t,n,i){return{id:Number(Date.now()),type:"paypal-address",firstName:e.firstName||"",lastName:e.lastName||"",company:e.company||"",address1:e.streetAddress,address2:e.extendedAddress||"",city:e.locality,stateOrProvince:e.region,stateOrProvinceCode:e.region,country:this._getCountryNameByCountryCode(e.countryCodeAlpha2,t),countryCode:e.countryCodeAlpha2,postalCode:e.postalCode,phone:n||"",customFields:i||[]}}_normalizeAddress(e){return le(e,["id"])}_mergeShippingAndBillingAddresses(e,t){return Y(this._normalizeAddress(e),this._normalizeAddress(t))?[e]:[e,t]}_mapPayPalToBcInstrument(e,t){if(!t)return;const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a}=i.card,[s,d]=o.split("-");return{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:tv.CVV,type:"card"}}_handleBraintreeFastlaneShippingAddressChange(){var e;return rv(this,void 0,void 0,function*(){const t=this._store.getState().countries.getCountries()||[],n=yield this._braintreeIntegrationService.getBraintreeFastlane(),{selectionChanged:i,selectedAddress:r}=yield n.profile.showShippingAddressSelector();if(i){const n=this._store.getState(),i=n.shippingAddress.getShippingAddressesOrThrow(),o=n.paymentProviderCustomer.getPaymentProviderCustomer(),a=xl(o)?o:{},s=this._mapPayPalToBcAddress(r,t,r.phoneNumber,null===(e=i[0])||void 0===e?void 0:e.customFields);if(s){const e=this._filterAddresses([s,...a.addresses||[]]);return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(Object.assign(Object.assign({},a),{addresses:e}))),yield this._store.dispatch(this._consignmentActionCreator.updateAddress(s)),s}}})}_filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this._isEqualAddresses(e,t))?e:[...e,t]:e,[])}_isEqualAddresses(e,t){return Y(this._normalizeAddress(e),this._normalizeAddress(t))}_shouldUseBraintreeFastlaneShippingComponent(e){var t;return rv(this,void 0,void 0,function*(){const n=this._store.getState().paymentProviderCustomer.getPaymentProviderCustomer(),i=xl(n)?n:{};if(i&&(null==i?void 0:i.authenticationState)!==Mi.CANCELED){const n=yield this._getBraintreePaymentMethodOrThrow(e);return!!(null===(t=null==n?void 0:n.initializationData)||void 0===t?void 0:t.isFastlaneEnabled)}return!1})}_getBraintreePaymentMethodOrThrow(e){return rv(this,void 0,void 0,function*(){const t=this._store.getState().paymentMethods.getPaymentMethod(e);return t||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e))).paymentMethods.getPaymentMethodOrThrow(e)})}}class av{constructor(e,t){this._store=e,this._consignmentActionCreator=t}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(){return Promise.resolve(this._store.getState())}deinitialize(){return Promise.resolve(this._store.getState())}}var sv=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class dv{constructor(e,t,n,i,r,o,a){this._store=e,this._billingAddressActionCreator=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=i,this._paymentProviderCustomerActionCreator=r,this._paypalSdkScriptLoader=o,this._paypalCommerceFastlaneUtils=a}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}deinitialize(){return Promise.resolve(this._store.getState())}initialize(e){return sv(this,void 0,void 0,function*(){const{methodId:t,paypalcommercefastlane:n,fastlane:i}=e||{},r=i||n,{onPayPalFastlaneAddressChange:o,styles:a}=r||{};if(!t)throw new qt('Unable to proceed because "methodId" argument is not provided.');const s=this._store.getState().customer.getCustomerOrThrow();if(!(null==s?void 0:s.isGuest))return Promise.resolve(this._store.getState());try{this._shouldAuthenticateUserWithFastlane()&&(yield this._initializePayPalSdk(t,a),yield this._authenticateUserWithFastlaneOtp(t)),"function"==typeof o&&this._shouldUsePayPalFastlaneShippingComponent()&&(yield this._initializePayPalSdk(t,a),o(()=>this._handlePayPalShippingAddressChange()))}catch(e){}return Promise.resolve(this._store.getState())})}_getPayPalPaymentMethodOrThrow(e){return sv(this,void 0,void 0,function*(){const t=this._store.getState().paymentMethods.getPaymentMethod(e);return t||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e))).paymentMethods.getPaymentMethodOrThrow(e)})}_getPayPalCustomerAuthenticationState(){const e=this._store.getState().paymentProviderCustomer.getPaymentProviderCustomerOrThrow();var t;return((t=e)&&("authenticationState"in t||"addresses"in t||"instruments"in t)?e:{}).authenticationState}_shouldAuthenticateUserWithFastlane(){const e=this._store.getState().cart.getCartOrThrow(),t=this._paypalCommerceFastlaneUtils.getStorageSessionId();return!this._getPayPalCustomerAuthenticationState()&&t===e.id}_shouldUsePayPalFastlaneShippingComponent(){const e=this._getPayPalCustomerAuthenticationState();return!!e&&e!==fs.CANCELED}_initializePayPalSdk(e,t){var n;return sv(this,void 0,void 0,function*(){const i=this._store.getState().cart.getCartOrThrow(),r=yield this._getPayPalPaymentMethodOrThrow(e),{isDeveloperModeApplicable:o,isFastlaneStylingEnabled:a}=(null==r?void 0:r.initializationData)||{},s=!!o,d=rd(a?null===(n=null==r?void 0:r.initializationData)||void 0===n?void 0:n.fastlaneStyles:{},t),c=yield this._paypalSdkScriptLoader.getPayPalFastlaneSdk(r,i.currency.code,i.id,i.locale);yield this._paypalCommerceFastlaneUtils.initializePayPalFastlane(c,s,d)})}_authenticateUserWithFastlaneOtp(e){var t,n;return sv(this,void 0,void 0,function*(){const i=this._store.getState(),r=i.cart.getCartOrThrow(),o=null===(t=i.customer.getCustomer())||void 0===t?void 0:t.email,a=null===(n=i.billingAddress.getBillingAddress())||void 0===n?void 0:n.email,s=o||a||"",{customerContextId:d}=yield this._paypalCommerceFastlaneUtils.lookupCustomerOrThrow(s),c=yield this._paypalCommerceFastlaneUtils.triggerAuthenticationFlowOrThrow(d),{authenticationState:l,addresses:u,billingAddress:h,shippingAddress:p,instruments:m}=this._paypalCommerceFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,c);yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:l,addresses:u,instruments:m})),c.authenticationState===fs.CANCELED?this._paypalCommerceFastlaneUtils.removeStorageSessionId():this._paypalCommerceFastlaneUtils.updateStorageSessionId(r.id),h&&(yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(Object.assign(Object.assign({},h),{id:String(h.id)})))),p&&r.lineItems.physicalItems.length>0&&(yield this._store.dispatch(this._consignmentActionCreator.updateAddress(p)))})}_handlePayPalShippingAddressChange(){var e;return sv(this,void 0,void 0,function*(){const t=this._paypalCommerceFastlaneUtils.getPayPalFastlaneOrThrow(),{selectionChanged:n,selectedAddress:i}=yield t.profile.showShippingAddressSelector();if(n){const t=this._store.getState(),n=t.shippingAddress.getShippingAddressesOrThrow(),r=t.paymentProviderCustomer.getPaymentProviderCustomer(),o=vp(r)?r:{},a=this._paypalCommerceFastlaneUtils.mapPayPalToBcAddress(i.address,i.name,i.phoneNumber,null===(e=n[0])||void 0===e?void 0:e.customFields),s=this._paypalCommerceFastlaneUtils.filterAddresses([a,...o.addresses||[]]);return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(Object.assign(Object.assign({},o),{addresses:s}))),yield this._store.dispatch(this._consignmentActionCreator.updateAddress(a)),a}})}}var cv;class lv{constructor(e,t,n,i){this._store=e,this._stripeScriptLoader=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=i}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(e){return t=this,n=void 0,r=function*(){if(!e.stripeupe)throw new qt('Unable to proceed because "options" argument is not provided.');const{container:t,gatewayId:n,methodId:i,onChangeShipping:r,getStyles:o,availableCountries:a,getStripeState:s}=e.stripeupe;Object.entries(e.stripeupe).forEach(([e,t])=>{if(!t)throw new qt(`Unable to proceed because "${e}" argument is not provided.`)});const d=yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n,{params:{method:i}})),c=d.paymentMethods.getPaymentMethodOrThrow(i,n),{initializationData:l}=c;if(!c||!c.initializationData.stripePublishableKey||!c.clientToken)throw new rt(et.MissingPaymentMethod);let u;this._stripeUPEClient=yield this._stripeScriptLoader.getStripeClient(l,d.cart.getLocale(),ka.V3,Fa,La);const h=o&&o(),{form:{getShippingAddressFields:p},shippingAddress:{getShippingAddress:m}}=this._store.getState(),y=p([],"");u=h?{variables:{colorPrimary:h.fieldInnerShadow,colorBackground:h.fieldBackground,colorText:h.labelText,colorDanger:h.fieldErrorText,colorTextSecondary:h.labelText,colorTextPlaceholder:h.fieldPlaceholderText,spacingUnit:"4px",borderRadius:"4px"},rules:{".Input":{borderColor:h.fieldBorder,color:h.fieldText,boxShadow:h.fieldInnerShadow}}}:{variables:{spacingUnit:"4px",borderRadius:"4px"}},this._stripeElements=yield this._stripeScriptLoader.getElements(this._stripeUPEClient,{clientSecret:c.clientToken,appearance:u});const g=m(),v=y.find(e=>"phone"===e.name);let f={mode:Ca.SHIPPING,allowedCountries:[a],fields:{phone:"always"},validation:{phone:{required:v&&v.required?"always":"never"}},display:{name:ba.SPLIT}};if(g){const{stateOrProvinceCode:e,countryCode:t,lastName:n,firstName:i,phone:r,address1:o,address2:a,city:d,postalCode:c}=g,l=e&&t?s(t,e):e;f=Object.assign(Object.assign({},f),{defaultValues:{firstName:i,lastName:n,phone:r,address:{line1:o,line2:a,city:d,state:l,postal_code:c,country:t}}})}let S=this._stripeElements.getElement(Da.SHIPPING);return S&&S.destroy(),S=this._stripeElements.create(Da.SHIPPING,f),S.on(za.CHANGE,e=>{if(!("isNewAddress"in e))throw new rt(et.MissingShippingAddress);(e.complete||e.isNewAddress)&&(this.sendData&&clearTimeout(this.sendData),this.sendData=setTimeout(()=>{r(Object.assign(Object.assign({},e),{phoneFieldRequired:!!v&&v.required}))},1e3))}),S.mount(`#${t}`),Promise.resolve(this._store.getState())},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}deinitialize(){return Promise.resolve(this._store.getState())}}!function(e){e.SendSignInEmailRequested="SEND_SIGNIN_EMAIL_REQUESTED",e.SendSignInEmailSucceeded="SEND_SIGNIN_EMAIL_SUCCEEDED",e.SendSignInEmailFailed="SEND_SIGNIN_EMAIL_FAILED"}(cv||(cv={}));class uv{constructor(e){this._requestSender=e}sendSignInEmail(e,t){return g(C(l(cv.SendSignInEmailRequested)),v(()=>{return n=this,i=void 0,o=function*(){const{body:n}=yield this._requestSender.sendSignInEmail(e,t);return l(cv.SendSignInEmailSucceeded,n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Je(cv.SendSignInEmailFailed,e)))}}class hv{constructor(e){this._requestSender=e}sendSignInEmail({email:e,redirectUrl:t},{timeout:n}={}){const i=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post("/login.php?action=passwordless_login",{body:{email:e,redirect_url:t||In(window.top?window.top.location.href:"").pathname},headers:i,timeout:n})}}class pv{constructor(e){this._messageCustomizer=e}transform(e){var t;return e.message=(t=this._messageCustomizer(e))?t.split(/(?:\r\n|\n|\r)/).map(e=>e.replace(/^\s+/gm,"")).join(" ").trim():"",e}}let mv=class{constructor(e,t,n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,_,w,I,C,b,P,O,E,A){this._store=e,this._storeProjection=t,this._extensionMessenger=n,this._extensionEventBroadcaster=i,this._b2bTokenActionCreator=r,this._billingAddressActionCreator=o,this._checkoutActionCreator=a,this._configActionCreator=s,this._customerActionCreator=d,this._consignmentActionCreator=c,this._countryActionCreator=l,this._couponActionCreator=u,this._customerStrategyActionCreator=h,this._errorActionCreator=p,this._giftCertificateActionCreator=m,this._instrumentActionCreator=y,this._orderActionCreator=g,this._paymentMethodActionCreator=v,this._paymentStrategyActionCreator=f,this._pickupOptionActionCreator=S,this._shippingCountryActionCreator=_,this._shippingStrategyActionCreator=w,this._signInEmailActionCreator=I,this._spamProtectionActionCreator=C,this._storeCreditActionCreator=b,this._subscriptionsActionCreator=P,this._formFieldsActionCreator=O,this._extensionActionCreator=E,this._workerExtensionMessenger=A,this._errorTransformer=function(e="development"===vt()){return new pv(t=>{if(!e||!function(e){return!(!e.subtype&&!e.type)}(t))return t.message;switch(t.subtype||t.type){case et.MissingConsignments:return`\n ${t.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 `;case et.MissingCart:case et.MissingCheckout:return`\n ${t.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 `;case et.MissingCheckoutConfig:return`\n ${t.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 `;case et.MissingOrder:return`\n ${t.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 `;case et.MissingOrderId:return`\n ${t.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 `;case et.MissingPaymentMethod:return`\n ${t.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 `;case cn.CustomerNotInitialized: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 ";case cn.PaymentNotInitialized:return`\n ${t.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 `;case cn.ShippingNotInitialized:return`\n ${t.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 `;default:return t.message}})}()}getState(){return this._storeProjection.getState()}notifyState(){this._storeProjection.notifyState()}subscribe(e,...t){return this._storeProjection.subscribe(e,...t)}hydrateInitialState(e){return this._dispatch(this._checkoutActionCreator.hydrateInitialState(e))}loadCheckout(e,t){return this._dispatch(e?this._checkoutActionCreator.loadCheckout(e,t):this._checkoutActionCreator.loadDefaultCheckout(t))}updateCheckout(e,t){const n=this._checkoutActionCreator.updateCheckout(e,t);return this._dispatch(n)}loadOrder(e,t){const n=this._orderActionCreator.loadOrder(e,t),i=this._formFieldsActionCreator.loadFormFields(t),r=this._configActionCreator.loadConfig(t);return Promise.all([this._dispatch(n),this._dispatch(r,{queueId:"config"}),this._dispatch(i,{queueId:"formFields"})]).then(()=>this.getState())}submitOrder(e,t){const n=this._paymentStrategyActionCreator.execute(e,t);return this._dispatch(n,{queueId:"paymentStrategy"})}finalizeOrderIfNeeded(e){const t=this._paymentStrategyActionCreator.finalize(e);return this._dispatch(t,{queueId:"paymentStrategy"})}loadPaymentMethods(e){const t=this._paymentMethodActionCreator.loadPaymentMethods(e);return this._dispatch(t,{queueId:"paymentMethods"})}loadPaymentMethodByIds(e,t){const n=this._paymentMethodActionCreator.loadPaymentMethodsById(e,t);return this._dispatch(n,{queueId:"paymentMethods"})}loadPaymentMethod(e,t){const n=this._paymentMethodActionCreator.loadPaymentMethod(e,t);return this._dispatch(n,{queueId:"paymentMethods"})}initializePayment(e){const t=this._paymentStrategyActionCreator.initialize(e);return this._dispatch(t,{queueId:"paymentStrategy"})}deinitializePayment(e){const t=this._paymentStrategyActionCreator.deinitialize(e);return this._dispatch(t,{queueId:"paymentStrategy"})}loadBillingCountries(e){const t=this._countryActionCreator.loadCountries(e);return this._dispatch(t,{queueId:"billingCountries"})}loadShippingCountries(e){const t=this._shippingCountryActionCreator.loadCountries(e);return this._dispatch(t,{queueId:"shippingCountries"})}loadPickupOptions(e){const t=this._pickupOptionActionCreator.loadPickupOptions(e);return this._dispatch(t,{queueId:"pickupOptions"})}loadBillingAddressFields(e){return this.loadBillingCountries(e)}loadShippingAddressFields(e){return this.loadShippingCountries(e)}initializeCustomer(e){const t=this._customerStrategyActionCreator.initialize(e);return this._dispatch(t,{queueId:"customerStrategy"})}deinitializeCustomer(e){const t=this._customerStrategyActionCreator.deinitialize(e);return this._dispatch(t,{queueId:"customerStrategy"})}sendSignInEmail(e,t){const n=this._signInEmailActionCreator.sendSignInEmail(e,t);return this._dispatch(n,{queueId:"signInEmail"})}getB2BToken(e){const t=this._b2bTokenActionCreator.loadB2BToken(e);return this._dispatch(t,{queueId:"b2bToken"})}createCustomerAccount(e,t){const n=this._customerActionCreator.createCustomer(e,t);return this._dispatch(n)}createCustomerAddress(e,t){const n=this._customerActionCreator.createAddress(e,t);return this._dispatch(n)}updateSubscriptions(e,t){const n=this._subscriptionsActionCreator.updateSubscriptions(e,t);return this._dispatch(n,{queueId:"subscriptions"})}continueAsGuest(e,t){const n=this._billingAddressActionCreator.continueAsGuest(e,t);return this._dispatch(n)}signInCustomer(e,t){const n=this._customerStrategyActionCreator.signIn(e,t);return this._dispatch(n,{queueId:"customerStrategy"})}signOutCustomer(e){const t=this._customerStrategyActionCreator.signOut(e);return this._dispatch(t,{queueId:"customerStrategy"})}executePaymentMethodCheckout(e){const t=this._customerStrategyActionCreator.executePaymentMethodCheckout(e);return this._dispatch(t,{queueId:"customerStrategy"})}loadShippingOptions(e){const t=this._consignmentActionCreator.loadShippingOptions(e);return this._dispatch(t)}initializeShipping(e){const t=this._shippingStrategyActionCreator.initialize(e);return this._dispatch(t,{queueId:"shippingStrategy"})}deinitializeShipping(e){const t=this._shippingStrategyActionCreator.deinitialize(e);return this._dispatch(t,{queueId:"shippingStrategy"})}selectShippingOption(e,t){const n=this._shippingStrategyActionCreator.selectOption(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}updateShippingAddress(e,t){const n=this._shippingStrategyActionCreator.updateAddress(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}createConsignments(e,t){const n=this._consignmentActionCreator.createConsignments(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}deleteConsignment(e,t){const n=this._consignmentActionCreator.deleteConsignment(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}updateConsignment(e,t){const n=this._consignmentActionCreator.updateConsignment(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}assignItemsToAddress(e,t){const n=this._consignmentActionCreator.assignItemsByAddress(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}unassignItemsToAddress(e,t){const n=this._consignmentActionCreator.unassignItemsByAddress(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}selectConsignmentShippingOption(e,t,n){const i=this._consignmentActionCreator.updateShippingOption({id:e,shippingOptionId:t},n);return this._dispatch(i,{queueId:"shippingStrategy"})}updateBillingAddress(e,t={}){const n=this._billingAddressActionCreator.updateAddress(e,t);return this._dispatch(n)}applyStoreCredit(e,t){const n=this._storeCreditActionCreator.applyStoreCredit(e,t);return this._dispatch(n)}applyCoupon(e,t){const n=this._couponActionCreator.applyCoupon(e,t);return this._dispatch(n)}removeCoupon(e,t){const n=this._couponActionCreator.removeCoupon(e,t);return this._dispatch(n)}applyGiftCertificate(e,t){const n=this._giftCertificateActionCreator.applyGiftCertificate(e,t);return this._dispatch(n)}removeGiftCertificate(e,t){const n=this._giftCertificateActionCreator.removeGiftCertificate(e,t);return this._dispatch(n)}loadInstruments(){const e=this._instrumentActionCreator.loadInstruments();return this._dispatch(e)}deleteInstrument(e){const t=this._instrumentActionCreator.deleteInstrument(e);return this._dispatch(t).then(()=>this.loadInstruments())}clearError(e){const t=this._errorActionCreator.clearError(e);return this._dispatch(t)}initializeSpamProtection(e){const t=this._spamProtectionActionCreator.initialize(e);return this._dispatch(t,{queueId:"spamProtection"})}executeSpamCheck(){const e=this._spamProtectionActionCreator.verifyCheckoutSpamProtection();return this._dispatch(e,{queueId:"spamProtection"})}loadExtensions(e){const t=this._extensionActionCreator.loadExtensions(e);return this._dispatch(t,{queueId:"extensions"})}renderExtension(e,t){return n=this,i=void 0,o=function*(){const n=this._extensionActionCreator.renderExtension(e,t,this._workerExtensionMessenger),i=yield this._dispatch(n,{queueId:"extensions"});return this._extensionEventBroadcaster.listen(),i},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}clearExtensionCache(e){this._extensionMessenger.clearCacheByRegion(e)}postMessageToExtension(e,t){this._extensionMessenger.post(e,t)}handleExtensionCommand(e,t,n){return this._extensionMessenger.listenForCommand(e,t,n)}handleExtensionQuery(e,t,n){return this._extensionMessenger.listenForQuery(e,t,n)}_dispatch(e,t){return this._store.dispatch(e,t).then(()=>this.getState()).catch(e=>{throw this._errorTransformer.transform(e)})}};mv=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],mv);const yv=mv;function gv(e){return(...t)=>{const n=t.pop();return e(...t,(...e)=>{const t=n(...e);return"function"==typeof t?Pe(t):t})}}const vv=gv(Re),fv=gv(Fe(Le,(e,t)=>Be(e,t)));class Sv extends Ot{constructor(e,t){super(e,{message:t||"An unexpected error has occurred. The checkout process cannot continue as a result."}),this.name="UnrecoverableError",this.type="unrecoverable"}}function _v(e){return e.reduce((e,t)=>t?[...e,t]:e,[]).join(" ")}class wv extends Ot{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}class Iv{constructor(){this._factoryMethods={},this.register("default",(e,t)=>new Ot(e,{message:t})),this.register("internal",(e,t)=>function(e,t){const{body:n}=e,{errors:i=[]}=n;return new Ot(e,{message:_v(i)||n.detail||n.title||t,errors:i.length?i.map(e=>({code:n.type,message:e})):[{code:n.type,message:n.detail||n.title}]})}(e,t)),this.register("storefront",(e,t)=>function(e,t){const{body:n}=e;return new Ot(e,{message:t||n.detail||n.title,errors:[{code:n.code||n.type,message:n.detail||n.title}]})}(e,t)),this.register("payment",(e,t)=>ly(e,t)),this.register("timeout",e=>new wv(e))}register(e,t){this._factoryMethods[e]=t}createError(e,t){return(this._factoryMethods[this._getType(e)]||this._factoryMethods.default)(e,t)}_getType(e){if(0===e.status)return"timeout";if(this._isStorefrontErrorResponseBody(e.body))return"storefront";if(this._isInternalErrorResponseBody(e.body)){const t=re(e.body.type.split("/"));return t&&this._factoryMethods[t]?t:"internal"}const t=re(e.body&&e.body.errors);return t&&t.code&&this._factoryMethods[t.code]?t.code:"payment"}_isStorefrontErrorResponseBody(e){const t=e;return!this._isInternalErrorResponseBody(e)&&"string"==typeof t.title&&"string"==typeof t.type&&"number"==typeof t.status&&"string"==typeof t.detail}_isInternalErrorResponseBody(e){const t=e;return"object"==typeof t.errors&&"string"==typeof t.title&&"string"==typeof t.type&&"number"==typeof t.status}}function Cv(e,t){return Array.isArray(e)?e.map(e=>Cv(e,t)):Q(e)?Se(ue(e,t),(e,n,i)=>{e[i]=Cv(n,t)},{}):e}function bv(e,t){return function(e){return e.type===pt.ClearError}(t)?Cv(e,e=>e===t.payload):e}function Pv(e,t,n){return e===t||(e&&t&&"object"==typeof e&&"object"==typeof t?Array.isArray(e)&&Array.isArray(t)?function(e,t,n){if(e.length!==t.length)return!1;for(let i=0,r=e.length;ivoid 0!==e.id&&e.id===t.id}=i||{};if(!t)return n;if(!n||t===n)return t;let o=0,a=0;const s=(e,t,n)=>(o+=e===t?1:0,a+=e===n?1:0,e),d=n.map((n,i)=>{const o=t&&t[i];return Rg(o)&&Rg(n)?r(o,n)?s(Bv(o,n),o,n):s(Mv(o,n),o,n):W(o)&&W(n)?s(e(o,n),o,n):s(Mv(o,n),o,n)});return o===n.length&&t&&t.length===n.length?t:a===n.length?n:d},Bv=function e(t,n){return t?n&&t!==n?Object.keys(n).reduce((t,i)=>{const r=t[i],o=n[i];return Rg(r)&&Rg(o)?Ov(t,i,e(r,o)):W(r)&&W(o)?Ov(t,i,Lv(r,o)):Ov(t,i,o)},t):t:n},jv={errors:{},statuses:{}};function Uv(e=jv,t){return d({data:qv,errors:c(Gv,bv),statuses:Vv})(e,t)}function qv(e,t){var n,i;switch(t.type){case tt.UpdateBillingAddressSucceeded:case $t.LoadCheckoutSucceeded:case _g.CreateConsignmentsSucceeded:case _g.DeleteConsignmentSucceeded:case _g.UpdateConsignmentSucceeded:case _g.UpdateShippingOptionSucceeded:case _g.LoadShippingOptionsSucceeded:case kt.ApplyCouponSucceeded:case kt.RemoveCouponSucceeded:case Nt.ApplyGiftCertificateSucceeded:case Nt.RemoveGiftCertificateSucceeded:return Bv(e,t.payload&&t.payload.cart);case Yt.HydrateInitialState:return Bv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.cart);default:return e}}function Vv(e=jv.statuses,t){switch(t.type){case $t.LoadCheckoutRequested:return Ov(e,"isLoading",!0);case $t.LoadCheckoutFailed:case $t.LoadCheckoutSucceeded:return Ov(e,"isLoading",!1);default:return e}}function Gv(e=jv.errors,t){switch(t.type){case $t.LoadCheckoutRequested:case $t.LoadCheckoutSucceeded:return Ov(e,"loadError",void 0);case $t.LoadCheckoutFailed:return Ov(e,"loadError",t.payload);default:return e}}var Hv;!function(e){e.InitializeButtonFailed="INITIALIZE_BUTTON_FAILED",e.InitializeButtonRequested="INITIALIZE_BUTTON_REQUESTED",e.InitializeButtonSucceeded="INITIALIZE_BUTTON_SUCCEEDED",e.DeinitializeButtonFailed="DEINITIALIZE_BUTTON_FAILED",e.DeinitializeButtonRequested="DEINITIALIZE_BUTTON_REQUESTED",e.DeinitializeButtonSucceeded="DEINITIALIZE_BUTTON_SUCCEEDED"}(Hv||(Hv={}));const Wv={data:{},errors:{},statuses:{}},$v={initializedContainers:{}},Yv={},Kv={};function Jv(e=Wv,t){return t.meta&&t.meta.methodId?d({data:d({[t.meta.methodId]:Zv}),errors:d({[t.meta.methodId]:Qv}),statuses:d({[t.meta.methodId]:Xv})})(e,t):e}function Zv(e=$v,t){switch(t.type){case Hv.InitializeButtonSucceeded:return t.meta&&t.meta.containerId?Bv(e,{initializedContainers:{[t.meta.containerId]:!0}}):e;case Hv.DeinitializeButtonSucceeded:return Ov(e,"initializedContainers",{})}return e}function Qv(e=Yv,t){switch(t.type){case Hv.InitializeButtonRequested:case Hv.InitializeButtonSucceeded:return Ov(e,"initializeError",void 0);case Hv.InitializeButtonFailed:return Ov(e,"initializeError",t.payload);case Hv.DeinitializeButtonRequested:case Hv.DeinitializeButtonSucceeded:return Ov(e,"deinitializeError",void 0);case Hv.DeinitializeButtonFailed:return Ov(e,"deinitializeError",t.payload);default:return e}}function Xv(e=Kv,t){switch(t.type){case Hv.InitializeButtonRequested:return Ov(e,"isInitializing",!0);case Hv.InitializeButtonFailed:case Hv.InitializeButtonSucceeded:return Ov(e,"isInitializing",!1);case Hv.DeinitializeButtonRequested:return Ov(e,"isDeinitializing",!0);case Hv.DeinitializeButtonFailed:case Hv.DeinitializeButtonSucceeded:return Ov(e,"isDeinitializing",!1);default:return e}}const ef={meta:{},errors:{},statuses:{}};function tf(e=ef,t){return d({data:nf,errors:c(rf,bv),statuses:of})(e,t)}function nf(e,t){var n,i;switch(t.type){case Ct.LoadConfigSucceeded:return Bv(e,t.payload);case Yt.HydrateInitialState:{const r=Bv(e,null===(n=t.payload)||void 0===n?void 0:n.config);return r&&(null===(i=t.payload)||void 0===i?void 0:i.b2bApiSettings)?Object.assign(Object.assign({},r),{storeConfig:Object.assign(Object.assign({},r.storeConfig),{b2bApiSettings:t.payload.b2bApiSettings})}):r}default:return e}}function rf(e=ef.errors,t){switch(t.type){case Ct.LoadConfigSucceeded:return Ov(e,"loadError",void 0);case Ct.LoadConfigFailed:return Ov(e,"loadError",t.payload);default:return e}}function of(e=ef.statuses,t){switch(t.type){case Ct.LoadConfigRequested:return Ov(e,"isLoading",!0);case Ct.LoadConfigSucceeded:case Ct.LoadConfigFailed:return Ov(e,"isLoading",!1);default:return e}}const af={errors:{},statuses:{}};function sf(e=af,t){return d({data:df,errors:c(cf,bv),statuses:lf})(e,t)}function df(e,t){var n,i;switch(t.type){case $t.LoadCheckoutSucceeded:case kt.ApplyCouponSucceeded:case _g.UpdateShippingOptionSucceeded:case kt.RemoveCouponSucceeded:case Mm.LoadOrderSucceeded:return Lv(e,t.payload&&t.payload.coupons);case Yt.HydrateInitialState:return Lv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.coupons);default:return e}}function cf(e={},t){switch(t.type){case kt.ApplyCouponRequested:case kt.ApplyCouponSucceeded:return Ov(e,"applyCouponError",void 0);case kt.ApplyCouponFailed:return Ov(e,"applyCouponError",t.payload);case kt.RemoveCouponRequested:case kt.RemoveCouponSucceeded:return Ov(e,"removeCouponError",void 0);case kt.RemoveCouponFailed:return Ov(e,"removeCouponError",t.payload);default:return e}}function lf(e={},t){switch(t.type){case kt.ApplyCouponRequested:return Ov(e,"isApplyingCoupon",!0);case kt.ApplyCouponSucceeded:case kt.ApplyCouponFailed:return Ov(e,"isApplyingCoupon",!1);case kt.RemoveCouponRequested:return Ov(e,"isRemovingCoupon",!0);case kt.RemoveCouponSucceeded:case kt.RemoveCouponFailed:return Ov(e,"isRemovingCoupon",!1);default:return e}}const uf={errors:{},statuses:{}};function hf(e=uf,t){return d({data:pf,errors:c(mf,bv),statuses:yf})(e,t)}function pf(e,t){var n,i;switch(t.type){case $t.LoadCheckoutSucceeded:case _g.CreateConsignmentsSucceeded:case _g.UpdateConsignmentSucceeded:case _g.DeleteConsignmentSucceeded:case _g.UpdateShippingOptionSucceeded:case kt.ApplyCouponSucceeded:case kt.RemoveCouponSucceeded:case Nt.ApplyGiftCertificateSucceeded:case Nt.RemoveGiftCertificateSucceeded:return Lv(e,t.payload&&t.payload.giftCertificates);case Yt.HydrateInitialState:return Lv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.giftCertificates);default:return e}}function mf(e=uf.errors,t){switch(t.type){case Nt.ApplyGiftCertificateRequested:case Nt.ApplyGiftCertificateSucceeded:return Ov(e,"applyGiftCertificateError",void 0);case Nt.ApplyGiftCertificateFailed:return Ov(e,"applyGiftCertificateError",t.payload);case Nt.RemoveGiftCertificateRequested:case Nt.RemoveGiftCertificateSucceeded:return Ov(e,"removeGiftCertificateError",void 0);case Nt.RemoveGiftCertificateFailed:return Ov(e,"removeGiftCertificateError",t.payload);default:return e}}function yf(e=uf.statuses,t){switch(t.type){case Nt.ApplyGiftCertificateRequested:return Ov(e,"isApplyingGiftCertificate",!0);case Nt.ApplyGiftCertificateSucceeded:case Nt.ApplyGiftCertificateFailed:return Ov(e,"isApplyingGiftCertificate",!1);case Nt.RemoveGiftCertificateRequested:return Ov(e,"isRemovingGiftCertificate",!0);case Nt.RemoveGiftCertificateSucceeded:case Nt.RemoveGiftCertificateFailed:return Ov(e,"isRemovingGiftCertificate",!1);default:return e}}const gf={errors:{},statuses:{}};function vf(e=gf,t){return d({data:ff,errors:c(Sf,bv),statuses:_f})(e,t)}function ff(e,t){var n,i;switch(t.type){case tt.ContinueAsGuestSucceeded:case $t.LoadCheckoutSucceeded:return Bv(e,t.payload&&t.payload.customer);case Rt.CreateCustomerAddressSucceeded:return Bv(e,t.payload);case Yt.HydrateInitialState:return Bv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.customer);default:return e}}function Sf(e=gf.errors,t){switch(t.type){case Rt.CreateCustomerRequested:case Rt.CreateCustomerSucceeded:return Ov(e,"createError",void 0);case Rt.CreateCustomerFailed:return Ov(e,"createError",t.payload);case Rt.CreateCustomerAddressRequested:case Rt.CreateCustomerAddressSucceeded:return Ov(e,"createAddressError",void 0);case Rt.CreateCustomerAddressFailed:return Ov(e,"createAddressError",t.payload);default:return e}}function _f(e=gf.statuses,t){switch(t.type){case Rt.CreateCustomerRequested:return Ov(e,"isCreating",!0);case Rt.CreateCustomerFailed:case Rt.CreateCustomerSucceeded:return Ov(e,"isCreating",!1);case Rt.CreateCustomerAddressRequested:return Ov(e,"isCreatingAddress",!0);case Rt.CreateCustomerAddressFailed:case Rt.CreateCustomerAddressSucceeded:return Ov(e,"isCreatingAddress",!1);default:return e}}const wf={data:{},errors:{},statuses:{}};function If(e=wf,t){return d({data:Cf,errors:c(bf,bv),statuses:Pf})(e,t)}function Cf(e=wf.data,t){switch(t.type){case Wt.InitializeSucceeded:return Bv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!0}});case Wt.DeinitializeSucceeded:return Bv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!1}})}return e}function bf(e=wf.errors,t){switch(t.type){case Wt.InitializeRequested:case Wt.InitializeSucceeded:return Bv(e,{initializeErrors:Object.assign({},e.initializeErrors),initializeMethodId:e.initializeMethodId?e.initializeMethodId:void 0});case Wt.InitializeFailed:return Bv(e,{initializeErrors:Object.assign(Object.assign({},e.initializeErrors),{[t.meta&&t.meta.methodId]:t.payload}),initializeMethodId:t.meta&&t.meta.methodId});case Wt.DeinitializeRequested:case Wt.DeinitializeSucceeded:return Bv(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Wt.DeinitializeFailed:return Bv(e,{deinitializeError:t.payload,deinitializeMethodId:t.meta&&t.meta.methodId});case Wt.SignInRequested:case Wt.SignInSucceeded:return Bv(e,{signInError:void 0,signInMethodId:void 0});case Wt.SignInFailed:return Bv(e,{signInError:t.payload,signInMethodId:t.meta&&t.meta.methodId});case Wt.SignOutRequested:case Wt.SignOutSucceeded:return Bv(e,{signOutError:void 0,signOutMethodId:void 0});case Wt.SignOutFailed:return Bv(e,{signOutError:t.payload,signOutMethodId:t.meta&&t.meta.methodId});case Wt.ExecutePaymentMethodCheckoutRequested:case Wt.ExecutePaymentMethodCheckoutSucceeded:return Bv(e,{executePaymentMethodCheckoutError:void 0,executePaymentMethodCheckoutMethodId:void 0});case Wt.ExecutePaymentMethodCheckoutFailed:return Bv(e,{executePaymentMethodCheckoutError:t.payload,executePaymentMethodCheckoutMethodId:t.meta&&t.meta.methodId});case Wt.WidgetInteractionStarted:case Wt.WidgetInteractionFinished:return Bv(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Wt.WidgetInteractionFailed:return Bv(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta.methodId});default:return e}}function Pf(e=wf.statuses,t){switch(t.type){case Wt.InitializeRequested:return Bv(e,{isInitializing:!0,initializeMethodId:t.meta&&t.meta.methodId});case Wt.InitializeFailed:case Wt.InitializeSucceeded:return Bv(e,{isInitializing:!1,initializeMethodId:void 0});case Wt.DeinitializeRequested:return Bv(e,{isDeinitializing:!0,deinitializeMethodId:t.meta&&t.meta.methodId});case Wt.DeinitializeFailed:case Wt.DeinitializeSucceeded:return Bv(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Wt.SignInRequested:return Bv(e,{isSigningIn:!0,signInMethodId:t.meta&&t.meta.methodId});case Wt.SignInFailed:case Wt.SignInSucceeded:return Bv(e,{isSigningIn:!1,signInMethodId:void 0});case Wt.SignOutRequested:return Bv(e,{isSigningOut:!0,signOutMethodId:t.meta&&t.meta.methodId});case Wt.SignOutFailed:case Wt.SignOutSucceeded:return Bv(e,{isSigningOut:!1,signOutMethodId:void 0});case Wt.ExecutePaymentMethodCheckoutRequested:return Bv(e,{isExecutingPaymentMethodCheckout:!0,executePaymentMethodCheckoutMethodId:t.meta&&t.meta.methodId});case Wt.ExecutePaymentMethodCheckoutFailed:case Wt.ExecutePaymentMethodCheckoutSucceeded:return Bv(e,{isExecutingPaymentMethodCheckout:!1,executePaymentMethodCheckoutMethodId:void 0});case Wt.WidgetInteractionStarted:return Bv(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta.methodId});case Wt.WidgetInteractionFinished:case Wt.WidgetInteractionFailed:return Bv(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const Of={errors:{},statuses:{}};function Ef(e=Of,t){return d({data:Af,errors:c(Tf,bv),statuses:kf})(e,t)}function Af(e,t){var n;return t.type===ln.LoadExtensionsSucceeded?Lv(e,t.payload):t.type===Yt.HydrateInitialState?Lv(e,null===(n=t.payload)||void 0===n?void 0:n.extensions):e}function Tf(e=Of.errors,t){switch(t.type){case ln.LoadExtensionsRequested:case ln.LoadExtensionsSucceeded:return Ov(e,"loadError",void 0);case ln.RenderExtensionRequested:case ln.RenderExtensionSucceeded:return Ov(e,"renderError",void 0);case ln.LoadExtensionsFailed:return Ov(e,"loadError",t.payload);case ln.RenderExtensionFailed:return Ov(e,"renderError",t.payload);default:return e}}function kf(e=Of.statuses,t){switch(t.type){case ln.LoadExtensionsRequested:return Ov(e,"isLoading",!0);case ln.LoadExtensionsSucceeded:case ln.LoadExtensionsFailed:return Ov(e,"isLoading",!1);default:return e}}const Df={errors:{},statuses:{}};function Mf(e=Df,t){return d({data:zf,extraFields:Nf,errors:c(xf,bv),statuses:Rf})(e,t)}function zf(e,t){var n;switch(t.type){case tn.LoadFormFieldsSucceeded:return Bv(e,t.payload);case Yt.HydrateInitialState:return Bv(e,null===(n=t.payload)||void 0===n?void 0:n.formFields);default:return e}}function Nf(e,t){var n,i;return t.type===Yt.HydrateInitialState&&null!==(i=null===(n=t.payload)||void 0===n?void 0:n.extraFields)&&void 0!==i?i:e}function xf(e=Df.errors,t){switch(t.type){case tn.LoadFormFieldsSucceeded:return Ov(e,"loadError",void 0);case tn.LoadFormFieldsFailed:return Ov(e,"loadError",t.payload);default:return e}}function Rf(e=Df.statuses,t){switch(t.type){case tn.LoadFormFieldsRequested:return Ov(e,"isLoading",!0);case tn.LoadFormFieldsSucceeded:case tn.LoadFormFieldsFailed:return Ov(e,"isLoading",!1);default:return e}}const Ff={errors:{},statuses:{}};function Lf(e=Ff,t){return d({data:Bf,errors:c(jf,bv),statuses:Uf})(e,t)}function Bf(e,t){return t.type===Dm.LoadCountriesSucceeded?Lv(e,t.payload):e}function jf(e=Ff.errors,t){switch(t.type){case Dm.LoadCountriesRequested:case Dm.LoadCountriesSucceeded:return Ov(e,"loadError",void 0);case Dm.LoadCountriesFailed:return Ov(e,"loadError",t.payload);default:return e}}function Uf(e=Ff.statuses,t){switch(t.type){case Dm.LoadCountriesRequested:return Ov(e,"isLoading",!0);case Dm.LoadCountriesSucceeded:case Dm.LoadCountriesFailed:return Ov(e,"isLoading",!1);default:return e}}const qf={errors:{},meta:{},statuses:{}};function Vf(e=qf,t){return d({data:Gf,errors:c(Wf,bv),meta:Hf,statuses:$f})(e,t)}function Gf(e,t){switch(t.type){case Mm.LoadOrderSucceeded:case Mm.LoadOrderPaymentsSucceeded:return Bv(e,le(t.payload,["billingAddress","coupons"]));default:return e}}function Hf(e,t){switch(t.type){case Mm.FinalizeOrderSucceeded:case Mm.SubmitOrderSucceeded:return Bv(e,Object.assign(Object.assign({},t.meta),{callbackUrl:t.payload&&t.payload.order.callbackUrl,orderToken:t.payload&&t.payload.order.token,payment:t.payload&&t.payload.order&&t.payload.order.payment}));default:return e}}function Wf(e=qf.errors,t){switch(t.type){case Mm.LoadOrderRequested:case Mm.LoadOrderSucceeded:case Mm.LoadOrderPaymentsSucceeded:case Mm.LoadOrderPaymentsRequested:return Ov(e,"loadError",void 0);case Mm.LoadOrderFailed:case Mm.LoadOrderPaymentsFailed:return Ov(e,"loadError",t.payload);default:return e}}function $f(e=qf.statuses,t){switch(t.type){case Mm.LoadOrderRequested:case Mm.LoadOrderPaymentsRequested:return Ov(e,"isLoading",!0);case Mm.LoadOrderSucceeded:case Mm.LoadOrderFailed:case Mm.LoadOrderPaymentsSucceeded:case Mm.LoadOrderPaymentsFailed:return Ov(e,"isLoading",!1);default:return e}}const Yf={};function Kf(e=Yf,t){return d({data:Jf})(e,t)}function Jf(e,t){switch(t.type){case Mm.LoadOrderPaymentsSucceeded:case Mm.LoadOrderSucceeded:return Mv(e,t.payload&&t.payload.billingAddress);default:return e}}function Zf(e={},t){return d({data:Qf})(e,t)}function Qf(e,t){return t.type===vy.SubmitPaymentSucceeded?t.payload:e}const Xf={errors:{},statuses:{}};function eS(e=Xf,t){return d({data:tS,errors:c(iS,bv),meta:nS,statuses:rS})(e,t)}function tS(e,t){switch(t.type){case qm.LoadPaymentMethodSucceeded:return function(e,t,n){if(!t)return e;const i=pe(t,"id"),r="object"==typeof n?me(n):n||i,o=j(e,r),a=[...e];if(-1===o)a.push(t);else{const n=e[o];a[o]=Rg(n)&&Rg(t)?Bv(n,t):t}return a}(e||[],t.payload,t.payload&&{id:t.payload.id,gateway:t.payload.gateway});case qm.LoadPaymentMethodsSucceeded:return Lv(e,t.payload,{matchObject:(e,t)=>e.id===t.id&&e.gateway===t.gateway});default:return e}}function nS(e,t){return t.type===qm.LoadPaymentMethodsSucceeded?Bv(e,t.meta):e}function iS(e=Xf.errors,t){switch(t.type){case qm.LoadPaymentMethodsRequested:case qm.LoadPaymentMethodsSucceeded:return Ov(e,"loadError",void 0);case qm.LoadPaymentMethodsFailed:return Ov(e,"loadError",t.payload);case qm.LoadPaymentMethodRequested:case qm.LoadPaymentMethodSucceeded:return Bv(e,{loadMethodId:void 0,loadMethodError:void 0});case qm.LoadPaymentMethodFailed:return Bv(e,{loadMethodId:t.meta.methodId,loadMethodError:t.payload});default:return e}}function rS(e=Xf.statuses,t){switch(t.type){case qm.LoadPaymentMethodsRequested:return Ov(e,"isLoading",!0);case qm.LoadPaymentMethodsSucceeded:case qm.LoadPaymentMethodsFailed:return Ov(e,"isLoading",!1);case qm.LoadPaymentMethodRequested:return Bv(e,{isLoadingMethod:!0,loadMethodId:t.meta.methodId});case qm.LoadPaymentMethodSucceeded:case qm.LoadPaymentMethodFailed:return Bv(e,{isLoadingMethod:!1,loadMethodId:void 0});default:return e}}const oS={data:{},errors:{},statuses:{}};function aS(e=oS,t){return d({data:sS,errors:c(dS,bv),statuses:cS})(e,t)}function sS(e=oS.data,t){switch(t.type){case Km.InitializeSucceeded:if(t.meta){const{methodId:n,gatewayId:i}=t.meta,r=i?`${n}.${i}`:n;return Bv(e,{[r]:{isInitialized:!0}})}break;case Km.DeinitializeSucceeded:if(t.meta){const{methodId:n,gatewayId:i}=t.meta,r=i?`${n}.${i}`:n;return Bv(e,{[r]:{isInitialized:!1}})}}return e}function dS(e=oS.errors,t){switch(t.type){case Km.InitializeRequested:case Km.InitializeSucceeded:return Bv(e,{initializeError:void 0,initializeMethodId:void 0});case Km.InitializeFailed:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return Bv(e,{initializeError:t.payload,initializeMethodId:n})}case Km.DeinitializeRequested:case Km.DeinitializeSucceeded:return Bv(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Km.DeinitializeFailed:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return Bv(e,{deinitializeError:t.payload,deinitializeMethodId:n})}case Km.ExecuteRequested:case Km.ExecuteSucceeded:return Bv(e,{executeError:void 0,executeMethodId:void 0});case Km.ExecuteFailed:return Bv(e,{executeError:t.payload,executeMethodId:t.meta&&t.meta.methodId});case Km.FinalizeRequested:case Km.FinalizeSucceeded:return Bv(e,{finalizeError:void 0,finalizeMethodId:void 0});case Km.FinalizeFailed:return Bv(e,{finalizeError:t.payload,finalizeMethodId:t.meta&&t.meta.methodId});case Km.WidgetInteractionStarted:case Km.WidgetInteractionFinished:return Bv(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Km.WidgetInteractionFailed:return Bv(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta.methodId});default:return e}}function cS(e=oS.statuses,t){switch(t.type){case Km.InitializeRequested:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return Bv(e,{isInitializing:!0,initializeMethodId:n})}case Km.InitializeFailed:case Km.InitializeSucceeded:return Bv(e,{isInitializing:!1,initializeMethodId:void 0});case Km.DeinitializeRequested:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return Bv(e,{isDeinitializing:!0,deinitializeMethodId:n})}case Km.DeinitializeFailed:case Km.DeinitializeSucceeded:return Bv(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Km.ExecuteRequested:return Bv(e,{isExecuting:!0,executeMethodId:t.meta&&t.meta.methodId});case Km.ExecuteFailed:case Km.ExecuteSucceeded:return Bv(e,{isExecuting:!1,executeMethodId:void 0});case Km.FinalizeRequested:return Bv(e,{isFinalizing:!0,finalizeMethodId:t.meta&&t.meta.methodId});case Km.FinalizeFailed:case Km.FinalizeSucceeded:return Bv(e,{isFinalizing:!1,finalizeMethodId:void 0});case Km.WidgetInteractionStarted:return Bv(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta.methodId});case Km.WidgetInteractionFinished:case Km.WidgetInteractionFailed:return Bv(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const lS={data:{}};function uS(e=lS,t){return d({data:hS})(e,t)}function hS(e=lS.data,t){return t.type===mg.UpdatePaymentProviderCustomer?Bv(e,t.payload):e}const pS={data:[],errors:{},statuses:{}};function mS(e=pS,t){return d({data:yS,errors:c(vS,bv),meta:gS,statuses:fS})(e,t)}function yS(e=pS.data,t){return t.type===Ug.LoadInstrumentsSucceeded?Lv(e,t.payload&&t.payload.vaultedInstruments||[]):e}function gS(e,t){switch(t.type){case Ug.LoadInstrumentsSucceeded:case Ug.DeleteInstrumentSucceeded:return Bv(e,t.meta);default:return e}}function vS(e=pS.errors,t){switch(t.type){case Ug.LoadInstrumentsRequested:case Ug.LoadInstrumentsSucceeded:return Ov(e,"loadError",void 0);case Ug.DeleteInstrumentRequested:case Ug.DeleteInstrumentSucceeded:return Bv(e,{deleteError:void 0,failedInstrument:void 0});case Ug.LoadInstrumentsFailed:return Ov(e,"loadError",t.payload);case Ug.DeleteInstrumentFailed:return Bv(e,{deleteError:t.payload,failedInstrument:t.meta.instrumentId});default:return e}}function fS(e=pS.statuses,t){switch(t.type){case Ug.LoadInstrumentsRequested:return Ov(e,"isLoading",!0);case Ug.DeleteInstrumentRequested:return Bv(e,{isDeleting:!0,deletingInstrument:t.meta.instrumentId});case Ug.LoadInstrumentsSucceeded:case Ug.LoadInstrumentsFailed:return Ov(e,"isLoading",!1);case Ug.DeleteInstrumentSucceeded:case Ug.DeleteInstrumentFailed:return Bv(e,{isDeleting:!1,deletingInstrument:void 0});default:return e}}const SS={data:{}};function _S(e=SS,t){return t.meta&&t.meta.methodId?d({data:d({[t.meta.methodId]:wS})})(e,t):e}function wS(e,t){switch(t.type){case yg.InitializeRemoteBillingSucceeded:return Ov(e,"billing",t.payload&&t.payload.billing);case yg.InitializeRemoteShippingSucceeded:return Ov(e,"shipping",t.payload&&t.payload.shipping);case yg.LoadRemoteSettingsSucceeded:return Ov(e,"settings",t.payload);case yg.UpdateRemoteCheckout:return Bv(e,t.payload);default:return e}}const IS={errors:{updateShippingOptionError:{},updateError:{},deleteError:{}},statuses:{isUpdating:{},isUpdatingShippingOption:{},isDeleting:{}}};function CS(e=IS,t){return d({data:bS,errors:c(PS,bv),statuses:OS})(e,t)}function bS(e,t){var n,i;switch(t.type){case $t.LoadCheckoutSucceeded:case _g.LoadShippingOptionsSucceeded:case _g.CreateConsignmentsSucceeded:case _g.UpdateConsignmentSucceeded:case _g.DeleteConsignmentSucceeded:case _g.UpdateShippingOptionSucceeded:case kt.ApplyCouponSucceeded:case kt.RemoveCouponSucceeded:return Lv(e,t.payload&&t.payload.consignments);case Rt.SignOutCustomerSucceeded:return Lv(e,[]);case Yt.HydrateInitialState:return Lv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.consignments);default:return e}}function PS(e=IS.errors,t){switch(t.type){case $t.LoadCheckoutRequested:case $t.LoadCheckoutSucceeded:case _g.LoadShippingOptionsSucceeded:case _g.LoadShippingOptionsRequested:return Ov(e,"loadError",void 0);case $t.LoadCheckoutFailed:case _g.LoadShippingOptionsFailed:return Ov(e,"loadError",t.payload);case _g.CreateConsignmentsRequested:case _g.CreateConsignmentsSucceeded:return Ov(e,"createError",void 0);case _g.CreateConsignmentsFailed:return Ov(e,"createError",t.payload);case _g.UpdateConsignmentSucceeded:case _g.UpdateConsignmentRequested:return t.meta?Bv(e,{updateError:{[t.meta.id]:void 0}}):e;case _g.UpdateConsignmentFailed:return t.meta?Bv(e,{updateError:{[t.meta.id]:t.payload}}):e;case _g.DeleteConsignmentSucceeded:case _g.DeleteConsignmentRequested:return t.meta?Bv(e,{deleteError:{[t.meta.id]:void 0}}):e;case _g.DeleteConsignmentFailed:return t.meta?Bv(e,{deleteError:{[t.meta.id]:t.payload}}):e;case _g.UpdateShippingOptionRequested:case _g.UpdateShippingOptionSucceeded:return t.meta?Bv(e,{updateShippingOptionError:{[t.meta.id]:void 0}}):e;case _g.UpdateShippingOptionFailed:return t.meta?Bv(e,{updateShippingOptionError:{[t.meta.id]:t.payload}}):e;default:return e}}function OS(e=IS.statuses,t){switch(t.type){case $t.LoadCheckoutRequested:return Ov(e,"isLoading",!0);case _g.LoadShippingOptionsRequested:return Ov(e,"isLoadingShippingOptions",!0);case $t.LoadCheckoutSucceeded:case $t.LoadCheckoutFailed:return Ov(e,"isLoading",!1);case _g.LoadShippingOptionsSucceeded:case _g.LoadShippingOptionsFailed:return Ov(e,"isLoadingShippingOptions",!1);case _g.CreateConsignmentsRequested:return Ov(e,"isCreating",!0);case _g.CreateConsignmentsSucceeded:case _g.CreateConsignmentsFailed:return Ov(e,"isCreating",!1);case _g.UpdateConsignmentRequested:return t.meta?Bv(e,{isUpdating:{[t.meta.id]:!0}}):e;case _g.UpdateConsignmentSucceeded:case _g.UpdateConsignmentFailed:return t.meta?Bv(e,{isUpdating:{[t.meta.id]:!1}}):e;case _g.DeleteConsignmentRequested:return t.meta?Bv(e,{isDeleting:{[t.meta.id]:!0}}):e;case _g.DeleteConsignmentSucceeded:case _g.DeleteConsignmentFailed:return t.meta?Bv(e,{isDeleting:{[t.meta.id]:!1}}):e;case _g.UpdateShippingOptionRequested:return t.meta?Bv(e,{isUpdatingShippingOption:{[t.meta.id]:!0}}):e;case _g.UpdateShippingOptionSucceeded:case _g.UpdateShippingOptionFailed:return t.meta?Bv(e,{isUpdatingShippingOption:{[t.meta.id]:!1}}):e;default:return e}}function ES(e,t){const n={};return Object.keys(e).forEach(i=>{const r=e[i],o=t?`${t}.${i}`:i;"object"==typeof r?Object.assign(n,ES(r,o)):n[o]=r}),n}function AS(e){return Object.keys(e).sort().reduce((t,n)=>Object.assign(Object.assign({},t),{[n]:e[n]}),{})}const TS={errors:{},statuses:{}};function kS(e=TS,t){return d({data:DS,errors:c(MS,bv),statuses:zS})(e,t)}function DS(e,t){if(t.type!==$g.LoadPickupOptionsSucceeded)return e;if(t.meta){const n=AS(ES({consignmentId:t.meta.consignmentId,searchArea:t.meta.searchArea}));return Ov(e,btoa(`${JSON.stringify(n)}`),t.payload)}}function MS(e=TS.errors,t){switch(t.type){case $g.LoadPickupOptionsRequested:case $g.LoadPickupOptionsSucceeded:return Ov(e,"loadError",void 0);case $g.LoadPickupOptionsFailed:return Ov(e,"loadError",t.payload);default:return e}}function zS(e=TS.statuses,t){switch(t.type){case $g.LoadPickupOptionsRequested:return Ov(e,"isLoading",!0);case $g.LoadPickupOptionsSucceeded:case $g.LoadPickupOptionsFailed:return Ov(e,"isLoading",!1);default:return e}}const NS={errors:{},statuses:{}};function xS(e=NS,t){return d({data:RS,errors:c(FS,bv),statuses:LS})(e,t)}function RS(e,t){return t.type===Og.LoadShippingCountriesSucceeded?Lv(e,t.payload):e}function FS(e=NS.errors,t){switch(t.type){case Og.LoadShippingCountriesRequested:case Og.LoadShippingCountriesSucceeded:return Ov(e,"loadError",void 0);case Og.LoadShippingCountriesFailed:return Ov(e,"loadError",t.payload);default:return e}}function LS(e=NS.statuses,t){switch(t.type){case Og.LoadShippingCountriesRequested:return Ov(e,"isLoading",!0);case Og.LoadShippingCountriesSucceeded:case Og.LoadShippingCountriesFailed:return Ov(e,"isLoading",!1);default:return e}}const BS={data:{},errors:{},statuses:{}};function jS(e=BS,t){return d({data:US,errors:c(qS,bv),statuses:VS})(e,t)}function US(e=BS.data,t){switch(t.type){case Yg.InitializeSucceeded:return Bv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!0}});case Yg.DeinitializeSucceeded:return Bv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!1}})}return e}function qS(e=BS.errors,t){switch(t.type){case Yg.InitializeRequested:case Yg.InitializeSucceeded:return Bv(e,{initializeError:void 0,initializeMethodId:void 0});case Yg.InitializeFailed:return Bv(e,{initializeError:t.payload,initializeMethodId:t.meta&&t.meta.methodId});case Yg.DeinitializeRequested:case Yg.DeinitializeSucceeded:return Bv(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Yg.DeinitializeFailed:return Bv(e,{deinitializeError:t.payload,deinitializeMethodId:t.meta&&t.meta.methodId});case Yg.UpdateAddressRequested:case Yg.UpdateAddressSucceeded:return Bv(e,{updateAddressError:void 0,updateAddressMethodId:void 0});case Yg.UpdateAddressFailed:return Bv(e,{updateAddressError:t.payload,updateAddressMethodId:t.meta&&t.meta.methodId});case Yg.SelectOptionRequested:case Yg.SelectOptionSucceeded:return Bv(e,{selectOptionError:void 0,selectOptionMethodId:void 0});case Yg.SelectOptionFailed:return Bv(e,{selectOptionError:t.payload,selectOptionMethodId:t.meta&&t.meta.methodId});case Yg.WidgetInteractionStarted:case Yg.WidgetInteractionFinished:return Bv(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Yg.WidgetInteractionFailed:return Bv(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta&&t.meta.methodId});default:return e}}function VS(e=BS.statuses,t){switch(t.type){case Yg.InitializeRequested:return Bv(e,{isInitializing:!0,initializeMethodId:t.meta&&t.meta.methodId});case Yg.InitializeFailed:case Yg.InitializeSucceeded:return Bv(e,{isInitializing:!1,initializeMethodId:void 0});case Yg.DeinitializeRequested:return Bv(e,{isDeinitializing:!0,deinitializeMethodId:t.meta&&t.meta.methodId});case Yg.DeinitializeFailed:case Yg.DeinitializeSucceeded:return Bv(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Yg.UpdateAddressRequested:return Bv(e,{isUpdatingAddress:!0,updateAddressMethodId:t.meta&&t.meta.methodId});case Yg.UpdateAddressFailed:case Yg.UpdateAddressSucceeded:return Bv(e,{isUpdatingAddress:!1,updateAddressMethodId:void 0});case Yg.SelectOptionRequested:return Bv(e,{isSelectingOption:!0,selectOptionMethodId:t.meta&&t.meta.methodId});case Yg.SelectOptionFailed:case Yg.SelectOptionSucceeded:return Bv(e,{isSelectingOption:!1,selectOptionMethodId:void 0});case Yg.WidgetInteractionStarted:return Bv(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta&&t.meta.methodId});case Yg.WidgetInteractionFinished:case Yg.WidgetInteractionFailed:return Bv(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const GS={errors:{},statuses:{}};function HS(e=GS,t){return d({data:WS,errors:c($S,bv),statuses:YS})(e,t)}function WS(e,t){return t.type===cv.SendSignInEmailSucceeded?Bv(e,t.payload):e}function $S(e=GS.errors,t){switch(t.type){case cv.SendSignInEmailRequested:case cv.SendSignInEmailSucceeded:return Ov(e,"sendError",void 0);case cv.SendSignInEmailFailed:return Ov(e,"sendError",t.payload);default:return e}}function YS(e=GS.statuses,t){switch(t.type){case cv.SendSignInEmailRequested:return Ov(e,"isSending",!0);case cv.SendSignInEmailFailed:case cv.SendSignInEmailSucceeded:return Ov(e,"isSending",!1);default:return e}}const KS={errors:{},statuses:{}};function JS(e=KS,t){return d({errors:c(ZS,bv),statuses:QS})(e,t)}function ZS(e=KS.errors,t){switch(t.type){case Eg.ApplyStoreCreditRequested:case Eg.ApplyStoreCreditSucceeded:return Ov(e,"applyError",void 0);case Eg.ApplyStoreCreditFailed:return Ov(e,"applyError",t.payload);default:return e}}function QS(e=KS.statuses,t){switch(t.type){case Eg.ApplyStoreCreditRequested:return Ov(e,"isApplying",!0);case Eg.ApplyStoreCreditSucceeded:case Eg.ApplyStoreCreditFailed:return Ov(e,"isApplying",!1);default:return e}}const XS={errors:{},statuses:{}};function e_(e=XS,t){return d({errors:c(t_,bv),statuses:n_})(e,t)}function t_(e=XS.errors,t){switch(t.type){case kg.UpdateSubscriptionsRequested:case kg.UpdateSubscriptionsSucceeded:return Ov(e,"updateError",void 0);case kg.UpdateSubscriptionsFailed:return Ov(e,"updateError",t.payload);default:return e}}function n_(e=XS.statuses,t){switch(t.type){case kg.UpdateSubscriptionsRequested:return Ov(e,"isUpdating",!0);case kg.UpdateSubscriptionsFailed:case kg.UpdateSubscriptionsSucceeded:return Ov(e,"isUpdating",!1);default:return e}}const i_={errors:{},statuses:{}};function r_(e=i_,t){return d({data:o_,errors:c(a_,bv),statuses:s_})(e,t)}function o_(e,t){var n;switch(t.type){case $t.LoadCheckoutSucceeded:case $t.UpdateCheckoutSucceeded:case Eg.ApplyStoreCreditSucceeded:case tt.UpdateBillingAddressSucceeded:case kt.ApplyCouponSucceeded:case kt.RemoveCouponSucceeded:case _g.CreateConsignmentsSucceeded:case _g.UpdateConsignmentSucceeded:case _g.DeleteConsignmentSucceeded:case _g.UpdateShippingOptionSucceeded:case _g.LoadShippingOptionsSucceeded:case Nt.ApplyGiftCertificateSucceeded:case Nt.RemoveGiftCertificateSucceeded:case rn.VerifyCheckoutSucceeded:return Bv(e,le(t.payload,["billingAddress","cart","consignments","customer","coupons","giftCertificates"]));case Mm.SubmitOrderSucceeded:return Ov(e,"orderId",t.payload&&t.payload.order.orderId);case Yt.HydrateInitialState:return Bv(e,le(null===(n=t.payload)||void 0===n?void 0:n.checkout,["billingAddress","cart","consignments","customer","coupons","giftCertificates"]));default:return e}}function a_(e=i_.errors,t){switch(t.type){case $t.LoadCheckoutRequested:case $t.LoadCheckoutSucceeded:return Ov(e,"loadError",void 0);case $t.LoadCheckoutFailed:return Ov(e,"loadError",t.payload);case $t.UpdateCheckoutRequested:case $t.UpdateCheckoutSucceeded:return Ov(e,"updateError",void 0);case $t.UpdateCheckoutFailed:return Ov(e,"updateError",t.payload);default:return e}}function s_(e=i_.statuses,t){switch(t.type){case $t.LoadCheckoutRequested:return Ov(e,"isLoading",!0);case $t.LoadCheckoutFailed:case $t.LoadCheckoutSucceeded:return Ov(e,"isLoading",!1);case $t.UpdateCheckoutRequested:return Ov(e,"isUpdating",!0);case $t.UpdateCheckoutFailed:case $t.UpdateCheckoutSucceeded:return Ov(e,"isUpdating",!1);case rn.ExecuteRequested:return Ov(e,"isExecutingSpamCheck",!0);case rn.ExecuteFailed:case rn.ExecuteSucceeded:return Ov(e,"isExecutingSpamCheck",!1);default:return e}}function d_(e,t){if(null==e)throw t?t():new Error("An unexpected error has occurred.");return e}function c_(e){return function(e){const t=Object.create(e);return function(e,t){let n=Object.getPrototypeOf(e);for(;n;)t(n),n=Object.getPrototypeOf(n)}(e,n=>{Object.getOwnPropertyNames(n).forEach(n=>{"constructor"!==n&&"function"==typeof t[n]&&"_"!==n.charAt(0)&&(t[n]=((e,t)=>(...n)=>p(e[t].call(e,...n)))(e,n))})}),t}(e)}const l_={"mollie.credit_card":{provider:"mollie",method:"credit_card"},"adyenv2.scheme":{provider:"adyenv2",method:"scheme"},"adyenv3.scheme":{provider:"adyenv3",method:"scheme"},"adyenv2.bcmc":{provider:"adyenv2",method:"bcmc"},"adyenv2.ideal":{provider:"adyenv2",method:"ideal"},"adyenv2.sepadirectdebit":{provider:"adyenv2",method:"sepadirectdebit"},"adyenv2.directEbanking":{provider:"adyenv2",method:"directEbanking"},"adyenv2.giropay":{provider:"adyenv2",method:"giropay"},braintree:{provider:"braintree",method:"credit_card"},braintreepaypal:{provider:"braintree",method:"paypal"},braintreeach:{provider:"braintree",method:"ach"},authorizenet:{provider:"authorizenet",method:"credit_card"},elavon:{provider:"elavon",method:"credit_card"},checkoutcom:{provider:"checkoutcom",method:"credit_card"},"checkoutcom.credit_card":{provider:"checkoutcom",method:"credit_card"},"checkoutcom.card":{provider:"checkoutcom",method:"card"},sagepay:{provider:"sagepay",method:"credit_card"},stripe:{provider:"stripe",method:"credit_card"},"stripev3.card":{provider:"stripev3",method:"card"},"stripeupe.card":{provider:"stripeupe",method:"card"},cybersource:{provider:"cybersource",method:"credit_card"},cybersourcev2:{provider:"cybersourcev2",method:"credit_card"},bnz:{provider:"bnz",method:"credit_card"},converge:{provider:"converge",method:"credit_card"},bluesnapv2:{provider:"bluesnapv2",method:"credit_card"},"bluesnapdirect.credit_card":{provider:"bluesnapdirect",method:"credit_card"},"bluesnapdirect.ecp":{provider:"bluesnapdirect",method:"ecp"},"bluesnapdirect.sepa_direct_debit":{provider:"bluesnapdirect",method:"sepa_direct_debit"},orbital:{provider:"orbital",method:"credit_card"},paymetric:{provider:"paymetric",method:"credit_card"},bolt:{provider:"bolt",method:"credit_card"},"barclaycard.credit_card":{provider:"barclaycard",method:"credit_card"},moneris:{provider:"moneris",method:"credit_card"},cba_mpgs:{provider:"cba_mpgs",method:"credit_card"},worldpayaccess:{provider:"worldpayaccess",method:"credit_card"},"worldpayaccess.credit_card":{provider:"worldpayaccess",method:"credit_card"},squarev2:{provider:"squarev2",method:"credit_card"},paypalcommercecreditcards:{provider:"paypalcommerce",method:"credit_card"},paypalcommerce:{provider:"paypalcommerce",method:"paypal"},bigcommerce_payments_creditcards:{provider:"bigcommerce_payments",method:"credit_card"},bigcommerce_payments:{provider:"bigcommerce_payments",method:"paypal"},tdonlinemart:{provider:"tdonlinemart",method:"credit_card"}};function u_(e){return me({firstName:e.firstName,lastName:e.lastName,company:e.company,address1:e.address1,address2:e.address2,city:e.city,stateOrProvince:e.stateOrProvince,countryCode:e.countryCode,postalCode:e.postalCode,phone:e.phone,customFields:e.customFields},G)}const h_={errors:{},statuses:{}};function p_(){const e=function(){const e=vv(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.token},e=>()=>e),t=vv(e=>e.errors.loadError,e=>()=>e),n=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((i=Ev)=>({getToken:e(i),getLoadError:t(i),isLoading:n(i)}))}(),t=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingBillingAddress))),n=vv(e=>e.errors.updateError,e=>()=>e),i=vv(e=>e.errors.continueAsGuestError,e=>()=>e),r=vv(e=>e.errors.loadError,e=>()=>e),o=vv(e=>!!e.statuses.isUpdating,e=>()=>e),a=vv(e=>!!e.statuses.isContinuingAsGuest,e=>()=>e),s=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((d=zv)=>({getBillingAddress:e(d),getBillingAddressOrThrow:t(d),getUpdateError:n(d),getContinueAsGuestError:i(d),getLoadError:r(d),isUpdating:o(d),isContinuingAsGuest:a(d),isLoading:s(d)}))}(),n=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingCart))),n=vv(e=>e.errors.loadError,e=>()=>e),i=vv(e=>!!e.statuses.isLoading,e=>()=>e),r=vv(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.locale},e=>()=>e);return Oe((o=jv)=>({getCart:e(o),getCartOrThrow:t(o),getLoadError:n(o),isLoading:i(o),getLocale:r(o)}))}(),i=function(){const e=vv(e=>e,e=>()=>e),t=vv(e=>e.statuses,e=>Pe(t=>{if(t){const n=e[t];return!0===(n&&n.isInitializing)}return ve(e,{isInitializing:!0})})),n=vv(e=>e.data,e=>Pe((t,n)=>{const i=e[t];return!!i&&(n?!0===i.initializedContainers[n]:ve(i.initializedContainers,e=>!0===e))})),i=vv(e=>e.statuses,e=>Pe(t=>{if(t){const n=e[t];return!0===(n&&n.isDeinitializing)}return ve(e,{isDeinitializing:!0})})),r=vv(e=>e.errors,e=>Pe(t=>{const n=t?e[t]:B(Ce(e),e=>!(!e||!e.initializeError));return n&&n.initializeError})),o=vv(e=>e.errors,e=>Pe(t=>{const n=t?e[t]:B(Ce(e),e=>!(!e||!e.deinitializeError));return n&&n.deinitializeError}));return Oe((a=Wv)=>({getState:e(a),isInitializing:t(a),isInitialized:n(a),isDeinitializing:i(a),getInitializeError:r(a),getDeinitializeError:o(a)}))}(),r=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.data,e=>t=>{if(!e)return;const{flashMessages:n}=e.context;return n?void 0!==t?n.filter(({type:e})=>t===e):n:void 0}),n=vv(e=>e.data,(e,{formState:t})=>t&&t.data,(e,t={customerAccount:[],shippingAddress:[],billingAddress:[]})=>()=>e?Object.assign(Object.assign({},e.storeConfig),{formFields:t}):void 0),i=vv(n,e=>()=>d_(e(),()=>new rt(et.MissingCheckoutConfig))),r=vv(e=>e.data&&e.data.context,e=>()=>e),o=vv(e=>e.meta&&e.meta.externalSource,e=>()=>e),a=vv(e=>{var t;return null===(t=e.meta)||void 0===t?void 0:t.host},e=>()=>e),s=vv(e=>{var t;return null===(t=e.meta)||void 0===t?void 0:t.locale},e=>()=>e),d=vv(e=>e.meta&&e.meta.variantIdentificationToken,e=>()=>e),c=vv(e=>e.errors.loadError,e=>()=>e),l=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((u=ef,h)=>({getConfig:e(u),getFlashMessages:t(u),getStoreConfig:n(u,{formState:h}),getStoreConfigOrThrow:i(u,{formState:h}),getContextConfig:r(u),getExternalSource:o(u),getHost:a(u),getLocale:s(u),getVariantIdentificationToken:d(u),getLoadError:c(u),isLoading:l(u)}))}(),o=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.loadError,e=>()=>e),n=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((i=Ff)=>({getCountries:e(i),getLoadError:t(i),isLoading:n(i)}))}(),a=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.removeCouponError,e=>()=>e),n=vv(e=>e.errors.applyCouponError,e=>()=>e),i=vv(e=>!!e.statuses.isApplyingCoupon,e=>()=>e),r=vv(e=>!!e.statuses.isRemovingCoupon,e=>()=>e);return Oe((o=af)=>({getCoupons:e(o),getRemoveError:t(o),getApplyError:n(o),isApplying:i(o),isRemoving:r(o)}))}(),s=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingCustomer))),n=vv(e=>e.errors.createError,e=>()=>e),i=vv(e=>!!e.statuses.isCreating,e=>()=>e),r=vv(e=>e.errors.createAddressError,e=>()=>e),o=vv(e=>!!e.statuses.isCreatingAddress,e=>()=>e);return Oe((a=gf)=>({getCustomer:e(a),getCustomerOrThrow:t(a),getCreateAccountError:n(a),isCreatingCustomerAccount:i(a),getCreateAddressError:r(a),isCreatingCustomerAddress:o(a)}))}(),d=function(){const e=vv(e=>e.errors.signInMethodId,e=>e.errors.signInError,(e,t)=>n=>{if(!n||e===n)return t}),t=vv(e=>e.errors.signOutMethodId,e=>e.errors.signOutError,(e,t)=>n=>{if(!n||e===n)return t}),n=vv(e=>e.errors.executePaymentMethodCheckoutMethodId,e=>e.errors.executePaymentMethodCheckoutError,(e,t)=>n=>{if(!n||e===n)return t}),i=vv(e=>e.errors.initializeMethodId,e=>e.errors.initializeErrors,(e,t)=>n=>{if(e&&t)return n?t[n]:t[e]}),r=vv(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>n=>{if(!n||e===n)return t}),o=vv(e=>e.statuses.signInMethodId,e=>e.statuses.isSigningIn,(e,t)=>n=>!(n&&e!==n||!t)),a=vv(e=>e.statuses.signOutMethodId,e=>e.statuses.isSigningOut,(e,t)=>n=>!(n&&e!==n||!t)),s=vv(e=>e.statuses.executePaymentMethodCheckoutMethodId,e=>e.statuses.isExecutingPaymentMethodCheckout,(e,t)=>n=>!(n&&e!==n||!t)),d=vv(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>n=>!(n&&e!==n||!t)),c=vv(e=>e.data,e=>t=>!(!e[t]||!e[t].isInitialized)),l=vv(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((u=wf)=>({getSignInError:e(u),getSignOutError:t(u),getExecutePaymentMethodCheckoutError:n(u),getInitializeError:i(u),getWidgetInteractionError:r(u),isSigningIn:o(u),isSigningOut:a(u),isExecutingPaymentMethodCheckout:s(u),isInitializing:d(u),isInitialized:c(u),isWidgetInteracting:l(u)}))}(),c=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.removeGiftCertificateError,e=>()=>e),n=vv(e=>e.errors.applyGiftCertificateError,e=>()=>e),i=vv(e=>!!e.statuses.isApplyingGiftCertificate,e=>()=>e),r=vv(e=>!!e.statuses.isRemovingGiftCertificate,e=>()=>e);return Oe((o=uf)=>({getGiftCertificates:e(o),getRemoveError:t(o),getApplyError:n(o),isApplying:i(o),isRemoving:r(o)}))}(),l=function(){const e=vv(e=>e.data,e=>t=>{if(!e)return;const n=t.gateway?`${t.gateway}.${t.id}`:t.id,i=l_[n];return i?L(e,i):[]}),t=vv(e=>e.data,(e=[])=>t=>{const n=Ce(l_);return e.find(e=>e.bigpayToken===t&&"card"===e.type&&n.some(t=>K(e,t)))}),n=vv(t,e=>t=>d_(e(t),()=>new rt(et.MissingPaymentInstrument))),i=vv(e=>e.data,e=>()=>{if(e)return U(l_,t=>L(e,e=>K(e,t)))}),r=vv(e=>e.meta,e=>()=>e),o=vv(e=>e.errors.loadError,e=>()=>e),a=vv(e=>e.errors.failedInstrument,e=>e.errors.deleteError,(e,t)=>n=>{if(!n||e===n)return t}),s=vv(e=>e.statuses.isLoading,e=>()=>!!e),d=vv(e=>e.statuses.deletingInstrument,e=>e.statuses.isDeleting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((c=pS)=>({getCardInstrument:t(c),getCardInstrumentOrThrow:n(c),getInstruments:i(c),getInstrumentsByPaymentMethod:e(c),getInstrumentsMeta:r(c),getLoadError:o(c),getDeleteError:a(c),isLoading:s(c),isDeleting:d(c)}))}(),u=function(){const e=vv(e=>e.data,e=>(t=[],n)=>{const i=B(t,{code:n});return(e?e.shippingAddress:[]).map(e=>a(e,t,i))}),t=vv(e=>e.data,e=>(t=[],n)=>{const i=B(t,{code:n});return(e?e.billingAddress:[]).map(e=>a(e,t,i))}),n=vv(e=>e.data,e=>()=>e?e.customerAccount:[]),i=vv(e=>e.extraFields,e=>()=>e&&e.address.length?e.address.map(Ke):[]),r=vv(e=>e.errors.loadError,e=>()=>e),o=vv(e=>!!e.statuses.isLoading,e=>()=>e);function a(e,t,n){return"countryCode"===e.name?function(e,t=[],n){if(!t.length)return e;const{code:i=""}=n||{},r=t.map(({code:e,name:t})=>({value:e,label:t}));return Object.assign(Object.assign({},e),{options:{items:r},default:i,type:"array",fieldType:"dropdown",itemtype:"string"})}(e,t,n):"stateOrProvince"===e.name?function(e,t){const{subdivisions:n=[],requiresState:i}=t||{};if(!n.length)return Object.assign(Object.assign({},e),{required:null!=i&&i});const r=n.map(({code:e,name:t})=>({value:e,label:t}));return Object.assign(Object.assign({},e),{name:"stateOrProvinceCode",options:{items:r},required:null==i||i,type:"array",fieldType:"dropdown",itemtype:"string"})}(e,n):"postalCode"===e.name?function(e,t){const{hasPostalCodes:n=[]}=t||{};return void 0===n?e:Object.assign(Object.assign({},e),{required:Boolean(n)})}(e,n):e}return Oe((a=Df)=>({getShippingAddressFields:e(a),getBillingAddressFields:t(a),getCustomerAccountFields:n(a),getAddressExtraFields:i(a),getLoadError:r(a),isLoading:o(a)}))}(),h=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.meta,e=>()=>e),n=vv(e=>e.data,e=>(t,n)=>B(e,n?{id:t,gateway:n}:{id:t})),i=vv(n,e=>(t,n)=>d_(e(t,n),()=>new rt(et.MissingPaymentMethod))),r=vv(e=>e.errors.loadError,e=>()=>e),o=vv(e=>e.errors.loadMethodId,e=>e.errors.loadMethodError,(e,t)=>n=>{if(!n||e===n)return t}),a=vv(e=>e.statuses.isLoading,e=>()=>!!e),s=vv(e=>e.statuses.loadMethodId,e=>e.statuses.isLoadingMethod,(e,t)=>n=>!(n&&e!==n||!t));return Oe((d=Xf)=>({getPaymentMethods:e(d),getPaymentMethodsMeta:t(d),getPaymentMethod:n(d),getPaymentMethodOrThrow:i(d),getLoadError:r(d),getLoadMethodError:o(d),isLoading:a(d),isLoadingMethod:s(d)}))}(),p=function(){const e=vv(e=>e.errors.initializeMethodId,e=>e.errors.initializeError,(e,t)=>n=>{if(!n||e===n)return t}),t=vv(e=>e.errors.executeMethodId,e=>e.errors.executeError,(e,t)=>n=>{if(!n||e===n)return t}),n=vv(e=>e.errors.finalizeMethodId,e=>e.errors.finalizeError,(e,t)=>n=>{if(!n||e===n)return t}),i=vv(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>n=>{if(!n||e===n)return t}),r=vv(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>n=>!(n&&e!==n||!t)),o=vv(e=>e.data,e=>t=>{const n=t.gatewayId?`${t.methodId}.${t.gatewayId}`:t.methodId;return!(!e[n]||!e[n].isInitialized)}),a=vv(e=>e.statuses.executeMethodId,e=>e.statuses.isExecuting,(e,t)=>n=>!(n&&e!==n||!t)),s=vv(e=>e.statuses.finalizeMethodId,e=>e.statuses.isFinalizing,(e,t)=>n=>!(n&&e!==n||!t)),d=vv(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((c=oS)=>({getInitializeError:e(c),getExecuteError:t(c),getFinalizeError:n(c),getWidgetInteractingError:i(c),isInitializing:r(c),isInitialized:o(c),isExecuting:a(c),isFinalizing:s(c),isWidgetInteracting:d(c)}))}(),m=function(){const e=vv(e=>e.data,e=>(t,n)=>{if(!e)return;const i=AS(ES({consignmentId:t,searchArea:n})),r=btoa(`${JSON.stringify(i)}`);return e[r]}),t=vv(e=>e.errors.loadError,e=>()=>e),n=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((i=TS)=>({getPickupOptions:e(i),getLoadError:t(i),isLoading:n(i)}))}(),y=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingPaymentProviderCustomer)));return Oe((n=lS)=>({getPaymentProviderCustomer:e(n),getPaymentProviderCustomerOrThrow:t(n)}))}(),g=function(){const e=vv(e=>e.data,e=>t=>e[t]);return Oe((t=SS)=>({getCheckout:e(t)}))}(),v=function(){const e=vv(e=>e.data,e=>()=>{const t=null==e?void 0:e.find(e=>!e.selectedPickupOption);return null==t?void 0:t.shippingAddress}),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingShippingAddress))),n=vv(e=>e.data,e=>()=>{const t=null==e?void 0:e.filter(e=>!e.selectedPickupOption);return t?t.map(e=>e.shippingAddress):[]}),i=vv(n,e=>()=>d_(e(),()=>new rt(et.MissingShippingAddress)));return Oe((r=IS)=>({getShippingAddress:e(r),getShippingAddressOrThrow:t(r),getShippingAddresses:n(r),getShippingAddressesOrThrow:i(r)}))}(),f=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.loadError,e=>()=>e),n=vv(e=>e.statuses.isLoading,e=>()=>!!e);return Oe((i=NS)=>({getShippingCountries:e(i),getLoadError:t(i),isLoading:n(i)}))}(),S=function(){const e=vv(e=>e.errors.updateAddressMethodId,e=>e.errors.updateAddressError,(e,t)=>n=>{if(!n||e===n)return t}),t=vv(e=>e.errors.selectOptionMethodId,e=>e.errors.selectOptionError,(e,t)=>n=>{if(!n||e===n)return t}),n=vv(e=>e.errors.initializeMethodId,e=>e.errors.initializeError,(e,t)=>n=>{if(!n||e===n)return t}),i=vv(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>n=>{if(!n||e===n)return t}),r=vv(e=>e.statuses.updateAddressMethodId,e=>e.statuses.isUpdatingAddress,(e,t)=>n=>!(n&&e!==n||!t)),o=vv(e=>e.statuses.selectOptionMethodId,e=>e.statuses.isSelectingOption,(e,t)=>n=>!(n&&e!==n||!t)),a=vv(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>n=>!(n&&e!==n||!t)),s=vv(e=>e.data,e=>t=>!(!e[t]||!e[t].isInitialized)),d=vv(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((c=BS)=>({getUpdateAddressError:e(c),getSelectOptionError:t(c),getInitializeError:n(c),getWidgetInteractionError:i(c),isUpdatingAddress:r(c),isSelectingOption:o(c),isInitializing:a(c),isInitialized:s(c),isWidgetInteracting:d(c)}))}(),_=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingConsignments))),n=vv(e=>e.data,e=>t=>{if(e&&e.length)return B(e,{id:t})}),i=vv(e=>e.data,e=>t=>{if(e&&e.length)return B(e,e=>{return n=e.shippingAddress,i=t,Y(u_(n),u_(i));var n,i})}),r=vv(e=>e.data,e=>()=>{if(e&&e.length)return e[0].selectedShippingOption}),o=vv(e=>e.errors.loadError,e=>()=>e),a=vv(e=>e.errors.createError,e=>()=>e),s=vv(e=>e.errors.loadShippingOptionsError,e=>()=>e),d=vv(e,(e,{cart:t})=>t.getCart,(e,t)=>()=>{const n=t();if(!n)return[];const i=(e()||[]).reduce((e,t)=>e.concat(t.lineItemIds),[]);return(n.lineItems.physicalItems||[]).filter(e=>i.indexOf(e.id)<0)}),c=vv(e=>e.errors.updateError,e=>t=>t?e[t]:B(e)),l=vv(e=>e.errors.deleteError,e=>t=>t?e[t]:B(e)),u=vv(i,c,a,(e,t,n)=>i=>{const r=e(i);return r?t(r.id):n()}),h=vv(e=>e.errors.updateShippingOptionError,e=>t=>t?e[t]:B(e)),p=vv(e=>e.statuses.isLoading,e=>()=>!0===e),m=vv(e=>e.statuses.isLoadingShippingOptions,e=>()=>!0===e),y=vv(e=>e.statuses.isCreating,e=>()=>!0===e),g=vv(e=>e.statuses.isUpdating,e=>t=>t?!0===e[t]:!0===B(e)),v=vv(e=>e.statuses.isDeleting,e=>t=>t?!0===e[t]:!0===B(e)),f=vv(i,g,y,(e,t,n)=>i=>{const r=e(i);return r?t(r.id):n()}),S=vv(e=>e.statuses.isUpdatingShippingOption,e=>t=>t?!0===e[t]:!0===B(e));return Oe((_=IS,w)=>({getConsignments:e(_),getConsignmentsOrThrow:t(_),getConsignmentById:n(_),getConsignmentByAddress:i(_),getShippingOption:r(_),getLoadError:o(_),getCreateError:a(_),getLoadShippingOptionsError:s(_),getUnassignedItems:d(_,{cart:w}),getUpdateError:c(_),getDeleteError:l(_),getItemAssignmentError:u(_),getUpdateShippingOptionError:h(_),isLoading:p(_),isLoadingShippingOptions:m(_),isCreating:y(_),isUpdating:g(_),isDeleting:v(_),isAssigningItems:f(_),isUpdatingShippingOption:S(_)}))}(),w=function(){const e=vv(e=>e.data,(e,{billingAddress:t})=>t.getBillingAddress,(e,{cart:t})=>t.getCart,(e,{customer:t})=>t.getCustomer,(e,{consignments:t})=>t.getConsignments,(e,{coupons:t})=>t.getCoupons,(e,{giftCertificates:t})=>t.getGiftCertificates,(e,t,n,i,r,o,a)=>()=>{const s=t(),d=n(),c=i(),l=r()||[],u=o()||[],h=a()||[];if(e&&d&&c)return Object.assign(Object.assign({},e),{billingAddress:s,cart:d,customer:c,consignments:l,coupons:u,giftCertificates:h})}),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingCheckout))),n=vv(e,e=>t=>{const n=e();if(!n)return;const i=n.grandTotal||0,r=n.customer.storeCredit||0;return t?Math.max(i-r,0):n.outstandingBalance}),i=vv(e=>e.errors.loadError,e=>()=>e),r=vv(e=>e.errors.updateError,e=>()=>e),o=vv(e=>e.statuses.isExecutingSpamCheck,e=>()=>!0===e),a=vv(e=>e.statuses.isLoading,e=>()=>!0===e),s=vv(e=>e.statuses.isUpdating,e=>()=>!0===e);return Oe((d=i_,c,l,u,h,p,m)=>({getCheckout:e(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getCheckoutOrThrow:t(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getOutstandingBalance:n(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getLoadError:i(d),getUpdateError:r(d),isExecutingSpamCheck:o(d),isLoading:a(d),isUpdating:s(d)}))}(),I=function(){const e=vv(e=>e.data,(e,{billingAddress:t})=>t.getOrderBillingAddress(),(e,{coupons:t})=>t.getCoupons(),(e,t,n=[])=>()=>{if(e&&t)return Object.assign(Object.assign({},e),{billingAddress:t,coupons:n})}),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingOrder))),n=vv(e=>e.meta,e=>()=>e),i=vv(e=>e.errors.loadError,e=>()=>e),r=vv(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.payments},(e=[])=>t=>{const n=e.find(({providerId:e})=>e===t);return null==n?void 0:n.paymentId}),o=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((a=qf,s,d)=>({getOrder:e(a,{billingAddress:s,coupons:d}),getOrderOrThrow:t(a,{billingAddress:s,coupons:d}),getOrderMeta:n(a),getLoadError:i(a),getPaymentId:r(a),isLoading:o(a)}))}(),C=function(){const e=vv(e=>e.data,e=>()=>e);return Oe((t=Yf)=>({getOrderBillingAddress:e(t)}))}(),b=function(){const e=vv(({order:e})=>e.getOrderMeta,e=>()=>{const t=e();return t&&t.payment}),t=vv(({order:e})=>e.getOrder,e=>()=>{const t=e();return B(t&&t.payments,({providerId:e})=>"giftcertificate"!==e&&"storecredit"!==e)}),n=vv(({checkout:e})=>e.getCheckout,e=>()=>{const t=e();return B(t&&t.payments,({providerType:e})=>"PAYMENT_TYPE_HOSTED"===e)}),i=vv(e,n,t,(e,t,n)=>()=>{const i=e();if(i&&i.id)return{providerId:i.id,gatewayId:i.gateway};const r=t()||n();return r&&r.providerId?{providerId:r.providerId,gatewayId:r.gatewayId}:void 0}),r=vv(i,e=>()=>d_(e(),()=>new rt(et.MissingPaymentId))),o=vv(e,n,t,(e,t,n)=>()=>{const i=e();if(i&&i.status)return i.status.replace("PAYMENT_STATUS_","");const r=t()||n();return r?r.detail.step:void 0}),a=vv(o,e=>()=>d_(e(),()=>new rt(et.MissingPaymentStatus))),s=vv(({order:e})=>e.getOrderMeta,e=>()=>{const t=e();return t&&t.token}),d=vv(s,e=>()=>d_(e(),()=>new rt(et.MissingPaymentToken))),c=vv(e,e=>()=>{const t=e();return t&&t.redirectUrl}),l=vv(c,e=>()=>d_(e(),()=>new rt(et.MissingPaymentRedirectUrl))),u=vv(({checkout:e})=>e.getOutstandingBalance,e=>(t=!1)=>{const n=e(t);return!!n&&n>0}),h=vv(o,e=>t=>!(!t||!t.nonce)||"ACKNOWLEDGE"===e()||e()===$y);return Oe((e,t)=>({getPaymentId:i({checkout:e,order:t}),getPaymentIdOrThrow:r({checkout:e,order:t}),getPaymentStatus:o({checkout:e,order:t}),getPaymentStatusOrThrow:a({checkout:e,order:t}),getPaymentToken:s({checkout:e,order:t}),getPaymentTokenOrThrow:d({checkout:e,order:t}),getPaymentRedirectUrl:c({checkout:e,order:t}),getPaymentRedirectUrlOrThrow:l({checkout:e,order:t}),isPaymentDataRequired:u({checkout:e,order:t}),isPaymentDataSubmitted:h({checkout:e,order:t})}))}(),P=function(){const e=vv(e=>e.errors.applyError,e=>()=>e),t=vv(e=>!!e.statuses.isApplying,e=>()=>e);return Oe((n=h_)=>({getApplyError:e(n),isApplying:t(n)}))}(),O=function(){const e=vv(e=>e.errors.updateError,e=>()=>e),t=vv(e=>!!e.statuses.isUpdating,e=>()=>e);return Oe((n=XS)=>({getUpdateError:e(n),isUpdating:t(n)}))}(),E=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.sendError,e=>()=>e),n=vv(e=>!!e.statuses.isSending,e=>()=>e);return Oe((i=GS)=>({getEmail:e(i),getSendError:t(i),isSending:n(i)}))}(),A=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.data,e=>t=>null==e?void 0:e.find(e=>e.region===t)),n=vv(e=>e.errors.loadError,e=>()=>e),i=vv(e=>e.statuses.isLoading,e=>()=>!!e);return Oe((r=Of)=>({getExtensions:e(r),getExtensionByRegion:t(r),getLoadError:n(r),isLoading:i(r)}))}();return(T,k={})=>{const D=e(T.b2bToken),M=t(T.billingAddress),z=n(T.cart),N=i(T.checkoutButton),x=o(T.countries),R=a(T.coupons),F=s(T.customer),L=d(T.customerStrategies),B=A(T.extensions),j=u(T.formFields),U=c(T.giftCertificates),q=l(T.instruments),V=C(T.orderBillingAddress),G=h(T.paymentMethods),H=y(T.paymentProviderCustomer),W=p(T.paymentStrategies),$=m(T.pickupOptions),Y=g(T.remoteCheckout),K=v(T.consignments),J=f(T.shippingCountries),Z=S(T.shippingStrategies),Q=O(T.subscriptions),X=P(T.storeCredit),ee=E(T.signInEmail),te=_(T.consignments,z),ne=w(T.checkout,M,z,te,R,F,U),ie=I(T.order,V,R),re=b(ne,ie),oe={b2bToken:D,billingAddress:M,cart:z,checkout:ne,checkoutButton:N,config:r(T.config,T.formFields),consignments:te,countries:x,coupons:R,customer:F,customerStrategies:L,extensions:B,form:j,giftCertificates:U,instruments:q,order:ie,orderBillingAddress:V,payment:re,paymentMethods:G,paymentProviderCustomer:H,paymentStrategies:W,pickupOptions:$,remoteCheckout:Y,shippingAddress:K,shippingCountries:J,shippingStrategies:Z,signInEmail:ee,subscriptions:Q,storeCredit:X};return k.shouldWarnMutation?(ae=oe,Object.keys(ae).reduce((e,t)=>(e[t]=c_(ae[t]),e),{})):oe;var ae}}function m_(e={},t){const n=(o=function(){const e=new Iv;return["catalog_only","empty_cart","invalid_order_id","invalid_order_token","missing_order_token","missing_provider_token","missing_shipping_method","order_completion_error","order_could_not_be_finalized_error","order_create_failed","provider_fatal_error","provider_setup_error","stock_too_low"].forEach(t=>{e.register(t,(e,t)=>new Sv(e,t))}),e.register("invalid_payment_provider",e=>new Xr(e)),e.register("payment_config_not_found",e=>new Xr(e)),e}(),e=>S(e).pipe(P(e=>{if(e instanceof Error||e.payload instanceof Error)throw e;if((t=e.payload)&&"object"==typeof t&&["body","headers","status","statusText"].every(e=>Object.prototype.hasOwnProperty.call(t,e))){const t=e.payload.body&&e.payload.body.detail;throw Object.assign(Object.assign({},e),{payload:o.createError(e.payload,t)})}var t;throw e}))),i=p_(),r=d({b2bToken:Av,billingAddress:Nv,cart:Uv,checkout:r_,checkoutButton:Jv,config:tf,consignments:CS,countries:Lf,coupons:sf,customer:vf,customerStrategies:If,extensions:Ef,formFields:Mf,giftCertificates:hf,instruments:mS,orderBillingAddress:Kf,order:Vf,payment:Zf,paymentMethods:eS,paymentStrategies:aS,pickupOptions:kS,paymentProviderCustomer:uS,remoteCheckout:_S,shippingCountries:xS,shippingStrategies:jS,signInEmail:HS,subscriptions:e_,storeCredit:JS});var o;return u(r,e,Object.assign({actionTransformer:n,stateTransformer:e=>i(e)},t))}function y_(e){"https:"!==document.location.protocol&&wt().warn("The BigCommerce Checkout SDK should not be used on a non-HTTPS page"),"production"!==vt()&&wt().warn("Note that the development build is not optimized. To create a production build, set process​.env.NODE_ENV to `production`.");const t={meta:{externalSource:e&&e.externalSource,host:null==e?void 0:e.host,locale:null==e?void 0:e.locale,variantIdentificationToken:window.checkoutVariantIdentificationToken},errors:{},statuses:{}},{locale:i="",shouldWarnMutation:r=!0}=e||{},s=n({host:e&&e.host}),d=m_({config:t},{shouldWarnMutation:r}),c=new gt(s,{getBasePath:()=>{var e,t;return null!==(t=null===(e=d.getState().config.getStoreConfig())||void 0===e?void 0:e.links.baseUrl)&&void 0!==t?t:void 0},getFeatures:()=>{var e,t,n;return null!==(n=null===(t=null===(e=d.getState().config.getStoreConfig())||void 0===e?void 0:e.checkoutSettings)||void 0===t?void 0:t.features)&&void 0!==n?n:{}}}),l=Gm(d),u=new jm(c),h=new en(c),p=new bt(new Tt(s)),m=Sn(o()),y=new _n(c),g=new pn(m,y),v=new Vm(u,new ny(h)),f=new Ng(new xg(c)),S=new on(new an(c)),_=new nn(h,p,S),w=Hg(d,c),I=function(e,t,n={useFallback:!1}){const{useFallback:i}=n,r=new Gt(i);for(const[,n]of Object.entries(t))if(Ut(n))for(const t of n.resolveIds)r.register(t,()=>n(e));return r}(w,He,{useFallback:!0}),C=function(e,t){const n=new Gt;for(const[,i]of Object.entries(t))if(Ut(i))for(const t of i.resolveIds)n.register(t,()=>i(e));return n}(w,Ge),b=new xn(new Rn(c)),P=new Hn,O=new Kn(d,P),E=mt(d,function(){const e=function(){const e=vv(({checkout:e})=>e.getCheckout,e=>Bg(e)),t=vv(({order:e})=>e.getOrder,e=>Bg(e)),n=vv(({config:e})=>e.getStoreConfig,e=>Bg(e)),i=vv(({shippingAddress:e})=>e.getShippingAddress,({config:e})=>e.getContextConfig,(e,t)=>Bg(()=>{const n=e(),i=t();if(!n){if(!i||!i.geoCountryCode)return;return{firstName:"",lastName:"",company:"",address1:"",address2:"",city:"",stateOrProvince:"",stateOrProvinceCode:"",postalCode:"",country:"",phone:"",customFields:[],countryCode:i.geoCountryCode}}return n})),r=vv(({consignments:e})=>e.getConsignments,e=>Bg(()=>{const t=e(),n=null==t?void 0:t.find(e=>!e.selectedPickupOption);return null==n?void 0:n.availableShippingOptions})),o=vv(({consignments:e})=>e.getConsignments,e=>Bg(e)),a=vv(({consignments:e})=>e.getConsignments,e=>Bg(()=>{const t=e(),n=null==t?void 0:t.find(e=>!e.selectedPickupOption);return null==n?void 0:n.selectedShippingOption})),s=vv(({shippingCountries:e})=>e.getShippingCountries,e=>Bg(e)),d=vv(({billingAddress:e})=>e.getBillingAddress,({config:e})=>e.getContextConfig,(e,t)=>Bg(()=>{const n=e(),i=t();return(!n||Ce(le(n,"shouldSaveAddress","email","id")).every(e=>!e||!e.length))&&i&&i.geoCountryCode?{id:n?n.id:"",firstName:"",lastName:"",company:"",address1:"",address2:"",city:"",email:n?n.email:"",stateOrProvince:"",stateOrProvinceCode:"",postalCode:"",country:"",phone:"",customFields:[],countryCode:i.geoCountryCode}:n})),c=vv(({countries:e})=>e.getCountries,e=>Bg(e)),l=vv(({paymentMethods:e})=>e.getPaymentMethods,e=>Bg(e)),u=vv(({paymentMethods:e})=>e.getPaymentMethod,e=>Bg(e)),h=vv(({payment:e})=>e.getPaymentId,({paymentMethods:e})=>e.getPaymentMethod,(e,t)=>Bg(()=>{const n=e();return n&&t(n.providerId,n.gatewayId)})),p=vv(({cart:e})=>e.getCart,e=>Bg(e)),m=vv(({coupons:e})=>e.getCoupons,e=>Bg(e)),y=vv(({giftCertificates:e})=>e.getGiftCertificates,e=>Bg(e)),g=vv(({customer:e})=>e.getCustomer,e=>Bg(e)),v=vv(({signInEmail:e})=>e.getEmail,e=>Bg(e)),f=vv(({b2bToken:e})=>e.getToken,e=>Bg(e)),S=vv(({payment:e})=>e.isPaymentDataRequired,e=>Bg(e)),_=vv(({payment:e})=>e.isPaymentDataSubmitted,({paymentMethods:e})=>e.getPaymentMethod,(e,t)=>Bg((n,i)=>e(t(n,i)))),w=vv(({instruments:e})=>e.getInstruments,({instruments:e})=>e.getInstrumentsByPaymentMethod,(e,t)=>Bg(function(n){return n?t(n):e()})),I=vv(({form:e})=>e.getCustomerAccountFields,e=>Bg(e)),C=vv(({form:e})=>e.getBillingAddressFields,({countries:e})=>e.getCountries,(e,t)=>Bg(n=>e(t(),n))),b=vv(({form:e})=>e.getShippingAddressFields,({shippingCountries:e})=>e.getShippingCountries,(e,t)=>Bg(n=>e(t(),n))),P=vv(({form:e})=>e.getAddressExtraFields,e=>Bg(e)),O=vv(({config:e})=>e.getFlashMessages,e=>Bg(e)),E=vv(({pickupOptions:e})=>e.getPickupOptions,e=>Bg(e)),A=vv(({config:e})=>e.getStoreConfig,e=>Bg(()=>{const t=e();if(t)return t.checkoutSettings.checkoutUserExperienceSettings})),T=vv(({extensions:e})=>e.getExtensions,e=>Bg(e)),k=vv(({paymentProviderCustomer:e})=>e.getPaymentProviderCustomer,e=>Bg(e)),D=vv(({extensions:e})=>e.getExtensionByRegion,e=>Bg(e));return Oe(M=>({getCheckout:e(M),getOrder:t(M),getConfig:n(M),getExtensions:T(M),getExtensionByRegion:D(M),getFlashMessages:O(M),getShippingAddress:i(M),getShippingOptions:r(M),getConsignments:o(M),getSelectedShippingOption:a(M),getShippingCountries:s(M),getBillingAddress:d(M),getBillingCountries:c(M),getPaymentMethods:l(M),getPaymentMethod:u(M),getSelectedPaymentMethod:h(M),getCart:p(M),getCoupons:m(M),getGiftCertificates:y(M),getCustomer:g(M),isPaymentDataRequired:S(M),isPaymentDataSubmitted:_(M),getSignInEmail:v(M),getB2BToken:f(M),getInstruments:w(M),getCustomerAccountFields:I(M),getBillingAddressFields:C(M),getShippingAddressFields:b(M),getAddressExtraFields:P(M),getPickupOptions:E(M),getUserExperienceSettings:A(M),getPaymentProviderCustomer:k(M)}))}(),t=function(){const e=fv(e=>e,e=>()=>{for(const t of Object.keys(e)){const n=e[t]();if(n)return n}}),t=vv(({shippingStrategies:e})=>e.getSelectOptionError,({consignments:e})=>e.getUpdateShippingOptionError,(e,t)=>n=>e()||t(n));return Oe(n=>{const i={getLoadCheckoutError:n.checkout.getLoadError,getUpdateCheckoutError:n.checkout.getUpdateError,getSubmitOrderError:n.paymentStrategies.getExecuteError,getFinalizeOrderError:n.paymentStrategies.getFinalizeError,getLoadOrderError:n.order.getLoadError,getLoadCartError:n.cart.getLoadError,getLoadBillingCountriesError:n.countries.getLoadError,getLoadShippingCountriesError:n.shippingCountries.getLoadError,getLoadPaymentMethodsError:n.paymentMethods.getLoadError,getLoadPaymentMethodError:n.paymentMethods.getLoadMethodError,getInitializePaymentError:n.paymentStrategies.getInitializeError,getSignInError:n.customerStrategies.getSignInError,getSignOutError:n.customerStrategies.getSignOutError,getInitializeCustomerError:n.customerStrategies.getInitializeError,getLoadShippingOptionsError:n.consignments.getLoadShippingOptionsError,getSelectShippingOptionError:t(n),getContinueAsGuestError:n.billingAddress.getContinueAsGuestError,getUpdateBillingAddressError:n.billingAddress.getUpdateError,getUpdateSubscriptionsError:n.subscriptions.getUpdateError,getUpdateShippingAddressError:n.shippingStrategies.getUpdateAddressError,getDeleteConsignmentError:n.consignments.getDeleteError,getUpdateConsignmentError:n.consignments.getUpdateError,getCreateConsignmentsError:n.consignments.getCreateError,getInitializeShippingError:n.shippingStrategies.getInitializeError,getApplyStoreCreditError:n.storeCredit.getApplyError,getApplyCouponError:n.coupons.getApplyError,getRemoveCouponError:n.coupons.getRemoveError,getApplyGiftCertificateError:n.giftCertificates.getApplyError,getRemoveGiftCertificateError:n.giftCertificates.getRemoveError,getLoadInstrumentsError:n.instruments.getLoadError,getDeleteInstrumentError:n.instruments.getDeleteError,getLoadConfigError:n.config.getLoadError,getSignInEmailError:n.signInEmail.getSendError,getLoadB2BTokenError:n.b2bToken.getLoadError,getCreateCustomerAccountError:n.customer.getCreateAccountError,getCreateCustomerAddressError:n.customer.getCreateAddressError,getPickupOptionsError:n.pickupOptions.getLoadError,getLoadExtensionsError:n.extensions.getLoadError};return Object.assign({getError:e(i)},i)})}(),n=function(){const e=fv(e=>e,e=>()=>Object.keys(e).some(t=>e[t]())),t=vv(({shippingStrategies:e})=>e.isSelectingOption,({consignments:e})=>e.isUpdatingShippingOption,(e,t)=>n=>e()||t(n)),n=vv(({customerStrategies:e})=>e.isInitializing,({customerStrategies:e})=>e.isSigningIn,({customerStrategies:e})=>e.isSigningOut,({customerStrategies:e})=>e.isExecutingPaymentMethodCheckout,({customerStrategies:e})=>e.isWidgetInteracting,(e,t,n,i,r)=>o=>e(o)||t(o)||n(o)||i(o)||r(o)),i=vv(({shippingStrategies:e})=>e.isInitializing,({shippingStrategies:e})=>e.isUpdatingAddress,({shippingStrategies:e})=>e.isSelectingOption,({shippingStrategies:e})=>e.isWidgetInteracting,(e,t,n,i)=>r=>e(r)||t(r)||n(r)||i(r)),r=vv(({paymentStrategies:e})=>e.isInitializing,({paymentStrategies:e})=>e.isExecuting,({paymentStrategies:e})=>e.isFinalizing,({paymentStrategies:e})=>e.isWidgetInteracting,(e,t,n,i)=>r=>e(r)||t(r)||n(r)||i(r)),o=vv(({paymentStrategies:e})=>e.isExecuting,({checkout:e})=>e.isExecutingSpamCheck,(e,t)=>n=>e(n)||t());return Oe(a=>{const s={isLoadingCheckout:a.checkout.isLoading,isUpdatingCheckout:a.checkout.isUpdating,isExecutingSpamCheck:a.checkout.isExecutingSpamCheck,isSubmittingOrder:o(a),isFinalizingOrder:a.paymentStrategies.isFinalizing,isLoadingOrder:a.order.isLoading,isLoadingCart:a.cart.isLoading,isLoadingBillingCountries:a.countries.isLoading,isLoadingShippingCountries:a.shippingCountries.isLoading,isLoadingPaymentMethods:a.paymentMethods.isLoading,isLoadingPaymentMethod:a.paymentMethods.isLoadingMethod,isInitializingPayment:a.paymentStrategies.isInitializing,isSigningIn:a.customerStrategies.isSigningIn,isSigningOut:a.customerStrategies.isSigningOut,isExecutingPaymentMethodCheckout:a.customerStrategies.isExecutingPaymentMethodCheckout,isInitializingCustomer:a.customerStrategies.isInitializing,isInitializedCustomer:a.customerStrategies.isInitialized,isLoadingShippingOptions:a.consignments.isLoadingShippingOptions,isSelectingShippingOption:t(a),isUpdatingBillingAddress:a.billingAddress.isUpdating,isUpdatingSubscriptions:a.subscriptions.isUpdating,isCreatingCustomerAccount:a.customer.isCreatingCustomerAccount,isCreatingCustomerAddress:a.customer.isCreatingCustomerAddress,isContinuingAsGuest:a.billingAddress.isContinuingAsGuest,isUpdatingShippingAddress:a.shippingStrategies.isUpdatingAddress,isUpdatingConsignment:a.consignments.isUpdating,isDeletingConsignment:a.consignments.isDeleting,isCreatingConsignments:a.consignments.isCreating,isInitializingShipping:a.shippingStrategies.isInitializing,isApplyingStoreCredit:a.storeCredit.isApplying,isApplyingCoupon:a.coupons.isApplying,isRemovingCoupon:a.coupons.isRemoving,isApplyingGiftCertificate:a.giftCertificates.isApplying,isRemovingGiftCertificate:a.giftCertificates.isRemoving,isLoadingInstruments:a.instruments.isLoading,isDeletingInstrument:a.instruments.isDeleting,isLoadingConfig:a.config.isLoading,isSendingSignInEmail:a.signInEmail.isSending,isLoadingB2BToken:a.b2bToken.isLoading,isCustomerStepPending:n(a),isShippingStepPending:i(a),isPaymentStepPending:r(a),isLoadingPickupOptions:a.pickupOptions.isLoading};return Object.assign({isPending:e(s)},s)})}();return i=>({data:e(i),errors:t(i),statuses:n(i)})}());return new yv(d,E,O,function(e,t){const n={[$n.ConsignmentsChanged]:Zn};return new Jn(e,t,n)}(E,O),new Qe(new nt(s)),new st(new ut(c),f),_,p,new Kt(new Jt(c),_,g),new Cg(new Pg(c),h),new zm(new Nm(c,{locale:i})),new Dt(new Lt(c)),new Qt(function(e,t){const n=new Vt,i=a(),r=new en(t),o=new nn(r,new bt(new Tt(t)),new on(new an(t))),s=new pn(Sn(i),new _n(t)),d=new Kt(new Jt(t),o,s);return n.register("default",()=>new wn(e,d)),n}(d,c),C,w),new yt,new Bt(new jt(c)),new Wg(new Zg(l,c)),v,new Wm(new $m(c)),new Xm(function(e,t,n){const i=new Wy({defaultToken:Zm.CREDIT_CARD}),r=new Gy,a=new by(t),s=new en(n),d=new ny(s),c=new Vm(new jm(n),d),l=new cy(Sn(o())),u=new Cy(a,c,r,l),h=Ee(),p=((e,t)=>new ig(new ng(e,t)))(h,l),m=new Iy(e);return i.register(Zm.CONVERGE,()=>new Zy(e,c,u,m,h)),i.register(Zm.PPSDK,()=>new dg(e,c,((e,t,n,i,r)=>{const o=new lg;return o.register(ag.CARD,()=>new hg(e,t,r,i)),o.register(ag.NONE,()=>new pg(n,i)),o.register(ag.UNSUPPORTED,()=>{}),o})(e,c,n,p,m),new vg(n,p),new iy("PPSDK"))),i}(d,l,c),I,v,g,w),new Qg(new Xg(c)),new Ag(new Tg(c,{locale:i}),d),new ev(function(e,t){const n=new Vt,i=Hg(e),r=new en(t),o=new Pg(t),s=new Cg(o,r),d=new Wm(new $m(t)),c=a(),l=new Ng(new xg(t)),u=new st(new ut(t),l),h=window,p=new Ei(i);return n.register("amazonpay",()=>new iv(e,s,new Wm(new $m(t)),gi(),new ev(n))),n.register("stripeupe",()=>new lv(e,new Ra(c),s,d)),n.register("braintreeacceleratedcheckout",()=>new ov(e,u,s,d,new Sg,new _o(new Hi(a(),h,p),h))),n.register("paypalcommerceacceleratedcheckout",()=>new dv(e,u,s,d,new Sg,Cs(),nd())),n.register("default",()=>new av(e,s)),n}(d,c)),new uv(new hv(c)),g,new Dg(new Mg(c)),f,S,b,P)}class g_ extends Qn{constructor(e){super(e||"An unexpected error has occurred during config creation process. Please try again later."),this.name="AmazonPayV2ConfigCreationError",this.type="amazon_pay_v2_config_creation_error"}}function v_(e){return e instanceof Object&&"buyNowInitializeOptions"in e}var f_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class S_{constructor(e,t,n){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t,this.amazonPayV2ConfigRequestSender=n}initialize(e){var t;return f_(this,void 0,void 0,function*(){const{methodId:n,containerId:i,amazonpay:r}=e,{buttonColor:o}=r||{};if(!n||!i)throw new fi('Unable to proceed because "methodId" or "containerId" argument is not provided.');const{getPaymentMethodOrThrow:a}=this.paymentIntegrationService.getState(),s=a(n),{initializationData:d}=s;yield this.amazonPayV2PaymentProcessor.initialize(s),r||(yield this.paymentIntegrationService.loadDefaultCheckout());const c=v_(r)?void 0:r;v_(r)&&"function"==typeof(null===(t=r.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody)&&(this._buyNowInitializeOptions=r.buyNowInitializeOptions,this.amazonPayV2PaymentProcessor.updateBuyNowFlowFlag(!0)),this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:this.paymentIntegrationService.getState(),containerId:i,methodId:n,options:c,placement:si.Cart,buttonColor:o,isButtonMicroTextDisabled:null==d?void 0:d.isButtonMicroTextDisabled}),this._buyNowInitializeOptions&&this.amazonPayV2PaymentProcessor.prepareCheckoutWithCreationRequestConfig(this._getCheckoutCreationRequestConfig.bind(this))})}deinitialize(){return this.amazonPayV2PaymentProcessor.deinitialize()}_createBuyNowCartOrThrow(){var e,t;return f_(this,void 0,void 0,function*(){const n=null===(t=null===(e=this._buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody)||void 0===t?void 0:t.call(e);if(!n)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(n)}catch(e){throw new er}})}_createCheckoutConfig(e){return f_(this,void 0,void 0,function*(){try{const t=(yield this.amazonPayV2ConfigRequestSender.createCheckoutConfig(e)).body,{payload:n,public_key:i}=t,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const t=n(),i=new __(t),r=gi();return new S_(e,r,i)},[{id:"amazonpay"}]);var I_,C_,b_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}(I_||(I_={})),function(e){e.Black="black",e.White="white",e.WhiteBorder="white-border"}(C_||(C_={}));class P_{constructor(e,t,n,i,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._braintreeSdk=i,this._applePayScriptLoader=r,this._onAuthorizeCallback=ce,this._subTotalLabel=I_.Subtotal,this._shippingLabel=I_.Shipping}initialize(e){var t,n;return b_(this,void 0,void 0,function*(){const{methodId:i,containerId:r,applepay:o}=e;if(!i||!o)throw new ti(Xn.MissingPaymentMethod);yield this._applePayScriptLoader.loadSdk();const{onPaymentAuthorize:a,buyNowInitializeOptions:s,requiresShipping:d}=o;this._requiresShipping=d,this._buyNowInitializeOptions=s,this._onAuthorizeCallback=a,s||(yield this._paymentIntegrationService.loadDefaultCheckout()),yield this._paymentIntegrationService.loadPaymentMethod(i);const c=this._paymentIntegrationService.getState();return this._paymentMethod=c.getPaymentMethodOrThrow(i),c.getCart()&&(yield this._paymentIntegrationService.verifyCheckoutSpamProtection()),(null===(t=this._paymentMethod.initializationData)||void 0===t?void 0:t.gateway)===Vi.BRAINTREE&&this._paymentMethod.clientToken&&this._braintreeSdk.initialize(this._paymentMethod.clientToken),this._applePayButton=this._createButton(r,null===(n=this._paymentMethod.initializationData)||void 0===n?void 0:n.styleOption),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),Promise.resolve()})}deinitialize(){return Promise.resolve()}_createButton(e,t){const n=document.getElementById(e);if(!n)throw new fi("Unable to create wallet button without valid container ID.");const i=this._createApplePayButtonElement(t);return n.appendChild(i),i}_createApplePayButtonElement(e){const t=document.createElement("apple-pay-button");return t.setAttribute("buttonstyle",(e=>{switch(e){case C_.White:return"white";case C_.WhiteBorder:return"white-outline";case C_.Black:default:return"black"}})(e)),t.setAttribute("type","plain"),t.setAttribute("style","--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;"),t}_handleWalletButtonClick(e){var t;return b_(this,void 0,void 0,function*(){if(e.preventDefault(),!this._paymentMethod||!this._paymentMethod.initializationData)throw new ti(Xn.MissingPaymentMethod);if(this._buyNowInitializeOptions&&"function"==typeof this._buyNowInitializeOptions.getBuyNowCartRequestBody){const{countryCode:e,currencyCode:n,merchantCapabilities:i,supportedNetworks:r,storeName:o}=this._paymentMethod.initializationData,a=this._getRequestWithEmptyTotal(e,n,r,i);this._requiresShipping&&(null===(t=a.requiredShippingContactFields)||void 0===t||t.push("postalAddress"));const s=this._sessionFactory.create(a);this._handleApplePayEvents(s,this._paymentMethod,o),s.begin()}else{const e=this._paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getStoreConfigOrThrow(),i=e.getCheckoutOrThrow(),r=this._getBaseRequest(t,i,n,this._paymentMethod),o=this._sessionFactory.create(r);this._handleApplePayEvents(o,this._paymentMethod,n.storeProfile.storeName),o.begin()}})}_getRequestWithEmptyTotal(e,t,n,i){return{countryCode:e,currencyCode:t,supportedNetworks:n,merchantCapabilities:i,total:{label:"",amount:"0",type:"pending"},requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"]}}_getBaseRequest(e,t,n,i){var r;const{storeProfile:{storeCountryCode:o,storeName:a}}=n,{currency:{code:s,decimalPlaces:d}}=e,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=i,u=e.lineItems.physicalItems.length>0,h={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:o,currencyCode:s,merchantCapabilities:c,supportedNetworks:l,lineItems:[],total:u?{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"pending"}:{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"final"}};if(u)null===(r=h.requiredShippingContactFields)||void 0===r||r.push("postalAddress");else{const e=[{label:this._subTotalLabel,amount:`${t.subtotal.toFixed(d)}`}];t.taxes.forEach(t=>e.push({label:t.name,amount:`${t.amount.toFixed(d)}`})),h.lineItems=e}return h}_handleApplePayEvents(e,t,n){e.onvalidatemerchant=n=>b_(this,void 0,void 0,function*(){try{const{body:i}=yield this._onValidateMerchant(t,n);e.completeMerchantValidation(i)}catch(e){throw new Error("Merchant validation failed")}}),this._buyNowInitializeOptions&&!this._requiresShipping&&(e.onpaymentmethodselected=()=>b_(this,void 0,void 0,function*(){yield this._createBuyNowCart(),this._handlePaymentMethodSelected(e)})),e.onshippingcontactselected=t=>b_(this,void 0,void 0,function*(){this._buyNowInitializeOptions&&this._requiresShipping&&(yield this._createBuyNowCart()),yield this._handleShippingContactSelected(e,n,t)}),e.onshippingmethodselected=t=>b_(this,void 0,void 0,function*(){yield this._handleShippingMethodSelected(e,n,t)}),e.oncancel=()=>b_(this,void 0,void 0,function*(){try{const e=`/remote-checkout/${t.id}/signout`;return yield this._requestSender.get(e),yield this._paymentIntegrationService.loadCheckout()}catch(e){throw new Wi}}),e.onpaymentauthorized=n=>b_(this,void 0,void 0,function*(){return this._onPaymentAuthorized(n,e,t)})}_createBuyNowCart(){var e,t;return b_(this,void 0,void 0,function*(){try{const n=null===(t=null===(e=this._buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody)||void 0===t?void 0:t.call(e);if(!n)throw new ti(Xn.MissingCart);const i=yield this._paymentIntegrationService.createBuyNowCart(n);yield this._paymentIntegrationService.loadCheckout(i.id);const r=this._paymentIntegrationService.getState(),{shouldExecuteSpamCheck:o}=r.getCheckoutOrThrow();o&&(yield this._paymentIntegrationService.verifyCheckoutSpamProtection())}catch(e){throw new er}})}_handlePaymentMethodSelected(e){const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getStoreConfigOrThrow(),r=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new ti(Xn.MissingPaymentMethod);const o=this._getBaseRequest(n,r,i,this._paymentMethod);delete o.total.type,e.completePaymentMethodSelection({newTotal:o.total,newLineItems:o.lineItems})}_handleShippingContactSelected(e,t,n){var i;return b_(this,void 0,void 0,function*(){const r=this._transformContactToAddress(n.shippingContact);try{yield this._paymentIntegrationService.updateShippingAddress(r)}catch(t){throw e.abort(),new Error("Shipping address update failed")}let o=this._paymentIntegrationService.getState();const{currency:{decimalPlaces:a}}=o.getCartOrThrow();let s=o.getCheckoutOrThrow();const d=null===(i=s.consignments[0].selectedShippingOption)||void 0===i?void 0:i.id,c=s.consignments[0].availableShippingOptions,l=null==c?void 0:c.find(({id:e})=>e===d),u=null==c?void 0:c.filter(e=>e.id!==d),h=l?[{label:l.description,amount:`${l.cost.toFixed(a)}`,detail:l.additionalDescription,identifier:l.id}]:[];if(u&&[...u.filter(e=>e.isRecommended),...u.filter(e=>!e.isRecommended)].forEach(e=>h.push({label:e.description,amount:`${e.cost.toFixed(a)}`,detail:e.additionalDescription,identifier:e.id})),!(c instanceof Array))throw new Error("Shipping options not available.");if(0===c.length)return void e.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:t,amount:`${s.grandTotal.toFixed(a)}`},[]);const p=c.find(e=>e.isRecommended),m=p?p.id:c[0].id,y=l?l.id:m;try{yield this._updateShippingOption(y)}catch(e){throw new Error("Shipping options update failed")}o=this._paymentIntegrationService.getState(),s=o.getCheckoutOrThrow(),e.completeShippingContactSelection({newShippingMethods:h,newTotal:{type:"final",label:t,amount:`${s.grandTotal.toFixed(a)}`},newLineItems:this._getUpdatedLineItems(s,a)})})}_handleShippingMethodSelected(e,t,n){return b_(this,void 0,void 0,function*(){const{shippingMethod:{identifier:i}}=n;try{yield this._updateShippingOption(i)}catch(t){throw e.abort(),new Error("Shipping option selection update failed.")}const r=this._paymentIntegrationService.getState(),{currency:{decimalPlaces:o}}=r.getCartOrThrow(),a=r.getCheckoutOrThrow();e.completeShippingMethodSelection({newTotal:{type:"final",label:t,amount:`${a.grandTotal.toFixed(o)}`},newLineItems:this._getUpdatedLineItems(a,o)})})}_getUpdatedLineItems(e,t){const n=[{label:this._subTotalLabel,amount:`${e.subtotal.toFixed(t)}`}];return e.taxes.forEach(e=>n.push({label:e.name,amount:`${e.amount.toFixed(t)}`})),n.push({label:this._shippingLabel,amount:`${e.shippingCostTotal.toFixed(t)}`}),n}_updateShippingOption(e){return b_(this,void 0,void 0,function*(){return this._paymentIntegrationService.selectShippingOption(e)})}_onValidateMerchant(e,t){return b_(this,void 0,void 0,function*(){const n=[`validationUrl=${t.validationURL}`,`merchantIdentifier=${e.initializationData.merchantId}`,`displayName=${e.initializationData.storeName}`,`domainName=${window.location.hostname}`].join("&");return this._requestSender.post(`${e.initializationData.paymentsUrl}/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})})}_onPaymentAuthorized(e,t,n){var i;return b_(this,void 0,void 0,function*(){const{token:r,billingContact:o,shippingContact:a}=e.payment,s=this._paymentIntegrationService.getState().getCartOrThrow().lineItems.physicalItems.length>0;let d;(null===(i=n.initializationData)||void 0===i?void 0:i.gateway)===Vi.BRAINTREE&&(d=yield this._getBraintreeDeviceData());const c={methodId:n.id,paymentData:{deviceSessionId:d,formattedPayload:{apple_pay_token:{payment_data:r.paymentData,payment_method:r.paymentMethod,transaction_id:r.transactionIdentifier}}}},l=this._transformContactToAddress(o),u=this._transformContactToAddress(a),h=null==a?void 0:a.emailAddress,p=(null==a?void 0:a.phoneNumber)||"";try{return yield this._paymentIntegrationService.updateBillingAddress(Object.assign(Object.assign({},l),{email:h,phone:p})),s&&(yield this._paymentIntegrationService.updateShippingAddress(u)),yield this._paymentIntegrationService.submitOrder({useStoreCredit:!1}),yield this._paymentIntegrationService.submitPayment(c),t.completePayment(ApplePaySession.STATUS_SUCCESS),this._onAuthorizeCallback()}catch(e){throw t.completePayment(ApplePaySession.STATUS_FAILURE),new Error("Payment cannot complete")}})}_transformContactToAddress(e){return{firstName:(null==e?void 0:e.givenName)||"",lastName:(null==e?void 0:e.familyName)||"",city:(null==e?void 0:e.locality)||"",company:"",address1:(null==e?void 0:e.addressLines)&&e.addressLines[0]||"",address2:(null==e?void 0:e.addressLines)&&e.addressLines[1]||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||"",phone:(null==e?void 0:e.phoneNumber)||"",stateOrProvince:(null==e?void 0:e.administrativeArea)||"",stateOrProvinceCode:(null==e?void 0:e.administrativeArea)||"",customFields:[]}}_getBraintreeDeviceData(){return b_(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}const O_=vi(e=>{const{getHost:t}=e.getState(),i=new Ei(e);return new P_(n({host:t()}),e,new Zi,new Ui(new Hi(a(),window,i)),new Qi(new r))},[{id:"applepay"}]);var E_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class A_{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){var t;return E_(this,void 0,void 0,function*(){const{bigcommerce_payments:n,containerId:i,methodId:r}=e,o=Boolean(null==n?void 0:n.buyNowInitializeOptions);if(!r)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');if(o&&!n.currencyCode)throw new fi('Unable to initialize payment because "options.bigcommerce_payments.currencyCode" argument is not provided.');if(o&&"function"!=typeof(null===(t=n.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.bigcommerce_payments.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');o||(yield this.paymentIntegrationService.loadDefaultCheckout());const a=o?n.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(r,a,!1),this.renderButton(i,r,n,o)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n,i){var r,o;const{buyNowInitializeOptions:a,style:s,onComplete:d,onEligibilityFailure:c}=n,l=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),u=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:h,isAppSwitchEnabled:p}=u.initializationData||{},m=Object.assign(Object.assign({},!i&&this.isPaypalCommerceAppSwitchEnabled(t)&&{appSwitchWhenAvailable:!0}),{createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)}),y={onClick:()=>this.handleClick(a),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},g=Object.assign(Object.assign({},!p&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(e,n)=>this.onHostedCheckoutApprove(e,n,t,d)}),v=Object.assign(Object.assign(Object.assign({fundingSource:l.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(s)},m),a&&y),h&&g),f=l.Buttons(v);f.isEligible()?(null===(r=f.hasReturned)||void 0===r?void 0:r.call(f))&&this.isPaypalCommerceAppSwitchEnabled(t)?null===(o=f.resume)||void 0===o||o.call(f):f.render(`#${e}`):c&&"function"==typeof c?c():this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return E_(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,n,i){return E_(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return E_(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return E_(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}isPaypalCommerceAppSwitchEnabled(e){var t,n;return null!==(n=null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)&&void 0!==n&&n}}const T_=vi(e=>new A_(e,_r(e)),[{id:"bigcommerce_payments"}]);var k_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class D_{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return k_(this,void 0,void 0,function*(){const{bigcommerce_payments_paylater:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');if(a&&!o)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=this.paymentIntegrationService.getState(),d=a?o:s.getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i,d,!1),this.renderButton(n,i,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){const{buyNowInitializeOptions:i,style:r,onComplete:o,onEligibilityFailure:a}=n,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:c}=d.initializationData||{},l={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},u={onClick:()=>this.handleClick(i),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},h={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(e,n)=>this.onHostedCheckoutApprove(e,n,t,o)},p=[s.FUNDING.PAYLATER,s.FUNDING.CREDIT];let m=!1;p.forEach(t=>{if(!m){const n=Object.assign(Object.assign(Object.assign({fundingSource:t,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(r)},l),i&&u),c&&h),o=s.Buttons(n);o.isEligible()?(o.render(`#${e}`),m=!0):a&&"function"==typeof a&&a()}}),m||this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return k_(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,n,i){return k_(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return k_(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return k_(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}}const M_=vi(e=>new D_(e,_r(e)),[{id:"bigcommerce_payments_paylater"}]);var z_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class N_{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return z_(this,void 0,void 0,function*(){const{bigcommerce_payments_venmo:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');if(a&&!o)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=a?o:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i,s,!1),this.renderButton(n,i,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){const{buyNowInitializeOptions:i,style:r,onEligibilityFailure:o}=n,a=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),s=a.FUNDING.VENMO,d={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},c={onClick:()=>this.handleClick(i),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},l=Object.assign(Object.assign({fundingSource:s,style:this.getValidVenmoButtonStyles(r)},d),i&&c),u=a.Buttons(l);u.isEligible()?u.render(`#${e}`):o&&"function"==typeof o?o():this.bigCommercePaymentsIntegrationService.removeElement(e)}getValidVenmoButtonStyles(e){const t=this.bigCommercePaymentsIntegrationService.getValidButtonStyle(e);return t.color===ar.gold?Object.assign(Object.assign({},t),{color:void 0}):t}handleClick(e){return z_(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const x_=vi(e=>new N_(e,_r(e)),[{id:"bigcommerce_payments_venmo"}]);class R_{constructor(e,t,n=window){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=n}initialize(e){return t=this,n=void 0,r=function*(){const{bolt:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,style:o}=t||{};if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bolt" argument is not provided.');if(!Boolean(r))throw new Si("Only buy now flow is implemented for Bolt button");if(!(null==r?void 0:r.storefrontApiToken)||"string"!=typeof r.storefrontApiToken)throw new fi('Unable to initialize payment because "options.storefrontApiToken" argument is not provided.');const a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i),{initializationData:s,config:d}=a,{publishableKey:c,developerConfig:l}=s||{};yield this.boltScriptLoader.loadBoltClient(c,d.testMode,l,"BigCommerce",r.storefrontApiToken),this.renderButton(n,a,o)},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}deinitialize(){return Promise.resolve()}renderButton(e,t,n){var i;"function"==typeof(null===(i=this.boltHostWindow.BoltConnect)||void 0===i?void 0:i.setupProductPageCheckout)&&(this.addButtonContainer(e,t,n),this.boltHostWindow.BoltConnect.setupProductPageCheckout())}addButtonContainer(e,t,n){const i=document.getElementById(e);if(!i)return;const r=document.createElement("div"),o=document.createElement("object");r.setAttribute("id","product-page-checkout-wrapper"),r.setAttribute("class","bolt-button-wrapper"),r.setAttribute("style","display:none"),r.setAttribute("data-tid","product-page-checkout-wrapper"),o.setAttribute("data",this.getBoltObjectData(t,n)),o.setAttribute("class","bolt-product-checkout-button"),r.append(o),i.innerHTML="",i.append(r)}getBoltObjectData(e,t){const{initializationData:n,config:i}=e,{publishableKey:r,developerConfig:o}=n||{},a=this.boltScriptLoader.getDomainURL(!!i.testMode,o),s=this.getButtonHeight(null==t?void 0:t.size),d=this.getButtonBorderRadius(null==t?void 0:t.shape,s);return xe({url:`https://${a}/v1/checkout_button`,query:{publishable_key:r,variant:"ppc",height:s,border_radius:d}})}getButtonHeight(e){if(e)switch(e){case to.Small:return 25;case to.Large:return 45;case to.Medium:default:return 40}}getButtonBorderRadius(e,t){if(e)switch(e){case no.Pill:return t?Math.round(t/2):void 0;case no.Rect:default:return 4}}}const F_=vi(e=>new R_(e,new ao(a())),[{id:"bolt"}]);function L_(e){const{color:t,fundingicons:n,height:i=40,layout:r,shape:o,size:a,tagline:s}=e||{},d={color:t,fundingicons:n,height:B_(i),layout:r,shape:o||"rect",size:a,tagline:s};return ue(d,J)}function B_(e){const t=Number(e);return!t||Number.isNaN(t)?40:t>55?55:t<25?25:t}var j_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class U_{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return j_(this,void 0,void 0,function*(){const{braintreepaypal:t,containerId:n,methodId:i}=e;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');let r,o=this.paymentIntegrationService.getState();if(t.buyNowInitializeOptions){if(!t.currencyCode)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');r=t.currencyCode}else yield this.paymentIntegrationService.loadDefaultCheckout(),o=this.paymentIntegrationService.getState(),r=o.getCartOrThrow().currency.code;const a=o.getPaymentMethodOrThrow(i),{clientToken:s,config:d,initializationData:c}=a;if(!s||!c)throw new ti(Xn.MissingPaymentMethod);const l={currency:r,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(l,e=>{this.renderPayPalButton(e,t,n,i,!!d.testMode)},e=>this.handleError(e,n,t.onError))})}deinitialize(){return j_(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}renderPayPalButton(e,t,n,i,r){const{style:o,shouldProcessPayment:a,onAuthorizeError:s,onEligibilityFailure:d}=t,{paypal:c}=this.braintreeHostWindow;if(c){const l=c.Buttons({env:r?"sandbox":"production",fundingSource:c.FUNDING.PAYPAL,style:L_(o),createOrder:()=>this.setupPayment(e,t,i),onApprove:t=>this.tokenizePayment(t,e,i,a,s)});l.isEligible()?l.render(`#${n}`):d&&"function"==typeof d&&d()}else this.braintreeIntegrationService.removeElement(n)}setupPayment(e,t,n){var i;return j_(this,void 0,void 0,function*(){const{onPaymentError:r,shippingAddress:o,buyNowInitializeOptions:a}=t;try{const r="function"==typeof(null==a?void 0:a.getBuyNowCartRequestBody)?yield this.createBuyNowCart(a.getBuyNowCartRequestBody()):void 0;this.buyNowCartId=null==r?void 0:r.id;const s=this.paymentIntegrationService.getState(),d=s.getCustomer(),c=s.getPaymentMethodOrThrow(n),l=r?r.cartAmount:s.getCartOrThrow().cartAmount,u=r?t.currencyCode:s.getCartOrThrow().currency.code,h=o||(null==d?void 0:d.addresses[0]),p=h?El(h):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:p,amount:l,currency:u,offerCredit:!1,intent:null===(i=c.initializationData)||void 0===i?void 0:i.intent})}catch(e){throw r&&(Ri(e)||e instanceof Qn)&&r(e),e}})}tokenizePayment(e,t,n,i,r){return j_(this,void 0,void 0,function*(){try{const{deviceData:r}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),o=yield t.tokenizePayment(e),{details:a,nonce:s}=o,d=this.braintreeIntegrationService.mapToLegacyBillingAddress(a),c=this.braintreeIntegrationService.mapToLegacyShippingAddress(a);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",provider:n,action:i?"process_payment":"set_external_checkout",nonce:s,device_data:r,billing_address:JSON.stringify(d),shipping_address:JSON.stringify(c)},this.buyNowCartId&&{cart_id:this.buyNowCartId})),o}catch(e){throw r&&(Ri(e)||e instanceof Qn)&&r(e),e}})}createBuyNowCart(e){return j_(this,void 0,void 0,function*(){if(!e)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(e)}catch(e){throw new er}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const q_=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t);return new U_(e,Ee(),i,t)},[{id:"braintreepaypal"}]);var V_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class G_{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return V_(this,void 0,void 0,function*(){const{braintreepaypalcredit:t,containerId:n,methodId:i}=e;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');let r,o=this.paymentIntegrationService.getState();if(t.buyNowInitializeOptions){if(!t.currencyCode)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');r=t.currencyCode}else yield this.paymentIntegrationService.loadDefaultCheckout(),o=this.paymentIntegrationService.getState(),r=o.getCartOrThrow().currency.code;const a=o.getPaymentMethodOrThrow(i),{clientToken:s,config:d,initializationData:c}=a;if(!s||!c)throw new ti(Xn.MissingPaymentMethod);const l={currency:r,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(l,e=>{this.renderPayPalButton(e,t,n,i,!!d.testMode)},e=>this.handleError(e,n,t.onError))})}deinitialize(){return V_(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}renderPayPalButton(e,t,n,i,r){const{style:o,shouldProcessPayment:a,onAuthorizeError:s,onEligibilityFailure:d}=t,{paypal:c}=this.braintreeHostWindow;let l=!1;c&&[c.FUNDING.PAYLATER,c.FUNDING.CREDIT].forEach(u=>{const h=u===c.FUNDING.CREDIT?Object.assign({label:go.CREDIT},L_(o)):L_(o);if(!l){const o=c.Buttons({env:r?"sandbox":"production",fundingSource:u,style:h,createOrder:()=>this.setupPayment(e,t,i),onApprove:t=>this.tokenizePayment(t,e,i,a,s)});o.isEligible()?(o.render(`#${n}`),l=!0):c.FUNDING.CREDIT&&d&&"function"==typeof d&&d()}}),c&&l||this.braintreeIntegrationService.removeElement(n)}setupPayment(e,t,n){var i;return V_(this,void 0,void 0,function*(){const{onPaymentError:r,shippingAddress:o,buyNowInitializeOptions:a}=t;try{const r="function"==typeof(null==a?void 0:a.getBuyNowCartRequestBody)?yield this.createBuyNowCart(a.getBuyNowCartRequestBody()):void 0;this.buyNowCartId=null==r?void 0:r.id;const s=this.paymentIntegrationService.getState(),d=s.getCustomer(),c=s.getPaymentMethodOrThrow(n),l=r?r.cartAmount:s.getCartOrThrow().cartAmount,u=r?t.currencyCode:s.getCartOrThrow().currency.code,h=o||(null==d?void 0:d.addresses[0]),p=h?El(h):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:p,amount:l,currency:u,offerCredit:!0,intent:null===(i=c.initializationData)||void 0===i?void 0:i.intent})}catch(e){throw r&&(Ri(e)||e instanceof Qn)&&r(e),e}})}tokenizePayment(e,t,n,i,r){return V_(this,void 0,void 0,function*(){try{const{deviceData:r}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),o=yield t.tokenizePayment(e),{details:a,nonce:s}=o,d=this.braintreeIntegrationService.mapToLegacyBillingAddress(a),c=this.braintreeIntegrationService.mapToLegacyShippingAddress(a);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",provider:n,action:i?"process_payment":"set_external_checkout",nonce:s,device_data:r,billing_address:JSON.stringify(d),shipping_address:JSON.stringify(c)},this.buyNowCartId&&{cart_id:this.buyNowCartId})),o}catch(e){throw r&&(Ri(e)||e instanceof Qn)&&r(e),e}})}createBuyNowCart(e){return V_(this,void 0,void 0,function*(){if(!e)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(e)}catch(e){throw new er}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const H_=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t);return new G_(e,Ee(),i,t)},[{id:"braintreepaypalcredit"}]);var W_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class $_{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n}initialize(e){return W_(this,void 0,void 0,function*(){const{containerId:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState(),{clientToken:r,initializationData:o,config:a}=i.getPaymentMethodOrThrow(n);if(!r||!o)throw new ti(Xn.MissingPaymentMethod);this.braintreeSdk.initialize(r);const s=yield this.braintreeSdk.getBraintreeVisaCheckout(),{currency:{code:d},cartAmount:c}=i.getCartOrThrow(),l=yield this.braintreeSdk.getVisaCheckoutSdk(a.testMode),u=s.createInitOptions({paymentRequest:{currencyCode:d,subtotal:String(c)},settings:{shipping:{collectShipping:!0}}});this.createSignInButton(t),yield l.init(u),l.on("payment.success",e=>W_(this,void 0,void 0,function*(){yield this.paymentSuccess(s,e)}))})}deinitialize(){return Promise.resolve()}paymentSuccess(e,t){return W_(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const n=this.paymentIntegrationService.getState(),i=n.getShippingAddress(),r=n.getBillingAddress(),{shippingAddress:o=this.toVisaCheckoutAddress(i),billingAddress:a=this.toVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}postForm(e,t){const{userData:n,billingAddress:i,shippingAddress:r,details:o}=e,{userEmail:a}=n,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,i)),shipping_address:JSON.stringify(this.getAddress(a,r))})}toVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}createSignInButton(e){const t=document.querySelector(`#${e}`);if(!t)throw new Error("Need a container to place the button");return this.insertVisaCheckoutButton(t)}insertVisaCheckoutButton(e){const t=document.createElement("div");return t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="flex-end",t.innerHTML='\n \n Tell Me More',e.appendChild(t),t}}const Y_=vi(e=>{const t=window,n=new Ei(e),i=new Ui(new Hi(a(),t,n));return new $_(e,Ee(),i)},[{id:"braintreevisacheckout"}]);function K_(e){const{billingAddress:t,email:n,firstName:i,lastName:r,phone:o,shippingAddress:a}=e,s=t||a;return{email:n,first_name:i,last_name:r,phone_number:o,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 J_(e){const{email:t,phone:n,shippingAddress:i}=e,r=(null==i?void 0:i.recipientName)||"",[o,a]=r.split(" ");return{email:t,first_name:o||"",last_name:a||"",phone_number:n,address_line_1:null==i?void 0:i.line1,address_line_2:null==i?void 0:i.line2,city:null==i?void 0:i.city,state:null==i?void 0:i.state,country_code:null==i?void 0:i.countryCode,postal_code:null==i?void 0:i.postalCode}}var Z_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const Q_=e=>{const{color:t,height:n}=e;return{backgroundColor:(i=t||"",i===yo.WHITE?"#FFFFFF":"#3D95CE"),backgroundPosition:"50% 50%",backgroundSize:"80px auto",backgroundImage:`url("/app/assets/img/payment-providers/venmo-logo-${t===yo.WHITE?yo.BLUE:yo.WHITE}.svg")`,backgroundRepeat:"no-repeat",borderRadius:"4px",cursor:"pointer",transition:"0.2s ease",minHeight:`${n||40}px`,minWidth:"150px",height:"100%",width:"100%",border:t===yo.WHITE?"1px solid black":"none"};var i};class X_{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n,this.onError=ce}initialize(e){return Z_(this,void 0,void 0,function*(){const{braintreevenmo:t,containerId:n,methodId:i}=e;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i),{clientToken:o,initializationData:a}=r,{paymentButtonStyles:s}=a,{cartButtonStyles:d}=s||{},c=(null==t?void 0:t.style)||d;if(!o||!a)throw new ti(Xn.MissingPaymentMethod);if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');yield this.paymentIntegrationService.loadDefaultCheckout(),this.onError=(null==t?void 0:t.onError)||this.handleError,this.braintreeSdk.initialize(o);try{const e=yield this.braintreeSdk.getVenmoCheckoutOrThrow();this.renderVenmoButton(e,n,null==t?void 0:t.buyNowInitializeOptions,c)}catch(e){(Ol(e)||function(e){return e instanceof Ai}(e))&&this.handleInitializationVenmoError(e,n)}})}deinitialize(){return Z_(this,void 0,void 0,function*(){return yield this.braintreeSdk.deinitialize(),Promise.resolve()})}handleError(e){throw new Error(e.message)}createBuyNowCart(e){return Z_(this,void 0,void 0,function*(){if("function"==typeof(null==e?void 0:e.getBuyNowCartRequestBody)){const t=null==e?void 0:e.getBuyNowCartRequestBody();if(!t)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}}})}handleInitializationVenmoError(e,t){return this.removeVenmoContainer(t),this.onError(e)}removeVenmoContainer(e){const t=document.getElementById(e);t&&t.remove()}renderVenmoButton(e,t,n,i){const r=document.getElementById(t),{color:o}=i||{};if(!r)throw new fi("Unable to create wallet button without valid container ID.");r.setAttribute("aria-label","Venmo"),Object.assign(r.style,Q_(i||{})),r.addEventListener("click",()=>Z_(this,void 0,void 0,function*(){r.setAttribute("disabled","true");const t=yield this.createBuyNowCart(n);e.tokenize&&e.tokenize((e,n)=>Z_(this,void 0,void 0,function*(){r.removeAttribute("disabled"),e&&this.onError(e),yield this.handlePostForm(n,null==t?void 0:t.id)}))})),o===yo.BLUE&&(r.addEventListener("mouseenter",()=>{r.style.backgroundColor="#0a7fc2"}),r.addEventListener("mouseleave",()=>{r.style.backgroundColor=Q_(i||{}).backgroundColor}))}handlePostForm(e,t){return Z_(this,void 0,void 0,function*(){const{deviceData:n}=yield this.braintreeSdk.getDataCollectorOrThrow(),{nonce:i,details:r}=e;this.formPoster.postForm("/checkout.php",Object.assign({nonce:i,provider:"braintreevenmo",payment_type:"paypal",device_data:n,action:"set_external_checkout",billing_address:JSON.stringify(K_(r)),shipping_address:JSON.stringify(J_(r))},t&&{cart_id:t}))})}}const ew=vi(e=>{const t=window,n=a(),i=new Ei(e),r=new Hi(n,t,i),o=new Ui(r);return new X_(e,Ee(),o)},[{id:"braintreevenmo"}]);var tw=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class nw{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t}initialize(e){var t,n,i;return tw(this,void 0,void 0,function*(){if(!e.methodId||!na(e.methodId))throw new fi('Unable to proceed because "methodId" is not a valid key.');if(this._methodId=e.methodId,!e.containerId)throw new fi('Unable to proceed because "containerId" is not a valid key.');const r=e[this._getMethodOrThrow()];if(!r)throw new fi("Unable to proceed without valid options.");const{buyNowInitializeOptions:o,currencyCode:a,buttonColor:s,buttonType:d,onError:c}=r;let l,u=this._paymentIntegrationService.getState();try{l=u.getPaymentMethodOrThrow(this._getMethodOrThrow())}catch(e){u=yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodOrThrow()),l=u.getPaymentMethodOrThrow(this._getMethodOrThrow())}if(this._countryCode=null===(t=l.initializationData)||void 0===t?void 0:t.storeCountry,this._googlePayPaymentProcessor.setIsWebViewExperimentOn(!!(null===(n=l.initializationData)||void 0===n?void 0:n.isWebViewExperimentOn)),o){if(!a)throw new fi('Unable to initialize payment because "options.currencyCode" argument is not provided.');this._currencyCode=a,this._buyNowInitializeOptions=o,yield this._googlePayPaymentProcessor.initialize(()=>l,this._getGooglePayClientOptions(),!!o,a)}else yield this._paymentIntegrationService.loadDefaultCheckout(),yield this._googlePayPaymentProcessor.initialize(()=>l,this._getGooglePayClientOptions());this._paymentButton=null!==(i=this._paymentButton)&&void 0!==i?i:this._googlePayPaymentProcessor.addPaymentButton(e.containerId,{buttonColor:null!=s?s:"default",buttonType:null!=d?d:"plain",onClick:this._handleClick(c)})})}deinitialize(){var e;return null===(e=this._paymentButton)||void 0===e||e.remove(),this._paymentButton=void 0,this._methodId=void 0,Promise.resolve()}_handleClick(e){return t=>tw(this,void 0,void 0,function*(){t.preventDefault();try{this._buyNowInitializeOptions?yield this._createBuyNowCartOrThrow(this._buyNowInitializeOptions):yield this._paymentIntegrationService.loadDefaultCheckout(),yield this._googlePayPaymentProcessor.initializeWidget(),yield this._interactWithPaymentSheet()}catch(t){let n=t;if(ta(t)){if("CANCELED"===t.statusCode)throw new Wi;n=new Qr(JSON.stringify(t))}throw null==e||e(new Qr("An error occurred while requesting your Google Pay payment details.")),n}})}_interactWithPaymentSheet(){var e;return tw(this,void 0,void 0,function*(){const t=yield this._googlePayPaymentProcessor.showPaymentSheet(),n=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(t),i=this._googlePayPaymentProcessor.mapToShippingAddressRequestBody(t),r="/embedded-checkout"===window.location.pathname?this._paymentIntegrationService.getState().getStoreConfigOrThrow().links.siteLink:void 0;n&&(yield this._paymentIntegrationService.updateBillingAddress(n)),i&&!(null===(e=this._buyNowCart)||void 0===e?void 0:e.lineItems.digitalItems.length)&&(yield this._paymentIntegrationService.updateShippingAddress(i)),yield this._googlePayPaymentProcessor.setExternalCheckoutForm(this._getMethodOrThrow(),t,r)})}_getGooglePayClientOptions(){return this._googlePayPaymentProcessor.isWebViewWithRestrictions()?{}:{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:e,shippingAddress:t,shippingOptionData:n,offerData:i})=>tw(this,void 0,void 0,function*(){const{availableTriggers:r,addressChangeTriggers:o,shippingOptionsChangeTriggers:a,offerChangeTriggers:s}=this._googlePayPaymentProcessor.getCallbackTriggers();if(!r.includes(e))return;const d=o.includes(e)?yield this._googlePayPaymentProcessor.handleShippingAddressChange(t):void 0;a.includes(e)&&(yield this._googlePayPaymentProcessor.handleShippingOptionChange(n.id));const{newOfferInfo:c,error:l}=s.includes(e)?yield this._googlePayPaymentProcessor.handleCoupons(i):{},u=l;return this._buyNowInitializeOptions?this._getBuyNowTransactionInfo(d,c,u):this._getTransactionInfo(d,c,u)})}}}_createBuyNowCartOrThrow(e){return tw(this,void 0,void 0,function*(){if("function"==typeof(null==e?void 0:e.getBuyNowCartRequestBody)){const t=e.getBuyNowCartRequestBody();try{this._buyNowCart=yield this._paymentIntegrationService.createBuyNowCart(t),yield this._paymentIntegrationService.loadCheckout(this._buyNowCart.id)}catch(e){if("string"==typeof e)throw new er(e);throw e}}})}_getBuyNowTransactionInfo(e,t,n){if(!this._buyNowCart)return;const{cartAmount:i}=this._buyNowCart,r=this._googlePayPaymentProcessor.getTotalPrice();return Object.assign(Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},this._countryCode&&{countryCode:this._countryCode}),{currencyCode:this._getCurrencyCodeOrThrow(),totalPrice:r||String(i),totalPriceStatus:Wo.FINAL})},e&&{newShippingOptionParameters:e}),t&&{newOfferInfo:t}),n&&{error:n})}_getTransactionInfo(e,t,n){return tw(this,void 0,void 0,function*(){yield this._paymentIntegrationService.loadCheckout();const i=this._googlePayPaymentProcessor.getTotalPrice(),{code:r}=this._paymentIntegrationService.getState().getCartOrThrow().currency;return Object.assign(Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},this._countryCode&&{countryCode:this._countryCode}),{currencyCode:r,totalPriceStatus:Wo.FINAL,totalPrice:i})},e&&{newShippingOptionParameters:e}),t&&{newOfferInfo:t}),n&&{error:n})})}_getMethodOrThrow(){return ii(this._methodId,()=>new ri(ei.PaymentNotInitialized))}_getCurrencyCodeOrThrow(){return ii(this._currencyCode,()=>new fi('Unable to initialize payment because "options.currencyCode" argument is not provided.'))}}const iw=vi(e=>{const t=n(),i=window,r=new Ei(e),o=new Ui(new Hi(a(),i,r));return new nw(e,new aa(da(),new $a(e,o),t,Ee()))},[{id:"googlepaybraintree"}]),rw=vi(e=>new nw(e,new aa(da(),new ns(e,new Xa(a())),n(),Ee())),[{id:"googlepaypaypalcommerce"}]),ow=vi(e=>new nw(e,new aa(da(),new os(e,new xr(a())),n(),Ee())),[{id:"googlepay_bigcommerce_payments"}]),aw=vi(e=>{const t=n();return new nw(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv2"}]),sw=vi(e=>{const t=n();return new nw(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv3"}]),dw=vi(e=>new nw(e,new aa(da(),new ua(e),n(),Ee())),[{id:"googlepayauthorizenet"}]),cw=vi(e=>{const t=n();return new nw(e,new aa(da(),new ga(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]),lw=vi(e=>new nw(e,new aa(da(),new fa(e),n(),Ee())),[{id:"googlepaycybersourcev2"},{id:"googlepaybnz"}]),uw=vi(e=>new nw(e,new aa(da(),new wa(e),n(),Ee())),[{id:"googlepayorbital"}]),hw=vi(e=>new nw(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeupe"},{id:"googlepaystripeocs"}]),pw=vi(e=>new nw(e,new aa(da(),new Ga(e),n(),Ee())),[{id:"googlepayworldpayaccess"}]),mw=vi(e=>new nw(e,new aa(da(),new cs(e,Ee()),n(),Ee())),[{id:"googlepaytdonlinemart"}]);class yw{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.paypalButtonCreationService=n}initialize(e){var t,n,i,r,o;return n=this,i=void 0,o=function*(){const{paypalcommerce:n,containerId:i,methodId:r}=e,o=Boolean(null==n?void 0:n.buyNowInitializeOptions);if(!r)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(o&&!n.currencyCode)throw new fi('Unable to initialize payment because "options.paypalcommerce.currencyCode" argument is not provided.');if(o&&"function"!=typeof(null===(t=n.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.paypalcommerce.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');o||(yield this.paymentIntegrationService.loadDefaultCheckout());const a=o?n.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.paypalIntegrationService.loadPayPalSdk(r,a,!1),this.renderButton(i,r,n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){var i,r;const{buyNowInitializeOptions:o,style:a,onComplete:s,onEligibilityFailure:d}=n,c=this.paypalIntegrationService.getPayPalSdkOrThrow(),l=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:u,isAppSwitchEnabled:h}=l.initializationData||{},p={onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},m=Object.assign(Object.assign({fundingSource:c.FUNDING.PAYPAL,style:this.paypalIntegrationService.getValidButtonStyle(a),isAppSwitchEnabled:h,isHostedCheckoutEnabled:u},o&&p),u&&s&&{onPaymentComplete:()=>s()}),y=this.paypalButtonCreationService.createPayPalButton("paypalcommerce",t,m,o);y.isEligible()?(null===(i=y.hasReturned)||void 0===i?void 0:i.call(y))&&h?null===(r=y.resume)||void 0===r||r.call(y):y.render(`#${e}`):d&&"function"==typeof d?d():this.paypalIntegrationService.removeElement(e)}}const gw=vi(e=>{const t=As(e),n=new ks(e,t);return new yw(e,t,n)},[{id:"paypalcommerce"}]);var vw=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class fw{constructor(e,t){this.paymentIntegrationService=e,this.paypalIntegrationService=t}initialize(e){return vw(this,void 0,void 0,function*(){const{paypalcommercecredit:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(a&&!o)throw new fi('Unable to initialize payment because "options.paypalcommercecredit.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.paypalcommercecredit.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=this.paymentIntegrationService.getState(),d=a?o:s.getCartOrThrow().currency.code;yield this.paypalIntegrationService.loadPayPalSdk(i,d,!1),this.renderButton(n,i,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){const{buyNowInitializeOptions:i,style:r,onComplete:o,onEligibilityFailure:a}=n,s=this.paypalIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:c,isAppSwitchEnabled:l}=d.initializationData||{},u={createOrder:()=>this.paypalIntegrationService.createOrder("paypalcommercecredit"),onApprove:({orderID:e})=>this.paypalIntegrationService.tokenizePayment(t,e)},h={onClick:()=>this.handleClick(i),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},p=Object.assign(Object.assign({},!l&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(e,n)=>this.onHostedCheckoutApprove(e,n,t,o)}),m=[s.FUNDING.PAYLATER,s.FUNDING.CREDIT];let y=!1;m.forEach(t=>{if(!y){const n=Object.assign(Object.assign(Object.assign({fundingSource:t,style:this.paypalIntegrationService.getValidButtonStyle(r)},u),i&&h),c&&p),o=s.Buttons(n);o.isEligible()?(o.render(`#${e}`),y=!0):a&&"function"==typeof a&&a()}}),y||this.paypalIntegrationService.removeElement(e)}handleClick(e){return vw(this,void 0,void 0,function*(){if(e){const t=yield this.paypalIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,n,i){return vw(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.paypalIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.paypalIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.paypalIntegrationService.updateOrder("paypalcommerce")}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.paypalIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return vw(this,void 0,void 0,function*(){const t=this.paypalIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.paypalIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.paypalIntegrationService.updateOrder("paypalcommerce")}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return vw(this,void 0,void 0,function*(){const t=this.paypalIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.paypalIntegrationService.updateOrder("paypalcommerce")}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}}const Sw=vi(e=>new fw(e,As(e)),[{id:"paypalcommercecredit"}]);var _w=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ww{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}initialize(e){return _w(this,void 0,void 0,function*(){const{paypalcommercevenmo:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(a&&!o)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.paypalcommercevenmo.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=a?o:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.paypalCommerceIntegrationService.loadPayPalSdk(i,s,!1),this.renderButton(n,i,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){const{buyNowInitializeOptions:i,style:r,onEligibilityFailure:o}=n,a=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),s=a.FUNDING.VENMO,d={createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo"),onApprove:({orderID:e})=>this.paypalCommerceIntegrationService.tokenizePayment(t,e)},c={onClick:()=>this.handleClick(i),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},l=Object.assign(Object.assign({fundingSource:s,style:this.getValidVenmoButtonStyles(r)},d),i&&c),u=a.Buttons(l);u.isEligible()?u.render(`#${e}`):o&&"function"==typeof o?o():this.paypalCommerceIntegrationService.removeElement(e)}getValidVenmoButtonStyles(e){const t=this.paypalCommerceIntegrationService.getValidButtonStyle(e);return t.color===Fs.gold?Object.assign(Object.assign({},t),{color:void 0}):t}handleClick(e){return _w(this,void 0,void 0,function*(){if(e){const t=yield this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const Iw=vi(e=>new ww(e,$s(e)),[{id:"paypalcommercevenmo"}]);var Cw=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class bw{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalExpressScriptLoader=t,this.formPoster=n}initialize(e){return Cw(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);if(!e.paypal)throw new fi;if(!t.config.merchantId)throw new ti(Xn.MissingPaymentMethod);const n=yield this.paypalExpressScriptLoader.loadPaypalSDK(t.config.merchantId);this.renderButton(e,n)})}deinitialize(){return Promise.resolve()}renderButton(e,t){const{containerId:n,methodId:i,paypal:r}=e,{allowCredit:o,clientId:a,onPaymentError:s,shouldProcessPayment:d,style:c}=r,l=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);if(!l.config.merchantId)throw new ti(Xn.MissingPaymentMethod);const u=l.config.merchantId,h=l.config.testMode?"sandbox":"production",p={[h]:a},m=t.FUNDING.CREDIT||"credit",y=o?[m]:[],g=o?[]:[m];return t.Button.render({env:h,client:p,commit:d,funding:{allowed:y,disallowed:g},style:this.getStyle(c),payment:(e,t)=>this.setupPayment(u,t,s),onAuthorize:(e,t)=>this.tokenizePayment(e,i,t,d)},n)}getStyle(e){const{color:t,fundingicons:n,label:i,layout:r,shape:o,size:a,tagline:s}=e||{};return{color:t,fundingicons:n,label:i,layout:r,shape:o||Pp.RECT,size:"small"===a?Ip.RESPONSIVE:a,tagline:s}}setupPayment(e,t,n){return Cw(this,void 0,void 0,function*(){if(!t)throw new ri(ei.CheckoutButtonNotInitialized);try{const n=yield this.paymentIntegrationService.loadDefaultCheckout(),{id:i}=n.getCartOrThrow(),r=n.getHost()||"";return(yield t.request.post(`${r}/api/storefront/payment/paypalexpress`,{merchantId:e,cartId:i},{headers:Object.assign({"X-API-INTERNAL":hr},yr)})).id}catch(e){throw n&&e instanceof Qn&&n(e),e}})}tokenizePayment(e,t,n,i){return Cw(this,void 0,void 0,function*(){if(!n)throw new ri(ei.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new ti(Xn.MissingPayment);const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),o=yield n.payment.get(e.paymentID);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:r.id,action:i?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(o.payer.payer_info)})})}}const Pw=vi(e=>new bw(e,new Tp(a()),Ee()),[{id:"paypalexpress"}]);var Ow=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ew{constructor(e,t,n,i){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n,this.loadingIndicator=i}initialize(e){return Ow(this,void 0,void 0,function*(){const{stripeocs:t,containerId:n}=e||{};if(!t||!n)throw new ri(ei.PaymentNotInitialized);const{gatewayId:i}=t;if(!i)throw new ti(Xn.MissingPaymentMethod);const r=this._getMethodId(i),o=yield this.paymentIntegrationService.loadPaymentMethod(i,{params:{method:r}}),a=o.getPaymentMethodOrThrow(r,i),{loadingContainerId:s,buttonHeight:d,onComplete:c}=t;if(this._loadingIndicatorContainer=s,this._onComplete=c,!dd(a))throw new ti(Xn.MissingPaymentMethod);const{initializationData:l}=a,{captureMethod:u}=l,h=this.stripeIntegrationService.getStripeJsVersion(l);this._captureMethod=u,this._stripeClient=yield this.scriptLoader.getStripeClient(l,o.getCartLocale(),h),yield this.paymentIntegrationService.loadDefaultCheckout(),yield this._mountExpressCheckoutElement(n,this._stripeClient,d),this._initializeEvents(r)})}signIn(){return Promise.resolve()}signOut(){return Promise.resolve()}executePaymentMethodCheckout(){return Promise.resolve()}deinitialize(){return Promise.resolve()}_mountExpressCheckoutElement(e,t,n=40){return Ow(this,void 0,void 0,function*(){const i=this._shouldRequireShippingAddress(),r=Object.assign(Object.assign(Object.assign({shippingAddressRequired:i},i?{allowedShippingCountries:yield this._getAvailableCountries()}:{}),i?{shippingRates:[{id:"_",amount:0,displayName:"Pending rates"}]}:{}),{billingAddressRequired:!0,emailRequired:!0,phoneNumberRequired:!0,paymentMethods:{link:Ta.AUTO,applePay:Ta.NEVER,googlePay:Ta.NEVER,amazonPay:Ta.NEVER,paypal:Ta.NEVER,klarna:Ta.NEVER},buttonHeight:n}),{cartAmount:o=1}=this.paymentIntegrationService.getState().getCart()||{},a=Object.assign({mode:"payment",amount:this._toCents(o),currency:this._getCurrency()},this._captureMethod?{captureMethod:this._captureMethod}:{});this._stripeElements=t.elements(a),this._linkV2Element=this._stripeElements.create(Da.EXPRESS_CHECKOUT,r),this._linkV2Element.mount(`#${e}`)})}_initializeEvents(e){this._linkV2Element&&(this._shouldRequireShippingAddress()&&(this._linkV2Element.on(za.SHIPPING_ADDRESS_CHANGE,e=>Ow(this,void 0,void 0,function*(){return this._onShippingAddressChange(e)})),this._linkV2Element.on(za.SHIPPING_RATE_CHANGE,e=>Ow(this,void 0,void 0,function*(){return this._onShippingRateChange(e)}))),this._linkV2Element.on(za.CONFIRM,t=>Ow(this,void 0,void 0,function*(){return this._onConfirm(t,e)})),this._linkV2Element.on(za.CANCEL,this._onCancel))}_onShippingAddressChange(e){return Ow(this,void 0,void 0,function*(){if(!("address"in e))return;const t=e.address,n={firstName:"",lastName:"",phone:"",company:"",address1:"",address2:"",city:(null==t?void 0:t.city)||"",countryCode:(null==t?void 0:t.country)||"",postalCode:(null==t?void 0:t.postal_code)||"",stateOrProvince:(null==t?void 0:t.state)||"",stateOrProvinceCode:(null==t?void 0:t.state)||"",customFields:[]};yield this.paymentIntegrationService.updateShippingAddress(n);const i=yield this._getAvailableShippingOptions();yield this._updateDisplayedPrice(),(null==i?void 0:i.length)?e.resolve({shippingRates:i}):e.reject()})}_onCancel(){throw new Wi}_onShippingRateChange(e){return Ow(this,void 0,void 0,function*(){if("shippingRate"in e){const{shippingRate:t}=e;yield this._handleShippingOptionChange(null==t?void 0:t.id),yield this._updateDisplayedPrice(),e.resolve({})}})}_onConfirm(e,t){return Ow(this,void 0,void 0,function*(){if("billingDetails"in e&&"shippingAddress"in e&&this._stripeClient&&this._stripeElements){yield this._updateShippingAndBillingAddress(e),yield this.paymentIntegrationService.submitOrder();const n=this._getPaymentPayload(t);try{yield this.paymentIntegrationService.submitPayment(n)}catch(e){yield this._processAdditionalAction(e,t)}}return Promise.resolve()})}_updateShippingAndBillingAddress(e){var t,n,i,r,o,a,s,d;return Ow(this,void 0,void 0,function*(){const c=this._shouldRequireShippingAddress(),l=(null===(n=null===(t=e.shippingAddress)||void 0===t?void 0:t.name)||void 0===n?void 0:n.split(" ")[0])||(null===(r=null===(i=e.billingDetails)||void 0===i?void 0:i.name)||void 0===r?void 0:r.split(" ")[0])||"",u=(null===(a=null===(o=e.shippingAddress)||void 0===o?void 0:o.name)||void 0===a?void 0:a.split(" ")[1])||(null===(d=null===(s=e.billingDetails)||void 0===s?void 0:s.name)||void 0===d?void 0:d.split(" ")[1])||"";if(c){const t=this._mapShippingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateShippingAddress(t)}const h=this._mapBillingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateBillingAddress(h)})}_mapShippingAddress(e,t,n,i){var r,o,a,s,d,c,l;return{firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==e?void 0:e.address)||void 0===r?void 0:r.line1)||"",address2:(null===(o=null==e?void 0:e.address)||void 0===o?void 0:o.line2)||"",city:(null===(a=null==e?void 0:e.address)||void 0===a?void 0:a.city)||"",countryCode:(null===(s=null==e?void 0:e.address)||void 0===s?void 0:s.country)||"",postalCode:(null===(d=null==e?void 0:e.address)||void 0===d?void 0:d.postal_code)||"",stateOrProvince:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",stateOrProvinceCode:(null===(l=null==e?void 0:e.address)||void 0===l?void 0:l.state)||"",customFields:[]}}_mapBillingAddress(e,t,n,i){var r,o,a,s,d,c;return{email:(null==t?void 0:t.email)||"",firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==t?void 0:t.address)||void 0===r?void 0:r.line1)||"",address2:"",city:(null===(o=null==t?void 0:t.address)||void 0===o?void 0:o.city)||"",countryCode:(null===(a=null==t?void 0:t.address)||void 0===a?void 0:a.country)||"",postalCode:(null===(s=null==t?void 0:t.address)||void 0===s?void 0:s.postal_code)||"",stateOrProvince:(null===(d=null==t?void 0:t.address)||void 0===d?void 0:d.state)||"",stateOrProvinceCode:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",customFields:[]}}_processAdditionalAction(e,t){return Ow(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeClient||!this._stripeElements)throw new ri(ei.PaymentNotInitialized);const{data:n}=e.body.additional_action_required,{token:i}=n,{paymentIntent:r}=yield this._confirmStripePaymentOrThrow(n,t),o=this._getPaymentPayload(t,(null==r?void 0:r.id)||i);try{this._toggleLoadingIndicator(!0),yield this.paymentIntegrationService.submitPayment(o),yield this._completeCheckoutFlow()}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}finally{this._toggleLoadingIndicator(!1)}})}_confirmStripePaymentOrThrow(e,t){var n,i,r;return Ow(this,void 0,void 0,function*(){const{token:o,redirect_url:a}=e,s=this.stripeIntegrationService.mapStripePaymentData(this._stripeElements,a);let d;try{const e=(yield this.stripeIntegrationService.isPaymentCompleted(t,this._stripeClient))?yield null===(r=this._stripeClient)||void 0===r?void 0:r.retrievePaymentIntent(o||""):yield null===(n=this._stripeClient)||void 0===n?void 0:n.confirmPayment({elements:s.elements,clientSecret:o,redirect:Ta.IF_REQUIRED,confirmParams:{return_url:null===(i=s.confirmParams)||void 0===i?void 0:i.return_url}});if(d=null==e?void 0:e.error,d||!(null==e?void 0:e.paymentIntent))throw new Qr;return e}catch(e){return this.stripeIntegrationService.throwStripeError(d)}})}_completeCheckoutFlow(){return Ow(this,void 0,void 0,function*(){return"function"==typeof this._onComplete?this._onComplete():(window.location.replace("/checkout/order-confirmation"),Promise.resolve())})}_getPaymentPayload(e,t){var n;const i=(null===(n=this.paymentIntegrationService.getState().getCart())||void 0===n?void 0:n.id)||"";return{methodId:e,paymentData:{formattedPayload:Object.assign(Object.assign({cart_id:i},t?{credit_card_token:{token:t}}:{}),{confirm:!1,method:Aa.Link})}}}_shouldRequireShippingAddress(){const{getCart:e}=this.paymentIntegrationService.getState(),{lineItems:t}=e()||{};return!!(null==t?void 0:t.physicalItems.length)}_updateDisplayedPrice(){return Ow(this,void 0,void 0,function*(){this._stripeElements&&this._stripeElements.update({currency:this._getCurrency(),mode:"payment",amount:yield this._getTotalPrice()})})}_getCurrency(){var e;if(!this._currencyCode){const t=null===(e=this.paymentIntegrationService.getState().getCart())||void 0===e?void 0:e.currency;t&&(this._currencyCode=t.code.toLowerCase())}return this._currencyCode}_getTotalPrice(){var e;return Ow(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const{getCheckoutOrThrow:t,getCart:n}=this.paymentIntegrationService.getState(),{decimalPlaces:i}=(null===(e=n())||void 0===e?void 0:e.currency)||{},r=ge(t().outstandingBalance,i).toFixed(i);return this._toCents(+r)})}_getAvailableCountries(){var e;return Ow(this,void 0,void 0,function*(){const t=yield this.paymentIntegrationService.loadShippingCountries();return((null===(e=t.getShippingCountries())||void 0===e?void 0:e.map(e=>e.code))||[]).filter(e=>Sd.includes(e))})}_getAvailableShippingOptions(){var e,t,n;return Ow(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getConsignments();if(!(null==i?void 0:i[0]))return;const r=i[0],o=(r.availableShippingOptions||[]).map(this._getStripeShippingOption.bind(this)),a=null===(e=r.availableShippingOptions)||void 0===e?void 0:e.find(e=>e.isRecommended),s=null===(t=r.selectedShippingOption)||void 0===t?void 0:t.id,d=null==a?void 0:a.id;return s?o.sort(e=>e.id===s?-1:0):d?(o.sort(e=>e.id===d?-1:0),yield this._handleShippingOptionChange(d)):yield this._handleShippingOptionChange(null===(n=o[0])||void 0===n?void 0:n.id),o.slice(0,9)})}_getStripeShippingOption({id:e,cost:t,description:n}){return{id:e,displayName:n,amount:this._toCents(t)}}_handleShippingOptionChange(e){return Ow(this,void 0,void 0,function*(){if(e&&"shipping_option_unselected"!==e)return this.paymentIntegrationService.selectShippingOption(e)})}_getAmountTransformer(){if(this._amountTransformer)return this._amountTransformer;const{getCart:e}=this.paymentIntegrationService.getState(),{currency:t}=e()||{};return t?new fd(t.decimalPlaces):void 0}_toCents(e){const t=Math.round(100*e),n=this._getAmountTransformer();return n?n.toInteger(e):t}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this.loadingIndicator.show(this._loadingIndicatorContainer):this.loadingIndicator.hide()}_getMethodId(e){const{initializationData:{checkoutSessionEnabled:t}={}}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e);return t?Aa.CHECKOUT_SESSION:Aa.OCS}}const Aw=vi(e=>{const t=new Ra(a()),n=new vd({containerStyles:yd});return new Ew(e,t,new pd(e,t),n)},[{id:"stripeocs"}]),Tw=e=>{const t=Ie(e);return document.getElementById(t)?Tw(e):t};function kw(e){return Object.prototype.hasOwnProperty.call(e,"cacheKey")}class Dw{constructor(e){this._lastId=0,this._map={maps:[]},this._usedMaps=[],this._options=Object.assign({maxSize:0,isEqual:Be,onExpire:ce},e)}getKey(...e){const t=this._resolveMap(...e),{index:n,parentMap:i}=t;let{map:r}=t;return r&&r.cacheKey?r.usedCount++:r=this._generateMap(i,e.slice(n)),this._removeLeastUsedMap(r),r.cacheKey}getUsedCount(...e){const{map:t}=this._resolveMap(...e);return t?t.usedCount:0}_resolveMap(...e){let t=0,n=this._map;for(;n.maps.length;){let i=!1;for(let r=0;r{const i=Object.getOwnPropertyDescriptor(e.prototype,n);i&&"constructor"!==n&&Object.defineProperty(t.prototype,n,function(e,t,n){if("function"!=typeof n.value)return n;let i=new Dw,r=n.value,o=Pe(r);return Fn(e,t,{get(){const e=(...e)=>{const t=o.call(this,...e);if(1===i.getUsedCount(...e))return t;const n=r.call(this,...e);return Pv(n,t,{keyFilter:e=>!function(e){return 0===`${e}`.indexOf("$$")||0===`${e}`.indexOf("_")}(e)})?t:(o.cache.set(i.getKey(...e),n),n)};return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e},set(e){i=new Dw,r=e,o=Pe(r)}})}(e.prototype,n,i))}),t}let zw=class{constructor(e){this._checkoutButton=e.checkoutButton}getInitializeButtonError(e){return this._checkoutButton.getInitializeError(e)}getDeinitializeButtonError(e){return this._checkoutButton.getDeinitializeError(e)}};zw=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Mw],zw);const Nw=zw;let xw=class{constructor(e){this._checkoutButton=e.checkoutButton}isInitializingButton(e){return this._checkoutButton.isInitializing(e)}isDeinitializingButton(e){return this._checkoutButton.isDeinitializing(e)}};xw=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Mw],xw);const Rw=xw;function Fw(e){return{errors:new Nw(e),statuses:new Rw(e)}}let Lw=class{constructor(e,t){this._store=e,this._buttonStrategyActionCreator=t,this._state=Fw(this._store.getState()),this._store.subscribe(e=>{this._state=Fw(e)})}getState(){return this._state}subscribe(e,...t){return this._store.subscribe(()=>e(this.getState()),e=>e.checkoutButton.getState(),...t.map(e=>t=>e(Fw(t))))}initializeButton(e){const t=(n=e.containerId,/^\w[\w\-\:\.]*$/.test(n)?[e.containerId]:function(e,t){const n=document.querySelectorAll(e);if(!n.length)throw new qt(`Unable to find any element with the specified selector: ${e}`);return Array.prototype.slice.call(n).map(e=>(e.id||(e.id=Tw(t)),e.id))}(e.containerId,`${e.methodId}-container`));var n;return Promise.all(t.map(t=>{const n=this._buttonStrategyActionCreator.initialize(Object.assign(Object.assign({},e),{containerId:t})),i=`checkoutButtonStrategy:${e.methodId}:${t}`;return this._store.dispatch(n,{queueId:i})})).then(()=>this.getState())}deinitializeButton(e){const t=this._buttonStrategyActionCreator.deinitialize(e),n=`checkoutButtonStrategy:${e.methodId}`;return this._store.dispatch(t,{queueId:n}).then(()=>this.getState())}};Lw=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],Lw);const Bw=Lw;class jw{constructor(e,t,n){this._registry=e,this._registryV2=t,this._paymentMethodActionCreator=n}initialize(e){return t=>{const n={methodId:e.methodId,containerId:e.containerId};if(t.getState().checkoutButton.isInitialized(e.methodId,e.containerId))return f();const i=e.currencyCode?{params:{currencyCode:e.currencyCode}}:{},r=Object.assign(Object.assign({},i),{timeout:e.timeout,useCache:!0});return g(C(l(Hv.InitializeButtonRequested,void 0,n)),this._paymentMethodActionCreator.loadPaymentMethod(e.methodId,r)(t),v(()=>this._getStrategy(e.methodId).initialize(e).then(()=>l(Hv.InitializeButtonSucceeded,void 0,n)))).pipe(P(e=>Je(Hv.InitializeButtonFailed,e,n)))}}deinitialize(e){return t=>{const n={methodId:e.methodId};return t.getState().checkoutButton.isInitialized(e.methodId)?g(C(l(Hv.DeinitializeButtonRequested,void 0,n)),v(()=>this._getStrategy(e.methodId).deinitialize().then(()=>l(Hv.DeinitializeButtonSucceeded,void 0,n)))).pipe(P(e=>Je(Hv.DeinitializeButtonFailed,e,n))):f()}}_getStrategy(e){let t;try{t=this._registryV2.get({id:e})}catch(n){t=this._registry.get(e)}return t}}class Uw extends it{constructor(e){super(e||"Unable to proceed because the client library of a payment method is not loaded or ready to be used."),this.name="PaymentMethodClientUnavailableError",this.type="payment_method_client_unavailable"}}var qw,Vw,Gw,Hw,Ww,$w,Yw,Kw;class Jw{constructor(e){this._scriptLoader=e,this._window=window}loadPaypal(e=""){return t=this,n=void 0,r=function*(){const t="//www.paypalobjects.com/api/checkout.min.js",n={async:!0,attributes:{"data-merchant-id":e}};if(e?yield this._scriptLoader.loadScript(t,n):yield this._scriptLoader.loadScript(t),!this._window.paypal)throw new Uw;return this._window.paypal},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(qw||(qw={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(Vw||(Vw={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black",e.WHITE="white"}(Gw||(Gw={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(Hw||(Hw={})),function(e){e.PILL="pill",e.RECT="rect"}(Ww||(Ww={}));class Zw{constructor(e,t,n,i,r=""){this._store=e,this._checkoutActionCreator=t,this._paypalScriptLoader=n,this._formPoster=i,this._host=r}initialize(e){const t=e.paypal,n=this._store.getState(),i=this._paymentMethod=n.paymentMethods.getPaymentMethod(e.methodId);if(!t)throw new qt;if(!i)throw new rt(et.MissingPaymentMethod);return this._paypalScriptLoader.loadPaypal(i.config.merchantId).then(n=>{var r,o;if(!i||!i.config.merchantId)throw new rt(et.MissingPaymentMethod);const a=i.config.merchantId,s=i.config.testMode?"sandbox":"production",d={[s]:t.clientId},c=n.FUNDING.CREDIT||"credit",l=t.allowCredit?[c]:[],u=t.allowCredit?[]:[c];return n.Button.render({env:s,client:d,commit:t.shouldProcessPayment,funding:{allowed:l,disallowed:u},style:Object.assign(Object.assign({shape:Ww.RECT},pe(t.style,"layout","color","label","shape","tagline","fundingicons")),{size:"paypalexpress"===i.id&&"small"===(null===(r=t.style)||void 0===r?void 0:r.size)?Vw.RESPONSIVE:null===(o=t.style)||void 0===o?void 0:o.size}),payment:(e,n)=>this._setupPayment(a,n,t.onPaymentError),onAuthorize:(e,n)=>this._tokenizePayment(e,n,t.shouldProcessPayment,t.onAuthorizeError)},e.containerId)})}deinitialize(){return this._paymentMethod=void 0,Promise.resolve()}_setupPayment(e,t,n){if(!t)throw new yn(cn.CheckoutButtonNotInitialized);return this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then(n=>{const i=n.cart.getCart(),r=i?i.id:"";return t.request.post(`${this._host}/api/storefront/payment/paypalexpress`,{merchantId:e,cartId:r},{headers:Object.assign({"X-API-INTERNAL":At},Xe)})}).then(e=>e.id).catch(e=>{throw n&&n(e),e})}_tokenizePayment(e,t,n,i){if(!this._paymentMethod)throw new yn(cn.CheckoutButtonNotInitialized);if(!t)throw new yn(cn.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new rt(et.MissingPayment);const r=this._paymentMethod.id;return t.payment.get(e.paymentID).then(t=>{this._formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:r,action:n?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(t.payer.payer_info)})})}}function Qw(e){const{host:t}=null!=e?e:{},i=m_({config:{meta:{host:null==e?void 0:e.host,locale:null==e?void 0:e.locale},errors:{},statuses:{}}}),r=n({host:t}),o=Ee({host:t}),s=function(e,t){const n=new Gt;for(const[,i]of Object.entries(t))if(Ut(i))for(const t of i.resolveIds)n.register(t,()=>i(e));return n}(Hg(i),We);return new Bw(i,new jw(function(e,t,n,i){const r=new Vt,o=a(),s=new en(t),d=new nn(s,new bt(new Tt(t)),new on(new an(t)));return r.register(zy.PAYPALEXPRESS,()=>new Zw(e,d,new Jw(o),n,i)),r}(i,r,o,t),s,new Wm(new $m(r))))}!function(e){e.CheckoutComplete="CHECKOUT_COMPLETE",e.CheckoutError="CHECKOUT_ERROR",e.CheckoutLoaded="CHECKOUT_LOADED",e.FrameError="FRAME_ERROR",e.FrameLoaded="FRAME_LOADED",e.SignedOut="SIGNED_OUT"}($w||($w={}));class Xw extends Ot{constructor(e){super(e,{message:e.body.title}),this.name="InvalidLoginTokenError",this.type="invalid_login_token"}}!function(e){e.MissingContainer="missing_container",e.MissingContent="missing_content",e.UnknownError="unknown_error"}(Yw||(Yw={}));class eI extends it{constructor(e,t=Yw.UnknownError){super(e||"Unable to embed the checkout form."),this.subtype=t,this.name="NotEmbeddableError",this.type="not_embeddable"}}!function(e){e.StyleConfigured="STYLE_CONFIGURED"}(Kw||(Kw={}));const tI="isCookieAllowed",nI="lastAllowCookieAttempt";let iI=class{constructor(e,t,n,i,r,o,a,s){this._iframeCreator=e,this._messageListener=t,this._messagePoster=n,this._loadingIndicator=i,this._requestSender=r,this._storage=o,this._location=a,this._options=s,this._isAttached=!1,this._options.onComplete&&this._messageListener.addListener($w.CheckoutComplete,this._options.onComplete),this._options.onError&&this._messageListener.addListener($w.CheckoutError,this._options.onError),this._options.onLoad&&this._messageListener.addListener($w.CheckoutLoaded,this._options.onLoad),this._options.onFrameLoad&&this._messageListener.addListener($w.FrameLoaded,this._options.onFrameLoad),this._options.onSignOut&&this._messageListener.addListener($w.SignedOut,this._options.onSignOut),this._messageListener.addListener($w.FrameLoaded,()=>this._configureStyles())}attach(){return this._isAttached?Promise.resolve(this):(this._isAttached=!0,this._messageListener.listen(),this._loadingIndicator.show(this._options.containerId),this._allowCookie().then(()=>this._attemptLogin()).then(e=>this._iframeCreator.createFrame(e,this._options.containerId)).then(e=>{this._iframe=e,this._configureStyles(),this._loadingIndicator.hide()}).catch(e=>(this._isAttached=!1,this._retryAllowCookie(e).catch(()=>{throw this._messageListener.trigger({type:$w.FrameError,payload:e}),this._loadingIndicator.hide(),e}))).then(()=>this))}detach(){this._isAttached&&(this._isAttached=!1,this._messageListener.stopListen(),this._iframe&&this._iframe.parentNode&&(this._iframe.parentNode.removeChild(this._iframe),this._iframe.iFrameResizer.close()))}_configureStyles(){this._iframe&&this._iframe.contentWindow&&this._options.styles&&(this._messagePoster.setTarget(this._iframe.contentWindow),this._messagePoster.post({type:Kw.StyleConfigured,payload:this._options.styles}))}_attemptLogin(){return/^\/login\/token/.test(In(this._options.url).pathname)?this._requestSender.post(this._options.url).then(({body:{redirectUrl:e}})=>e).catch(e=>Promise.reject(new Xw(e))):Promise.resolve(this._options.url)}_allowCookie(){if(this._storage.getItem(tI))return Promise.resolve();this._storage.setItem(tI,!0),this._storage.setItem(nI,Date.now());const{origin:e}=In(this._options.url),t=`${e}/embedded-checkout/allow-cookie?returnUrl=${encodeURIComponent(this._location.href)}`;return document.body.style.visibility="hidden",this._location.replace(t),new Promise(()=>{})}_retryAllowCookie(e){const t=Number(this._storage.getItem(nI));return(!t||Date.now()-t>6e5)&&e instanceof eI&&e.subtype===Yw.MissingContent?(this._storage.removeItem(nI),this._storage.removeItem(tI),this._allowCookie()):Promise.reject()}};iI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],iI);const rI=iI;class oI{constructor(e){this._options=e}createFrame(e,t){const n=document.getElementById(t),{timeout:i=6e4}=this._options||{};if(!n)throw new eI("Unable to embed the iframe because the container element could not be found.",Yw.MissingContainer);const r=document.createElement("iframe");return r.src=e,r.style.border="none",r.style.display="none",r.style.width="100%",r.allowPaymentRequest=!0,r.allow="payment",n.appendChild(r),this._toResizableFrame(r,i).catch(e=>{throw n.removeChild(r),e})}_toResizableFrame(e,t){return new Promise((n,i)=>{const r=window.setTimeout(()=>{i(new eI("Unable to embed the iframe because the content could not be loaded."))},t),o=t=>{if((t.origin===In(e.src).origin||t.origin===Wn(In(e.src)).origin)&&(bn(t.data,$w.FrameError)&&(a(),i(new eI(t.data.payload.message,Yw.MissingContent))),bn(t.data,$w.FrameLoaded))){e.style.display="";const i=Dn({scrolling:!1,sizeWidth:!1,heightCalculationMethod:t.data.payload&&t.data.payload.contentId?"taggedElement":"lowestElement"},e);a(),n(i[i.length-1])}},a=()=>{window.removeEventListener("message",o),window.clearTimeout(r)};window.addEventListener("message",o)})}}function aI(e){const t=In(e.url).origin;return new rI(new oI,new Yn(t),new Pn(t),new vd({styles:e.styles&&e.styles.loadingIndicator}),n(),new iy("BigCommerce.EmbeddedCheckout"),window.location,e).attach()}function sI(e){if(!e.payload||!e.payload.contentId)return;const t=document.getElementById(e.payload.contentId);t&&!t.hasAttribute("data-iframe-height")&&t.setAttribute("data-iframe-height","")}function dI(e){return"object"==typeof e&&null!==e&&"message"in e&&"type"in e}let cI=class{constructor(e,t,n,i={}){this._messageListener=e,this._messagePoster=t,this._untargetedMessagePoster=n,this._messageHandlers=i,this._messageListener.listen()}postComplete(){const e={type:$w.CheckoutComplete};this._postMessage(e)}postError(e){const t={type:$w.CheckoutError,payload:this._transformError(e)};this._postMessage(t)}postFrameError(e){const t={type:$w.FrameError,payload:this._transformError(e)};this._postMessage(t,{untargeted:!0})}postFrameLoaded(e){const t={type:$w.FrameLoaded,payload:e};this._postMessage(t)}postLoaded(){const e={type:$w.CheckoutLoaded};this._postMessage(e)}postSignedOut(){const e={type:$w.SignedOut};this._postMessage(e)}receiveStyles(e){this._messageListener.addListener(Kw.StyleConfigured,({payload:t})=>{e(t)})}_postMessage(e,t){if(this._notifyMessageHandlers(e),t&&t.untargeted)return this._untargetedMessagePoster.post(e);this._messagePoster.post(e)}_notifyMessageHandlers(e){Object.keys(this._messageHandlers).forEach(t=>{if(e.type!==t)return;const n=this._messageHandlers[t];n&&n.call(null,e)})}_transformError(e){return{message:e.message,type:dI(e)?e.type:void 0,subtype:dI(e)?e.subtype:void 0}}};cI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],cI);const lI=cI;let uI=class{postComplete(){}postError(){}postFrameError(){}postFrameLoaded(){}postLoaded(){}postSignedOut(){}receiveStyles(){}};uI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],uI);const hI=uI;function pI(e){Ve(939);const t=e.parentWindow||window.parent;return window===t?new hI:new lI(new Yn(e.parentOrigin),new Pn(e.parentOrigin,t),new Pn("*",t),{[$w.FrameLoaded]:sI})}const mI="en",yI="optimized_checkout";let gI=class{constructor(e,t){this._logger=t;const{locale:n,locales:i,translations:r}=this._transformConfig(e);this._locale=n,this._locales=i,this._translations=r,this._formatters={}}mapKeys(e){Object.keys(e).forEach(t=>{const n=`${yI}.${e[t]}`;this._translations[`${yI}.${t}`]=this._translations[n]})}getLocale(){return this._hasTranslations()?this._locale:mI}translate(e,t={}){var n;const i=`${yI}.${e}`;if("string"!=typeof this._translations[i])return this._logger.warn(`Translation key "${i}" is missing`),i;this._formatters[i]||(this._formatters[i]=new je(this._escapeSpecialCharacters(this._translations[i]||""),this._locales[i],void 0,{ignoreTag:!0}));try{return this._formatters[i].format(this._transformData(t))}catch(e){if(this._isFormatError(e))return null!==(n=e.originalMessage)&&void 0!==n?n:"";throw e}}_transformConfig(e={}){const t={defaultLocale:"",defaultTranslations:{},translations:{},locales:{},locale:e.locale||mI},n=e.locales||{},i=this._flattenObject(e.translations||{}),r=this._flattenObject(e.defaultTranslations||{}),o=this._flattenObject(e.fallbackTranslations||{});return _e(Object.keys(o),Object.keys(r),Object.keys(i)).forEach(a=>{var s,d;i&&i[a]?(t.translations[a]=i[a],t.locales[a]=n[a]||t.locale):r[a]?(t.translations[a]=r[a],t.locales[a]=null!==(s=e.defaultLocale)&&void 0!==s?s:mI):(t.translations[a]=o[a],t.locales[a]=null!==(d=e.fallbackLocale)&&void 0!==d?d:mI)}),t}_flattenObject(e,t={},n=""){try{Object.keys(e).forEach(i=>{const r=e[i],o=n?`${n}.${i}`:i;if(Z(r))return this._flattenObject(r,t,o);t[o]=r})}catch(e){this._logger.warn(`Unable to parse object: ${e}`)}return t}_transformData(e){return Object.keys(e).reduce((t,n)=>{const i=e[n];return t[n]=null==i?"":i,t},{})}_hasTranslations(){return Object.keys(this._locales).map(e=>this._locales[e]).filter(e=>e.split("-")[0]===this._locale.split("-")[0]).length>0}_isFormatError(e){return"object"==typeof e&&null!==e&&"originalMessage"in e}_escapeSpecialCharacters(e){return e.replace(/(\w+)='([^']*)'/g,"$1=''$2''")}};gI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],gI);const vI=gI;function fI(e={}){return new vI(e,wt())}let SI=class{constructor(e){this._storeConfig=e,this._customerFormatter=new Fo(this._storeConfig.shopperCurrency),this._storeFormatter=new Fo(this._storeConfig.currency)}toCustomerCurrency(e){const t=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(e*t)}toStoreCurrency(e){return this._storeFormatter.format(e)}};SI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],SI);const _I=SI;function wI(e){return new _I(e)}function II(e){return e&&"ga"in e&&"function"==typeof e.ga}function CI(e,t){II(window)&&window.ga("send",e,Object.assign(Object.assign({},t),{nonInteraction:!1}))}function bI(e){return PI(e).length>=8096}function PI(e){return Object.keys(e).reduce((t,n)=>{const i=typeof e[n];return"string"===i||"number"===i?[...t,`${n}=${e[n]}`]:"object"===i&&null!==e[n]?[...t,PI(e[n])]:t},[]).join("&")}var OI;!function(e){e[e.CUSTOMER=1]="CUSTOMER",e[e.SHIPPING=2]="SHIPPING",e[e.BILLING=3]="BILLING",e[e.PAYMENT=4]="PAYMENT"}(OI||(OI={}));const EI={customer:OI.CUSTOMER,shipping:OI.SHIPPING,billing:OI.BILLING,payment:OI.PAYMENT};class AI{constructor(e,t,n,{checkoutSteps:i}={}){if(this.checkoutService=e,this.analyticsExtraItemsManager=t,this.analytics=n,this._checkoutStarted=!1,this._completedSteps={},this._viewedSteps={},this._analyticStepOrder=["customer","shipping","billing","payment"],void 0!==i){if(i.some(e=>!(e in EI)))throw new qt(`Invalid checkout steps provided. Valid values are: ${ie(EI).join(", ")}.`);this._analyticStepOrder=i}}trackCheckoutStarted(){if(this._checkoutStarted)return;const e=this.getCheckout();if(!e)return;const{coupons:t,grandTotal:n,shippingCostTotal:i,taxTotal:r,cart:{lineItems:o,discountAmount:a,id:s}}=e,d=this.analyticsExtraItemsManager.saveExtraItemsData(s,o);this.analytics.track("Checkout Started",this.getTrackingPayload({revenue:n,shipping:i,tax:r,discount:a,coupons:t,lineItems:o,extraItemsData:d})),this._checkoutStarted=!0}trackOrderComplete(){var e;const t=this.getOrder();if(!t)return;const{isComplete:n,orderId:i,orderAmount:r,shippingCostTotal:o,taxTotal:a,discountAmount:s,coupons:d,lineItems:c,cartId:l}=t;if(!n)return;const u=this.analyticsExtraItemsManager.readExtraItemsData(l);if(null===u)return;const h=null===(e=this.checkoutService.getState().data.getConfig())||void 0===e?void 0:e.checkoutSettings.features["DATA-6891.missing_orders_within_GA"],p=this.getTrackingPayload({orderId:i,revenue:r,shipping:o,tax:a,discount:s,coupons:d,extraItemsData:u,lineItems:c});if(h&&pl(window)&&II(window)&&bI(p))return CI("transaction",{"&ti":p.order_id,"&ta":p.affiliation,"&tr":p.revenue,"&ts":p.shipping,"&tt":p.tax,"&tcc":p.coupon,"&cu":p.currency}),p.products.forEach(e=>{CI("item",{"&ti":p.order_id,"&in":e.name,"&ic":e.sku,"&iv":`${e.category}`,"&ip":e.price,"&iq":e.quantity})}),this.analyticsExtraItemsManager.clearExtraItemData(l);this.analytics.track("Order Completed",p),this.analyticsExtraItemsManager.clearExtraItemData(l)}trackStepViewed(e){const t=this.getIdFromStep(e);t&&!this.hasStepViewed(t)&&(this.trackViewed(t),this.backfill(t))}trackStepCompleted(e){const t=this.getIdFromStep(e);t&&!this.hasStepCompleted(t)&&(this.backfill(t),this.trackCompleted(t))}backfill(e){for(const t of this._analyticStepOrder){const n=this.getIdFromStep(t);if(!n)break;if(this.hasStepViewed(n)||this.trackViewed(n),n===e)break;this.hasStepCompleted(n)||this.trackCompleted(n)}}trackCompleted(e){const t=this.getSelectedShippingOption(),{code:n=""}=this.getShopperCurrency()||{},i=this.getPaymentMethodName(),r={step:e,currency:n};t&&(r.shipping_method=t.description),i&&(r.payment_method=i),r.shipping_method||r.payment_method||(r.shipping_method=" "),this.analytics.track("Checkout Step Completed",r);const o=t?t.id:"",a=e===OI.SHIPPING?`${e}-${o}`:e;this._completedSteps[a]=!0}getTrackingPayload({orderId:e,revenue:t,shipping:n,tax:i,discount:r,coupons:o,extraItemsData:a,lineItems:s}){const{code:d=""}=this.getShopperCurrency()||{},{storeName:c=""}=this.getStoreProfile()||{};return{order_id:String(e),affiliation:c,revenue:this.toShopperCurrency(t),shipping:this.toShopperCurrency(n),tax:this.toShopperCurrency(i),discount:this.toShopperCurrency(r),coupon:(o||[]).map(e=>e.code.toUpperCase()).join(","),currency:d,products:this.getProducts(a,s)}}hasStepCompleted(e){const t=this.getSelectedShippingOption(),n=t?t.id:"";return Object.prototype.hasOwnProperty.call(this._completedSteps,e)||e===OI.SHIPPING&&Object.prototype.hasOwnProperty.call(this._completedSteps,`${e}-${n}`)}hasStepViewed(e){return!!this._viewedSteps[e]}getIdFromStep(e){const t=e.split(".");return EI[t[0]]||null}trackViewed(e){const t=this.getShopperCurrency();this.analytics.track("Checkout Step Viewed",{step:e,currency:t?t.code:""}),this._viewedSteps[e]=!0}getOrder(){const{data:{getOrder:e}}=this.checkoutService.getState();return e()}getCheckout(){const{data:{getCheckout:e}}=this.checkoutService.getState();return e()}getShopperCurrency(){const{data:{getConfig:e}}=this.checkoutService.getState(),t=e();return t&&t.shopperCurrency}getStoreProfile(){const{data:{getConfig:e}}=this.checkoutService.getState(),t=e();return t&&t.storeProfile}toShopperCurrency(e){const{exchangeRate:t=1}=this.getShopperCurrency()||{};return Math.round(e*t*100)/100}getSelectedShippingOption(){const{data:e}=this.checkoutService.getState(),t=e.getSelectedShippingOption();return t&&t.id&&t.description?t:null}getPaymentMethodName(){const{data:e}=this.checkoutService.getState(),t=e.getSelectedPaymentMethod();return t&&t.config&&t.config.displayName||""}getProducts(e,t){const n=(t.customItems||[]).map(e=>({product_id:e.id,sku:e.sku,price:e.listPrice,quantity:e.quantity,name:e.name})),i=t.giftCertificates.map(e=>({product_id:e.id,price:this.toShopperCurrency(e.amount),name:e.name,quantity:1}));return[...n,...[...t.physicalItems,...t.digitalItems].map(t=>{let n;t.options&&t.options.length&&(n=t.options.map(e=>`${e.name}:${e.value}`),n.sort());const i=Array.isArray(n)&&n.length?n.join(", "):"single-product-option",r=e[t.productId]&&e[t.productId].brand;return Object.assign({product_id:String(t.productId),sku:t.sku,price:t.salePrice,image_url:t.imageUrl,name:t.name,quantity:t.quantity,category:e[t.productId]?e[t.productId].category:"",variant:i},r&&{brand:r})}),...i]}}class TI{trackCheckoutStarted(){}trackOrderComplete(){}trackStepViewed(){}trackStepCompleted(){}}function kI(e,t){const{data:n}=e.getState(),i=n.getConfig();if(!i)throw new rt(et.MissingCheckoutConfig);const{isAnalyticsEnabled:r}=i.checkoutSettings;return r&&pl(window)?new AI(e,new hl(Te),window.analytics,t):new TI}function DI(e){return Boolean(e.hasOwnProperty("braintreeFastlane"))}class MI{constructor(e){this.checkoutService=e,this._selectedPaymentMethodId=""}customerPaymentMethodExecuted(){this._shouldTrackFastlaneEvent()&&this._trackEmailSubmitted()}paymentComplete(){this._shouldTrackFastlaneEvent()&&this._trackOrderPlaced(this._selectedPaymentMethodId)}selectedPaymentMethod(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!1))}walletButtonClick(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!0))}_shouldTrackFastlaneEvent(){const e=this.checkoutService.getState(),t=e.data.getPaymentMethod("braintree")||e.data.getPaymentMethod("braintreeacceleratedcheckout"),n=null==t?void 0:t.initializationData.isBraintreeAnalyticsV2Enabled,i=DI(window)&&window.braintreeFastlane.events;return n&&i}_getBraintreeEventsOrThrow(){if(DI(window))return window.braintreeFastlane.events;throw new mi}_trackEmailSubmitted(){const{emailSubmitted:e}=this._getBraintreeEventsOrThrow();e(this._getEmailSubmittedEventOptions())}_trackApmSelected(e,t){const{apmSelected:n}=this._getBraintreeEventsOrThrow();n(this._getApmSelectedEventOptions(e,t))}_trackOrderPlaced(e){const{orderPlaced:t}=this._getBraintreeEventsOrThrow();t(this._getOrderPlacedEventOptions(e))}_getEventCommonOptions(){var e,t;const n=this.checkoutService.getState(),i=n.data.getCart(),r=null===(e=n.data.getConfig())||void 0===e?void 0:e.storeProfile,o=null===(t=n.data.getCustomer())||void 0===t?void 0:t.isGuest,a=n.data.getPaymentMethod("braintreeacceleratedcheckout"),s=[{treatment_group:!n.errors.getLoadPaymentMethodError("braintreeacceleratedcheckout")&&(null==a?void 0:a.initializationData.shouldRunAcceleratedCheckout)?"test":"control"}];return{context_type:"cs_id",context_id:(null==i?void 0:i.id)||"",page_type:"checkout_page",page_name:window.document.title,partner_name:"bigc",user_type:o?"store_guest":"store_member",store_id:(null==r?void 0:r.storeId)||"",merchant_name:(null==r?void 0:r.storeName)||"",experiment:JSON.stringify(s)}}_getEmailSubmittedEventOptions(){const e=(this.checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{user_email_saved:!1,apm_shown:e.length>1?"1":"0",apm_list:e.join(",")})}_getApmSelectedEventOptions(e,t){const n=(this.checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{apm_shown:n.length>1?"1":"0",apm_list:n.join(","),apm_selected:e,apm_location:t?"pre-email section":"payment section"})}_getOrderPlacedEventOptions(e){const t=this.checkoutService.getState().data.getCart();return Object.assign(Object.assign({},this._getEventCommonOptions()),{selected_payment_method:e,currency_code:(null==t?void 0:t.currency.code)||""})}}function zI(e){return new MI(e)}class NI{constructor(e){this._checkoutService=e,this._selectedPaymentMethodId=""}customerPaymentMethodExecuted(){this._shouldTrackFastlaneEvent()&&this._trackEmailSubmitted()}paymentComplete(){this._shouldTrackFastlaneEvent()&&this._trackOrderPlaced(this._selectedPaymentMethodId)}selectedPaymentMethod(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!1))}walletButtonClick(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!0))}_shouldTrackFastlaneEvent(){const e=this._checkoutService.getState().data.getPaymentMethod("paypalcommerce"),t=((null==e?void 0:e.initializationData)||{}).isPayPalCommerceAnalyticsV2Enabled,n=window,i=!!n.paypalFastlane&&!!n.paypalFastlane.events;return t&&i}_getPayPalEventsOrThrow(){const e=window;if(e.paypalFastlane&&e.paypalFastlane.events)return e.paypalFastlane.events;throw new mi}_trackEmailSubmitted(){const{emailSubmitted:e}=this._getPayPalEventsOrThrow();e(this._getEmailSubmittedEventOptions())}_trackApmSelected(e,t){const{apmSelected:n}=this._getPayPalEventsOrThrow();n(this._getApmSelectedEventOptions(e,t))}_trackOrderPlaced(e){const{orderPlaced:t}=this._getPayPalEventsOrThrow();t(this._getOrderPlacedEventOptions(e))}_getEventCommonOptions(){var e,t;const n=this._checkoutService.getState(),i=n.data.getCart(),r=null===(e=n.data.getConfig())||void 0===e?void 0:e.storeProfile,o=null===(t=n.data.getCustomer())||void 0===t?void 0:t.isGuest,a="paypalcommerceacceleratedcheckout",s=n.data.getPaymentMethod(a),d=[{treatment_group:!n.errors.getLoadPaymentMethodError(a)&&(null==s?void 0:s.initializationData.shouldRunAcceleratedCheckout)?"test":"control"}];return{context_type:"cs_id",context_id:(null==i?void 0:i.id.replace(/-/g,""))||"",page_type:"checkout_page",page_name:window.document.title,partner_name:"bigc",user_type:o?"store_guest":"store_member",store_id:(null==r?void 0:r.storeId)||"",merchant_name:(null==r?void 0:r.storeName)||"",experiment:JSON.stringify(d)}}_getEmailSubmittedEventOptions(){const e=(this._checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{user_email_saved:!1,apm_shown:e.length>1?"1":"0",apm_list:e.join(",")})}_getApmSelectedEventOptions(e,t){const n=(this._checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{apm_shown:n.length>1?"1":"0",apm_list:n.join(","),apm_selected:e,apm_location:t?"pre-email section":"payment section"})}_getOrderPlacedEventOptions(e){const t=this._checkoutService.getState().data.getCart();return Object.assign(Object.assign({},this._getEventCommonOptions()),{selected_payment_method:e,currency_code:(null==t?void 0:t.currency.code)||""})}}function xI(e){return new NI(e)}var RI;class FI{constructor(e,t){this._host=e,this._hostedFormFactory=t}submitStoredCard(e,t){return n=this,i=void 0,o=function*(){const n=this._hostedForm;if(!n)throw new yn(cn.PaymentNotInitialized);yield n.validate().then(()=>n.submitStoredCard({fields:e,data:t}))},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}initialize(e){const t=this._hostedFormFactory.create(this._host,e);return t.attach().then(()=>{this._hostedForm=t})}deinitialize(){this._hostedForm&&this._hostedForm.detach()}}function LI(e){const t=m_();return new FI(e,new Iy(t))}!function(e){e.CUSTOMER="customer",e.SHIPPING="shipping",e.BILLING="billing",e.PAYMENT="payment"}(RI||(RI={}));const BI=[RI.CUSTOMER,RI.SHIPPING,RI.BILLING,RI.PAYMENT];class jI{constructor(e,t){this.subscribe=e,this.bodlEvents=t,this._checkoutStarted=!1,this._emailEntryBegan=!1,this._shippingOptionsShown=!1,this._completedSteps={},this.subscribe(e=>{var t;if(this.setState(e.data),!(null===(t=this.state)||void 0===t?void 0:t.getConfig()))throw new rt(et.MissingCheckoutConfig)})}setState(e){this.state=e}checkoutBegin(){const e=this._getCommonCheckoutData();!this._checkoutStarted&&e&&(this.bodlEvents.emitCheckoutBeginEvent(e),this._checkoutStarted=!0)}orderPurchased(){var e;const t=null===(e=this.state)||void 0===e?void 0:e.getOrder();if(!t)return;const{currency:n,isComplete:i,orderId:r,orderAmount:o,shippingCostTotal:a,lineItems:s,cartId:d,coupons:c,channelId:l,taxTotal:u}=t;i&&this.bodlEvents.emitOrderPurchasedEvent({event_id:d,currency:n.code,order_id:r,tax:u,channel_id:l,cart_value:o,coupon_codes:c.map(e=>e.code.toUpperCase()),shipping_cost:a,line_items:this._getProducts(s,n.code)})}stepCompleted(e){e&&BI.some(t=>(this._hasStepCompleted(t)||this._trackCompletedStep(t),t===e))}customerEmailEntry(e){!this._emailEntryBegan&&(null==e?void 0:e.length)&&(this._emailEntryBegan=!0,this.bodlEvents.emit("bodl_checkout_email_entry_began"))}customerSuggestionInit(e){this.bodlEvents.emit("bodl_checkout_customer_suggestion_initialization",e)}customerSuggestionExecute(){this.bodlEvents.emit("bodl_checkout_customer_suggestion_execute")}customerPaymentMethodExecuted(e){this.bodlEvents.emit("bodl_checkout_customer_payment_method_executed",e)}showShippingMethods(){this._shippingOptionsShown||(this._shippingOptionsShown=!0,this.bodlEvents.emit("bodl_checkout_show_shipping_options"))}selectedPaymentMethod(e){const t=this._getCommonCheckoutData();t&&e&&this.bodlEvents.emitPaymentDetailsProvidedEvent(Object.assign(Object.assign({},t),{payment_type:e}))}clickPayButton(e){this.bodlEvents.emit("bodl_checkout_click_pay_button",e)}paymentRejected(){this.bodlEvents.emit("bodl_checkout_payment_rejected")}paymentComplete(){this.bodlEvents.emit("bodl_checkout_payment_complete")}exitCheckout(){this.bodlEvents.emit("bodl_checkout_exit")}_trackCompletedStep(e){this._completedSteps[e]=!0;const t={[RI.SHIPPING]:this._trackShippingStepCompleted.bind(this)}[e];t?t():this.bodlEvents.emit("bodl_checkout_step_completed",{step:e})}_trackShippingStepCompleted(){var e,t;const n=null===(t=null===(e=this.state)||void 0===e?void 0:e.getSelectedShippingOption())||void 0===t?void 0:t.description,i=this._getCommonCheckoutData();i&&n&&this.bodlEvents.emitShippingDetailsProvidedEvent(Object.assign(Object.assign({},i),{shipping_method:n}))}_getCommonCheckoutData(){var e;const t=null===(e=this.state)||void 0===e?void 0:e.getCheckout();if(!t)return null;const{cart:{cartAmount:n,currency:i,lineItems:r,id:o,coupons:a},channelId:s}=t;return{event_id:o,currency:i.code,cart_value:n,coupon_codes:a.map(e=>e.code.toUpperCase()),line_items:this._getProducts(r,i.code),channel_id:s}}_getProducts(e,t){const n=(e.customItems||[]).map(e=>({product_id:e.id,sku:e.sku,base_price:e.listPrice,sale_price:e.listPrice,purchase_price:e.listPrice,quantity:e.quantity,product_name:e.name,currency:t})),i=e.giftCertificates.map(e=>({product_id:e.id,gift_certificate_id:e.id,base_price:e.amount,sale_price:e.amount,purchase_price:e.amount,product_name:e.name,gift_certificate_name:e.name,gift_certificate_theme:e.theme,quantity:1,currency:t}));return[...n,...[...e.physicalItems,...e.digitalItems].map(e=>{let n;return e.options&&e.options.length&&(n=e.options.map(e=>`${e.name}:${e.value}`),n.sort()),{product_id:e.productId,quantity:e.quantity,product_name:e.name,base_price:e.listPrice,sale_price:e.salePrice,purchase_price:e.salePrice>0?e.salePrice:e.listPrice,sku:e.sku,variant_id:e.variantId,discount:e.discountAmount,coupon_amount:e.couponAmount,brand_name:e.brand,currency:t,category_names:(i=e,Array.isArray(i.categoryNames)?i.categoryNames:Array.isArray(i.categories)?q(i.categories).map(({name:e})=>e):[]),retail_price:e.retailPrice};var i}),...i].map(e=>Object.assign(Object.assign({},e),{product_id:String(e.product_id)}))}_hasStepCompleted(e){return this._completedSteps[e]}}class UI{checkoutBegin(){}orderPurchased(){}stepCompleted(){}customerEmailEntry(){}customerSuggestionInit(){}customerSuggestionExecute(){}customerPaymentMethodExecuted(){}showShippingMethods(){}selectedPaymentMethod(){}clickPayButton(){}paymentRejected(){}paymentComplete(){}exitCheckout(){}}function qI(e){return function(e){return"bodlEvents"in e}(window)?new jI(e,window.bodlEvents.checkout):new UI}export{Bn as ExtensionCommandType,jn as ExtensionQueryType,qI as createBodlService,zI as createBraintreeAnalyticTracker,Qw as createCheckoutButtonInitializer,y_ as createCheckoutService,wI as createCurrencyService,pI as createEmbeddedCheckoutMessenger,fI as createLanguageService,xI as createPayPalCommerceAnalyticTracker,kI as createStepTracker,LI as createStoredCardHostedFormService,i as createTimeout,aI as embedCheckout,Ye as isExtraField}; +import*as e from"iframe-resizer";import*as t from"iframe-resizer/js/iframeResizer.contentWindow";import{createRequestSender as n,createTimeout as i}from"@bigcommerce/request-sender";import{ScriptLoader as r,createScriptLoader as o,getScriptLoader as a,getStylesheetLoader as s}from"@bigcommerce/script-loader";import{combineReducers as d,composeReducers as c,createAction as l,createDataStore as u,createErrorAction as h,deepFreeze as p}from"@bigcommerce/data-store";import{Observable as m,Subject as y,concat as g,defer as v,empty as f,from as S,fromEvent as _,merge as w,noop as I,of as C,throwError as b}from"rxjs";import{catchError as P,delay as O,distinctUntilChanged as E,filter as A,map as T,retryWhen as k,shareReplay as D,switchMap as M,take as z}from"rxjs/operators";import{cond as N,constant as x,difference as R,each as F,filter as L,find as B,findIndex as j,flatMap as U,flatten as q,get as V,identity as G,includes as H,isArray as W,isEmpty as $,isEqual as Y,isMatch as K,isNil as J,isObject as Z,isPlainObject as Q,isString as X,isUndefined as ee,kebabCase as te,keyBy as ne,keys as ie,last as re,map as oe,max as ae,memoize as se,merge as de,noop as ce,omit as le,omitBy as ue,overSome as he,pick as pe,pickBy as me,reduce as ye,round as ge,some as ve,stubTrue as fe,transform as Se,union as _e,uniq as we,uniqueId as Ie,values as Ce,without as be}from"lodash";import{memoize as Pe,memoizeOne as Oe}from"@bigcommerce/memoize";import{createFormPoster as Ee}from"@bigcommerce/form-poster";import{supportsPopups as Ae}from"@braintree/browser-detection";import{default as Te}from"local-storage-fallback";import{createClient as ke}from"@bigcommerce/bigpay-client";import{creditCardType as De,number as Me}from"card-validator";import{exclude as ze,parseUrl as Ne,stringifyUrl as xe}from"query-string";import{createSelector as Re,createSelectorCreator as Fe,defaultMemoize as Le}from"reselect";import{default as Be}from"shallowequal";import{IntlMessageFormat as je}from"intl-messageformat";var Ue={785(t,n,i){var r,o;t.exports=(r={iframeResizer:()=>e.iframeResizer},o={},i.d(o,r),o)},939(e){e.exports=t}},qe={};function Ve(e){var t=qe[e];if(void 0!==t)return t.exports;var n=qe[e]={exports:{}};return Ue[e](n,n.exports,Ve),n.exports}Ve.d=(e,t)=>{for(var n in t)Ve.o(t,n)&&!Ve.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},Ve.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ve.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var Ge={};Ve.r(Ge),Ve.d(Ge,{createAmazonPayV2CustomerStrategy:()=>Ii,createApplePayCustomerStrategy:()=>Xi,createBigCommercePaymentsCustomerStrategy:()=>br,createBigCommercePaymentsFastlaneCustomerStrategy:()=>Hr,createBigCommercePaymentsPayLaterCustomerStrategy:()=>Yr,createBigCommercePaymentsVenmoCustomerStrategy:()=>Zr,createBoltCustomerStrategy:()=>so,createBraintreeFastlaneCustomerStrategy:()=>zo,createBraintreePaypalCreditCustomerStrategy:()=>Oo,createBraintreePaypalCustomerStrategy:()=>Co,createBraintreeVisaCheckoutCustomerStrategy:()=>Ro,createGooglePayAdyenV2CustomerStrategy:()=>ca,createGooglePayAdyenV3CustomerStrategy:()=>la,createGooglePayAuthorizeDotNetCustomerStrategy:()=>ha,createGooglePayBigCommercePaymentsCustomerStrategy:()=>as,createGooglePayBnzCustomerStrategy:()=>_a,createGooglePayBraintreeCustomerStrategy:()=>Ya,createGooglePayCheckoutComCustomerStrategy:()=>va,createGooglePayCybersourceCustomerStrategy:()=>Sa,createGooglePayOrbitalCustomerStrategy:()=>Ia,createGooglePayPayPalCommerceCustomerStrategy:()=>is,createGooglePayStripeCustomerStrategy:()=>qa,createGooglePayStripeUpeCustomerStrategy:()=>Va,createGooglePayTdOnlineMartCustomerStrategy:()=>ls,createGooglePayWorldpayAccessCustomerStrategy:()=>Ha,createPayPalCommerceCreditCustomerStrategy:()=>Js,createPayPalCommerceCustomerStrategy:()=>zs,createPayPalCommerceFastlaneCustomerStrategy:()=>sd,createPayPalCommerceVenmoCustomerStrategy:()=>Xs,createStripeLinkV2CustomerStrategy:()=>Id,createStripeUPECustomerStrategy:()=>ud});var He={};Ve.r(He),Ve.d(He,{createAdyenV2PaymentStrategy:()=>Ld,createAdyenV3PaymentStrategy:()=>Vd,createAffirmPaymentStrategy:()=>Yd,createAfterpayPaymentStrategy:()=>tc,createAmazonPayV2PaymentStrategy:()=>rc,createApplePayPaymentStrategy:()=>dc,createBigCommercePaymentsAlternativeMethodsPaymentStrategy:()=>xc,createBigCommercePaymentsCreditCardsPaymentStrategy:()=>Mc,createBigCommercePaymentsFastlanePaymentStrategy:()=>fc,createBigCommercePaymentsPayLaterPaymentStrategy:()=>wc,createBigCommercePaymentsPaymentStrategy:()=>mc,createBigCommercePaymentsRatePayPayPaymentStrategy:()=>Pc,createBigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy:()=>Fc,createBigCommercePaymentsVenmoPaymentStrategy:()=>jc,createBlueSnapDirectAPMPaymentStrategy:()=>al,createBlueSnapDirectCreditCardPaymentStrategy:()=>rl,createBlueSnapV2PaymentStrategy:()=>ul,createBoltPaymentStrategy:()=>fl,createBraintreeAchPaymentStrategy:()=>Il,createBraintreeCreditCardPaymentStrategy:()=>Ql,createBraintreeFastlanePaymentStrategy:()=>Ll,createBraintreeLocalMethodsPaymentStrategy:()=>Nl,createBraintreePaypalPaymentStrategy:()=>kl,createBraintreeVenmoPaymentStrategy:()=>Gl,createBraintreeVisaCheckoutPaymentStrategy:()=>Ul,createCBAMPGSPaymentStrategy:()=>ou,createCheckoutComAPMPaymentStrategy:()=>wu,createCheckoutComCreditCardPaymentStrategy:()=>mu,createCheckoutComFawryPaymentStrategy:()=>cu,createCheckoutComIdealPaymentStrategy:()=>fu,createCheckoutComSepaPaymentStrategy:()=>gu,createClearpayPaymentStrategy:()=>Pu,createCreditCardPaymentStrategy:()=>Ou,createCyberSourcePaymentStrategy:()=>Uu,createCyberSourceV2PaymentStrategy:()=>Wu,createGooglePayAdyenV2PaymentStrategy:()=>Qu,createGooglePayAdyenV3PaymentStrategy:()=>th,createGooglePayAuthorizeNetPaymentStrategy:()=>nh,createGooglePayBigCommercePaymentsPaymentStrategy:()=>fh,createGooglePayBraintreePaymentStrategy:()=>dh,createGooglePayCheckoutComPaymentStrategy:()=>ih,createGooglePayCybersourcePaymentStrategy:()=>rh,createGooglePayOrbitalPaymentStrategy:()=>oh,createGooglePayPPCPPaymentStrategy:()=>ph,createGooglePayStripePaymentStrategy:()=>ah,createGooglePayTdOnlineMartPaymentStrategy:()=>Sh,createGooglePayWorldpayAccessPaymentStrategy:()=>sh,createHummPaymentStrategy:()=>Ih,createKlarnaPaymentStrategy:()=>Ah,createKlarnaV2PaymentStrategy:()=>zh,createLegacyPaymentStrategy:()=>xh,createMolliePaymentStrategy:()=>Uh,createMonerisPaymentStrategy:()=>Hh,createNoPaymentStrategy:()=>Pd,createOfflinePaymentStrategy:()=>$h,createOffsitePaymentStrategy:()=>Jh,createPayPalCommerceAlternativeMethodsPaymentStrategy:()=>lp,createPayPalCommerceCreditCardsPaymentStrategy:()=>pp,createPayPalCommerceCreditPaymentStrategy:()=>ip,createPayPalCommerceFastlanePaymentStrategy:()=>_p,createPayPalCommercePaymentStrategy:()=>ep,createPayPalCommerceRatePayPaymentStrategy:()=>gp,createPayPalCommerceVenmoPaymentStrategy:()=>ap,createPayPalProPaymentStrategy:()=>zp,createPaypalExpressPaymentStrategy:()=>kp,createSagePayPaymentStrategy:()=>xp,createSezzlePaymentStrategy:()=>Lp,createSquareV2PaymentStrategy:()=>Wp,createStripeCSPaymentStrategy:()=>ym,createStripeOCSPaymentStrategy:()=>hm,createStripeUPEPaymentStrategy:()=>dm,createStripeV3PaymentStrategy:()=>im,createTDOnlineMartPaymentStrategy:()=>_m,createWorldpayAccessOpenBankingPaymentStrategy:()=>Em,createWorldpayAccessPaymentStrategy:()=>Pm,createZipPaymentStrategy:()=>km});var We={};Ve.r(We),Ve.d(We,{createAmazonPayV2ButtonStrategy:()=>w_,createApplePayButtonStrategy:()=>O_,createBigCommercePaymentsButtonStrategy:()=>T_,createBigCommercePaymentsPayLaterButtonStrategy:()=>M_,createBigCommercePaymentsVenmoButtonStrategy:()=>x_,createBoltButtonStrategy:()=>F_,createBraintreePaypalButtonStrategy:()=>q_,createBraintreePaypalCreditButtonStrategy:()=>H_,createBraintreeVenmoButtonStrategy:()=>ew,createBraintreeVisaCheckoutButtonStrategy:()=>Y_,createGooglePayAdyenV2ButtonStrategy:()=>aw,createGooglePayAdyenV3ButtonStrategy:()=>sw,createGooglePayAuthorizeDotNetButtonStrategy:()=>dw,createGooglePayBigCommercePaymentsButtonStrategy:()=>ow,createGooglePayBraintreeButtonStrategy:()=>iw,createGooglePayCheckoutComButtonStrategy:()=>cw,createGooglePayCybersourceButtonStrategy:()=>lw,createGooglePayOrbitalButtonStrategy:()=>uw,createGooglePayPayPalCommerceButtonStrategy:()=>rw,createGooglePayStripeButtonStrategy:()=>hw,createGooglePayTdOnlineMartButtonStrategy:()=>mw,createGooglePayWorldpayAccessButtonStrategy:()=>pw,createLinkV2ButtonStrategy:()=>Aw,createPayPalCommerceButtonStrategy:()=>gw,createPayPalCommerceCreditButtonStrategy:()=>Sw,createPayPalCommerceVenmoButtonStrategy:()=>Iw,createPaypalExpressButtonStrategy:()=>Pw});const $e="b2bExtraField_";function Ye(e){return e.name.startsWith($e)}function Ke(e){var t;const{fieldType:n,type:i}=function(e){switch(e){case"multiline_text":return{fieldType:"multiline",type:"string"};case"number":return{fieldType:"text",type:"integer"};case"dropdown":return{fieldType:"dropdown",type:"array"};default:return{fieldType:"text",type:"string"}}}(e.type);let r;return e.config.numberOfRows&&(r={rows:e.config.numberOfRows}),(null===(t=e.config.options)||void 0===t?void 0:t.length)&&(r=Object.assign(Object.assign({},r),{items:e.config.options.map(e=>({value:e,label:e}))})),{id:`${$e}${e.id}`,name:`${$e}${e.id}`,custom:!1,label:e.name,hidden:!e.visibleToStorefront,required:e.isRequired,default:null!=e.config.defaultValue?String(e.config.defaultValue):void 0,fieldType:n,type:i,maxLength:e.config.maxLength,max:e.config.maxValue,options:r}}function Je(e,t,n){return(i=t)&&i.type&&i.error?g(C(t),b(h(e,t.payload,n))):b(h(e,t,n));var i}var Ze;!function(e){e.LoadB2BTokenRequested="LOAD_B2B_TOKEN_REQUESTED",e.LoadB2BTokenSucceeded="LOAD_B2B_TOKEN_SUCCEEDED",e.LoadB2BTokenFailed="LOAD_B2B_TOKEN_FAILED"}(Ze||(Ze={}));class Qe{constructor(e){this._requestSender=e}loadB2BToken(e){return t=>{var n;const i=t.getState(),r=i.config.getStoreConfigOrThrow(),{storeHash:o}=r.storeProfile,{baseUrl:a="",clientId:s=""}=null!==(n=r.b2bApiSettings)&&void 0!==n?n:{},{id:d}=i.customer.getCustomerOrThrow(),{channelId:c}=i.checkout.getCheckoutOrThrow();return g(C(l(Ze.LoadB2BTokenRequested)),v(()=>{return t=this,n=void 0,r=function*(){const{body:t}=yield this._requestSender.getB2BToken(s,d,o,c,a,e);return l(Ze.LoadB2BTokenSucceeded,{token:t.data.token})},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r})).pipe(P(e=>Je(Ze.LoadB2BTokenFailed,e)))}}}const Xe={"X-Checkout-SDK-Version":"1.909.5"};var et,tt;class nt{constructor(e){this._requestSender=e}getB2BToken(e,t,n,i,r,o){return a=this,s=void 0,c=function*(){const{body:a}=yield this._requestSender.get("/customer/current.jwt",{timeout:null==o?void 0:o.timeout,params:{app_client_id:e},headers:Xe});return this._requestSender.post(`${r}/api/v2/login`,{timeout:null==o?void 0:o.timeout,credentials:!1,headers:{"Content-Type":"application/json"},body:{bcToken:a.token,customerId:t,storeHash:n,channelId:i}})},new((d=void 0)||(d=Promise))(function(e,t){function n(e){try{r(c.next(e))}catch(e){t(e)}}function i(e){try{r(c.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof d?r:new d(function(e){e(r)})).then(n,i)}r((c=c.apply(a,s||[])).next())});var a,s,d,c}}class it extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}!function(e){e[e.MissingBillingAddress=0]="MissingBillingAddress",e[e.MissingCart=1]="MissingCart",e[e.MissingCheckout=2]="MissingCheckout",e[e.MissingConsignments=3]="MissingConsignments",e[e.MissingCustomer=4]="MissingCustomer",e[e.MissingCheckoutConfig=5]="MissingCheckoutConfig",e[e.MissingOrder=6]="MissingOrder",e[e.MissingOrderConfig=7]="MissingOrderConfig",e[e.MissingOrderId=8]="MissingOrderId",e[e.MissingPayment=9]="MissingPayment",e[e.MissingPaymentId=10]="MissingPaymentId",e[e.MissingPaymentInstrument=11]="MissingPaymentInstrument",e[e.MissingPaymentMethod=12]="MissingPaymentMethod",e[e.MissingPaymentProviderCustomer=13]="MissingPaymentProviderCustomer",e[e.MissingPaymentRedirectUrl=14]="MissingPaymentRedirectUrl",e[e.MissingPaymentStatus=15]="MissingPaymentStatus",e[e.MissingPaymentToken=16]="MissingPaymentToken",e[e.MissingShippingAddress=17]="MissingShippingAddress"}(et||(et={}));class rt extends it{constructor(e){super(function(e){switch(e){case et.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case et.MissingCart:return"Unable to proceed because cart data is unavailable.";case et.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case et.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case et.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case et.MissingCheckoutConfig:case et.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case et.MissingOrder:return"Unable to proceed because order data is unavailable.";case et.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case et.MissingPayment:return"Unable to proceed because payment data is unavailable.";case et.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case et.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case et.MissingPaymentProviderCustomer:return"Unable to proceed because payment provider customer is unavailable.";case et.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e)),this.subtype=e,this.name="MissingDataError",this.type="missing_data"}}!function(e){e.UpdateBillingAddressRequested="UPDATE_BILLING_ADDRESS_REQUESTED",e.UpdateBillingAddressSucceeded="UPDATE_BILLING_ADDRESS_SUCCEEDED",e.UpdateBillingAddressFailed="UPDATE_BILLING_ADDRESS_FAILED",e.ContinueAsGuestRequested="CONTINUE_AS_GUEST_REQUESTED",e.ContinueAsGuestSucceeded="CONTINUE_AS_GUEST_SUCCEEDED",e.ContinueAsGuestFailed="CONTINUE_AS_GUEST_FAILED"}(tt||(tt={}));class ot extends it{constructor(e){super(e||"Unable to continue as a guest because the customer is already signed in."),this.name="UnableToContinueAsGuestError",this.type="unable_to_continue_as_guest"}}var at;class st{constructor(e,t){this._requestSender=e,this._subscriptionActionCreator=t}continueAsGuest(e,t){return n=>{const i=n.getState(),r=i.checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);const o=i.customer.getCustomer();if(o&&!o.isGuest)throw new ot;const a=i.billingAddress.getBillingAddress();let s;if(a){const{country:t}=a,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{return e=this,n=void 0,o=function*(){const{body:e}=yield this._createOrUpdateBillingAddress(r.id,s,d,t);return l(tt.ContinueAsGuestSucceeded,e)},new((i=void 0)||(i=Promise))(function(t,r){function a(e){try{d(o.next(e))}catch(e){r(e)}}function s(e){try{d(o.throw(e))}catch(e){r(e)}}function d(e){var n;e.done?t(e.value):(n=e.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((o=o.apply(e,n||[])).next())});var e,n,i,o})).pipe(P(e=>Je(tt.ContinueAsGuestFailed,e))),this._updateCustomerConsent(e,t))}}updateAddress(e,t){return n=>m.create(i=>{const r=n.getState(),o=r.checkout.getCheckout();if(!o)throw new rt(et.MissingCheckout);i.next(l(tt.UpdateBillingAddressRequested));const a=r.billingAddress.getBillingAddress(),s=!$(a),d=Object.assign(Object.assign({},e),{email:void 0===e.email&&a?a.email:e.email});a&&a.id&&(d.id=a.id),this._createOrUpdateBillingAddress(o.id,d,s,t).then(({body:e})=>{i.next(l(tt.UpdateBillingAddressSucceeded,e)),i.complete()}).catch(e=>{i.error(h(tt.UpdateBillingAddressFailed,e))})})}_updateCustomerConsent({email:e,acceptsAbandonedCartEmails:t,acceptsMarketingNewsletter:n},i){return null==t&&null==n?f():this._subscriptionActionCreator.updateSubscriptions({email:e,acceptsMarketingNewsletter:n||!1,acceptsAbandonedCartEmails:t||!1},i)}_createOrUpdateBillingAddress(e,t,n,i){return n?this._requestSender.updateAddress(e,t,i):this._requestSender.createAddress(e,t,i)}}class dt extends it{constructor(e){super(e||"Your checkout could not be processed because your cart is empty. Please add items to your cart and try again."),this.name="EmptyCartError",this.type="empty_cart"}}!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(at||(at={}));const ct=at;const lt={include:["cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","promotions.banners"].join(",")};class ut{constructor(e){this._requestSender=e}createAddress(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/billing-address`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{body:t,params:lt,headers:r,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}updateAddress(e,t,{timeout:n}={}){const{id:i}=t,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if("empty_cart"===e.body.type)throw new dt;throw e})}}var ht,pt;function mt(e,t){const n=u((e,t)=>t.type===ht.Synchronize?t.payload:e,e.getState(),{stateTransformer:t});return e.subscribe(e=>{n.dispatch(l(ht.Synchronize,e))},{initial:!1}),n}!function(e){e.Synchronize="SYNCHRONIZE"}(ht||(ht={})),function(e){e.ClearError="CLEAR_ERROR"}(pt||(pt={}));class yt{clearError(e){return{type:pt.ClearError,payload:e}}}class gt{constructor(e,t){this._requestSender=e,this._config=t}sendRequest(e,t){return this._requestSender.sendRequest(e,t)}get(e,t){return this._requestSender.get(e,t)}post(e,t){return this._requestSender.post(this._prefixed(e),t)}put(e,t){return this._requestSender.put(this._prefixed(e),t)}patch(e,t){return this._requestSender.patch(this._prefixed(e),t)}delete(e,t){return this._requestSender.delete(this._prefixed(e),t)}_prefixed(e){const t=this._config.getBasePath();return!this._config.getFeatures()["CHECKOUT-9950.update_sf_checkout_url_for_subfolder"]||!t||t.endsWith("/checkout")||/^https?:\/\//.test(e)?e:`${t}${e}`}}function vt(){try{return"production"}catch(e){return"development"}}class ft{constructor(e){this._console=e}log(...e){this._logToConsole("log",...e)}info(...e){this._logToConsole("info",...e)}warn(...e){this._logToConsole("warn",...e)}error(...e){this._logToConsole("error",...e)}debug(...e){this._logToConsole("debug",...e)}_logToConsole(e,...t){this._console&&this._console[e]&&this._console[e].call(this._console,...t)}}class St{log(){}info(){}warn(){}error(){}debug(){}}const _t=function(e=!0){return e?new ft(console):new St}("test"!==vt());function wt(){return _t}function It(e,t,n){const i=new WeakMap;function r(e){return(...n)=>{const r=n[n.length-1],{useCache:o}=(a=r)&&"boolean"==typeof a.useCache?r:{useCache:!1};var a;if(!o)return e.call(this,...n);const s=i.get(this)||{};var d;return i.get(this)||i.set(this,s),s[t]||(s[t]=(d=e,Pe(function(...e){const t=d.call(this,...e);return t instanceof m?S(t).pipe(D()):"function"==typeof t?Pe(e=>S(t(e)).pipe(D()),{isEqual:Y}):t},{isEqual:Y}))),s[t].call(this,...n)}}return{get(){if("function"!=typeof n.value)throw new Error("Decorator should be used in functions");const e=r.call(this,n.value);return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e}}}var Ct;!function(e){e.LoadConfigRequested="LOAD_CONFIG_REQUESTED",e.LoadConfigSucceeded="LOAD_CONFIG_SUCCEEDED",e.LoadConfigFailed="LOAD_CONFIG_FAILED"}(Ct||(Ct={}));class bt{constructor(e){this._configRequestSender=e}loadConfig(e){return m.create(t=>{t.next(l(Ct.LoadConfigRequested)),this._configRequestSender.loadConfig(e).then(e=>{t.next(l(Ct.LoadConfigSucceeded,e.body)),t.complete()}).catch(e=>{t.error(h(Ct.LoadConfigFailed,e))})})}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([It],bt.prototype,"loadConfig",null);const Pt={body:{},headers:{},status:0};class Ot extends it{constructor(e,{message:t,errors:n}={}){const{body:i,headers:r,status:o}=e||Pt;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=i,this.headers=r,this.status=o,this.errors=n||[]}}class Et extends Ot{constructor(e){super(e,{message:e.body.title}),this.name="CheckoutNotAvailableError",this.type="checkout_not_available"}}const At="This API endpoint is for internal use only and may change in the future";class Tt{constructor(e){this._requestSender=e}loadConfig({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/checkout-settings",{timeout:e,headers:Object.assign({Accept:ct.JsonV1,"X-API-INTERNAL":At},Xe),params:t}).catch(e=>{if(e.status>=400&&e.status<500)throw new Et(e);throw e})}}var kt;!function(e){e.ApplyCouponRequested="APPLY_COUPON_REQUESTED",e.ApplyCouponSucceeded="APPLY_COUPON_SUCCEEDED",e.ApplyCouponFailed="APPLY_COUPON_FAILED",e.RemoveCouponRequested="REMOVE_COUPON_REQUESTED",e.RemoveCouponSucceeded="REMOVE_COUPON_SUCCEEDED",e.RemoveCouponFailed="REMOVE_COUPON_FAILED"}(kt||(kt={}));class Dt{constructor(e){this._couponRequestSender=e}applyCoupon(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l(kt.ApplyCouponRequested)),this._couponRequestSender.applyCoupon(r.id,e,t).then(({body:e})=>{i.next(l(kt.ApplyCouponSucceeded,e)),i.complete()}).catch(e=>{i.error(h(kt.ApplyCouponFailed,e))})})}removeCoupon(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l(kt.RemoveCouponRequested)),this._couponRequestSender.removeCoupon(r.id,e,t).then(({body:e})=>{i.next(l(kt.RemoveCouponSucceeded,e)),i.complete()}).catch(e=>{i.error(h(kt.RemoveCouponFailed,e))})})}}const Mt=["cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","customer.customerGroup","payments","promotions.banners"];var zt,Nt,xt,Rt;function Ft(e){return we(e).join(",")}!function(e){e.AvailableShippingOptions="consignments.availableShippingOptions",e.PhysicalItemsCategoryNames="cart.lineItems.physicalItems.categoryNames",e.DigitalItemsCategoryNames="cart.lineItems.digitalItems.categoryNames"}(zt||(zt={}));class Lt{constructor(e){this._requestSender=e}applyCoupon(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/coupons`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{headers:r,timeout:n,params:{include:Ft([...Mt,zt.AvailableShippingOptions])},body:{couponCode:t}}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}removeCoupon(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/coupons/${t}`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.delete(i,{headers:r,timeout:n,params:{include:Ft([...Mt,zt.AvailableShippingOptions])}}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}!function(e){e.ApplyGiftCertificateRequested="APPLY_GIFT_CERTIFICATE_REQUESTED",e.ApplyGiftCertificateSucceeded="APPLY_GIFT_CERTIFICATE_SUCCEEDED",e.ApplyGiftCertificateFailed="APPLY_GIFT_CERTIFICATE_FAILED",e.RemoveGiftCertificateRequested="REMOVE_GIFT_CERTIFICATE_REQUESTED",e.RemoveGiftCertificateSucceeded="REMOVE_GIFT_CERTIFICATE_SUCCEEDED",e.RemoveGiftCertificateFailed="REMOVE_GIFT_CERTIFICATE_FAILED"}(Nt||(Nt={}));class Bt{constructor(e){this._giftCertificateRequestSender=e}applyGiftCertificate(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l(Nt.ApplyGiftCertificateRequested)),this._giftCertificateRequestSender.applyGiftCertificate(r.id,e,t).then(({body:e})=>{i.next(l(Nt.ApplyGiftCertificateSucceeded,e)),i.complete()}).catch(e=>{i.error(h(Nt.ApplyGiftCertificateFailed,e))})})}removeGiftCertificate(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l(Nt.RemoveGiftCertificateRequested)),this._giftCertificateRequestSender.removeGiftCertificate(r.id,e,t).then(({body:e})=>{i.next(l(Nt.RemoveGiftCertificateSucceeded,e)),i.complete()}).catch(e=>{i.error(h(Nt.RemoveGiftCertificateFailed,e))})})}}class jt{constructor(e){this._requestSender=e}applyGiftCertificate(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/gift-certificates`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{headers:r,timeout:n,params:{include:Ft(Mt)},body:{giftCertificateCode:t}}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}removeGiftCertificate(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/gift-certificates/${t}`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.delete(i,{headers:r,timeout:n,params:{include:Ft(Mt)}}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}function Ut(e){return e&&"resolveIds"in e}class qt extends it{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class Vt{constructor(e){var t,n,i;this._factories={},this._instances={},this._defaultToken=null!==(t=null==e?void 0:e.defaultToken)&&void 0!==t?t:"default",this._useFallback=null===(n=null==e?void 0:e.useFallback)||void 0===n||n,this._tokenResolver=null!==(i=null==e?void 0:e.tokenResolver)&&void 0!==i?i:e=>e}get(e,t){try{return this._getInstance(e||this._defaultToken,t||e||this._defaultToken)}catch(e){if(!this._useFallback)throw e;return this._getInstance(this._defaultToken,t||this._defaultToken)}}getFactory(e,t){const n=this._tokenResolver(e,Object.keys(this._factories),t);return n?this._factories[n]:void 0}register(e,t){if(this._hasFactory(e))throw new qt(`'${e}' is already registered.`);this._factories[e]=t}_hasFactory(e){return!!this._factories[e]}_hasInstance(e){return!!this._instances[e]}_getInstance(e,t){if(!this._hasInstance(t)){const n=this.getFactory(e);if(!n)throw new qt(`'${e}' is not registered.`);this._instances[t]=n()}return this._instances[t]}}class Gt{constructor(e=!1){this._useFallback=e,this._registry=new Vt({tokenResolver:this._resolveToken.bind(this),defaultToken:this._encodeToken({default:!0}),useFallback:this._useFallback})}get(e){return this._registry.get(this._encodeToken(e))}getFactory(e,t){try{return this._registry.getFactory(this._encodeToken(e),t)}catch(e){return}}getUseFallback(){return this._useFallback}register(e,t){this._registry.register(this._encodeToken(e),t)}_encodeToken(e){return btoa(JSON.stringify(e))}_decodeToken(e){return JSON.parse(atob(e))}_resolveToken(e,t,n){var i;const r=this._decodeToken(e),o=[];t.forEach(e=>{const t=this._decodeToken(e),n={token:e,matches:0,default:!1,totalKeys:Object.keys(t).length};for(const[e,i]of Object.entries(t)){if(e in r&&r[e]!==i){n.matches=0;break}e in r&&r[e]===i&&n.matches++,"default"===e&&!0===i&&(n.default=!0)}o.push(n)});const a=o.sort((e,t)=>t.matches-e.matches).filter(e=>e.matches>0);a.length>1&&a[0].matches===a[1].matches&&"development"===vt()&&wt().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.");const s=Object.keys(r).length;if(n){const e=a.find(e=>e.matches===s&&e.matches===e.totalKeys);if(!e)throw new Error(`Unable to resolve to a registered token with the provided token for ${JSON.stringify(r)} with exact match.`);return e.token}const d=a[0];if(d&&d.token)return d.token;if(this._useFallback){const e=null===(i=o.find(e=>e.default))||void 0===i?void 0:i.token;if(e)return e}throw new Error(`Unable to resolve to a registered token with the provided token for ${JSON.stringify(r)}.`)}}function Ht(e){const t=e;return"object"==typeof t&&"object"==typeof t.payload&&"string"==typeof t.payload.token}!function(e){e.BuyNow="BUY_NOW"}(xt||(xt={})),function(e){e.SignInCustomerRequested="SIGN_IN_CUSTOMER_REQUESTED",e.SignInCustomerSucceeded="SIGN_IN_CUSTOMER_SUCCEEDED",e.SignInCustomerFailed="SIGN_IN_CUSTOMER_FAILED",e.SignOutCustomerRequested="SIGN_OUT_CUSTOMER_REQUESTED",e.SignOutCustomerSucceeded="SIGN_OUT_CUSTOMER_SUCCEEDED",e.SignOutCustomerFailed="SIGN_OUT_CUSTOMER_FAILED",e.CreateCustomerRequested="CREATE_CUSTOMER_REQUESTED",e.CreateCustomerSucceeded="CREATE_CUSTOMER_SUCCEEDED",e.CreateCustomerFailed="CREATE_CUSTOMER_FAILED",e.CreateCustomerAddressRequested="CREATE_CUSTOMER_ADDRESS_REQUESTED",e.CreateCustomerAddressSucceeded="CREATE_CUSTOMER_ADDRESS_SUCCEEDED",e.CreateCustomerAddressFailed="CREATE_CUSTOMER_ADDRESS_FAILED",e.StripeLinkAuthenticated="STRIPE_LINK_AUTHENTICATED"}(Rt||(Rt={}));var Wt,$t,Yt;class Kt{constructor(e,t,n){this._customerRequestSender=e,this._checkoutActionCreator=t,this._spamProtectionActionCreator=n}createCustomer(e,t){return n=>{const i=n.getState().config.getStoreConfigOrThrow(),{isStorefrontSpamProtectionEnabled:r}=i.checkoutSettings,o=i=>S(this._customerRequestSender.createAccount(Object.assign(Object.assign({},e),{token:i}),t)).pipe(M(()=>g(this._checkoutActionCreator.loadCurrentCheckout(t)(n),C(l(Rt.CreateCustomerSucceeded)))));return g(C(l(Rt.CreateCustomerRequested)),r?S(this._spamProtectionActionCreator.execute()(n)).pipe(M(e=>{var t;return Ht(e)?g(C(e),o(null===(t=e.payload)||void 0===t?void 0:t.token)):C(e)})):o()).pipe(P(e=>Je(Rt.CreateCustomerFailed,e)))}}createAddress(e,t){return g(C(l(Rt.CreateCustomerAddressRequested)),v(()=>{return n=this,i=void 0,o=function*(){const{body:n}=yield this._customerRequestSender.createAddress(e,t);return l(Rt.CreateCustomerAddressSucceeded,n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Je(Rt.CreateCustomerAddressFailed,e)))}signInCustomer(e,t){return n=>{const i=n.getState().checkout.getCheckoutOrThrow(),r=i.cart.source===xt.BuyNow?i.id:void 0;return g(C(l(Rt.SignInCustomerRequested)),S(this._customerRequestSender.signInCustomer(Object.assign(Object.assign({},e),{cartId:r}),t)).pipe(M(({body:e})=>e.data.persistentCartRetrievalInformation?g(this._checkoutActionCreator.loadCheckout(e.data.persistentCartRetrievalInformation.id,t)(n),C(l(Rt.SignInCustomerSucceeded,e.data))):g(this._checkoutActionCreator.loadCurrentCheckout(t)(n),C(l(Rt.SignInCustomerSucceeded,e.data)))))).pipe(P(e=>Je(Rt.SignInCustomerFailed,e)))}}signOutCustomer(e){return t=>{const n=t.getState().checkout.getCheckoutOrThrow(),i=n.cart.source===xt.BuyNow?n.id:void 0;return g(C(l(Rt.SignOutCustomerRequested)),S(this._customerRequestSender.signOutCustomer(e,i)).pipe(M(({body:n})=>g(this._checkoutActionCreator.loadCurrentCheckout(e)(t),C(l(Rt.SignOutCustomerSucceeded,n.data)))))).pipe(P(e=>Je(Rt.SignOutCustomerFailed,e)))}}}class Jt{constructor(e){this._requestSender=e}createAccount(e,{timeout:t}={}){return this._requestSender.post("/api/storefront/customer",{timeout:t,headers:Xe,body:e})}createAddress(e,{timeout:t}={}){return this._requestSender.post("/api/storefront/customer-address",{timeout:t,headers:Xe,body:e})}signInCustomer(e,{timeout:t}={}){return this._requestSender.post("/internalapi/v1/checkout/customer",{timeout:t,headers:Xe,body:e})}signOutCustomer({timeout:e}={},t){return this._requestSender.delete("/internalapi/v1/checkout/customer",Object.assign({timeout:e,headers:Xe},t&&{body:{cartId:t}}))}}function Zt(e,t,n){t.forEach(t=>{Ut(t)&&t.resolveIds.forEach(i=>{e.getFactory(i,!0)||e.register(i,()=>t(n))})})}!function(e){e.SignInFailed="CUSTOMER_STRATEGY_SIGN_IN_FAILED",e.SignInRequested="CUSTOMER_STRATEGY_SIGN_IN_REQUESTED",e.SignInSucceeded="CUSTOMER_STRATEGY_SIGN_IN_SUCCEEDED",e.SignOutFailed="CUSTOMER_STRATEGY_SIGN_OUT_FAILED",e.SignOutRequested="CUSTOMER_STRATEGY_SIGN_OUT_REQUESTED",e.SignOutSucceeded="CUSTOMER_STRATEGY_SIGN_OUT_SUCCEEDED",e.ExecutePaymentMethodCheckoutFailed="CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_FAILED",e.ExecutePaymentMethodCheckoutRequested="CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_REQUESTED",e.ExecutePaymentMethodCheckoutSucceeded="CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_SUCCEEDED",e.InitializeFailed="CUSTOMER_STRATEGY_INITIALIZE_FAILED",e.InitializeRequested="CUSTOMER_STRATEGY_INITIALIZE_REQUESTED",e.InitializeSucceeded="CUSTOMER_STRATEGY_INITIALIZE_SUCCEEDED",e.DeinitializeFailed="CUSTOMER_STRATEGY_DEINITIALIZE_FAILED",e.DeinitializeRequested="CUSTOMER_STRATEGY_DEINITIALIZE_REQUESTED",e.DeinitializeSucceeded="CUSTOMER_STRATEGY_DEINITIALIZE_SUCCEEDED",e.WidgetInteractionStarted="CUSTOMER_STRATEGY_WIDGET_INTERACTION_STARTED",e.WidgetInteractionFinished="CUSTOMER_STRATEGY_WIDGET_INTERACTION_FINISHED",e.WidgetInteractionFailed="CUSTOMER_STRATEGY_WIDGET_INTERACTION_FAILED"}(Wt||(Wt={}));class Qt{constructor(e,t,n){this._strategyRegistry=e,this._strategyRegistryV2=t,this._paymentIntegrationService=n}signIn(e,t){return m.create(n=>{const i=t&&t.methodId,r={methodId:i};n.next(l(Wt.SignInRequested,void 0,r)),this._getStrategy(i).signIn(e,t).then(()=>{n.next(l(Wt.SignInSucceeded,void 0,r)),n.complete()}).catch(e=>{n.error(h(Wt.SignInFailed,e,r))})})}signOut(e){return m.create(t=>{const n=e&&e.methodId,i={methodId:n};t.next(l(Wt.SignOutRequested,void 0,i)),this._getStrategy(n).signOut(e).then(()=>{t.next(l(Wt.SignOutSucceeded,void 0,i)),t.complete()}).catch(e=>{t.error(h(Wt.SignOutFailed,e,i))})})}executePaymentMethodCheckout(e){return m.create(t=>{const n=e&&e.methodId,i={methodId:n};t.next(l(Wt.ExecutePaymentMethodCheckoutRequested,void 0,i)),this._getStrategy(n).executePaymentMethodCheckout(e).then(()=>{t.next(l(Wt.ExecutePaymentMethodCheckoutSucceeded,void 0,i)),t.complete()}).catch(e=>{t.error(h(Wt.ExecutePaymentMethodCheckoutFailed,e,i))})})}initialize(e){return t=>m.create(n=>{var i;const r=t.getState(),o=e&&e.methodId,a={methodId:o};if(Zt(this._strategyRegistryV2,null!==(i=null==e?void 0:e.integrations)&&void 0!==i?i:[],this._paymentIntegrationService),o&&r.customerStrategies.isInitialized(o))return n.complete();n.next(l(Wt.InitializeRequested,void 0,a)),this._getStrategy(o).initialize(e).then(()=>{n.next(l(Wt.InitializeSucceeded,void 0,a)),n.complete()}).catch(e=>{n.error(h(Wt.InitializeFailed,e,a))})})}deinitialize(e){return t=>m.create(n=>{const i=t.getState(),r=e&&e.methodId,o={methodId:r};if(r&&!i.customerStrategies.isInitialized(r))return n.complete();n.next(l(Wt.DeinitializeRequested,void 0,o)),this._getStrategy(r).deinitialize(e).then(()=>{n.next(l(Wt.DeinitializeSucceeded,void 0,o)),n.complete()}).catch(e=>{n.error(h(Wt.DeinitializeFailed,e,o))})})}widgetInteraction(e,t){return m.create(n=>{const i={methodId:t&&t.methodId};n.next(l(Wt.WidgetInteractionStarted,void 0,i)),e().then(()=>{n.next(l(Wt.WidgetInteractionFinished,void 0,i)),n.complete()}).catch(e=>{n.error(h(Wt.WidgetInteractionFailed,e,i))})})}_getStrategy(e){let t;try{t=this._strategyRegistryV2.get({id:e||""})}catch(n){t=this._strategyRegistry.get(e)}return t}}function Xt(e,t=[]){return Array.isArray(t)?Ft([...e,...t]):function(e,t){const n=ie(me(t,e=>!e)),i=ie(L(t));return Ft([...R(e,n),...i])}(e,t)}class en{constructor(e){this._requestSender=e}loadCheckout(e,{params:{include:t}={},timeout:n}={}){const i=`/api/storefront/checkout/${e}`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.get(i,{params:{include:Xt(Mt,t)},headers:r,timeout:n}).catch(e=>{if(e.status>=400&&e.status<500)throw new Et(e);throw e})}updateCheckout(e,t,{params:{include:n}={},timeout:i}={}){const r=`/api/storefront/checkout/${e}`,o=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.put(r,{params:{include:Xt(Mt,n)},body:t,headers:o,timeout:i}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}!function(e){e.LoadCheckoutRequested="LOAD_CHECKOUT_REQUESTED",e.LoadCheckoutSucceeded="LOAD_CHECKOUT_SUCCEEDED",e.LoadCheckoutFailed="LOAD_CHECKOUT_FAILED",e.UpdateCheckoutRequested="UPDATE_CHECKOUT_REQUESTED",e.UpdateCheckoutSucceeded="UPDATE_CHECKOUT_SUCCEEDED",e.UpdateCheckoutFailed="UPDATE_CHECKOUT_FAILED"}($t||($t={})),function(e){e.HydrateInitialState="HYDRATE_INITIAL_STATE"}(Yt||(Yt={}));var tn;class nn{constructor(e,t,n){this._checkoutRequestSender=e,this._configActionCreator=t,this._formFieldsActionCreator=n}loadCheckout(e,t){return()=>g(C(l($t.LoadCheckoutRequested)),w(this._configActionCreator.loadConfig({useCache:!0,timeout:null==t?void 0:t.timeout,params:{checkoutId:e}}),this._formFieldsActionCreator.loadFormFields({useCache:!0,timeout:null==t?void 0:t.timeout})),v(()=>this._checkoutRequestSender.loadCheckout(e,t).then(({body:e})=>l($t.LoadCheckoutSucceeded,this._transformCustomerAddresses(e))))).pipe(P(e=>Je($t.LoadCheckoutFailed,e)))}loadDefaultCheckout(e){return t=>g(C(l($t.LoadCheckoutRequested)),w(this._configActionCreator.loadConfig({useCache:!0,timeout:null==e?void 0:e.timeout}),this._formFieldsActionCreator.loadFormFields({useCache:!0,timeout:null==e?void 0:e.timeout})),v(()=>{return n=this,i=void 0,o=function*(){const n=t.getState().config.getContextConfig();if(!n||!n.checkoutId)throw new rt(et.MissingCheckoutConfig);const{body:i}=yield this._checkoutRequestSender.loadCheckout(n.checkoutId,e);return l($t.LoadCheckoutSucceeded,this._transformCustomerAddresses(i))},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Je($t.LoadCheckoutFailed,e)))}updateCheckout(e,t){return n=>new m(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);i.next(l($t.UpdateCheckoutRequested)),this._checkoutRequestSender.updateCheckout(r.id,e,t).then(({body:e})=>{i.next(l($t.UpdateCheckoutSucceeded,e)),i.complete()}).catch(e=>{i.error(h($t.UpdateCheckoutFailed,e))})})}loadCurrentCheckout(e){return t=>{const n=t.getState().checkout.getCheckout();if(!n)throw new rt(et.MissingCheckout);return this.loadCheckout(n.id,e)(t)}}hydrateInitialState(e){return{type:Yt.HydrateInitialState,payload:e}}_transformCustomerAddresses(e){return Object.assign(Object.assign({},e),{customer:Object.assign(Object.assign({},e.customer),{addresses:e.customer.addresses.map(e=>Object.assign(Object.assign({},e),{shouldSaveAddress:!1}))})})}}!function(e){e.LoadFormFieldsRequested="LOAD_FORM_FIELDS_REQUESTED",e.LoadFormFieldsSucceeded="LOAD_FORM_FIELDS_SUCCEEDED",e.LoadFormFieldsFailed="LOAD_FORM_FIELDS_FAILED"}(tn||(tn={}));var rn;class on{constructor(e){this._formFieldsRequestSender=e}loadFormFields(e){return g(C(l(tn.LoadFormFieldsRequested)),v(()=>{return t=this,n=void 0,r=function*(){const{body:t}=yield this._formFieldsRequestSender.loadFields(e);return l(tn.LoadFormFieldsSucceeded,t)},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r})).pipe(P(e=>Je(tn.LoadFormFieldsFailed,e)))}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([It],on.prototype,"loadFormFields",null);class an{constructor(e){this._requestSender=e}loadFields({timeout:e}={}){return this._requestSender.get("/api/storefront/form-fields",{timeout:e,headers:Object.assign({Accept:ct.JsonV1,"X-API-INTERNAL":At},Xe)})}}class sn extends it{constructor(){super("You haven't complete our spam protection challenge. Please try again."),this.name="SpamProtectionChallengeNotCompletedError",this.type="spam_protection_challenge_not_completed"}}class dn extends it{constructor(){super("We were not able to complete your spam protection verification. Please try again."),this.name="SpamProtectionFailedError",this.type="spam_protection_failed"}}!function(e){e.InitializeFailed="SPAM_PROTECTION_INITIALIZE_FAILED",e.InitializeSucceeded="SPAM_PROTECTION_INITIALIZE_SUCCEEDED",e.InitializeRequested="SPAM_PROTECTION_INITIALIZE_REQUESTED",e.VerifyCheckoutRequested="SPAM_PROTECTION_CHECKOUT_VERIFY_REQUESTED",e.VerifyCheckoutSucceeded="SPAM_PROTECTION_CHECKOUT_VERIFY_SUCCEEDED",e.VerifyCheckoutFailed="SPAM_PROTECTION_CHECKOUT_VERIFY_FAILED",e.ExecuteRequested="SPAM_PROTECTION_EXECUTE_REQUESTED",e.ExecuteSucceeded="SPAM_PROTECTION_EXECUTE_SUCCEEDED",e.ExecuteFailed="SPAM_PROTECTION_EXECUTE_FAILED"}(rn||(rn={}));var cn,ln,un,hn=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pn{constructor(e,t){this._googleRecaptcha=e,this._requestSender=t}initialize(e){return t=>g(C(l(rn.InitializeRequested,void 0)),v(()=>hn(this,void 0,void 0,function*(){const n=e?e.containerId:"spamProtectionContainer";if(document.getElementById(n)&&this._googleRecaptcha.reset(n),!e&&!document.getElementById(n)){const e=document.createElement("div");e.setAttribute("id",n),document.body.appendChild(e)}const i=t.getState().config.getStoreConfigOrThrow().checkoutSettings.googleRecaptchaSitekey;return yield this._googleRecaptcha.load(n,i),l(rn.InitializeSucceeded)}))).pipe(P(e=>Je(rn.InitializeFailed,e)))}verifyCheckoutSpamProtection(){return e=>v(()=>{const t=e.getState().checkout.getCheckout();if(!t)throw new rt(et.MissingCheckout);return g(C(l(rn.VerifyCheckoutRequested)),S(this.execute()(e)).pipe(M(e=>Ht(e)&&e.payload?S(this._requestSender.validate(t.id,e.payload.token)).pipe(M(({body:t})=>g(C(e),C(l(rn.VerifyCheckoutSucceeded,t))))):C(e)))).pipe(P(e=>Je(rn.VerifyCheckoutFailed,e)))})}execute(){return e=>g(C(l(rn.ExecuteRequested)),this.initialize()(e),this._googleRecaptcha.execute().pipe(z(1)).pipe(M(({error:e,token:t})=>hn(this,void 0,void 0,function*(){if(e instanceof sn)throw e;if(e||!t)throw new dn;return l(rn.ExecuteSucceeded,{token:t})})))).pipe(P(e=>Je(rn.ExecuteFailed,e)))}}class mn{constructor(e=window){this._window=e}create(e){return new this._window.MutationObserver(e)}}!function(e){e[e.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",e[e.CustomerNotInitialized=1]="CustomerNotInitialized",e[e.PaymentNotInitialized=2]="PaymentNotInitialized",e[e.ShippingNotInitialized=3]="ShippingNotInitialized",e[e.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(cn||(cn={}));class yn extends it{constructor(e){super(function(e){switch(e){case cn.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case cn.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case cn.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case cn.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.subtype=e,this.name="NotInitializedError",this.type="not_initialized"}}class gn extends it{constructor(){super("Spam protection is not loaded. Please try again."),this.name="SpamProtectionNotLoadedError",this.type="spam_protection_failed"}}class vn{constructor(e,t){this.googleRecaptchaScriptLoader=e,this.mutationObserverFactory=t,this._memoized=Pe((e,t,n)=>{const i=new y;if(!n)throw new Error;return this._widgetId=e.render(n.id,{sitekey:t,size:"invisible",callback:()=>{i.next({token:e.getResponse(this._widgetId)}),e.reset(this._widgetId)},"error-callback":()=>{i.next({error:new dn})}}),i},{isEqual:(e,t)=>e===t})}load(e,t){return this.googleRecaptchaScriptLoader.load().then(n=>{n&&(this._event$=this._memoized(n,t,document.getElementById(e)),this._recaptcha=n)}).catch(e=>{throw e})}reset(e){var t;const n=document.getElementById(e);null==n||n.remove(),null===(t=this._recaptcha)||void 0===t||t.reset(this._widgetId)}execute(){return v(()=>{const e=this._event$,t=this._recaptcha;if(!e||!t)throw new yn(cn.SpamProtectionNotInitialized);return v(()=>{const e=document.querySelector('iframe[src*="bframe"]');return e?C(e):b(new gn)}).pipe(k(e=>e.pipe(O(250),M((e,t)=>t<28?C(e):b(e)))),M(n=>(this._watchRecaptchaChallengeWindow(e,n),t.execute(this._widgetId),e)),P(e=>C({error:e})))})}_watchRecaptchaChallengeWindow(e,t){const n=t.parentElement;if(!n)throw new gn;const i=n.parentElement;if(!i)throw new gn;this.mutationObserverFactory.create(()=>{"hidden"===i.style.visibility&&e.next({error:new sn})}).observe(i,{attributes:!0,attributeFilter:["style"]})}}class fn{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(){return this._loadPromise||(this._loadPromise=this._loadScript()),this._loadPromise}_loadScript(){const e="initRecaptcha",t=[`onload=${e}`,"render=explicit"].join("&");return new Promise((n,i)=>{this._window[e]=()=>n(this._window.grecaptcha),this._scriptLoader.loadScript(`//www.google.com/recaptcha/api.js?${t}`).catch(e=>{this._loadPromise=void 0,i(e)})})}}function Sn(e){return new vn(new fn(e),new mn)}class _n{constructor(e){this._requestSender=e}validate(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/spam-protection`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{body:{token:t},headers:r,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}class wn{constructor(e,t){this._store=e,this._customerActionCreator=t}signIn(e,t){return this._store.dispatch(this._customerActionCreator.signInCustomer(e,t))}signOut(e){return this._store.dispatch(this._customerActionCreator.signOutCustomer(e))}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())}initialize(){return Promise.resolve(this._store.getState())}deinitialize(){return Promise.resolve(this._store.getState())}}function In(e){if(!/^(https?:)?\/\//.test(e))throw new qt("The provided URL must be absolute.");const t=document.createElement("a");t.href=e;const n=t.port&&-1!==e.indexOf(`${t.hostname}:${t.port}`)?t.port:"";return{hash:t.hash,hostname:t.hostname,href:t.href,origin:`${t.protocol}//${t.hostname}${n?`:${n}`:""}`,pathname:t.pathname,port:n,protocol:t.protocol,search:t.search}}class Cn extends it{constructor(e){super(e||"Unable to proceed due to no extension configured for this region."),this.name="ExtensionNotFoundError",this.type="extension_not_found"}}function bn(e,t){return e.type===t}!function(e){e.LoadExtensionsRequested="LOAD_EXTENSIONS_REQUESTED",e.LoadExtensionsSucceeded="LOAD_EXTENSIONS_SUCCEEDED",e.LoadExtensionsFailed="LOAD_EXTENSIONS_FAILED",e.RenderExtensionRequested="RENDER_EXTENSION_REQUESTED",e.RenderExtensionSucceeded="RENDER_EXTENSION_SUCCEEDED",e.RenderExtensionFailed="RENDER_EXTENSION_FAILED"}(ln||(ln={}));class Pn{constructor(e,t,n){this._targetWindow=t,this._context=n,this._targetOrigin="*"===e?"*":In(e).origin}post(e,t){const n=this._targetWindow;if(window===n)return;if(!n)throw new Error("Unable to post message because target window is not set.");const i=t&&_(window,"message").pipe(A(e=>e.origin===this._targetOrigin&&bn(e.data,e.data.type)&&-1!==[t.successType,t.errorType].indexOf(e.data.type)),T(e=>{if(t.errorType===e.data.type)throw e.data;return e.data}),z(1)).toPromise();return n.postMessage(Object.assign(Object.assign({},e),{context:this._context}),this._targetOrigin),i}setTarget(e){this._targetWindow=e}setContext(e){this._context=e}}function On(e){var t;const n=null===(t=document.querySelector(`[data-extension-id="${e.id}"]`))||void 0===t?void 0:t.querySelector("iframe");if(!(null==n?void 0:n.contentWindow))throw new Cn(`Unable to post due to no extension rendered for ID: ${e.id}.`);return new Pn(e.url,n.contentWindow)}!function(e){e.ExtensionReady="EXTENSION:READY",e.ExtensionFailed="EXTENSION:FAILED"}(un||(un={}));class En{constructor(e){const t=new Promise((e,t)=>{this.cancel=t});this.promise=Promise.race([e,t])}}class An extends it{constructor(e){super(e||"Unable to proceed because the required element is unexpectedly detached from the page."),this.name="UnexpectedDetachmentError",this.type="unexpected_detachment"}}var Tn;class kn{constructor(e){this._mutationObserver=e}ensurePresence(e,t){return n=this,i=void 0,o=function*(){const n=new En(t),i=this._mutationObserver.create(t=>{t.forEach(t=>{0!==Array.from(t.removedNodes).filter(t=>e.some(e=>t===e||t.contains(e))).length&&n.cancel(new An)})});i.observe(document.body,{childList:!0,subtree:!0});try{const e=yield n.promise;return i.disconnect(),e}catch(e){throw i.disconnect(),e}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}function Dn(e,t){const{iframeResizer:n}=Ve(785);return n(e,t)}class Mn extends it{constructor(e){super(e||"Unable to load an extension"),this.name="ExtensionNotLoadedError",this.type="extension_not_loaded"}}!function(e){e.Subscribe="EXTENSION_INTERNAL:SUBSCRIBE",e.Unsubscribe="EXTENSION_INTERNAL:UNSUBSCRIBE",e.ResizeIframe="EXTENSION_INTERNAL:RESIZE_IFRAME"}(Tn||(Tn={}));class zn{constructor(e){this._options=e}createFrame(e,t,n,i){const r=document.getElementById(t),{timeout:o=6e4}=this._options||{};if(!r)throw new Mn("Unable to embed the iframe because the container element could not be found.");const a=document.createElement("iframe");return a.src=e,a.style.border="none",a.style.display="none",a.style.width="100%",r.appendChild(a),this._toResizableFrame(a,o,n,i).catch(e=>{throw r.removeChild(a),e})}_toResizableFrame(e,t,n,i){return r=this,o=void 0,s=function*(){const r=new kn(new mn),o=new Promise((r,o)=>{const a=window.setTimeout(()=>{try{i()}catch(e){e instanceof Error&&console.error(`Extension rendering timed out after ${t}ms, and the callback function could not be executed. Error: ${e.message}`)}o(new Mn("Unable to load the extension because the content could not be loaded."))},t),s=t=>{if(t.origin===In(e.src).origin&&bn(t.data,Tn.ResizeIframe)){e.style.display="";const t=Dn({autoResize:!1,scrolling:!1,sizeWidth:!1,heightCalculationMethod:"bodyOffset",initCallback:n},e);d(),r(t[t.length-1])}},d=()=>{window.removeEventListener("message",s),window.clearTimeout(a)};window.addEventListener("message",s)});return r.ensurePresence([e],o)},new((a=void 0)||(a=Promise))(function(e,t){function n(e){try{d(s.next(e))}catch(e){t(e)}}function i(e){try{d(s.throw(e))}catch(e){t(e)}}function d(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a(function(e){e(r)})).then(n,i)}d((s=s.apply(r,o||[])).next())});var r,o,a,s}}class Nn{constructor(e,t,n){this._containerId=e,this._extension=t,this._config=n;const{cartId:i,parentOrigin:r}=this._config;this._url=new URL(this._extension.url),this._url.searchParams.set("extensionId",this._extension.id),this._url.searchParams.set("cartId",i),this._url.searchParams.set("parentOrigin",r)}attach(){var e,t,n,i,r;return t=this,n=void 0,r=function*(){if(null===(e=document.querySelector(`[data-extension-id="${this._extension.id}"]`))||void 0===e?void 0:e.querySelector("iframe"))return;const t=new zn,n=e=>{On(this._extension).post({type:e})};this._iframe=yield t.createFrame(this._url.toString(),this._containerId,()=>{n(un.ExtensionReady)},()=>{n(un.ExtensionFailed)});const i=document.getElementById(this._containerId);null==i||i.setAttribute("data-extension-id",this._extension.id)},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())})}detach(){this._iframe&&this._iframe.parentElement&&this._iframe.parentElement.removeChild(this._iframe)}}class xn{constructor(e){this._requestSender=e}loadExtensions(e){return()=>m.create(t=>{t.next(l(ln.LoadExtensionsRequested)),this._requestSender.loadExtensions(e).then(e=>{const n=e.body;t.next(l(ln.LoadExtensionsSucceeded,n)),t.complete()}).catch(e=>{t.error(h(ln.LoadExtensionsFailed,e))})})}renderExtension(e,t,n){return i=>m.create(r=>{return o=this,a=void 0,d=function*(){const o=i.getState(),{id:a}=o.cart.getCartOrThrow(),{links:{checkoutLink:s}}=o.config.getStoreConfigOrThrow(),d=o.extensions.getExtensionByRegion(t);try{if(!d)throw new Cn(`Unable to proceed due to no extension configured for the region: ${t}.`);if(r.next(l(ln.RenderExtensionRequested)),"worker"===d.type){const e=function(e){if(!window.Worker)throw new Error("Unable to load the extension's web worker: your browser does not support Web Workers.");try{const t=URL.createObjectURL(new Blob([`importScripts=((i)=>(...a)=>i(...a.map((u)=>''+new URL(u,"${e}"))))(importScripts);importScripts("${e}")`],{type:"text/javascript"}));return new Worker(t)}catch(e){throw new Error("Unable to load the extension's web worker")}}(d.url);n.add(d.id,e)}else{const t=new Nn(e,d,{cartId:a,parentOrigin:In(s).origin});yield t.attach()}r.next(l(ln.RenderExtensionSucceeded)),r.complete()}catch(e){r.error(h(ln.RenderExtensionFailed,e))}},new((s=void 0)||(s=Promise))(function(e,t){function n(e){try{r(d.next(e))}catch(e){t(e)}}function i(e){try{r(d.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof s?r:new s(function(e){e(r)})).then(n,i)}r((d=d.apply(o,a||[])).next())});var o,a,s,d})}}class Rn{constructor(e){this._requestSender=e}loadExtensions({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/checkout-extensions",{timeout:e,headers:Object.assign({Accept:ct.JsonV1},Xe),params:t})}}const Fn=function(e,t,n){return t&&n?Ln(0,t,n):function(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(n=>{const i=Object.getOwnPropertyDescriptor(e.prototype,n);i&&"constructor"!==n&&Object.defineProperty(t.prototype,n,Ln(e.prototype,n,i))}),t}(e)};function Ln(e,t,n){if("function"!=typeof n.value)return n;let i=n.value;return{get(){const e=i.bind(this);return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e},set(e){i=e}}}var Bn,jn;class Un{constructor(e){this._worker=e,this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,this._worker.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,this._worker.removeEventListener("message",this._handleMessage))}addListener(e,t){let n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)}removeListener(e,t){const n=this._listeners[e];if(!n)return;const i=n.indexOf(t);i>=0&&n.splice(i,1)}trigger(e,t){const n=this._listeners[e.type];n&&n.forEach(n=>t?n(e,t):n(e))}_handleMessage(e){const t=e.data,{context:n}=t,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([Fn],Un.prototype,"_handleMessage",null);class qn{constructor(e,t){this._worker=e,this._context=t}post(e){if(!this._worker)throw new Error("WorkerPoster: Worker is not initialized or creation failed. Cannot post message.");this._worker.postMessage(Object.assign(Object.assign({},e),{context:this._context}))}}class Vn extends it{constructor(e){super(e||"Unable to proceed due to unsupported extension command."),this.name="UnsupportedExtensionCommandError",this.type="unsupported_extension_command_error"}}class Gn extends it{constructor(e){super(e||"Unable to proceed due to unsupported extension query."),this.name="UnsupportedExtensionQueryError",this.type="unsupported_extension_query_error"}}!function(e){e.ReloadCheckout="EXTENSION:RELOAD_CHECKOUT",e.ShowLoadingIndicator="EXTENSION:SHOW_LOADING_INDICATOR",e.SetIframeStyle="EXTENSION:SET_IFRAME_STYLE",e.ReRenderShippingForm="EXTENSION:RE_RENDER_SHIPPING_FORM",e.ReRenderShippingStep="EXTENSION:RE_RENDER_SHIPPING_STEP"}(Bn||(Bn={})),function(e){e.GetConsignments="EXTENSION:GET_CONSIGNMENTS"}(jn||(jn={}));class Hn{constructor(e={},t={},n={}){this._workers=e,this._commandListeners=t,this._queryListeners=n}add(e,t){this._workers[e]=t}listenForCommand(e,t,n){const i=this._getWorkerById(e);this._commandListeners[e]||(this._commandListeners[e]=new Un(i));const r=this._commandListeners[e];r.listen();const o=this._validateCommand(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}listenForQuery(e,t,n){const i=this._getWorkerById(e);this._queryListeners[e]||(this._queryListeners[e]=new Un(i));const r=this._queryListeners[e];r.listen();const o=this._validateQuery(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}stopListen(e){this._commandListeners[e]&&this._commandListeners[e].stopListen(),this._queryListeners[e]&&this._queryListeners[e].stopListen()}post(e,t){if(!this._workers[e])throw new Error(`Worker with extensionId ${e} not found`);new qn(this._workers[e],e).post(t)}clearCacheById(e){delete this._workers[e]}_getWorkerById(e){const t=this._workers[e];if(!t)throw new Cn(`Worker with extensionId ${e} not found`);return t}_validateCommand(e){if(Object.values(Bn).includes(e))return e;throw new Vn}_validateQuery(e){if(Object.values(jn).includes(e))return e;throw new Gn}}function Wn(e){return In(0===e.hostname.indexOf("www")?e.href:e.href.replace(e.hostname,`www.${e.hostname}`))}var $n;class Yn{constructor(e){this._sourceOrigins=[In(e).origin,Wn(In(e)).origin],this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))}addListener(e,t){let n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)}removeListener(e,t){const n=this._listeners[e];if(!n)return;const i=n.indexOf(t);i>=0&&n.splice(i,1)}trigger(e,t){const n=this._listeners[e.type];n&&n.forEach(n=>t?n(e,t):n(e))}_handleMessage(e){if(-1===this._sourceOrigins.indexOf(e.origin)||!bn(e.data,e.data.type))return;const t=e.data,{context:n}=t,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([Fn],Yn.prototype,"_handleMessage",null);class Kn{constructor(e,t,n={},i={},r={}){this._store=e,this._workerExtensionMessenger=t,this._commandListeners=n,this._queryListeners=i,this._posters=r}clearCacheByRegion(e){const t=this._getExtensionByRegion(e);"worker"!==t.type?this.clearCacheById(t.id):this._workerExtensionMessenger.clearCacheById(t.id)}clearCacheById(e){const t=this._getExtensionById(e);"worker"!==t.type?(this._commandListeners[e]&&delete this._commandListeners[e],this._queryListeners[e]&&delete this._queryListeners[e],this._posters[e]&&delete this._posters[e]):this._workerExtensionMessenger.clearCacheById(t.id)}listenForCommand(e,t,n){const i=this._getExtensionById(e);if("worker"===i.type)return this._workerExtensionMessenger.listenForCommand(e,t,n);this._commandListeners[e]||(this._commandListeners[e]=new Yn(i.url));const r=this._commandListeners[e];r.listen();const o=this._validateCommand(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}listenForQuery(e,t,n){const i=this._getExtensionById(e);if("worker"===i.type)return this._workerExtensionMessenger.listenForQuery(e,t,n);this._queryListeners[e]||(this._queryListeners[e]=new Yn(i.url));const r=this._queryListeners[e];r.listen();const o=this._validateQuery(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}stopListen(e){"worker"!==this._getExtensionById(e).type?(this._commandListeners[e]&&this._commandListeners[e].stopListen(),this._queryListeners[e]&&this._queryListeners[e].stopListen()):this._workerExtensionMessenger.stopListen(e)}post(e,t){try{const n=this._getExtensionById(e);if("worker"===n.type)return void this._workerExtensionMessenger.post(e,t);this._posters[e]||(this._posters[e]=On(n)),this._posters[e].post(t)}catch(n){this.clearCacheById(e),console.log(`Unable to post event to extension(${e}) because extension iframe is not mounted.\nThe event that could not be delivered:`,t)}}_getExtensionById(e){var t;this._getExtensions();const n=null===(t=this._extensions)||void 0===t?void 0:t.find(t=>t.id===e);if(!n)throw new Cn(`Unable to proceed due to no extension found for ID: ${e}.`);return n}_getExtensionByRegion(e){var t;this._getExtensions();const n=null===(t=this._extensions)||void 0===t?void 0:t.find(t=>t.region===e);if(!n)throw new Cn(`Unable to proceed due to no extension found for region: ${e}.`);return n}_getExtensions(){if(this._extensions)return;const{extensions:{getExtensions:e}}=this._store.getState();if(this._extensions=e(),!this._extensions)throw new Cn("Extension configurations not found.")}_validateCommand(e){if(Object.values(Bn).includes(e))return e;throw new Vn}_validateQuery(e){if(Object.values(jn).includes(e))return e;throw new Gn}}class Jn{constructor(e,t,n){this._store=e,this._extensionMessenger=t,this._subscribers=n,this._subscribed={},this._unsubscribers={},this._listeners={}}listen(){var e;const{data:{getExtensions:t}}=this._store.getState();null===(e=t())||void 0===e||e.forEach(e=>{if(this._listeners[e.id])return;const t=new Yn(e.url);t.addListener(Tn.Subscribe,this._handleSubscribe.bind(this)),t.addListener(Tn.Unsubscribe,this._handleUnsubscribe.bind(this)),t.listen(),this._listeners[e.id]=t})}broadcast(e){var t;const{data:{getExtensions:n}}=this._store.getState();null===(t=n())||void 0===t||t.forEach(t=>{this._subscribed[t.id]&&this._extensionMessenger.post(t.id,e)})}_handleSubscribe({payload:{eventType:e,extensionId:t}}){this._subscribed[t]=!0,this._unsubscribers[e]||(this._unsubscribers[e]=this._subscribers[e](this._store,this))}_handleUnsubscribe({payload:{eventType:e,extensionId:t}}){var n,i;delete this._subscribed[t],Object.keys(this._subscribed).length||(null===(i=(n=this._unsubscribers)[e])||void 0===i||i.call(n),delete this._unsubscribers[e])}}!function(e){e.ConsignmentsChanged="EXTENSION:CONSIGNMENTS_CHANGED"}($n||($n={}));const Zn=(e,t)=>{var n;const{data:{getConsignments:i}}=e.getState();let r=null!==(n=i())&&void 0!==n?n:[];return e.subscribe(({data:{getConsignments:e}})=>{var n;const i=null!==(n=e())&&void 0!==n?n:[];i!==r&&(t.broadcast({type:$n.ConsignmentsChanged,payload:{consignments:i,previousConsignments:r}}),r=i)},({data:{getConsignments:e}})=>e())};class Qn extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}var Xn,ei;!function(e){e[e.MissingBillingAddress=0]="MissingBillingAddress",e[e.MissingCart=1]="MissingCart",e[e.MissingCheckout=2]="MissingCheckout",e[e.MissingConsignments=3]="MissingConsignments",e[e.MissingCustomer=4]="MissingCustomer",e[e.MissingCheckoutConfig=5]="MissingCheckoutConfig",e[e.MissingOrder=6]="MissingOrder",e[e.MissingOrderConfig=7]="MissingOrderConfig",e[e.MissingOrderId=8]="MissingOrderId",e[e.MissingPayment=9]="MissingPayment",e[e.MissingPaymentId=10]="MissingPaymentId",e[e.MissingPaymentInstrument=11]="MissingPaymentInstrument",e[e.MissingPaymentMethod=12]="MissingPaymentMethod",e[e.MissingPaymentRedirectUrl=13]="MissingPaymentRedirectUrl",e[e.MissingPaymentStatus=14]="MissingPaymentStatus",e[e.MissingPaymentToken=15]="MissingPaymentToken",e[e.MissingShippingAddress=16]="MissingShippingAddress"}(Xn||(Xn={}));class ti extends Qn{constructor(e){super(function(e){switch(e){case Xn.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case Xn.MissingCart:return"Unable to proceed because cart data is unavailable.";case Xn.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case Xn.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case Xn.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case Xn.MissingCheckoutConfig:case Xn.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case Xn.MissingOrder:return"Unable to proceed because order data is unavailable.";case Xn.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case Xn.MissingPayment:return"Unable to proceed because payment data is unavailable.";case Xn.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case Xn.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case Xn.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e)),this.subtype=e,this.name="MissingDataError",this.type="missing_data"}}function ni(e){return t=e.lineItems.physicalItems.filter(e=>!e.addedByPromotion),ye(t,(e,t)=>e+t.quantity,0);var t}function ii(e,t){if(null==e)throw t?t():new Error("An unexpected error has occurred.");return e}!function(e){e[e.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",e[e.CustomerNotInitialized=1]="CustomerNotInitialized",e[e.PaymentNotInitialized=2]="PaymentNotInitialized",e[e.ShippingNotInitialized=3]="ShippingNotInitialized",e[e.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(ei||(ei={}));class ri extends Qn{constructor(e){super(function(e){switch(e){case ei.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case ei.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case ei.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case ei.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.subtype=e,this.name="NotInitializedError",this.type="not_initialized"}}const oi={de:"eu",jp:"fe",uk:"eu",us:"na"};var ai,si,di,ci,li,ui;!function(e){e.en_US="en_US",e.en_GB="en_GB",e.de_DE="de_DE",e.fr_FR="fr_FR",e.it_IT="it_IT",e.es_ES="es_ES",e.ja_JP="ja_JP"}(ai||(ai={})),function(e){e.Home="Home",e.Product="Product",e.Cart="Cart",e.Checkout="Checkout",e.Other="Other"}(si||(si={})),function(e){e.USD="USD",e.EUR="EUR",e.GBP="GBP",e.JPY="JPY"}(di||(di={})),function(e){e.PayAndShip="PayAndShip",e.PayOnly="PayOnly"}(ci||(ci={})),function(e){e.Gold="Gold",e.LightGray="LightGray",e.DarkGray="DarkGray"}(li||(li={})),function(e){e.C0001="C0001"}(ui||(ui={}));var hi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pi{constructor(e){this.amazonPayV2ScriptLoader=e}initialize(e){return hi(this,void 0,void 0,function*(){this.amazonPayV2SDK=yield this.amazonPayV2ScriptLoader.load(e),this.buttonParentContainer=this.buttonParentContainer||this.createAmazonPayButtonParentContainer()})}deinitialize(){var e;return this.amazonPayV2Button=void 0,null===(e=this.buttonParentContainer)||void 0===e||e.remove(),this.buttonParentContainer=void 0,this.amazonPayV2SDK=void 0,Promise.resolve()}bindButton(e,t,n){this.getAmazonPayV2SDK().Pay.bindChangeAction(`#${e}`,{amazonCheckoutSessionId:t,changeAction:n})}createButton(e,t){this.amazonPayV2Button=this.getAmazonPayV2SDK().Pay.renderButton(`#${e}`,t)}prepareCheckout(e){const t=this.prepareRequestConfig(e);this.getAmazonPayV2Button().onClick(()=>{this.getAmazonPayV2Button().initCheckout(t)})}prepareCheckoutWithCreationRequestConfig(e){this.getAmazonPayV2Button().onClick(()=>hi(this,void 0,void 0,function*(){const t=yield e();if(t){const e=this.prepareRequestConfig(t.createCheckoutSessionConfig,t.estimatedOrderAmount,t.productType);this.getAmazonPayV2Button().initCheckout(e)}}))}signout(){return hi(this,void 0,void 0,function*(){return this.amazonPayV2SDK&&this.amazonPayV2SDK.Pay.signout(),Promise.resolve()})}renderAmazonPayButton({buttonColor:e,checkoutState:t,containerId:n,decoupleCheckoutInitiation:i=!1,methodId:r,options:o,placement:a,isButtonMicroTextDisabled:s=!1}){const d=document.querySelector(`#${n}`);if(!d)return;const{id:c}=d.appendChild(this.getButtonParentContainer());o&&s&&(o.design=ui.C0001);const l=null!=o?o:this.getAmazonPayV2ButtonOptions(t,r,a,i,e);return this.createButton(c,l),this.getButtonParentContainer()}updateBuyNowFlowFlag(e){this.isBuyNowFlow=Boolean(e)}isPh4Enabled(e,t){const n=!!e["PROJECT-3483.amazon_pay_ph4"],i=!!e["INT-6885.amazon_pay_ph4_us_only"];return n&&i?"US"===t:n}prepareRequestConfig(e,t,n){const{publicKeyId:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew ri(ei.PaymentNotInitialized))}getCheckoutState(e){return"object"==typeof(t=e)&&null!==t&&"cart"in t&&"checkout"in t&&"config"in t&&"paymentMethods"in t?{getCart:e.cart.getCart,getCheckout:e.checkout.getCheckout,getStoreConfigOrThrow:e.config.getStoreConfigOrThrow,getPaymentMethodOrThrow:t=>e.paymentMethods.getPaymentMethodOrThrow(t)}:e;var t}}class mi extends Qn{constructor(e){super(e||"Unable to proceed because the client library of a payment method is not loaded or ready to be used."),this.name="PaymentMethodClientUnavailableError",this.type="payment_method_client_unavailable"}}class yi{constructor(e,t=window){this.scriptLoader=e,this.windowWithAmazonPay=t}load(e){return t=this,n=void 0,r=function*(){const{initializationData:t}=e,n=(null==t?void 0:t.region)||"us",i=oi[n];if(yield this.scriptLoader.loadScript(`https://static-${i}.payments-amazon.com/checkout.js`),!this.windowWithAmazonPay.amazon)throw new mi;return this.windowWithAmazonPay.amazon},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}function gi(){return new pi(new yi(a()))}function vi(e,t){return Object.assign(e,{resolveIds:t})}class fi extends Qn{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class Si extends Qn{constructor(e){super(e||"Not implemented."),this.name="NotImplementedError",this.type="not_implemented"}}var _i=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class wi{constructor(e,t){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t}initialize(e){return _i(this,void 0,void 0,function*(){const{methodId:t,amazonpay:n}=e;if(!t||!(null==n?void 0:n.container))throw new fi('Unable to proceed because "methodId" or "containerId" argument is not provided.');let i;try{i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)}catch(e){yield this.paymentIntegrationService.loadPaymentMethod(t),i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)}yield this.amazonPayV2PaymentProcessor.initialize(i),this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:this.paymentIntegrationService.getState(),containerId:n.container,methodId:t,placement:si.Checkout})})}deinitialize(){return _i(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize()})}signIn(){throw new Si('In order to sign in via Amazon, the shopper must click on "Amazon Pay" button.')}signOut(e){return _i(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getPaymentId();t&&(yield this.amazonPayV2PaymentProcessor.signout(),yield this.paymentIntegrationService.remoteCheckoutSignOut(t.providerId,e))})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}}const Ii=vi(e=>new wi(e,gi()),[{id:"amazonpay"}]);function Ci(e,t,n=!0){var i;return null!==(i=e[t])&&void 0!==i?i:n}const bi="3.128.0",Pi="3.123.2",Oi="3.106.0";class Ei{constructor(e){this.paymentIntegrationService=e,this.braintreeWindow=window}getSDKVersion(){const e=this.paymentIntegrationService.getState().getStoreConfig(),t=(null==e?void 0:e.checkoutSettings.features)||{};return this.getPreloadedSDKVersion()||(Ci(t,"PAYPAL-5809.braintree_hosted_fields_fix_version")?bi:Ci(t,"PAYPAL-5636.update_braintree_sdk_version")?Pi:Oi)}getPreloadedSDKVersion(){const e=this.braintreeWindow.braintree;if(e){const t=B(Object.values(e),e=>!!e.VERSION);return null==t?void 0:t.VERSION}}}class Ai extends Qn{constructor(e){super(e||"Unsupported browser error"),this.name="UnsupportedBrowserError",this.type="unsupported_browser"}}var Ti,ki,Di,Mi,zi,Ni,xi;function Ri(e){return Boolean("object"==typeof e&&null!==e&&("type"in e||"message"in e||"code"in e))}!function(e){e.ESTIMATED="ESTIMATED",e.FINAL="FINAL",e.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(Ti||(Ti={})),function(e){e.Completed="COMPLETED",e.Pending="PENDING",e.Failed="FAILED"}(ki||(ki={})),function(e){e.TRUSTLY="trustly"}(Di||(Di={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="cancelled",e.UNRECOGNIZED="unrecognized"}(Mi||(Mi={})),function(e){e.Customer="CUSTOMER",e.Merchant="MERCHANT",e.Network="NETWORK",e.Internal="INTERNAL",e.Unknown="UNKNOWN"}(zi||(zi={})),function(e){e.KountNotEnabled="DATA_COLLECTOR_KOUNT_NOT_ENABLED"}(Ni||(Ni={})),function(e){e.Visa="visa",e.Mastercard="mastercard",e.AmericanExpress="american-express",e.DinersClub="diners-club",e.Discover="discover",e.Jcb="jcb",e.UnionPay="union-pay",e.Maestro="maestro",e.Elo="elo",e.Mir="mir",e.Hiper="hiper",e.Hipercard="hipercard"}(xi||(xi={}));var Fi,Li,Bi,ji=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ui{constructor(e){this.braintreeScriptLoader=e}initialize(e){this.setClientToken(e)}deinitialize(){return ji(this,void 0,void 0,function*(){yield this.teardownModule(this.dataCollector),this.dataCollector=void 0})}getClient(){return ji(this,void 0,void 0,function*(){if(!this.client){const e=this.getClientTokenOrThrow(),t=yield this.braintreeScriptLoader.loadClient();this.client=yield t.create({authorization:e})}return this.client})}getDataCollectorOrThrow(e){return ji(this,void 0,void 0,function*(){const t={deviceData:void 0,teardown:()=>Promise.resolve()};if(!this.dataCollector)try{const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadDataCollector(),i=Object.assign({client:t,kount:!0},e);this.dataCollector=yield n.create(i)}catch(e){if(Ri(e)&&e.code===Ni.KountNotEnabled)return t;throw e}return this.dataCollector})}getBraintreeGooglePayment(){return ji(this,void 0,void 0,function*(){if(!this.googlePayment){const[e,t]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.loadGooglePayment()]);this.googlePayment=yield t.create({client:e})}return this.googlePayment})}getBraintreeThreeDS(){return ji(this,void 0,void 0,function*(){if(!this.threeDS){const[e,t]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.load3DS()]);this.threeDS=yield t.create({client:e,version:2})}return this.threeDS})}getBraintreeLocalPayment(e){return ji(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment){const[t,n]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.loadLocalPayment()]);this.braintreeLocalPayment=yield new Promise((i,r)=>{n.create({client:t,merchantAccountId:e},(e,t)=>{e&&r(e),i(t)})})}return this.braintreeLocalPayment})}getUsBankAccount(){return ji(this,void 0,void 0,function*(){if(!this.usBankAccount){const e=yield this.getClient(),t=yield this.braintreeScriptLoader.loadUsBankAccount();this.usBankAccount=yield t.create({client:e})}return this.usBankAccount})}getBraintreeVisaCheckout(){return this.visaCheckout||(this.visaCheckout=Promise.all([this.getClient(),this.braintreeScriptLoader.loadVisaCheckout()]).then(([e,t])=>t.create({client:e}))),this.visaCheckout}getVisaCheckoutSdk(e){return ji(this,void 0,void 0,function*(){return this.visaCheckoutSDK||(this.visaCheckoutSDK=yield this.braintreeScriptLoader.loadVisaCheckoutSdk(e)),this.visaCheckoutSDK})}getVenmoCheckoutOrThrow(){return ji(this,void 0,void 0,function*(){if(!this.braintreeVenmo){const e=yield this.getClient(),t=yield this.braintreeScriptLoader.loadVenmoCheckout(),n={client:e,allowDesktop:!0,paymentMethodUsage:"multi_use"},i=yield t.create(n);if(!i.isBrowserSupported())throw new Ai;this.braintreeVenmo=i}return this.braintreeVenmo})}setClientToken(e){this.clientToken=e}getClientTokenOrThrow(){if(!this.clientToken)throw new ri(ei.PaymentNotInitialized);return this.clientToken}teardownModule(e){return e?e.teardown():Promise.resolve()}}!function(e){e.Sandbox="sandbox",e.Production="production"}(Fi||(Fi={})),function(e){e.Client="client",e.DataCollector="dataCollector",e.Fastlane="fastlane",e.GooglePayment="googlePayment",e.HostedFields="hostedFields",e.LocalPayment="localPayment",e.Paypal="paypal",e.PaypalCheckout="paypalCheckout",e.ThreeDSecure="threeDSecure",e.UsBankAccount="usBankAccount",e.Venmo="venmo",e.VisaCheckout="visaCheckout"}(Li||(Li={})),function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification"}(Bi||(Bi={}));const qi={[Oi]:{[Li.Client]:"sha384-26BXDNnJI23JYRyFBj4xe4sVNrUSSiSSu11kxVXNM/vEPONm4LuL00w6ZaTgQewt",[Li.PaypalCheckout]:"sha384-B+vzbZwnQtzWBthpkT4TXKUibO65tyeK7eCxSvpblgprTep2+IAXB2Cxxjrn710O",[Li.Paypal]:"sha384-uyAGL1/3+XJAHnGoNy4eCoXdzJ4f7Ilzp+6w9PNnEjs6DCCz9WMyJjMN1gzc78U+",[Li.LocalPayment]:"sha384-LIvOEMkIVEwVuYBdVOQc1AC5YbGGlwyfUheS0ACK218D2STuVYQlZ4FyEPowAEfT",[Li.DataCollector]:"sha384-1bo9JDz+Kscthc085cCKWur8CLwUoBpoNyxsDi7932mCl0zFq3A5mv+FQLw9GHpV",[Li.UsBankAccount]:"sha384-xmHBVaU+w74V+OebD3AaPONFxHUGMf+QRs8G/JxVPXNNP7MDa2jL0ICWHIe2tTfJ",[Li.GooglePayment]:"sha384-WKDJl8mqoP82qZpMGH6AbZxnvXnSW8ILV4M64CyMLiugGMwu7LyP89wjCkHqsiBe",[Li.ThreeDSecure]:"sha384-VQUlpGHzsGvs5XeiGFip7EXRsvoHWEXDVmgCacfbyieZI9mdBOqq3NSoyo28OCOB",[Li.VisaCheckout]:"sha384-yx7mADfzTN0T43Q6rlH49LIg1EJ0iUZgBp/EczX9LXsUGkySgxrD+nWHQRBkyfoT",[Li.Venmo]:"sha384-QX4rPjoj1ZDhuG0aSyKs56lEKDqTMTcjYxUHY1SzO5VZDsqIE2NTkqot7KNSCyov",[Li.HostedFields]:"sha384-VvYBACfSu0Cr/J32uKmxG7AXcNOJE1AzIIL3kbikyS7YKp5fz5Is+NzNP/lyauNy",[Li.Fastlane]:"sha384-9oGsZMRZwpGtDEDYa/dFt76dECqj1xAni9gIKgc3KfMIiRnR73nEeeUDLiBzxhFa"},[Pi]:{[Li.Client]:"sha384-o+nbQGcwNNxIBeXeu3+XmbSq+Cg8R3EN3N0l5hXCgMMU2RGY0t1z0LroSEIAbfAO",[Li.PaypalCheckout]:"sha384-WrfbWPBS4mH86GAoycPSgiH8hQ8KH7A67C93Hjhunv/xhNk2YpBn3wbFA4Fhg9U/",[Li.Paypal]:"sha384-VF389nvvrRUgDsTXMxTYORDtVegB9IQa3Cxr//DyJnLYnz8/X8VCzEvck2c+Megt",[Li.LocalPayment]:"sha384-tZKx2rEQbfmZpoPSY5VPmJEhaq4X75dLvwHMs3VE9U+C8lPyw+hWTIL1+GPvWCIH",[Li.DataCollector]:"sha384-E6k3wOpP7syCDDwaRDLF06942Y00NkbwJvWi2OQXwwKzGwG5fd3E7RFUvCCecfvO",[Li.UsBankAccount]:"sha384-258FON8LZGG0W9Qaz4Jij83pZHu30YnKjJA7gNulLBh6CclkucgF+tHDQuYFRYfW",[Li.GooglePayment]:"sha384-taJ2p/0+n0VH328POAoBiuEbL3tnHUTE9S42hK1V+Txs3X+QYjZOyKW35JgHRFfO",[Li.ThreeDSecure]:"sha384-+NSZH4Zj3sO5bdWvPKhU5N16QDxeueTVTnUVeleeESkhLSaz4Ob1hh/5myecc9Ym",[Li.VisaCheckout]:"sha384-66DiBjghxk1OmBj8aksN8gbQ+CwoQcx1vPfiXUN08g1iQVM+BwewF0p7toM3i7SS",[Li.Venmo]:"sha384-B5UwY42kE4RoLoWbQ7YpqosUlUad2/DlGWiw0HhoZbSPk30CQAaSA10ohyLDTkDU",[Li.HostedFields]:"sha384-Aw9EesSaUeWxe36PqEHiOyOyOq8M6CIb1gw7/yHNVPRzGtFXXcd2OQ8qXrIlOj2P",[Li.Fastlane]:"sha384-rhBL1hpZ71JqG+2TsT0Dih47mbjx8cjJCpeZjk9tw3df1gFMKfCTmMyZunhr7H4Y"},[bi]:{[Li.Client]:"sha384-0WNxksIpRP+fYZiIdr12g6DBUQfLDzYCQJZtR/C8KkcwSGhPHfcFp3tTaGcMyFTq",[Li.PaypalCheckout]:"sha384-lWM1jk4BOxoDNV6Kop7tVNvQgINlmEVz0c/OwM+HNHK3QC8xqwd54Ovrt2QRDTjh",[Li.Paypal]:"sha384-fXUmVxC2EMZBDXZ7eTHSTL/LFBrHej/MSXT/vTBXvra4lzgLNGvREAp+x0GYObuH",[Li.LocalPayment]:"sha384-pha1xGuGSkmZH5x9aqHvRaO4xLea7rmQ/79PFj9zxNzxuFcOWZg7gOP7FibygOEC",[Li.DataCollector]:"sha384-Q6PI2F9eekWbAxhroybl+aEcvqhdowN/EQlGwBUyJOzPFn9982u9xl6SU6XfGKzc",[Li.UsBankAccount]:"sha384-W3RLQSKJL1tQ3+Y7mP6tmkamtZ8bV4Yw/XxL9Jj5JtXHraD8loMF8hAIG5m2zK7F",[Li.GooglePayment]:"sha384-TITQMsFWA3elDNGP2mWz2oKBo4qjt+TlqzovcaPoeBiAh/wPBi6nae50ADdgU1/i",[Li.ThreeDSecure]:"sha384-YiycYN89ZlL/Evcaq4y1ajW1mhd7JYfZBDuOwHtIn4/Jnm20GL+/XCM+zYAwWD8D",[Li.VisaCheckout]:"sha384-/OdaTv9qrkKzjObtUe6yzfDhHozFW/+uXlrSl736sOZRJpjGQETvpYXqMFFg69xv",[Li.Venmo]:"sha384-dA+ojdW9vbJS4JavcXyOs9d5uZHJg5dNtYupoPSH2zsXIiYDVS5amLb/u8qmQ6oz",[Li.HostedFields]:"sha384-31ZkS58+iaWsW06ftW52zzVZFp43WPd7pNYRiddYynSNg6Oh7WGbSFGorAUH6T1z",[Li.Fastlane]:"sha384-jlbrwNvL3HvLAUCtLSmrnQ2GH1udCUrRS/bVmReAS5fuIVvcW8Pko/Gkg82tlgtr"}};var Vi,Gi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Hi{constructor(e,t,n){this.scriptLoader=e,this.braintreeHostWindow=t,this.braintreeSDKVersionManager=n}loadClient(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.Client,"client.min.js")})}loadFastlane(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.Fastlane,"fastlane.min.js")})}loadPaypalCheckout(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.PaypalCheckout,"paypal-checkout.min.js")})}loadPaypal(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.Paypal,"paypal.min.js")})}loadLocalPayment(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.LocalPayment,"local-payment.min.js")})}loadDataCollector(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.DataCollector,"data-collector.min.js")})}loadUsBankAccount(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.UsBankAccount,"us-bank-account.min.js")})}loadGooglePayment(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.GooglePayment,"google-payment.min.js")})}load3DS(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.ThreeDSecure,"three-d-secure.min.js")})}loadVisaCheckout(){return this.loadBraintreeModuleOrThrow(Li.VisaCheckout,"visa-checkout.min.js")}loadVenmoCheckout(){return this.loadBraintreeModuleOrThrow(Li.Venmo,"venmo.min.js")}loadHostedFields(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.HostedFields,"hosted-fields.min.js")})}loadVisaCheckoutSdk(e){return Gi(this,void 0,void 0,function*(){if(this.braintreeHostWindow.V)return this.braintreeHostWindow.V;const t=e?"sha384-0eu1s1GtqzXlL9DtLgmwzC5WWlEH/ADRM0n38cVQkvtT+W/gey96rcb1LwuUOPDm":"sha384-1f1csvP3ZFxg4dILH1GaY4LHlZ0oX7Rk83rxmLlwbnIi4TM0NYzXoev1VoEiVDS6";return this.scriptLoader.loadScript(`//${e?"sandbox-":""}assets.secure.checkout.visa.com/checkout-widget/resources/js/integration/v1/sdk.js`,{async:!0,attributes:{integrity:t,crossorigin:"anonymous"}}).then(()=>{if(!this.braintreeHostWindow.V)throw new mi;return this.braintreeHostWindow.V})})}loadBraintreeModuleOrThrow(e,t){return Gi(this,void 0,void 0,function*(){let n=this.getBraintreeModule(e);if(n)return n;const i=this.braintreeSDKVersionManager.getSDKVersion(),r=`//js.braintreegateway.com/web/${i}/js/${t}`,o=i in qi?this.getIntegrityValuesByModuleName(e,i):void 0;if(yield this.scriptLoader.loadScript(r,o?{async:!0,attributes:{integrity:o,crossorigin:"anonymous"}}:void 0),n=this.getBraintreeModule(e),!n)throw new mi;return n})}getBraintreeModule(e){var t;return null===(t=this.braintreeHostWindow.braintree)||void 0===t?void 0:t[e]}getIntegrityValuesByModuleName(e,t){const n=qi[t][e];if(!n)throw new Error("Unexpected fileName value");return n}}class Wi extends Qn{constructor(e){super(e||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}!function(e){e.BRAINTREE="braintree",e.BRAINTREE_FASTLANE="braintreeacceleratedcheckout"}(Vi||(Vi={}));var $i,Yi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}($i||($i={}));class Ki{constructor(e,t,n,i,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._braintreeSdk=i,this._applePayScriptLoader=r,this._onAuthorizeCallback=ce,this._onError=ce,this._onClick=ce,this._subTotalLabel=$i.Subtotal,this._shippingLabel=$i.Shipping,this._hasApplePaySession=!1}initialize(e){var t;return Yi(this,void 0,void 0,function*(){const{methodId:n,applepay:i}=e;if(!n||!i)throw new ti(Xn.MissingPaymentMethod);const{container:r,shippingLabel:o,subtotalLabel:a,onError:s=ce,onClick:d=ce,onPaymentAuthorize:c}=i;this._shippingLabel=o||$i.Shipping,this._subTotalLabel=a||$i.Subtotal,this._onAuthorizeCallback=c,this._onError=s,this._onClick=d;let l=this._paymentIntegrationService.getState();yield this._applePayScriptLoader.loadSdk();try{this._paymentMethod=l.getPaymentMethodOrThrow(n)}catch(e){l=yield this._paymentIntegrationService.loadPaymentMethod(n),this._paymentMethod=l.getPaymentMethodOrThrow(n)}yield this._paymentIntegrationService.verifyCheckoutSpamProtection(),this._applePayButton=this._createButton(r),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),(null===(t=this._paymentMethod.initializationData)||void 0===t?void 0:t.gateway)===Vi.BRAINTREE&&this._paymentMethod.clientToken&&this._braintreeSdk.initialize(this._paymentMethod.clientToken)})}deinitialize(){return Promise.resolve()}signIn(){throw new Si('In order to sign in via Apple, the shopper must click on "Apple Pay" button.')}signOut(){throw new Si("Need to do signout via apple.")}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}_createButton(e){const t=document.getElementById(e);if(!t)throw new fi("Unable to create sign-in button without valid container ID.");const n=this._createApplePayButtonElement();return t.appendChild(n),n}_createApplePayButtonElement(){const e=document.createElement("apple-pay-button");return e.setAttribute("buttonstyle","black"),e.setAttribute("type","plain"),e.setAttribute("style","--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;"),e}_handleWalletButtonClick(e){if(e.preventDefault(),this._hasApplePaySession)return;this._onClick();const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getStoreConfigOrThrow(),r=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new ti(Xn.MissingPaymentMethod);const o=this._getBaseRequest(n,r,i,this._paymentMethod),a=this._sessionFactory.create(o);this._handleApplePayEvents(a,this._paymentMethod,i),a.begin(),this._hasApplePaySession=!0}_getBaseRequest(e,t,n,i){var r;const{storeProfile:{storeCountryCode:o,storeName:a}}=n,{currency:{code:s,decimalPlaces:d}}=e,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=i,u=e.lineItems.physicalItems.length>0,h={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:o,currencyCode:s,merchantCapabilities:c,supportedNetworks:l,lineItems:[],total:u?{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"pending"}:{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"final"}};if(u)null===(r=h.requiredShippingContactFields)||void 0===r||r.push("postalAddress");else{const e=[{label:this._subTotalLabel,amount:`${t.subtotal.toFixed(d)}`}];t.taxes.forEach(t=>e.push({label:t.name,amount:`${t.amount.toFixed(d)}`})),h.lineItems=e}return h}_handleApplePayEvents(e,t,n){e.onvalidatemerchant=n=>Yi(this,void 0,void 0,function*(){try{const{body:i}=yield this._onValidateMerchant(t,n);e.completeMerchantValidation(i)}catch(e){this._onError(e)}}),e.onshippingcontactselected=t=>Yi(this,void 0,void 0,function*(){return this._handleShippingContactSelected(e,n,t)}),e.onshippingmethodselected=t=>Yi(this,void 0,void 0,function*(){return this._handleShippingMethodSelected(e,n,t)}),e.oncancel=()=>Yi(this,void 0,void 0,function*(){this._hasApplePaySession=!1;try{const e=`/remote-checkout/${t.id}/signout`;return yield this._requestSender.get(e),yield this._paymentIntegrationService.loadCheckout()}catch(e){return this._onError(new Wi)}}),e.onpaymentauthorized=n=>Yi(this,void 0,void 0,function*(){return this._onPaymentAuthorized(n,e,t)})}_handleShippingContactSelected(e,t,n){var i;return Yi(this,void 0,void 0,function*(){const r=this._transformContactToAddress(n.shippingContact);try{yield this._paymentIntegrationService.updateShippingAddress(r)}catch(t){return e.abort(),this._hasApplePaySession=!1,this._onError(t)}const{storeProfile:{storeName:o}}=t;let a=this._paymentIntegrationService.getState();const{currency:{decimalPlaces:s}}=a.getCartOrThrow();let d=a.getCheckoutOrThrow();const c=null===(i=d.consignments[0].selectedShippingOption)||void 0===i?void 0:i.id,l=d.consignments[0].availableShippingOptions,u=null==l?void 0:l.find(({id:e})=>e===c),h=null==l?void 0:l.filter(e=>e.id!==c),p=u?[{label:u.description,amount:`${u.cost.toFixed(s)}`,detail:u.additionalDescription,identifier:u.id}]:[];if(h&&[...h.filter(e=>e.isRecommended),...h.filter(e=>!e.isRecommended)].forEach(e=>p.push({label:e.description,amount:`${e.cost.toFixed(s)}`,detail:e.additionalDescription,identifier:e.id})),!(l instanceof Array))throw new Error("Shipping options not available.");if(0===l.length)return void e.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:o,amount:`${d.grandTotal.toFixed(s)}`},[]);const m=l.find(e=>e.isRecommended),y=m?m.id:l[0].id,g=u?u.id:y;try{yield this._updateShippingOption(g)}catch(e){return this._onError(e)}a=this._paymentIntegrationService.getState(),d=a.getCheckoutOrThrow(),e.completeShippingContactSelection({newShippingMethods:p,newTotal:{type:"final",label:o,amount:`${d.grandTotal.toFixed(s)}`},newLineItems:this._getUpdatedLineItems(d,s)})})}_handleShippingMethodSelected(e,t,n){return Yi(this,void 0,void 0,function*(){const{storeProfile:{storeName:i}}=t,{shippingMethod:{identifier:r}}=n;try{yield this._updateShippingOption(r)}catch(t){return e.abort(),this._hasApplePaySession=!1,this._onError(t)}const o=this._paymentIntegrationService.getState(),{currency:{decimalPlaces:a}}=o.getCartOrThrow(),s=o.getCheckoutOrThrow();e.completeShippingMethodSelection({newTotal:{type:"final",label:i,amount:`${s.grandTotal.toFixed(a)}`},newLineItems:this._getUpdatedLineItems(s,a)})})}_getUpdatedLineItems(e,t){const n=[{label:this._subTotalLabel,amount:`${e.subtotal.toFixed(t)}`}];return e.taxes.forEach(e=>n.push({label:e.name,amount:`${e.amount.toFixed(t)}`})),n.push({label:this._shippingLabel,amount:`${e.shippingCostTotal.toFixed(t)}`}),n}_updateShippingOption(e){return Yi(this,void 0,void 0,function*(){return this._paymentIntegrationService.selectShippingOption(e)})}_onValidateMerchant(e,t){return Yi(this,void 0,void 0,function*(){const n=[`validationUrl=${t.validationURL}`,`merchantIdentifier=${e.initializationData.merchantId}`,`displayName=${e.initializationData.storeName}`,`domainName=${window.location.hostname}`].join("&");return this._requestSender.post(`${e.initializationData.paymentsUrl}/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})})}_onPaymentAuthorized(e,t,n){var i;return Yi(this,void 0,void 0,function*(){const{token:r,billingContact:o,shippingContact:a}=e.payment,s=this._paymentIntegrationService.getState().getCartOrThrow().lineItems.physicalItems.length>0;let d;(null===(i=n.initializationData)||void 0===i?void 0:i.gateway)===Vi.BRAINTREE&&(d=yield this._getBraintreeDeviceData());const c={methodId:n.id,paymentData:{deviceSessionId:d,formattedPayload:{apple_pay_token:{payment_data:r.paymentData,payment_method:r.paymentMethod,transaction_id:r.transactionIdentifier}}}},l=this._transformContactToAddress(o),u=this._transformContactToAddress(a),h=null==a?void 0:a.emailAddress,p=(null==a?void 0:a.phoneNumber)||"";try{return yield this._paymentIntegrationService.updateBillingAddress(Object.assign(Object.assign({},l),{email:h,phone:p})),s&&(yield this._paymentIntegrationService.updateShippingAddress(u)),yield this._paymentIntegrationService.submitOrder({useStoreCredit:!1}),yield this._paymentIntegrationService.submitPayment(c),t.completePayment(ApplePaySession.STATUS_SUCCESS),this._onAuthorizeCallback()}catch(e){return t.completePayment(ApplePaySession.STATUS_FAILURE),this._onError(e)}})}_transformContactToAddress(e){return{firstName:(null==e?void 0:e.givenName)||"",lastName:(null==e?void 0:e.familyName)||"",city:(null==e?void 0:e.locality)||"",company:"",address1:(null==e?void 0:e.addressLines)&&e.addressLines[0]||"",address2:(null==e?void 0:e.addressLines)&&e.addressLines[1]||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||"",phone:(null==e?void 0:e.phoneNumber)||"",stateOrProvince:(null==e?void 0:e.administrativeArea)||"",stateOrProvinceCode:(null==e?void 0:e.administrativeArea)||"",customFields:[]}}_getBraintreeDeviceData(){return Yi(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}function Ji(e){if(!function(e){return"ApplePaySession"in e}(e))throw new Error("Apple pay is not supported")}class Zi{create(e){return Ji(window),new ApplePaySession(1,e)}}class Qi{constructor(e){this.scriptLoader=e,this.sdkVersion="1.latest"}loadSdk(){return e=this,t=void 0,i=function*(){(function(e){return"ApplePaySDK"in e})(window)||(yield this.scriptLoader.loadScript(`https://applepay.cdn-apple.com/jsapi/${this.sdkVersion}/apple-pay-sdk.js`),Ji(window))},new((n=void 0)||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())});var e,t,n,i}}const Xi=vi(e=>{const{getHost:t}=e.getState(),i=new Ei(e);return new Ki(n({host:t()}),e,new Zi,new Ui(new Hi(a(),window,i)),new Qi(new r))},[{id:"applepay"}]);class er extends Qn{constructor(e){super(e||"An unexpected error has occurred during buy now cart creation process. Please try again later."),this.name="BuyNowCartCreationError",this.type="buy_now_cart_creation_error"}}const tr={body:{},headers:{},status:0};class nr extends Qn{constructor(e,{message:t,errors:n}={}){const{body:i,headers:r,status:o}=e||tr;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=i,this.headers=r,this.status=o,this.errors=n||[]}}var ir,rr,or,ar,sr,dr,cr;!function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(ir||(ir={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(rr||(rr={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(or||(or={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(ar||(ar={})),function(e){e.pill="pill",e.rect="rect"}(sr||(sr={})),function(e){e.OXXO="oxxo"}(dr||(dr={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(cr||(cr={}));var lr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ur{constructor(e,t,n,i){this.formPoster=e,this.paymentIntegrationService=t,this.bigCommercePaymentsRequestSender=n,this.bigCommercePaymentsScriptLoader=i}loadPayPalSdk(e,t,n,i){return lr(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e);return this.paypalSdk=yield this.bigCommercePaymentsScriptLoader.getPayPalSDK(a,o,n,i),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new mi;return this.paypalSdk}createBuyNowCartOrThrow(e){return lr(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}})}createOrder(e,t){return lr(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:n},t));return i})}createOrderCardFields(e,t){return lr(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i,setupToken:r}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:n},t));return Object.assign({orderId:i},r?{setupToken:r}:{})})}updateOrder(){return lr(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getConsignmentsOrThrow()[0];try{yield this.bigCommercePaymentsRequestSender.updateOrder({availableShippingOptions:n.availableShippingOptions,cartId:t.id,selectedShippingOption:n.selectedShippingOption})}catch(e){throw new nr}})}getOrderStatus(e,t){return lr(this,void 0,void 0,function*(){try{const{status:n}=yield this.bigCommercePaymentsRequestSender.getOrderStatus(e,t);return n}catch(e){throw new nr}})}tokenizePayment(e,t){const n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new ti(Xn.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===xt.BuyNow&&{cart_id:n.id}))}submitPayment(e,t,n){return lr(this,void 0,void 0,function*(){const i={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}};yield this.paymentIntegrationService.submitPayment(Object.assign({methodId:e,paymentData:i},n?{gatewayId:n}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],i=n.find(e=>e.isRecommended),r=(e?n.find(t=>t.id===e):n.find(e=>{var n;return e.id===(null===(n=t.selectedShippingOption)||void 0===n?void 0:n.id)}))||i||n[0];if(!r)throw new Error("Your order can't be shipped to this address");return r}getAddress(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:(null==e?void 0:e.phone)||"",company:"",address1:(null==e?void 0:e.address1)||"",address2:(null==e?void 0:e.address2)||"",city:(null==e?void 0:e.city)||"",countryCode:(null==e?void 0:e.countryCode)||"",postalCode:(null==e?void 0:e.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==e?void 0:e.stateOrProvinceCode)||"",customFields:[]}}getBillingAddressFromOrderDetails({payer:e}){var t,n;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,address2:e.address.address_line_2,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1,phone:null===(n=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===n?void 0:n.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:n}=e,{address:i,name:{full_name:r}}=n[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:i.address_line_1,address2:i.address_line_2,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})}getValidButtonStyle(e){const{color:t,height:n,label:i,shape:r}=e||{},o={color:t&&ar[t]?t:void 0,height:this.getValidHeight(n),label:i&&or[i]?i:void 0,shape:r&&sr[r]?r:void 0};return ue(o,J)}getValidHeight(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40}removeElement(e){const t=e&&document.getElementById(e);t&&(t.style.display="none")}}const hr="This API endpoint is for internal use only and may change in the future";var pr;!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(pr||(pr={}));const mr=pr,yr={"X-Checkout-SDK-Version":"1.909.5"};var gr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vr{constructor(e){this.requestSender=e}createOrder(e,t){return gr(this,void 0,void 0,function*(){const n=`/api/storefront/payment/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.post(n,{headers:r,body:i})).body})}updateOrder(e){return gr(this,void 0,void 0,function*(){const t=e,n=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.put("/api/storefront/initialization/bigcommerce_payments",{headers:n,body:t})).body})}getOrderStatus(e="bigcommerce_payments",t){return gr(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body})}}var fr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Sr{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,n,i){return fr(this,void 0,void 0,function*(){const r=this.getPayPalSdkScriptConfigOrThrow(e,t,n);return this.loadPayPalSDK(r,i)})}loadPayPalSDK(e,t=!1){return fr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsPayPalSDK||t){const t=this.transformConfig(e.options),n=this.transformConfig(e.attributes),i=`https://www.paypal.com/sdk/js?${new URLSearchParams(t).toString()}`;yield this.scriptLoader.loadScript(i,{async:!0,attributes:n})}if(!this.window.bigCommercePaymentsPayPalSDK)throw new mi;return this.window.bigCommercePaymentsPayPalSDK})}getPayPalSdkScriptConfigOrThrow(e,t,n=!0){const{id:i,clientToken:r,initializationData:o}=e;if(!(null==o?void 0:o.clientId))throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:c,attributionId:l,isVenmoEnabled:u,isHostedCheckoutEnabled:h,isPayPalCreditAvailable:p,isDeveloperModeApplicable:m,availableAlternativePaymentMethods:y=[],enabledAlternativePaymentMethods:g=[],isGooglePayEnabled:v}=o,f=h||n,S="bigcommerce_payments_creditcards"===i,_=S?["card"]:[],w=S?[]:["card"],I=p?["credit","paylater"]:[],C=p?[]:["credit","paylater"],b=u?["venmo"]:[],P=u?[]:["venmo"],O=y.filter(e=>!g.includes(e)),E=v?["googlepay"]:[],A=n?["card-fields"]:[],T=this.filterFundingOptions([...w,...C,...P,...O]),k=this.filterFundingOptions([..._,...I,...b,...g]);return{options:Object.assign({"client-id":s,"merchant-id":d,"enable-funding":k.length>0?k:void 0,"disable-funding":T.length>0?T:void 0,commit:f,components:["buttons","hosted-fields","payment-fields","legal",...E,...A],currency:t,intent:a},m&&{"buyer-country":c}),attributes:{"data-partner-attribution-id":l,"data-client-token":r,"data-namespace":"bigCommercePaymentsPayPalSDK"}}}filterFundingOptions(e){const t=["klarna","afterpay"];return e?e.filter(e=>!t.includes(e)):[]}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}const _r=e=>{const{getHost:t}=e.getState();return new ur(Ee(),e,new vr(n({host:t()})),new Sr(a()))},wr=40;var Ir=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Cr{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=ce}initialize(e){return Ir(this,void 0,void 0,function*(){const{bigcommerce_payments:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.bigcommerce_payments.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.bigcommerce_payments.onClick" argument is not a function.');this.onError=t.onError||ce,this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Ir(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return Ir(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){var n,i;const{container:r,onClick:o,onComplete:a}=t,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:c,paymentButtonStyles:l,isAppSwitchEnabled:u=!1}=d.initializationData||{},{checkoutTopButtonStyles:h}=l||{},p=Object.assign(Object.assign(Object.assign({},u&&{appSwitchWhenAvailable:!0}),{createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)}),o&&{onClick:()=>o()}),m=Object.assign(Object.assign({},!u&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(t,n)=>this.onHostedCheckoutApprove(t,n,e,a)}),y=Object.assign(Object.assign({fundingSource:s.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},h),{height:wr}))},p),c&&m),g=s.Buttons(y);g.isEligible()?(null===(n=g.hasReturned)||void 0===n?void 0:n.call(g))&&u?null===(i=g.resume)||void 0===i||i.call(g):g.render(`#${r}`):this.bigCommercePaymentsIntegrationService.removeElement(r)}onHostedCheckoutApprove(e,t,n,i){return Ir(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Ir(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}onShippingOptionsChange(e){return Ir(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const br=vi(e=>new Cr(e,_r(e)),[{id:"bigcommerce_payments"}]);var Pr,Or,Er,Ar,Tr,kr,Dr,Mr,zr,Nr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class xr{constructor(e){this.scriptLoader=e,this.window=window}getPayPalFastlaneSdk(e,t,n){return Nr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsFastlaneSdk){const i=this.getPayPalFastlaneSdkConfiguration(e,t,n);if(yield this.loadPayPalSdk(i),!this.window.bigCommercePaymentsFastlaneSdk)throw new mi}return this.window.bigCommercePaymentsFastlaneSdk})}getPayPalGooglePaySdk(e,t,n,i){return Nr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsGooglePay||i){const i=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n);yield this.loadPayPalSdk(i)}if(!this.window.bigCommercePaymentsGooglePay)throw new mi;return this.window.bigCommercePaymentsGooglePay})}getPayPalApmsSdk(e,t){return Nr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsApms){const n=this.getPayPalApmSdkConfiguration(e,t);if(yield this.loadPayPalSdk(n),!this.window.bigCommercePaymentsApms)throw new mi}return this.window.bigCommercePaymentsApms})}getPayPalMessages(e,t){return Nr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsMessages){const n=this.getPayPalSdkMessagesConfiguration(e,t);yield this.loadPayPalSdk(n)}if(!this.window.bigCommercePaymentsMessages)throw new mi;return this.window.bigCommercePaymentsMessages})}loadPayPalSdk({options:e,attributes:t}){return Nr(this,void 0,void 0,function*(){const n=this.transformConfig(e),i=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(n).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:i})})}getPayPalFastlaneSdkConfiguration(e,t,n){const{clientToken:i,initializationData:r}=e;if(!r||!r.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,attributionId:d}=r;return{options:{"client-id":a,"merchant-id":s,commit:!0,components:["fastlane","three-domain-secure"],currency:t,intent:o},attributes:{"data-client-metadata-id":n.replace(/-/g,""),"data-namespace":"bigCommercePaymentsFastlaneSdk","data-partner-attribution-id":d,"data-sdk-client-token":i}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n=!0){const{clientToken:i,initializationData:r}=e;if(!r||!r.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,buyerCountry:d,attributionId:c,isHostedCheckoutEnabled:l,isDeveloperModeApplicable:u}=r,h=l||n;return{options:Object.assign({"client-id":a,"merchant-id":s,commit:h,components:["googlepay"],currency:t,intent:o},u&&{"buyer-country":d}),attributes:{"data-partner-attribution-id":c,"data-client-token":i,"data-namespace":"bigCommercePaymentsGooglePay"}}}getPayPalApmSdkConfiguration(e,t){const{initializationData:n}=e;if(!n||!n.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:i,clientId:r,merchantId:o,buyerCountry:a,attributionId:s,isDeveloperModeApplicable:d,availableAlternativePaymentMethods:c=[],enabledAlternativePaymentMethods:l=[]}=n,u=this.filterFundingOptions(l),h=this.filterFundingOptions(c.filter(e=>!l.includes(e)));return{options:Object.assign({"client-id":r,"merchant-id":o,"enable-funding":u.length>0?u:void 0,"disable-funding":h.length>0?h:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:i},d&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":s,"data-namespace":"bigCommercePaymentsApms"}}}getPayPalSdkMessagesConfiguration(e,t){const{initializationData:n}=e;if(!n||!n.clientId)throw new ti(Xn.MissingPaymentMethod);const{clientId:i,merchantId:r,attributionId:o,isDeveloperModeApplicable:a,buyerCountry:s}=n;return{options:Object.assign({"client-id":i,"merchant-id":r,components:["messages"],currency:t},a&&{"buyer-country":s}),attributes:{"data-namespace":"bigCommercePaymentsMessages","data-partner-attribution-id":o}}}filterFundingOptions(e){const t=["klarna","afterpay"];return e?e.filter(e=>!t.includes(e)):[]}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}function Rr(){return new xr(o())}!function(e){e.CVV="cvv",e.PAN="pan"}(Pr||(Pr={}));class Fr{static get(e){const t=`${encodeURIComponent(`${e}`)}=`,n=document.cookie;let i=null;const r=n.indexOf(t);if(r>-1){let e=n.indexOf(";",r);-1===e&&(e=n.length),i=decodeURIComponent(n.substring(r+t.length,e))}return i}static set(e,t,n={secure:!0}){let i=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;const{expires:r,path:o,domain:a,secure:s}=n;if(r)i+=`; expires=${r.toUTCString()}`;else{const e=new Date,t=60;e.setTime(e.getTime()+60*t*1e3),i+=`; expires=${e.toUTCString()}`}o&&(i+=`; path=${o}`),a&&(i+=`; domain=${a}`),s&&(i+="; secure"),document.cookie=i}static remove(e,t){Fr.set(e,"",Object.assign({expires:new Date(0)},t))}}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Or||(Or={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(Er||(Er={})),function(e){e.Always="SCA_ALWAYS"}(Ar||(Ar={})),function(e){e.Succeeded="succeeded",e.Cancelled="cancelled",e.Errored="errored"}(Tr||(Tr={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(kr||(kr={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(Dr||(Dr={})),function(e){e.pill="pill",e.rect="rect"}(Mr||(Mr={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="canceled",e.UNRECOGNIZED="unrecognized"}(zr||(zr={}));var Lr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Br{constructor(){this.window=window}initializePayPalFastlane(e,t,n){return Lr(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("fastlaneEnv","sandbox"),window.localStorage.setItem("axoEnv","sandbox")),!this.window.bigCommercePaymentsFastlane){const t={root:{backgroundColorPrimary:"transparent"}};this.window.bigCommercePaymentsFastlane=yield e.Fastlane({styles:n||t})}return this.window.bigCommercePaymentsFastlane})}getPayPalFastlaneOrThrow(){if(!this.window.bigCommercePaymentsFastlane)throw new mi;return this.window.bigCommercePaymentsFastlane}lookupCustomerOrThrow(e){return Lr(this,void 0,void 0,function*(){return this.getPayPalFastlaneOrThrow().identity.lookupCustomerByEmail(e)})}triggerAuthenticationFlowOrThrow(e){return Lr(this,void 0,void 0,function*(){return e?this.getPayPalFastlaneOrThrow().identity.triggerAuthenticationFlow(e):{}})}updateStorageSessionId(e){const t=new Date;t.setDate(t.getDate()+14);const n={expires:t,secure:!0};Fr.set("bc-fastlane-sessionId",e,n)}removeStorageSessionId(){Fr.remove("bc-fastlane-sessionId")}getStorageSessionId(){return Fr.get("bc-fastlane-sessionId")||""}mapPayPalFastlaneProfileToBcCustomerData(e,t){var n,i,r;const{authenticationState:o,profileData:a}=t,s=null===(r=null===(i=null===(n=null==a?void 0:a.card)||void 0===n?void 0:n.paymentSource)||void 0===i?void 0:i.card)||void 0===r?void 0:r.billingAddress,d=null==a?void 0:a.shippingAddress,c=null==a?void 0:a.name,l=null==a?void 0:a.card,u=d?this.mapPayPalToBcAddress(d.address,d.name,d.phoneNumber):void 0,h=s&&c?this.mapPayPalToBcAddress(s,c,null==d?void 0:d.phoneNumber):void 0,p=l?this.mapPayPalToBcInstrument(e,l):[],m=this.filterAddresses([u,h]);return{authenticationState:o||zr.UNRECOGNIZED,addresses:m,billingAddress:h,shippingAddress:u,instruments:p}}mapPayPalToBcInstrument(e,t){const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a}=i.card,[s,d]=o.split("-");return[{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:Pr.PAN,type:"card"}]}mapBcToPayPalAddress(e){return{company:(null==e?void 0:e.company)||"",addressLine1:(null==e?void 0:e.address1)||"",addressLine2:(null==e?void 0:e.address2)||"",adminArea1:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",adminArea2:(null==e?void 0:e.city)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||""}}mapPayPalToBcAddress(e,t,n,i){const[r,o]=t.fullName.split(" "),a=(null==n?void 0:n.nationalNumber)||"",s=(null==n?void 0:n.countryCode)||"";return{id:Date.now(),type:"paypal-address",firstName:t.firstName||r||"",lastName:t.lastName||o||"",company:e.company||"",address1:e.addressLine1,address2:e.addressLine2||"",city:e.adminArea2,stateOrProvince:e.adminArea1,stateOrProvinceCode:e.adminArea1,country:e.countryCode||"",countryCode:e.countryCode||"",postalCode:e.postalCode,phone:s+a,customFields:i||[]}}filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this.isEqualAddresses(e,t))?e:[...e,t]:e,[])}isEqualAddresses(e,t){return Y(this.normalizeAddress(e),this.normalizeAddress(t))}normalizeAddress(e){return le(e,["id","phone"])}}function jr(){return new Br}function Ur(e){return"string"!=typeof e}function qr(e,t){if(t||e)return function(e){var t,n;const i={},r=ue(e.root,Ur),o=ue(e.input,Ur),a=ue(e.toggle,Ur),s=ue(null===(t=e.text)||void 0===t?void 0:t.body,Ur),d=ue(null===(n=e.text)||void 0===n?void 0:n.caption,Ur),c=e.branding;return Object.keys(r).length&&(i.root=r),Object.keys(o).length&&(i.input=o),Object.keys(a).length&&(i.toggle=a),Object.keys(s).length&&(i.text={},i.text.body=s),Object.keys(d).length&&(i.text=Object.assign({},i.text),i.text.caption=d),c&&(i.branding=c),i}(function(e,t){var n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,_,w,I,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(c=null==t?void 0:t.input)||void 0===c?void 0:c.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.focusBorderColor),backgroundColor:(null==e?void 0:e.fastlaneInputSettingsBackgroundColor)||(null===(u=null==t?void 0:t.input)||void 0===u?void 0:u.backgroundColor),borderWidth:(null==e?void 0:e.fastlaneInputSettingsBorderWidth)||(null===(h=null==t?void 0:t.input)||void 0===h?void 0:h.borderWidth),textColorBase:(null==e?void 0:e.fastlaneInputSettingsTextColorBase)||(null===(p=null==t?void 0:t.input)||void 0===p?void 0:p.textColorBase)},toggle:{colorPrimary:(null==e?void 0:e.fastlaneToggleSettingsColorPrimary)||(null===(m=null==t?void 0:t.toggle)||void 0===m?void 0:m.colorPrimary),colorSecondary:(null==e?void 0:e.fastlaneToggleSettingsColorSecondary)||(null===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(S=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===S?void 0:S.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(w=null===(_=null==t?void 0:t.text)||void 0===_?void 0:_.caption)||void 0===w?void 0:w.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(I=null==t?void 0:t.text)||void 0===I?void 0:I.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var Vr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Gr{constructor(e,t,n){this.paymentIntegrationService=e,this.bigCommercePaymentsSdk=t,this.bigCommercePaymentsFastlaneUtils=n}initialize(e){var t;return Vr(this,void 0,void 0,function*(){const{methodId:n,bigcommerce_payments_fastlane:i}=e;if(!n)throw new fi('Unable to proceed because "methodId" argument is not provided.');try{yield this.paymentIntegrationService.loadPaymentMethod(n);const e=this.paymentIntegrationService.getState(),r=e.getCartOrThrow(),o=e.getPaymentMethodOrThrow(n),a=!!(null===(t=o.initializationData)||void 0===t?void 0:t.isDeveloperModeApplicable),s=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(o,r.currency.code,r.id);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(s,a,this.getFastlaneStyles(n,i))}catch(e){}return Promise.resolve()})}deinitialize(){return Vr(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return Vr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:void 0,addresses:void 0,instruments:void 0}),this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId()})}signOut(e){return Vr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return Vr(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:n,methodId:i}=e||{};if(!i)throw new fi('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof n)throw new fi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(this.paymentIntegrationService.getState().getCustomerOrThrow().isGuest){t&&"function"==typeof t&&t();try{yield this.runPayPalAuthenticationFlowOrThrow(i)}catch(e){}}n()})}runPayPalAuthenticationFlowOrThrow(e){return Vr(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow().id,i=t.getCustomer(),r=t.getBillingAddress(),o=(null==i?void 0:i.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(a),d=s.authenticationState===zr.CANCELED;yield this.updateCustomerDataState(e,s),d?this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId():this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(n)})}updateCustomerDataState(e,t){var n;return Vr(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow(),{authenticationState:r,addresses:o,billingAddress:a,shippingAddress:s,instruments:d}=this.bigCommercePaymentsFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,t);if(yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:r,addresses:o,instruments:d}),a&&(yield this.paymentIntegrationService.updateBillingAddress(a)),s&&i.lineItems.physicalItems.length>0){const t=yield this.paymentIntegrationService.updateShippingAddress(s),i=t.getPaymentMethodOrThrow(e),{isFastlaneShippingOptionAutoSelectEnabled:r}=i.initializationData||{},o=t.getConsignments()||[],a=(null===(n=o[0])||void 0===n?void 0:n.availableShippingOptions)||[],d=a[0],c=a.find(e=>e.isRecommended);if((c||d)&&r){const e=(null==c?void 0:c.id)||d.id;yield this.paymentIntegrationService.selectShippingOption(e)}}})}getFastlaneStyles(e,t){const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{fastlaneStyles:i,isFastlaneStylingEnabled:r}=n.initializationData||{};return qr(r?i:{},null==t?void 0:t.styles)}}const Hr=vi(e=>new Gr(e,Rr(),jr()),[{id:"bigcommerce_payments_fastlane"},{id:"bigcommerce_payments_creditcards"}]);var Wr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class $r{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=ce}initialize(e){return Wr(this,void 0,void 0,function*(){const{bigcommerce_payments_paylater:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater.onClick" argument is not a function.');this.onError=t.onError||ce,this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC BigCommercePayments PayLater]: button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Wr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Wr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){const{container:n,onComplete:i,onClick:r}=t,o=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:s,paymentButtonStyles:d}=a.initializationData||{},{checkoutTopButtonStyles:c}=d||{},l=Object.assign({createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},r&&{onClick:()=>r()}),u={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(t,n)=>this.onHostedCheckoutApprove(t,n,e,i)},h=[o.FUNDING.PAYLATER,o.FUNDING.CREDIT];let p=!1;h.forEach(e=>{if(!p){const t=Object.assign(Object.assign({fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},c),{height:wr}))},l),s&&u),i=o.Buttons(t);i.isEligible()&&(i.render(`#${n}`),p=!0)}}),p||this.bigCommercePaymentsIntegrationService.removeElement(n)}onHostedCheckoutApprove(e,t,n,i){return Wr(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Wr(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}onShippingOptionsChange(e){return Wr(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const Yr=vi(e=>new $r(e,_r(e)),[{id:"bigcommerce_payments_paylater"}]);var Kr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Jr{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return Kr(this,void 0,void 0,function*(){const{bigcommerce_payments_venmo:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC Payments Venmo]: Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Kr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Kr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){const{container:n,onClick:i}=t,r=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:a}=o.initializationData||{},{checkoutTopButtonStyles:s}=a||{},d=Object.assign({fundingSource:r.FUNDING.VENMO,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},s),{height:wr})),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},i&&{onClick:()=>i()}),c=r.Buttons(d);c.isEligible()?c.render(`#${n}`):this.bigCommercePaymentsIntegrationService.removeElement(n)}}const Zr=vi(e=>new Jr(e,_r(e)),[{id:"bigcommerce_payments_venmo"}]);class Qr extends Qn{constructor(e){super(e||"Unable to proceed because the client library of a payment method has thrown an unexpected error."),this.name="PaymentMethodFailedError",this.type="payment_method_client_invalid"}}class Xr extends nr{constructor(e){super(e,{message:"There is a problem processing your payment. Please try again later."}),this.name="PaymentMethodInvalidError",this.type="payment_method_invalid"}}var eo,to,no,io=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ro{constructor(e,t){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=window}initialize(e){var t;return io(this,void 0,void 0,function*(){const{methodId:n,bolt:i}=e,{onInit:r}=i||{};if(!n)throw new fi('Unable to proceed because "methodId" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n);if(!(null===(t=o.initializationData)||void 0===t?void 0:t.publishableKey))throw new ti(Xn.MissingPaymentMethod);const{developerConfig:a,publishableKey:s}=o.initializationData;if(yield this.boltScriptLoader.loadBoltClient(s,o.config.testMode,a),r&&"function"==typeof r){const e=this.getCustomerEmail();r(yield this.hasBoltAccount(e),e)}})}deinitialize(){return Promise.resolve()}signIn(e,t){return io(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return io(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){return io(this,void 0,void 0,function*(){const{continueWithCheckoutCallback:t=I,checkoutPaymentMethodExecuted:n,methodId:i}=e||{},r=this.getCustomerEmail();if(!i)throw new fi('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof t)throw new fi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(r)return this.openBoltCheckoutModalOrThrow(r,i,t,n);t()})}openBoltCheckoutModalOrThrow(e,t,n,i){var r;return io(this,void 0,void 0,function*(){const o=this.getBoltClientOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethod(t);try{if(null===(r=null==a?void 0:a.initializationData)||void 0===r?void 0:r.embeddedOneClickEnabled){const t=yield this.hasBoltAccount(e);if(t){const t={close:()=>{n()}};yield o.openCheckout(e,t)}else n();"function"==typeof i&&i({hasBoltAccount:t})}else n()}catch(e){if(function(e){return"string"==typeof e.message&&"string"==typeof e.type&&("string"==typeof e.subtype||!e.subtype)&&e instanceof Error}(e)&&"MissingDataError"!==e.name&&"NotInitializedError"!==e.name)throw new Qr(e.message);throw e}})}getBoltClientOrThrow(){const e=this.boltHostWindow.BoltCheckout;if(!e)throw new ri(ei.PaymentNotInitialized);return e}hasBoltAccount(e){return io(this,void 0,void 0,function*(){const t=this.getBoltClientOrThrow();try{return yield t.hasBoltAccount(e)}catch(e){throw new Xr}})}getCustomerEmail(){const e=this.paymentIntegrationService.getState(),t=e.getCustomer(),n=e.getBillingAddress();return(null==t?void 0:t.email)||(null==n?void 0:n.email)||""}}!function(e){e.SandboxMode="bolt_sandbox",e.StagingMode="bolt_staging",e.DevelopmentMode="bolt_development"}(eo||(eo={})),function(e){e.Small="small",e.Medium="medium",e.Large="large"}(to||(to={})),function(e){e.Pill="pill",e.Rect="rect"}(no||(no={}));var oo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ao{constructor(e,t=window){this.scriptLoader=e,this.boltHostWindow=t}loadBoltClient(e,t,n,i,r){return oo(this,void 0,void 0,function*(){if(this.boltHostWindow.BoltCheckout)return this.boltHostWindow.BoltCheckout;if(!e)throw new fi('Unable to initialize payment because "publishableKey" argument is not provided.');if(yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,n)}/connect-bigcommerce.js`,this.getScriptOptions("bolt-connect",e,i,r)),yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,n)}/track.js`,this.getScriptOptions("bolt-track",e)),!this.boltHostWindow.BoltCheckout)throw new mi;return this.boltHostWindow.BoltCheckout})}loadBoltEmbedded(e,t,n){return oo(this,void 0,void 0,function*(){if(yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,n)}/embed.js`,{async:!0,attributes:{id:"bolt-embedded"}}),!this.boltHostWindow.Bolt)throw new mi;return this.boltHostWindow.Bolt(e)})}getDomainURL(e,t){if(!e)return"connect.bolt.com";if(t)switch(t.developerMode){case eo.StagingMode:return"connect-staging.bolt.com";case eo.DevelopmentMode:return`connect.${t.developerDomain}`}return"connect-sandbox.bolt.com"}getScriptOptions(e,t,n,i){return{async:!0,attributes:Object.assign(Object.assign({id:e,"data-publishable-key":t},n&&{"data-shopping-cart-id":n}),i&&{"data-storefront-api-token":i})}}}const so=vi(e=>new ro(e,new ao(a())),[{id:"bolt"}]);class co extends fi{constructor(e){let t="Unable to submit payment for the order because the payload is invalid.";e&&(t=`${t} Make sure the following fields are provided correctly: ${e.join(", ")}.`),super(t),this.name="PaymentArgumentInvalidError"}}class lo extends Qn{constructor(e,t){super(t||"Unable to proceed because the payment form contains invalid data."),this.details=e,this.name="PaymentInvalidFormError",this.type="payment_invalid_form"}}let uo=null;const ho=["buttons","messages"];var po,mo,yo,go,vo,fo;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(po||(po={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(mo||(mo={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black",e.WHITE="white"}(yo||(yo={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(go||(go={})),function(e){e.PILL="pill",e.RECT="rect"}(vo||(vo={})),function(e){e.CART="cart",e.HOME="homepage",e.PAYMENT="payment",e.PRODUCT="product"}(fo||(fo={}));var So=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class _o{constructor(e,t,n){this.braintreeScriptLoader=e,this.braintreeHostWindow=t,this.overlay=n,this.dataCollectors={}}initialize(e,t){this.clientToken=e,this.threeDSecureOptions=t}getBraintreeFastlane(e,t,n){return So(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("axoEnv","sandbox"),window.localStorage.setItem("fastlaneEnv","sandbox")),!this.braintreeHostWindow.braintreeFastlane){const t=this.getClientTokenOrThrow(),i=yield this.getClient(),r=yield this.getSessionId(e),o=yield this.braintreeScriptLoader.loadFastlane(),a={root:{backgroundColorPrimary:"transparent"}};this.braintreeHostWindow.braintreeFastlane=yield o.create({authorization:t,client:i,deviceData:r,styles:n||a})}return this.braintreeHostWindow.braintreeFastlane})}getClient(){return So(this,void 0,void 0,function*(){if(!this.client){const e=this.getClientTokenOrThrow(),t=yield this.braintreeScriptLoader.loadClient();this.client=t.create({authorization:e})}return this.client})}getPaypal(){return this.braintreePaypal||(this.braintreePaypal=Promise.all([this.getClient(),this.braintreeScriptLoader.loadPaypal()]).then(([e,t])=>t.create({client:e}))),this.braintreePaypal}paypal(e){var{shouldSaveInstrument:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{var r;return i&&(null===(r=this.overlay)||void 0===r||r.show({onClick:()=>e.focusWindow()})),e.tokenize(Object.assign({enableShippingAddress:!0,flow:t?"vault":"checkout",useraction:"commit"},n))}).then(e=>{var t;return null===(t=this.overlay)||void 0===t||t.remove(),e}).catch(e=>{var t;throw null===(t=this.overlay)||void 0===t||t.remove(),e})}getPaypalCheckout(e,t,n){return So(this,void 0,void 0,function*(){const i=yield this.getClient(),r=yield this.braintreeScriptLoader.loadPaypalCheckout(),o={client:i};return this.paypalCheckout=yield r.create(o,(i,r)=>{var o;if(i)return n(i);const a=Object.assign(Object.assign({currency:e.currency},e.isCreditEnabled&&{"enable-funding":"paylater"}),{components:ho.toString(),intent:e.intent,commit:null===(o=e.commit)||void 0===o||o});this.braintreeHostWindow.paypal?t(r):function(e,t){return uo||(uo=new Promise((n,i)=>{e.loadPayPalSDK(t,t=>{t?(uo=null,i(t)):n(e)})})),uo}(r,a).then(()=>t(r))}),this.paypalCheckout})}getDataCollector(e){return So(this,void 0,void 0,function*(){const t=(null==e?void 0:e.paypal)?"paypal":"default";let n=this.dataCollectors[t];if(!n){try{const t=yield this.getClient(),i=yield this.braintreeScriptLoader.loadDataCollector(),r=Object.assign({client:t,kount:!0},e);n=yield i.create(r)}catch(e){if(!Ri(e)||"DATA_COLLECTOR_KOUNT_NOT_ENABLED"!==e.code)throw e;n={deviceData:void 0,teardown:()=>Promise.resolve()}}this.dataCollectors[t]=n}return n})}getBraintreeEnv(e=!1){return e?Fi.Sandbox:Fi.Production}mapToBraintreeShippingAddressOverride(e){return{recipientName:`${e.firstName} ${e.lastName}`,line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,postalCode:e.postalCode,countryCode:e.countryCode,phone:e.phone}}mapToLegacyShippingAddress(e){const{email:t,phone:n,shippingAddress:i}=e,r=(null==i?void 0:i.recipientName)||"",[o,a]=r.split(" ");return{email:t,first_name:o||"",last_name:a||"",phone_number:n,address_line_1:null==i?void 0:i.line1,address_line_2:null==i?void 0:i.line2,city:null==i?void 0:i.city,state:null==i?void 0:i.state,country_code:null==i?void 0:i.countryCode,postal_code:null==i?void 0:i.postalCode}}mapToLegacyBillingAddress(e){const{billingAddress:t,email:n,firstName:i,lastName:r,phone:o,shippingAddress:a}=e,s=t||a;return{email:n,first_name:i,last_name:r,phone_number:o,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}}removeElement(e){const t=e&&document.getElementById(e);t&&t.remove()}getSessionId(e){return So(this,void 0,void 0,function*(){const{deviceData:t}=yield this.getDataCollector({riskCorrelationId:e});return t})}teardown(){return So(this,void 0,void 0,function*(){yield this.teardownModule(this.dataCollectors.default),yield this.teardownModule(this.dataCollectors.paypal),this.dataCollectors={},yield this.teardownModule(this.paypalCheckout),this.paypalCheckout=void 0})}get3DS(){return So(this,void 0,void 0,function*(){return this.threeDS||(this.threeDS=Promise.all([this.getClient(),this.braintreeScriptLoader.load3DS()]).then(([e,t])=>t.create({client:e,version:2}))),this.threeDS})}getVenmoCheckout(e){return So(this,void 0,void 0,function*(){if(!this.venmoCheckout){const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadVenmoCheckout(),i=Object.assign({client:t,allowDesktop:!0,paymentMethodUsage:"multi_use"},e||{});this.venmoCheckout=yield new Promise((e,t)=>{n.create(i,(n,i)=>n?t(n):i.isBrowserSupported()?void e(i):t(new Ai))})}return this.venmoCheckout})}verifyCard(e,t,n){return So(this,void 0,void 0,function*(){const i=yield this.tokenizeCard(e,t);return this.challenge3DSVerification(i,n)})}tokenizeCard(e,t){return So(this,void 0,void 0,function*(){const{paymentData:n}=e;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"object"==typeof t.ccExpiry&&null!==t.ccExpiry&&"string"==typeof t.ccNumber&&"string"==typeof t.ccName}(n))throw new co(["payment.paymentData"]);const i=this.getErrorsRequiredFields(n);if(!$(i))throw new lo(i);const r=this.mapToCreditCard(n,t),o=yield this.getClient(),{creditCards:a}=yield o.request(r);return{nonce:a[0].nonce,bin:a[0].details.bin}})}challenge3DSVerification(e,t){return So(this,void 0,void 0,function*(){const n=yield this.get3DS();return this.present3DSChallenge(n,t,e)})}teardownModule(e){return e?e.teardown():Promise.resolve()}getClientTokenOrThrow(){if(!this.clientToken)throw new ri(ei.PaymentNotInitialized);return this.clientToken}getErrorsRequiredFields(e){const{ccNumber:t,ccExpiry:n}=e,i={};return t||(i.ccNumber=[{message:"Credit card number is required",type:"required"}]),n||(i.ccExpiry=[{message:"Expiration date is required",type:"required"}]),i}mapToCreditCard(e,t){return{data:{creditCard:{cardholderName:e.ccName,number:e.ccNumber,cvv:e.ccCvv,expirationDate:`${e.ccExpiry.month}/${e.ccExpiry.year}`,options:{validate:!1},billingAddress:t&&{countryCodeAlpha2:t.countryCode,locality:t.city,countryName:t.country,postalCode:t.postalCode,streetAddress:t.address2?`${t.address1} ${t.address2}`:t.address1}}},endpoint:"payment_methods/credit_cards",method:"post"}}present3DSChallenge(e,t,n){const{nonce:i,bin:r}=n;if(!this.threeDSecureOptions||!i)throw new ri(ei.PaymentNotInitialized);const{addFrame:o,removeFrame:a,challengeRequested:s=!0,additionalInformation:d}=this.threeDSecureOptions,c=()=>So(this,void 0,void 0,function*(){const t=yield e.cancelVerifyCard();return u.cancel(new Wi),t}),l=t.toFixed(2),u=new En(e.verifyCard({addFrame:(e,t)=>{o&&o(e,t,c)},amount:Number(l),bin:r,challengeRequested:s,nonce:i,removeFrame:a,onLookupComplete:(e,t)=>{t()},collectDeviceData:!0,additionalInformation:d}));return u.promise}}var wo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Io{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return wo(this,void 0,void 0,function*(){const{braintreepaypal:t,methodId:n}=e,{container:i,onError:r}=t||{};if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.braintreepaypal.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(n),!o.clientToken)throw new ti(Xn.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(n),o=a.getPaymentMethodOrThrow(n)}const{clientToken:s,config:d,initializationData:c}=o,{paymentButtonStyles:l}=c||{},{checkoutTopButtonStyles:u}=l||{};if(!s||!c)throw new ti(Xn.MissingPaymentMethod);const h={currency:a.getCartOrThrow().currency.code,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{this.renderPayPalButton(e,t,n,Boolean(d.testMode),u)},e=>this.handleError(e,i,r))})}deinitialize(){return wo(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}signIn(e,t){return wo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return wo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderPayPalButton(e,t,n,i,r){const{container:o,onClick:a=ce}=t,{paypal:s}=this.braintreeHostWindow,d=null==s?void 0:s.FUNDING.PAYPAL;if(s&&d){const c=s.Buttons({env:this.braintreeIntegrationService.getBraintreeEnv(i),fundingSource:d,style:Object.assign(Object.assign({},r),{height:wr}),createOrder:()=>this.setupPayment(e,t,n),onApprove:i=>this.tokenizePayment(i,e,n,t),onClick:a});c.isEligible()&&c.render(`#${o}`)}else this.braintreeIntegrationService.removeElement(o)}setupPayment(e,t,n){var i;return wo(this,void 0,void 0,function*(){try{yield this.paymentIntegrationService.loadDefaultCheckout();const t=this.paymentIntegrationService.getState(),r=t.getCheckoutOrThrow().outstandingBalance,o=t.getCartOrThrow().currency.code,a=t.getCustomer(),s=t.getPaymentMethodOrThrow(n),d=null==a?void 0:a.addresses[0],c=d?this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(d):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:c,amount:r,currency:o,offerCredit:!1,intent:null===(i=s.initializationData)||void 0===i?void 0:i.intent})}catch(e){const{container:n,onError:i}=t;this.handleError(e,n,i)}})}tokenizePayment(e,t,n,i){return wo(this,void 0,void 0,function*(){try{const{deviceData:i}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),r=yield t.tokenizePayment(e),{details:o,nonce:a}=r,s=this.braintreeIntegrationService.mapToLegacyBillingAddress(o),d=this.braintreeIntegrationService.mapToLegacyShippingAddress(o);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:n,action:"set_external_checkout",nonce:a,device_data:i,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:n}=i;this.handleError(e,t,n)}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const Co=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t);return new Io(e,Ee(),i,t)},[{id:"braintreepaypal"}]);var bo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Po{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return bo(this,void 0,void 0,function*(){const{braintreepaypalcredit:t,methodId:n}=e,{container:i,onError:r}=t||{};if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(n),!o.clientToken)throw new ti(Xn.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(n),o=a.getPaymentMethodOrThrow(n)}const{clientToken:s,config:d,initializationData:c}=o,{paymentButtonStyles:l}=c||{},{checkoutTopButtonStyles:u}=l||{};if(!s||!c)throw new ti(Xn.MissingPaymentMethod);const h={currency:a.getCartOrThrow().currency.code,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{this.renderPayPalButton(e,t,n,Boolean(d.testMode),Object.assign(Object.assign({},u),{height:wr}))},e=>this.handleError(e,i,r))})}deinitialize(){return bo(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}signIn(e,t){return bo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return bo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderPayPalButton(e,t,n,i,r){const{container:o,onClick:a=ce}=t,{paypal:s}=this.braintreeHostWindow;let d=!1;s&&[s.FUNDING.PAYLATER,s.FUNDING.CREDIT].forEach(c=>{if(!d){const l=s.Buttons({env:i?"sandbox":"production",fundingSource:c,style:r,createOrder:()=>this.setupPayment(e,t,n),onApprove:i=>this.tokenizePayment(i,e,n,t),onClick:a});l.isEligible()&&(l.render(`#${o}`),d=!0)}}),s&&d||this.braintreeIntegrationService.removeElement(o)}setupPayment(e,t,n){var i;return bo(this,void 0,void 0,function*(){try{yield this.paymentIntegrationService.loadDefaultCheckout();const t=this.paymentIntegrationService.getState(),r=t.getCheckoutOrThrow().outstandingBalance,o=t.getCartOrThrow().currency.code,a=t.getCustomer(),s=t.getPaymentMethodOrThrow(n),d=null==a?void 0:a.addresses[0],c=d?this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(d):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:c,amount:r,currency:o,offerCredit:!0,intent:null===(i=s.initializationData)||void 0===i?void 0:i.intent})}catch(e){const{container:n,onError:i}=t;this.handleError(e,n,i)}})}tokenizePayment(e,t,n,i){return bo(this,void 0,void 0,function*(){try{const{deviceData:i}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),r=yield t.tokenizePayment(e),{details:o,nonce:a}=r,s=this.braintreeIntegrationService.mapToLegacyBillingAddress(o),d=this.braintreeIntegrationService.mapToLegacyShippingAddress(o);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:n,action:"set_external_checkout",nonce:a,device_data:i,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:n}=i;this.handleError(e,t,n)}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const Oo=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t);return new Po(e,Ee(),i,t)},[{id:"braintreepaypalcredit"}]);function Eo(e){return"string"!=typeof e}function Ao(e,t){if(t||e)return function(e){var t,n;const i={},r=ue(e.root,Eo),o=ue(e.input,Eo),a=ue(e.toggle,Eo),s=ue(null===(t=e.text)||void 0===t?void 0:t.body,Eo),d=ue(null===(n=e.text)||void 0===n?void 0:n.caption,Eo),c=e.branding;return Object.keys(r).length&&(i.root=r),Object.keys(o).length&&(i.input=o),Object.keys(a).length&&(i.toggle=a),Object.keys(s).length&&(i.text={},i.text.body=s),Object.keys(d).length&&(i.text=Object.assign({},i.text),i.text.caption=d),c&&(i.branding=c),i}(function(e,t){var n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,_,w,I,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(c=null==t?void 0:t.input)||void 0===c?void 0:c.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.focusBorderColor),backgroundColor:(null==e?void 0:e.fastlaneInputSettingsBackgroundColor)||(null===(u=null==t?void 0:t.input)||void 0===u?void 0:u.backgroundColor),borderWidth:(null==e?void 0:e.fastlaneInputSettingsBorderWidth)||(null===(h=null==t?void 0:t.input)||void 0===h?void 0:h.borderWidth),textColorBase:(null==e?void 0:e.fastlaneInputSettingsTextColorBase)||(null===(p=null==t?void 0:t.input)||void 0===p?void 0:p.textColorBase)},toggle:{colorPrimary:(null==e?void 0:e.fastlaneToggleSettingsColorPrimary)||(null===(m=null==t?void 0:t.toggle)||void 0===m?void 0:m.colorPrimary),colorSecondary:(null==e?void 0:e.fastlaneToggleSettingsColorSecondary)||(null===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(S=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===S?void 0:S.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(w=null===(_=null==t?void 0:t.text)||void 0===_?void 0:_.caption)||void 0===w?void 0:w.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(I=null==t?void 0:t.text)||void 0===I?void 0:I.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var To=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ko{constructor(e,t){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.isAcceleratedCheckoutEnabled=!1}initialize({methodId:e,braintreefastlane:t}){var n;return To(this,void 0,void 0,function*(){if(!e)throw new fi('Unable to proceed because "methodId" argument is not provided.');const i=yield this.getValidPaymentMethodOrThrow(e),{isAcceleratedCheckoutEnabled:r,isFastlaneStylingEnabled:o}=i.initializationData||{},a=o?null===(n=i.initializationData)||void 0===n?void 0:n.fastlaneStyles:void 0;this.isAcceleratedCheckoutEnabled=!!r;try{if(this.isAcceleratedCheckoutEnabled){const e=Ao(a,null==t?void 0:t.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(i.id,e)}}catch(e){}return Promise.resolve()})}deinitialize(){return To(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return To(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return To(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return To(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:n}=e||{};if("function"!=typeof n)throw new fi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');const i=this.paymentIntegrationService.getState().getCustomerOrThrow();if(this.isAcceleratedCheckoutEnabled&&i.isGuest){const e=yield this.shouldRunAuthenticationFlow();t&&"function"==typeof t&&t(),e&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow(void 0,!0))}n()})}shouldRunAuthenticationFlow(){var e;return To(this,void 0,void 0,function*(){const t="braintreeacceleratedcheckout";try{yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t);return(null===(e=n.initializationData)||void 0===e?void 0:e.shouldRunAcceleratedCheckout)||!1}catch(e){return!1}})}getValidPaymentMethodOrThrow(e){return To(this,void 0,void 0,function*(){let t=e;try{yield this.paymentIntegrationService.loadPaymentMethod(t)}catch(n){t="braintree"===e?"braintreeacceleratedcheckout":"braintree",yield this.paymentIntegrationService.loadPaymentMethod(t)}return this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)})}}var Do=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Mo{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}getDeviceSessionId(){return Do(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getCart();return this.braintreeIntegrationService.getSessionId(null==e?void 0:e.id)})}initializeBraintreeFastlaneOrThrow(e,t){return Do(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getCart(),{clientToken:r,config:o}=n.getPaymentMethodOrThrow(e);if(!r)throw new ti(Xn.MissingPaymentMethod);this.methodId=e,this.braintreeIntegrationService.initialize(r),this.braintreeFastlane=yield this.braintreeIntegrationService.getBraintreeFastlane(null==i?void 0:i.id,o.testMode,t)})}getBraintreeFastlaneOrThrow(){if(!this.braintreeFastlane)throw new mi;return this.braintreeFastlane}getBraintreeFastlaneComponentOrThrow(){return this.getBraintreeFastlaneOrThrow().FastlaneCardComponent}runPayPalAuthenticationFlowOrThrow(e,t){var n;return Do(this,void 0,void 0,function*(){try{const i=this.getMethodIdOrThrow(),r=this.getBraintreeFastlaneOrThrow(),{lookupCustomerByEmail:o,triggerAuthenticationFlow:a}=r.identity,s=this.paymentIntegrationService.getState(),d=s.getCartOrThrow(),c=s.getCustomer(),l=s.getBillingAddress(),{isFastlaneShippingOptionAutoSelectEnabled:u}=s.getPaymentMethodOrThrow(i).initializationData||{},h=e||(null==c?void 0:c.email)||(null==l?void 0:l.email)||"",{customerContextId:p}=yield o(h);if(!p)return yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:Mi.UNRECOGNIZED,addresses:[],instruments:[]}),void this.saveSessionIdToCookies(d.id);const{authenticationState:m,profileData:y}=yield a(p),g=(null===(n=null==y?void 0:y.shippingAddress)||void 0===n?void 0:n.phoneNumber)||"";if(m===Mi.CANCELED)return yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:[],instruments:[]}),void this.removeSessionIdFromCookies();const v=this.mapPayPalToBcAddress([y.shippingAddress],[g])||[],f=this.getPayPalBillingAddresses(y),S=f?this.mapPayPalToBcAddress([f],[g]):[],_=y.card?this.mapPayPalToBcInstrument(i,[y.card]):[],w=this.mergeShippingAndBillingAddresses(v,S);if(this.saveSessionIdToCookies(d.id),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:w,instruments:_}),S.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateBillingAddress(S[0])),S.length>0&&d.lineItems.digitalItems.length>0&&0===d.lineItems.physicalItems.length){const{firstName:e,lastName:t}=w[0],n=Object.assign(Object.assign({},S[0]),{firstName:e,lastName:t});yield this.paymentIntegrationService.updateBillingAddress(n)}v.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateShippingAddress(v[0]),t&&u&&(yield this.setShippingOption()))}catch(e){}})}getSessionIdFromCookies(){return Fr.get("bc-fastlane-sessionId")||""}saveSessionIdToCookies(e){const t=new Date;t.setDate(t.getDate()+14),Fr.set("bc-fastlane-sessionId",e,{expires:t,secure:!0})}removeSessionIdFromCookies(){Fr.remove("bc-fastlane-sessionId")}mapPayPalToBcInstrument(e,t){if(t)return t.map(t=>{const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a,binDetails:s}=i.card,[d,c]=o.split("-");return{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:c,expiryYear:d,iin:(null==s?void 0:s.bin)||"",last4:a,method:e,provider:e,trustedShippingAddress:!1,type:"card",untrustedShippingCardVerificationMode:Pr.PAN}})}mapPayPalToBcAddress(e,t){if(!e)return[];const n=this.paymentIntegrationService.getState().getCountries()||[],i=e=>{const t=n.find(t=>t.code===e);return(null==t?void 0:t.name)||""};return e.map(e=>({id:Date.now(),type:"paypal-address",firstName:e.firstName||"",lastName:e.lastName||"",company:e.company||"",address1:e.streetAddress,address2:e.extendedAddress||"",city:e.locality,stateOrProvince:e.region,stateOrProvinceCode:e.region,country:i(e.countryCodeAlpha2),countryCode:e.countryCodeAlpha2,postalCode:e.postalCode,phone:t&&t[0]||"",customFields:[]}))}getPayPalBillingAddresses(e){const{card:t,name:n}=e||{};if(!t)return;const{firstName:i,lastName:r}=t.paymentSource.card.billingAddress,{firstName:o,lastName:a}=n||{},{shippingAddress:s}=e||{},d=Object.assign(Object.assign({},t.paymentSource.card.billingAddress),{firstName:i||o,lastName:r||a});return s&&Y(this.normalizeAddress(d),this.normalizeAddress(s))?s:d}normalizeAddress(e){return le(e,["id"])}mergeShippingAndBillingAddresses(e,t){const n=t.filter(t=>!e.some(e=>Y(this.normalizeAddress(e),this.normalizeAddress(t))));return[...e,...n]}getMethodIdOrThrow(){if(!this.methodId)throw new fi('Unable to proceed because "methodId" argument is not provided.');return this.methodId}setShippingOption(){var e;return Do(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getConsignments()||[],n=(null===(e=t[0])||void 0===e?void 0:e.availableShippingOptions)||[],i=n.find(e=>e.isRecommended);if(i||n.length){const e=i||n[0];yield this.paymentIntegrationService.selectShippingOption(e.id)}})}}const zo=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t),r=new Mo(e,i);return new ko(e,r)},[{id:"braintreeacceleratedcheckout"},{id:"braintree"}]);var No=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class xo{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n,this.buttonClassName="visa-checkout-wrapper",this.onError=ce}initialize(e){return No(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:n}=e;if(!n)throw new fi('Unable to proceed because "methodId" argument is not provided.');if(!t)throw new fi('Unable to proceed because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState(),r=i.getCheckoutOrThrow(),{clientToken:o,config:a}=i.getPaymentMethodOrThrow(n),s=i.getStoreConfigOrThrow();if(!o)throw new ti(Xn.MissingPaymentMethod);this.braintreeSdk.initialize(o);const d=yield this.braintreeSdk.getBraintreeVisaCheckout(),c=yield this.braintreeSdk.getVisaCheckoutSdk(a.testMode),{container:l,onError:u}=t;this.onError=u||ce;const h=d.createInitOptions({paymentRequest:{currencyCode:s.currency.code,subtotal:String(r.subtotal)},settings:{locale:s.storeProfile.storeLanguage,shipping:{collectShipping:!0}}}),p=this.createSignInButton(l,this.buttonClassName);yield c.init(h),c.on("payment.success",e=>this.tokenizePayment(d,e).then(()=>this.paymentIntegrationService.loadCheckout()).catch(e=>this.handleError(e))),c.on("payment.error",(e,t)=>this.handleError(t)),p.style.visibility="visible"})}deinitialize(){return No(this,void 0,void 0,function*(){yield this.braintreeSdk.deinitialize()})}signIn(){throw new Si('In order to sign in via VisaCheckout, the shopper must click on "Visa Checkout" button.')}signOut(e){return No(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}tokenizePayment(e,t){return No(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const n=this.paymentIntegrationService.getState(),i=n.getShippingAddress(),r=n.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(i),billingAddress:a=this.mapToVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}postForm(e,t){const{userData:n,billingAddress:i,shippingAddress:r,details:o}=e,{userEmail:a}=n,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,i)),shipping_address:JSON.stringify(this.getAddress(a,r))})}mapToVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}createSignInButton(e,t){const n=document.querySelector(`#${e}`);if(!n)throw new Error("Unable to proceed because the provided container ID is not valid.");return this.insertVisaCheckoutButton(n,t)}insertVisaCheckoutButton(e,t){const n=document.createElement("div");return n.style.display="flex",n.style.flexDirection="column",n.style.visibility="hidden",n.style.width="max-content",n.className=t,n.innerHTML='\n \n Tell Me More',e.appendChild(n),n}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const Ro=vi(e=>{const t=window,n=new Ei(e),i=new Ui(new Hi(a(),t,n));return new xo(e,Ee(),i)},[{id:"braintreevisacheckout"}]);class Fo{constructor(e){if(!e)throw new Error("Currency settings missing");const{decimalPlaces:t,symbolLocation:n,symbol:i,thousandsSeparator:r,decimalSeparator:o}=e;if("string"!=typeof n||"string"!=typeof i||"string"!=typeof r||"string"!=typeof o||"string"!=typeof t)throw new fi("Invalid currency settings provided");this._decimalPlaces=parseInt(t,10),this._symbolLocation=n,this._symbol=i,this._thousandsSeparator=r,this._decimalSeparator=o}format(e){if("number"!=typeof e)throw new fi("Invalid amount provided");const t=this._formatNumber(e),n=this._formatCurrency(t);return e<0?`-${n}`:n}_formatNumber(e){const t=Math.abs(e),[n,i=""]=this._toFixed(t,this._decimalPlaces).split("."),r=n.replace(/\B(?=(\d{3})+(?!\d))/g,this._thousandsSeparator);return this._decimalPlaces<1?r:[r,i].join(this._decimalSeparator)}_formatCurrency(e){return"left"===this._symbolLocation.toLowerCase()?`${this._symbol}${e}`:`${e}${this._symbol}`}_toFixed(e,t){return(+`${Math.round(+`${e}e${t}`)}e${-t}`).toFixed(t)}}let Lo=class{constructor(e){this._storeConfig=e,this._customerFormatter=new Fo(this._storeConfig.shopperCurrency),this._storeFormatter=new Fo(this._storeConfig.currency)}toCustomerCurrency(e){const t=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(e*t)}toStoreCurrency(e){return this._storeFormatter.format(e)}};Lo=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],Lo);const Bo=Lo,jo=(e,t)=>!!e&&(!!e.lineItems.physicalItems.some(e=>e.isShippingRequired)||!(!t||!e.lineItems.customItems)&&e.lineItems.customItems.length>0);function Uo(){if("undefined"==typeof window)return!1;if(function(e){return"ReactNativeWebView"in e}(window))return!0;const e=navigator.userAgent||navigator.vendor||(function(e){return"opera"in e}(window)?window.opera:""),t=/android.+; wv/i.test(e),n=/iPhone|iPod|iPad/i.test(e)&&/AppleWebKit/i.test(e)&&!/Safari/i.test(e);return t||n}var qo,Vo,Go,Ho,Wo,$o,Yo,Ko,Jo;function Zo(e){return e in $o}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(qo||(qo={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Vo||(Vo={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(Go||(Go={})),function(e){e.pill="pill",e.rect="rect"}(Ho||(Ho={})),function(e){e.ESTIMATED="ESTIMATED",e.FINAL="FINAL",e.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(Wo||(Wo={})),function(e){e.AMEX="AMEX",e.DISCOVER="DISCOVER",e.INTERAC="INTERAC",e.JCB="JCB",e.MC="MASTERCARD",e.VISA="VISA"}($o||($o={})),function(e){e.OFFER="OFFER",e.PAYMENT_AUTHORIZATION="PAYMENT_AUTHORIZATION",e.SHIPPING_ADDRESS="SHIPPING_ADDRESS",e.SHIPPING_OPTION="SHIPPING_OPTION"}(Yo||(Yo={})),function(e){e.OFFER_INVALID="OFFER_INVALID",e.PAYMENT_DATA_INVALID="PAYMENT_DATA_INVALID",e.SHIPPING_ADDRESS_INVALID="SHIPPING_ADDRESS_INVALID",e.SHIPPING_ADDRESS_UNSERVICEABLE="SHIPPING_ADDRESS_UNSERVICEABLE",e.SHIPPING_OPTION_INVALID="SHIPPING_OPTION_INVALID",e.OTHER_ERROR="OTHER_ERROR"}(Ko||(Ko={})),function(e){e.INITIALIZE="INITIALIZE",e.SHIPPING_OPTION="SHIPPING_OPTION",e.SHIPPING_ADDRESS="SHIPPING_ADDRESS",e.OFFER="OFFER"}(Jo||(Jo={}));var Qo,Xo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ea{constructor(e,t){this._gatewayIdentifier=e,this._paymentIntegrationService=t,this._isBuyNowFlow=!1,this._shouldRequestShipping=!0,this._isWebViewExperimentOn=null}mapToShippingAddressRequestBody({shippingAddress:e}){if(!e)return;const{company:t="",phone:n=""}=this._paymentIntegrationService.getState().getShippingAddress()||{};return this._mapToAddressRequestBody(e,t,n)}mapToBillingAddressRequestBody(e){const{billingAddress:t}=e.paymentMethodData.info;if(!t)return;const{company:n="",phone:i="",email:r,customFields:o=[]}=this._paymentIntegrationService.getState().getBillingAddress()||{};return Object.assign(Object.assign({},this._mapToAddressRequestBody(t,n,i,o)),{email:r||e.email})}mapToExternalCheckoutData(e){var t;const{paymentMethodData:{tokenizationData:{token:n},info:{cardNetwork:i,cardDetails:r}}}=e;if(!n)throw new ti(Xn.MissingPaymentToken);return Promise.resolve(Object.assign({nonce:n,card_information:{type:i,number:r}},this._isBuyNowFlow&&{cart_id:null===(t=this._paymentIntegrationService.getState().getCart())||void 0===t?void 0:t.id}))}getRequiredData(){var e;return Xo(this,void 0,void 0,function*(){const t={emailRequired:!0};if(!this._isShippingAddressRequired())return t;const n=yield this._paymentIntegrationService.loadShippingCountries(),i=null===(e=n.getShippingCountries())||void 0===e?void 0:e.map(e=>e.code);return Object.assign(Object.assign({},t),{shippingAddressRequired:!0,shippingAddressParameters:Object.assign({phoneNumberRequired:!0},i&&{allowedCountryCodes:i}),shippingOptionRequired:!0})})}getCallbackIntents(){return this._isShippingAddressRequired()?[Yo.OFFER,Yo.SHIPPING_ADDRESS,Yo.SHIPPING_OPTION]:[Yo.OFFER]}getCallbackTriggers(){return{availableTriggers:[Jo.INITIALIZE,Jo.SHIPPING_ADDRESS,Jo.SHIPPING_OPTION,Jo.OFFER],initializationTrigger:[Jo.INITIALIZE],addressChangeTriggers:[Jo.INITIALIZE,Jo.SHIPPING_ADDRESS],shippingOptionsChangeTriggers:[Jo.SHIPPING_OPTION],offerChangeTriggers:[Jo.OFFER]}}getNonce(e){var t;const n=null===(t=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.nonce;if(!n)throw new ti(Xn.MissingPaymentToken);return Promise.resolve(n)}extraPaymentData(){return Promise.resolve(void 0)}getMerchantInfo(){const{googleMerchantName:e,googleMerchantId:t,platformToken:n}=this.getGooglePayInitializationData();return{merchantName:e,merchantId:t,authJwt:n}}getTransactionInfo(){let e;const{getCartOrThrow:t}=this._paymentIntegrationService.getState();e=this._isBuyNowFlow?this._getCurrencyCodeOrThrow():t().currency.code;const n=this.getGooglePayInitializationData().storeCountry;if(this.isWebViewWithRestrictions()){const t=this.getTotalPrice();return Object.assign(Object.assign({},n&&{countryCode:n}),{currencyCode:e,totalPrice:t,totalPriceStatus:Wo.ESTIMATED})}return Object.assign(Object.assign({},n&&{countryCode:n}),{currencyCode:e,totalPriceStatus:Wo.ESTIMATED,totalPrice:"0"})}isWebViewWithRestrictions(){return null!==this._isWebViewExperimentOn?this._isWebViewExperimentOn&&Uo():Uo()}setIsWebViewExperimentOn(e){this._isWebViewExperimentOn=e}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData().gatewayMerchantId;if(!e)throw new fi("Unable to proceed, gatewayMerchantId is missing.");return{gateway:this._gatewayIdentifier,gatewayMerchantId:e}}getCardParameters(){return{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:this.getPaymentMethod().supportedCards.filter(Zo).map(e=>$o[e]),billingAddressRequired:!0,billingAddressParameters:{format:"FULL",phoneNumberRequired:!0}}}initialize(e,t,n){return this._getPaymentMethodFn=e,this._isBuyNowFlow=Boolean(t),this._currencyCode=n,this._isBuyNowFlow&&this._getCurrencyCodeOrThrow(),Promise.resolve()}handleShippingAddressChange(e){var t,n,i,r;return Xo(this,void 0,void 0,function*(){e&&(e.name=e.name||"",e.address1=e.address1||"");const o=this.mapToShippingAddressRequestBody({shippingAddress:e});o&&(yield this._paymentIntegrationService.updateShippingAddress(o));const a=this._paymentIntegrationService.getState(),s=a.getConsignments();if(!(null==s?void 0:s[0]))return;const d=s[0],c=a.getStoreConfigOrThrow();this._currencyService||(this._currencyService=new Bo(c));const l=(d.availableShippingOptions||[]).map(this._getGooglePayShippingOption.bind(this)),u=null===(t=d.availableShippingOptions)||void 0===t?void 0:t.find(e=>e.isRecommended);if(l.length){const e=(null===(n=d.selectedShippingOption)||void 0===n?void 0:n.id)||(null==u?void 0:u.id)||(null===(i=l[0])||void 0===i?void 0:i.id);return!(null===(r=d.selectedShippingOption)||void 0===r?void 0:r.id)&&l[0]&&(yield this.handleShippingOptionChange((null==u?void 0:u.id)||l[0].id)),{defaultSelectedOptionId:e,shippingOptions:l}}})}handleShippingOptionChange(e){return Xo(this,void 0,void 0,function*(){if("shipping_option_unselected"!==e)return this._paymentIntegrationService.selectShippingOption(e)})}getTotalPrice(){const{getCheckoutOrThrow:e,getCartOrThrow:t,getStoreConfigOrThrow:n}=this._paymentIntegrationService.getState(),{decimalPlaces:i}=t().currency,r=Ci(n().checkoutSettings.features,"PI-5075.google_pay_round_total_price_to_max_2_decimal_places")?Math.min(i,2):i;return ge(e().outstandingBalance,r).toFixed(r)}handleCoupons(e){return Xo(this,void 0,void 0,function*(){const{redemptionCodes:t=[]}=e,{offers:n}=this.getAppliedCoupons()||{};let i;return yield t.reduce((e,t)=>Xo(this,void 0,void 0,function*(){if(yield e,(n||[]).some(({redemptionCode:e})=>e===t))return;const r=yield this.applyCoupon(t);r&&(i=r)}),Promise.resolve()),yield(n||[]).reduce((e,n)=>Xo(this,void 0,void 0,function*(){yield e,t.includes(n.redemptionCode)||(yield this._paymentIntegrationService.removeCoupon(n.redemptionCode))}),Promise.resolve()),{newOfferInfo:this.getAppliedCoupons(),error:i}})}getAppliedCoupons(){const e=this._paymentIntegrationService.getState(),{coupons:t}=e.getCheckout()||{};return{offers:(t||[]).map(e=>{const{displayName:t,code:n}=e;return{redemptionCode:n,description:t}})}}applyCoupon(e){return Xo(this,void 0,void 0,function*(){let t;try{yield this._paymentIntegrationService.applyCoupon(e)}catch(e){return e instanceof Error&&(t={reason:Ko.OFFER_INVALID,message:e.message,intent:Jo.OFFER}),t}})}setShouldRequestShipping(e){this._shouldRequestShipping=e}getGooglePayInitializationData(){return ii(this.getPaymentMethod().initializationData,()=>new fi("Missing initialization data."))}getPaymentMethod(){return ii(this._getPaymentMethodFn,()=>new ri(ei.PaymentNotInitialized))()}getGatewayIdentifier(){return this._gatewayIdentifier}setGatewayIdentifier(e){this._gatewayIdentifier=e||this.getGatewayIdentifier()}_isShippingAddressRequired(){const{getCartOrThrow:e,getStoreConfigOrThrow:t,getShippingAddress:n}=this._paymentIntegrationService.getState(),i=t();let r;return r=Ci(i.checkoutSettings.features,"PI-4290.google_pay_require_shipping_address")?this._shouldRequestShipping:void 0===n(),r&&jo(e(),i)}_mapToAddressRequestBody(e,t,n,i){const{name:r,address1:o,address2:a,address3:s,locality:d,administrativeArea:c,countryCode:l,postalCode:u,phoneNumber:h}=e,[p,m]=this._getFirstAndLastName(r);return{firstName:p,lastName:m,company:t,address1:o,address2:`${a} ${s}`.trim(),city:d||c,stateOrProvince:c,stateOrProvinceCode:c,countryCode:l,postalCode:u,phone:h||n,customFields:i||[]}}_getFirstAndLastName(e){const t=e.split(" ");return 1===t.length?[e,""]:[t.slice(0,-1).join(" "),t[t.length-1]]}_getCurrencyCodeOrThrow(){return ii(this._currencyCode,()=>new fi('Unable to initialize payment because "options.currencyCode" argument is not provided.'))}_getGooglePayShippingOption({id:e,cost:t,description:n,additionalDescription:i}){var r;return{id:e,label:`${(null===(r=this._currencyService)||void 0===r?void 0:r.toCustomerCurrency(t))||t} ${n}`,description:i}}}function ta(e){return"object"==typeof e&&null!==e&&"statusCode"in e}function na(e){return Object.values(Qo).includes(e)}!function(e){e.ADYEN_V2="googlepayadyenv2",e.ADYEN_V3="googlepayadyenv3",e.AUTHORIZE_NET="googlepayauthorizenet",e.BNZ="googlepaybnz",e.BRAINTREE="googlepaybraintree",e.PAYPAL_COMMERCE="googlepaypaypalcommerce",e.BIGCOMMERCE_PAYMENTS="googlepay_bigcommerce_payments",e.CHECKOUT_COM="googlepaycheckoutcom",e.CYBERSOURCE_V2="googlepaycybersourcev2",e.ORBITAL="googlepayorbital",e.STRIPE="googlepaystripe",e.STRIPE_UPE="googlepaystripeupe",e.STRIPE_OCS="googlepaystripeocs",e.WORLDPAY_ACCESS="googlepayworldpayaccess",e.TD_ONLINE_MART="googlepaytdonlinemart"}(Qo||(Qo={}));var ia=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ra{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t}initialize(e){var t,n;return ia(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId)||!na(e.methodId))throw new fi('Unable to proceed because "methodId" is not a valid key.');this._methodId=e.methodId;const i=e[this._getMethodId()];if(!i)throw new fi("Unable to proceed without valid options.");let r,o=this._paymentIntegrationService.getState();try{r=o.getPaymentMethodOrThrow(this._getMethodId())}catch(e){o=yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodId()),r=o.getPaymentMethodOrThrow(this._getMethodId())}try{this._googlePayPaymentProcessor.setIsWebViewExperimentOn(!!(null===(t=r.initializationData)||void 0===t?void 0:t.isWebViewExperimentOn)),yield this._googlePayPaymentProcessor.initialize(()=>r,this._getGooglePayClientOptions(null===(n=r.initializationData)||void 0===n?void 0:n.storeCountry))}catch(e){return}this._addPaymentButton(i)})}signIn(){return Promise.reject(new Si('In order to sign in via Google Pay, the shopper must click on "Google Pay" button.'))}signOut(){var e;return ia(this,void 0,void 0,function*(){const t=null===(e=this._paymentIntegrationService.getState().getPaymentId())||void 0===e?void 0:e.providerId;t&&(yield this._googlePayPaymentProcessor.signOut(t))})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}deinitialize(){var e;return null===(e=this._paymentButton)||void 0===e||e.remove(),this._paymentButton=void 0,this._methodId=void 0,Promise.resolve()}_getGooglePayClientOptions(e){return this._googlePayPaymentProcessor.isWebViewWithRestrictions()?{}:{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:t,shippingAddress:n,shippingOptionData:i,offerData:r})=>ia(this,void 0,void 0,function*(){const{availableTriggers:o,addressChangeTriggers:a,shippingOptionsChangeTriggers:s,offerChangeTriggers:d}=this._googlePayPaymentProcessor.getCallbackTriggers();if(!o.includes(t))return;const c=a.includes(t)?yield this._googlePayPaymentProcessor.handleShippingAddressChange(n):void 0;s.includes(t)&&(yield this._googlePayPaymentProcessor.handleShippingOptionChange(i.id));const{newOfferInfo:l,error:u}=d.includes(t)?yield this._googlePayPaymentProcessor.handleCoupons(r):{},h=u;yield this._paymentIntegrationService.loadCheckout();const p=this._googlePayPaymentProcessor.getTotalPrice(),{code:m}=this._paymentIntegrationService.getState().getCartOrThrow().currency;return Object.assign(Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},e&&{countryCode:e}),{currencyCode:m,totalPriceStatus:Wo.FINAL,totalPrice:p})},c&&{newShippingOptionParameters:c}),l&&{newOfferInfo:l}),h&&{error:h})})}}}_addPaymentButton({container:e,buttonColor:t,buttonType:n,onClick:i,onError:r}){var o;this._paymentButton=null!==(o=this._paymentButton)&&void 0!==o?o:this._googlePayPaymentProcessor.addPaymentButton(e,{buttonColor:null!=t?t:"default",buttonType:null!=n?n:"plain",onClick:this._handleClick(r,i)})}_handleClick(e,t){return n=>ia(this,void 0,void 0,function*(){n.preventDefault(),t&&"function"==typeof t&&t();try{yield this._googlePayPaymentProcessor.initializeWidget(),yield this._interactWithPaymentSheet()}catch(t){let n=t;if(ta(t)){if("CANCELED"===t.statusCode)throw new Wi;n=new Qr(JSON.stringify(t))}throw null==e||e(new Qr("An error occurred while requesting your Google Pay payment details.")),n}})}_interactWithPaymentSheet(){return ia(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet(),t=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e),n=this._googlePayPaymentProcessor.mapToShippingAddressRequestBody(e),i="/embedded-checkout"===window.location.pathname?this._paymentIntegrationService.getState().getStoreConfigOrThrow().links.siteLink:void 0;t&&(yield this._paymentIntegrationService.updateBillingAddress(t)),n&&(yield this._paymentIntegrationService.updateShippingAddress(n)),yield this._googlePayPaymentProcessor.setExternalCheckoutForm(this._getMethodId(),e,i)})}_getMethodId(){return ii(this._methodId,()=>new ri(ei.PaymentNotInitialized))}}var oa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class aa{constructor(e,t,n,i){this._scriptLoader=e,this._gateway=t,this._requestSender=n,this._formPoster=i,this._baseRequest={apiVersion:2,apiVersionMinor:0}}initialize(e,t,n,i){return oa(this,void 0,void 0,function*(){this._paymentsClient=yield this._scriptLoader.getGooglePaymentsClient(e().config.testMode,t),yield this._gateway.initialize(e,n,i),this._buildButtonPayloads()})}initializeWidget(){return oa(this,void 0,void 0,function*(){yield this._buildWidgetPayloads(),yield this._determineReadinessToPay(),this._prefetchGooglePaymentData()})}getNonce(e){return this._gateway.getNonce(e)}extraPaymentData(){return oa(this,void 0,void 0,function*(){return this._gateway.extraPaymentData()})}addPaymentButton(e,t){const n=document.querySelector(`#${e}`);if(!n)return;const i=this._getPaymentsClient().createButton(Object.assign(Object.assign({},t),{allowedPaymentMethods:[this._getBaseCardPaymentMethod()]}));return n.appendChild(i)}showPaymentSheet(){return oa(this,void 0,void 0,function*(){const e=this._getPaymentDataRequest();return this._getPaymentsClient().loadPaymentData(e)})}setExternalCheckoutXhr(e,t){return oa(this,void 0,void 0,function*(){return this._setExternalCheckout(e,t)})}setExternalCheckoutForm(e,t,n){return oa(this,void 0,void 0,function*(){return this._setExternalCheckout(e,t,!0,n)})}mapToBillingAddressRequestBody(e){return this._gateway.mapToBillingAddressRequestBody(e)}mapToShippingAddressRequestBody(e){return this._gateway.mapToShippingAddressRequestBody(e)}processAdditionalAction(e,t){return"processAdditionalAction"in this._gateway?this._gateway.processAdditionalAction(e,t):Promise.reject(e)}signOut(e){return oa(this,void 0,void 0,function*(){yield this._requestSender.get(`/remote-checkout/${e}/signout`)})}getCallbackTriggers(){return this._gateway.getCallbackTriggers()}setShouldRequestShipping(e){return this._gateway.setShouldRequestShipping(e)}handleShippingAddressChange(e){return oa(this,void 0,void 0,function*(){return this._gateway.handleShippingAddressChange(e)})}handleShippingOptionChange(e){return oa(this,void 0,void 0,function*(){yield this._gateway.handleShippingOptionChange(e)})}handleCoupons(e){return oa(this,void 0,void 0,function*(){return this._gateway.handleCoupons(e)})}getTotalPrice(){return this._gateway.getTotalPrice()}_setExternalCheckout(e,t,n=!1,i){return oa(this,void 0,void 0,function*(){const r="/checkout.php",o=Object.assign({action:"set_external_checkout",provider:e},yield this._gateway.mapToExternalCheckoutData(t));if(n)return new Promise(e=>{this._formPoster.postForm(i?`${i}/checkout`:r,Object.assign(Object.assign({},o),{card_information:JSON.stringify(o.card_information)}),e)});yield this._requestSender.post(r,{headers:Object.assign({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded"},yr),body:o})})}isWebViewWithRestrictions(){return this._gateway.isWebViewWithRestrictions()}setIsWebViewExperimentOn(e){return this._gateway.setIsWebViewExperimentOn(e)}_prefetchGooglePaymentData(){const e=this._getPaymentDataRequest();e.transactionInfo=this._gateway.getTransactionInfo(),this._getPaymentsClient().prefetchPaymentData(e)}_determineReadinessToPay(){return oa(this,void 0,void 0,function*(){try{const{result:e}=yield this._getPaymentsClient().isReadyToPay(this._getIsReadyToPayRequest());if(!1===e)throw new Qr("Google Pay is not supported by the current device and browser, please try another payment method.")}catch(e){if(e instanceof Qr)throw e;throw new Qr}})}_buildButtonPayloads(){this._baseCardPaymentMethod={type:"CARD",parameters:this._gateway.getCardParameters()}}_buildWidgetPayloads(){return oa(this,void 0,void 0,function*(){const e=this._getBaseCardPaymentMethod();this._cardPaymentMethod=Object.assign(Object.assign({},e),{tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:yield this._gateway.getPaymentGatewayParameters()}});const t=this._gateway.isWebViewWithRestrictions()?{shippingOptionRequired:!1}:{callbackIntents:this._gateway.getCallbackIntents(),offerInfo:this._gateway.getAppliedCoupons()};this._paymentDataRequest=Object.assign(Object.assign(Object.assign(Object.assign({},this._baseRequest),{allowedPaymentMethods:[this._cardPaymentMethod],transactionInfo:this._gateway.getTransactionInfo(),merchantInfo:this._gateway.getMerchantInfo()}),yield this._gateway.getRequiredData()),t),this._isReadyToPayRequest=Object.assign(Object.assign({},this._baseRequest),{allowedPaymentMethods:[e]})})}_getBaseCardPaymentMethod(){return this._getOrThrow(this._baseCardPaymentMethod)}_getPaymentDataRequest(){return this._getOrThrow(this._paymentDataRequest)}_getIsReadyToPayRequest(){return this._getOrThrow(this._isReadyToPayRequest)}_getPaymentsClient(){return this._getOrThrow(this._paymentsClient)}_getOrThrow(e){return ii(e,()=>new ri(ei.PaymentNotInitialized))}}class sa{constructor(e){this._scriptLoader=e,this._window=window}getGooglePaymentsClient(e=!1,t){return n=this,i=void 0,o=function*(){if(yield this._scriptLoader.loadScript("https://pay.google.com/gp/p/js/pay.js"),!this._window.google)throw new mi;return void 0===this._paymentsClient&&(this._paymentsClient=new this._window.google.payments.api.PaymentsClient(Object.assign({environment:e?"TEST":"PRODUCTION"},null!=t?t:{}))),this._paymentsClient},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}function da(){return new sa(a())}const ca=vi(e=>{const t=n();return new ra(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv2"}]),la=vi(e=>{const t=n();return new ra(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv3"}]);class ua extends ea{constructor(e){super("authorizenet",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();return function(e){if(!function(e){return"paymentGatewayId"in e}(e))throw new ti(Xn.MissingPaymentMethod)}(e),{gateway:this.getGatewayIdentifier(),gatewayMerchantId:e.paymentGatewayId}}}const ha=vi(e=>new ra(e,new aa(da(),new ua(e),n(),Ee())),[{id:"googlepayauthorizenet"}]),pa=e=>"object"==typeof e&&null!==e&&"body"in e;function ma(e){if(!function(e){return"checkoutcomkey"in e}(e))throw new ti(Xn.MissingPaymentMethod)}var ya=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ga extends ea{constructor(e,t){super("checkoutltd",e),this._requestSender=t}processAdditionalAction(e){return new Promise((t,n)=>{if(pa(e)&&function(e){var t;if("object"!=typeof e||null===e)return!1;const n=e;return"string"==typeof(null===(t=n.three_ds_result)||void 0===t?void 0:t.acs_url)&&"string"==typeof n.three_ds_result.code}(e.body)&&"three_d_secure_required"===e.body.three_ds_result.code)return window.location.assign(e.body.three_ds_result.acs_url);n(e)})}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ya(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);let i;try{i=JSON.parse(n.nonce)}catch(e){throw new fi("Unable to parse response from Google Pay.")}return function(e){if(!function(e){return"object"==typeof e&&null!==e&&"protocolVersion"in e&&"signature"in e&&"signedMessage"in e}(e))throw new ti(Xn.MissingPaymentToken)}(i),n.nonce=yield this._tokenize(i),n})}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();return ma(e),{gateway:this.getGatewayIdentifier(),gatewayMerchantId:e.checkoutcomkey}}_tokenize(e){return ya(this,void 0,void 0,function*(){const t=this.getPaymentMethod().config.testMode?"https://api.sandbox.checkout.com/tokens":"https://api.checkout.com/tokens",n=this.getGooglePayInitializationData();ma(n);const{body:i}=yield this._requestSender.post(t,{credentials:!1,body:{type:"googlepay",token_data:e},headers:{Authorization:n.checkoutcomkey,"Content-Type":mr.Json,"X-XSRF-TOKEN":null}});return i.token})}}const va=vi(e=>{const t=n();return new ra(e,new aa(da(),new ga(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]);class fa extends ea{constructor(e){super("cybersource",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const Sa=vi(e=>new ra(e,new aa(da(),new fa(e),n(),Ee())),[{id:"googlepaycybersourcev2"}]),_a=vi(e=>new ra(e,new aa(da(),new fa(e),n(),Ee())),[{id:"googlepaybnz"}]);class wa extends ea{constructor(e){super("chase",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const Ia=vi(e=>new ra(e,new aa(da(),new wa(e),n(),Ee())),[{id:"googlepayorbital"}]);var Ca,ba,Pa,Oa,Ea,Aa,Ta,ka,Da,Ma,za,Na;!function(e){e.SHIPPING="shipping",e.BILLING="billing"}(Ca||(Ca={})),function(e){e.SPLIT="split",e.FULL="full",e.ORGANIZATION="organization"}(ba||(ba={})),function(e){e.Open="open",e.Expired="expired",e.Complete="complete"}(Pa||(Pa={})),function(e){e.Paid="paid",e.UnPaid="unpaid",e.NoPaymentRequired="no_payment_required"}(Oa||(Oa={})),function(e){e.SUCCESS="success",e.ERROR="error"}(Ea||(Ea={})),function(e){e.CreditCard="card",e.ACH="us_bank_account",e.Link="link",e.EPS="eps",e.GRABPAY="grabpay",e.BANCONTACT="bancontact",e.IDEAL="ideal",e.ALIPAY="alipay",e.KLARNA="klarna",e.OCS="optimized_checkout",e.CHECKOUT_SESSION="checkout_session"}(Aa||(Aa={})),function(e){e.NEVER="never",e.AUTO="auto",e.ALWAYS="always",e.PAYMENT="payment",e.IF_REQUIRED="if_required"}(Ta||(Ta={})),function(e){e.V3="v3",e.ACACIA="acacia",e.BASIL="basil",e.CLOVER="clover"}(ka||(ka={})),function(e){e.PAYMENT="payment",e.AUTHENTICATION="linkAuthentication",e.SHIPPING="address",e.EXPRESS_CHECKOUT="expressCheckout"}(Da||(Da={})),function(e){e.REQUIRES_PAYMENT_METHOD="requires_payment_method",e.REQUIRES_CONFIRMATION="requires_confirmation",e.REQUIRES_ACTION="requires_action",e.PROCESSING="processing",e.SUCCEEDED="succeeded",e.CANCELED="canceled"}(Ma||(Ma={})),function(e){e.CLICK="click",e.CHANGE="change",e.READY="ready",e.SHIPPING_ADDRESS_CHANGE="shippingaddresschange",e.SHIPPING_RATE_CHANGE="shippingratechange",e.CONFIRM="confirm",e.CANCEL="cancel",e.LOADER_START="loaderstart"}(za||(za={})),function(e){e.ON_SESSION="on_session",e.OFF_SESSION="off_session"}(Na||(Na={}));var xa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ra{constructor(e,t=window){this.scriptLoader=e,this.stripeWindow=t}getStripeClient(e,t,n,i,r){return xa(this,void 0,void 0,function*(){if(this.stripeWindow.bcStripeClient)return this.stripeWindow.bcStripeClient;const o=yield this.load(n),{stripePublishableKey:a,stripeConnectedAccount:s}=e,d=o(a,Object.assign(Object.assign(Object.assign(Object.assign({},s?{stripeAccount:s}:{}),t?{locale:t}:{}),i?{betas:i}:{}),r?{apiVersion:r}:{}));return Object.assign(this.stripeWindow,{bcStripeClient:d}),d})}getElements(e,t){return xa(this,void 0,void 0,function*(){let n=this.stripeWindow.bcStripeElements;return n?yield this.updateStripeElements(t):(n=e.elements(t),Object.assign(this.stripeWindow,{bcStripeElements:n})),n})}updateStripeElements(e){return xa(this,void 0,void 0,function*(){const t=this.stripeWindow.bcStripeElements;t&&(t.update(e),yield t.fetchUpdates())})}getStripeCheckout(e,t){return xa(this,void 0,void 0,function*(){let n=yield this.getStoredStripeCheckout(t);return n||(n=yield e.initCheckout(t),Object.assign(this.stripeWindow,{bcStripeCheckout:n})),n})}load(e){return xa(this,void 0,void 0,function*(){if(!this.stripeWindow.Stripe&&(yield this.scriptLoader.loadScript(this.getScriptUrl(e)),!this.stripeWindow.Stripe))throw new mi;return this.stripeWindow.Stripe})}getScriptUrl(e){return e&&e!==ka.V3?`https://js.stripe.com/${e}/stripe.js`:"https://js.stripe.com/v3/"}getStoredStripeCheckout(e){return xa(this,void 0,void 0,function*(){const t=this.stripeWindow.bcStripeCheckout;if(t)try{const{actions:n,error:i}=yield t.loadActions();if(i||!n)return void this.logErrorToConsole(i);const r=yield n.getSession(),o=e.clientSecret.split("_secret_")[0];if(r.id===o)return t}catch(e){return void this.logErrorToConsole(e)}})}logErrorToConsole(e){e?console.error(e):console.error("No stripe checkout actions available on loadActions().")}}const Fa=["payment_element_beta_2","alipay_pm_beta_1","link_default_integration_beta_1","shipping_address_element_beta_1","address_element_beta_1"],La="2020-03-02;alipay_beta=v1;link_beta=v1";function Ba(e){if(!function(e){return"stripeConnectedAccount"in e&&"stripePublishableKey"in e&&"stripeVersion"in e}(e))throw new ti(Xn.MissingPaymentMethod)}var ja=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ua extends ea{constructor(e,t){super("stripe",e),this.paymentIntegrationService=e,this.scriptLoader=t}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ja(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);let i;try{i=JSON.parse(n.nonce)}catch(e){throw new fi("Unable to parse response from Google Pay.")}return function(e){if(!function(e){return"object"==typeof e&&null!==e&&"id"in e}(e))throw new ti(Xn.MissingPaymentToken)}(i),n.nonce=i.id,n})}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();Ba(e);const{stripeVersion:t,stripePublishableKey:n,stripeConnectedAccount:i}=e;return{gateway:this.getGatewayIdentifier(),"stripe:version":t,"stripe:publishableKey":`${n}/${i}`}}processAdditionalAction(e,t){var n;return ja(this,void 0,void 0,function*(){if(!t)throw new co(["payment"]);if(!pa(e)||("object"!=typeof(i=e.body)||null===i||!("three_ds_result"in i)||!("errors"in i)))throw e;var i;if(ve(e.body.errors,{code:"three_d_secure_required"})){const i=this.getGooglePayInitializationData();Ba(i),this.stripeUPEClient=yield this.loadStripeJs(i,t);const r=e.body.three_ds_result.token;let o,a=!1;try{o=yield this.stripeUPEClient.confirmCardPayment(r)}catch(e){try{o=yield this.stripeUPEClient.retrievePaymentIntent(r)}catch(e){a=!0}}if(null==o?void 0:o.error){if(this._throwDisplayableStripeError(o.error),this._isCancellationError(o.error))throw new Wi;throw new Qr}if(!(null==o?void 0:o.paymentIntent)&&!a)throw new nr;return this.paymentIntegrationService.submitPayment({methodId:t,paymentData:{nonce:(null===(n=null==o?void 0:o.paymentIntent)||void 0===n?void 0:n.id)||r}})}throw e})}loadStripeJs(e,t){return ja(this,void 0,void 0,function*(){if(this.stripeUPEClient)return this.stripeUPEClient;const n=this.paymentIntegrationService.getState().getCartLocale();return"googlepaystripeocs"===t&&e.useNewStripeJsVersion?this.scriptLoader.getStripeClient(e,n,ka.CLOVER):this.scriptLoader.getStripeClient(e,n,ka.V3,Fa,La)})}_isCancellationError(e){var t,n;return e&&-1!==(null===(n=null===(t=e.payment_intent.last_payment_error)||void 0===t?void 0:t.message)||void 0===n?void 0:n.indexOf("canceled"))}_throwDisplayableStripeError(e){if(H(["card_error","invalid_request_error","validation_error"],e.type))throw new Error(e.message)}}const qa=vi(e=>new ra(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeocs"}]),Va=vi(e=>new ra(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripeupe"}]);class Ga extends ea{constructor(e){super("worldpay",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const Ha=vi(e=>new ra(e,new aa(da(),new Ga(e),n(),Ee())),[{id:"googlepayworldpayaccess"}]);var Wa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class $a extends ea{constructor(e,t){super("braintree",e),this._braintreeSdk=t,this._methodId=Qo.BRAINTREE,this._service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Wa(this,void 0,void 0,function*(){yield i.initialize.call(this,e,t,n);let r=i.getPaymentMethod.call(this);if(r.clientToken||(r=(yield this._service.loadPaymentMethod(this._methodId)).getPaymentMethodOrThrow(this._methodId)),!r.clientToken||!r.initializationData)throw new ti(Xn.MissingPaymentMethod);return this._braintreeSdk.initialize(r.clientToken),this._braintreeGooglePayment=yield this._braintreeSdk.getBraintreeGooglePayment(),Promise.resolve()})}getNonce(e){const t=Object.create(null,{getNonce:{get:()=>super.getNonce},getPaymentMethod:{get:()=>super.getPaymentMethod}});var n;return Wa(this,void 0,void 0,function*(){const i=yield t.getNonce.call(this,e),{clientToken:r,initializationData:o}=t.getPaymentMethod.call(this);if(!r||!o||!(null===(n=o.card_information)||void 0===n?void 0:n.bin))throw new ti(Xn.MissingPaymentMethod);const{isThreeDSecureEnabled:a,card_information:{bin:s,isNetworkTokenized:d}}=o;if(a&&!d){const e=yield this._braintreeSdk.getBraintreeThreeDS(),{orderAmount:t}=this._service.getState().getOrderOrThrow();return(yield this._braintreePresent3DSChallenge(e,t,i,s)).nonce}return i})}extraPaymentData(){return Wa(this,void 0,void 0,function*(){return{deviceSessionId:yield this._getBraintreeDeviceData()}})}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return Wa(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);let i;try{i=JSON.parse(n.nonce)}catch(e){throw new fi("Unable to parse response from Google Pay.")}return function(e){if(!function(e){return"object"==typeof e&&null!==e&&"androidPayCards"in e}(e))throw new ti(Xn.MissingPaymentToken)}(i),n.nonce=i.androidPayCards[0].nonce,n.card_information.bin=i.androidPayCards[0].details.bin,n.card_information.isNetworkTokenized=i.androidPayCards[0].details.isNetworkTokenized,n})}getCardParameters(){return super.getCardParameters()}getPaymentGatewayParameters(){const e=Object.create(null,{getMerchantInfo:{get:()=>super.getMerchantInfo},getTransactionInfo:{get:()=>super.getTransactionInfo},getRequiredData:{get:()=>super.getRequiredData}});return Wa(this,void 0,void 0,function*(){return this.getBraintreeGooglePayment().createPaymentDataRequest(Object.assign({merchantInfo:e.getMerchantInfo.call(this),transactionInfo:e.getTransactionInfo.call(this),cardRequirements:{billingAddressRequired:!0,billingAddressFormat:"FULL"}},yield e.getRequiredData.call(this))).paymentMethodTokenizationParameters.parameters})}getBraintreeGooglePayment(){if(!this._braintreeGooglePayment)throw new ti(Xn.MissingPaymentMethod);return this._braintreeGooglePayment}_getBraintreeDeviceData(){return Wa(this,void 0,void 0,function*(){const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e})}_braintreePresent3DSChallenge(e,t,n,i){return new En(e.verifyCard({amount:t,bin:i,nonce:n,onLookupComplete:(e,t)=>{t()}})).promise}}const Ya=vi(e=>{const t=n(),i=window,r=new Ei(e),o=new Ui(new Hi(a(),i,r));return new ra(e,new aa(da(),new $a(e,o),t,Ee()))},[{id:"googlepaybraintree"}]),Ka={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},Ja=["ar_BH","ar_DZ","ar_EG","ar_JO","ar_KW","ar_MA","ar_OM","ar_QA","ar_SA","ar_TN","ar_YE","ar_AE","bg_BG","cs_CZ","da_DK","da_FO","da_GL","de_AT","de_CH","de_DE","de_LU","el_GR","en_AD","en_AE","en_AG","en_AI","en_AL","en_AM","en_AN","en_AO","en_AT","en_AU","en_AW","en_AZ","en_BB","en_BE","en_BH","en_BJ","en_BM","en_BN","en_BS","en_BT","en_BW","en_BY","en_BZ","en_C2","en_CA","en_CD","en_CG","en_CH","en_CI","en_CK","en_CL","en_CM","en_CN","en_CO","en_CR","en_CV","en_CY","en_CZ","en_DE","en_DJ","en_DK","en_DM","en_DO","en_DZ","en_EC","en_EE","en_EG","en_ER","en_ES","en_ET","en_FI","en_FJ","en_FK","en_FM","en_FO","en_FR","en_GA","en_GB","en_GD","en_GE","en_GF","en_GI","en_GL","en_GM","en_GN","en_GP","en_GR","en_GT","en_GW","en_GY","en_HK","en_HN","en_HR","en_HU","en_ID","en_IE","en_IL","en_IN","en_IS","en_IT","en_JM","en_JO","en_JP","en_KE","en_KG","en_KH","en_KI","en_KM","en_KN","en_KR","en_KW","en_KY","en_KZ","en_LA","en_LC","en_LI","en_LK","en_LS","en_LT","en_LU","en_LV","en_MA","en_MC","en_MD","en_ME","en_MG","en_MH","en_MK","en_ML","en_MN","en_MQ","en_MR","en_MS","en_MT","en_MU","en_MV","en_MW","en_MY","en_MZ","en_NA","en_NC","en_NE","en_NF","en_NG","en_NI","en_NL","en_NO","en_NP","en_NR","en_NU","en_NZ","en_OM","en_PA","en_PE","en_PF","en_PG","en_PH","en_PL","en_PM","en_PN","en_PT","en_PW","en_PY","en_QA","en_RE","en_RO","en_RS","en_RU","en_RW","en_SA","en_SB","en_SC","en_SE","en_SG","en_SH","en_SI","en_SJ","en_SK","en_SL","en_SM","en_SN","en_SO","en_SR","en_ST","en_SV","en_SZ","en_TC","en_TD","en_TG","en_TH","en_TJ","en_TM","en_TN","en_TO","en_TR","en_TT","en_TV","en_TW","en_TZ","en_UA","en_UG","en_US","en_UY","en_VA","en_VC","en_VE","en_VG","en_VN","en_VU","en_WF","en_WS","en_YE","en_YT","en_ZA","en_ZM","en_ZW","es_AD","es_AI","es_AO","es_AR","es_AW","es_BB","es_BJ","es_BM","es_BO","es_BS","es_BZ","es_CD","es_CG","es_CK","es_CL","es_CO","es_CR","es_CV","es_DJ","es_DM","es_DO","es_DZ","es_EC","es_EG","es_ER","es_ES","es_ET","es_FJ","es_FK","es_FO","es_GA","es_GD","es_GE","es_GI","es_GL","es_GM","es_GN","es_GT","es_GW","es_GY","es_HN","es_IE","es_JM","es_JO","es_KE","es_KG","es_KI","es_KM","es_KN","es_KW","es_KY","es_KZ","es_LC","es_LI","es_LS","es_LU","es_MA","es_MG","es_MH","es_ML","es_MR","es_MS","es_MU","es_MW","es_MX","es_MZ","es_NA","es_NC","es_NE","es_NF","es_NI","es_NR","es_NU","es_NZ","es_OM","es_PA","es_PE","es_PF","es_PG","es_PM","es_PN","es_PW","es_PY","es_QA","es_RS","es_RW","es_SA","es_SB","es_SC","es_SH","es_SJ","es_SL","es_SM","es_SN","es_SO","es_SR","es_ST","es_SV","es_SZ","es_TC","es_TD","es_TG","es_TJ","es_TM","es_TN","es_TT","es_TV","es_UA","es_UG","es_US","es_UY","es_VA","es_VC","es_VE","es_VG","es_VU","es_WF","es_YE","es_ZM","et_EE","fi_FI","fr_AD","fr_AE","fr_AI","fr_AM","fr_AO","fr_AW","fr_AZ","fr_BB","fr_BE","fr_BF","fr_BI","fr_BJ","fr_BM","fr_BS","fr_BZ","fr_CA","fr_CD","fr_CG","fr_CH","fr_CI","fr_CK","fr_CM","fr_CV","fr_DJ","fr_DM","fr_DO","fr_DZ","fr_EC","fr_ER","fr_ET","fr_FJ","fr_FK","fr_FO","fr_FR","fr_GA","fr_GD","fr_GE","fr_GF","fr_GI","fr_GL","fr_GM","fr_GN","fr_GP","fr_GT","fr_GW","fr_GY","fr_HN","fr_IE","fr_JM","fr_JO","fr_KE","fr_KG","fr_KI","fr_KM","fr_KN","fr_KW","fr_KY","fr_KZ","fr_LC","fr_LI","fr_LS","fr_LU","fr_MA","fr_MC","fr_MG","fr_MH","fr_ML","fr_MQ","fr_MR","fr_MS","fr_MU","fr_MW","fr_MZ","fr_NA","fr_NC","fr_NE","fr_NF","fr_NI","fr_NR","fr_NU","fr_NZ","fr_OM","fr_PA","fr_PE","fr_PF","fr_PG","fr_PM","fr_PN","fr_PW","fr_QA","fr_RE","fr_RS","fr_RW","fr_SA","fr_SB","fr_SC","fr_SH","fr_SJ","fr_SL","fr_SM","fr_SN","fr_SO","fr_SR","fr_ST","fr_SV","fr_SZ","fr_TC","fr_TD","fr_TG","fr_TJ","fr_TM","fr_TN","fr_TT","fr_TV","fr_UA","fr_UG","fr_US","fr_UY","fr_VA","fr_VC","fr_VE","fr_VG","fr_VU","fr_WF","fr_YE","fr_YT","fr_ZA","fr_ZM","he_IL","hu_HU","id_ID","it_IT","ja_JP","ko_KR","lv_LV","lt_LT","ms_BN","ms_MY","nl_BE","nl_NL","pl_PL","pt_BR","pt_PT","ro_RO","ru_EE","ru_LT","ru_LV","ru_RU","ru_UA","si_LK","sk_SK","sl_SI","sq_AL","sv_SE","tl_PH","th_TH","tr_TR","vi_VN","zh_C2","zh_CN","zh_HK","zh_TW","zh_AD","zh_AE","zh_AI","zh_AO","zh_AW","zh_BB","zh_BH","zh_BJ","zh_BM","zh_BS","zh_BZ","zh_CD","zh_CG","zh_CK","zh_CL","zh_CO","zh_CV","zh_DJ","zh_DM","zh_DO","zh_DZ","zh_EC","zh_EG","zh_ER","zh_ET","zh_FJ","zh_FK","zh_FO","zh_GA","zh_GD","zh_GE","zh_GI","zh_GL","zh_GM","zh_GN","zh_GT","zh_GW","zh_GY","zh_HN","zh_IE","zh_JM","zh_JO","zh_KE","zh_KG","zh_KI","zh_KM","zh_KN","zh_KW","zh_KY","zh_KZ","zh_LC","zh_LI","zh_LS","zh_LT","zh_LU","zh_MA","zh_MG","zh_MH","zh_ML","zh_MR","zh_MS","zh_MU","zh_MW","zh_MZ","zh_NA","zh_NC","zh_NE","zh_NF","zh_NI","zh_NR","zh_NU","zh_NZ","zh_OM","zh_PA","zh_PE","zh_PF","zh_PG","zh_PM","zh_PN","zh_PW","zh_QA","zh_RS","zh_RW","zh_SA","zh_SB","zh_SC","zh_SH","zh_SJ","zh_SL","zh_SM","zh_SN","zh_SO","zh_SR","zh_ST","zh_SV","zh_SZ","zh_TC","zh_TD","zh_TG","zh_TJ","zh_TM","zh_TN","zh_TT","zh_TV","zh_UA","zh_UG","zh_US","zh_UY","zh_VA","zh_VC","zh_VE","zh_VG","zh_VU","zh_WF","zh_YE","zh_ZA","zh_ZM"];function Za(e){if(!e)return;let t;if(e.includes("-")){const[n,i]=e.split("-");t=`${n}_${i.toUpperCase()}`}else t=`${e}_${e.toUpperCase()}`;return Ja.includes(t)?t:void 0}var Qa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Xa{constructor(e){this.scriptLoader=e,this.window=window}getPayPalFastlaneSdk(e,t,n,i){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const r=this.getPayPalFastlaneSdkConfiguration(e,t,n,i);if(yield this.loadPayPalSdk(r),!this.window.paypalFastlaneSdk)throw new mi}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,n,i,r){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||r){const r=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i);yield this.loadPayPalSdk(r)}if(!this.window.paypalGooglePay)throw new mi;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t,n){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t,n);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new mi}return this.window.paypalApms})}getPayPalMessages(e,t,n){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t,n);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new mi;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return Qa(this,void 0,void 0,function*(){const n=this.transformConfig(e),i=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(n).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:i})})}getPayPalFastlaneSdkConfiguration(e,t,n,i){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,attributionId:c}=o,l=Za(i);return{options:Object.assign({"client-id":s,"merchant-id":d,commit:!0,components:["fastlane","buttons","payment-fields","hosted-fields","three-domain-secure"],currency:t,intent:a},l&&{locale:l}),attributes:{"data-client-metadata-id":n.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":c,"data-sdk-client-token":r}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i=!0){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:c,attributionId:l,isHostedCheckoutEnabled:u,isDeveloperModeApplicable:h}=o,p=u||i,m=Za(n);return{options:Object.assign(Object.assign({"client-id":s,"merchant-id":d,commit:p,components:["googlepay"],currency:t,intent:a},h&&{"buyer-country":c}),m&&{locale:m}),attributes:{"data-partner-attribution-id":l,"data-client-token":r,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:r,clientId:o,merchantId:a,buyerCountry:s,attributionId:d,isDeveloperModeApplicable:c,availableAlternativePaymentMethods:l=[],enabledAlternativePaymentMethods:u=[]}=i,h=u,p=l.filter(e=>!u.includes(e)),m=Za(n);return{options:Object.assign(Object.assign({"client-id":o,"merchant-id":a,"enable-funding":h.length>0?h:void 0,"disable-funding":p.length>0?p:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:r},c&&{"buyer-country":s}),m&&{locale:m}),attributes:{"data-partner-attribution-id":d,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ti(Xn.MissingPaymentMethod);const{clientId:r,merchantId:o,attributionId:a,isDeveloperModeApplicable:s,buyerCountry:d}=i,c=Za(n);return{options:Object.assign(Object.assign({"client-id":r,"merchant-id":o,components:["messages"],currency:t},s&&{"buyer-country":d}),c&&{locale:c}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":a}}}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}function es(e){if(!function(e){return!!e.initializationData&&"attributionId"in e.initializationData&&"isVenmoEnabled"in e.initializationData&&"isGooglePayEnabled"in e.initializationData&&"isPayPalCreditAvailable"in e.initializationData}(e))throw new ti(Xn.MissingPaymentMethod)}var ts=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ns extends ea{constructor(e,t){super("paypalsb",e),this.payPalCommerceSdk=t,this.service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});var r,o,a,s,d;return ts(this,void 0,void 0,function*(){const c=this.service.getState(),l=null!==(o=null===(r=c.getStoreConfig())||void 0===r?void 0:r.currency.code)&&void 0!==o?o:n;if(!l)throw new ti(Xn.MissingPaymentMethod);yield i.initialize.call(this,e,t,l);const u=i.getPaymentMethod.call(this);if(!u.initializationData)throw new ti(Xn.MissingPaymentMethod);es(u);const h=yield this.payPalCommerceSdk.getPayPalGooglePaySdk(u,l,c.getLocale());this.googlepayConfig=yield h.Googlepay().config();const{allowedPaymentMethods:p}=this.googlepayConfig;this.setGatewayIdentifier(null===(d=null===(s=null===(a=p[0])||void 0===a?void 0:a.tokenizationSpecification)||void 0===s?void 0:s.parameters)||void 0===d?void 0:d.gateway)})}getPaymentGatewayParameters(){if(this.googlepayConfig){const{allowedPaymentMethods:e}=this.googlepayConfig,{gatewayMerchantId:t}=e[0].tokenizationSpecification.parameters;return{gateway:this.getGatewayIdentifier(),gatewayMerchantId:t}}return{gateway:this.getGatewayIdentifier()}}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ts(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n})}}const is=vi(e=>new ra(e,new aa(da(),new ns(e,new Xa(a())),n(),Ee())),[{id:"googlepaypaypalcommerce"}]);var rs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class os extends ea{constructor(e,t){super("googlepay_bigcommerce_payments",e),this.payPalSdkHelper=t,this.service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});var r,o,a,s,d;return rs(this,void 0,void 0,function*(){const c=null!==(o=null===(r=this.service.getState().getStoreConfig())||void 0===r?void 0:r.currency.code)&&void 0!==o?o:n;if(!c)throw new ti(Xn.MissingPaymentMethod);yield i.initialize.call(this,e,t,c);const l=i.getPaymentMethod.call(this);if(!l.initializationData)throw new ti(Xn.MissingPaymentMethod);es(l);const u=yield this.payPalSdkHelper.getPayPalGooglePaySdk(l,c);this.googlepayConfig=yield u.Googlepay().config();const{allowedPaymentMethods:h}=this.googlepayConfig;this.setGatewayIdentifier(null===(d=null===(s=null===(a=h[0])||void 0===a?void 0:a.tokenizationSpecification)||void 0===s?void 0:s.parameters)||void 0===d?void 0:d.gateway)})}getPaymentGatewayParameters(){if(this.googlepayConfig){const{allowedPaymentMethods:e}=this.googlepayConfig,{gatewayMerchantId:t}=e[0].tokenizationSpecification.parameters;return{gateway:this.getGatewayIdentifier(),gatewayMerchantId:t}}return{gateway:this.getGatewayIdentifier()}}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return rs(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n})}}const as=vi(e=>new ra(e,new aa(da(),new os(e,new xr(a())),n(),Ee())),[{id:"googlepay_bigcommerce_payments"}]);function ss(){const{navigator:e}=window;let t;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 ds=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class cs extends ea{constructor(e,t){super("worldlinena",e),this.formPoster=t}extraPaymentData(){return ds(this,void 0,void 0,function*(){return Promise.resolve({browser_info:ss()})})}processAdditionalAction(e){return ds(this,void 0,void 0,function*(){if(!function(e){return pa(e)&&(t=e.body,Z(t)&&"object"==typeof t&&"errors"in t&&"three_ds_result"in t&&W(t.errors)&&ve(t.errors,{code:"three_d_secure_required"}));var t}(e))throw e;const{three_ds_result:t}=e.body,{acs_url:n,payer_auth_request:i,merchant_data:r}=t||{};if(!n||!i||!r)throw new co(["formUrl","threeDSSessionData","creq"]);return new Promise(e=>{this.formPoster.postForm(n,{threeDSSessionData:i,creq:r},e,"_top")})})}}const ls=vi(e=>new ra(e,new aa(da(),new cs(e,Ee()),n(),Ee())),[{id:"googlepaytdonlinemart"}]);var us,hs,ps,ms,ys,gs,vs,fs,Ss,_s,ws=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Is{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,n,i,r){return ws(this,void 0,void 0,function*(){if(!this.window.paypal||r){const r=this.getPayPalSdkScriptConfigOrThrow(e,t,n,i);if(yield this.loadPayPalSdk(r),!this.window.paypal)throw new mi}return this.window.paypal})}getPayPalFastlaneSdk(e,t,n,i){return ws(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const r=this.getPayPalFastlaneSdkConfiguration(e,t,n,i);if(yield this.loadPayPalSdk(r),!this.window.paypalFastlaneSdk)throw new mi}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,n,i,r){return ws(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||r){const r=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i);yield this.loadPayPalSdk(r)}if(!this.window.paypalGooglePay)throw new mi;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t,n){return ws(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t,n);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new mi}return this.window.paypalApms})}getPayPalMessages(e,t,n){return ws(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t,n);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new mi;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return ws(this,void 0,void 0,function*(){const n=this.transformConfig(e),i=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(n).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:i})})}getPayPalSdkScriptConfigOrThrow(e,t,n,i=!0){const{id:r,clientToken:o,initializationData:a}=e;if(!a||!a.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:s,clientId:d,merchantId:c,buyerCountry:l,attributionId:u,isVenmoEnabled:h,isHostedCheckoutEnabled:p,isPayPalCreditAvailable:m,isDeveloperModeApplicable:y,availableAlternativePaymentMethods:g=[],enabledAlternativePaymentMethods:v=[],isGooglePayEnabled:f}=a,S=p||i,_="paypalcommercecreditcards"===r||"bigcommerce_payments_creditcards"===r,w=_?["card"]:[],I=m?["credit","paylater"]:[],C=h?["venmo"]:[],b=f?["googlepay"]:[],P=i?["card-fields"]:[],O=[..._?[]:["card"],...m?[]:["credit","paylater"],...h?[]:["venmo"],...g.filter(e=>!v.includes(e))],E=[...w,...I,...C,...v],A=Za(n);return{options:Object.assign(Object.assign({"client-id":d,"merchant-id":c,"enable-funding":E.length>0?E:void 0,"disable-funding":O.length>0?O:void 0,commit:S,components:["buttons","hosted-fields","payment-fields","legal",...b,...P],currency:t,intent:s},y&&{"buyer-country":l}),A&&{locale:A}),attributes:{"data-partner-attribution-id":u,"data-client-token":o}}}getPayPalFastlaneSdkConfiguration(e,t,n,i){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,attributionId:c}=o,l=Za(i);return{options:Object.assign(Object.assign({"client-id":s,"merchant-id":d,commit:!0,components:["fastlane","buttons","payment-fields","hosted-fields","three-domain-secure"],currency:t},l&&{locale:l}),{intent:a}),attributes:{"data-client-metadata-id":n.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":c,"data-sdk-client-token":r}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i=!0){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:c,attributionId:l,isHostedCheckoutEnabled:u,isDeveloperModeApplicable:h}=o,p=u||i,m=Za(n);return{options:Object.assign(Object.assign({"client-id":s,"merchant-id":d,commit:p,components:["googlepay"],currency:t,intent:a},h&&{"buyer-country":c}),m&&{locale:m}),attributes:{"data-partner-attribution-id":l,"data-client-token":r,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ti(Xn.MissingPaymentMethod);const{intent:r,clientId:o,merchantId:a,buyerCountry:s,attributionId:d,isDeveloperModeApplicable:c,availableAlternativePaymentMethods:l=[],enabledAlternativePaymentMethods:u=[]}=i,h=u,p=l.filter(e=>!u.includes(e)),m=Za(n);return{options:Object.assign(Object.assign({"client-id":o,"merchant-id":a,"enable-funding":h.length>0?h:void 0,"disable-funding":p.length>0?p:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:r},c&&{"buyer-country":s}),m&&{locale:m}),attributes:{"data-partner-attribution-id":d,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ti(Xn.MissingPaymentMethod);const{clientId:r,merchantId:o,attributionId:a,isDeveloperModeApplicable:s,buyerCountry:d}=i,c=Za(n);return{options:Object.assign(Object.assign({"client-id":r,"merchant-id":o,components:["messages"],currency:t},s&&{"buyer-country":d}),c&&{locale:c}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":a}}}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}function Cs(){return new Is(a())}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(us||(us={})),(hs||(hs={})).Always="SCA_ALWAYS",function(e){e.Succeeded="succeeded",e.Cancelled="cancelled",e.Errored="errored"}(ps||(ps={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(ms||(ms={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(ys||(ys={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(gs||(gs={})),function(e){e.pill="pill",e.rect="rect"}(vs||(vs={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="canceled",e.UNRECOGNIZED="unrecognized"}(fs||(fs={})),(Ss||(Ss={})).OXXO="oxxo",function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(_s||(_s={}));var bs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ps{constructor(e,t,n,i){this.formPoster=e,this.paymentIntegrationService=t,this.paypalRequestSender=n,this.paypalSdkLoader=i}loadPayPalSdk(e,t,n,i){return bs(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e),s=r.getLocale();return this.paypalSdk=yield this.paypalSdkLoader.getPayPalSDK(a,o,s,n,i),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new mi;return this.paypalSdk}createBuyNowCartOrThrow(e){return bs(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}})}createOrder(e,t){return bs(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i}=yield this.paypalRequestSender.createOrder(e,Object.assign({cartId:n},t));return i})}createOrderCardFields(e,t){return bs(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i,setupToken:r}=yield this.paypalRequestSender.createOrder(e,Object.assign({cartId:n},t));return Object.assign({orderId:i},r?{setupToken:r}:{})})}updateOrder(e,t,n){return bs(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),r=i.getCartOrThrow(),o=i.getConsignmentsOrThrow()[0];try{yield this.paypalRequestSender.updateOrder(e,Object.assign(Object.assign({availableShippingOptions:o.availableShippingOptions,cartId:r.id,selectedShippingOption:o.selectedShippingOption},t?{methodId:t}:{}),n?{orderId:n}:{}))}catch(e){throw new nr}})}getOrderStatus(e,t){return bs(this,void 0,void 0,function*(){try{const{status:n}=yield this.paypalRequestSender.getOrderStatus(e,t);return n}catch(e){throw new nr}})}tokenizePayment(e,t){const n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new ti(Xn.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===xt.BuyNow&&{cart_id:n.id}))}submitPayment(e,t,n){return bs(this,void 0,void 0,function*(){const i={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}};yield this.paymentIntegrationService.submitPayment(Object.assign({methodId:e,paymentData:i},n?{gatewayId:n}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],i=n.find(e=>e.isRecommended),r=(e?n.find(t=>t.id===e):n.find(e=>{if(t.selectedShippingOption){const n=t.selectedShippingOption.id;return e.id===n}return!1}))||i||n[0];if(!r)throw new Error("Your order can't be shipped to this address");return r}getAddress(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:(null==e?void 0:e.phone)||"",company:"",address1:(null==e?void 0:e.address1)||"",address2:(null==e?void 0:e.address2)||"",city:(null==e?void 0:e.city)||"",countryCode:(null==e?void 0:e.countryCode)||"",postalCode:(null==e?void 0:e.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==e?void 0:e.stateOrProvinceCode)||"",customFields:[]}}getBillingAddressFromOrderDetails({payer:e}){var t,n;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,address2:e.address.address_line_2,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1,phone:null===(n=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===n?void 0:n.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:n}=e,{address:i,name:{full_name:r}}=n[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:i.address_line_1,address2:i.address_line_2,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})}getValidButtonStyle(e={}){const{color:t,height:n,label:i,shape:r}=e,o={color:t&&gs[t]?t:void 0,height:this.getValidHeight(n),label:i&&ys[i]?i:void 0,shape:r&&vs[r]?r:void 0};return ue(o,J)}getValidHeight(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40}removeElement(e){const t=e&&document.getElementById(e);t&&(t.style.display="none")}}var Os=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Es{constructor(e){this.requestSender=e}createOrder(e,t){return Os(this,void 0,void 0,function*(){const n=`/api/storefront/payment/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.post(n,{headers:r,body:i})).body})}updateOrder(e,t){return Os(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.put(n,{headers:r,body:i})).body})}getOrderStatus(e,t){return Os(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body})}}const As=e=>{const{getHost:t}=e.getState();return new Ps(Ee(),e,new Es(n({host:t()})),Cs())};var Ts=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const ks=class{constructor(e,t){this.paymentIntegrationService=e,this.paypalIntegrationService=t}createPayPalButton(e,t,n,i){const{style:r,fundingSource:o,isAppSwitchEnabled:a,isHostedCheckoutEnabled:s,onClick:d,onCancel:c,onPaymentComplete:l,onError:u}=n;this.onError=u;const h=this.paypalIntegrationService.getPayPalSdkOrThrow();if(!Object.values(h.FUNDING).includes(o))throw new fi('Unable to initialize PayPal button because "fundingSource" argument is not valid funding source.');const p=Object.assign(Object.assign({},!a&&{onShippingAddressChange:t=>this.onShippingAddressChange(t,e),onShippingOptionsChange:t=>this.onShippingOptionsChange(t,e)}),{onApprove:(n,i)=>this.onHostedCheckoutApprove(n,i,t,e,l)});return h.Buttons(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({fundingSource:o,style:this.paypalIntegrationService.getValidButtonStyle(r)},a&&{appSwitchWhenAvailable:!0}),{createOrder:()=>Ts(this,void 0,void 0,function*(){if(i){const e=yield this.paypalIntegrationService.createBuyNowCartOrThrow(i);yield this.paymentIntegrationService.loadCheckout(e.id)}return this.paypalIntegrationService.createOrder(e)}),onApprove:({orderID:e})=>this.paypalIntegrationService.tokenizePayment(t,e)}),d?{onClick:d}:{}),c?{onCancel:c}:{}),s&&p))}onHostedCheckoutApprove(e,t,n,i,r){return Ts(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const o=this.paymentIntegrationService.getState().getCartOrThrow(),a=yield t.order.get();try{const t=this.paypalIntegrationService.getBillingAddressFromOrderDetails(a);if(yield this.paymentIntegrationService.updateBillingAddress(t),o.lineItems.physicalItems.length>0){const e=this.paypalIntegrationService.getShippingAddressFromOrderDetails(a);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.paypalIntegrationService.updateOrder(i)}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.paypalIntegrationService.submitPayment(n,e.orderID),r&&"function"==typeof r&&r()}catch(e){this.handleError(e)}})}onShippingAddressChange(e,t){return Ts(this,void 0,void 0,function*(){const n=this.paypalIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(n),yield this.paymentIntegrationService.updateShippingAddress(n);const e=this.paypalIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.paypalIntegrationService.updateOrder(t)}catch(e){this.handleError(e)}})}onShippingOptionsChange(e,t){return Ts(this,void 0,void 0,function*(){const n=this.paypalIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(n.id),yield this.paypalIntegrationService.updateOrder(t)}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}};var Ds=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ms{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.paypalButtonCreationService=n}initialize(e){return Ds(this,void 0,void 0,function*(){const{paypalcommerce:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.paypalcommerce.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.paypalcommerce.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.paypalIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Ds(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return Ds(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){var n,i;const{container:r,onClick:o,onComplete:a,onError:s}=t,d=this.paypalIntegrationService.getPayPalSdkOrThrow(),c=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:l,paymentButtonStyles:u,isAppSwitchEnabled:h}=c.initializationData||{},{checkoutTopButtonStyles:p}=u||{},m=Object.assign(Object.assign(Object.assign({fundingSource:d.FUNDING.PAYPAL,isAppSwitchEnabled:h,isHostedCheckoutEnabled:l,style:Object.assign(Object.assign({},p),{height:wr})},o&&{onClick:()=>o()}),l&&a&&{onPaymentComplete:()=>a()}),{onError:s}),y=this.paypalButtonCreationService.createPayPalButton("paypalcommerce",e,m);y.isEligible()?(null===(n=y.hasReturned)||void 0===n?void 0:n.call(y))&&h?null===(i=y.resume)||void 0===i||i.call(y):y.render(`#${r}`):this.paypalIntegrationService.removeElement(r)}}const zs=vi(e=>{const t=As(e),n=new ks(e,t);return new Ms(e,t,n)},[{id:"paypalcommerce"}]);var Ns,xs,Rs,Fs,Ls,Bs,js;!function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(Ns||(Ns={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(xs||(xs={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Rs||(Rs={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(Fs||(Fs={})),function(e){e.pill="pill",e.rect="rect"}(Ls||(Ls={})),function(e){e.OXXO="oxxo",e.IDEAL="ideal"}(Bs||(Bs={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(js||(js={}));var Us=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class qs{constructor(e,t,n,i){this.formPoster=e,this.paymentIntegrationService=t,this.paypalCommerceRequestSender=n,this.paypalCommerceScriptLoader=i}loadPayPalSdk(e,t,n,i){return Us(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e);return this.paypalSdk=yield this.paypalCommerceScriptLoader.getPayPalSDK(a,o,r.getLocale(),n,i),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new mi;return this.paypalSdk}createBuyNowCartOrThrow(e){return Us(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}})}createOrder(e,t){return Us(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i}=yield this.paypalCommerceRequestSender.createOrder(e,Object.assign({cartId:n},t));return i})}createOrderCardFields(e,t){return Us(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i,setupToken:r}=yield this.paypalCommerceRequestSender.createOrder(e,Object.assign({cartId:n},t));return Object.assign({orderId:i},r?{setupToken:r}:{})})}updateOrder(){return Us(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getConsignmentsOrThrow()[0];try{yield this.paypalCommerceRequestSender.updateOrder({availableShippingOptions:n.availableShippingOptions,cartId:t.id,selectedShippingOption:n.selectedShippingOption})}catch(e){throw new nr}})}getOrderStatus(e,t){return Us(this,void 0,void 0,function*(){try{const{status:n}=yield this.paypalCommerceRequestSender.getOrderStatus(e,t);return n}catch(e){throw new nr}})}tokenizePayment(e,t){const n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new ti(Xn.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===xt.BuyNow&&{cart_id:n.id}))}submitPayment(e,t,n){return Us(this,void 0,void 0,function*(){const i={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}};yield this.paymentIntegrationService.submitPayment(Object.assign({methodId:e,paymentData:i},n?{gatewayId:n}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],i=n.find(e=>e.isRecommended),r=(e?n.find(t=>t.id===e):n.find(e=>{var n;return e.id===(null===(n=t.selectedShippingOption)||void 0===n?void 0:n.id)}))||i||n[0];if(!r)throw new Error("Your order can't be shipped to this address");return r}getAddress(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:(null==e?void 0:e.phone)||"",company:"",address1:(null==e?void 0:e.address1)||"",address2:(null==e?void 0:e.address2)||"",city:(null==e?void 0:e.city)||"",countryCode:(null==e?void 0:e.countryCode)||"",postalCode:(null==e?void 0:e.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==e?void 0:e.stateOrProvinceCode)||"",customFields:[]}}getBillingAddressFromOrderDetails({payer:e}){var t,n;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,address2:e.address.address_line_2,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1,phone:null===(n=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===n?void 0:n.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:n}=e,{address:i,name:{full_name:r}}=n[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:i.address_line_1,address2:i.address_line_2,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})}getValidButtonStyle(e){const{color:t,height:n,label:i,shape:r}=e||{},o={color:t&&Fs[t]?t:void 0,height:this.getValidHeight(n),label:i&&Rs[i]?i:void 0,shape:r&&Ls[r]?r:void 0};return ue(o,J)}getValidHeight(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40}removeElement(e){const t=e&&document.getElementById(e);t&&(t.style.display="none")}}var Vs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Gs{constructor(e){this.requestSender=e}createOrder(e,t){return Vs(this,void 0,void 0,function*(){const n=`/api/storefront/payment/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.post(n,{headers:r,body:i})).body})}updateOrder(e){return Vs(this,void 0,void 0,function*(){const t=e,n=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.put("/api/storefront/initialization/paypalcommerce",{headers:n,body:t})).body})}getOrderStatus(e="paypalcommerce",t){return Vs(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body})}}var Hs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ws{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,n,i,r){return Hs(this,void 0,void 0,function*(){const o=this.getPayPalSdkScriptConfigOrThrow(e,t,n,i);return this.loadPayPalSDK(o,r)})}loadPayPalSDK(e,t=!1){return Hs(this,void 0,void 0,function*(){if(!this.window.paypal||t){const t=this.transformConfig(e.options),n=this.transformConfig(e.attributes),i=`https://www.paypal.com/sdk/js?${new URLSearchParams(t).toString()}`;yield this.scriptLoader.loadScript(i,{async:!0,attributes:n})}if(!this.window.paypal)throw new mi;return this.window.paypal})}getPayPalSdkScriptConfigOrThrow(e,t,n,i=!0){const{id:r,clientToken:o,initializationData:a}=e;if(!(null==a?void 0:a.clientId))throw new ti(Xn.MissingPaymentMethod);const{intent:s,clientId:d,merchantId:c,buyerCountry:l,attributionId:u,isVenmoEnabled:h,isHostedCheckoutEnabled:p,isPayPalCreditAvailable:m,isDeveloperModeApplicable:y,availableAlternativePaymentMethods:g=[],enabledAlternativePaymentMethods:v=[],isGooglePayEnabled:f}=a,S=p||i,_="paypalcommercecreditcards"===r,w=_?["card"]:[],I=m?["credit","paylater"]:[],C=h?["venmo"]:[],b=f?["googlepay"]:[],P=i?["card-fields"]:[],O=[..._?[]:["card"],...m?[]:["credit","paylater"],...h?[]:["venmo"],...g.filter(e=>!v.includes(e))],E=[...w,...I,...C,...v],A=Za(n);return{options:Object.assign(Object.assign({"client-id":d,"merchant-id":c,"enable-funding":E.length>0?E:void 0,"disable-funding":O.length>0?O:void 0,commit:S,components:["buttons","hosted-fields","payment-fields","legal",...b,...P],currency:t,intent:s},y&&{"buyer-country":l}),A&&{locale:A}),attributes:{"data-partner-attribution-id":u,"data-client-token":o}}}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}const $s=e=>{const{getHost:t}=e.getState();return new qs(Ee(),e,new Gs(n({host:t()})),new Ws(a()))};var Ys=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ks{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.onError=ce}initialize(e){return Ys(this,void 0,void 0,function*(){const{paypalcommercecredit:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.paypalcommercecredit.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.paypalcommercecredit.onClick" argument is not a function.');this.onError=t.onError||ce,this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.paypalCommerceIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Ys(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Ys(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){const{container:n,onComplete:i,onClick:r}=t,o=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:s,paymentButtonStyles:d,isAppSwitchEnabled:c}=a.initializationData||{},{checkoutTopButtonStyles:l}=d||{},u=Object.assign({createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercecredit"),onApprove:({orderID:t})=>this.paypalCommerceIntegrationService.tokenizePayment(e,t)},r&&{onClick:()=>r()}),h=Object.assign(Object.assign({},!c&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(t,n)=>this.onHostedCheckoutApprove(t,n,e,i)}),p=[o.FUNDING.PAYLATER,o.FUNDING.CREDIT];let m=!1;p.forEach(e=>{if(!m){const t=Object.assign(Object.assign({fundingSource:e,style:this.paypalCommerceIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},l),{height:wr}))},u),s&&h),i=o.Buttons(t);i.isEligible()&&(i.render(`#${n}`),m=!0)}}),m||this.paypalCommerceIntegrationService.removeElement(n)}onHostedCheckoutApprove(e,t,n,i){return Ys(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.paypalCommerceIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.paypalCommerceIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Ys(this,void 0,void 0,function*(){const t=this.paypalCommerceIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.paypalCommerceIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}onShippingOptionsChange(e){return Ys(this,void 0,void 0,function*(){const t=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.paypalCommerceIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const Js=vi(e=>new Ks(e,$s(e)),[{id:"paypalcommercecredit"}]);var Zs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Qs{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}initialize(e){return Zs(this,void 0,void 0,function*(){const{paypalcommercevenmo:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(!t.container)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.paypalCommerceIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Zs(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Zs(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderButton(e,t){const{container:n,onClick:i}=t,r=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:a}=o.initializationData||{},{checkoutTopButtonStyles:s}=a||{},d=Object.assign({fundingSource:r.FUNDING.VENMO,style:this.paypalCommerceIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},s),{height:wr})),createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo"),onApprove:({orderID:t})=>this.paypalCommerceIntegrationService.tokenizePayment(e,t)},i&&{onClick:()=>i()}),c=r.Buttons(d);c.isEligible()?c.render(`#${n}`):this.paypalCommerceIntegrationService.removeElement(n)}}const Xs=vi(e=>new Qs(e,$s(e)),[{id:"paypalcommercevenmo"}]);var ed=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class td{constructor(){this.window=window}initializePayPalFastlane(e,t,n){return ed(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("fastlaneEnv","sandbox"),window.localStorage.setItem("axoEnv","sandbox")),!this.window.paypalFastlane){const t={root:{backgroundColorPrimary:"transparent"}};this.window.paypalFastlane=yield e.Fastlane({styles:n||t})}return this.window.paypalFastlane})}getPayPalFastlaneOrThrow(){if(!this.window.paypalFastlane)throw new mi;return this.window.paypalFastlane}lookupCustomerOrThrow(e){return ed(this,void 0,void 0,function*(){return this.getPayPalFastlaneOrThrow().identity.lookupCustomerByEmail(e)})}triggerAuthenticationFlowOrThrow(e){return ed(this,void 0,void 0,function*(){return e?this.getPayPalFastlaneOrThrow().identity.triggerAuthenticationFlow(e):{}})}updateStorageSessionId(e){const t=new Date;t.setDate(t.getDate()+14);const n={expires:t,secure:!0};Fr.set("bc-fastlane-sessionId",e,n)}removeStorageSessionId(){Fr.remove("bc-fastlane-sessionId")}getStorageSessionId(){return Fr.get("bc-fastlane-sessionId")||""}mapPayPalFastlaneProfileToBcCustomerData(e,t){var n,i,r;const{authenticationState:o,profileData:a}=t,s=null===(r=null===(i=null===(n=null==a?void 0:a.card)||void 0===n?void 0:n.paymentSource)||void 0===i?void 0:i.card)||void 0===r?void 0:r.billingAddress,d=null==a?void 0:a.shippingAddress,c=null==a?void 0:a.name,l=null==a?void 0:a.card,u=d?this.mapPayPalToBcAddress(d.address,d.name,d.phoneNumber):void 0,h=s&&c?this.mapPayPalToBcAddress(s,c,null==d?void 0:d.phoneNumber):void 0,p=l?this.mapPayPalToBcInstrument(e,l):[],m=this.filterAddresses([u,h]);return{authenticationState:o||fs.UNRECOGNIZED,addresses:m,billingAddress:h,shippingAddress:u,instruments:p}}mapPayPalToBcInstrument(e,t){const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a}=i.card,[s,d]=o.split("-");return[{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:Pr.PAN,type:"card"}]}mapBcToPayPalAddress(e){return{company:(null==e?void 0:e.company)||"",addressLine1:(null==e?void 0:e.address1)||"",addressLine2:(null==e?void 0:e.address2)||"",adminArea1:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",adminArea2:(null==e?void 0:e.city)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||""}}mapPayPalToBcAddress(e,t,n,i){const[r,o]=t.fullName.split(" "),a=(null==n?void 0:n.nationalNumber)||"",s=(null==n?void 0:n.countryCode)||"";return{id:Date.now(),type:"paypal-address",firstName:t.firstName||r||"",lastName:t.lastName||o||"",company:e.company||"",address1:e.addressLine1,address2:e.addressLine2||"",city:e.adminArea2,stateOrProvince:e.adminArea1,stateOrProvinceCode:e.adminArea1,country:e.countryCode||"",countryCode:e.countryCode||"",postalCode:e.postalCode,phone:s+a,customFields:i||[]}}filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this.isEqualAddresses(e,t))?e:[...e,t]:e,[])}isEqualAddresses(e,t){return Y(this.normalizeAddress(e),this.normalizeAddress(t))}normalizeAddress(e){return le(e,["id","phone"])}}function nd(){return new td}function id(e){return"string"!=typeof e}function rd(e,t){if(t||e)return function(e){var t,n;const i={},r=ue(e.root,id),o=ue(e.input,id),a=ue(e.toggle,id),s=ue(null===(t=e.text)||void 0===t?void 0:t.body,id),d=ue(null===(n=e.text)||void 0===n?void 0:n.caption,id),c=e.branding;return Object.keys(r).length&&(i.root=r),Object.keys(o).length&&(i.input=o),Object.keys(a).length&&(i.toggle=a),Object.keys(s).length&&(i.text={},i.text.body=s),Object.keys(d).length&&(i.text=Object.assign({},i.text),i.text.caption=d),c&&(i.branding=c),i}(function(e,t){var n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,_,w,I,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(c=null==t?void 0:t.input)||void 0===c?void 0:c.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.focusBorderColor),backgroundColor:(null==e?void 0:e.fastlaneInputSettingsBackgroundColor)||(null===(u=null==t?void 0:t.input)||void 0===u?void 0:u.backgroundColor),borderWidth:(null==e?void 0:e.fastlaneInputSettingsBorderWidth)||(null===(h=null==t?void 0:t.input)||void 0===h?void 0:h.borderWidth),textColorBase:(null==e?void 0:e.fastlaneInputSettingsTextColorBase)||(null===(p=null==t?void 0:t.input)||void 0===p?void 0:p.textColorBase)},toggle:{colorPrimary:(null==e?void 0:e.fastlaneToggleSettingsColorPrimary)||(null===(m=null==t?void 0:t.toggle)||void 0===m?void 0:m.colorPrimary),colorSecondary:(null==e?void 0:e.fastlaneToggleSettingsColorSecondary)||(null===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(S=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===S?void 0:S.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(w=null===(_=null==t?void 0:t.text)||void 0===_?void 0:_.caption)||void 0===w?void 0:w.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(I=null==t?void 0:t.text)||void 0===I?void 0:I.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var od=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ad{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalSdkScriptLoader=t,this.paypalFastlaneUtils=n}initialize(e){var t;return od(this,void 0,void 0,function*(){const{methodId:n,paypalcommercefastlane:i}=e;if(!n)throw new fi('Unable to proceed because "methodId" argument is not provided.');try{yield this.paymentIntegrationService.loadPaymentMethod(n);const e=this.paymentIntegrationService.getState(),r=e.getCartOrThrow(),o=e.getPaymentMethodOrThrow(n),a=!!(null===(t=o.initializationData)||void 0===t?void 0:t.isDeveloperModeApplicable),s=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(o,r.currency.code,r.id,e.getLocale());yield this.paypalFastlaneUtils.initializePayPalFastlane(s,a,this.getFastlaneStyles(n,i))}catch(e){}return Promise.resolve()})}deinitialize(){return od(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return od(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:void 0,addresses:void 0,instruments:void 0}),this.paypalFastlaneUtils.removeStorageSessionId()})}signOut(e){return od(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return od(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:n,methodId:i}=e||{};if(!i)throw new fi('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof n)throw new fi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(this.paymentIntegrationService.getState().getCustomerOrThrow().isGuest){t&&"function"==typeof t&&t();try{yield this.runPayPalAuthenticationFlowOrThrow(i)}catch(e){}}n()})}runPayPalAuthenticationFlowOrThrow(e){return od(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow().id,i=t.getCustomer(),r=t.getBillingAddress(),o=(null==i?void 0:i.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.paypalFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.paypalFastlaneUtils.triggerAuthenticationFlowOrThrow(a),d=s.authenticationState===fs.CANCELED;yield this.updateCustomerDataState(e,s),d?this.paypalFastlaneUtils.removeStorageSessionId():this.paypalFastlaneUtils.updateStorageSessionId(n)})}updateCustomerDataState(e,t){var n;return od(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow(),{authenticationState:r,addresses:o,billingAddress:a,shippingAddress:s,instruments:d}=this.paypalFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,t);if(yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:r,addresses:o,instruments:d}),a&&(yield this.paymentIntegrationService.updateBillingAddress(a)),s&&i.lineItems.physicalItems.length>0){const t=yield this.paymentIntegrationService.updateShippingAddress(s),i=t.getPaymentMethodOrThrow(e),{isFastlaneShippingOptionAutoSelectEnabled:r}=i.initializationData||{},o=t.getConsignments()||[],a=(null===(n=o[0])||void 0===n?void 0:n.availableShippingOptions)||[],d=a[0],c=a.find(e=>e.isRecommended);if((c||d)&&r){const e=(null==c?void 0:c.id)||d.id;yield this.paymentIntegrationService.selectShippingOption(e)}}})}getFastlaneStyles(e,t){const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{fastlaneStyles:i,isFastlaneStylingEnabled:r}=n.initializationData||{};return rd(r?i:{},null==t?void 0:t.styles)}}const sd=vi(e=>new ad(e,Cs(),nd()),[{id:"paypalcommerceacceleratedcheckout"},{id:"paypalcommercecreditcards"}]);function dd(e){return"object"==typeof e&&null!==e&&"initializationData"in e&&void 0!==e.initializationData&&null!==e.initializationData&&"object"==typeof e.initializationData&&"stripePublishableKey"in e.initializationData&&"stripeConnectedAccount"in e.initializationData&&"shopperLanguage"in e.initializationData&&void 0!==e.initializationData.stripePublishableKey&&void 0!==e.initializationData.stripeConnectedAccount&&void 0!==e.initializationData.shopperLanguage}function cd(e){return"stripeLinkAuthenticationState"in e}class ld{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){var t,n,i,r,o;return n=this,i=void 0,o=function*(){let n;if(!e.stripeupe)throw new fi('Unable to proceed because "options" argument is not provided.');const{container:i,gatewayId:r,methodId:o,onEmailChange:a,getStyles:s,isLoading:d}=e.stripeupe;Object.entries(e.stripeupe).forEach(([e,t])=>{if(!t)throw new fi(`Unable to proceed because "${e}" argument is not provided.`)}),yield this.paymentIntegrationService.loadPaymentMethod(r,{params:{method:o}});const c=this.paymentIntegrationService.getState(),l=c.getPaymentMethodOrThrow(o,r),{clientToken:u}=l;if(!dd(l)||!u)throw new ti(Xn.MissingPaymentToken);const{email:h}=c.getCustomerOrThrow(),p=c.getPaymentProviderCustomerOrThrow(),m=(cd(p)?p:{}).stripeLinkAuthenticationState;if(!h){let e;const r="function"==typeof s&&s();e=r?{variables:{colorPrimary:r.fieldInnerShadow,colorBackground:r.fieldBackground,colorText:r.labelText,colorDanger:r.fieldErrorText,colorTextSecondary:r.labelText,colorTextPlaceholder:r.fieldPlaceholderText},rules:{".Input":{borderColor:r.fieldBorder,color:r.fieldText,boxShadow:r.fieldInnerShadow}}}:{},n=yield this.scriptLoader.getStripeClient(l.initializationData,c.getCartLocale(),ka.V3,Fa,La),this._stripeElements=yield this.scriptLoader.getElements(n,{clientSecret:u,appearance:e});const{getBillingAddress:o,getConsignments:h}=this.paymentIntegrationService.getState(),p=h(),y=null===(t=null==p?void 0:p[0])||void 0===t?void 0:t.id,{email:g}=o()||{},v=g?{defaultValues:{mode:Ca.SHIPPING,email:g}}:{},f=this._stripeElements.getElement(Da.AUTHENTICATION)||this._stripeElements.create(Da.AUTHENTICATION,v);f.on(za.CHANGE,e=>{if(!("authenticated"in e))throw new ti(Xn.MissingCustomer);this.paymentIntegrationService.updatePaymentProviderCustomer({stripeLinkAuthenticationState:e.authenticated}),e.complete?a(e.authenticated,e.value.email):a(!1,""),d&&d(!1),void 0===m&&e.authenticated&&y&&this.paymentIntegrationService.deleteConsignment(y)}),f.mount(`#${i}`)}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}deinitialize(){var e,t;return null===(t=null===(e=this._stripeElements)||void 0===e?void 0:e.getElement(Da.AUTHENTICATION))||void 0===t||t.unmount(),Promise.resolve()}signIn(e,t){return this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()}signOut(e){return this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}}const ud=vi(e=>new ld(e,new Ra(a())),[{id:"stripeupe"}]);var hd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pd{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t,this.isMounted=!1}deinitialize(){var e;null===(e=this.checkoutEventsUnsubscribe)||void 0===e||e.call(this),this.isMounted=!1}initCheckoutEventsSubscription(e,t,n,i){this.checkoutEventsUnsubscribe=this.paymentIntegrationService.subscribe(()=>hd(this,void 0,void 0,function*(){var r;const o=null==i?void 0:i.getElement(Da.PAYMENT);if(o){try{yield this.updateStripePaymentIntent(e,t)}catch(e){return this.isMounted&&(o.unmount(),this.isMounted=!1),void(e instanceof Error&&(null===(r=n.onError)||void 0===r||r.call(n,e)))}this.isMounted||(yield null==i?void 0:i.fetchUpdates(),this.mountElement(o,n.containerId))}}),e=>{var t;return null===(t=e.getCheckout())||void 0===t?void 0:t.outstandingBalance},e=>{var t;return null===(t=e.getCheckout())||void 0===t?void 0:t.coupons})}mountElement(e,t){document.getElementById(t)&&(e.mount(`#${t}`),this.isMounted=!0)}mapAppearanceVariables(e){return{colorPrimary:e.fieldInnerShadow,colorBackground:e.fieldBackground,colorText:e.labelText,colorDanger:e.fieldErrorText,colorTextSecondary:e.labelText,colorTextPlaceholder:e.fieldPlaceholderText,colorIcon:e.fieldPlaceholderText}}mapInputAppearanceRules(e){return{borderColor:e.fieldBorder,color:e.fieldText,boxShadow:e.fieldInnerShadow}}throwStripeError(e){if("object"==typeof(t=e)&&null!==t&&"type"in t&&(this.throwDisplayableStripeError(e),this.isCancellationError(e)))throw new Wi;var t;throw new Qr}throwDisplayableStripeError(e){if(H(["card_error","invalid_request_error","validation_error"],e.type))throw new Error(e.message)}isCancellationError(e){var t;const n=null===(t=null==e?void 0:e.payment_intent.last_payment_error)||void 0===t?void 0:t.message;return!!n&&-1!==n.indexOf("canceled")}throwPaymentConfirmationProceedMessage(){throw new Qr("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.")}isPaymentCompleted(e,t){return hd(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getPaymentMethodOrThrow(e),{features:r}=n.getStoreConfigOrThrow().checkoutSettings;if(!i.clientToken||!t||!r["PI-626.Block_unnecessary_payment_confirmation_for_StripeUPE"])return!1;const{paymentIntent:o}=yield t.retrievePaymentIntent(i.clientToken);return(null==o?void 0:o.status)===Ma.SUCCEEDED})}mapStripePaymentData(e,t,n=!1){const i=this.paymentIntegrationService.getState().getBillingAddress(),{firstName:r="",lastName:o="",email:a=""}=i||{},s=this.mapStripeAddress(i);if(!e)throw new ri(ei.PaymentNotInitialized);if(!(a&&s&&s.city&&s.country&&r&&o))throw new ti(Xn.MissingBillingAddress);return{elements:e,redirect:Ta.IF_REQUIRED,confirmParams:Object.assign({payment_method_data:Object.assign(Object.assign({},n?{allow_redisplay:"always"}:{}),{billing_details:{email:a,address:s,name:this.getShopperFullName(i)}})},t&&{return_url:t})}}isAdditionalActionError(e){return ve(e,{code:"additional_action_required"})}isRedirectAction(e){const{type:t,data:{redirect_url:n}}=e;return"redirect_to_url"===t&&!!n}isOnPageAdditionalAction(e){const{type:t,data:{token:n}}=e;return"additional_action_requires_payment_method"===t&&!!n}updateStripePaymentIntent(e,t){return hd(this,void 0,void 0,function*(){const n=yield this.paymentIntegrationService.loadPaymentMethod(e,{params:{method:t}}),{clientToken:i}=n.getPaymentMethodOrThrow(t);i&&this.scriptLoader.updateStripeElements({clientSecret:i})})}getStripeJsVersion(e){return e.useNewStripeJsVersion?ka.CLOVER:ka.V3}mapStripeAddress(e){if(e){const{city:t,address1:n,address2:i,countryCode:r,postalCode:o,stateOrProvinceCode:a}=e;return Object.assign({city:t,country:r,postal_code:o,line1:n,line2:i},a?{state:a}:{})}throw new ti(Xn.MissingBillingAddress)}getShopperFullName(e){const{firstName:t="",lastName:n=""}=e||{};return`${t} ${n}`.trim()}}const md={size:70,color:"#d9d9d9",backgroundColor:"#ffffff"},yd={position:"fixed","background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},gd="embedded-checkout-loading-indicator-rotation";class vd{constructor(e){this.styles=Object.assign(Object.assign({},md),e&&e.styles),this.containerStyles=Object.assign({},e&&e.containerStyles),this.defineAnimation(),this.container=this.buildContainer(),this.indicator=this.buildIndicator(),this.container.appendChild(this.indicator)}show(e){if(e){const t=document.getElementById(e);if(!t)throw new Error("Unable to attach the loading indicator because the parent ID is not valid.");t.appendChild(this.container)}this.container.style.visibility="visible",this.container.style.opacity="1"}hide(){const e=()=>{this.container.style.visibility="hidden",this.container.removeEventListener("transitionend",e)};this.container.addEventListener("transitionend",e),this.container.style.opacity="0"}buildContainer(){const e=document.createElement("div");return e.style.display="block",e.style.bottom="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.position="absolute",e.style.right="0",e.style.top="0",e.style.transition="all 250ms ease-out",e.style.opacity="0",this.setStyleAttribute(e,this.containerStyles),e}buildIndicator(){const e=document.createElement("div");return e.style.display="block",e.style.width=`${this.styles.size}px`,e.style.height=`${this.styles.size}px`,e.style.borderRadius=`${this.styles.size}px`,e.style.border="solid 1px",e.style.borderColor=`${this.styles.backgroundColor} ${this.styles.backgroundColor} ${this.styles.color} ${this.styles.color}`,e.style.margin="0 auto",e.style.position="absolute",e.style.left="0",e.style.right="0",e.style.top="50%",e.style.transform="translateY(-50%) rotate(0deg)",e.style.transformStyle="preserve-3d",e.style.animation=`${gd} 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)`,e}setStyleAttribute(e,t){Object.keys(t).forEach(n=>{e.style.setProperty(n,t[n])})}defineAnimation(){var e;if(document.getElementById(gd))return;const t=document.createElement("style");t.id=gd,null===(e=document.head)||void 0===e||e.appendChild(t),t.sheet instanceof CSSStyleSheet&&t.sheet.insertRule(`\n @keyframes ${gd} {\n 0% { transform: translateY(-50%) rotate(0deg); }\n 100% { transform: translateY(-50%) rotate(360deg); }\n }\n `,0)}}class fd{constructor(e){this._decimalPlaces=e}toInteger(e){return Math.round(e*Math.pow(10,this._decimalPlaces))}}const Sd=["AC","AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CV","CW","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MK","ML","MM","MN","MO","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SZ","TA","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","US","UY","UZ","VA","VC","VE","VG","VN","VU","WF","WS","XK","YE","YT","ZA","ZM","ZW","ZZ"];var _d=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class wd{constructor(e,t,n,i){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n,this.loadingIndicator=i}initialize(e){return _d(this,void 0,void 0,function*(){const{stripeocs:t}=e||{};if(!t)throw new fi('Unable to proceed because "options" argument is not provided.');const{gatewayId:n,container:i}=t;if(!i||!n)throw new ri(ei.PaymentNotInitialized);const r=this._getMethodId(n),o=yield this.paymentIntegrationService.loadPaymentMethod(n,{params:{method:r}}),a=o.getPaymentMethodOrThrow(r,n),{loadingContainerId:s,buttonHeight:d,onComplete:c}=t;if(this._loadingIndicatorContainer=s,this._onComplete=c,!dd(a))throw new ti(Xn.MissingPaymentMethod);const{initializationData:l}=a,{captureMethod:u}=l,h=this.stripeIntegrationService.getStripeJsVersion(l);this._captureMethod=u,this._stripeClient=yield this.scriptLoader.getStripeClient(l,o.getCartLocale(),h),yield this._mountExpressCheckoutElement(i,this._stripeClient,d),this._initializeEvents(r)})}signIn(){return Promise.resolve()}signOut(){return Promise.resolve()}executePaymentMethodCheckout(){return Promise.resolve()}deinitialize(){return Promise.resolve()}_mountExpressCheckoutElement(e,t,n=40){return _d(this,void 0,void 0,function*(){const i=this._shouldRequireShippingAddress(),r=Object.assign(Object.assign(Object.assign({shippingAddressRequired:i},i?{allowedShippingCountries:yield this._getAvailableCountries()}:{}),i?{shippingRates:[{id:"_",amount:0,displayName:"Pending rates"}]}:{}),{billingAddressRequired:!0,emailRequired:!0,phoneNumberRequired:!0,paymentMethods:{link:Ta.AUTO,applePay:Ta.NEVER,googlePay:Ta.NEVER,amazonPay:Ta.NEVER,paypal:Ta.NEVER,klarna:Ta.NEVER},buttonHeight:n}),{cartAmount:o}=this.paymentIntegrationService.getState().getCartOrThrow(),a=Object.assign({mode:"payment",amount:this._toCents(o),currency:this._getCurrency()},this._captureMethod?{captureMethod:this._captureMethod}:{});return this._stripeElements=t.elements(a),this._linkV2Element=this._stripeElements.create(Da.EXPRESS_CHECKOUT,r),this._linkV2Element.mount(`#${e}`),this._linkV2Element})}_initializeEvents(e){this._linkV2Element&&(this._shouldRequireShippingAddress()&&(this._linkV2Element.on(za.SHIPPING_ADDRESS_CHANGE,e=>_d(this,void 0,void 0,function*(){return this._onShippingAddressChange(e)})),this._linkV2Element.on(za.SHIPPING_RATE_CHANGE,e=>_d(this,void 0,void 0,function*(){return this._onShippingRateChange(e)}))),this._linkV2Element.on(za.CONFIRM,t=>_d(this,void 0,void 0,function*(){return this._onConfirm(t,e)})),this._linkV2Element.on(za.CANCEL,this._onCancel))}_onShippingAddressChange(e){return _d(this,void 0,void 0,function*(){if(!("address"in e))return;const t=e.address,n={firstName:"",lastName:"",phone:"",company:"",address1:"",address2:"",city:(null==t?void 0:t.city)||"",countryCode:(null==t?void 0:t.country)||"",postalCode:(null==t?void 0:t.postal_code)||"",stateOrProvince:(null==t?void 0:t.state)||"",stateOrProvinceCode:(null==t?void 0:t.state)||"",customFields:[]};yield this.paymentIntegrationService.updateShippingAddress(n);const i=yield this._getAvailableShippingOptions();yield this._updateDisplayedPrice(),(null==i?void 0:i.length)?e.resolve({shippingRates:i}):e.reject()})}_onCancel(){throw new Wi}_onShippingRateChange(e){return _d(this,void 0,void 0,function*(){if("shippingRate"in e){const{shippingRate:t}=e;yield this._handleShippingOptionChange(null==t?void 0:t.id),yield this._updateDisplayedPrice(),e.resolve({})}})}_onConfirm(e,t){return _d(this,void 0,void 0,function*(){if("billingDetails"in e&&"shippingAddress"in e&&this._stripeClient&&this._stripeElements){yield this._updateShippingAndBillingAddress(e),yield this.paymentIntegrationService.submitOrder();const n=this._getPaymentPayload(t);try{yield this.paymentIntegrationService.submitPayment(n)}catch(e){yield this._processAdditionalAction(e,t)}}return Promise.resolve()})}_updateShippingAndBillingAddress(e){var t,n,i,r,o,a,s,d;return _d(this,void 0,void 0,function*(){const c=this._shouldRequireShippingAddress(),l=(null===(n=null===(t=e.shippingAddress)||void 0===t?void 0:t.name)||void 0===n?void 0:n.split(" ")[0])||(null===(r=null===(i=e.billingDetails)||void 0===i?void 0:i.name)||void 0===r?void 0:r.split(" ")[0])||"",u=(null===(a=null===(o=e.shippingAddress)||void 0===o?void 0:o.name)||void 0===a?void 0:a.split(" ")[1])||(null===(d=null===(s=e.billingDetails)||void 0===s?void 0:s.name)||void 0===d?void 0:d.split(" ")[1])||"";if(c){const t=this._mapShippingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateShippingAddress(t)}const h=this._mapBillingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateBillingAddress(h)})}_mapShippingAddress(e,t,n,i){var r,o,a,s,d,c,l;return{firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==e?void 0:e.address)||void 0===r?void 0:r.line1)||"",address2:(null===(o=null==e?void 0:e.address)||void 0===o?void 0:o.line2)||"",city:(null===(a=null==e?void 0:e.address)||void 0===a?void 0:a.city)||"",countryCode:(null===(s=null==e?void 0:e.address)||void 0===s?void 0:s.country)||"",postalCode:(null===(d=null==e?void 0:e.address)||void 0===d?void 0:d.postal_code)||"",stateOrProvince:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",stateOrProvinceCode:(null===(l=null==e?void 0:e.address)||void 0===l?void 0:l.state)||"",customFields:[]}}_mapBillingAddress(e,t,n,i){var r,o,a,s,d,c;return{email:(null==t?void 0:t.email)||"",firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==t?void 0:t.address)||void 0===r?void 0:r.line1)||"",address2:"",city:(null===(o=null==t?void 0:t.address)||void 0===o?void 0:o.city)||"",countryCode:(null===(a=null==t?void 0:t.address)||void 0===a?void 0:a.country)||"",postalCode:(null===(s=null==t?void 0:t.address)||void 0===s?void 0:s.postal_code)||"",stateOrProvince:(null===(d=null==t?void 0:t.address)||void 0===d?void 0:d.state)||"",stateOrProvinceCode:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",customFields:[]}}_processAdditionalAction(e,t){return _d(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeClient||!this._stripeElements)throw new ri(ei.PaymentNotInitialized);const{data:n}=e.body.additional_action_required,{token:i}=n,{paymentIntent:r}=yield this._confirmStripePaymentOrThrow(n,t),o=this._getPaymentPayload(t,(null==r?void 0:r.id)||i);try{this._toggleLoadingIndicator(!0),yield this.paymentIntegrationService.submitPayment(o),yield this._completeCheckoutFlow()}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}finally{this._toggleLoadingIndicator(!1)}})}_confirmStripePaymentOrThrow(e,t){var n,i,r;return _d(this,void 0,void 0,function*(){const{token:o,redirect_url:a}=e,s=this.stripeIntegrationService.mapStripePaymentData(this._stripeElements,a);let d;try{const e=(yield this.stripeIntegrationService.isPaymentCompleted(t,this._stripeClient))?yield null===(r=this._stripeClient)||void 0===r?void 0:r.retrievePaymentIntent(o||""):yield null===(n=this._stripeClient)||void 0===n?void 0:n.confirmPayment({elements:s.elements,clientSecret:o,redirect:Ta.IF_REQUIRED,confirmParams:{return_url:null===(i=s.confirmParams)||void 0===i?void 0:i.return_url}});if(d=null==e?void 0:e.error,d||!(null==e?void 0:e.paymentIntent))throw new Qr;return e}catch(e){return this.stripeIntegrationService.throwStripeError(d)}})}_completeCheckoutFlow(){return _d(this,void 0,void 0,function*(){return"function"==typeof this._onComplete?this._onComplete():(window.location.replace("/order-confirmation"),Promise.resolve())})}_getPaymentPayload(e,t){var n;const i=(null===(n=this.paymentIntegrationService.getState().getCart())||void 0===n?void 0:n.id)||"";return{methodId:e,paymentData:{formattedPayload:Object.assign(Object.assign({cart_id:i},t?{credit_card_token:{token:t}}:{}),{confirm:!1,method:Aa.Link})}}}_shouldRequireShippingAddress(){const{getCartOrThrow:e}=this.paymentIntegrationService.getState(),{lineItems:t}=e();return!!t.physicalItems.length}_updateDisplayedPrice(){return _d(this,void 0,void 0,function*(){this._stripeElements&&this._stripeElements.update({currency:this._getCurrency(),mode:"payment",amount:yield this._getTotalPrice()})})}_getCurrency(){if(!this._currencyCode){const{code:e}=this.paymentIntegrationService.getState().getCartOrThrow().currency;this._currencyCode=e.toLowerCase()}return this._currencyCode}_getTotalPrice(){return _d(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const{getCheckoutOrThrow:e,getCartOrThrow:t}=this.paymentIntegrationService.getState(),{decimalPlaces:n}=t().currency,i=ge(e().outstandingBalance,n).toFixed(n);return this._toCents(+i)})}_getAvailableCountries(){var e;return _d(this,void 0,void 0,function*(){const t=yield this.paymentIntegrationService.loadShippingCountries();return((null===(e=t.getShippingCountries())||void 0===e?void 0:e.map(e=>e.code))||[]).filter(e=>Sd.includes(e))})}_getAvailableShippingOptions(){var e,t,n;return _d(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getConsignments();if(!(null==i?void 0:i[0]))return;const r=i[0],o=(r.availableShippingOptions||[]).map(this._getStripeShippingOption.bind(this)),a=null===(e=r.availableShippingOptions)||void 0===e?void 0:e.find(e=>e.isRecommended),s=null===(t=r.selectedShippingOption)||void 0===t?void 0:t.id,d=null==a?void 0:a.id;return s?o.sort(e=>e.id===s?-1:0):d?(o.sort(e=>e.id===d?-1:0),yield this._handleShippingOptionChange(d)):yield this._handleShippingOptionChange(null===(n=o[0])||void 0===n?void 0:n.id),o.slice(0,9)})}_getStripeShippingOption({id:e,cost:t,description:n}){return{id:e,displayName:n,amount:this._toCents(t)}}_handleShippingOptionChange(e){return _d(this,void 0,void 0,function*(){if(e&&"shipping_option_unselected"!==e)return this.paymentIntegrationService.selectShippingOption(e)})}_getAmountTransformer(){if(this._amountTransformer)return this._amountTransformer;const{getCart:e}=this.paymentIntegrationService.getState(),{currency:t}=e()||{};return t?new fd(t.decimalPlaces):void 0}_toCents(e){const t=Math.round(100*e),n=this._getAmountTransformer();return n?n.toInteger(e):t}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this.loadingIndicator.show(this._loadingIndicatorContainer):this.loadingIndicator.hide()}_getMethodId(e){const{initializationData:{checkoutSessionEnabled:t}={}}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e);return t?Aa.CHECKOUT_SESSION:Aa.OCS}}const Id=vi(e=>{const t=new Ra(a()),n=new vd({containerStyles:yd});return new wd(e,t,new pd(e,t),n)},[{id:"stripeocs"}]);class Cd extends Qn{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}class bd{constructor(e){this._paymentIntegrationService=e}execute(e,t){return n=this,i=void 0,o=function*(){yield this._paymentIntegrationService.submitOrder(le(e,"payment"),t)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const Pd=vi(e=>new bd(e),[{id:"nopaymentdatarequired"}]);var Od,Ed,Ad,Td,kd,Dd,Md;class zd{constructor(e,t,n=window){this._scriptLoader=e,this._stylesheetLoader=t,this._window=n}load(e){var t,n,i,r,o,a;return i=this,r=void 0,a=function*(){if(yield Promise.all([this._stylesheetLoader.loadStylesheet(`https://checkoutshopper-${null!==(t=e.environment)&&void 0!==t?t:""}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.css`,{prepend:!1,attributes:{integrity:"sha384-8ofgICZZ/k5cC5N7xegqFZOA73H9RQ7H13439JfAZW8Gj3qjuKL2isaTD3GMIhDE",crossorigin:"anonymous"}}),this._scriptLoader.loadScript(`https://checkoutshopper-${null!==(n=e.environment)&&void 0!==n?n:""}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.js`,{async:!0,attributes:{integrity:"sha384-wG2z9zSQo61EIvyXmiFCo+zB3y0ZB4hsrXVcANmpP8HLthjoQJQPBh7tZKJSV8jA",crossorigin:"anonymous"}})]),!this._window.AdyenCheckout)throw new mi;return new this._window.AdyenCheckout(e)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}}function Nd(e){return"object"==typeof e&&"string"==typeof e.data.paymentMethod.encryptedSecurityCode||"string"==typeof e.data.paymentMethod.encryptedExpiryMonth}function xd(e){return Boolean(e.instrumentId)}!function(e){e.ThreeDS2Fingerprint="threeDS2Fingerprint",e.ThreeDS2="threeDS2",e.Redirect="redirect",e.QRCode="qrCode",e.Voucher="voucher",e.Sdk="sdk"}(Od||(Od={})),function(e){e.ThreeDS2Fingerprint="threeDS2Fingerprint",e.ThreeDS2Challenge="threeDS2Challenge",e.Redirect="redirect",e.QRCode="qrCode",e.Voucher="voucher"}(Ed||(Ed={})),function(e){e.SecuredFields="securedfields"}(Ad||(Ad={})),function(e){e.ACH="ach",e.AliPay="alipay",e.Bancontact="bcmc",e.CreditCard="scheme",e.Klarna="klarna",e.KlarnaPayNow="klarna_paynow",e.KlarnaAccount="klarna_account",e.IDEAL="ideal",e.GiroPay="giropay",e.GooglePay="paywithgoogle",e.SEPA="sepadirectdebit",e.Sofort="directEbanking",e.Vipps="vipps",e.WeChatPayQR="wechatpayQR"}(Td||(Td={})),function(e){e.POST="POST"}(kd||(kd={})),function(e){e.ChallengeShopper="ChallengeShopper",e.Error="Error",e.IdentifyShopper="IdentifyShopper"}(Dd||(Dd={})),function(e){e.CardNumber="encryptedCardNumber",e.SecurityCode="encryptedSecurityCode",e.ExpiryDate="encryptedExpiryDate"}(Md||(Md={}));var Rd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Fd{constructor(e,t){this._paymentIntegrationService=e,this._scriptLoader=t}initialize(e){return Rd(this,void 0,void 0,function*(){const{adyenv2:t}=e;if(!t)throw new fi('Unable to initialize payment because "options.adyenv2" argument is not provided.');this._paymentInitializeOptions=t;const n=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{originKey:i,clientKey:r,environment:o,paymentMethodsResponse:a}=n.initializationData||{},s={key:"",value:""};return i?(s.key="originKey",s.value=i):(s.key="clientKey",s.value=r||""),this._adyenClient=yield this._scriptLoader.load({environment:o,locale:this._paymentIntegrationService.getState().getLocale(),[s.key]:s.value,paymentMethodsResponse:a,translations:{es:{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-AR":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-ES":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-MX":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CL":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CO":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-PE":{"creditCard.expiryDateField.title":"Fecha de caducidad"}}}),this._paymentComponent=yield this._mountPaymentComponent(n),n.method!==Td.CreditCard&&n.method!==Td.Bancontact||(this._cardVerificationComponent=yield this._mountCardVerificationComponent()),Promise.resolve()})}execute(e,t){return Rd(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const{threeDS2ContainerId:i,additionalActionOptions:r}=this._getPaymentInitializeOptions(),{onBeforeLoad:o,containerId:a,onLoad:s,onComplete:d}=r,c=JSON.parse(e.action),l=this._getAdyenClient().createFromAction(c,{onAdditionalDetails:e=>{const n={methodId:c.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};d&&d(),t(n)},size:this._getThreeDS2ChallengeWidgetSize(),onError:e=>n(e)});o&&o(c.type===Ed.ThreeDS2Challenge||c.type===Ed.QRCode),l.mount(`#${a||i}`),s&&s(()=>{n(new Wi),l.unmount()})})}_mapAdyenPlaceholderData(e,t){if(!e)return{};const{firstName:n,lastName:i,address1:r,address2:o,postalCode:a,city:s,stateOrProvinceCode:d,countryCode:c}=e;return{holderName:t?`${n} ${i}`:"",billingAddress:{street:r,houseNumberOrName:o,postalCode:a,city:s,stateOrProvince:d,country:c}}}_mountCardVerificationComponent(){const e=this._getPaymentInitializeOptions(),t=this._getAdyenClient();let n;return new Promise((i,r)=>{var o,a,s;if(e.cardVerificationContainerId){n=t.create(Ad.SecuredFields,Object.assign(Object.assign({},e.options),{styles:Object.assign(Object.assign({},null===(o=e.options)||void 0===o?void 0:o.styles),{placeholder:Object.assign({color:"transparent",caretColor:"#000"},null===(s=null===(a=e.options)||void 0===a?void 0:a.styles)||void 0===s?void 0:s.placeholder)}),onChange:e=>this._updateComponentState(e),onError:t=>e.validateCardFields(t),onFieldValid:t=>e.validateCardFields(t)}));try{n.mount(`#${e.cardVerificationContainerId}`)}catch(e){r(new ri(ei.PaymentNotInitialized))}}i(n)})}_mountPaymentComponent(e){let t;const n=this._getPaymentInitializeOptions(),i=this._getAdyenClient();return new Promise((r,o)=>{switch(e.method){case Td.CreditCard:case Td.ACH:case Td.Bancontact:{const r=this._paymentIntegrationService.getState().getBillingAddress(),{prefillCardHolderName:a}=e.initializationData;t=i.create(e.method,Object.assign(Object.assign({},n.options),{onChange:e=>this._updateComponentState(e),data:this._mapAdyenPlaceholderData(r,a)}));try{t.mount(`#${n.containerId}`)}catch(e){o(new ri(ei.PaymentNotInitialized))}break}case Td.IDEAL:case Td.SEPA:if(n.hasVaultedInstruments)this._updateComponentState({data:{paymentMethod:{type:e.method}}});else{t=i.create(e.method,Object.assign(Object.assign({},n.options),{onChange:e=>this._updateComponentState(e)}));try{t.mount(`#${n.containerId}`)}catch(e){o(new ri(ei.PaymentNotInitialized))}}break;case Td.AliPay:case Td.GiroPay:case Td.Sofort:case Td.Klarna:case Td.KlarnaPayNow:case Td.KlarnaAccount:case Td.Vipps:case Td.WeChatPayQR:this._updateComponentState({data:{paymentMethod:{type:e.method}}})}r(t)})}_processAdditionalAction(e,t,n){return Rd(this,void 0,void 0,function*(){if(!pa(e)||!ve(e.body.errors,{code:"additional_action_required"}))throw e;const i=yield this._handleAction(e.body.provider_data);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:Object.assign(Object.assign({},i.paymentData),{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n})}))}catch(e){return this._processAdditionalAction(e,t,n)}})}_updateComponentState(e){this._componentState=e}_validateCardData(){var e,t;const n=this._getPaymentInitializeOptions().hasVaultedInstruments?this._cardVerificationComponent:this._paymentComponent;if((null===(e=null==n?void 0:n.componentRef)||void 0===e?void 0:e.showValidation)&&n.state&&(n.componentRef.showValidation(),0===Object.keys(n.state).length||!n.state.isValid&&!n.state.issuer||"sepadirectdebit"===(null===(t=n.props)||void 0===t?void 0:t.type)&&n.state.data&&Object.values(n.state.data).some(e=>0===e.toString().trim().length)))throw new lo(this._mapCardErrors(n.state.errors))}_mapCardErrors(e={}){const t={};return Object.keys(e).forEach(n=>{t[n]=[{message:e[n],type:n}]}),t}}const Ld=vi(e=>new Fd(e,new zd(a(),s())),[{gateway:"adyenv2"}]);class Bd{constructor(e,t,n=window){this._scriptLoader=e,this._stylesheetLoader=t,this._window=n}load(e){var t,n,i,r,o,a;return i=this,r=void 0,a=function*(){if(yield Promise.all([this._stylesheetLoader.loadStylesheet(`https://checkoutshopper-${null!==(t=e.environment)&&void 0!==t?t:""}.adyen.com/checkoutshopper/sdk/5.71.1/adyen.css`,{prepend:!1,attributes:{integrity:"sha384-5MvB4RnzvviA3VBT4KYABZ4HXNZG5LRqREEgd41xt/pf/QvKmsj2O9GuNuywRXx9",crossorigin:"anonymous"}}),this._scriptLoader.loadScript(`https://checkoutshopper-${null!==(n=e.environment)&&void 0!==n?n:""}.adyen.com/checkoutshopper/sdk/5.71.1/adyen.js`,{async:!0,attributes:{integrity:"sha384-yvY2yFNR4WqIjPqP9MzjI+gJimmaJnAvj4rLHKvgJbgFD5fMuf8zIJrFJOW8Lhhf",crossorigin:"anonymous"}})]),!this._window.AdyenCheckout)throw new mi;return yield this._window.AdyenCheckout(e)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}}function jd(e){return!("object"!=typeof e||null===e||void 0!==e.shouldSaveInstrument&&"boolean"!=typeof e.shouldSaveInstrument||void 0!==e.shouldSetAsDefaultInstrument&&"boolean"!=typeof e.shouldSetAsDefaultInstrument)}var Ud=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class qd{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){return Ud(this,void 0,void 0,function*(){const{adyenv3:t}=e;if(!t)throw new fi('Unable to initialize payment because "options.adyenv3" argument is not provided.');this.paymentInitializeOptions=t;const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{environment:i,clientKey:r,paymentMethodsResponse:o,installmentOptions:a}=n.initializationData||{};return this.adyenClient=yield this.scriptLoader.load({paymentMethodsConfiguration:Object.assign({klarna:{useKlarnaWidget:!0},klarna_account:{useKlarnaWidget:!0},klarna_paynow:{useKlarnaWidget:!0}},a?{card:{installmentOptions:Object.assign({showInstallmentAmounts:!0},a)}}:{}),environment:i,locale:this._getLocale(),clientKey:r,paymentMethodsResponse:o,showPayButton:!1,translations:{es:{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-AR":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-ES":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-MX":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CL":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CO":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-PE":{"creditCard.expiryDateField.title":"Fecha de caducidad"}}}),this.paymentComponent=yield this._mountPaymentComponent(n),n.method!==Td.CreditCard&&n.method!==Td.Bancontact||(this.cardVerificationComponent=yield this._mountCardVerificationComponent()),Promise.resolve()})}execute(e,t){var n;return Ud(this,void 0,void 0,function*(){const{payment:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const{additionalActionOptions:i}=this._getPaymentInitializeOptions(),{onBeforeLoad:r,containerId:o,onLoad:a,onComplete:s,widgetSize:d,onActionHandled:c}=i,l=JSON.parse(e.action),u=this._getAdyenClient().createFromAction(l,{onActionHandled:e=>{c&&"function"==typeof c&&"3DS2Fingerprint"!==e.componentType&&c()},onAdditionalDetails:e=>{const n={methodId:l.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};s&&"function"==typeof s&&s(),t(n)},challengeWindowSize:d||"05",onError:e=>n(e)});r&&"function"==typeof r&&r(l.type===Od.ThreeDS2||l.type===Od.QRCode||l.type===Od.Sdk),this._mountElement(u,o).then(()=>{a&&"function"==typeof a&&a(()=>{n(new Wi),u.unmount()})}).catch(n)})}_mapAdyenPlaceholderData(e,t){if(!e)return{};const{firstName:n,lastName:i,address1:r,address2:o,postalCode:a,city:s,stateOrProvinceCode:d,countryCode:c}=e;return{holderName:t?`${n} ${i}`:"",firstName:t?n:"",lastName:t?i:"",billingAddress:{street:r,houseNumberOrName:o,postalCode:a,city:s,stateOrProvince:d,country:c}}}_mountCardVerificationComponent(){var e,t,n;return Ud(this,void 0,void 0,function*(){const i=this._getPaymentInitializeOptions(),r=this._getAdyenClient();if(!i.cardVerificationContainerId)return;const o=r.create(Ad.SecuredFields,Object.assign(Object.assign({},i.options),{styles:Object.assign(Object.assign({},null===(e=i.options)||void 0===e?void 0:e.styles),{placeholder:Object.assign({color:"transparent",caretColor:"#000"},null===(n=null===(t=i.options)||void 0===t?void 0:t.styles)||void 0===n?void 0:n.placeholder)}),onChange:e=>this._updateComponentState(e),onError:e=>i.validateCardFields(e),onFieldValid:e=>i.validateCardFields(e)}));try{yield this._mountElement(o,i.cardVerificationContainerId)}catch(e){throw new ri(ei.PaymentNotInitialized)}return o})}_mountPaymentComponent(e){return Ud(this,void 0,void 0,function*(){const t=this._getPaymentInitializeOptions(),n=this._getAdyenClient(),i=this.paymentIntegrationService.getState().getBillingAddress(),{prefillCardHolderName:r}=e.initializationData,o=n.create(e.method,Object.assign(Object.assign(Object.assign(Object.assign({},this._isOneyPaymentMethod(e.method)?{visibility:{personalDetails:"hidden",billingAddress:"hidden",deliveryAddress:"hidden"}}:{}),t.options),{showBrandsUnderCardNumber:!1,billingAddressRequired:!1,showEmailAddress:!1,onChange:e=>this._updateComponentState(e),onSubmit:e=>this._updateComponentState(e)}),i?{data:this._mapAdyenPlaceholderData(i,r)}:{}));try{yield this._mountElement(o,t.containerId)}catch(e){throw new ri(ei.PaymentNotInitialized)}return o})}_isOneyPaymentMethod(e){return e.startsWith("facilypay")}_processAdditionalAction(e,t,n,i,r){return Ud(this,void 0,void 0,function*(){if(!pa(e)||!ve(e.body.errors,{code:"additional_action_required"}))throw e;const o=yield this._handleAction(e.body.provider_data);try{const e=Object.assign(Object.assign({},o.paymentData),{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n}),a=n&&!t?{instrumentId:i,formattedPayload:{bigpay_token:Object.assign(Object.assign({},r),{token:i})}}:{};yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},o),{paymentData:Object.assign(Object.assign({},e),a)}))}catch(e){return this._processAdditionalAction(e,t,n,i,r)}})}_validateCardData(){var e;const t=this._getPaymentInitializeOptions().hasVaultedInstruments?this.cardVerificationComponent:this.paymentComponent;if((null===(e=null==t?void 0:t.componentRef)||void 0===e?void 0:e.showValidation)&&t.state&&(t.componentRef.showValidation(),0===Object.keys(t.state).length||!t.state.isValid))throw new lo(this._mapCardErrors(t.state.errors))}_mapCardErrors(e={}){const t={};return Object.keys(e).forEach(n=>{t[n]=[{message:e[n],type:n}]}),t}_mountElement(e,t){return Ud(this,void 0,void 0,function*(){yield this._waitForMountContainer(t);try{e.mount(`#${t}`)}catch(e){throw new ri(ei.PaymentNotInitialized)}})}_waitForMountContainer(e){return Ud(this,void 0,void 0,function*(){const t=Math.ceil(qd.mountContainerMaxWaitMs/qd.mountContainerPollIntervalMs),n=qd.mountContainerPollIntervalMs;let i=0;const r=()=>Ud(this,void 0,void 0,function*(){if(i===t)throw new ri(ei.PaymentNotInitialized);document.getElementById(e)||(yield new Promise(e=>{setTimeout(e,n)}),i+=1,yield r())});yield r()})}}qd.mountContainerMaxWaitMs=5e3,qd.mountContainerPollIntervalMs=50;const Vd=vi(e=>new qd(e,new Bd(a(),s())),[{gateway:"adyenv3"}]);var Gd,Hd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Wd{constructor(e,t){this.paymentIntegrationService=e,this.affirmScriptLoader=t}initialize(e){return Hd(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadPaymentMethod(e.methodId);const t=this.paymentIntegrationService.getState(),{clientToken:n,config:{testMode:i}}=t.getPaymentMethodOrThrow(e.methodId);if(!n)throw new ti(Xn.MissingPaymentMethod);this.affirm=yield this.affirmScriptLoader.load(n,i)})}execute(e,t){var n;return Hd(this,void 0,void 0,function*(){const i=null===(n=e.payment)||void 0===n?void 0:n.methodId,{useStoreCredit:r}=e;if(!this.affirm)throw new ri(ei.PaymentNotInitialized);if(!i)throw new co(["payment.methodId"]);yield this.paymentIntegrationService.submitOrder({useStoreCredit:r},t);const o={methodId:i,paymentData:{nonce:(yield this.initializeAffirmCheckout()).checkout_token}};yield this.paymentIntegrationService.submitPayment(o)})}deinitialize(){return this.affirm&&(this.affirm=void 0),Promise.resolve()}finalize(){return Promise.reject(new Cd)}initializeAffirmCheckout(){var e;return null===(e=this.affirm)||void 0===e||e.checkout(this.getCheckoutInformation()),new Promise((e,t)=>{var n,i;null===(n=this.affirm)||void 0===n||n.checkout.open({onFail:e=>{"canceled"===e.reason?t(new Wi):t(new Xr)},onSuccess:t=>{e(t)}}),null===(i=this.affirm)||void 0===i||i.ui.error.on("close",()=>{t(new Wi)})})}getCheckoutInformation(){const e=this.paymentIntegrationService.getState(),t=e.getStoreConfig(),n=e.getConsignments(),i=e.getOrder(),r=e.getCart();if(!t)throw new ti(Xn.MissingCheckoutConfig);if(!i)throw new ti(Xn.MissingCheckout);const o=new fd(i.currency.decimalPlaces),a=this.getBillingAddress(),s=this.getShippingAddress(),d=jo(r,t)&&s?s:a;return{merchant:{user_confirmation_url:t.links.checkoutLink,user_cancel_url:t.links.checkoutLink,user_confirmation_url_action:"POST"},shipping:d,billing:a,items:this.getItems(o,i),metadata:{shipping_type:this.getShippingType(n),mode:"modal",platform_type:"BigCommerce",platform_version:"",platform_affirm:""},discounts:this.getDiscounts(o,i),order_id:i.orderId?i.orderId.toString():"",shipping_amount:o.toInteger(i.shippingCostTotal),tax_amount:o.toInteger(i.taxTotal),total:o.toInteger(i.orderAmount)}}getShippingType(e){if(!e)return"";const t=e[0];return(null==t?void 0:t.selectedShippingOption)?t.selectedShippingOption.type:""}getBillingAddress(){const e=this.paymentIntegrationService.getState().getBillingAddress();if(!e)throw new ti(Xn.MissingBillingAddress);return{name:{first:e.firstName,last:e.lastName,full:`${e.firstName} ${e.lastName}`},address:{line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,zipcode:e.postalCode,country:e.countryCode},phone_number:e.phone,email:e.email}}getShippingAddress(){const e=this.paymentIntegrationService.getState().getShippingAddress();if(e)return{name:{first:e.firstName,last:e.lastName,full:`${e.firstName} ${e.lastName}`},address:{line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,zipcode:e.postalCode,country:e.countryCode},phone_number:e.phone}}getItems(e,t){const n=[];return t.lineItems.physicalItems.forEach(t=>{n.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.salePrice),qty:t.quantity,item_image_url:t.imageUrl,item_url:t.url,categories:this.getCategories(t.categories)})}),t.lineItems.digitalItems.forEach(t=>{n.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.salePrice),qty:t.quantity,item_image_url:t.imageUrl,item_url:t.url,categories:this.getCategories(t.categories)})}),t.lineItems.giftCertificates.forEach(t=>{n.push({display_name:t.name,sku:"",unit_price:e.toInteger(t.amount),qty:1,item_image_url:"",item_url:""})}),t.lineItems.customItems&&t.lineItems.customItems.forEach(t=>{n.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.listPrice),qty:t.quantity,item_image_url:"",item_url:""})}),n}getDiscounts(e,t){const n={};return t.coupons.forEach(t=>{t.discountedAmount>0&&(n[t.code]={discount_amount:e.toInteger(t.discountedAmount),discount_display_name:t.displayName})}),t.discountAmount>0&&(n.DISCOUNTED_AMOUNT={discount_amount:e.toInteger(t.discountAmount),discount_display_name:"discount"}),n}getCategories(e){return e?e.map(e=>e.map(e=>e.name)):[[]]}}!function(e){e.PROD="//cdn1.affirm.com/js/v2/affirm.js",e.SANDBOX="//cdn1-sandbox.affirm.com/js/v2/affirm.js"}(Gd||(Gd={}));class $d{constructor(e=window){this.affirmWindow=e}load(e="",t){const n=t?Gd.SANDBOX:Gd.PROD;if(function(e,t,n,i,r,o,a){const s=e[n]||{},d=document.createElement(o),c=document.getElementsByTagName(o)[0],l=function(e,t,n){return function(){e[t]._.push([n,arguments])}};s[i]=l(s,i,"set");const u=s[i];s[r]={},s[r]._=[],u._=[],s._=[],s[r][a]=l(s,r,a),s.jsReady=function(){s._.push([a,arguments])};let h=0;for(const e="set add save post open empty reset on off trigger ready setProduct".split(" ");hnew Wd(e,new $d),[{id:"affirm"}]);class Kd extends Qn{constructor(e){super(e||"The current order could not be finalized successfully"),this.name="OrderFinalizationNotCompletedError",this.type="order_finalization_not_completed"}}var Jd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Zd{constructor(e,t){this._paymentIntegrationService=e,this._afterpayScriptLoader=t}initialize(e){var t;return Jd(this,void 0,void 0,function*(){const n=this._paymentIntegrationService.getState(),i=n.getPaymentMethod(e.methodId,e.gatewayId),r=(null===(t=n.getCart())||void 0===t?void 0:t.currency.code)||"",o=this._mapCurrencyToISO2(r),a=Ci(n.getStoreConfigOrThrow().checkoutSettings.features,"PI-4789.afterpay_script_use_https",!1);if(!i)throw new ti(Xn.MissingPaymentMethod);this._afterpaySdk=yield this._afterpayScriptLoader.load(i,o,a)})}deinitialize(){return this._afterpaySdk&&(this._afterpaySdk=void 0),Promise.resolve()}execute(e,t){var n;return Jd(this,void 0,void 0,function*(){if(!e.payment)throw new co(["payment.gatewayId","payment.methodId"]);const{gatewayId:i,methodId:r}=e.payment;if(!i||!r)throw new co(["payment.gatewayId","payment.methodId"]);const{useStoreCredit:o}=e;void 0!==o&&(yield this._paymentIntegrationService.applyStoreCredit(o)),yield this._loadPaymentMethod(i,r,t);const a=this._paymentIntegrationService.getState();yield this._paymentIntegrationService.validateCheckout(a.getCheckout(),t);const s=(null===(n=a.getCart())||void 0===n?void 0:n.currency.code)||"",d=this._mapCurrencyToISO2(s);return this._redirectToAfterpay(d,a.getPaymentMethod(r,i)),new Promise(()=>{})})}finalize(e){var t,n,i;return Jd(this,void 0,void 0,function*(){const r=this._paymentIntegrationService.getState(),o=r.getPaymentId(),a=r.getContextConfig();if(!o)throw new ti(Xn.MissingCheckout);if(!(null==a?void 0:a.payment.token))throw new ti(Xn.MissingCheckoutConfig);const s={methodId:o.providerId,paymentData:{nonce:a.payment.token}};yield this._paymentIntegrationService.submitOrder({},e);try{yield this._paymentIntegrationService.submitPayment(s)}catch(e){if(yield this._paymentIntegrationService.forgetCheckout(o.providerId),yield this._paymentIntegrationService.loadPaymentMethods(),pa(e))throw new Kd(null===(i=null===(n=null===(t=e.body)||void 0===t?void 0:t.errors)||void 0===n?void 0:n[0])||void 0===i?void 0:i.message)}})}_redirectToAfterpay(e,t){if(!this._afterpaySdk||!(null==t?void 0:t.clientToken))throw new ri(ei.PaymentNotInitialized);this._afterpaySdk.initialize({countryCode:e}),this._afterpaySdk.redirect({token:t.clientToken})}_mapCurrencyToISO2(e){return{AUD:"AU",NZD:"NZ",CAD:"CA",USD:"US"}[e]||"AU"}_loadPaymentMethod(e,t,n){var i;return Jd(this,void 0,void 0,function*(){try{return yield this._paymentIntegrationService.loadPaymentMethod(e,Object.assign(Object.assign({},n),{params:Object.assign(Object.assign({},null==n?void 0:n.params),{method:t})}))}catch(e){if(e instanceof nr&&422===(null===(i=e.body)||void 0===i?void 0:i.status))throw new fi("Afterpay can't process your payment for this order, please try another payment method");throw e}})}}var Qd,Xd;!function(e){e.PROD="//portal.afterpay.com/afterpay-async.js",e.SANDBOX="//portal.sandbox.afterpay.com/afterpay.js",e.HTTPS_PROD="https://portal.afterpay.com/afterpay-async.js",e.HTTPS_SANDBOX="https://portal.sandbox.afterpay.com/afterpay.js"}(Qd||(Qd={})),function(e){e.PROD="//portal.afterpay.com/afterpay-async.js",e.SANDBOX="//portal.sandbox.afterpay.com/afterpay.js",e.HTTPS_PROD="https://portal.afterpay.com/afterpay-async.js",e.HTTPS_SANDBOX="https://portal.sandbox.afterpay.com/afterpay.js"}(Xd||(Xd={}));class ec{constructor(e){this._scriptLoader=e}load(e,t,n=!1){return i=this,r=void 0,a=function*(){const i=e.config.testMode||!1,r=this._getScriptURI(t,i,n);return this._scriptLoader.loadScript(r).then(()=>{if(!function(e){return"AfterPay"in e}(window))throw new mi;return window.AfterPay})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a}_getScriptURI(e,t,n=!1){return"US"===e?n?t?Xd.HTTPS_SANDBOX:Xd.HTTPS_PROD:t?Xd.SANDBOX:Xd.PROD:n?t?Qd.HTTPS_SANDBOX:Qd.HTTPS_PROD:t?Qd.SANDBOX:Qd.PROD}}const tc=vi(e=>new Zd(e,new ec(o())),[{gateway:"afterpay"},{id:"afterpay"}]);var nc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ic{constructor(e,t){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t}initialize(e){return nc(this,void 0,void 0,function*(){const{methodId:t,amazonpay:n}=e;if(!t)throw new fi('Unable to proceed because "methodId" argument is not provided.');const i=this.paymentIntegrationService.getState(),{features:r}=i.getStoreConfigOrThrow().checkoutSettings,o=i.getPaymentMethodOrThrow(t),a=o.initializationData||{},{paymentToken:s="",region:d="",isButtonMicroTextDisabled:c}=a;if(yield this.amazonPayV2PaymentProcessor.initialize(o),this._isReadyToPay(s))(null==n?void 0:n.editButtonId)&&this._bindEditButton(n.editButtonId,s,"changePayment",this._isModalFlow(d));else{const{id:e}=this._createContainer();if(this._amazonPayButton=this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:i,containerId:e,decoupleCheckoutInitiation:this._isOneTimeTransaction(r,d.toUpperCase()),methodId:t,placement:si.Checkout,isButtonMicroTextDisabled:c}),!this._amazonPayButton)throw new fi("Unable to render the Amazon Pay button to an invalid HTML container element.")}})}execute(e,t){return nc(this,void 0,void 0,function*(){const{payment:n}=e;if(!n)throw new co(["payment"]);const{methodId:i}=n,r=this.paymentIntegrationService.getState(),{features:o}=r.getStoreConfigOrThrow().checkoutSettings,a=r.getPaymentMethodOrThrow(i).initializationData||{},{paymentToken:s="",region:d=""}=a;if(this._isReadyToPay(s)||this._isOneTimeTransaction(o,d.toUpperCase())){const n={methodId:i,paymentData:{nonce:s||"apb"}};yield this.paymentIntegrationService.submitOrder(e,t);try{return void(yield this.paymentIntegrationService.submitPayment(n))}catch(e){if(!(pa(e)&&(c=e.body,"object"==typeof c&&null!==c&&"status"in c&&"additional_action_required"in c&&"additional_action_required"===c.status&&"data"in c.additional_action_required&&"redirect_url"in c.additional_action_required.data&&"string"==typeof c.additional_action_required.data.redirect_url)))throw e;const{additional_action_required:t}=e.body,{redirect_url:n}=t.data;if(s)return new Promise(()=>window.location.assign(n));this.amazonPayV2PaymentProcessor.prepareCheckout(JSON.parse(n))}}var c;return this._getAmazonPayButton().click(),this._isModalFlow(d)?new Promise((e,t)=>{const n=()=>{window.removeEventListener("focus",n),t(new Wi("Shopper needs to login to Amazonpay to continue"))};window.addEventListener("focus",n)}):new Promise(ce)})}finalize(){return Promise.reject(new Cd)}deinitialize(){return nc(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize(),this._amazonPayButton=void 0})}_bindEditButton(e,t,n,i){const r=document.getElementById(e);if(r&&r.parentNode){if(!i){const e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener("click",()=>{this._showLoadingSpinner()})}this.amazonPayV2PaymentProcessor.bindButton(e,t,n)}}_isModalFlow(e){return"us"===e}_showLoadingSpinner(){return nc(this,void 0,void 0,function*(){yield this.paymentIntegrationService.widgetInteraction(()=>new Promise(ce))})}_createContainer(){let e=document.getElementById("AmazonPayButton");return e||(e=document.createElement("div"),e.id="AmazonPayButton",e.style.display="none",document.body.appendChild(e))}_getAmazonPayButton(){return ii(this._amazonPayButton,()=>new ri(ei.PaymentNotInitialized))}_isOneTimeTransaction(e,t){return this.amazonPayV2PaymentProcessor.isPh4Enabled(e,t)&&e["INT-6399.amazon_pay_apb"]}_isReadyToPay(e){return!!e}}const rc=vi(e=>new ic(e,gi()),[{id:"amazonpay"}]);var oc,ac=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.Shipping="Shipping",e.Subtotal="Subtotal",e.StoreCredit="Store Credit"}(oc||(oc={}));class sc{constructor(e,t,n,i,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._braintreeSdk=i,this._applePayScriptLoader=r,this._shippingLabel=oc.Shipping,this._subTotalLabel=oc.Subtotal,this._storeCreditLabel=oc.StoreCredit}initialize(e){var t,n,i,r;return ac(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new fi('Unable to submit payment because "options.methodId" argument is not provided.');const{methodId:o}=e;yield this._applePayScriptLoader.loadSdk(),this._shippingLabel=(null===(t=e.applepay)||void 0===t?void 0:t.shippingLabel)||oc.Shipping,this._subTotalLabel=(null===(n=e.applepay)||void 0===n?void 0:n.subtotalLabel)||oc.Subtotal,this._storeCreditLabel=(null===(i=e.applepay)||void 0===i?void 0:i.storeCreditLabel)||oc.StoreCredit;const a=(yield this._paymentIntegrationService.loadPaymentMethod(o)).getPaymentMethodOrThrow(o);(null===(r=a.initializationData)||void 0===r?void 0:r.gateway)===Vi.BRAINTREE&&a.clientToken&&this._braintreeSdk.initialize(a.clientToken)})}execute(e,t){return ac(this,void 0,void 0,function*(){const{payment:n}=e,i=this._paymentIntegrationService.getState();if(!n)throw new co(["payment"]);const{methodId:r}=n,o=i.getPaymentMethodOrThrow(r),a=this._getBaseRequest(i,o),s=this._sessionFactory.create(a);return yield this._paymentIntegrationService.submitOrder({useStoreCredit:e.useStoreCredit},t),s.begin(),new Promise((e,t)=>{this._handleApplePayEvents(s,o,{resolve:e,reject:t})})})}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_getBaseRequest(e,t){const n=e.getCheckoutOrThrow(),i=e.getCartOrThrow(),r=e.getStoreConfigOrThrow(),{storeProfile:{storeCountryCode:o,storeName:a}}=r,{currency:{code:s,decimalPlaces:d}}=i,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=t,{grandTotal:u,isStoreCreditApplied:h,outstandingBalance:p}=n,m=[{label:this._subTotalLabel,amount:`${n.subtotal.toFixed(d)}`}];if(n.taxes.forEach(e=>m.push({label:e.name,amount:`${e.amount.toFixed(d)}`})),m.push({label:this._shippingLabel,amount:`${n.shippingCostTotal.toFixed(d)}`}),h){const{storeCredit:t}=e.getCustomerOrThrow();m.push({label:this._storeCreditLabel,amount:`-${Math.min(u,t).toFixed(d)}`})}return{countryCode:o,currencyCode:s,merchantCapabilities:c,supportedNetworks:l,lineItems:m,total:{label:a,amount:`${p.toFixed(d)}`,type:"final"}}}_handleApplePayEvents(e,t,n){e.onvalidatemerchant=n=>ac(this,void 0,void 0,function*(){try{const{body:i}=yield this._onValidateMerchant(t,n);e.completeMerchantValidation(i)}catch(e){throw new Error("Merchant validation failed")}}),e.oncancel=()=>ac(this,void 0,void 0,function*(){return n.reject(new Wi("Continue with applepay"))}),e.onpaymentauthorized=i=>this._onPaymentAuthorized(i,e,t,n)}_onValidateMerchant(e,t){return ac(this,void 0,void 0,function*(){const n=[`validationUrl=${t.validationURL}`,`merchantIdentifier=${e.initializationData.merchantId}`,`displayName=${e.initializationData.storeName}`,`domainName=${window.location.hostname}`].join("&");return this._requestSender.post(`${e.initializationData.paymentsUrl}/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})})}_onPaymentAuthorized(e,t,n,i){var r;return ac(this,void 0,void 0,function*(){const{token:o}=e.payment;let a;(null===(r=n.initializationData)||void 0===r?void 0:r.gateway)===Vi.BRAINTREE&&(a=yield this._getBraintreeDeviceData());const s={methodId:n.id,paymentData:{deviceSessionId:a,formattedPayload:{apple_pay_token:{payment_data:o.paymentData,payment_method:o.paymentMethod,transaction_id:o.transactionIdentifier}}}};try{return yield this._paymentIntegrationService.submitPayment(s),t.completePayment(ApplePaySession.STATUS_SUCCESS),i.resolve()}catch(e){return t.completePayment(ApplePaySession.STATUS_FAILURE),i.reject(new ri(ei.PaymentNotInitialized))}})}_getBraintreeDeviceData(){return ac(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}const dc=vi(e=>{const{getHost:t}=e.getState(),i=new Ei(e);return new sc(n({host:t()}),e,new Zi,new Ui(new Hi(a(),window,i)),new Qi(new r))},[{id:"applepay"}]),cc={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},lc=function({styles:e}){const t={};return e.color&&(t.color=e.color),e.layout&&(t.layout=e.layout),(e["logo-type"]||e["logo-position"])&&(t.logo={},e["logo-type"]&&(t.logo.type=e["logo-type"]),e["logo-position"]&&(t.logo.position=e["logo-position"])),e.ratio&&(t.ratio=e.ratio),(e["text-color"]||e["text-size"])&&(t.text={},e["text-color"]&&(t.text.color=e["text-color"]),e["text-size"]&&(t.text.size=+e["text-size"])),t};function uc(e){return"object"==typeof e&&null!==e&&"bigpayToken"in e&&"defaultInstrument"in e&&"provider"in e&&"trustedShippingAddress"in e&&"method"in e&&"type"in e}var hc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.paypalSdkHelper=n,this.loadingIndicator=i}initialize(e){return hc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments:n}=e||{};if(this.bigcommerce_payments=n,!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(t),{container:o,bannerContainerId:a}=n,{orderId:s,paypalBNPLConfiguration:d=[],isPayPalCreditAvailable:c}=r.initializationData||{};if(void 0!==a){if(!document.getElementById(a))return void console.error("Unable to create banner without valid banner container ID.");const e=null==d?void 0:d.find(({id:e})=>"checkout"===e);if(c||!(null==e?void 0:e.status))return;const t=yield this.paypalSdkHelper.getPayPalMessages(r,i.getCartOrThrow().currency.code);return t&&"function"==typeof(null==t?void 0:t.Messages)?this.renderMessages(t,a,e):void console.error("[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK")}s?this.orderId=s:(this.loadingIndicatorContainer=null==o?void 0:o.split("#")[1],yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t),n.onInit&&"function"==typeof n.onInit&&n.onInit(()=>this.renderButton(t,n)),(void 0===n.shouldRenderPayPalButtonOnInitialization||n.shouldRenderPayPalButtonOnInitialization)&&this.renderButton(t,n))})}execute(e,t){return hc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{var i;this.bigcommerce_payments&&(null===(i=this.paypalButton)||void 0===i||i.close(),this.renderButton(n.methodId,this.bigcommerce_payments),this.handleError(new Error("INSTRUMENT_DECLINED"),r)),t()})),this.handleError(e,r),Promise.reject()}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}prepareVaultedInstrumentPaymentPayload(e,t,n){const{instrumentId:i,shouldSetAsDefaultInstrument:r}=n,o=!this.isTrustedVaultingFlow(n);return o?{methodId:e,paymentData:{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}:{methodId:e,paymentData:{instrumentId:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t},bigpay_token:{token:i}}}}}preparePaymentPayload(e,t,n){const{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:r=!1}=jd(n)?n:{};return{methodId:e,paymentData:{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}}renderButton(e,t){var n,i,r,o;const a=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:d}=s.initializationData||{},{checkoutPaymentButtonStyles:c}=d||{},{container:l,onError:u,onRenderButton:h,onValidate:p,submitForm:m}=t;if(!l)throw new fi('Unable to initialize payment because "container" argument is not provided.');const y=Object.assign(Object.assign({},this.isAppSwitchEnabled(e)&&{appSwitchWhenAvailable:!0}),{fundingSource:a.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(c),createOrder:()=>this.createOrder(),onClick:(e,t)=>this.handleClick(t,p),onApprove:e=>this.handleApprove(e,m),onError:e=>this.handleError(e,u),onCancel:()=>this.toggleLoadingIndicator(!1)});this.paypalButton=a.Buttons(y),this.paypalButton.isEligible()&&(h&&"function"==typeof h&&h(),(null===(i=(n=this.paypalButton).hasReturned)||void 0===i?void 0:i.call(n))&&this.isAppSwitchEnabled(e)?null===(o=(r=this.paypalButton).resume)||void 0===o||o.call(r):this.paypalButton.render(l))}handleClick(e,t){return hc(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;yield null==t?void 0:t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,null==t||t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createOrder(){return hc(this,void 0,void 0,function*(){const e=this.getFieldsValues();return this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_paymentscheckout",{shouldSaveInstrument:(null==e?void 0:e.shouldSaveInstrument)||!1})})}getFieldsValues(){const{getFieldsValues:e}=this.bigcommerce_payments||{};return"function"==typeof e?e():void 0}isTrustedVaultingFlow(e){if(e&&xd(e)){const t=this.paymentIntegrationService.getState().getInstruments(),n=null==t?void 0:t.find(t=>uc(t)&&t.bigpayToken===e.instrumentId);return!(uc(n)&&!n.trustedShippingAddress)}return!1}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isPayPalVaultedInstrumentPaymentData(e){return!!e&&xd(e)&&jd(e)}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:lc(n)};e.Messages(i).render(`#${t}`)}isProviderError(e){var t,n,i;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"INSTRUMENT_DECLINED"===(null===(i=null===(n=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===n?void 0:n.provider_error)||void 0===i?void 0:i.code)}isAppSwitchEnabled(e){var t,n;return null!==(n=null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)&&void 0!==n&&n}}const mc=vi(e=>new pc(e,_r(e),Rr(),new vd({containerStyles:cc})),[{id:"bigcommerce_payments"}]);function yc(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var gc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsRequestSender=t,this.bigCommercePaymentsSdk=n,this.bigCommercePaymentsFastlaneUtils=i}initialize(e){var t,n;return gc(this,void 0,void 0,function*(){const{methodId:i,bigcommerce_payments_fastlane:r}=e;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(this.methodId=i,!r)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_fastlane" argument is not provided.');if(this.bigcommerce_payments_fastlane=r,!r.onInit||"function"!=typeof r.onInit)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_fastlane.onInit" argument is not provided or it is not a function.');if(!r.onChange||"function"!=typeof r.onChange)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_fastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState(),a=o.getCartOrThrow(),s=o.getPaymentMethodOrThrow(i),{isDeveloperModeApplicable:d,isFastlaneStylingEnabled:c}=s.initializationData||{};this.threeDSVerificationMethod=null===(t=s.initializationData)||void 0===t?void 0:t.threeDSVerificationMethod,this.paypalFastlaneSdk=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(s,a.currency.code,a.id);const l=qr(c?null===(n=null==s?void 0:s.initializationData)||void 0===n?void 0:n.fastlaneStyles:{},null==r?void 0:r.styles);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(this.paypalFastlaneSdk,!!d,l),this.shouldRunAuthenticationFlow()&&(yield this.runPayPalAuthenticationFlowOrThrow(i)),yield this.initializePayPalPaymentComponent(),r.onInit(e=>this.renderPayPalPaymentComponent(e)),r.onChange(()=>this.handlePayPalStoredInstrumentChange(i))})}execute(e,t){return gc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const{getHost:t}=e.getState();return new vc(e,new vr(n({host:t()})),Rr(),jr())},[{id:"bigcommerce_payments_fastlane"}]);var Sc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class _c{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=n,this.paypalSdkHelper=i}initialize(e){return Sc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_paylater:n}=e||{};if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(t),{paypalBNPLConfiguration:o=[],orderId:a}=r.initializationData||{},{bannerContainerId:s,container:d}=n;if(void 0!==s){if(!document.getElementById(s))return void console.error("Unable to create banner without valid banner container ID.");const e=o&&o.find(({id:e})=>"checkout"===e);if(!(null==e?void 0:e.status))return;const t=yield this.paypalSdkHelper.getPayPalMessages(r,i.getCartOrThrow().currency.code);return this.renderMessages(t,s,e)}a?this.orderId=a:(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t),this.loadingIndicatorContainer=null==d?void 0:d.split("#")[1],this.renderButton(t,n))})}execute(e,t){return Sc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(h)return;const t={fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.bigCommercePaymentsButtons=n.Buttons(t),this.bigCommercePaymentsButtons.isEligible()||e!==n.FUNDING.PAYLATER){if(!this.bigCommercePaymentsButtons.isEligible()&&e===n.FUNDING.CREDIT)throw new Si(`BigCommercePayments ${e} is not available for your region. Please use BigCommercePayments Checkout instead.`);d&&"function"==typeof d&&d(),this.bigCommercePaymentsButtons.render(a),h=!0}})}handleClick(e,t){return Sc(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;t&&"function"==typeof t&&(yield t(()=>(this.toggleLoadingIndicator(!0),n()),i))})}handleApprove({orderID:e},t){this.orderId=e,t&&"function"==typeof t&&t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:lc(n)};e.Messages(i).render(`#${t}`)}}const wc=vi(e=>new _c(e,_r(e),new vd({containerStyles:cc}),Rr()),[{id:"bigcommerce_payments_paylater"}]);class Ic extends nr{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}var Cc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class bc{constructor(e,t,n,i=3e3,r=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=n,this.pollingInterval=i,this.maxPollingIntervalTime=r,this.pollingTimer=0,this.stopPolling=ce}initialize(e){return Cc(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,bigcommerce_payments_ratepay:i}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_ratepay" argument is not provided.');const{legalTextContainer:r,container:o,loadingContainerId:a}=i;if(!o)throw new fi('Unable to initialize payment because "options.container" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.legalTextContainer" argument is not provided.');if(!a)throw new fi('Unable to initialize payment because "options.loadingContainerId" argument is not provided.');this.loadingIndicatorContainer=a;const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t),{merchantId:d}=s.initializationData||{};if(!d)throw new fi("Unable to initialize payment because merchantId argument is not provided.");this.bigcommerce_payments_ratepay=i,yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n),this.createFraudNetScript(d,n,t),this.loadFraudnetConfig(),this.renderLegalText(r,o)})}execute(e,t){return Cc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.initializePollingMechanism(n.methodId,e,t,n.gatewayId)})}catch(e){return this.handleError(e),new Promise((e,t)=>t())}})}finalize(){return Promise.reject(new Cd)}deinitialize(){const{legalTextContainer:e}=this.bigcommerce_payments_ratepay||{},t=document.querySelectorAll('[data-id="fraudnetScript"]')[0],n=document.querySelectorAll('[data-id="fraudnetConfig"]')[0];if(this.deinitializePollingMechanism(),t.remove(),n.remove(),e){const t=document.getElementById(e);null==t||t.remove()}return Promise.resolve()}normalizeDate(e){const t=this.formatDate(e.getDate()),n=this.formatDate(e.getMonth()+1);return`${e.getFullYear()}-${n}-${t}`}formatDate(e){return`${e<10?0:""}${e}`}renderLegalText(e,t){const n=e,i=t.split("#")[1],r=document.getElementById(i),o=null==r?void 0:r.parentNode,a=document.createElement("div");a.style.marginBottom="20px",a.setAttribute("id",n),null==o||o.prepend(a);const s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=s.Legal({fundingSource:s.Legal.FUNDING.PAY_UPON_INVOICE});if(!document.getElementById(n))throw new fi('Unable to initialize payment because "legalTextContainerElement" argument is not found.');d.render(`#${n}`)}handleError(e){const{onError:t}=this.bigcommerce_payments_ratepay||{};this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createFraudNetScript(e,t,n){const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{testMode:r}=i.config,o=document.createElement("script");o.setAttribute("type","application/json"),o.setAttribute("fncls","fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99"),o.setAttribute("data-id","fraudnetScript"),this.guid=this.generateGUID();const a={f:this.guid,s:`${e}_checkout-page`,sandbox:r};o.innerHTML=JSON.stringify(a),document.body.appendChild(o)}generateGUID(){let e="";for(let t=0;t<32;t+=1)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(62*Math.random())];return e}loadFraudnetConfig(){const e=document.createElement("script");e.setAttribute("data-id","fraudnetConfig"),e.src="https://c.paypal.com/da/r/fb.js",document.body.appendChild(e)}reinitializeStrategy(e){return Cc(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}initializePollingMechanism(e,t,n,i){return Cc(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.bigCommercePaymentsIntegrationService.getOrderStatus("bigcommerce_payments_apms",{params:{useMetadata:!0}}),o=r===cr.PollingStop,a=r===cr.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimernew bc(e,_r(e),new vd({containerStyles:Object.assign(Object.assign({},cc),{position:"fixed"})})),[{gateway:"bigcommerce_payments_apms",id:"ratepay"}]);var Oc;!function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification",e.CardExpiryVerification="cardExpiryVerification"}(Oc||(Oc={}));const Ec=Oc;function Ac(e){return Ec.CardNumber in e&&Ec.CardName in e&&Ec.CardExpiry in e}function Tc(e){return Ec.CardNumberVerification in e&&Ec.CardCodeVerification in e&&Ec.CardExpiryVerification in e}var kc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Dc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdk=n,this.bigCommercePaymentsFastlaneUtils=i}initialize(e){return kc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_creditcards:n}=e,i=n,{form:r,onCreditCardFieldsRenderingError:o,onLoadComplete:a}=i||{};if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new fi('Unable to proceed because "options.bigcommerce_payments_creditcards.form" argument is not provided.');this.hostedFormOptions=r,this.isCreditCardForm=Ac(r.fields),this.isCreditCardVaultedForm=Tc(r.fields)&&!this.hasUndefinedValues(),yield this.paymentIntegrationService.loadPaymentMethod(t),yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t,void 0,!0,!0),(this.isCreditCardForm||this.isCreditCardVaultedForm)&&(yield this.initializeFields(r,o)),null==a||a(),this.shouldInitializePayPalFastlane(t)&&(yield this.initializePayPalFastlaneOrThrow(t))})}execute(e,t){return kc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(n===ir.No||n===ir.Unknown)throw new Error;return this.handleApprove({orderID:e,vaultSetupToken:t})},onError:()=>{throw new Qr},inputEvents:{onChange:t=>this.onChangeHandler(e,t),onFocus:t=>this.onFocusHandler(e,t),onBlur:t=>this.onBlurHandler(e,t),onInputSubmitRequest:t=>this.onInputSubmitRequest(e,t)}},o);if(this.cardFields=yield r.CardFields(a),!this.cardFields.isEligible())throw new ri(ei.PaymentNotInitialized);try{this.stylizeInputContainers(n),Ac(n)&&(yield this.renderFields(n)),Tc(n)&&(yield this.renderVaultedFields(n))}catch(e){"function"==typeof t&&t(e)}})}getExecuteCallback(e){return Tc(e)?this.createVaultSetupTokenCallback():this.createOrderCallback()}createVaultSetupTokenCallback(){return{createVaultSetupToken:()=>kc(this,void 0,void 0,function*(){const{setupToken:e}=(yield this.bigCommercePaymentsIntegrationService.createOrderCardFields("bigcommerce_payments_creditcardscheckout",Object.assign(Object.assign({},this.getInstrumentParams()),{setupToken:!0})))||{};return e})}}createOrderCallback(){return{createOrder:()=>kc(this,void 0,void 0,function*(){const{orderId:e}=(yield this.bigCommercePaymentsIntegrationService.createOrderCardFields("bigcommerce_payments_creditcardscheckout",this.getInstrumentParams()))||{};return e})}}handleApprove({orderID:e,vaultSetupToken:t}){e&&(this.returnedOrderId=e),t&&(this.returnedVaultedToken=t)}renderFields(e){var t,n,i,r;return kc(this,void 0,void 0,function*(){const o=this.getCardFieldsOrThrow();(null===(t=e.cardCode)||void 0===t?void 0:t.containerId)&&(this.cvvField=o.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCode.containerId}`)),(null===(n=e.cardExpiry)||void 0===n?void 0:n.containerId)&&(this.expiryField=o.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiry.containerId}`)),(null===(i=e.cardName)||void 0===i?void 0:i.containerId)&&(this.nameField=o.NameField({placeholder:""}),yield this.nameField.render(`#${e.cardName.containerId}`)),(null===(r=e.cardNumber)||void 0===r?void 0:r.containerId)&&(this.numberField=o.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumber.containerId}`))})}renderVaultedFields(e){var t,n,i;return kc(this,void 0,void 0,function*(){const r=this.getCardFieldsOrThrow();(null===(t=e.cardCodeVerification)||void 0===t?void 0:t.containerId)&&(this.cvvField=r.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCodeVerification.containerId}`)),(null===(n=e.cardExpiryVerification)||void 0===n?void 0:n.containerId)&&(this.expiryField=r.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiryVerification.containerId}`)),(null===(i=e.cardNumberVerification)||void 0===i?void 0:i.containerId)&&(this.numberField=r.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumberVerification.containerId}`))})}getInstrumentParams(){if(!this.executionPaymentData)return{};if(jd(this.executionPaymentData)){const{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}=this.executionPaymentData;return{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}}if(xd(this.executionPaymentData)){const{instrumentId:e}=this.executionPaymentData;return{instrumentId:e}}return{}}getFieldTypeByEmittedField({emittedBy:e}){return{fieldType:this.mapFieldType(e)}}submitHostedForm(){return kc(this,void 0,void 0,function*(){const e=this.getCardFieldsOrThrow(),t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),n={billingAddress:{company:t.company,addressLine1:t.address1,addressLine2:t.address2,adminArea1:t.stateOrProvinceCode,adminArea2:t.city,postalCode:t.postalCode,countryCode:t.countryCode}};try{this.isCreditCardVaultedForm?yield e.submit():yield e.submit(n)}catch(e){throw new Qr("Failed authentication. Please try to authorize again.")}})}validateHostedFormOrThrow(){var e,t;return kc(this,void 0,void 0,function*(){const n=this.getCardFieldsOrThrow(),i=yield n.getState().then(e=>e),r=this.getValidityData(i);if(!r.isValid)throw null===(t=null===(e=this.hostedFormOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,r),new lo(this.mapValidationErrors(r.errors))})}getValidityData({fields:e}){const t=Object.assign({},e);delete t.cardNameField;const n=Object.keys(t);return{isValid:n.every(e=>{var n;return null===(n=t[e])||void 0===n?void 0:n.isValid}),errors:n.reduce((e,n)=>{var i;const r=this.mapFieldType(n);return Object.assign(Object.assign({},e),{[r]:(null===(i=t[n])||void 0===i?void 0:i.isValid)?void 0:[this.getInvalidErrorByFieldType(r)]})},{})}}getInvalidErrorByFieldType(e){switch(e){case Ec.CardCode:case Ec.CardCodeVerification:return{fieldType:e,message:"Invalid card code",type:"invalid_card_code"};case Ec.CardNumber:case Ec.CardNumberVerification:return{fieldType:e,message:"Invalid card number",type:"invalid_card_number"};case Ec.CardExpiry:case Ec.CardExpiryVerification:return{fieldType:e,message:"Invalid card expiry",type:"invalid_card_expiry"};default:return{fieldType:e,message:"Invalid field",type:"invalid"}}}mapValidationErrors(e={}){const t={};return Object.keys(e).forEach(n=>{var i,r;t[n]=[{message:(null===(r=null===(i=e[n])||void 0===i?void 0:i[0])||void 0===r?void 0:r.message)||"",type:n}]}),t}mapFieldType(e){switch(e){case"name":return Ec.CardName;case"cardNumberField":case"number":return this.isCreditCardForm?Ec.CardNumber:Ec.CardNumberVerification;case"cardExpiryField":case"expiry":return this.isCreditCardForm?Ec.CardExpiry:Ec.CardExpiryVerification;case"cardCvvField":case"cvv":return this.isCreditCardForm?Ec.CardCode:Ec.CardCodeVerification;default:throw new Error("Unexpected field type")}}getCardFieldsOrThrow(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);return this.cardFields}getInputStyles(e){var t,n,i;const r={"font-size":(null===(t=null==e?void 0:e.default)||void 0===t?void 0:t.fontSize)||"1rem","font-family":(null===(n=null==e?void 0:e.default)||void 0===n?void 0:n.fontFamily)||"Montserrat, Arial, Helvetica, sans-serif","font-weight":(null===(i=null==e?void 0:e.default)||void 0===i?void 0:i.fontWeight)||"400",outline:"none",padding:"9px 13px"},o=Object.assign(Object.assign({},r),{color:"#333333"});return{input:o,".invalid":Object.assign(Object.assign({},r),{color:"red"}),".valid":o,":focus":o}}stylizeInputContainers(e){Object.values(e||{}).forEach(e=>{const t=document.getElementById(`${(null==e?void 0:e.containerId)||""}`);t&&(t.style.padding="0px",t.style.boxShadow="none",t.style.border="none",t.style.background="transparent",t.style.marginBottom="10px",t.style.marginLeft="-5px")})}hasUndefinedValues(){return!this.hostedFormOptions||Object.values(this.hostedFormOptions.fields).some(e=>void 0===e)}onChangeHandler(e,t){var n;null===(n=null==e?void 0:e.onValidate)||void 0===n||n.call(e,this.getValidityData(t))}onFocusHandler(e,t){var n;null===(n=null==e?void 0:e.onFocus)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onBlurHandler(e,t){var n;null===(n=null==e?void 0:e.onBlur)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onInputSubmitRequest(e,t){var n;null===(n=null==e?void 0:e.onEnter)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}shouldInitializePayPalFastlane(e){var t,n;const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(e),o=i.getPaymentProviderCustomer(),a=(s=o)&&("authenticationState"in s||"addresses"in s||"instruments"in s)?o:{};var s;return(null===(t=null==r?void 0:r.initializationData)||void 0===t?void 0:t.isAcceleratedCheckoutEnabled)&&(null===(n=null==r?void 0:r.initializationData)||void 0===n?void 0:n.isBigCommercePaymentsAnalyticsV2Enabled)&&!(null==a?void 0:a.authenticationState)}initializePayPalFastlaneOrThrow(e){return kc(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getPaymentMethodOrThrow(e),{initializationData:r}=i;if(!(null==r?void 0:r.connectClientToken))return;const o=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(i,n.currency.code,n.id);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(o,!!(null==r?void 0:r.isDeveloperModeApplicable))}catch(e){}})}}const Mc=vi(e=>new Dc(e,_r(e),Rr(),jr()),[{id:"bigcommerce_payments_creditcards"}]);var zc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Nc{constructor(e,t,n,i,r=3e3,o=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdkHelper=n,this.loadingIndicator=i,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.pollingTimer=0,this.stopPolling=ce,this.isPollingEnabled=!1}initialize(e){return zc(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,bigcommerce_payments_apms:i}=e;if(this.bigCommercePaymentsAlternativeMethods=i,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_apms" argument is not provided.');const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(n,t),{orderId:a,shouldRenderFields:s}=o.initializationData||{},d=r.getStoreConfigOrThrow().checkoutSettings.features;this.isPollingEnabled=Ci(d,"PAYPAL-5624.bcp_ideal_polling"),a?this.orderId=a:(this.paypalApms=yield this.bigCommercePaymentsSdkHelper.getPayPalApmsSdk(o,r.getCartOrThrow().currency.code),this.loadingIndicatorContainer=i.container.split("#")[1],this.renderButton(n,t,i),s&&this.renderFields(n,i))})}execute(e,t){return zc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.initializePollingMechanism(r,e,t,o)})),this.isNonInstantPaymentMethod(r)||(yield this.paymentIntegrationService.submitOrder(i,t)),yield this.bigCommercePaymentsIntegrationService.submitPayment(r,this.orderId,o)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,this.isPollingEnabled&&this.resetPollingMechanism(),null===(e=this.bigCommercePaymentsButton)||void 0===e||e.close(),Promise.resolve()}initializePollingMechanism(e,t,n,i){return zc(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.bigCommercePaymentsIntegrationService.getOrderStatus(i),o=r===cr.Approved,a=r===cr.PollingError;if(o)return this.deInitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimern.onInitButton(t),createOrder:()=>this.onCreateOrder(e,t,n),onApprove:e=>this.handleApprove(e,c),onCancel:()=>{this.toggleLoadingIndicator(!1),this.deInitializePollingMechanism()},onError:e=>{this.deInitializePollingMechanism(),this.handleFailure(e,s)},onClick:(e,t)=>zc(this,void 0,void 0,function*(){return n.onValidate(t.resolve,t.reject)})};this.bigCommercePaymentsButton=i.Buttons(l),this.bigCommercePaymentsButton.isEligible()&&(d&&"function"==typeof d&&d(),this.bigCommercePaymentsButton.render(a))}onCreateOrder(e,t,n){return zc(this,void 0,void 0,function*(){const{onValidate:i}=n;yield i(()=>(this.toggleLoadingIndicator(!0),()=>Promise.resolve()),ce);const r=yield this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apms");if(this.isNonInstantPaymentMethod(e)){const n={useStoreCredit:!1},i={params:{methodId:e,gatewayId:t}};yield this.paymentIntegrationService.submitOrder(n,i),yield this.bigCommercePaymentsIntegrationService.submitPayment(e,r,t)}return r})}handleApprove({orderID:e},t){this.orderId=e,t()}handleFailure(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderFields(e,t){const n=this.getPaypalAmpsSdkOrThrow(),i=this.paymentIntegrationService.getState(),{firstName:r,lastName:o,email:a}=i.getBillingAddressOrThrow(),{apmFieldsContainer:s,apmFieldsStyles:d}=t;if(!s)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_apms" argument should contain "apmFieldsContainer".');const c=document.querySelector(s);c&&(c.innerHTML="");const l={fundingSource:e,style:d||{},fields:{name:{value:`${r} ${o}`},email:{value:a}}};n.PaymentFields(l).render(s)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isNonInstantPaymentMethod(e){return e.toUpperCase()in dr}getPaypalAmpsSdkOrThrow(){if(!this.paypalApms)throw new mi;return this.paypalApms}}const xc=vi(e=>new Nc(e,_r(e),Rr(),new vd({containerStyles:cc})),[{gateway:"bigcommerce_payments_apms"}]);class Rc{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){const{gatewayId:t,methodId:n,bigcommerce_payments_apms:i}=e;if(this.bigCommercePaymentsAlternativeMethods=i,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');return Promise.resolve()}execute(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{window.location.replace(t),n()})}return this.handleError(e),Promise.reject(e)}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}handleError(e){const{onError:t}=this.bigCommercePaymentsAlternativeMethods||{};t&&"function"==typeof t&&t(e)}}const Fc=vi(e=>new Rc(e,_r(e)),[{gateway:"bigcommerce_payments_apms",id:"klarna"},{gateway:"bigcommerce_payments_apms",id:"afterpay"}]);var Lc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Bc{constructor(e,t,n){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=n}initialize(e){var t,n;return Lc(this,void 0,void 0,function*(){const{methodId:i,bigcommerce_payments_venmo:r}=e||{};if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i);(null===(t=o.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(n=o.initializationData)||void 0===n?void 0:n.orderId:(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i),this.loadingIndicatorContainer=r.container.split("#")[1],this.renderButton(i,r))})}execute(e,t){return Lc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rthis.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmocheckout"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=n.Buttons(u),!this.paypalButton.isEligible())throw new Si("Venmo is not available for your region. Please another payment method instead.");d&&"function"==typeof d&&d(),this.paypalButton.render(a)}handleClick(e,t){return Lc(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;yield t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,t(),this.toggleLoadingIndicator(!1)}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const jc=vi(e=>new Bc(e,_r(e),new vd({styles:{backgroundColor:"black"}})),[{id:"bigcommerce_payments_venmo"}]);class Uc{initialize(e){this._blueSnapSdk=e}initialize3ds(e,t){return n=this,i=void 0,o=function*(){const n=this._getBlueSnapSdk();return new Promise((i,r)=>{n.threeDsPaymentsSetup(e,e=>"1"===e.code?i(e.threeDSecure.threeDSecureReferenceId):r(new Qr)),n.threeDsPaymentsSubmitData(t)})},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_getBlueSnapSdk(){return ii(this._blueSnapSdk,()=>new ri(ei.PaymentNotInitialized))}}function qc(e){return Ec.CardNumber in e}function Vc(e){return Ec.CardCodeVerification in e||Ec.CardNumberVerification in e}var Gc,Hc,Wc,$c,Yc,Kc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Jc{constructor(e,t,n,i){this._scriptLoader=e,this._paymentIntegrationService=t,this._blueSnapDirectHostedForm=n,this._blueSnapDirect3ds=i}initialize(e){return Kc(this,void 0,void 0,function*(){const{methodId:t,gatewayId:n,creditCard:i}=e;if(!n||!i)throw new fi;const r=yield this._paymentIntegrationService.loadPaymentMethod(n,{params:{method:t,bigpayToken:i.bigpayToken}}),{config:{testMode:o,is3dsEnabled:a},clientToken:s}=r.getPaymentMethodOrThrow(t,n);if(this._blueSnapSdk=yield this._scriptLoader.load(o),this._paymentFieldsToken=s,this._shouldUseHostedFields=qc(i.form.fields)||Vc(i.form.fields)&&!!i.form.fields.cardNumberVerification,this._shouldUseHostedFields){this._blueSnapDirectHostedForm.initialize(this._blueSnapSdk,i.form.fields);try{yield this._blueSnapDirectHostedForm.attach(this._getPaymentFieldsToken(),i,a)}catch(e){if(e instanceof fi)return;throw e}}})}execute(e){return Kc(this,void 0,void 0,function*(){if(!e.payment)throw new co(["payment"]);if(!this._blueSnapSdk)throw new co(["payment"]);const{paymentData:t}=e.payment,{shouldSaveInstrument:n,shouldSetAsDefaultInstrument:i}=jd(t)?t:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},r=this._getPaymentFieldsToken();let o;const{is3dsEnabled:a}=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.payment.methodId,e.payment.gatewayId).config,s=this._shouldUseHostedFields?yield this._blueSnapDirectHostedForm.validate().submit(a?this._getBlueSnapDirectThreeDSecureData():void 0,!(jd(t)&&xd(t))):void 0;if(yield this._paymentIntegrationService.submitOrder(),jd(t)&&xd(t)&&this._paymentFieldsToken&&t.instrumentId){if(a){this._blueSnapDirect3ds.initialize(this._blueSnapSdk);const{last4:e,brand:n}=this._paymentIntegrationService.getState().getCardInstrumentOrThrow(t.instrumentId),i=Object.assign({last4Digits:e,ccType:n.toUpperCase()},this._getBlueSnapDirectThreeDSecureData());o=yield this._blueSnapDirect3ds.initialize3ds(this._paymentFieldsToken,i)}yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e.payment),{paymentData:Object.assign(Object.assign(Object.assign({instrumentId:t.instrumentId},this._shouldUseHostedFields?{nonce:r}:{}),o?{deviceSessionId:o}:{}),{shouldSetAsDefaultInstrument:!!i})}))}else yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e.payment),{paymentData:{formattedPayload:{credit_card_token:{token:JSON.stringify({pfToken:r,cardHolderName:s&&s.cardHolderName})},vault_payment_instrument:n,set_as_default_stored_instrument:i}}}))})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this._shouldUseHostedFields&&this._blueSnapDirectHostedForm.detach(),Promise.resolve()}_getBlueSnapDirectThreeDSecureData(){var e;const{getBillingAddress:t,getShippingAddress:n,getCustomer:i,getCheckoutOrThrow:r,getCartOrThrow:o}=this._paymentIntegrationService.getState(),a=t(),s=n(),d=(null===(e=i())||void 0===e?void 0:e.email)||(null==a?void 0:a.email),c=(null==a?void 0:a.phone)||(null==s?void 0:s.phone);return Object.assign(Object.assign(Object.assign(Object.assign({amount:r().outstandingBalance,currency:o().currency.code},d&&{email:d}),c&&{phone:c}),a&&{billingFirstName:a.firstName,billingLastName:a.lastName,billingCountry:a.countryCode,billingCity:a.city,billingAddress:`${a.address1} ${a.address2}`.trim(),billingZip:a.postalCode}),s&&{shippingFirstName:s.firstName,shippingLastName:s.lastName,shippingCountry:s.countryCode,shippingCity:s.city,shippingAddress:`${s.address1} ${s.address2}`.trim(),shippingZip:s.postalCode})}_getPaymentFieldsToken(){return ii(this._paymentFieldsToken,()=>new ti(Xn.MissingPaymentToken))}}!function(e){e.AMEX="american-express",e.CHINA_UNION_PAY="unionpay",e.DINERS="diners-club",e.DISCOVER="discover",e.JCB="jcb",e.MASTERCARD="mastercard",e.UNKNOWN="unknown",e.VISA="visa"}(Gc||(Gc={})),function(e){e.ON_BLUR="onBlur",e.ON_SUBMIT="onSubmit"}(Hc||(Hc={})),function(e){e.EMPTY="empty",e.INVALID="invalid",e.THREE_DS_NOT_ENABLED="3D Secure is not enabled"}(Wc||(Wc={})),function(e){e.CC_NOT_SUPORTED="22013",e.ERROR_403="403",e.ERROR_404="404",e.ERROR_500="500",e.INVALID_OR_EMPTY="10",e.SESSION_EXPIRED="400",e.THREE_DS_AUTH_FAILED="14101",e.THREE_DS_CLIENT_ERROR="14103",e.THREE_DS_MISSING_FIELDS="14102",e.THREE_DS_NOT_ENABLED="14100",e.TOKEN_EXPIRED="14040",e.TOKEN_NOT_ASSOCIATED="14042",e.TOKEN_NOT_FOUND="14041"}($c||($c={})),function(e){e.CardCode="cvv",e.CardExpiry="exp",e.CardName="noc",e.CardNumber="ccn"}(Yc||(Yc={}));const Zc={[Yc.CardNumber]:Ec.CardNumber,[Yc.CardExpiry]:Ec.CardExpiry,[Yc.CardName]:Ec.CardName,[Yc.CardCode]:Ec.CardCode},Qc={empty:{[Ec.CardNumber]:{fieldType:"cardNumber",message:"Credit card number is required",type:"required"},[Ec.CardNumberVerification]:{fieldType:"cardNumber",message:"Credit card number is required",type:"required"},[Ec.CardExpiry]:{fieldType:"cardExpiry",message:"Expiration date is required",type:"required"},[Ec.CardCode]:{fieldType:"cardCode",message:"CVV is required",type:"required"},[Ec.CardName]:{fieldType:"cardName",message:"Full name is required",type:"required"}},invalid:{[Ec.CardNumber]:{fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},[Ec.CardNumberVerification]:{fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},[Ec.CardExpiry]:{fieldType:"cardExpiry",message:"Expiration date must be a valid future date in MM / YY format",type:"invalid_card_expiry"},[Ec.CardCode]:{fieldType:"cardCode",message:"CVV must be valid",type:"invalid_card_code"},[Ec.CardName]:{fieldType:"cardName",message:"Full name is required",type:"required"}}};class Xc{constructor(e,t){this._nameOnCardInput=e,this._hostedInputValidator=t}initialize(e,t){this._blueSnapSdk=e,t&&(qc(t)?this._hostedInputValidator.initialize():Vc(t)&&t.cardNumberVerification&&this._hostedInputValidator.initializeValidationFields())}attach(e,t,n){var i,r,o,a,s=t.form,{fields:d}=s,c=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const r=this._getHostedPaymentFieldsOptions(e,d,c,i,n);t.hostedPaymentFieldsCreate(r),qc(d)&&this._nameOnCardInput.attach(r,d.cardName.accessibilityLabel,d.cardName.placeholder)})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}validate(){var e;const t=this._hostedInputValidator.validate();if(null===(e=this._onValidate)||void 0===e||e.call(this,t),!t.isValid){const e=Object.entries(t.errors).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n.map(({message:e,type:t})=>({message:e,type:t}))}),{});throw new lo(e)}return this}submit(e,t=!1){return new Promise((n,i)=>this._getBlueSnapSdk().hostedPaymentFieldsSubmitData(e=>this._isBlueSnapDirectCallbackError(e)?i(new Qr(e.statusCode===$c.THREE_DS_AUTH_FAILED?e.error[0].errorDescription:`Submission failed with status: ${e.statusCode} and errors: ${JSON.stringify(e.error)}`)):n(Object.assign(Object.assign({},e.cardData),t?{cardHolderName:this._nameOnCardInput.getValue()}:{})),e))}detach(){this._nameOnCardInput.detach()}_isBlueSnapDirectCallbackError(e){return"error"in e}_getHostedPaymentFieldsOptions(e,t,{onFocus:n,onBlur:i,onValidate:r,onCardTypeChange:o,onEnter:a,styles:s},d,c){var l;return Object.assign(Object.assign(Object.assign({token:e,onFieldEventHandler:{setupComplete:()=>d(),onFocus:this._usetUiEventCallback(n),onBlur:this._usetUiEventCallback(i),onError:this._handleError(r),onType:(e,t)=>null==o?void 0:o({cardType:Gc[t]}),onEnter:this._usetUiEventCallback(a),onValid:e=>null==r?void 0:r(this._hostedInputValidator.validate({tagId:e}))}},qc(t)&&{ccnPlaceHolder:t.cardNumber.placeholder||"",cvvPlaceHolder:(null===(l=t.cardCode)||void 0===l?void 0:l.placeholder)||"",expPlaceHolder:t.cardExpiry.placeholder||"MM / YY"}),s&&{style:this._mapStyles(s)}),{"3DS":c})}_mapStyles({default:e,error:t,focus:n}){return Object.entries(Object.assign(Object.assign(Object.assign({},e&&{input:e}),t&&{".invalid":t}),n&&{":focus":n})).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:Object.entries(n).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[te(t)]:n}),{})}),{})}_handleError(e){return(t,n,i,r)=>{if(n===$c.INVALID_OR_EMPTY&&t&&function(e){return void 0!==e&&[Wc.EMPTY,Wc.INVALID].includes(e)}(i))return null==e?void 0:e(this._hostedInputValidator.validate({tagId:t,errorDescription:i}));throw new Qr(`An unexpected error has occurred: ${JSON.stringify({tagId:t,errorCode:n,errorDescription:i,eventOrigin:r})}`)}}_usetUiEventCallback(e){return t=>{e&&e({fieldType:Zc[t]})}}_getBlueSnapSdk(){return ii(this._blueSnapSdk,()=>new ri(ei.PaymentNotInitialized))}_setCustomBlueSnapAttributes(e){const{cardNumber:t,cardExpiry:n,cardCode:i,cardName:r}=e,o=document.getElementById(t.containerId),a=document.getElementById(n.containerId),s=i&&document.getElementById(i.containerId),d=document.getElementById(r.containerId);if(!(o&&a&&s&&d))throw new fi("Unable to create hosted payment fields to invalid HTML container elements.");o.dataset.bluesnap=Yc.CardNumber,a.dataset.bluesnap=Yc.CardExpiry,s.dataset.bluesnap=Yc.CardCode,d.dataset.bluesnap=Yc.CardName}_setCustomStoredCardsBlueSnapAttributes(e){const{cardNumberVerification:t,cardCodeVerification:n}=e,i=t&&document.getElementById(t.containerId),r=n&&document.getElementById(n.containerId);(i||r)&&(i&&(i.dataset.bluesnap=Yc.CardNumber),r&&(r.dataset.bluesnap=Yc.CardCode))}}class el{constructor(){this._errors={}}initialize(){this._errors={cardNumber:[Qc.empty.cardNumber],cardExpiry:[Qc.empty.cardExpiry],cardCode:[Qc.empty.cardCode],cardName:[Qc.empty.cardName]}}initializeValidationFields(){this._errors={cardNumberVerification:[Qc.empty.cardNumber]}}validate(e){return e&&this._updateErrors(e.tagId,e.errorDescription),{isValid:Object.values(this._errors).every(e=>0===e.length),errors:this._errors}}_updateErrors(e,t){const n=this._errors.cardNumberVerification?Ec.CardNumberVerification:Zc[e];this._errors[n]=t?[Qc[t][n]]:[]}}class tl{attach({style:e,onFieldEventHandler:{onFocus:t,onBlur:n,onValid:i,onError:r,onEnter:o}={}},a,s){var d;this._style=e,this._create(),this._getInput().addEventListener("focus",this._handleFocus(t)),this._getInput().addEventListener("blur",this._handleBlur(n,i,r)),this._getInput().addEventListener("enter",this._handleEnter(o)),a&&this._getInput().setAttribute("aria-label",a),s&&(this._getInput().placeholder=s),null===(d=document.querySelector('[data-bluesnap="noc"]'))||void 0===d||d.appendChild(this._getInput())}getValue(){return this._getInput().value}detach(){this._input&&(this._input.remove(),this._input=void 0)}_handleFocus(e){return()=>{var t;this._applyStyles(null===(t=this._style)||void 0===t?void 0:t[":focus"]),null==e||e(Yc.CardName)}}_handleBlur(e,t,n){return({target:i})=>{var r,o;null==e||e(Yc.CardName),i instanceof HTMLInputElement&&(/\w{1,200}/.test(i.value)?(this._applyStyles(null===(r=this._style)||void 0===r?void 0:r.input),null==t||t(Yc.CardName)):(this._applyStyles(null===(o=this._style)||void 0===o?void 0:o[".invalid"]),null==n||n(Yc.CardName,$c.INVALID_OR_EMPTY,Wc.EMPTY,Hc.ON_BLUR)))}}_handleEnter(e){return()=>null==e?void 0:e(Yc.CardName)}_applyStyles(e={}){const t={color:e.color,fontFamily:e["font-family"],fontSize:e["font-size"],fontWeight:e["font-weight"]},n=Object.keys(t);n.every(e=>["color","fontFamily","fontSize","fontWeight"].includes(e))&&n.forEach(e=>{t[e]&&(this._getInput().style[e]=t[e]||"")})}_configureInput(){this._getInput().autocomplete="cc-name",this._getInput().id=Yc.CardName,this._getInput().inputMode="text",this._getInput().maxLength=200,this._getInput().style.backgroundColor="transparent",this._getInput().style.border="0",this._getInput().style.height="100%",this._getInput().style.margin="0",this._getInput().style.outline="none",this._getInput().style.padding="0",this._getInput().style.width="100%",this._getInput().type="text"}_getInput(){return ii(this._input,()=>new ri(ei.PaymentNotInitialized))}_create(){var e;this._input=document.createElement("input"),this._configureInput(),this._applyStyles(null===(e=this._style)||void 0===e?void 0:e.input)}}var nl;!function(e){e.PRODUCTION="https://pay.bluesnap.com/web-sdk/5/bluesnap.js",e.SANDBOX="https://sandpay.bluesnap.com/web-sdk/5/bluesnap.js"}(nl||(nl={}));class il{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e=!1){return t=this,n=void 0,r=function*(){if(this._window.bluesnap)return this._window.bluesnap;if(yield this._scriptLoader.loadScript(e?nl.SANDBOX:nl.PRODUCTION),!this._window.bluesnap)throw new mi;return this._window.bluesnap},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const rl=vi(e=>new Jc(new il(a()),e,new Xc(new tl,new el),new Uc),[{id:"credit_card",gateway:"bluesnapdirect"}]);class ol{constructor(e){this._paymentIntegrationService=e}execute(e){return t=this,n=void 0,r=function*(){const t=this._formatePaymentPayload(e);yield this._paymentIntegrationService.submitOrder();try{yield this._paymentIntegrationService.submitPayment(t)}catch(e){if(this._isBlueSnapDirectRedirectResponse(e)){const t=e.body.provider_data&&JSON.parse(e.body.provider_data);let n=e.body.additional_action_required.data.redirect_url;if(function(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!t.merchantid&&"string"==typeof t.merchantid}(t)){const e=new URLSearchParams(t).toString();n=`${n}&${e}`}return new Promise(()=>window.location.replace(n))}return Promise.reject(e)}},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}initialize(){return Promise.resolve()}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_formatePaymentPayload({payment:e}){if(!e)throw new co(["payment"]);return e.paymentData&&xd(e.paymentData)&&jd(e.paymentData)?Object.assign(Object.assign({},e),{paymentData:{instrumentId:e.paymentData.instrumentId,shouldSetAsDefaultInstrument:!!e.paymentData.shouldSetAsDefaultInstrument}}):(t=e.paymentData,Boolean("object"==typeof t&&null!==t&&"accountNumber"in t&&"accountType"in t&&"shopperPermission"in t&&"routingNumber"in t)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{ecp:Object.assign({account_number:e.paymentData.accountNumber,account_type:e.paymentData.accountType,shopper_permission:e.paymentData.shopperPermission,routing_number:e.paymentData.routingNumber},e.paymentData.companyName?{company_name:e.paymentData.companyName}:{}),vault_payment_instrument:e.paymentData.shouldSaveInstrument,set_as_default_stored_instrument:e.paymentData.shouldSetAsDefaultInstrument}}}):(n=e.paymentData,Boolean("object"==typeof n&&null!==n&&"iban"in n&&"firstName"in n&&"lastName"in n&&"shopperPermission"in n)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{sepa_direct_debit:{iban:e.paymentData.iban,first_name:e.paymentData.firstName,last_name:e.paymentData.lastName,shopper_permission:e.paymentData.shopperPermission},vault_payment_instrument:e.paymentData.shouldSaveInstrument,set_as_default_stored_instrument:e.paymentData.shouldSetAsDefaultInstrument}}}):function(e){return Boolean("object"==typeof e&&null!==e&&"bic"in e)}(e.paymentData)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{ideal:{bic:e.paymentData.bic}}}}):function(e){return Boolean("object"==typeof e&&null!==e&&"iban"in e&&!("firstName"in e)&&!("lastName"in e)&&!("shopperPermission"in e))}(e.paymentData)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{pay_by_bank:{iban:e.paymentData.iban}}}}):{methodId:e.methodId}));var t,n}_isBlueSnapDirectRedirectResponse(e){var t;if("object"!=typeof e||null===e)return!1;const n=e;if(!n.body)return!1;const i=n.body;return"additional_action_required"===i.status&&!!(null===(t=i.additional_action_required)||void 0===t?void 0:t.data.redirect_url)}}const al=vi(e=>new ol(e),[{gateway:"bluesnapdirect"}]);var sl;!function(e){e.ACKNOWLEDGE="ACKNOWLEDGE",e.FINALIZE="FINALIZE",e.INITIALIZE="INITIALIZE"}(sl||(sl={}));const dl=sl;var cl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ll{constructor(e){this._paymentIntegrationService=e}execute(e,t){return cl(this,void 0,void 0,function*(){const{payment:n}=e;if(!n)throw new co(["payment"]);if(!this._initializeOptions)throw new ri(ei.PaymentNotInitialized);const{onLoad:i,style:r}=this._initializeOptions,o=this._createIframe("bluesnapv2_hosted_payment_page",r),a=new En(new Promise(ce));i(o,()=>a.cancel(new Wi)),yield this._paymentIntegrationService.submitOrder(e,t),yield this._paymentIntegrationService.initializeOffsitePayment({methodId:n.methodId,gatewayId:n.gatewayId,shouldSaveInstrument:!1,target:o.name,promise:a.promise})})}finalize(e){return cl(this,void 0,void 0,function*(){const t=this._paymentIntegrationService.getState(),n=t.getOrder(),i=t.getPaymentStatus();if(!n||i!==dl.ACKNOWLEDGE&&i!==dl.FINALIZE)return Promise.reject(new Cd);yield this._paymentIntegrationService.finalizeOrder(e)})}initialize(e){return cl(this,void 0,void 0,function*(){this._initializeOptions=e&&e.bluesnapv2,yield Promise.resolve()})}deinitialize(){return Promise.resolve()}_createIframe(e,t){const n=document.createElement("iframe");if(n.setAttribute("sandbox","allow-top-navigation allow-scripts allow-forms allow-same-origin"),n.name=e,t){const{border:e,height:i,width:r}=t;n.style.border=null!=e?e:"",n.style.height=null!=i?i:"",n.style.width=null!=r?r:""}return n}}const ul=vi(e=>new ll(e),[{gateway:"bluesnapv2"}]);class hl{constructor(e){this.storage=e}saveExtraItemsData(e,t){const n=[...t.physicalItems,...t.digitalItems].reduce((e,t)=>(e[t.productId]={brand:t.brand?t.brand:"",category:t.categoryNames?t.categoryNames.join(", "):""},e),{});try{return this.storage.setItem(this.getStorageKey(e),JSON.stringify(n)),n}catch(e){return{}}}readExtraItemsData(e){try{const t=this.storage.getItem(this.getStorageKey(e));if(!t)return null;const n=JSON.parse(t);return function(e){if(!Z(e))return!1;const t=Object.values(e).some(e=>!Z(e)||!("brand"in e)||!("category"in e));return Boolean(!t)}(n)?n:null}catch(e){return null}}clearExtraItemData(e){try{this.storage.removeItem(this.getStorageKey(e))}catch(e){}}getStorageKey(e){return e?`ORDER_ITEMS_${e}`:""}}function pl(e){return Boolean(e.hasOwnProperty("analytics"))}function ml(e){return"object"==typeof e&&null!==e&&"shouldCreateAccount"in e}class yl extends Qn{constructor(e){super(),this.errorCode=e,this.name="BoltPaymentsFieldError",this.type="bolt_payments_field_error",this.body={errors:[yl.getError(e)]}}static getError(e){switch(e){case"1000":case"2000":case"3000":return{code:"invalid_number"};case"1001":case"2001":case"3001":return{code:"invalid_expiry_date"};case"1002":case"2002":return{code:"invalid_cvc"};case"1003":return{code:"invalid_zip"};case"2003":return{code:"incorrect_zip"};default:return{code:"general_error"}}}}var gl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vl{constructor(e,t,n){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.analyticsExtraItemsManager=n,this.useBoltClient=!1,this.useBoltEmbedded=!1}initialize(e){return gl(this,void 0,void 0,function*(){const{bolt:t,methodId:n}=e,{containerId:i,onPaymentSelect:r,useBigCommerceCheckout:o}=t||{};if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)return void(this.boltClient=yield this.boltScriptLoader.loadBoltClient());const a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{initializationData:s,config:d}=a,{publishableKey:c,developerConfig:l,embeddedOneClickEnabled:u}=s||{},{testMode:h}=d;if(!c)throw new ti(Xn.MissingPaymentMethod);if(this.boltClient=yield this.boltScriptLoader.loadBoltClient(c,h,l),this.useBoltClient=!u,this.useBoltEmbedded=!!u,this.useBoltEmbedded){if(!i)throw new fi('Unable to initialize payment because "options.bolt.containerId" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.bolt.onPaymentSelect" argument is not provided.');this.boltEmbedded=yield this.boltScriptLoader.loadBoltEmbedded(c,h,l),this.mountBoltEmbeddedField(i),r(yield this.hasBoltAccount())}})}deinitialize(){var e;return null===(e=this.embeddedField)||void 0===e||e.unmount(),this.boltClient=void 0,this.boltEmbedded=void 0,Promise.resolve()}finalize(){return Promise.reject(new Cd)}execute(e,t){return gl(this,void 0,void 0,function*(){this.setExtraItemsForAnalytics();const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const n={success:(n,i)=>{n.reference?e(n):t(new Qr("Unable to proceed because transaction reference is unavailable. Please try again later.")),i()},close:()=>{t(new Wi)}};s.configure({orderToken:r},{},n).open()});return{methodId:e,paymentData:{nonce:d.reference,shouldSaveInstrument:a}}})}getBoltEmbeddedPaymentPayload(e,t){var n;return gl(this,void 0,void 0,function*(){if(!ml(t))throw new ti(Xn.MissingPayment);const i=this.validateTokenizeResultOrThrow(yield null===(n=this.embeddedField)||void 0===n?void 0:n.tokenize());return{methodId:e,paymentData:{formattedPayload:{credit_card_token:{token:i.token,last_four_digits:i.last4,iin:i.bin,expiration_month:+i.expiration.split("-")[1],expiration_year:+i.expiration.split("-")[0]},provider_data:{create_account:!!t.shouldCreateAccount,embedded_checkout:!0}}}}})}getBoltFullCheckoutPaymentPayload(e,t){return gl(this,void 0,void 0,function*(){yield this.setBoltOrderId();const n=this.getBoltClientOrThrow(),i=yield n.getTransactionReference();if(!i)throw new Xr;return{methodId:e,paymentData:Object.assign(Object.assign({},t),{nonce:i})}})}getBoltClientOrThrow(){if(!this.boltClient)throw new ri(ei.PaymentNotInitialized);return this.boltClient}getBoltEmbeddedOrThrow(){if(!this.boltEmbedded)throw new ri(ei.PaymentNotInitialized);return this.boltEmbedded}hasBoltAccount(){return gl(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCustomer(),n=e.getBillingAddress(),i=(null==t?void 0:t.email)||(null==n?void 0:n.email)||"",r=this.getBoltClientOrThrow();try{return yield r.hasBoltAccount(i)}catch(e){throw new Xr}})}setBoltOrderId(){return gl(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getOrderOrThrow(),t=this.getBoltClientOrThrow();try{yield t.setOrderId(e.orderId)}catch(e){throw new Xr}})}mountBoltEmbeddedField(e){const t=this.getBoltEmbeddedOrThrow().create("payment_field",{styles:{backgroundColor:"#fff"},renderSeparateFields:!0});t.mount(`#${e}`),this.embeddedField=t}validateTokenizeResultOrThrow(e){if(!e)throw new Xr;if(e instanceof Error)throw new yl(e.message);const{token:t,last4:n,bin:i,expiration:r}=e,o=+n,a=+i,s=+`${r}`.split("-")[1],d=+`${r}`.split("-")[0];if(!t||Number.isNaN(o)||Number.isNaN(a)||Number.isNaN(s)||Number.isNaN(d))throw new co;return e}setExtraItemsForAnalytics(){const e=this.paymentIntegrationService.getState(),t=e.getStoreConfigOrThrow(),n=e.getCartOrThrow();if(t.checkoutSettings.isAnalyticsEnabled&&pl(window)){const{id:e,lineItems:t}=n;this.analyticsExtraItemsManager.saveExtraItemsData(e,t)}}}const fl=vi(e=>new vl(e,new ao(a()),new hl(Te)),[{id:"bolt"}]);function Sl(e){return!!e&&"accountNumber"in e&&"routingNumber"in e&&"ownershipType"in e&&"accountType"in e}var _l=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class wl{constructor(e,t){this.paymentIntegrationService=e,this.braintreeSdk=t}initialize(e){return _l(this,void 0,void 0,function*(){const{methodId:t,braintreeach:n}=e||{};if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');this.getMandateText=null==n?void 0:n.getMandateText,yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{clientToken:r,initializationData:o}=i;if(!r||!o)throw new ti(Xn.MissingPaymentMethod);this.braintreeSdk.initialize(r);try{this.usBankAccount=yield this.braintreeSdk.getUsBankAccount()}catch(e){this.handleBraintreeError(e)}})}execute(e,t){return _l(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew wl(e,(e=>{const t=new Ei(e),n=new Hi(a(),window,t);return new Ui(n)})(e)),[{id:"braintreeach"}]);class Cl{constructor(e){this.paymentIntegrationService=e,this.braintreeHostWindow=window}render(e,t,n){const i=t&&document.getElementById(t);if(this.braintreeHostWindow.paypal&&i){const r=this.paymentIntegrationService.getState(),o=r.getCartOrThrow(),a=r.getBillingAddressOrThrow(),s=r.getPaymentMethodOrThrow(e);if(!s.initializationData)return;const{paypalBNPLConfiguration:d=[]}=s.initializationData,c=n===fo.PAYMENT?"checkout":n,l=d&&d.find(({id:e})=>e===c);if(!l||!l.status)return;n===fo.CART&&(i.removeAttribute("data-pp-style-logo-type"),i.removeAttribute("data-pp-style-logo-position"),i.removeAttribute("data-pp-style-text-color"),i.removeAttribute("data-pp-style-text-size")),this.braintreeHostWindow.paypal.Messages({amount:o.cartAmount,buyerCountry:a.countryCode,placement:n,style:this.getPaypalMessagesStylesFromBNPLConfig(l)}).render(`#${t}`)}}getPaypalMessagesStylesFromBNPLConfig({styles:e}){const t={};return e.color&&(t.color=e.color),e.layout&&(t.layout=e.layout),(e["logo-type"]||e["logo-position"])&&(t.logo={},e["logo-type"]&&(t.logo.type=e["logo-type"]),e["logo-position"]&&(t.logo.position=e["logo-position"])),e.ratio&&(t.ratio=e.ratio),(e["text-color"]||e["text-size"])&&(t.text={},e["text-color"]&&(t.text.color=e["text-color"]),e["text-size"]&&(t.text.size=+e["text-size"])),t}}class bl{constructor(e){const{element:t,closeElement:n,mainElement:i}=this._createElements(e);this._element=t,this._closeElement=n,this._mainElement=i}show(e){this._mainElement.parentElement||(this._registerClick(e),document.body.appendChild(this._mainElement),setTimeout(()=>this._element.style.opacity="1"))}remove(){this._mainElement.parentElement&&(this._unregisterClick&&this._unregisterClick(),this._removeAfterTransition(),setTimeout(()=>this._element.style.opacity="0"))}_createElements(e){const t=document.createElement("div"),{background:n="rgba(0, 0, 0, 0.8)",id:i="checkoutOverlay",transitionDuration:r=400,hasCloseButton:o=!1,innerHtml:a=null}=e||{};let s,d,c,l,u=t;if(i&&(t.id=i),a){const e=document.createElement("div");l=`${i}--overlayText`,e.className=l,e.appendChild(a),t.appendChild(e)}return o&&(c=`${i}--close`,s=document.createElement("div"),s.className=c,d=`${i}--layout`,u=document.createElement("div"),u.className=d,u.appendChild(t),u.appendChild(s)),u.appendChild(function(e){const{id:t,background:n,transitionDuration:i,classLayout:r,classOverlayText:o,classClose:a}=e,s=document.createElement("style"),d=r?`, .${r}`:"";return s.id=`${t}--styles`,s.type="text/css",s.innerText=`\n #${t}${d} {\n display: block;\n height: 100%;\n width: 100%;\n left: 0;\n top: 0;\n position: fixed;\n z-index: 2147483647;\n }\n #${t} {\n transition: opacity ${i}ms ease-out;\n background: ${n};\n opacity: 0;\n }\n `,o&&(s.innerText+=`\n #${t} {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n #${t} .${o} {\n color: white;\n max-width: 330px;\n font-size: 1.2em;\n text-align: center;\n }\n `),a&&(s.innerText+=`\n #${t} {\n opacity: 1;\n }\n .${r} .${a} {\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 .${r} .${a}::after, .${r} .${a}::before {\n position: absolute;\n left: 8px;\n content: '';\n height: 16px;\n width: 2px;\n background-color: #fff;\n }\n .${r} .${a}::after {\n transform: rotate(-45deg);\n }\n .${r} .${a}::before {\n transform: rotate(45deg);\n }\n `),s}({id:i,background:n,transitionDuration:r,classLayout:d,classOverlayText:l,classClose:c})),{element:t,closeElement:s,mainElement:u}}_addEventListener(e,t){e&&t&&e.addEventListener("click",t)}_removeEventListener(e,t){e&&t&&e.removeEventListener("click",t)}_registerClick(e){if(this._unregisterClick&&this._unregisterClick(),e){const{onClick:t,onClickClose:n}=e;this._addEventListener(this._element,t),this._addEventListener(this._closeElement,n),this._unregisterClick=()=>{this._removeEventListener(this._element,t),this._removeEventListener(this._closeElement,n),this._unregisterClick=void 0}}}_removeAfterTransition(){const e=t=>{"opacity"===t.propertyName&&(this._mainElement.parentElement&&this._mainElement.remove(),this._element.removeEventListener("transitionend",e))};this._element.addEventListener("transitionend",e)}}const Pl={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"};function Ol(e){return"object"==typeof e&&null!==e&&"name"in e&&"BraintreeError"===e.name}function El(e){return{recipientName:`${e.firstName} ${e.lastName}`,line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,postalCode:e.postalCode,countryCode:e.countryCode,phone:e.phone}}var Al=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Tl{constructor(e,t,n,i){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeMessages=n,this.loadingIndicator=i,this.braintreeHostWindow=window}initialize(e){return Al(this,void 0,void 0,function*(){const{braintree:t,methodId:n}=e;if((null==t?void 0:t.containerId)&&(this.braintreeButtonOptions=t),this.paymentMethod&&this.paymentMethod.nonce||(this.paymentMethod=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n)),this.paymentMethod.clientToken&&(null==t?void 0:t.bannerContainerId))return yield this.loadPaypal(),this.loadPaypalCheckoutInstance(t);if(this.paymentMethod.clientToken)return this.loadPaypal();const i=yield this.paymentIntegrationService.loadPaymentMethod(n);if(this.paymentMethod=i.getPaymentMethodOrThrow(n),null==t?void 0:t.bannerContainerId)return this.loadPaypalCheckoutInstance(t);if(!this.paymentMethod.clientToken)throw new ti(Xn.MissingPaymentMethod);return this.loadPaypal()})}execute(e,t){var n;return Al(this,void 0,void 0,function*(){const{payment:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{o&&"function"==typeof o&&o(new Error("INSTRUMENT_DECLINED")),t()})),this.handleError(e)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.braintreeTokenizePayload=void 0,null===(e=this.paypalButtonRender)||void 0===e||e.close(),this.braintreeIntegrationService.teardown()}preparePaymentData(e,t){var n;return Al(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),r=i.getOutstandingBalance(t),o=i.getStoreConfig();if(!r)throw new ti(Xn.MissingCheckout);if(!o)throw new ti(Xn.MissingCheckoutConfig);if(!this.paymentMethod)throw new ri(ei.PaymentNotInitialized);const{currency:a,storeProfile:{storeLanguage:s}}=o,{nonce:d,config:{isVaultingEnabled:c}}=this.paymentMethod,{methodId:l,paymentData:u={}}=e,h=(null===(n=this.braintreeTokenizePayload)||void 0===n?void 0:n.nonce)||d;if(h){const t=yield this.paymentIntegrationService.loadPaymentMethod(l);return this.paymentMethod=t.getPaymentMethod(l),Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(h)})}if(xd(u)||(p=u,Boolean(p.instrumentId)&&!Object.prototype.hasOwnProperty.call(p,"ccNumber")&&!Object.prototype.hasOwnProperty.call(p,"ccCvv"))){if(!c)throw new fi("Vaulting is disabled but a vaulted instrument was being used for this transaction");return Promise.resolve(e)}var p;if(!jd(u))throw new ti(Xn.MissingPayment);const{shouldSaveInstrument:m,shouldSetAsDefaultInstrument:y}=u;if(m&&!c)throw new fi("Vaulting is disabled but shouldSaveInstrument is set to true");const g=i.getShippingAddress(),v=g?El(g):void 0;return Promise.all([this.braintreeIntegrationService.paypal({amount:r,locale:s,currency:a.code,offerCredit:"braintreepaypalcredit"===this.paymentMethod.id,shippingAddressOverride:v,shouldSaveInstrument:m||!1,shippingAddressEditable:!1}),this.braintreeIntegrationService.getSessionId()]).then(([{nonce:t,details:n}={},i])=>Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(t,n&&n.email,i,m,y)}))})}formattedPayload(e,t,n,i,r){return{formattedPayload:{vault_payment_instrument:i||null,set_as_default_stored_instrument:r||null,device_info:n||null,paypal_account:{token:e,email:t||null}}}}loadPaypalCheckoutInstance(e){return Al(this,void 0,void 0,function*(){const{clientToken:t,initializationData:n,id:i}=this.paymentMethod||{};if(!t)throw new ti(Xn.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(t);const r={currency:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,intent:null==n?void 0:n.intent,isCreditEnabled:null==n?void 0:n.isCreditEnabled},o="braintreepaypalcredit"===i||!(null==n?void 0:n.isCreditEnabled);yield this.braintreeIntegrationService.getPaypalCheckout(r,t=>{o&&i&&(null==e?void 0:e.bannerContainerId)&&this.renderPayPalMessages(i,e.bannerContainerId),this.renderPayPalButton(t,e)},this.handleError)}catch(e){this.handleError(e)}})}renderPayPalMessages(e,t){this.braintreeMessages.render(e,t,fo.PAYMENT)}renderPayPalButton(e,t){const{onPaymentError:n,submitForm:i,onRenderButton:r,containerId:o,onError:a}=t||{};if(!o)return;const s=this.getSmartButtonContainerId(o);if(!document.getElementById(s))throw new fi(`Unable to initialize payment because element with id ${o} does not exist.`);if(!this.paymentMethod)throw new ri(ei.PaymentNotInitialized);this.loadingIndicatorContainer=o.split("#")[1];const{id:d,config:{testMode:c}}=this.paymentMethod,{paypal:l}=this.braintreeHostWindow,u=null==l?void 0:l.FUNDING.PAYPAL;l&&u?(this.paypalButtonRender=l.Buttons({env:c?"sandbox":"production",commit:!1,fundingSource:u,onClick:()=>{this.toggleLoadingIndicator(!0)},createOrder:()=>this.setupPayment(e,d,n),onApprove:t=>Al(this,void 0,void 0,function*(){this.braintreeTokenizePayload=yield this.tokenizePaymentOrThrow(t,e),i&&"function"==typeof i&&i()}),onCancel:()=>{this.toggleLoadingIndicator(!1)},onError:e=>{this.toggleLoadingIndicator(!1),null==a||a(e)}}),r&&"function"==typeof r&&r(),this.paypalButtonRender.isEligible()&&this.paypalButtonRender.render(`${o}`)):this.removeElement(o.split("#")[1])}setupPayment(e,t,n){return Al(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState();try{const n=i.getCustomer(),r=i.getPaymentMethodOrThrow(t),o=i.getCheckoutOrThrow().outstandingBalance,a=i.getStoreConfigOrThrow().currency.code,s=i.getShippingAddress()||(null==n?void 0:n.addresses[0]),d=s?El(s):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:d,amount:o,currency:a,offerCredit:!1,intent:r.initializationData.intent})}catch(e){throw n&&(Ol(e)||e instanceof Qn)&&n(e),e}})}tokenizePaymentOrThrow(e,t,n){return Al(this,void 0,void 0,function*(){try{return yield t.tokenizePayment(e)}catch(e){throw n&&(Ol(e)||e instanceof Qn)&&n(e),e}})}loadPaypal(){return Al(this,void 0,void 0,function*(){const{clientToken:e,initializationData:t}=this.paymentMethod||{};if(!e||!t)throw new ti(Xn.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(e),yield this.braintreeIntegrationService.getPaypal()}catch(e){this.handleError(e)}return Promise.resolve()})}handleError(e){if(!Ol(e))throw e;if("PAYPAL_POPUP_CLOSED"===e.code)throw new Wi(e.message);throw new Qr(e.message)}isProviderError(e){var t,n,i;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"2046"===(null===(i=null===(n=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===n?void 0:n.provider_error)||void 0===i?void 0:i.code)}removeElement(e){const t=e&&document.getElementById(e);t&&t.remove()}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}getSmartButtonContainerId(e){var t;return null!==(t=e.split("#")[1])&&void 0!==t?t:e}}const kl=vi(e=>{const t=window,n=new bl,i=new Ei(e),r=new _o(new Hi(a(),t,i),t,n),o=new Cl(e);return new Tl(e,r,o,new vd({containerStyles:Pl}))},[{id:"braintreepaypal"},{id:"braintreepaypalcredit"}]);class Dl{constructor(e){this.requestSender=e}getOrderStatus(e="braintreelocalmethods",t){return n=this,i=void 0,o=function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}var Ml=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class zl{constructor(e,t,n,i,r=3e3,o=3e5){this.paymentIntegrationService=e,this.braintreeSdk=t,this.braintreeRequestSender=n,this.loadingIndicator=i,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.isLPMsUpdateExperimentEnabled=!1,this.pollingTimer=0,this.stopPolling=ce,this.isPollingEnabled=!1}initialize(e){return Ml(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,braintreelocalmethods:i}=e;if(this.gatewayId=t,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.braintreelocalmethods" argument is not provided.');this.braintreelocalmethods=i,this.loadingIndicatorContainer=i.container.split("#")[1],yield this.paymentIntegrationService.loadPaymentMethod(t);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(t),{clientToken:a,config:s,initializationData:d}=o,c=r.getStoreConfigOrThrow().checkoutSettings.features;if(this.isPollingEnabled=Ci(c,"PAYPAL-5258.braintree_local_methods_polling"),this.isLPMsUpdateExperimentEnabled=Ci(c,"PAYPAL-4853.add_new_payment_flow_for_braintree_lpms"),!a||!d||!s.merchantId)throw new ti(Xn.MissingPaymentMethod);try{this.braintreeSdk.initialize(a),this.isNonInstantPaymentMethod(n)||(this.braintreeLocalPayment=yield this.braintreeSdk.getBraintreeLocalPayment(s.merchantId))}catch(e){this.handleError(e)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return Ml(this,void 0,void 0,function*(){return this.toggleLoadingIndicator(!1),Promise.resolve()})}execute(e,t){return Ml(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{window.location.replace(t),this.toggleLoadingIndicator(!1),n()})}return this.handleError(e),Promise.reject(e)}})}executeWithInstantLPM(e,t,n){return Ml(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment)throw new Xr;yield new Promise((i,r)=>{var o;null===(o=this.braintreeLocalPayment)||void 0===o||o.startPayment(this.getInstantLPMConfig(e,t,n),this.getInstantLPMCallback(i,r,e,t,n))})})}getLPMsBasicPaymentData(){return Ml(this,void 0,void 0,function*(){const{deviceData:e}=yield this.braintreeSdk.getDataCollectorOrThrow();return{deviceSessionId:e}})}getInstantLPMConfig(e,t,n){const i=this.paymentIntegrationService.getState(),r=i.getCartOrThrow(),o=i.getBillingAddressOrThrow(),{firstName:a,lastName:s,countryCode:d}=o,{currency:c,email:l,lineItems:u}=r,h=u.physicalItems.length>0,p=i.getCheckoutOrThrow().outstandingBalance,m=i.getStoreConfigOrThrow().links.checkoutLink;return{paymentType:e,amount:p,fallback:{url:m,buttonText:"Complete Payment"},currencyCode:c.code,shippingAddressRequired:h,email:l,givenName:a,surname:s,address:{countryCode:d},onPaymentStart:(i,r)=>Ml(this,void 0,void 0,function*(){if(!this.isLPMsUpdateExperimentEnabled)return this.orderId=i.paymentId,void r();const o=yield this.getLPMsBasicPaymentData(),a=Object.assign(Object.assign({},o),{formattedPayload:{method:e,[`${e}_account`]:{order_id:i.paymentId}}});try{yield this.paymentIntegrationService.submitOrder(t,n),yield this.paymentIntegrationService.submitPayment({methodId:e,paymentData:a})}catch(t){if(this.isBraintreeOrderSavedResponse(t)&&t.body.additional_action_required.data.order_id_saved_successfully)return r(),this.isPollingEnabled?new Promise((t,n)=>{this.initializePollingMechanism(e,t,n,this.gatewayId)}):void 0;throw t}})}}getInstantLPMCallback(e,t,n,i,r){const o=this.paymentIntegrationService.getState().getCartOrThrow();return(a,s)=>Ml(this,void 0,void 0,function*(){if(a)return"LOCAL_PAYMENT_WINDOW_CLOSED"===a.code?(this.toggleLoadingIndicator(!1),this.resetPollingMechanism(),t()):(this.isPollingEnabled&&this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t(new Xr));const d=yield this.getLPMsBasicPaymentData(),c=Object.assign(Object.assign({},d),{formattedPayload:{method:n,[`${n}_account`]:Object.assign({email:o.email,token:s.nonce},this.isLPMsUpdateExperimentEnabled?{}:{order_id:this.orderId})}});try{return this.isLPMsUpdateExperimentEnabled||(yield this.paymentIntegrationService.submitOrder(i,r)),yield this.paymentIntegrationService.submitPayment({methodId:n,paymentData:c}),e(void 0)}catch(e){return this.handleError(e),t(e)}})}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}handleError(e){const{onError:t}=this.braintreelocalmethods||{};this.isPollingEnabled&&this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}isNonInstantPaymentMethod(e){return e.toUpperCase()in Di}isBraintreeRedirectError(e){var t;if("object"!=typeof e||null===e)return!1;const{body:n}=e;return!!n&&!!(null===(t=n.additional_action_required)||void 0===t?void 0:t.data.redirect_url)}isBraintreeOrderSavedResponse(e){var t;if("object"!=typeof e||null===e)return!1;const{body:n}=e;return!!n&&(null===(t=n.additional_action_required)||void 0===t?void 0:t.data.hasOwnProperty("order_id_saved_successfully"))}initializePollingMechanism(e,t,n,i){return Ml(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.braintreeRequestSender.getOrderStatus(i,{params:{useMetadata:!1}}),o=r.status===ki.Pending,a=r.status===ki.Completed,s=r.status===ki.Failed;if(a)return this.deinitializePollingMechanism(),t();if(s)return n();if(!a&&o&&this.pollingTimer{const t=window,i=new Ei(e),r=new Ui(new Hi(a(),t,i)),o=n(),s=new Dl(o);return new zl(e,r,s,new vd({styles:{backgroundColor:"black"}}))},[{gateway:"braintreelocalmethods"}]);function xl(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var Rl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Fl{constructor(e,t,n){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.braintreeSdk=n}initialize(e){var t;return Rl(this,void 0,void 0,function*(){const{methodId:n,braintreefastlane:i}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.braintreefastlane" argument is not provided.');if(!i.onInit||"function"!=typeof i.onInit)throw new fi('Unable to initialize payment because "options.braintreefastlane.onInit" argument is not provided or it is not a function.');if(!i.onChange||"function"!=typeof i.onChange)throw new fi('Unable to initialize payment because "options.braintreefastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(n);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(n),{initializationData:a,clientToken:s}=o||{},{isFastlaneStylingEnabled:d}=a||{},c=Ci(r.getStoreConfigOrThrow().checkoutSettings.features,"PROJECT-7080.braintree_fastlane_three_ds");this.is3DSEnabled=o.config.is3dsEnabled,s&&c&&this.braintreeSdk.initialize(s);const l=Ao(d?null===(t=o.initializationData)||void 0===t?void 0:t.fastlaneStyles:void 0,i.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(n,l),this.shouldRunAuthenticationFlow()&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow()),yield this.initializeCardComponent(),this.onError=i.onError,i.onInit(e=>this.renderBraintreeCardComponent(e)),i.onChange(()=>this.handleBraintreeStoredInstrumentChange(n))})}execute(e,t){return Rl(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{i.verifyCard({amount:null==r?void 0:r.orderAmount,nonce:e,bin:t,onLookupComplete:(e,t)=>{i.on("customer-canceled",()=>{"function"==typeof this.onError&&this.onError(new Wi),o(new Wi)}),t()}},(e,t)=>(e&&"THREEDS_VERIFY_CARD_CANCELED_BY_MERCHANT"===e.code&&("function"==typeof this.onError&&this.onError(new Wi),o(new Wi)),n(t.nonce)))})})}mapToPayPalAddress(e){return{streetAddress:(null==e?void 0:e.address1)||"",locality:(null==e?void 0:e.city)||"",region:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCodeAlpha2:(null==e?void 0:e.countryCode)||""}}shouldRunAuthenticationFlow(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getCustomerOrThrow(),i=e.getPaymentProviderCustomer(),r=xl(i)?i:{},o=this.braintreeFastlaneUtils.getSessionIdFromCookies();return!(!n.isGuest||(null==r?void 0:r.authenticationState)===Mi.CANCELED||(null==r?void 0:r.authenticationState)||o!==t.id)}getBraintreeCardComponentOrThrow(){if(!this.braintreeCardComponent)throw new mi;return this.braintreeCardComponent}getPayPalInstruments(){const e=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow();return(xl(e)?e:{}).instruments||[]}handleBraintreeStoredInstrumentChange(e){return Rl(this,void 0,void 0,function*(){const t=this.braintreeFastlaneUtils.getBraintreeFastlaneOrThrow(),{selectionChanged:n,selectedCard:i}=yield t.profile.showCardSelector();if(n){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),n=xl(t)?t:{},r=this.braintreeFastlaneUtils.mapPayPalToBcInstrument(e,[i]);if(r&&r.length>0)return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},n),{instruments:[...r]})),r[0]}})}}const Ll=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t),r=new Mo(e,i),o=new Hi(a(),t,n),s=new Ui(o);return new Fl(e,r,s)},[{id:"braintreeacceleratedcheckout"}]);var Bl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class jl{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n}initialize(e){return Bl(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:n}=e;if(!t)throw new fi('Unable to initialize payment because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState();this.paymentMethod=i.getPaymentMethodOrThrow(n);const r=i.getCheckoutOrThrow(),o=i.getStoreConfigOrThrow(),{clientToken:a,config:s}=this.paymentMethod||{};if(!a)throw new ti(Xn.MissingPaymentMethod);const{onError:d=ce,onPaymentSelect:c=ce}=t;this.braintreeSdk.initialize(a);const l=yield this.braintreeSdk.getBraintreeVisaCheckout(),u=yield this.braintreeSdk.getVisaCheckoutSdk(null==s?void 0:s.testMode),h=l.createInitOptions({settings:{locale:o.storeProfile.storeLanguage,shipping:{collectShipping:!1}},paymentRequest:{currencyCode:o.currency.code,subtotal:String(r.subtotal)}});yield u.init(h),u.on("payment.success",e=>this.tokenizePayment(l,e).then(()=>Promise.all([this.paymentIntegrationService.loadCheckout(),this.paymentIntegrationService.loadPaymentMethod(n)])).then(()=>c()).catch(e=>d(e))),u.on("payment.error",(e,t)=>d(t))})}execute(e,t){var n,i;return Bl(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const n=this.paymentIntegrationService.getState(),i=n.getShippingAddress(),r=n.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(i),billingAddress:a=this.mapToVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}mapToVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}postForm(e,t){const{userData:n,billingAddress:i,shippingAddress:r,details:o}=e,{userEmail:a}=n,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,i)),shipping_address:JSON.stringify(this.getAddress(a,r))})}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}handleError(e){if(e instanceof Error&&"BraintreeError"===e.name)throw new Qr(e.message);throw e}}const Ul=vi(e=>{const t=window,n=new Ei(e),i=new Ui(new Hi(a(),t,n));return new jl(e,Ee(),i)},[{id:"braintreevisacheckout"}]);var ql=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vl{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}initialize(e){return ql(this,void 0,void 0,function*(){const{methodId:t}=e;yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState();this.venmoOptions=e.braintreevenmo;const i=n.getPaymentMethodOrThrow(t);yield this.initializeBraintreeVenmo(i)})}execute(e){return ql(this,void 0,void 0,function*(){const{payment:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{var n;null===(n=this.braintreeVenmoCheckout)||void 0===n||n.tokenize((n,i)=>{if(n)return t(n);e(i)})})}}const Gl=vi(e=>{const t=window,n=a(),i=new Ei(e),r=new Hi(n,t,i),o=new _o(r,t);return new Vl(e,o)},[{id:"braintreevenmo"}]);var Hl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Wl{constructor(e,t,n){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeHostedForm=n}initialize(e){return Hl(this,void 0,void 0,function*(){const{methodId:t,gatewayId:n,braintree:i}=e;yield this.paymentIntegrationService.loadPaymentMethod(t);const r=this.paymentIntegrationService.getState();this.paymentMethod=r.getPaymentMethodOrThrow(t);const{clientToken:o}=this.paymentMethod;if(!o)throw new ti(Xn.MissingPaymentMethod);this.threeDSecure=null==i?void 0:i.threeDSecure,this.onPaymentError=null==i?void 0:i.onPaymentError;try{this.braintreeIntegrationService.initialize(o,this.threeDSecure),this.isHostedPaymentFormEnabled(t,n)&&(null==i?void 0:i.form)&&(yield this.braintreeHostedForm.initialize(i.form,i.unsupportedCardBrands,o),this.isHostedFormInitialized=this.braintreeHostedForm.isInitialized()),this.is3dsEnabled=this.paymentMethod.config.is3dsEnabled,this.deviceSessionId=yield this.braintreeIntegrationService.getSessionId(),this.shouldInitializeBraintreeFastlane()&&(yield this.initializeBraintreeFastlaneOrThrow(t))}catch(e){return this.handleError(e,t)}})}execute(e){return Hl(this,void 0,void 0,function*(){const{payment:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r"string"==typeof e));var n}var Kl,Jl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e[e.CreditCard=0]="CreditCard",e[e.StoredCardVerification=1]="StoredCardVerification"}(Kl||(Kl={}));class Zl{constructor(e,t){this.braintreeScriptLoader=e,this.braintreeSDKVersionManager=t,this.isInitializedHostedForm=!1,this.handleBlur=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onBlur)||void 0===n||n.call(t,{fieldType:this.mapFieldType(e.emittedBy),errors:this.mapErrors(e.fields)})},this.handleFocus=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onFocus)||void 0===n||n.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleCardTypeChange=e=>{var t,n;const i=1===e.cards.length?e.cards[0].type.replace(/^master-card$/,"mastercard"):void 0;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onCardTypeChange)||void 0===n||n.call(t,{cardType:i})},this.handleInputSubmitRequest=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onEnter)||void 0===n||n.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleValidityChange=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===n||n.call(t,{isValid:this.isValidForm(e),errors:this.mapValidationErrors(e.fields)})}}initialize(e,t,n){var i,r,o,a,s;return Jl(this,void 0,void 0,function*(){this.clientToken=n,this.formOptions=e,this.type=$l(e.fields)?Kl.CreditCard:Kl.StoredCardVerification;const d=this.mapFieldOptions(e.fields,t);$(d)?this.isInitializedHostedForm=!1:(this.cardFields=yield this.createHostedFields({fields:d,styles:e.styles&&this.mapStyleOptions(e.styles)}),null===(i=this.cardFields)||void 0===i||i.on("blur",this.handleBlur),null===(r=this.cardFields)||void 0===r||r.on("focus",this.handleFocus),null===(o=this.cardFields)||void 0===o||o.on("cardTypeChange",this.handleCardTypeChange),null===(a=this.cardFields)||void 0===a||a.on("validityChange",this.handleValidityChange),null===(s=this.cardFields)||void 0===s||s.on("inputSubmitRequest",this.handleInputSubmitRequest),this.isInitializedHostedForm=!0)})}isInitialized(){return!!this.isInitializedHostedForm}deinitialize(){var e;return Jl(this,void 0,void 0,function*(){this.isInitializedHostedForm&&(this.isInitializedHostedForm=!1,yield null===(e=this.cardFields)||void 0===e?void 0:e.teardown())})}validate(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);const e=this.cardFields.getState();if(!this.isValidForm(e)){this.handleValidityChange(e);const t=this.mapValidationErrors(e.fields);throw new lo(t)}}tokenize(e){var t,n,i,r,o;return Jl(this,void 0,void 0,function*(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);try{const r=yield this.cardFields.tokenize(ue({billingAddress:e&&this.mapBillingAddress(e)},J));return null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===n||n.call(t,{isValid:!0,errors:{}}),{nonce:r.nonce,bin:null===(i=r.details)||void 0===i?void 0:i.bin}}catch(e){if(Yl(e)){const t=this.mapTokenizeError(e);if(t)throw null===(o=null===(r=this.formOptions)||void 0===r?void 0:r.onValidate)||void 0===o||o.call(r,{isValid:!1,errors:t}),new lo(t)}throw e}})}tokenizeForStoredCardVerification(){var e,t,n,i,r;return Jl(this,void 0,void 0,function*(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);try{const i=yield this.cardFields.tokenize();return null===(t=null===(e=this.formOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,{isValid:!0,errors:{}}),{nonce:i.nonce,bin:null===(n=i.details)||void 0===n?void 0:n.bin}}catch(e){if(Yl(e)){const t=this.mapTokenizeError(e,!0);if(t)throw null===(r=null===(i=this.formOptions)||void 0===i?void 0:i.onValidate)||void 0===r||r.call(i,{isValid:!1,errors:t}),new lo(t)}throw e}})}createHostedFields(e){return Jl(this,void 0,void 0,function*(){const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadHostedFields(),i=this.braintreeSDKVersionManager.getSDKVersion()===bi?Object.assign(Object.assign({},e),{preventCursorJumps:!0}):e;return n.create(Object.assign(Object.assign({},i),{client:t}))})}getClient(){return Jl(this,void 0,void 0,function*(){if(!this.clientToken)throw new ri(ei.PaymentNotInitialized);if(!this.client){const e=yield this.braintreeScriptLoader.loadClient();this.client=e.create({authorization:this.clientToken})}return this.client})}mapBillingAddress(e){return{countryName:e.country,postalCode:e.postalCode,streetAddress:e.address2?`${e.address1} ${e.address2}`:e.address1}}mapFieldOptions(e,t){if($l(e)){const n={};return null==t||t.forEach(e=>{(e=>Object.values(xi).includes(e))(e)&&(n[e]=!1)}),ue({number:Object.assign({container:`#${e.cardNumber.containerId}`,placeholder:e.cardNumber.placeholder,internalLabel:e.cardNumber.accessibilityLabel},Object.keys(n).length>0?{supportedCardBrands:n}:{}),expirationDate:{container:`#${e.cardExpiry.containerId}`,placeholder:e.cardExpiry.placeholder,internalLabel:e.cardExpiry.accessibilityLabel},cvv:e.cardCode&&{container:`#${e.cardCode.containerId}`,placeholder:e.cardCode.placeholder,internalLabel:e.cardCode.accessibilityLabel},cardholderName:{container:`#${e.cardName.containerId}`,placeholder:e.cardName.placeholder,internalLabel:e.cardName.accessibilityLabel}},J)}return ue({number:e.cardNumberVerification&&{container:`#${e.cardNumberVerification.containerId}`,placeholder:e.cardNumberVerification.placeholder},cvv:e.cardCodeVerification&&{container:`#${e.cardCodeVerification.containerId}`,placeholder:e.cardCodeVerification.placeholder}},J)}mapStyleOptions(e){const t=(e={})=>ue({color:e.color,"font-family":e.fontFamily,"font-size":e.fontSize,"font-weight":e.fontWeight},J);return{input:t(e.default),".invalid":t(e.error),":focus":t(e.focus)}}mapFieldType(e){switch(e){case"number":return this.type===Kl.StoredCardVerification?Bi.CardNumberVerification:Bi.CardNumber;case"expirationDate":return Bi.CardExpiry;case"cvv":return this.type===Kl.StoredCardVerification?Bi.CardCodeVerification:Bi.CardCode;case"cardholderName":return Bi.CardName;default:throw new Error("Unexpected field type")}}mapErrors(e){const t={};if(e)for(const[n,i]of Object.entries(e))if(i&&this.isValidParam(n)){const{isValid:e,isEmpty:r,isPotentiallyValid:o}=i;t[n]={isValid:e,isEmpty:r,isPotentiallyValid:o}}return t}mapValidationErrors(e){return Object.keys(e).reduce((t,n)=>{var i;return Object.assign(Object.assign({},t),{[this.mapFieldType(n)]:(null===(i=e[n])||void 0===i?void 0:i.isValid)?void 0:[this.createInvalidError(this.mapFieldType(n))]})},{})}mapTokenizeError(e,t=!1){var n,i;if("HOSTED_FIELDS_FIELDS_EMPTY"===e.code){const e=[this.createRequiredError(this.mapFieldType("cvv"))];return t?{[this.mapFieldType("cvv")]:e}:{[this.mapFieldType("cvv")]:e,[this.mapFieldType("expirationDate")]:[this.createRequiredError(this.mapFieldType("expirationDate"))],[this.mapFieldType("number")]:[this.createRequiredError(this.mapFieldType("number"))],[this.mapFieldType("cardholderName")]:[this.createRequiredError(this.mapFieldType("cardholderName"))]}}return null===(i=null===(n=e.details)||void 0===n?void 0:n.invalidFieldKeys)||void 0===i?void 0:i.reduce((e,t)=>{const n=this.mapFieldType(t);return Object.assign(Object.assign({},e),{[n]:[this.createInvalidError(n)]})},{})}createRequiredError(e){var t;return{fieldType:e,message:null!==(t={[Bi.CardCode]:"CVV is required",[Bi.CardCodeVerification]:"CVV is required",[Bi.CardNumber]:"Credit card number is required",[Bi.CardNumberVerification]:"Credit card number is required",[Bi.CardExpiry]:"Expiration date is required",[Bi.CardName]:"Full name is required"}[e])&&void 0!==t?t:"Field is required",type:"required"}}createInvalidError(e){var t,n,i,r;const o={[Bi.CardCode]:{message:"Invalid card code",type:"invalid_card_code"},[Bi.CardCodeVerification]:{message:"Invalid card code",type:"invalid_card_code"},[Bi.CardNumber]:{message:"Invalid card number",type:"invalid_card_number"},[Bi.CardNumberVerification]:{message:"Invalid card number",type:"invalid_card_number"},[Bi.CardExpiry]:{message:"Invalid card expiry",type:"invalid_card_expiry"},[Bi.CardName]:{message:"Invalid card name",type:"invalid_card_name"}};return{fieldType:e,message:null!==(n=null===(t=o[e])||void 0===t?void 0:t.message)&&void 0!==n?n:"Invalid field",type:null!==(r=null===(i=o[e])||void 0===i?void 0:i.type)&&void 0!==r?r:"invalid"}}isValidForm(e){return Object.keys(e.fields).every(t=>{var n;return null===(n=e.fields[t])||void 0===n?void 0:n.isValid})}isValidParam(e){return["number","cvv","expirationDate","postalCode","cardholderName","cardType"].includes(e)}}const Ql=vi(e=>{const t=window,n=new Ei(e),i=new Hi(a(),t,n),r=new _o(i,t),o=new Zl(i,n);return new Wl(e,r,o)},[{id:"braintree"}]);var Xl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})},eu=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r(this._shouldRenderHostedForm=!0,this._hostedForm=r,Promise.resolve()))}deinitialize(){return this._hostedForm&&this._hostedForm.detach(),Promise.resolve()}finalize(){return Promise.reject(new Cd)}_executeWithoutHostedForm(e,t){return Xl(this,void 0,void 0,function*(){const{payment:n}=e,i=eu(e,["payment"]),r=n&&n.paymentData;if(!n||!r)throw new co(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(i,t),yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:r}))})}_executeWithHostedForm(e,t){return Xl(this,void 0,void 0,function*(){const{payment:n}=e,i=eu(e,["payment"]),r=this._hostedForm;if(!r)throw new ri(ei.PaymentNotInitialized);if(!n||!n.methodId)throw new co(["payment.methodId"]);yield this._paymentIntegrationService.submitOrder(i,t),yield r.validate().then(()=>r.submit(n))})}_isHostedPaymentFormEnabled(e,t){return!!e&&!0===this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t).config.isHostedFormEnabled}_isHostedFieldAvailable(e){return!Ce(e&&e.creditCard&&e.creditCard.form.fields).every(J)}}var nu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class iu extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this.cbaMGPSScriptLoader=t,this.sessionId=""}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return nu(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{methodId:n}=e;yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(n);if(!function(e){return"object"==typeof e&&null!==e&&"initializationData"in e&&"object"==typeof e.initializationData&&null!==e.initializationData&&"merchantId"in e.initializationData&&"string"==typeof e.initializationData.merchantId&&("boolean"==typeof e.initializationData.isTestModeFlagEnabled||void 0===e.initializationData.isTestModeFlagEnabled)}(r))throw new ti(Xn.MissingPaymentMethod);const{clientToken:o,initializationData:{isTestModeFlagEnabled:a=!1,merchantId:s},config:{is3dsEnabled:d}}=r;if(d){if(this.threeDSjs=yield this.cbaMGPSScriptLoader.load(a),!this.threeDSjs)throw new ri(ei.PaymentNotInitialized);if(!o||!s)throw new ti(Xn.MissingPaymentMethod);if(this.sessionId=o,this.locale=i.getLocale(),!this.locale)throw new ti(Xn.MissingCart);yield this.threeDSjs.configure({merchantId:s,sessionId:this.sessionId,callback:()=>{var e;if(null===(e=this.threeDSjs)||void 0===e?void 0:e.isConfigured())return this.paymentIntegrationService.getState();throw new Qr("Failed to configure 3DS API.")},configuration:{userLanguage:this.locale,wsVersion:62}})}return Promise.resolve()})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return nu(this,void 0,void 0,function*(){const{payment:i}=e,r=i&&i.paymentData;if(!i||!r)throw new co(["payment.paymentData"]);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i.methodId),{is3dsEnabled:a}=o.config;if(a){const t=Object.assign(Object.assign({},r),{threeDSecure:{token:this.sessionId}});e.payment&&(e.payment.paymentData=t)}return n.execute.call(this,e,t).catch(e=>{if(!a||!pa(e)||!ve(e.body.errors,{code:"three_d_secure_required"}))return Promise.reject(e);const t=this.paymentIntegrationService.getState(),n=t.getOrder(),{storeProfile:{storeId:i}}=t.getStoreConfigOrThrow();if(!n||!this.sessionId)throw new ti(Xn.MissingCheckout);const r=`${i}_${n.orderId}`;if("object"!=typeof(o=e.body)||null===o||!("three_ds_result"in o)||"object"!=typeof o.three_ds_result||null===o.three_ds_result||!("token"in o.three_ds_result)||"string"!=typeof o.three_ds_result.token)throw new nr;var o;const{three_ds_result:{token:s}}=e.body;return s?this.initiateAuthentication(r,s):Promise.reject(e)})})}finalize(e){return nu(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE?(yield this.paymentIntegrationService.finalizeOrder(e),Promise.resolve()):Promise.reject(new Cd)})}deinitialize(){return this.threeDSjs=void 0,this.sessionId="",super.deinitialize()}initiateAuthentication(e,t){return nu(this,void 0,void 0,function*(){const n=yield new Promise((n,i)=>{if(!this.threeDSjs)throw new ri(ei.PaymentNotInitialized);this.threeDSjs.initiateAuthentication(e,t,e=>{const t=e.error;return t?i(new Qr(t.msg)):this.threeDSjs&&"PROCEED"===e.gatewayRecommendation?n(e.restApiResponse):i(new Qr)})});if(n.transaction&&"AUTHENTICATION_AVAILABLE"===n.transaction.authenticationStatus)return this.authenticatePayer(e,t);throw new Qr})}authenticatePayer(e,t,n=1){return nu(this,void 0,void 0,function*(){return new Promise((i,r)=>{if(!this.threeDSjs)return r(new ri(ei.PaymentNotInitialized));this.threeDSjs.authenticatePayer(e,t,i=>nu(this,void 0,void 0,function*(){const o=i.error;return o?o.cause&&"SERVER_BUSY"===o.cause&&n<5?(yield new Promise(e=>setTimeout(e,3e3)),this.authenticatePayer(e,t,++n)):r(new Qr):new Promise(ce)}),{fullScreenRedirect:!0})})})}}class ru{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e){return t=this,n=void 0,r=function*(){if(yield this._scriptLoader.loadScript(`//${e?"test":"ap"}-gateway.mastercard.com/static/threeDS/1.3.0/three-ds.min.js`),!this._window.ThreeDS)throw new mi;return this._window.ThreeDS},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const ou=vi(e=>new iu(e,new ru(a())),[{id:"cba_mpgs"}]);var au;!function(e){e.OffsiteRedirect="offsite_redirect"}(au||(au={}));class su extends tu{constructor(e){super(e),this.paymentIntegrationService=e}finalize(e){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),Promise.reject(new Cd)}_executeWithHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{window.location.replace(e.data.redirect_url)})}}class du extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew du(e),[{gateway:"checkoutcom",id:"fawry"}]);function lu(e){return pa(e)&&ve(e.body.errors,{code:"three_d_secure_required"})}var uu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})},hu=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rthis.formPoster.postForm(t,{PaReq:n||null,TermUrl:i||null,MD:r||null}))}}const mu=vi(e=>new pu(e,Ee()),[{gateway:"checkoutcom",id:"credit_card"},{gateway:"checkoutcom",id:"card"}]);class yu extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew yu(e),[{gateway:"checkoutcom",id:"sepa"}]);class vu extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew vu(e),[{gateway:"checkoutcom",id:"ideal"}]);const Su=["boleto","oxxo","qpay","ideal"];class _u extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew _u(e),[{gateway:"checkoutcom"}]);var Iu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Cu{constructor(e,t){this._paymentIntegrationService=e,this._clearpayScriptLoader=t}initialize(e){return Iu(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:t}=this._paymentIntegrationService.getState(),n=t(e.methodId,e.gatewayId),i=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features;this._clearpaySdk=yield this._clearpayScriptLoader.load(n,i)})}deinitialize(){return this._clearpaySdk=void 0,Promise.resolve()}execute(e,t){return Iu(this,void 0,void 0,function*(){const{gatewayId:n,methodId:i}=e.payment||{};if(!n||!i)throw new co(["payment.gatewayId","payment.methodId"]);const r=this._paymentIntegrationService.getState(),{isStoreCreditApplied:o}=r.getCheckoutOrThrow();yield this._paymentIntegrationService.applyStoreCredit(o),yield this._paymentIntegrationService.validateCheckout(r.getCheckout(),t);const{countryCode:a}=r.getBillingAddressOrThrow();if(!this._isCountrySupported(a))throw new fi("Unable to proceed because billing country is not supported.");return yield this._loadPaymentMethod(n,i,t),yield this._redirectToClearpay(a,this._paymentIntegrationService.getState().getPaymentMethod(i,n)),new Promise(ce)})}finalize(e){var t,n,i;return Iu(this,void 0,void 0,function*(){const r=this._paymentIntegrationService.getState(),o=r.getPaymentId(),a=r.getContextConfig();if(!o)throw new ti(Xn.MissingCheckout);if(!a||!a.payment.token)throw new ti(Xn.MissingCheckoutConfig);const s={methodId:o.providerId,paymentData:{nonce:a.payment.token}};yield this._paymentIntegrationService.submitOrder({},e);try{yield this._paymentIntegrationService.submitPayment(s)}catch(e){if(yield this._paymentIntegrationService.forgetCheckout(o.providerId),yield this._paymentIntegrationService.loadPaymentMethods(),pa(e))throw new Kd(null===(i=null===(n=null===(t=e.body)||void 0===t?void 0:t.errors)||void 0===n?void 0:n[0])||void 0===i?void 0:i.message)}})}_redirectToClearpay(e,t){return Iu(this,void 0,void 0,function*(){if(!this._clearpaySdk||!t||!t.clientToken)throw new ri(ei.PaymentNotInitialized);return this._clearpaySdk.initialize({countryCode:e}),this._clearpaySdk.redirect({token:t.clientToken}),Promise.resolve()})}_isCountrySupported(e){return"GB"===e}_loadPaymentMethod(e,t,n){var i;return Iu(this,void 0,void 0,function*(){try{return yield this._paymentIntegrationService.loadPaymentMethod(e,Object.assign(Object.assign({},n),{params:Object.assign(Object.assign({},null==n?void 0:n.params),{method:t})}))}catch(e){if(e instanceof nr&&422===(null===(i=e.body)||void 0===i?void 0:i.status))throw new fi("Clearpay can't process your payment for this order, please try another payment method");throw e}})}}class bu{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e,t={}){return n=this,i=void 0,o=function*(){if(yield this._scriptLoader.loadScript(this._getScriptUrl(e.config.testMode,t)),!this._window.AfterPay)throw new mi;return this._window.AfterPay},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_getScriptUrl(e,t={}){const n=Ci(t,"PI-4555.clearpay_add_https_to_prod_script",!1);return e?n?"https://portal.sandbox.clearpay.co.uk/afterpay-async.js":"//portal.sandbox.clearpay.co.uk/afterpay-async.js":n?"https://portal.clearpay.co.uk/afterpay-async.js":"//portal.clearpay.co.uk/afterpay-async.js"}}const Pu=vi(e=>new Cu(e,new bu(a())),[{gateway:"clearpay"},{id:"clearpay"}]),Ou=vi(e=>new tu(e),[{default:!0}]);var Eu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Au{constructor(e,t){this._paymentIntegrationService=e,this._cardinalClient=t}prepare(e){return Eu(this,void 0,void 0,function*(){yield this._cardinalClient.load(e.id,e.config.testMode),yield this._cardinalClient.configure(yield this._getClientToken(e))})}start(e,t,n,i){return Eu(this,void 0,void 0,function*(){const{getCardInstrument:r,getPaymentMethodOrThrow:o}=this._paymentIntegrationService.getState(),{payment:{methodId:a="",paymentData:s={}}={}}=t,d=xd(s)&&r(s.instrumentId),c=d?d.iin:i&&i.getBin();c&&(yield this._cardinalClient.runBinProcess(c));try{return yield e(de(t,{payment:{paymentData:{threeDSecure:{token:o(a).clientToken}}}}),n)}catch(e){if(!pa(e)||!ve(e.body.errors,{code:"three_d_secure_required"}))throw e;const n=yield this._cardinalClient.getThreeDSecureData(e.body.three_ds_result,this._getOrderData());if(!i)return void(yield this._paymentIntegrationService.submitPayment(de(t.payment,{paymentData:{threeDSecure:n}})));yield i.submit(de(t.payment,{paymentData:{threeDSecure:n}}))}})}_getClientToken(e){return Eu(this,void 0,void 0,function*(){return e.clientToken?e.clientToken:(yield this._paymentIntegrationService.loadPaymentMethod(e.id),this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.id).clientToken||"")})}_getOrderData(){const e=this._paymentIntegrationService.getState(),t=e.getBillingAddressOrThrow(),n=e.getShippingAddress(),i=e.getCheckoutOrThrow(),r=e.getOrderOrThrow();return{billingAddress:t,shippingAddress:n,currencyCode:i.cart.currency.code,id:r.orderId.toString(),amount:i.cart.cartAmount}}}const Tu=[100004,1010,1011,1020];var ku,Du,Mu,zu,Nu,xu,Ru;!function(e){e.SetupCompleted="payments.setupComplete",e.Validated="payments.validated"}(ku||(ku={})),function(e){e.Init="init",e.Complete="complete",e.Confirm="confirm"}(Du||(Du={})),function(e){e.Success="SUCCESS",e.NoAction="NOACTION",e.Failure="FAILURE",e.Error="ERROR"}(Mu||(Mu={})),function(e){e.CCA="CCA",e.Paypal="Paypal",e.Wallet="Wallet",e.VisaCheckout="VisaCheckout",e.ApplePay="ApplePay",e.DiscoverWallet="DiscoverWallet"}(zu||(zu={})),function(e){e.BinProcess="bin.process"}(Nu||(Nu={})),function(e){e.CCA="cca"}(xu||(xu={})),function(e){e.Yes="Y",e.No="N"}(Ru||(Ru={}));class Fu{constructor(e){this._scriptLoader=e,this._provider="",this._testMode=!1,this._configurationToken=""}load(e,t=!1){return this._provider=e,this._testMode=t,this._sdk||(this._sdk=this._scriptLoader.load(e,t)),this._sdk.then(ce)}configure(e){if(this._configurationToken){if(this._configurationToken===e)return Promise.resolve();this._sdk=this._scriptLoader.load(`${this._provider}.${Date.now()}`,this._testMode)}return this._getClientSDK().then(t=>new Promise((n,i)=>{t.on(ku.SetupCompleted,()=>{t.off(ku.SetupCompleted),t.off(ku.Validated),this._configurationToken=e,n()}),t.on(ku.Validated,e=>{t.off(ku.SetupCompleted),t.off(ku.Validated),e.ActionCode===Mu.Error&&(H(Tu,e.ErrorNumber)&&i(new ti(Xn.MissingPaymentMethod)),i(new Qr(e.ErrorDescription)))}),t.setup(Du.Init,{jwt:e})}))}runBinProcess(e){return this._getClientSDK().then(t=>t.trigger(Nu.BinProcess,e).catch(ce)).then(e=>{if(!e||!e.Status)throw new ri(ei.PaymentNotInitialized)})}getThreeDSecureData(e,t){return this._getClientSDK().then(n=>new Promise((i,r)=>{n.on(ku.Validated,(e,t)=>{if(n.off(ku.Validated),!t)return r(new Qr(e.ErrorDescription?e.ErrorDescription:"An error was encountered while processing the transaction."));if(!e.ActionCode)return i({token:t});switch(e.ActionCode){case Mu.Success:return i({token:t});case Mu.NoAction:return e.ErrorNumber>0?r(new Qr(e.ErrorDescription)):e.Payment&&e.Payment.ExtendedData&&e.Payment.ExtendedData.SignatureVerification===Ru.Yes?i({token:t}):r(new Qr("Transaction signature could not be validated."));case Mu.Failure:return r(new Qr("User failed authentication or an error was encountered while processing the transaction."));case Mu.Error:return r(new Qr(e.ErrorDescription))}});const o={AcsUrl:e.acs_url,Payload:e.merchant_data},a=this._mapToPartialOrder(t,e.payer_auth_request);n.continue(xu.CCA,o,a)}))}_mapToPartialOrder(e,t){const n={BillingAddress:this._mapToCardinalAddress(e.billingAddress)};return e.paymentData&&(n.Account=this._mapToCardinalAccount(e.paymentData)),e.billingAddress.email&&(n.Email1=e.billingAddress.email),e.shippingAddress&&(n.ShippingAddress=this._mapToCardinalAddress(e.shippingAddress)),{Consumer:n,OrderDetails:{OrderNumber:e.id,Amount:e.amount,CurrencyCode:e.currencyCode,OrderChannel:"S",TransactionId:t}}}_mapToCardinalAccount(e){return{AccountNumber:Number(e.ccNumber),ExpirationMonth:Number(e.ccExpiry.month),ExpirationYear:Number(e.ccExpiry.year),NameOnAccount:e.ccName,CardCode:Number(e.ccCvv)}}_mapToCardinalAddress(e){const t={FirstName:e.firstName,LastName:e.lastName,Address1:e.address1,City:e.city,State:e.stateOrProvince,PostalCode:e.postalCode,CountryCode:e.countryCode};return e.address2&&(t.Address2=e.address2),e.phone&&(t.Phone1=e.phone),t}_getClientSDK(){if(!this._sdk)throw new ri(ei.PaymentNotInitialized);return this._sdk}}class Lu{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e,t){const n=t?"https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js":"https://static.client.cardinaltrusted.com/songbird/v2.0.0/songbird.js";return this._scriptLoader.loadScript(`${n}?v=${e}`).then(()=>{if(!this._window.Cardinal)throw new mi;return this._window.Cardinal})}}var Bu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ju extends tu{constructor(e,t){super(e),this._threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Bu(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),i=n(e.methodId);i.config.is3dsEnabled&&(yield this._threeDSecureFlow.prepare(i))})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return Bu(this,void 0,void 0,function*(){const{payment:{methodId:i=""}={}}=e,{getPaymentMethodOrThrow:r}=this._paymentIntegrationService.getState();return r(i).config.is3dsEnabled?this._threeDSecureFlow.start(n.execute.bind(this),e,t,this._hostedForm):n.execute.call(this,e,t)})}}const Uu=vi(e=>new ju(e,new Au(e,new Fu(new Lu(a())))),[{id:"cybersource"}]);var qu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vu{constructor(e,t){this._paymentIntegrationService=e,this._cardinalClient=t}prepare(e){return qu(this,void 0,void 0,function*(){yield this._cardinalClient.load(e.id,e.config.testMode)})}start(e,t,n,i){var r,o,a,s;return qu(this,void 0,void 0,function*(){const{getCardInstrument:d}=this._paymentIntegrationService.getState(),{payment:c={methodId:""}}=t,{paymentData:l={}}=c;try{return yield e(t,n)}catch(e){if(pa(e)&&"additional_action_required"===(null===(r=e.body)||void 0===r?void 0:r.status)){const t=null===(a=null===(o=e.body.additional_action_required)||void 0===o?void 0:o.data)||void 0===a?void 0:a.token,n=null===(s=e.body.three_ds_result)||void 0===s?void 0:s.payer_auth_request;yield this._cardinalClient.configure(t);const r=this._getBin(l,d,i);r&&(yield this._cardinalClient.runBinProcess(r));try{return yield this._submitPayment(c,{xid:n},i)}catch(e){if(pa(e)&&ve(e.body.errors,{code:"three_d_secure_required"})){const t=e.body.three_ds_result,n=null==t?void 0:t.payer_auth_request;return yield this._cardinalClient.getThreeDSecureData(t,this._getOrderData()),this._submitPayment(c,{token:n},i)}throw e}}throw e}})}_getOrderData(){const e=this._paymentIntegrationService.getState(),t=e.getBillingAddressOrThrow(),n=e.getShippingAddress(),{cart:{currency:{code:i},cartAmount:r}}=e.getCheckoutOrThrow();return{billingAddress:t,shippingAddress:n,currencyCode:i,id:e.getOrderOrThrow().orderId.toString(),amount:r}}_submitPayment(e,t,n){return qu(this,void 0,void 0,function*(){const i=de({},e,{paymentData:{threeDSecure:t}});n||(yield this._paymentIntegrationService.submitPayment(i)),yield null==n?void 0:n.submit(i)})}_getBin(e,t,n){const i=xd(e)&&t(e.instrumentId),r=function(e){const t=e;return!xd(t)&&"string"==typeof t.ccName&&"string"==typeof t.ccNumber&&"object"==typeof t.ccExpiry&&"string"==typeof t.ccExpiry.month&&"string"==typeof t.ccExpiry.year}(e)&&e.ccNumber,o=n?n.getBin():r;return(i?i.iin:o)||""}}var Gu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Hu extends tu{constructor(e,t){super(e),this._threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Gu(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),i=n(e.methodId);i.config.is3dsEnabled&&(yield this._threeDSecureFlow.prepare(i))})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return Gu(this,void 0,void 0,function*(){const{payment:{methodId:i=""}={}}=e,{getPaymentMethodOrThrow:r}=this._paymentIntegrationService.getState();return r(i).config.is3dsEnabled?this._threeDSecureFlow.start(n.execute.bind(this),e,t,this._hostedForm):n.execute.call(this,e,t)})}}const Wu=vi(e=>new Hu(e,new Vu(e,new Fu(new Lu(a())))),[{id:"cybersourcev2"},{id:"bnz"}]);function $u(e){return"object"==typeof e&&null!==e&&"errors"in e&&Array.isArray(e.errors)&&"code"in e.errors[0]&&"string"==typeof e.errors[0].code&&"provider_data"in e&&"object"==typeof e.provider_data}var Yu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ku extends ea{constructor(e,t){super("adyen",e),this._scriptLoader=t,this._service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Yu(this,void 0,void 0,function*(){yield i.initialize.call(this,e,t,n);const r=i.getPaymentMethod.call(this),o=this._service.getState().getStoreConfig();if(!o)throw new ti(Xn.MissingCheckoutConfig);return this._adyenClient=yield this._scriptLoader.load({environment:r.config.testMode?"test":"live",locale:o.storeProfile.storeLanguage}),Promise.resolve()})}getNonce(e){const t=Object.create(null,{getNonce:{get:()=>super.getNonce},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Yu(this,void 0,void 0,function*(){const n=yield t.getNonce.call(this,e),i=t.getPaymentMethod.call(this);return JSON.stringify({type:i.method,googlePayToken:n,browser_info:ss()})})}processAdditionalAction(e){return Yu(this,void 0,void 0,function*(){if(!pa(e)||!$u(e.body))throw e;const t=yield this._handleAction(e.body.provider_data);try{return yield this._service.submitPayment(t)}catch(e){return this.processAdditionalAction(e)}})}_handleAction(e){return new Promise((t,n)=>{const i=JSON.parse(e.action);this._getAdyenClient().createFromAction(i,{onAdditionalDetails:e=>{const n={methodId:i.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};t(n)},size:"05",onError:e=>n(e)}).mount("body"),n(new Wi)})}_getAdyenClient(){if(!this._adyenClient)throw new ri(ei.PaymentNotInitialized);return this._adyenClient}}var Ju=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Zu{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t,this._isDeinitializationBlocked=!1,this._loadingIndicator=new vd({containerStyles:yd})}initialize(e){var t,n;return Ju(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId)||!na(e.methodId))throw new fi('Unable to proceed because "methodId" is not a valid key.');this._methodId=e.methodId;const i=e[this._getMethodId()];if(!(null==i?void 0:i.walletButton))throw new fi("Unable to proceed without valid options.");const{walletButton:r,loadingContainerId:o}=i,a=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rs,this._getGooglePayClientOptions(null===(n=s.initializationData)||void 0===n?void 0:n.storeCountry)),this._addPaymentButton(r,a)})}execute({payment:e}){return Ju(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new co(["payment"]);yield this._paymentIntegrationService.submitOrder();const t=yield this._googlePayPaymentProcessor.getNonce(e.methodId),n=yield this._googlePayPaymentProcessor.extraPaymentData();try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:Object.assign({nonce:t},n)}))}catch(t){yield this._googlePayPaymentProcessor.processAdditionalAction(t,e.methodId)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this._isDeinitializationBlocked||(this._clickListener&&(null===(e=this._paymentButton)||void 0===e||e.removeEventListener("click",this._clickListener)),this._paymentButton=void 0,this._clickListener=void 0,this._methodId=void 0),Promise.resolve()}_addPaymentButton(e,t){if(this._paymentButton)return;const n=document.getElementById(e);if(!n)throw new fi("Unable to proceed without a walletButton.");this._paymentButton=n,this._clickListener=this._handleClick(t),this._paymentButton.addEventListener("click",this._clickListener)}_handleClick({onPaymentSelect:e,onError:t}){return n=>Ju(this,void 0,void 0,function*(){n.preventDefault();try{this._googlePayPaymentProcessor.setShouldRequestShipping(!1),yield this._googlePayPaymentProcessor.initializeWidget(),this._isDirectPayOnClickEnabled()?yield this._interactWithPaymentSheetAndPay():yield this._interactWithPaymentSheet()}catch(e){let n=e;if(this._toggleLoadingIndicator(!1),ta(e)){if("CANCELED"===e.statusCode)throw new Wi;n=new Qr(JSON.stringify(e))}throw null==t||t(new Qr("An error occurred while requesting your Google Pay payment details.")),n}finally{this._toggleBlockDeinitialization(!1)}null==e||e()})}_interactWithPaymentSheetAndPay(){return Ju(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet();this._toggleBlockDeinitialization(!0),this._toggleLoadingIndicator(!0);const t=this._getMethodId(),n=this._paymentIntegrationService.getState(),{features:i}=n.getStoreConfigOrThrow().checkoutSettings,r=Ci(i,"PI-5031.google_pay_dont_override_address"),o=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e);o&&!r&&(yield this._paymentIntegrationService.updateBillingAddress(o)),yield this._googlePayPaymentProcessor.setExternalCheckoutXhr(t,e),yield this._paymentIntegrationService.loadCheckout(),yield this._paymentIntegrationService.loadPaymentMethod(t);const a=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(t);yield this._googlePayPaymentProcessor.initialize(()=>a),yield this.execute({useStoreCredit:!1,payment:{methodId:t}}),this._completeCheckoutFlow()})}_completeCheckoutFlow(){window.location.replace("/checkout/order-confirmation"),this._toggleLoadingIndicator(!1),this._toggleBlockDeinitialization(!1)}_interactWithPaymentSheet(){return Ju(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet(),t=this._paymentIntegrationService.getState(),{features:n}=t.getStoreConfigOrThrow().checkoutSettings,i=Ci(n,"PI-5031.google_pay_dont_override_address");this._toggleBlockDeinitialization(!0),this._toggleLoadingIndicator(!0);const r=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e);r&&!i&&(yield this._paymentIntegrationService.updateBillingAddress(r)),yield this._googlePayPaymentProcessor.setExternalCheckoutXhr(this._getMethodId(),e),yield this._paymentIntegrationService.loadCheckout(),yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodId()),this._toggleLoadingIndicator(!1),this._toggleBlockDeinitialization(!1)})}_getMethodId(){return ii(this._methodId,()=>new ri(ei.PaymentNotInitialized))}_getIsSignedInOrThrow(){return Ju(this,void 0,void 0,function*(){try{return!!(yield this._googlePayPaymentProcessor.getNonce(this._getMethodId()))}catch(e){if(e instanceof ti&&e.subtype===Xn.MissingPaymentToken)return!1;throw e}})}_handleOfferTrigger(e){return Ju(this,void 0,void 0,function*(){let t=!1,n="Sign in to Google Pay first to apply or remove promo codes.";try{t=yield this._getIsSignedInOrThrow()}catch(e){e instanceof ti&&(n=e.message)}if(t){const{newOfferInfo:t,error:n}=yield this._googlePayPaymentProcessor.handleCoupons(e);return{newOfferInfo:t,error:n}}return{error:{reason:Ko.OFFER_INVALID,message:n,intent:Jo.OFFER}}})}_getGooglePayClientOptions(e){return this._googlePayPaymentProcessor.isWebViewWithRestrictions()?{}:{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:t,offerData:n})=>Ju(this,void 0,void 0,function*(){if(t!==Jo.INITIALIZE&&t!==Jo.OFFER)return;const{offerChangeTriggers:i}=this._googlePayPaymentProcessor.getCallbackTriggers(),{newOfferInfo:r,error:o}=i.includes(t)?yield this._handleOfferTrigger(n):{},a=o;yield this._paymentIntegrationService.loadCheckout();const{code:s}=this._paymentIntegrationService.getState().getCartOrThrow().currency,d=this._googlePayPaymentProcessor.getTotalPrice();return Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},e&&{countryCode:e}),{currencyCode:s,totalPriceStatus:Wo.FINAL,totalPrice:d})},r&&{newOfferInfo:r}),a&&{error:a})})}}}_isDirectPayOnClickEnabled(){const{features:e}=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings;return Ci(e,"PI-5111.google_pay_direct_pay_on_click")}_toggleBlockDeinitialization(e){this._isDeinitializationBlocked=e}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this._loadingIndicator.show(this._loadingIndicatorContainer):this._loadingIndicator.hide()}}const Qu=vi(e=>new Zu(e,new aa(da(),new Ku(e,new zd(a(),s())),n(),Ee())),[{id:"googlepayadyenv2"}]);var Xu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class eh extends ea{constructor(e,t){super("adyen",e),this._scriptLoader=t,this._service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Xu(this,void 0,void 0,function*(){yield i.initialize.call(this,e,t,n);const r=i.getPaymentMethod.call(this),o=this._service.getState().getStoreConfig();if(!o)throw new ti(Xn.MissingCheckoutConfig);return this._adyenClient=yield this._scriptLoader.load({environment:r.config.testMode?"test":"live",locale:o.storeProfile.storeLanguage}),Promise.resolve()})}processAdditionalAction(e){return Xu(this,void 0,void 0,function*(){if(!pa(e)||!$u(e.body))throw e;const t=yield this._handleAction(e.body.provider_data);try{return yield this._service.submitPayment(t)}catch(e){return this.processAdditionalAction(e)}})}getNonce(e){const t=Object.create(null,{getNonce:{get:()=>super.getNonce},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Xu(this,void 0,void 0,function*(){const n=yield t.getNonce.call(this,e),i=t.getPaymentMethod.call(this);return JSON.stringify({type:i.method,googlePayToken:n,browser_info:ss()})})}_handleAction(e){return new Promise((t,n)=>{const i=JSON.parse(e.action);this._getAdyenClient().createFromAction(i,{onAdditionalDetails:e=>{const n={methodId:i.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};t(n)},size:"05",onError:e=>n(e)}).mount("body"),n(new Wi)})}_getAdyenClient(){if(!this._adyenClient)throw new ri(ei.PaymentNotInitialized);return this._adyenClient}}const th=vi(e=>new Zu(e,new aa(da(),new eh(e,new Bd(a(),s())),n(),Ee())),[{id:"googlepayadyenv3"}]),nh=vi(e=>new Zu(e,new aa(da(),new ua(e),n(),Ee())),[{id:"googlepayauthorizenet"}]),ih=vi(e=>{const t=n();return new Zu(e,new aa(da(),new ga(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]),rh=vi(e=>new Zu(e,new aa(da(),new fa(e),n(),Ee())),[{id:"googlepaycybersourcev2"},{id:"googlepaybnz"}]),oh=vi(e=>new Zu(e,new aa(da(),new wa(e),n(),Ee())),[{id:"googlepayorbital"}]),ah=vi(e=>new Zu(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeupe"},{id:"googlepaystripeocs"}]),sh=vi(e=>new Zu(e,new aa(da(),new Ga(e),n(),Ee())),[{id:"googlepayworldpayaccess"}]),dh=vi(e=>{const t=n(),i=window,r=new Ei(e),o=new Ui(new Hi(a(),i,r));return new Zu(e,new aa(da(),new $a(e,o),t,Ee()))},[{id:"googlepaybraintree"}]);var ch,lh;!function(e){e.Approved="APPROVED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(ch||(ch={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(lh||(lh={}));var uh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class hh extends Zu{constructor(e,t,n,i){super(e,t),this._payPalCommerceSdk=n,this._requestSender=i}execute({payment:e}){return uh(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new co(["payment"]);const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow().id,{initializationData:i}=t.getPaymentMethodOrThrow(this._getMethodId()),{orderId:r}=yield this.getOrderId(n),{card_information:o}=i||{},a=yield this._googlePayPaymentProcessor.getNonce(e.methodId),s={tokenizationData:{type:"PAYMENT_GATEWAY",token:atob(a)},info:{cardNetwork:(null==o?void 0:o.type)||"",cardDetails:(null==o?void 0:o.number)||""},type:"CARD"};yield this.confirmOrder(r,s),yield this._paymentIntegrationService.submitOrder();try{const t={formattedPayload:{method_id:e.methodId,paypal_account:{order_id:r}}};yield this._paymentIntegrationService.submitPayment({methodId:e.methodId,paymentData:t})}catch(e){yield this._googlePayPaymentProcessor.processAdditionalAction(e)}})}confirmOrder(e,t){return uh(this,void 0,void 0,function*(){const n=this._paymentIntegrationService.getState(),i=n.getPaymentMethodOrThrow(this._getMethodId());if(!i.initializationData)throw new ti(Xn.MissingPaymentMethod);const r=n.getCartOrThrow().currency.code,o=yield this._payPalCommerceSdk.getPayPalGooglePaySdk(i,r,n.getLocale(),!0),{status:a}=yield o.Googlepay().confirmOrder({orderId:e,paymentMethodData:t});if(a===ch.PayerActionRequired)return yield o.Googlepay().initiatePayerAction({orderId:e}),Promise.resolve();if(a!==ch.Approved)throw new fi("Payment is not approved.");return Promise.resolve()})}getOrderId(e){return uh(this,void 0,void 0,function*(){const t={cartId:e,shouldSaveInstrument:!1},{body:n}=yield this._requestSender.post("/api/storefront/payments/googlepaypaypalcommercecheckout",{headers:Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr),body:t});return n})}}const ph=vi(e=>{const t=new Xa(a());return new hh(e,new aa(da(),new ns(e,t),n(),Ee()),t,n())},[{id:"googlepaypaypalcommerce"}]);var mh,yh;!function(e){e.Approved="APPROVED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(mh||(mh={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(yh||(yh={}));var gh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vh extends Zu{constructor(e,t,n,i){super(e,t),this._payPalSdkHelper=n,this._requestSender=i}execute({payment:e}){return gh(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new co(["payment"]);const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow().id,{initializationData:i}=t.getPaymentMethodOrThrow(this._getMethodId()),{orderId:r}=yield this.getOrderId(n),{card_information:o}=i||{},a=yield this._googlePayPaymentProcessor.getNonce(e.methodId),s={tokenizationData:{type:"PAYMENT_GATEWAY",token:atob(a)},info:{cardNetwork:(null==o?void 0:o.type)||"",cardDetails:(null==o?void 0:o.number)||""},type:"CARD"};yield this.confirmOrder(r,s),yield this._paymentIntegrationService.submitOrder();try{const t={formattedPayload:{method_id:e.methodId,paypal_account:{order_id:r}}};yield this._paymentIntegrationService.submitPayment({methodId:e.methodId,paymentData:t})}catch(e){yield this._googlePayPaymentProcessor.processAdditionalAction(e)}})}confirmOrder(e,t){return gh(this,void 0,void 0,function*(){const n=this._paymentIntegrationService.getState(),i=n.getPaymentMethodOrThrow(this._getMethodId());if(!i.initializationData)throw new ti(Xn.MissingPaymentMethod);const r=n.getCartOrThrow().currency.code,o=yield this._payPalSdkHelper.getPayPalGooglePaySdk(i,r,!0),{status:a}=yield o.Googlepay().confirmOrder({orderId:e,paymentMethodData:t});if(a===mh.PayerActionRequired)return yield o.Googlepay().initiatePayerAction({orderId:e}),Promise.resolve();if(a!==mh.Approved)throw new fi("Payment is not approved.");return Promise.resolve()})}getOrderId(e){return gh(this,void 0,void 0,function*(){const t={cartId:e,shouldSaveInstrument:!1},{body:n}=yield this._requestSender.post("/api/storefront/payments/googlepay_bigcommerce_paymentscheckout",{headers:Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr),body:t});return n})}}const fh=vi(e=>{const t=new xr(a());return new vh(e,new aa(da(),new os(e,t),n(),Ee()),t,n())},[{id:"googlepay_bigcommerce_payments"}]),Sh=vi(e=>new Zu(e,new aa(da(),new cs(e,Ee()),n(),Ee())),[{id:"googlepaytdonlinemart"}]);class _h extends Qn{constructor(e,t,n){super(n||"Payment cannot be processed for this order, please select another payment method"),this.type="custom_provider_execute_error",this.name=t,this.subtype=e}}class wh{constructor(e,t){this.paymentIntegrationService=e,this.formPoster=t}execute(e,t){var n,i,r,o,a;return i=this,r=void 0,a=function*(){const{payment:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.formPoster.postForm(t,JSON.parse(n),e)})}isOffsiteRedirectResponse(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!t.body)return!1;const n=t.body;return"additional_action_required"===n.status&&!!n.additional_action_required&&"offsite_redirect"===n.additional_action_required.type&&"string"==typeof n.provider_data}}const Ih=vi(e=>new wh(e,Ee()),[{id:"humm"}]),Ch=["AT","BE","CA","CH","CZ","DE","DK","ES","FI","FR","GB","GR","IE","IT","NL","NO","NZ","PL","PT","SE"],bh=["AU"];var Ph=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Oh{constructor(e,t){this.paymentIntegrationService=e,this.klarnaScriptLoader=t}initialize(e){return Ph(this,void 0,void 0,function*(){this.klarnaCredit=yield this.klarnaScriptLoader.load(),this.unsubscribe=this.paymentIntegrationService.subscribe(t=>{t.isPaymentMethodInitialized({methodId:e.methodId,gatewayId:e.gatewayId})&&this.loadWidget(e)},e=>{const t=e.getCheckout();return t&&t.outstandingBalance},e=>{const t=e.getCheckout();return t&&t.coupons}),yield this.loadWidget(e)})}deinitialize(){return this.unsubscribe&&this.unsubscribe(),Promise.resolve()}execute(e,t){return Ph(this,void 0,void 0,function*(){if(!e.payment)throw new fi('Unable to proceed because "payload.payment" argument is not provided.');const n=e.payment,{paymentData:i}=n,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const r=this.paymentIntegrationService.getState().getPaymentMethod(t);if(!r)throw new ti(Xn.MissingPaymentMethod);if(!this.klarnaCredit||!r.clientToken)throw new ri(ei.PaymentNotInitialized);this.klarnaCredit.init({client_token:r.clientToken}),this.klarnaCredit.load({container:n},t=>{i&&i(t),e(t)})})})}getUpdateSessionData(e,t){if(!H([...Ch,...bh],e.countryCode))return{};const n={billing_address:this.mapToKlarnaAddress(e,e.email)};return t&&(n.shipping_address=this.mapToKlarnaAddress(t,e.email)),n}needsStateCode(e){return H(bh,e)}mapToKlarnaAddress(e,t){const n={street_address:e.address1,city:e.city,country:e.countryCode,given_name:e.firstName,family_name:e.lastName,postal_code:e.postalCode,region:this.needsStateCode(e.countryCode)?e.stateOrProvinceCode:e.stateOrProvince,email:t};return e.address2&&(n.street_address2=e.address2),e.phone&&(n.phone=e.phone),n}authorize(){return new Promise((e,t)=>{const n=this.paymentIntegrationService.getState(),i=n.getBillingAddress(),r=n.getShippingAddress();if(!i)throw new ti(Xn.MissingBillingAddress);if(!this.klarnaCredit)throw new ri(ei.PaymentNotInitialized);const o=this.getUpdateSessionData(i,r);this.klarnaCredit.authorize(o,n=>n.approved?e(n):n.show_form?t(new Wi):void t(new Xr))})}}class Eh{constructor(e,t=window){this.scriptLoader=e,this.klarnaWindow=t}load(){var e,t,n,i,r,o;return n=this,i=void 0,o=function*(){if((null===(e=this.klarnaWindow.Klarna)||void 0===e?void 0:e.Credit)||(yield this.scriptLoader.loadScript("//credit.klarnacdn.net/lib/v1/api.js")),!(null===(t=this.klarnaWindow.Klarna)||void 0===t?void 0:t.Credit))throw new mi;return this.klarnaWindow.Klarna.Credit},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}}const Ah=vi(e=>new Oh(e,new Eh(a())),[{id:"klarna"}]);var Th=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class kh{constructor(e,t,n){this.paymentIntegrationService=e,this.klarnav2ScriptLoader=t,this.klarnav2TokenUpdater=n}initialize(e){return Th(this,void 0,void 0,function*(){this.klarnaPayments=yield this.klarnav2ScriptLoader.load(),this.unsubscribe=this.paymentIntegrationService.subscribe(t=>{t.isPaymentMethodInitialized({methodId:e.methodId,gatewayId:e.gatewayId})&&this.loadPaymentsWidget(e)},e=>{const t=e.getCheckout();return t&&t.outstandingBalance},e=>{const t=e.getCheckout();return t&&t.coupons}),yield this.loadPaymentsWidget(e)})}deinitialize(){return this.unsubscribe&&this.unsubscribe(),Promise.resolve()}execute(e,t){return Th(this,void 0,void 0,function*(){if(!e.payment)throw new fi('Unable to proceed because "payload.payment" argument is not provided.');const n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{throw new ti(Xn.MissingPaymentMethod)}),new Promise(e=>{const a=o.getPaymentMethodOrThrow(t),{klarnaMultipleRadioButton:s}=a.initializationData||{};if(!this.klarnaPayments||!a.clientToken)throw new ri(ei.PaymentNotInitialized);this.klarnaPayments.init({client_token:a.clientToken}),this.klarnaPayments.load({container:i,payment_method_category:this.isKlarnaMultipleRadioButtonEnabled(s,n,t)},t=>{r&&r(t),e(t)})})})}getUpdateSessionData(e,t,n){if(!H([...Ch,...bh],t.countryCode))return{};const i={billing_address:this.mapToKlarnaAddress(e,t,t.email)};return n&&(i.shipping_address=this.mapToKlarnaAddress(e,n,t.email)),i}needsStateCode(e){return H(bh,e)}isKlarnaMultipleRadioButtonEnabled(e,t,n){return e?n:t}mapToKlarnaAddress(e,t,n){const i=this.paymentIntegrationService.getState(),{checkoutSettings:r}=i.getStoreConfigOrThrow(),o=i.getPaymentMethodOrThrow(e),{enableBillie:a}=o.initializationData||{},s={street_address:t.address1,city:t.city,country:t.countryCode,given_name:t.firstName,family_name:t.lastName,postal_code:t.postalCode,region:this.needsStateCode(t.countryCode)?t.stateOrProvinceCode:t.stateOrProvince,email:n};return t.address2&&(s.street_address2=t.address2),t.phone&&(s.phone=t.phone),t.company&&a&&Ci(r.features,"PI-3915.b2b_payment_session_for_klarna")&&(s.organization_name=t.company),s}authorizeOrThrow(e,t){return Th(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const n=this.paymentIntegrationService.getState(),i=n.getBillingAddressOrThrow(),r=n.getShippingAddress(),o=this.getUpdateSessionData(t,i,r);return new Promise((t,n)=>{if(!this.klarnaPayments)return n(new ri(ei.PaymentNotInitialized));this.klarnaPayments.authorize({payment_method_category:e},o,e=>e.approved?t(e):e.show_form?n(new Wi):void n(new Xr))})})}}class Dh{constructor(e,t=window){this.scriptLoader=e,this.klarnaWindow=t}load(){var e,t,n,i,r,o;return n=this,i=void 0,o=function*(){if((null===(e=this.klarnaWindow.Klarna)||void 0===e?void 0:e.Payments)||(yield this.scriptLoader.loadScript("https://x.klarnacdn.net/kp/lib/v1/api.js")),!(null===(t=this.klarnaWindow.Klarna)||void 0===t?void 0:t.Payments))throw new mi;return this.klarnaWindow.Klarna.Payments},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}}class Mh{constructor(e){this.requestSender=e}updateClientToken(e,{timeout:t,params:n}={}){const i=`/api/storefront/payments/${e}`;return this.requestSender.get(i,{timeout:t,headers:Object.assign({Accept:mr.JsonV1,"X-API-INTERNAL":hr},yr),params:n})}klarnaOrderInitialization(e,t){return n=this,i=void 0,o=function*(){const n={headers:Object.assign({Accept:mr.JsonV1,"X-API-INTERNAL":hr},yr),body:{cartId:e,clientToken:t}};yield this.requestSender.put("/api/storefront/initialization/klarna",n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const zh=vi(e=>{const{getHost:t}=e.getState(),i=n({host:t()});return new kh(e,new Dh(a()),new Mh(i))},[{gateway:"klarna"}]);class Nh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return n=this,i=void 0,o=function*(){return yield this._paymentIntegrationService.submitOrder(e,t),Promise.resolve()},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const xh=vi(e=>new Nh(e),[{id:"testgateway"}]);var Rh,Fh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.CREDIT_CARD="credit_card"}(Rh||(Rh={}));const Lh=["klarnapaylater","klarnasliceit"];class Bh{constructor(e,t){this.mollieScriptLoader=e,this.paymentIntegrationService=t}initialize(e){return Fh(this,void 0,void 0,function*(){const{mollie:t,methodId:n,gatewayId:i}=e;if(!t)throw new fi('Unable to initialize payment because "options.mollie" argument is not provided.');if(!n||!i)throw new fi('Unable to initialize payment because "methodId" and/or "gatewayId" argument is not provided.');const r=document.querySelectorAll(".mollie-components-controller");F(r,e=>e.remove());const o=this.paymentIntegrationService.getState(),a=o.getStoreConfigOrThrow();this.initializeOptions=t;const s=o.getPaymentMethodOrThrow(n,i),{config:{merchantId:d,testMode:c}}=s;if(this.locale=o.getLocale(),!d)throw new ti(Xn.MissingPaymentMethod);return this.isCreditCard(n)&&t.form&&this.shouldShowTSVHostedForm(n,i)?this.hostedForm=yield this.mountCardVerificationfields(t.form):this.isCreditCard(n)&&(this.mollieClient=yield this.loadMollieJs(d,a.storeProfile.storeLanguage,c),this.mountElements()),this.unsubscribe=()=>{if(this.paymentIntegrationService.getState().isPaymentMethodInitialized({methodId:e.methodId,gatewayId:e.gatewayId})){const e=document.getElementById(`${i}-${n}-paragraph`);e&&e.remove(),t.disableButton(!1),this.loadPaymentMethodsAllowed(t,n,i)}},this.unsubscribe(),this.loadPaymentMethodsAllowed(t,n,i),Promise.resolve()})}execute(e,t){return Fh(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rFh(this,void 0,void 0,function*(){try{const n=this.paymentIntegrationService.getState().getStoreConfig(),i=null==n?void 0:n.paymentSettings.bigpayBaseUrl;if(!i)throw new ti(Xn.MissingCheckoutConfig);const r=this.paymentIntegrationService.createHostedForm(i,e);yield r.attach(),t(r)}catch(e){n(e)}}))}isHostedPaymentFormEnabled(e,t){const{getPaymentMethodOrThrow:n}=this.paymentIntegrationService.getState();return!0===n(e,t).config.isHostedFormEnabled}isHostedFieldAvailable(){var e;return!!(null===(e=this.getInitializeOptions().form)||void 0===e?void 0:e.fields)}processAdditionalAction(e){if(!pa(e))return Promise.reject(e);if(ve(e.body.errors,{code:"additional_action_required"})){const{additional_action_required:{data:{redirect_url:t}}}=e.body;return new Promise(()=>window.location.replace(t))}return Promise.reject(e)}getInitializeOptions(){if(!this.initializeOptions)throw new ri(ei.PaymentNotInitialized);return this.initializeOptions}loadMollieJs(e,t,n=!1){return this.mollieClient?Promise.resolve(this.mollieClient):this.mollieScriptLoader.load(e,t,n)}getMollieClient(){if(!this.mollieClient)throw new ri(ei.PaymentNotInitialized);return this.mollieClient}getShopperLocale(){if(!this.locale)throw new ri(ei.PaymentNotInitialized);return this.locale}mountElements(){const{containerId:e,cardNumberId:t,cardCvcId:n,cardExpiryId:i,cardHolderId:r,styles:o}=this.getInitializeOptions();let a;e&&(a=document.getElementById(e)),setTimeout(()=>{if(!e||"none"!==(null==a?void 0:a.style.display)){const e=this.getMollieClient();this.cardHolderElement=e.createComponent("cardHolder",{styles:o}),this.cardHolderElement.mount(`#${r}`),this.cardNumberElement=e.createComponent("cardNumber",{styles:o}),this.cardNumberElement.mount(`#${t}`),this.verificationCodeElement=e.createComponent("verificationCode",{styles:o}),this.verificationCodeElement.mount(`#${n}`),this.expiryDateElement=e.createComponent("expiryDate",{styles:o}),this.expiryDateElement.mount(`#${i}`)}},0)}loadPaymentMethodsAllowed(e,t,n){var i;if(Lh.includes(t)){const r=null===(i=this.paymentIntegrationService.getState().getCartOrThrow().lineItems)||void 0===i?void 0:i.digitalItems;if(r&&r.length>0){const{containerId:i}=this.getInitializeOptions();if(i){const r=document.getElementById(i);if(r){const i=document.createElement("p");i.setAttribute("id",`${n}-${t}-paragraph`),e.unsupportedMethodMessage&&(i.innerText=e.unsupportedMethodMessage,r.appendChild(i),e.disableButton(!0))}}}}}}class jh{constructor(e,t=window){this.scriptLoader=e,this.mollieHostWindow=t}load(e,t,n){return i=this,r=void 0,a=function*(){if(yield this.scriptLoader.loadScript("https://js.mollie.com/v1/mollie.js"),!function(e){return"Mollie"in e}(this.mollieHostWindow))throw new mi;return this.mollieHostWindow.Mollie(e,{locale:t,testmode:n})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a}}const Uh=vi(e=>new Bh(new jh(a()),e),[{gateway:"mollie"},{gateway:"mollie",id:"applepay"}]);var qh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const Vh="moneris-payment-iframe";class Gh{constructor(e){this.paymentIntegrationService=e}initialize(e){return qh(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),{moneris:n,methodId:i}=e;if(!i)throw new fi('Unable to initialize payment because "methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.moneris" argument is not provided.');this.initializeOptions=n;const{config:r,initializationData:o}=t.getPaymentMethodOrThrow(i);if(!(null==o?void 0:o.profileId))throw new ti(Xn.MissingPaymentMethod);return n.form&&this.shouldShowTSVHostedForm(i)&&(this.hostedForm=yield this.mountCardVerificationfields(n.form)),this.iframe||(this.iframe=this.createIframe(n.containerId,o,!!r.testMode)),Promise.resolve()})}execute(e,t){return qh(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(!this.iframe)throw new ri(ei.PaymentNotInitialized);const i=this.iframe.contentWindow;if(null===i)throw new ri(ei.PaymentNotInitialized);i.postMessage("tokenize",this.monerisURL(!!t)),this.windowEventListener=i=>{if("string"==typeof i.data&&i.origin===`https://${t?"esqa":"www3"}.moneris.com`)try{e(this.handleMonerisResponse(i))}catch(e){n(e)}},window.addEventListener("message",this.windowEventListener)});void 0!==a&&(yield this.paymentIntegrationService.submitPayment({methodId:e.methodId,paymentData:{nonce:a,shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o}}))})}executeWithVaulted(e){return qh(this,void 0,void 0,function*(){if(this.hostedForm){const t=this.hostedForm;return yield t.validate(),yield t.submit(e),this.paymentIntegrationService.loadCurrentOrder()}return this.paymentIntegrationService.submitPayment(e)})}shouldShowTSVHostedForm(e){return this.isHostedPaymentFormEnabled(e)&&this.isHostedFieldAvailable()}isHostedPaymentFormEnabled(e){const t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e);return Boolean(t.config.isHostedFormEnabled)}isHostedFieldAvailable(){var e;const t=this.getInitializeOptions(),n=ue(null===(e=t.form)||void 0===e?void 0:e.fields,$);return!$(n)}getInitializeOptions(){if(!this.initializeOptions)throw new ri(ei.PaymentNotInitialized);return this.initializeOptions}mountCardVerificationfields(e){var t;return qh(this,void 0,void 0,function*(){const n=null===(t=this.paymentIntegrationService.getState().getStoreConfig())||void 0===t?void 0:t.paymentSettings.bigpayBaseUrl;if(!n)throw new ti(Xn.MissingCheckoutConfig);const i=this.paymentIntegrationService.createHostedForm(n,e);return yield i.attach(),i})}createIframe(e,t,n,i){const r=document.getElementById(e);if(!r)throw new fi("Unable to create iframe without valid container ID.");const o=document.createElement("iframe"),a={id:t.profileId,pmmsg:!0,display_labels:1,enable_exp:1,enable_cvd:1,css_body:(null==i?void 0:i.cssBody)||"font-family: Arial, Helvetica,sans-serif;background: transparent;",css_textbox:(null==i?void 0:i.cssTextbox)||"border-radius:4px;border: 2px solid rgb(00,00,00);width: 100%;font-weight: 600;padding: 8px 8px;outline: 0;",css_textbox_pan:(null==i?void 0:i.cssTextboxCardNumber)||"width: 240px;",css_textbox_exp:(null==i?void 0:i.cssTextboxExpiryDate)||"margin-bottom: 0;width: calc(30% - 12px);",css_textbox_cvd:(null==i?void 0:i.cssTextboxCVV)||"margin-bottom: 0;width: calc(30% - 12px);",css_input_label:(null==i?void 0:i.cssInputLabel)||"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;",pan_label:t.creditCardLabel||"Credit Card Number",exp_label:t.expiryDateLabel||"Expiration",cvd_label:t.cvdLabel||"CVD"},s=oe(a,(e,t)=>`${t}=${e}`).join("&");return o.width="100%",o.height="100%",o.name=Vh,o.id=Vh,o.style.border="none",o.src=`${this.monerisURL(n)}?${s}`,o.allow="payment",r.appendChild(o),o}handleMonerisResponse(e){const t=JSON.parse(e.data);if("001"!==t.responseCode[0])throw new Error(t.errorMessage);return t.dataKey}monerisURL(e){return`https://${e?"esqa":"www3"}.moneris.com/HPPtoken/index.php`}}const Hh=vi(e=>new Gh(e),[{id:"moneris"}]);class Wh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return n=this,i=void 0,o=function*(){return yield this._paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:e.payment?{methodId:e.payment.methodId}:void 0}),t),Promise.resolve()},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const $h=vi(e=>new Wh(e),[{type:"PAYMENT_TYPE_OFFLINE"}]);var Yh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Kh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return Yh(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rnew Kh(e),[{type:"PAYMENT_TYPE_HOSTED"}]),Zh=function({styles:e}){const t={};return e.color&&(t.color=e.color),e.layout&&(t.layout=e.layout),(e["logo-type"]||e["logo-position"])&&(t.logo={},e["logo-type"]&&(t.logo.type=e["logo-type"]),e["logo-position"]&&(t.logo.position=e["logo-position"])),e.ratio&&(t.ratio=e.ratio),(e["text-color"]||e["text-size"])&&(t.text={},e["text-color"]&&(t.text.color=e["text-color"]),e["text-size"]&&(t.text.size=+e["text-size"])),t};var Qh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Xh{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.payPalSdkScriptLoader=n,this.loadingIndicator=i}initialize(e){var t;return Qh(this,void 0,void 0,function*(){const{methodId:n,paypalcommerce:i}=e||{};if(this.paypalcommerce=i,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(n),{container:a,bannerContainerId:s}=i,{orderId:d,paypalBNPLConfiguration:c=[],isPayPalCreditAvailable:l}=o.initializationData||{};if(void 0!==s){if(!document.getElementById(s))return void console.error("Unable to create banner without valid banner container ID.");const e=null==c?void 0:c.find(({id:e})=>"checkout"===e);if(l||!(null==e?void 0:e.status))return;const t=yield this.payPalSdkScriptLoader.getPayPalMessages(o,r.getCartOrThrow().currency.code,r.getLocale());return t&&"function"==typeof(null==t?void 0:t.Messages)?this.renderMessages(t,s,e):void console.error("[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK")}d?this.orderId=null===(t=o.initializationData)||void 0===t?void 0:t.orderId:(this.loadingIndicatorContainer=null==a?void 0:a.split("#")[1],yield this.paypalIntegrationService.loadPayPalSdk(n),i.onInit&&"function"==typeof i.onInit&&i.onInit(()=>this.renderButton(n,i)),(void 0===i.shouldRenderPayPalButtonOnInitialization||i.shouldRenderPayPalButtonOnInitialization)&&this.renderButton(n,i))})}execute(e,t){var n,i;return Qh(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rwindow.location.replace(t))}return this.isProviderError(e)&&(yield this.paypalIntegrationService.loadPayPalSdk(r.methodId),yield new Promise((e,t)=>{var n;this.paypalcommerce&&(null===(n=this.paypalButton)||void 0===n||n.close(),this.renderButton(r.methodId,this.paypalcommerce),this.handleError(new Error("INSTRUMENT_DECLINED"),a)),t()})),this.handleError(e,a),Promise.reject()}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}prepareVaultedInstrumentPaymentPayload(e,t,n){const{instrumentId:i,shouldSetAsDefaultInstrument:r}=n,o=!this.isTrustedVaultingFlow(n);return o?{methodId:e,paymentData:{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}:{methodId:e,paymentData:{instrumentId:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t},bigpay_token:{token:i}}}}}preparePaymentPayload(e,t,n){const{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:r=!1}=jd(n)?n:{};return{methodId:e,paymentData:{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}}renderButton(e,t){var n,i,r,o;const a=this.paypalIntegrationService.getPayPalSdkOrThrow(),s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:d}=s.initializationData||{},{checkoutPaymentButtonStyles:c}=d||{},{container:l,onError:u,onRenderButton:h,onValidate:p,submitForm:m}=t;if(!l)throw new fi('Unable to initialize payment because "container" argument is not provided.');const y=this.getSmartButtonContainerId(l);if(!document.getElementById(y))throw new fi(`Unable to initialize payment because element with id ${y} does not exist.`);const g=Object.assign(Object.assign({},this.isPaypalCommerceAppSwitchEnabled(e)&&{appSwitchWhenAvailable:!0}),{fundingSource:a.FUNDING.PAYPAL,style:this.paypalIntegrationService.getValidButtonStyle(c),createOrder:()=>this.createOrder(),onClick:(e,t)=>this.handleClick(t,p),onApprove:e=>this.handleApprove(e,m),onError:e=>this.handleError(e,u),onCancel:()=>this.toggleLoadingIndicator(!1)});this.paypalButton=a.Buttons(g),this.paypalButton.isEligible()&&(h&&"function"==typeof h&&h(),(null===(i=(n=this.paypalButton).hasReturned)||void 0===i?void 0:i.call(n))&&this.isPaypalCommerceAppSwitchEnabled(e)?null===(o=(r=this.paypalButton).resume)||void 0===o||o.call(r):this.paypalButton.render(l))}handleClick(e,t){return Qh(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;return null==t?void 0:t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,null==t||t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createOrder(){return Qh(this,void 0,void 0,function*(){const e=this.getFieldsValues();return this.paypalIntegrationService.createOrder("paypalcommercecheckout",{shouldSaveInstrument:(null==e?void 0:e.shouldSaveInstrument)||!1})})}getFieldsValues(){const{getFieldsValues:e}=this.paypalcommerce||{};return"function"==typeof e?e():void 0}isTrustedVaultingFlow(e){if(e&&xd(e)){const t=this.paymentIntegrationService.getState().getInstruments(),n=null==t?void 0:t.find(t=>uc(t)&&t.bigpayToken===e.instrumentId);return!(uc(n)&&!n.trustedShippingAddress)}return!1}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isPayPalVaultedInstrumentPaymentData(e){return!!e&&xd(e)&&jd(e)}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:Zh(n)};e.Messages(i).render(`#${t}`)}isProviderError(e){var t,n,i;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"INSTRUMENT_DECLINED"===(null===(i=null===(n=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===n?void 0:n.provider_error)||void 0===i?void 0:i.code)}isPaypalCommerceAppSwitchEnabled(e){var t;return(null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)||!1}getSmartButtonContainerId(e){var t;return null!==(t=e.split("#")[1])&&void 0!==t?t:e}}const ep=vi(e=>new Xh(e,As(e),new Is(a()),new vd({containerStyles:Ka})),[{id:"paypalcommerce"}]);var tp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class np{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.loadingIndicator=n,this.payPalSdkScriptLoader=i}initialize(e){return tp(this,void 0,void 0,function*(){const{methodId:t,paypalcommerce:n,paypalcommercecredit:i}=e||{},r=i||n;if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const o=this.paymentIntegrationService.getState(),a=o.getPaymentMethodOrThrow(t),{paypalBNPLConfiguration:s=[],orderId:d}=a.initializationData||{},{bannerContainerId:c,container:l}=r;if(void 0!==c){if(!document.getElementById(c))return void console.error("Unable to create banner without valid banner container ID.");const e=s&&s.find(({id:e})=>"checkout"===e);if(!(null==e?void 0:e.status))return;const t=yield this.payPalSdkScriptLoader.getPayPalMessages(a,o.getCartOrThrow().currency.code,o.getLocale());return this.renderMessages(t,c,e)}d?this.orderId=d:(yield this.paypalIntegrationService.loadPayPalSdk(t),this.loadingIndicatorContainer=null==l?void 0:l.split("#")[1],this.renderButton(t,r))})}execute(e,t){return tp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(h)return;const t={fundingSource:e,style:this.paypalIntegrationService.getValidButtonStyle(o),createOrder:()=>this.paypalIntegrationService.createOrder("paypalcommercecreditcheckout"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=n.Buttons(t),this.paypalButton.isEligible()||e!==n.FUNDING.PAYLATER){if(!this.paypalButton.isEligible()&&e===n.FUNDING.CREDIT)throw new Si(`PayPal ${e} is not available for your region. Please use PayPal Checkout instead.`);d&&"function"==typeof d&&d(),this.paypalButton.render(a),h=!0}})}handleClick(e,t){return tp(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;if(t&&"function"==typeof t)return t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,t&&"function"==typeof t&&t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:Zh(n)};e.Messages(i).render(`#${t}`)}}const ip=vi(e=>new np(e,As(e),new vd({containerStyles:Ka}),Cs()),[{id:"paypalcommercecredit"}]);var rp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class op{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.loadingIndicator=n}initialize(e){var t,n;return rp(this,void 0,void 0,function*(){const{methodId:i,paypalcommerce:r,paypalcommercevenmo:o}=e||{},a=o||r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!a)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i);(null===(t=s.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(n=s.initializationData)||void 0===n?void 0:n.orderId:(yield this.paypalIntegrationService.loadPayPalSdk(i),this.loadingIndicatorContainer=a.container.split("#")[1],this.renderButton(i,a))})}execute(e,t){return rp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rthis.paypalIntegrationService.createOrder("paypalcommercevenmocheckout"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=n.Buttons(u),!this.paypalButton.isEligible())throw new Si("PayPal Venmo is not available for your region. Please use PayPal Checkout instead.");d&&"function"==typeof d&&d(),this.paypalButton.render(a)}handleClick(e,t){return rp(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;return t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,t(),this.toggleLoadingIndicator(!1)}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const ap=vi(e=>new op(e,As(e),new vd({styles:{backgroundColor:"black"}})),[{id:"paypalcommercevenmo"}]),sp={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"};var dp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class cp{constructor(e,t,n,i,r=3e3,o=3e5){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.paypalSdkScriptLoader=n,this.loadingIndicator=i,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.pollingTimer=0,this.stopPolling=ce,this.isOrderApprovedProcessing=!1}initialize(e){return dp(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,paypalcommerce:i,paypalcommercealternativemethods:r}=e,o=r||i;if(this.paypalcommercealternativemethods=r,!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!o)throw new fi('Unable to initialize payment because "options.paypalcommercealternativemethods" argument is not provided.');const a=this.paymentIntegrationService.getState(),s=a.getPaymentMethodOrThrow(n,t),{orderId:d,shouldRenderFields:c}=s.initializationData||{},l=a.getStoreConfigOrThrow().checkoutSettings.features;this.isOrderApprovedProcessing=Ci(l,"PAYPAL-5431.order_approved_processing",!1),d?this.orderId=d:(this.paypalApms=yield this.paypalSdkScriptLoader.getPayPalApmsSdk(s,a.getCartOrThrow().currency.code,a.getLocale()),this.loadingIndicatorContainer=o.container.split("#")[1],this.renderButton(n,t,o),c&&this.renderFields(n,o))})}execute(e,t){return dp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.initializePollingMechanism(r,e,t,o)})),this.isNonInstantPaymentMethod(r)&&(r!==Bs.IDEAL||this.isOrderApprovedProcessing)||(yield this.paymentIntegrationService.submitOrder(i,t)),yield this.paypalCommerceIntegrationService.submitPayment(r,this.orderId,o)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,this.isOrderApprovedProcessing||this.resetPollingMechanism(),null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}initializePollingMechanism(e,t,n,i){return dp(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.paypalCommerceIntegrationService.getOrderStatus(null!=i?i:"paypalcommerce"),o=r===js.Approved,a=r===js.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimern.onInitButton(t),createOrder:()=>this.onCreateOrder(e,t,n),onApprove:e=>this.handleApprove(e,c),onCancel:()=>{this.toggleLoadingIndicator(!1),this.deinitializePollingMechanism()},onError:e=>{this.deinitializePollingMechanism(),this.handleFailure(e,s)},onClick:(e,t)=>dp(this,void 0,void 0,function*(){return n.onValidate(t.resolve,t.reject)})};this.paypalButton=i.Buttons(l),this.paypalButton.isEligible()&&(d&&"function"==typeof d&&d(),this.paypalButton.render(a))}onCreateOrder(e,t,n){var i;return dp(this,void 0,void 0,function*(){const{onValidate:r}=n;yield r(()=>(this.toggleLoadingIndicator(!0),()=>Promise.resolve()),ce);const o=yield this.paypalCommerceIntegrationService.createOrder("paypalcommercealternativemethodscheckout");if(this.isNonInstantPaymentMethod(e)&&(e===Bs.IDEAL&&this.isOrderApprovedProcessing||e===Bs.OXXO)){const n={useStoreCredit:!1},r={params:{methodId:e,gatewayId:t}};if(yield this.paymentIntegrationService.submitOrder(n,r),e===Bs.IDEAL){const t=this.paymentIntegrationService.getState(),n=null===(i=t.getOrder())||void 0===i?void 0:i.orderId;yield this.paypalCommerceIntegrationService.updateOrder("paypalcommercealternativemethods",e,n)}yield this.paypalCommerceIntegrationService.submitPayment(e,o,t)}return o})}handleApprove({orderID:e},t){this.orderId=e,t()}handleFailure(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderFields(e,t){const n=this.getPaypalAmpsSdkOrThrow(),i=this.paymentIntegrationService.getState(),{firstName:r,lastName:o,email:a}=i.getBillingAddressOrThrow(),{apmFieldsContainer:s,apmFieldsStyles:d}=t;if(!s)throw new fi('Unable to initialize payment because "options.paypalcommercealternativemethods" argument should contain "apmFieldsContainer".');const c=document.querySelector(s);c&&(c.innerHTML="");const l={fundingSource:e,style:d||{},fields:{name:{value:`${r} ${o}`},email:{value:a}}};n.PaymentFields(l).render(s)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isNonInstantPaymentMethod(e){return e.toUpperCase()in Bs}getPaypalAmpsSdkOrThrow(){if(!this.paypalApms)throw new mi;return this.paypalApms}}const lp=vi(e=>new cp(e,As(e),Cs(),new vd({containerStyles:sp})),[{gateway:"paypalcommercealternativemethods"}]);var up=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class hp{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.paypalSdkScriptLoader=n,this.paypalFastlaneUtils=i}initialize(e){return up(this,void 0,void 0,function*(){const{methodId:t,paypalcommercecreditcards:n,paypalcommerce:i}=e,r=n||i,{form:o,onCreditCardFieldsRenderingError:a,onLoadComplete:s}=r||{};if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)throw new fi('Unable to proceed because "options.paypalcommercecreditcards.form" argument is not provided.');this.hostedFormOptions=o,this.isCreditCardForm=Ac(o.fields),this.isCreditCardVaultedForm=Tc(o.fields)&&!this.hasUndefinedValues(),yield this.paymentIntegrationService.loadPaymentMethod(t),yield this.paypalIntegrationService.loadPayPalSdk(t,void 0,!0,!0),(this.isCreditCardForm||this.isCreditCardVaultedForm)&&(yield this.initializeFields(o,a)),null==s||s(),this.shouldInitializePayPalFastlane(t)&&(yield this.initializePayPalFastlaneOrThrow(t))})}execute(e,t){return up(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if(n===Ns.No||n===Ns.Unknown)throw new Error;return this.handleApprove({orderID:e,vaultSetupToken:t})},onError:()=>{throw new Qr},inputEvents:{onChange:t=>this.onChangeHandler(e,t),onFocus:t=>this.onFocusHandler(e,t),onBlur:t=>this.onBlurHandler(e,t),onInputSubmitRequest:t=>this.onInputSubmitRequest(e,t)}},o);if(this.cardFields=yield r.CardFields(a),!this.cardFields.isEligible())throw new ri(ei.PaymentNotInitialized);try{this.stylizeInputContainers(n),Ac(n)&&(yield this.renderFields(n)),Tc(n)&&(yield this.renderVaultedFields(n))}catch(e){"function"==typeof t&&t(e)}})}getExecuteCallback(e){return Tc(e)?this.createVaultSetupTokenCallback():this.createOrderCallback()}createVaultSetupTokenCallback(){return{createVaultSetupToken:()=>up(this,void 0,void 0,function*(){const{setupToken:e}=(yield this.paypalIntegrationService.createOrderCardFields("paypalcommercecreditcardscheckout",Object.assign(Object.assign({},this.getInstrumentParams()),{setupToken:!0})))||{};return e})}}createOrderCallback(){return{createOrder:()=>up(this,void 0,void 0,function*(){const{orderId:e}=(yield this.paypalIntegrationService.createOrderCardFields("paypalcommercecreditcardscheckout",this.getInstrumentParams()))||{};return e})}}handleApprove({orderID:e,vaultSetupToken:t}){e&&(this.returnedOrderId=e),t&&(this.returnedVaultedToken=t)}renderFields(e){var t,n,i,r;return up(this,void 0,void 0,function*(){const o=this.getCardFieldsOrThrow();(null===(t=e.cardCode)||void 0===t?void 0:t.containerId)&&(this.cvvField=o.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCode.containerId}`)),(null===(n=e.cardExpiry)||void 0===n?void 0:n.containerId)&&(this.expiryField=o.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiry.containerId}`)),(null===(i=e.cardName)||void 0===i?void 0:i.containerId)&&(this.nameField=o.NameField({placeholder:""}),yield this.nameField.render(`#${e.cardName.containerId}`)),(null===(r=e.cardNumber)||void 0===r?void 0:r.containerId)&&(this.numberField=o.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumber.containerId}`))})}renderVaultedFields(e){var t,n,i;return up(this,void 0,void 0,function*(){const r=this.getCardFieldsOrThrow();(null===(t=e.cardCodeVerification)||void 0===t?void 0:t.containerId)&&(this.cvvField=r.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCodeVerification.containerId}`)),(null===(n=e.cardExpiryVerification)||void 0===n?void 0:n.containerId)&&(this.expiryField=r.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiryVerification.containerId}`)),(null===(i=e.cardNumberVerification)||void 0===i?void 0:i.containerId)&&(this.numberField=r.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumberVerification.containerId}`))})}getInstrumentParams(){if(!this.executionPaymentData)return{};if(jd(this.executionPaymentData)){const{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}=this.executionPaymentData;return{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}}if(xd(this.executionPaymentData)){const{instrumentId:e}=this.executionPaymentData;return{instrumentId:e}}return{}}getFieldTypeByEmittedField({emittedBy:e}){return{fieldType:this.mapFieldType(e)}}submitHostedForm(){return up(this,void 0,void 0,function*(){const e=this.getCardFieldsOrThrow(),t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),n={billingAddress:{company:t.company,addressLine1:t.address1,addressLine2:t.address2,adminArea1:t.stateOrProvinceCode,adminArea2:t.city,postalCode:t.postalCode,countryCode:t.countryCode}};try{this.isCreditCardVaultedForm?yield e.submit():yield e.submit(n)}catch(e){throw new Qr("Failed authentication. Please try to authorize again.")}})}validateHostedFormOrThrow(){var e,t;return up(this,void 0,void 0,function*(){const n=this.getCardFieldsOrThrow(),i=yield n.getState().then(e=>e),r=this.getValidityData(i);if(!r.isValid)throw null===(t=null===(e=this.hostedFormOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,r),new lo(this.mapValidationErrors(r.errors))})}getValidityData({fields:e}){const t=Object.assign({},e);delete t.cardNameField;const n=Object.keys(t);return{isValid:n.every(e=>{var n;return null===(n=t[e])||void 0===n?void 0:n.isValid}),errors:n.reduce((e,n)=>{var i;const r=this.mapFieldType(n);return Object.assign(Object.assign({},e),{[r]:(null===(i=t[n])||void 0===i?void 0:i.isValid)?void 0:[this.getInvalidErrorByFieldType(r)]})},{})}}getInvalidErrorByFieldType(e){switch(e){case Ec.CardCode:case Ec.CardCodeVerification:return{fieldType:e,message:"Invalid card code",type:"invalid_card_code"};case Ec.CardNumber:case Ec.CardNumberVerification:return{fieldType:e,message:"Invalid card number",type:"invalid_card_number"};case Ec.CardExpiry:case Ec.CardExpiryVerification:return{fieldType:e,message:"Invalid card expiry",type:"invalid_card_expiry"};default:return{fieldType:e,message:"Invalid field",type:"invalid"}}}mapValidationErrors(e={}){const t={};return Object.keys(e).forEach(n=>{var i,r;t[n]=[{message:(null===(r=null===(i=e[n])||void 0===i?void 0:i[0])||void 0===r?void 0:r.message)||"",type:n}]}),t}mapFieldType(e){switch(e){case"name":return Ec.CardName;case"cardNumberField":case"number":return this.isCreditCardForm?Ec.CardNumber:Ec.CardNumberVerification;case"cardExpiryField":case"expiry":return this.isCreditCardForm?Ec.CardExpiry:Ec.CardExpiryVerification;case"cardCvvField":case"cvv":return this.isCreditCardForm?Ec.CardCode:Ec.CardCodeVerification;default:throw new Error("Unexpected field type")}}getCardFieldsOrThrow(){if(!this.cardFields)throw new ri(ei.PaymentNotInitialized);return this.cardFields}getInputStyles(e){var t,n,i;const r={"font-size":(null===(t=null==e?void 0:e.default)||void 0===t?void 0:t.fontSize)||"1rem","font-family":(null===(n=null==e?void 0:e.default)||void 0===n?void 0:n.fontFamily)||"Montserrat, Arial, Helvetica, sans-serif","font-weight":(null===(i=null==e?void 0:e.default)||void 0===i?void 0:i.fontWeight)||"400",outline:"none",padding:"9px 13px"},o=Object.assign(Object.assign({},r),{color:"#333333"});return{input:o,".invalid":Object.assign(Object.assign({},r),{color:"red"}),".valid":o,":focus":o}}stylizeInputContainers(e){Object.values(e||{}).forEach(e=>{const t=document.getElementById(`${(null==e?void 0:e.containerId)||""}`);t&&(t.style.padding="0px",t.style.boxShadow="none",t.style.border="none",t.style.background="transparent",t.style.marginBottom="10px",t.style.marginLeft="-5px")})}hasUndefinedValues(){return!this.hostedFormOptions||Object.values(this.hostedFormOptions.fields).some(e=>void 0===e)}onChangeHandler(e,t){var n;null===(n=null==e?void 0:e.onValidate)||void 0===n||n.call(e,this.getValidityData(t))}onFocusHandler(e,t){var n;null===(n=null==e?void 0:e.onFocus)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onBlurHandler(e,t){var n;null===(n=null==e?void 0:e.onBlur)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onInputSubmitRequest(e,t){var n;null===(n=null==e?void 0:e.onEnter)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}shouldInitializePayPalFastlane(e){var t,n;const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(e),o=i.getPaymentProviderCustomer(),a=(s=o)&&("authenticationState"in s||"addresses"in s||"instruments"in s)?o:{};var s;return(null===(t=null==r?void 0:r.initializationData)||void 0===t?void 0:t.isAcceleratedCheckoutEnabled)&&(null===(n=null==r?void 0:r.initializationData)||void 0===n?void 0:n.isPayPalCommerceAnalyticsV2Enabled)&&!(null==a?void 0:a.authenticationState)}initializePayPalFastlaneOrThrow(e){return up(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getPaymentMethodOrThrow(e),{initializationData:r}=i;if(!(null==r?void 0:r.connectClientToken))return;const o=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(i,n.currency.code,n.id,t.getLocale());yield this.paypalFastlaneUtils.initializePayPalFastlane(o,!!(null==r?void 0:r.isDeveloperModeApplicable))}catch(e){}})}}const pp=vi(e=>new hp(e,As(e),Cs(),nd()),[{id:"paypalcommercecreditcards"}]);var mp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class yp{constructor(e,t,n,i=3e3,r=3e5){this.paymentIntegrationService=e,this.paypalCommerceService=t,this.loadingIndicator=n,this.pollingInterval=i,this.maxPollingIntervalTime=r,this.pollingTimer=0,this.stopPolling=ce}initialize(e){return mp(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,paypalcommerceratepay:i}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.paypalcommerceratepay" argument is not provided.');const{legalTextContainer:r,container:o,loadingContainerId:a}=i;if(!o)throw new fi('Unable to initialize payment because "options.container" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.legalTextContainer" argument is not provided.');if(!a)throw new fi('Unable to initialize payment because "options.loadingContainerId" argument is not provided.');this.loadingIndicatorContainer=a;const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t),{merchantId:d}=s.initializationData||{};if(!d)throw new fi("Unable to initialize payment because merchantId argument is not provided.");this.paypalcommerceratepay=i,yield this.paypalCommerceService.loadPayPalSdk(n),this.createFraudNetScript(d,n,t),this.loadFraudnetConfig(),this.renderLegalText(r,o)})}execute(e,t){return mp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.initializePollingMechanism(n.methodId,e,t,n.gatewayId)})}catch(e){return this.handleError(e),new Promise((e,t)=>t())}})}finalize(){return Promise.reject(new Cd)}deinitialize(){const{legalTextContainer:e}=this.paypalcommerceratepay||{},t=document.querySelectorAll('[data-id="fraudnetScript"]')[0],n=document.querySelectorAll('[data-id="fraudnetConfig"]')[0];if(this.deinitializePollingMechanism(),t.remove(),n.remove(),e){const t=document.getElementById(e);null==t||t.remove()}return Promise.resolve()}normalizeDate(e){const t=this.formatDate(e.getDate()),n=this.formatDate(e.getMonth()+1);return`${e.getFullYear()}-${n}-${t}`}formatDate(e){return`${e<10?0:""}${e}`}renderLegalText(e,t){const n=e,i=t.split("#")[1],r=document.getElementById(i),o=null==r?void 0:r.parentNode,a=document.createElement("div");a.style.marginBottom="20px",a.setAttribute("id",n),null==o||o.prepend(a);const s=this.paypalCommerceService.getPayPalSdkOrThrow(),d=s.Legal({fundingSource:s.Legal.FUNDING.PAY_UPON_INVOICE});if(!document.getElementById(n))throw new fi('Unable to initialize payment because "legalTextContainerElement" argument is not found.');d.render(`#${n}`)}handleError(e){const{onError:t}=this.paypalcommerceratepay||{};this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createFraudNetScript(e,t,n){const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{testMode:r}=i.config,o=document.createElement("script");o.setAttribute("type","application/json"),o.setAttribute("fncls","fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99"),o.setAttribute("data-id","fraudnetScript"),this.guid=this.generateGUID();const a={f:this.guid,s:`${e}_checkout-page`,sandbox:r};o.innerHTML=JSON.stringify(a),document.body.appendChild(o)}generateGUID(){let e="";for(let t=0;t<32;t+=1)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(62*Math.random())];return e}loadFraudnetConfig(){const e=document.createElement("script");e.setAttribute("data-id","fraudnetConfig"),e.src="https://c.paypal.com/da/r/fb.js",document.body.appendChild(e)}reinitializeStrategy(e){return mp(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}initializePollingMechanism(e,t,n,i){return mp(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.paypalCommerceService.getOrderStatus("paypalcommercealternativemethods",{params:{useMetadata:!0}}),o=r===_s.PollingStop,a=r===_s.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimernew yp(e,As(e),new vd({containerStyles:Object.assign(Object.assign({},Ka),{position:"fixed"})})),[{gateway:"paypalcommercealternativemethods",id:"ratepay"}]);function vp(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var fp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Sp{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalCommerceRequestSender=t,this.paypalSdkScriptLoader=n,this.paypalFastlaneUtils=i}initialize(e){var t,n;return fp(this,void 0,void 0,function*(){const{methodId:i,paypalcommercefastlane:r}=e;if(this.methodId=i,this.paypalcommercefastlane=r,!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new fi('Unable to initialize payment because "options.paypalcommercefastlane" argument is not provided.');if(!r.onInit||"function"!=typeof r.onInit)throw new fi('Unable to initialize payment because "options.paypalcommercefastlane.onInit" argument is not provided or it is not a function.');if(!r.onChange||"function"!=typeof r.onChange)throw new fi('Unable to initialize payment because "options.paypalcommercefastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState(),a=o.getCartOrThrow(),s=o.getPaymentMethodOrThrow(i),{isDeveloperModeApplicable:d,isFastlaneStylingEnabled:c}=s.initializationData||{};this.threeDSVerificationMethod=null===(t=s.initializationData)||void 0===t?void 0:t.threeDSVerificationMethod,this.paypalFastlaneSdk=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(s,a.currency.code,a.id,o.getLocale());const l=rd(c?null===(n=null==s?void 0:s.initializationData)||void 0===n?void 0:n.fastlaneStyles:{},null==r?void 0:r.styles);yield this.paypalFastlaneUtils.initializePayPalFastlane(this.paypalFastlaneSdk,!!d,l),this.shouldRunAuthenticationFlow()&&(yield this.runPayPalAuthenticationFlowOrThrow(i)),yield this.initializePayPalPaymentComponent(),r.onInit(e=>this.renderPayPalPaymentComponent(e)),r.onChange(()=>this.handlePayPalStoredInstrumentChange(i))})}execute(e,t){return fp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const{getHost:t}=e.getState();return new Sp(e,new Gs(n({host:t()})),Cs(),nd())},[{id:"paypalcommerceacceleratedcheckout"}]);var wp,Ip,Cp,bp,Pp,Op;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(wp||(wp={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(Ip||(Ip={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black"}(Cp||(Cp={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(bp||(bp={})),function(e){e.PILL="pill",e.RECT="rect"}(Pp||(Pp={})),function(e){e.ACKNOWLEDGE="ACKNOWLEDGE",e.FINALIZE="FINALIZE",e.INITIALIZE="INITIALIZE"}(Op||(Op={}));var Ep=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ap{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t,this.useRedirectFlow=!1,this.window=window}initialize(e){return Ep(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState();this.paymentMethod=t.getPaymentMethodOrThrow(e.methodId),this.useRedirectFlow=!0===(e.paypalexpress&&e.paypalexpress.useRedirectFlow);const n=this.paymentMethod.config.merchantId;if(!this.isInContextEnabled()||!n)throw new ti(Xn.MissingPaymentMethod);const i=yield this.scriptLoader.loadPaypalSDK();this.paypalSdk=i,this.paypalSdk.checkout.setup(n,{button:"paypal-button",environment:this.paymentMethod.config.testMode?"sandbox":"production"})})}deinitialize(){return this.isInContextEnabled()&&this.paypalSdk&&(this.paypalSdk.checkout.closeFlow(),this.paypalSdk=void 0),Promise.resolve()}execute(e,t){return Ep(this,void 0,void 0,function*(){let n,i;const r=this.paypalSdk;if(!this.isAcknowledgedOrFinalized()){if(!this.isInContextEnabled()||this.useRedirectFlow)return n=yield this.paymentIntegrationService.submitOrder(e,t),i=n.getPaymentRedirectUrl(),i&&this.window.top&&(this.window.top.location.href=i),new Promise(ce);if(!r)throw new ri(ei.PaymentNotInitialized);r.checkout.initXO();try{n=yield this.paymentIntegrationService.submitOrder(e,t)}catch(e){return r.checkout.closeFlow(),Promise.reject(e)}return i=n.getPaymentRedirectUrl(),i&&r.checkout.startFlow(i),new Promise(ce)}yield this.paymentIntegrationService.submitOrder(e,t)})}finalize(e){return Ep(this,void 0,void 0,function*(){return this.paymentIntegrationService.getState().getOrder()&&this.isAcknowledgedOrFinalized()?(yield this.paymentIntegrationService.finalizeOrder(e),Promise.resolve()):Promise.reject(new Cd)})}isAcknowledgedOrFinalized(){const e=this.paymentIntegrationService.getState();return e.getPaymentStatus()===Op.ACKNOWLEDGE||e.getPaymentStatus()===Op.FINALIZE}isInContextEnabled(){return!(!this.paymentMethod||!this.paymentMethod.config.merchantId)}}class Tp{constructor(e){this.scriptLoader=e,this.window=window}loadPaypalSDK(e=""){return t=this,n=void 0,r=function*(){const t=Object.assign({async:!0,attributes:{"data-merchant-id":e}},e&&{attributes:{"data-merchant-id":e}});if(yield this.scriptLoader.loadScript("//www.paypalobjects.com/api/checkout.min.js",t),!this.window.paypal)throw new mi;return this.window.paypal},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const kp=vi(e=>new Ap(e,new Tp(a())),[{id:"paypalexpress",type:"PAYMENT_TYPE_HOSTED"},{id:"paypalexpresscredit",type:"PAYMENT_TYPE_HOSTED"}]);var Dp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Mp extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this.threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Dp(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);n.config.is3dsEnabled&&(yield this.threeDSecureFlow.prepare(n))})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return Dp(this,void 0,void 0,function*(){const{payment:{methodId:i=""}={}}=e,r=this.paymentIntegrationService.getState();return r.getPaymentStatus()===dl.ACKNOWLEDGE?(yield this.paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:{methodId:i}}),t),Promise.resolve()):r.getPaymentMethodOrThrow(i).config.is3dsEnabled?this.threeDSecureFlow.start(n.execute.bind(this),e,t,this._hostedForm):n.execute.call(this,e,t)})}}const zp=vi(e=>new Mp(e,new Au(e,new Fu(new Lu(a())))),[{id:"paypal"}]);class Np extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this._formPoster=t}execute(e,t){const{payment:n}=e;if(!n)throw new ri(ei.PaymentNotInitialized);const{paymentData:i}=n;if(!i)throw new ti(Xn.MissingPayment);if(this._isThreeDSTwoExperimentOn()){const t=Object.assign(Object.assign({},i),{browser_info:ss()});e.payment&&(e.payment.paymentData=t)}return super.execute(e,t).catch(e=>pa(e)&&ve(e.body.errors,{code:"three_d_secure_required"})?new Promise(()=>{let t;t=this._isThreeDSTwoExperimentOn()&&!e.body.three_ds_result.merchant_data?{creq:e.body.three_ds_result.payer_auth_request}:{PaReq:e.body.three_ds_result.payer_auth_request,TermUrl:e.body.three_ds_result.callback_url,MD:e.body.three_ds_result.merchant_data},this._formPoster.postForm(e.body.three_ds_result.acs_url,t,void 0,"_top")}):Promise.reject(e))}finalize(e){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),super.finalize()}_isThreeDSTwoExperimentOn(){return!0===this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features["INT-4994.Opayo_3DS2"]}}const xp=vi(e=>new Np(e,Ee()),[{id:"sagepay"}]);class Rp{constructor(e,t){this._formPoster=e,this._paymentIntegrationService=t}execute(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{this.redirectUrl(t)})}var o},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}redirectUrl(e){return this._formPoster.postForm(e,{})}_isAdditionalActionRequired(e){const{additional_action_required:t,status:n}=e;return"additional_action_required"===n&&t&&"offsite_redirect"===t.type}}class Fp extends Rp{redirectUrl(e){window.location.replace(e)}}const Lp=vi(e=>new Fp(Ee(),e),[{id:"sezzle"}]);var Bp;!function(e){e.CHARGE="CHARGE",e.STORE="STORE"}(Bp||(Bp={}));var jp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Up{constructor(e,t){this._scriptLoader=e,this._paymentIntegrationService=t}initialize({testMode:e,applicationId:t,locationId:n}){return jp(this,void 0,void 0,function*(){const i=yield this._scriptLoader.load(e);this._payments=i.payments(t,n)})}deinitialize(){return jp(this,void 0,void 0,function*(){this._formValidationSubscription&&this._formValidationSubscription.unsubscribe(),this._card&&(yield this._card.destroy()),this._formValidationSubscription=void 0,this._card=void 0,this._payments=void 0})}initializeCard({containerId:e,style:t,onValidationChange:n}){return jp(this,void 0,void 0,function*(){const{postalCode:i}=this._paymentIntegrationService.getState().getBillingAddress()||{};this._card=yield this._getPayments().card(),yield this._card.attach(`#${e}`);try{yield this._card.configure({postalCode:i,style:t})}catch(e){}n&&(this._formValidationSubscription=this._subscribeToFormValidation(this._card,n))})}tokenize(){return jp(this,void 0,void 0,function*(){const e=yield this._getCard().tokenize();if("OK"!==e.status||!e.token){let t=`Tokenization failed with status: ${e.status}`;throw"errors"in e&&e.errors&&(t+=` and errors: ${JSON.stringify(e.errors)}`),new _h("payment.errors.card_error","SquareV2TokenizationError",t)}return e.token})}verifyBuyer(e,t){return jp(this,void 0,void 0,function*(){return t===Bp.CHARGE?this._chargeVerifyBuyer(e):this._storeVerifyBuyer(e)})}_getPayments(){return ii(this._payments,()=>new ri(ei.PaymentNotInitialized))}_subscribeToFormValidation(e,t){const n=["cardNumber","cvv"],i=new Set(n),r=["focusClassAdded","focusClassRemoved","errorClassAdded","errorClassRemoved","cardBrandChanged","postalCodeChanged"].map(t=>_(e,t));return w(...r).pipe(T(e=>{const{detail:{field:t,currentState:{isCompletelyValid:r}}}=e;return n.includes(t)&&i[r?"delete":"add"](t),0===i.size}),E()).subscribe(t)}_getCard(){return ii(this._card,()=>new ri(ei.PaymentNotInitialized))}_mapToSquareBillingContact({firstName:e,lastName:t,address1:n,address2:i,city:r,stateOrProvinceCode:o,postalCode:a,countryCode:s,email:d,phone:c}){return{givenName:e,familyName:t,addressLines:[n,i],city:r,state:o,postalCode:a,countryCode:s,email:d,phone:c}}_chargeVerifyBuyer(e){return jp(this,void 0,void 0,function*(){const{getCheckoutOrThrow:t,getBillingAddressOrThrow:n}=this._paymentIntegrationService.getState(),{outstandingBalance:i,cart:r}=t(),o={amount:i.toString(),billingContact:this._mapToSquareBillingContact(n()),currencyCode:r.currency.code,intent:Bp.CHARGE},a=yield this._getPayments().verifyBuyer(e,o);return a?a.token:""})}_storeVerifyBuyer(e){return jp(this,void 0,void 0,function*(){const{getBillingAddressOrThrow:t}=this._paymentIntegrationService.getState(),n={billingContact:this._mapToSquareBillingContact(t()),intent:Bp.STORE},i=yield this._getPayments().verifyBuyer(e,n);return i?i.token:""})}}var qp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vp{constructor(e,t){this._paymentIntegrationService=e,this._squareV2PaymentProcessor=t}initialize(e){var t;return qp(this,void 0,void 0,function*(){if(!(null===(t=null==e?void 0:e.squarev2)||void 0===t?void 0:t.containerId))throw new fi('Unable to proceed because "containerId" argument is not provided.');const{methodId:n,squarev2:i}=e,{config:{testMode:r},initializationData:o}=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(n),{applicationId:a,locationId:s}=o||{};if(!a)throw new Xr;yield this._squareV2PaymentProcessor.initialize({applicationId:a,locationId:s,testMode:r}),yield this._squareV2PaymentProcessor.initializeCard(i)})}execute({payment:e}){return qp(this,void 0,void 0,function*(){if(!e)throw new co(["payment"]);const{methodId:t,paymentData:n}=e,{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r}=jd(n)?n:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1};yield this._paymentIntegrationService.submitOrder();const o=n&&xd(n)?yield this._getVaultedInstrumentPayload(t,n):yield this._getCardPayload(t,i);yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:{formattedPayload:Object.assign(Object.assign({},o),{vault_payment_instrument:i||!1,set_as_default_stored_instrument:r||!1})}}))})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this._squareV2PaymentProcessor.deinitialize()}shouldVerify(){const{features:e}=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings;return e["PROJECT-3828.add_3ds_support_on_squarev2"]}_getCardPayload(e,t){return qp(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),{initializationData:i}=n(e),r=yield this._squareV2PaymentProcessor.tokenize();if(i&&"isSquareV2ApiV2Enabled"in i?!i.isSquareV2ApiV2Enabled:!this.shouldVerify())return{credit_card_token:{token:r}};let o={nonce:r,token:yield this._squareV2PaymentProcessor.verifyBuyer(r,Bp.CHARGE)};if(t){const e=yield this._squareV2PaymentProcessor.tokenize();o=Object.assign(Object.assign({},o),{store_card_nonce:e,store_card_token:yield this._squareV2PaymentProcessor.verifyBuyer(e,Bp.STORE)})}return{credit_card_token:{token:JSON.stringify(o)}}})}_getVaultedInstrumentPayload(e,t){return qp(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),{initializationData:i}=n(e),{instrumentId:r}=t,o=(i&&"isSquareV2ApiV2Enabled"in i?i.isSquareV2ApiV2Enabled:this.shouldVerify())?yield this._squareV2PaymentProcessor.verifyBuyer(yield this._getSquareCardIdOrThrow(e,r),Bp.CHARGE):void 0;return{bigpay_token:Object.assign({token:r},o&&{three_d_secure:{token:o}})}})}_getSquareCardIdOrThrow(e,t){return qp(this,void 0,void 0,function*(){const n=yield this._paymentIntegrationService.loadPaymentMethod(e,{params:{method:e,bigpayToken:t}}),{initializationData:i}=n.getPaymentMethodOrThrow(e),{cardId:r}=i||{};if(!r)throw new co(["cardId"]);return r})}}var Gp;!function(e){e.LIVE="https://web.squarecdn.com/v1/square.js",e.SANDBOX="https://sandbox.web.squarecdn.com/v1/square.js"}(Gp||(Gp={}));class Hp{constructor(e){this._scriptLoader=e}load(e=!1){return t=this,n=void 0,r=function*(){return yield this._scriptLoader.loadScript(e?Gp.SANDBOX:Gp.LIVE),function(e){if(!function(e){return"Square"in e}(e))throw new mi}(window),window.Square},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const Wp=vi(e=>new Vp(e,new Up(new Hp(a()),e)),[{id:"squarev2"}]);function $p(e){return null!==e&&"object"==typeof e&&"cardNumberElementOptions"in e&&"cardCvcElementOptions"in e&&"cardExpiryElementOptions"in e&&void 0!==e.cardNumberElementOptions&&void 0!==e.cardCvcElementOptions&&void 0!==e.cardExpiryElementOptions}var Yp,Kp,Jp,Zp;!function(e){e.Solid="solid",e.Default="default"}(Yp||(Yp={})),function(e){e.Alipay="alipay",e.CardCvc="cardCvc",e.CardExpiry="cardExpiry",e.CardNumber="cardNumber",e.CreditCard="card",e.IDEAL="idealBank",e.Sepa="iban"}(Kp||(Kp={})),function(e){e.Alipay="alipay",e.CreditCard="card",e.IDEAL="ideal",e.Sepa="sepa_debit"}(Jp||(Jp={})),function(e){e.AuthFailure="auth_failure"}(Zp||(Zp={}));class Qp extends Qn{constructor(e){super(e===Zp.AuthFailure?"User did not authenticate":"There was an error while processing your payment. Please try again or contact us."),this.type="stripev3_error",this.subtype=e}}var Xp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const em=[Kp.Alipay,Kp.IDEAL];class tm{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){return Xp(this,void 0,void 0,function*(){const{stripev3:t,methodId:n,gatewayId:i}=e;if(!i)throw new fi('Unable to initialize payment because "gatewayId" argument is not provided.');this.initializeOptions=t,this.isDeinitialize=!1;const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n),{initializationData:{stripePublishableKey:o,stripeConnectedAccount:a,useIndividualCardFields:s,allowRedisplayForStoredInstruments:d}}=r;this._allowRedisplayForStoredInstruments=d;const c=this.getInitializeOptions().form;this.useIndividualCardFields=s,this.stripeV3Client=yield this.loadStripeJs(o,a),this.isCreditCard(n)&&this.shouldShowTSVHostedForm(n,i)&&c?this.hostedForm=yield this.mountCardVerificationFields(c):this.stripeElement=yield this.mountCardFields(n)})}execute(e,t){var n,i;return Xp(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{switch(this.stripeElements||(this.stripeElements=this.getStripeJs().elements()),e){case Kp.CreditCard:if(this.useIndividualCardFields&&$p(t)){const{cardNumberElementOptions:e,cardExpiryElementOptions:n,cardCvcElementOptions:r}=t,a=this.stripeElements.getElement(Kp.CardNumber)||this.stripeElements.create(Kp.CardNumber,e),s=this.stripeElements.getElement(Kp.CardExpiry)||this.stripeElements.create(Kp.CardExpiry,n),d=this.stripeElements.getElement(Kp.CardCvc)||this.stripeElements.create(Kp.CardCvc,r);this.stripeCardElements=[a,s,d],i=this.stripeCardElements[0];try{a.mount(`#${e.containerId}`),s.mount(`#${n.containerId}`),d.mount(`#${r.containerId}`)}catch(e){this.isDeinitialize||o(new fi("Unable to mount Stripe component without valid container ID."))}}else{i=this.stripeElements.getElement(e)||this.stripeElements.create(e,t);try{i.mount(`#${n}`)}catch(e){this.isDeinitialize||o(new fi("Unable to mount Stripe component without valid container ID."))}}break;case Kp.IDEAL:case Kp.Sepa:i=this.stripeElements.getElement(e)||this.stripeElements.create(e,t);try{i.mount(`#${n}`)}catch(e){this.isDeinitialize||o(new fi("Unable to mount Stripe component without valid container ID."))}case Kp.Alipay:}r(i)})}mountCardVerificationFields(e){return Xp(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getStoreConfig();if(!t)throw new ti(Xn.MissingCheckoutConfig);const n=t.paymentSettings.bigpayBaseUrl,i=this.paymentIntegrationService.createHostedForm(n,e);return yield i.attach(),i})}processAdditionalAction(e,t,n=!1,i=!1){return Xp(this,void 0,void 0,function*(){if(!pa(e))throw e;const r=ve(e.body.errors,{code:"additional_action_required"}),o=ve(e.body.errors,{code:"three_d_secure_required"});if(r){const t=e.body.additional_action_required;if(t&&"redirect_to_url"===t.type)return new Promise(()=>{t.data.redirect_url&&window.location.replace(t.data.redirect_url)})}if(o){const r=e.body.three_ds_result.token,o=!1;let a,s=!1;try{a=yield this.getStripeJs().confirmCardPayment(r)}catch(e){s=!0}if(null==a?void 0:a.error){if(this.isCancellationError(a.error))throw new Wi;if(this.isAuthError(a.error))throw new Qp(Zp.AuthFailure);throw new Error(a.error.message)}const d={credit_card_token:{token:this.getPaymentToken(null==a?void 0:a.paymentIntent,r,s)},vault_payment_instrument:n,confirm:o},c=this.buildPaymentPayload(t,d,i);try{return yield this.paymentIntegrationService.submitPayment(c)}catch(e){throw this.handleEmptyPaymentIntentError(e,null==a?void 0:a.error)}}throw e})}getPaymentToken(e,t,n){return!e||n?t:e.id}shouldShowTSVHostedForm(e,t){return this.isHostedFieldAvailable()&&this.isHostedPaymentFormEnabled(e,t)}unmountElement(){this.stripeElement&&(this.stripeElement.unmount(),this.stripeElement=void 0)}}class nm{constructor(e,t=window){this.scriptLoader=e,this.stripeWindow=t}load(e,t,n){return this.scriptLoader.loadScript("https://js.stripe.com/v3/").then(()=>{if(!this.stripeWindow.Stripe)throw new mi;return this.stripeWindow.Stripe(e,{stripeAccount:t,locale:n,betas:["payment_intent_beta_3","alipay_pm_beta_1"],apiVersion:"2020-03-02;alipay_beta=v1"})})}}const im=vi(e=>new tm(e,new nm(a())),[{gateway:"stripev3"}]),rm={ar:["ar"],bg:["bg"],cs:["cs"],da:["da"],de:["de"],el:["el"],en:["en","en-GB"],es:["es","es-419"],et:["et"],fi:["fi"],fil:["fil"],fr:["fr","fr-CA"],he:["he"],hr:["hr"],hu:["hu"],id:["id"],it:["it"],ja:["ja"],ko:["ko"],lt:["lt"],lv:["lv"],ms:["ms"],mt:["mt"],nb:["nb"],nl:["nl"],pl:["pl"],pt:["pt","pt-BR"],ro:["ro"],ru:["ru"],sk:["sk"],sl:["sl"],sv:["sv"],th:["th"],tr:["tr"],vi:["vi"],zh:["zh","zh-HK","zh-TW"]};function om(e){const[t,n]=e.replace(/_/g,"-").toLowerCase().split("-"),i=rm[t];if(!i)return"auto";const r=n?`${t}-${n.toUpperCase()}`:t;return i.indexOf(r)>-1?r:i[0]}var am=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class sm{constructor(e,t,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n}initialize(e){return am(this,void 0,void 0,function*(){const{stripeupe:t,methodId:n,gatewayId:i}=e;if(!(null==t?void 0:t.containerId))throw new ri(ei.PaymentNotInitialized);if(!i)throw new fi('Unable to initialize payment because "gatewayId" argument is not provided.');return this._loadStripeElement(t,i,n).catch(e=>{var n;return null===(n=t.onError)||void 0===n?void 0:n.call(t,e)}),this.stripeIntegrationService.initCheckoutEventsSubscription(i,n,t,this._stripeElements),Promise.resolve()})}execute(e,t){return am(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{o()}),f.on(za.CHANGE,e=>{(null==e?void 0:e.value)&&"type"in e.value&&this._updateStripeLinkStateByElementType(e.value.type)}),this._isStripeElementUpdateEnabled&&(null==a||a(this._updateStripeElement.bind(this)))})}_processAdditionalActionWithStripeConfirmation(e,t,n,i=!1,r=!1){return am(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new ri(ei.PaymentNotInitialized);const{data:o}=e.body.additional_action_required,{token:a}=o,{paymentIntent:s,error:d}=yield this._confirmStripePaymentOrThrow(t,o),c=this._getPaymentPayload(t,(null==s?void 0:s.id)||a,i,r);if(d||!s){const{initializationData:e}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{sendSecondPaymentRequestOnStripeError:i}=e||{};if(i)try{const e=de({},c,{paymentData:{formattedPayload:{client_side_error:!0}}});yield this.paymentIntegrationService.submitPayment(e)}catch(e){}this.stripeIntegrationService.throwStripeError(d)}try{yield this.paymentIntegrationService.submitPayment(c)}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}})}_confirmStripePaymentOrThrow(e,t){return am(this,void 0,void 0,function*(){if(!this._stripeUPEClient)throw new ri(ei.PaymentNotInitialized);const{token:n,redirect_url:i}=t,r=this.stripeIntegrationService.mapStripePaymentData(this._stripeElements,i,!!this._allowRedisplayForStoredInstruments);return(yield this.stripeIntegrationService.isPaymentCompleted(e,this._stripeUPEClient))?this._stripeUPEClient.retrievePaymentIntent(n||""):this._stripeUPEClient.confirmPayment(r)})}_processVaultedAdditionalAction(e,t,n=!1){var i;return am(this,void 0,void 0,function*(){if(!t||!pa(e)||!ve(e.body.errors,{code:"three_d_secure_required"}))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new ri(ei.PaymentNotInitialized);const r=e.body.three_ds_result.token;let o,a=!1;try{o=yield this._stripeUPEClient.confirmCardPayment(r)}catch(e){try{o=yield this._stripeUPEClient.retrievePaymentIntent(r)}catch(e){a=!0}}if((null==o?void 0:o.error)&&this.stripeIntegrationService.throwStripeError(o.error),!(null==o?void 0:o.paymentIntent)&&!a)throw new nr;const s=this._getPaymentPayload(t,a?r:null===(i=null==o?void 0:o.paymentIntent)||void 0===i?void 0:i.id,!1,n);return this.paymentIntegrationService.submitPayment(s)})}_loadStripeJs(e){return am(this,void 0,void 0,function*(){if(this._stripeUPEClient)return this._stripeUPEClient;const t=this.paymentIntegrationService.getState();return this.scriptLoader.getStripeClient(e,t.getCartLocale(),ka.V3,Fa,La)})}_getPaymentPayload(e,t,n=!1,i=!1){var r;return{methodId:e,paymentData:{formattedPayload:{cart_id:(null===(r=this.paymentIntegrationService.getState().getCart())||void 0===r?void 0:r.id)||"",credit_card_token:{token:t},confirm:!1,vault_payment_instrument:n,set_as_default_stored_instrument:i}}}}_updateStripeElement({shouldShowTerms:e}){var t;const n=null===(t=this._stripeElements)||void 0===t?void 0:t.getElement(Da.PAYMENT);null==n||n.update(Object.assign({},this._getStripeElementTerms(e)))}_getStripeElementTerms(e){let t=Ta.AUTO;return this._isStripeElementUpdateEnabled&&(t=e?Ta.AUTO:Ta.NEVER),{terms:{card:t}}}_updateStripeLinkStateByElementType(e){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow(),n=e===Aa.Link;!cd(t)&&n&&this.paymentIntegrationService.updatePaymentProviderCustomer({stripeLinkAuthenticationState:n})}}const dm=vi(e=>{const t=new Ra(a());return new sm(e,t,new pd(e,t))},[{gateway:"stripeupe"},{gateway:"stripeupe",id:"klarna"}]),cm=e=>"object"==typeof e&&null!==e&&"value"in e&&"collapsed"in e;var lm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class um{constructor(e,t,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n}initialize(e){var t;return lm(this,void 0,void 0,function*(){const{stripeocs:n,methodId:i,gatewayId:r}=e;if(!(null==n?void 0:n.containerId))throw new ri(ei.PaymentNotInitialized);if(!r)throw new fi('Unable to initialize payment because "gatewayId" argument is not provided.');try{yield this._initializeStripeElement(n,r,i)}catch(e){e instanceof Error&&(null===(t=n.onError)||void 0===t||t.call(n,e))}this.stripeIntegrationService.initCheckoutEventsSubscription(r,i,n,this.stripeElements)})}execute(e,t){return lm(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{null==y||y(!1)}),_.on(za.READY,()=>{h()}),_.on(za.CHANGE,e=>{this._onStripeElementChange(e,t,n,p)}),null==m||m(this._collapseStripeElement.bind(this))})}_loadStripeJs(e){return lm(this,void 0,void 0,function*(){if(this.stripeClient)return this.stripeClient;const t=this.paymentIntegrationService.getState(),n=this.stripeIntegrationService.getStripeJsVersion(e);return this.scriptLoader.getStripeClient(e,t.getCartLocale(),n)})}_collapseStripeElement(){var e;const t=null===(e=this.stripeElements)||void 0===e?void 0:e.getElement(Da.PAYMENT);null==t||t.collapse()}_getPaymentPayload(e,t,n){var i;const r=(null===(i=this.paymentIntegrationService.getState().getCart())||void 0===i?void 0:i.id)||"",{card:o,us_bank_account:a}=n||{},s=this._shouldSaveInstrument(o)||this._shouldSaveInstrument(a),d=this._getTokenizedOptions(t,n);return{methodId:e,paymentData:{formattedPayload:Object.assign({cart_id:r,confirm:!1,method:this.selectedMethodId,vault_payment_instrument:s},d)}}}_processAdditionalAction(e,t,n){return lm(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this.stripeClient||!this.stripeElements)throw new ri(ei.PaymentNotInitialized);const{data:i}=e.body.additional_action_required,{token:r}=i,{paymentIntent:o,error:a}=yield this._confirmStripePaymentOrThrow(t,i),{client_secret:s,payment_method_options:d}=o||{},c=this._getPaymentPayload(t,s||r,d);if(a||!o){const{initializationData:e}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{sendSecondPaymentRequestOnStripeError:i}=e||{};if(i)try{const e=de({},c,{paymentData:{formattedPayload:{client_side_error:!0}}});yield this.paymentIntegrationService.submitPayment(e)}catch(e){}this.stripeIntegrationService.throwStripeError(a)}try{return yield this.paymentIntegrationService.submitPayment(c)}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}})}_confirmStripePaymentOrThrow(e,t){return lm(this,void 0,void 0,function*(){if(!this.stripeClient)throw new ri(ei.PaymentNotInitialized);const{token:n,redirect_url:i}=t,r=this.stripeIntegrationService.mapStripePaymentData(this.stripeElements,i);return(yield this.stripeIntegrationService.isPaymentCompleted(e,this.stripeClient))?this.stripeClient.retrievePaymentIntent(n||""):this.stripeClient.confirmPayment(r)})}_onStripeElementChange(e,t,n,i){cm(e)&&!e.collapsed&&(this.selectedMethodId=e.value.type,null==i||i(`${t}-${n}`))}_shouldSaveInstrument(e){const t=null==e?void 0:e.setup_future_usage;return t===Na.ON_SESSION||t===Na.OFF_SESSION}_getTokenizedOptions(e,t){return this._shouldSaveInstrument(null==t?void 0:t.us_bank_account)?{tokenized_ach:{token:e}}:{credit_card_token:{token:e}}}}const hm=vi(e=>{const t=new Ra(a());return new um(e,t,new pd(e,t))},[{gateway:"stripeocs",id:"optimized_checkout"}]);var pm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class mm{constructor(e,t,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n}initialize(e){var t;return pm(this,void 0,void 0,function*(){const{stripeocs:n,methodId:i,gatewayId:r}=e;if(!(null==n?void 0:n.containerId)||!r)throw new ri(ei.PaymentNotInitialized);let o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,r);(null==o?void 0:o.clientToken)||(yield this.paymentIntegrationService.loadPaymentMethod(r,{params:{method:i}}),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,r));try{yield this._initStripeCheckoutSession(n,o),yield this._updateStripeShopperData(),this._initializePaymentElement(n,o),this._initializeAdaptivePricingElement(n,o)}catch(e){e instanceof Error&&(null===(t=n.onError)||void 0===t||t.call(n,e))}})}execute(e,t){return pm(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{null==u||u(!1)}),h.on(za.READY,()=>{d()}),h.on(za.CHANGE,e=>{this._onStripeElementChange(e,r,i,c)}),null==l||l(this._collapseStripeElement.bind(this))}_loadStripeJs(e){return pm(this,void 0,void 0,function*(){if(this.stripeClient)return this.stripeClient;const t=this.paymentIntegrationService.getState();return this.scriptLoader.getStripeClient(e,t.getCartLocale(),ka.CLOVER)})}_getStripeActionsOrThrow(){return pm(this,void 0,void 0,function*(){if(!this.stripeCheckout)throw new ri(ei.PaymentNotInitialized);const{actions:e,error:t}=yield this.stripeCheckout.loadActions();if(!e||t)throw new Qr(null==t?void 0:t.message);return e})}_getStripeElement(e){var t,n;return(null===(t=this.stripeCheckout)||void 0===t?void 0:t.getPaymentElement())||(null===(n=this.stripeCheckout)||void 0===n?void 0:n.createPaymentElement(e))}_onStripeElementChange(e,t,n,i){cm(e)&&!e.collapsed&&(this.selectedMethodId=e.value.type,null==i||i(`${t}-${n}`))}_collapseStripeElement(){var e;const t=null===(e=this.stripeCheckout)||void 0===e?void 0:e.getPaymentElement();null==t||t.collapse()}_updateCheckoutSessionData(e,t){return pm(this,void 0,void 0,function*(){yield this._updateStripeShopperData(),yield this.paymentIntegrationService.loadPaymentMethod(e,{params:{method:t}})})}_getPaymentPayload(e,t,n){var i;const r=(null===(i=this.paymentIntegrationService.getState().getCart())||void 0===i?void 0:i.id)||"",o=this._getTokenizedOptions(t,n);return{methodId:e,paymentData:{formattedPayload:Object.assign({cart_id:r,confirm:!1,method:this.selectedMethodId,vault_payment_instrument:!!n},o)}}}_processAdditionalAction(e,t,n){var i;return pm(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;const{data:r}=(null===(i=e.body)||void 0===i?void 0:i.additional_action_required)||{},{token:o}=r||{},a=yield this._getStripeSavedPaymentMethodsOrThrow(),{session:s,error:d}=yield this._confirmStripePayment(r),c=yield this._getStripeSavedPaymentMethodsOrThrow(s),{id:l,status:u}=s||{},h=this._getNewVaultedStripeInstrument(a,c),p=this._getPaymentPayload(n,l||o,h),{initializationData:m}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t),{sendSecondPaymentRequestOnStripeError:y}=m||{};if(d||!s){if(y)try{const e=de({},p,{paymentData:{formattedPayload:{client_side_error:!0}}});yield this.paymentIntegrationService.submitPayment(e)}catch(e){}throw new Qr(null==d?void 0:d.message)}try{return yield this.paymentIntegrationService.submitPayment(p)}catch(e){throw(null==u?void 0:u.paymentStatus)===Oa.Paid&&this.stripeIntegrationService.throwPaymentConfirmationProceedMessage(),e}})}_confirmStripePayment(e){return pm(this,void 0,void 0,function*(){const{redirect_url:t}=e||{};if(!this.stripeCheckout)throw new ri(ei.PaymentNotInitialized);return(yield this._getStripeActionsOrThrow()).confirm({redirect:Ta.IF_REQUIRED,returnUrl:t})})}_updateStripeShopperData(){return pm(this,void 0,void 0,function*(){const e=yield this._getStripeActionsOrThrow();yield this._updateStripeEmail(e),yield this._updateStripeShippingAddress(e),yield this._updateStripeBillingAddress(e)})}_updateStripeEmail(e){return pm(this,void 0,void 0,function*(){if((yield e.getSession()).email)return;const{getBillingAddress:t}=this.paymentIntegrationService.getState(),n=t();yield e.updateEmail((null==n?void 0:n.email)||"")})}_updateStripeShippingAddress(e){return pm(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getShippingAddress();t&&(yield e.updateShippingAddress({name:this.stripeIntegrationService.getShopperFullName(t),address:this.stripeIntegrationService.mapStripeAddress(t)}))})}_updateStripeBillingAddress(e){return pm(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getBillingAddress();t&&(yield e.updateBillingAddress({name:this.stripeIntegrationService.getShopperFullName(t),address:this.stripeIntegrationService.mapStripeAddress(t)}))})}_getStripeSavedPaymentMethodsOrThrow(e){return pm(this,void 0,void 0,function*(){if(null==e?void 0:e.savedPaymentMethods)return e.savedPaymentMethods;const t=yield this._getStripeActionsOrThrow(),{savedPaymentMethods:n}=yield t.getSession();return n||[]})}_getNewVaultedStripeInstrument(e,t){return t.find(t=>!e.some(e=>e.id===t.id))}_getTokenizedOptions(e,t){return(null==t?void 0:t.type)===Aa.ACH?{tokenized_ach:{token:e}}:{credit_card_token:{token:e}}}_initializeAdaptivePricingElement(e,t){const{initializationData:n}=t,{currencySelectorContainerId:i}=e;if(!(null==n?void 0:n.adaptivePricingEnabled))return;if(!i)throw new ri(ei.PaymentNotInitialized);const r=this._getCurrencySelectorElement();r&&(r.mount(`#${i}`),this._initAdaptivePricingEvents(r))}_getCurrencySelectorElement(){var e,t;return(null===(e=this.stripeCheckout)||void 0===e?void 0:e.getCurrencySelectorElement())||(null===(t=this.stripeCheckout)||void 0===t?void 0:t.createCurrencySelectorElement())}_initAdaptivePricingEvents(e){e.on(za.CHANGE,e=>pm(this,void 0,void 0,function*(){if(!e.value||!("currency"in e.value))return;const{currency:t}=this.paymentIntegrationService.getState().getCartOrThrow(),n=t.code.toLowerCase(),i=e.value.currency.toLowerCase();yield this.paymentIntegrationService.updatePaymentProviderCustomer({isCustomerCurrencySelected:n!==i,customerCurrency:i})}))}}const ym=vi(e=>{const t=new Ra(a());return new mm(e,t,new pd(e,t))},[{gateway:"stripeocs",id:"checkout_session"}]);var gm;!function(e){e.CARD_NUMBER="card-number",e.CVV="cvv",e.EXPIRY="expiry"}(gm||(gm={}));var vm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class fm{constructor(e,t,n){this.paymentIntegrationService=e,this.tdOnlineMartScriptLoader=t,this.formPoster=n,this.tdInputs=[{id:"ccNumber",fieldType:gm.CARD_NUMBER},{id:"ccCvv",fieldType:gm.CVV},{id:"ccExpiry",fieldType:gm.EXPIRY}]}initialize(e){return vm(this,void 0,void 0,function*(){const{methodId:t}=e;if(!t)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');this.tdOnlineMartClient=yield this.loadTDOnlineMartJs(),this.mountHostedFields(t)})}execute(e,t){return vm(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{null==e||e.unmount()}),Promise.resolve()}getPaymentPayloadOrThrow(e){return vm(this,void 0,void 0,function*(){const{methodId:t,paymentData:n}=e,{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:r=!1}=jd(n)?n:{},o={browser_info:ss(),shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r};if(jd(n)&&xd(n)&&n.instrumentId){const e=!!this.paymentIntegrationService.getState().getCartOrThrow().lineItems.digitalItems.length,i=!this.isTrustedVaultingInstrument(n.instrumentId)||e;return{methodId:t,paymentData:Object.assign(Object.assign(Object.assign({},o),{instrumentId:n.instrumentId}),i?{nonce:n.instrumentId}:{})}}let a;try{a=yield this.getTokenOrThrow()}catch(e){this.throwTokenizationError(e)}return{methodId:t,paymentData:Object.assign(Object.assign({},o),{nonce:a})}})}mountHostedFields(e){const t=this.getHostedFieldsOptions(),n=this.getTDOnlineMartClientOrThrow();this.tdInputs.forEach(i=>{const r=`${e}-${i.id}`;document.getElementById(r)&&(i.inputElement=n.create(i.fieldType,t),i.inputElement.mount(`#${r}`))})}loadTDOnlineMartJs(){return vm(this,void 0,void 0,function*(){return this.tdOnlineMartClient?this.tdOnlineMartClient:this.tdOnlineMartScriptLoader.load()})}getTokenOrThrow(){return new Promise((e,t)=>{this.getTDOnlineMartClientOrThrow().createToken(n=>{const{error:i,token:r}=n;if(i||!r)return t(i);e(r)})})}getTDOnlineMartClientOrThrow(){if(!this.tdOnlineMartClient)throw new ri(ei.PaymentNotInitialized);return this.tdOnlineMartClient}processWithAdditionalAction(e){return vm(this,void 0,void 0,function*(){if(!function(e){return pa(e)&&(t=e.body,Z(t)&&"object"==typeof t&&"errors"in t&&"three_ds_result"in t&&W(t.errors)&&ve(t.errors,{code:"three_d_secure_required"}));var t}(e))throw e;const{three_ds_result:t}=e.body,{acs_url:n,payer_auth_request:i,merchant_data:r}=t||{};if(!n||!i||!r)throw new co(["formUrl","threeDSSessionData","creq"]);return new Promise(e=>{this.formPoster.postForm(n,{threeDSSessionData:i,creq:r},e,"_top")})})}throwTokenizationError(e){if(!function(e){return"object"==typeof e&&null!==e&&"field"in e&&"type"in e&&"message"in e}(e))throw new ti(Xn.MissingPaymentToken);throw new Error(e.message)}getHostedFieldsOptions(){return{style:{error:{color:"#d14343"}},classes:{error:"form-input--error"}}}isTrustedVaultingInstrument(e){const t=this.paymentIntegrationService.getState().getInstruments(),n=null==t?void 0:t.find(t=>uc(t)&&t.bigpayToken===e);return!(uc(n)&&!n.trustedShippingAddress)}}class Sm{constructor(e,t=window){this.scriptLoader=e,this.tdOnlineMartWindow=t}load(){return e=this,t=void 0,i=function*(){if(this.tdOnlineMartWindow.customcheckout||(yield this.scriptLoader.loadScript("https://libs.na.bambora.com/customcheckout/1/customcheckout.js")),!this.tdOnlineMartWindow.customcheckout)throw new mi;return this.tdOnlineMartWindow.customcheckout()},new((n=void 0)||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())});var e,t,n,i}}const _m=vi(e=>new fm(e,new Sm(a()),Ee()),[{id:"tdonlinemart"}]);var wm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const Im="Payment cannot continue";let Cm;class bm extends tu{initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return wm(this,void 0,void 0,function*(){if(this._initializeOptions=e&&e.worldpay,!this._initializeOptions)throw new ri(ei.PaymentNotInitialized);return t.initialize.call(this,e)})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return wm(this,void 0,void 0,function*(){const{payment:i}=e;if(Cm=this._submitAdditionalAction(),!i)throw new co(["payment"]);try{return yield n.execute.call(this,e,t)}catch(e){return this._processAdditionalAction(e,i)}})}_processAdditionalAction(e,t){return wm(this,void 0,void 0,function*(){return pa(e)&&ve(e.body.errors,{code:"additional_action_required"})?new Promise((n,i)=>{const r=e=>wm(this,void 0,void 0,function*(){if(-1===e.origin.indexOf("cardinalcommerce.com"))return;if("string"!=typeof e.data||!this._isValidJsonWithSessionId(e.data))return i(new Error(Im));window.removeEventListener("message",r),o.remove();const a=JSON.parse(e.data),s=de({},t,{paymentData:{threeDSecure:{token:a.SessionId}}});try{n(yield Cm(s))}catch(e){if(!pa(e)||!ve(e.body.errors,{code:"three_d_secure_required"}))return i(e);if(!this._initializeOptions)return i(new ri(ei.PaymentNotInitialized));const{onLoad:t}=this._initializeOptions,n=this._createIframe(e.body.three_ds_result);try{t(n,()=>i(new Error("Payment was cancelled")))}catch(e){i(new Error(Im))}}});let o;window.addEventListener("message",r);try{o=this._createHiddenIframe(e.body)}catch(e){throw window.removeEventListener("message",r),new Error(Im)}}):Promise.reject(e)})}_createHiddenIframe(e){const t=document.createElement("iframe");if(document.body.appendChild(t),!t.contentWindow)throw new Error;t.id="worldpay_hosted_hidden_payment_page",t.height="0px",t.width="0px";const n=document.createElement("form"),i="collectionForm";n.id=i,n.name="devicedata",n.method="post";const r=e.additional_action_required.data.redirect_url;n.action=r;const o=document.createElement("input");o.name="Bin",o.type="hidden",o.value=e.provider_data.source_id,n.appendChild(o);const a=document.createElement("input");a.name="JWT",a.type="hidden",a.value=e.provider_data.data,n.appendChild(a);const s=document.createElement("button");s.type="submit",s.id="btnsubmit",n.appendChild(s),navigator.userAgent.match("Firefox")?t.srcdoc=n.outerHTML:t.contentWindow.document.body.appendChild(n);const d=document.createElement("script");return d.innerHTML=`\n document.getElementById('${i}').submit();\n `,t.contentWindow.document.body.appendChild(d),t}_createIframe(e){const t=document.createElement("form");t.id="challengeForm",t.method="POST",t.action=e.acs_url;const n=document.createElement("input");n.name="JWT",n.type="hidden",n.value=e.payer_auth_request,t.appendChild(n);const i=document.createElement("input");i.name="MD",i.type="hidden",i.value=`merchantSessionId=${e.merchant_data}`,t.appendChild(i);const r=document.createElement("script");r.type="text/javascript",r.innerHTML="window.onload = function() { document.getElementById('challengeForm').submit(); }";const o=document.createElement("iframe");return o.name="worldpay_hosted_payment_page",o.height="400",o.width="100%",o.srcdoc=`${t.outerHTML} ${r.outerHTML}`,o}_submitAdditionalAction(){if(this._shouldRenderHostedForm){if(!this._hostedForm)throw new ri(ei.PaymentNotInitialized);const e=this._hostedForm;return t=>wm(this,void 0,void 0,function*(){yield e.submit(t)})}return e=>wm(this,void 0,void 0,function*(){yield this._paymentIntegrationService.submitPayment(e)})}_isValidJsonWithSessionId(e){try{const t=JSON.parse(e);return!(!t.SessionId||!t.Status)}catch(e){return!1}}}const Pm=vi(e=>new bm(e),[{gateway:"worldpayaccess",id:"credit_card"},{id:"worldpayaccess"}]);class Om{constructor(e){this._paymentIntegrationService=e}execute({payment:e}){return t=this,n=void 0,r=function*(){if(!e)throw new co(["payment"]);yield this._paymentIntegrationService.submitOrder();try{yield this._paymentIntegrationService.submitPayment(this._buildOpenBankingSubmitPayment(e))}catch(e){if(this._isWorldpayAccessRedirectResponse(e)){const t=e.body.additional_action_required.data.redirect_url;return new Promise(()=>window.location.replace(t))}return Promise.reject(e)}},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}initialize(){return Promise.resolve()}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_buildOpenBankingSubmitPayment(e){const{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n}=jd(e.paymentData)?e.paymentData:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1};return Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{open_banking:{},vault_payment_instrument:t||!1,set_as_default_stored_instrument:n||!1}}})}_isWorldpayAccessRedirectResponse(e){var t,n;if("object"!=typeof e||null===e)return!1;const i=e;if(!i.body)return!1;const r=i.body;return"additional_action_required"===r.status&&!!(null===(n=null===(t=r.additional_action_required)||void 0===t?void 0:t.data)||void 0===n?void 0:n.redirect_url)}}const Em=vi(e=>new Om(e),[{id:"open_banking",gateway:"worldpayaccess"}]);class Am{constructor(e){this._requestSender=e}saveExternalId(e,t){return n=this,i=void 0,o=function*(){const n=`/api/storefront/payment/${e}/save-external-id`,i={headers:Object.assign({Accept:mr.JsonV1,"X-API-INTERNAL":hr},yr),body:{externalId:t,provider:e}};yield this._requestSender.post(n,i)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}class Tm{constructor(e,t){this.paymentIntegrationService=e,this.storefrontPaymentRequestSender=t}initialize(){return Promise.resolve()}execute(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rwindow.location.replace(d));throw e}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_prepareForReferredRegistration(e,t){return this.storefrontPaymentRequestSender.saveExternalId(e,t)}}const km=vi(e=>{const{getHost:t}=e.getState(),i=n({host:t()}),r=new Am(i);return new Tm(e,r)},[{id:"zip"},{id:"quadpay"}]);var Dm,Mm;!function(e){e.LoadCountriesRequested="LOAD_COUNTRIES_REQUESTED",e.LoadCountriesSucceeded="LOAD_COUNTRIES_SUCCEEDED",e.LoadCountriesFailed="LOAD_COUNTRIES_FAILED"}(Dm||(Dm={}));class zm{constructor(e){this._countryRequestSender=e}loadCountries(e){return m.create(t=>{t.next(l(Dm.LoadCountriesRequested)),this._countryRequestSender.loadCountries(e).then(e=>{t.next(l(Dm.LoadCountriesSucceeded,e.body.data)),t.complete()}).catch(e=>{t.error(h(Dm.LoadCountriesFailed,e))})})}}class Nm{constructor(e,t){this._requestSender=e,this._config=t}loadCountries({timeout:e}={}){const t=Object.assign({"Accept-Language":this._config.locale},Xe);return this._requestSender.get("/internalapi/v1/store/countries",{headers:t,timeout:e})}}class xm extends it{constructor(e){super(e||"Your checkout could not be processed because some details have changed. Please review your order and try again."),this.name="CartConsistencyError",this.type="cart_consistency"}}class Rm extends it{constructor(e,t){super(t||"At least one item changed stock position. Please review your cart and try again."),this.name="CartStockPositionsChangedError",this.type="cart_stock_positions_changed",this.changedItemIds=e}}class Fm extends it{constructor(e){super(e||"The tax provider is unavailable."),this.name="OrderTaxProviderUnavailableError",this.type="tax_provider_unavailable"}}class Lm extends it{constructor(e){super(e),this.name="MissingShippingMethodError",this.type="missing_shipping_method"}}class Bm extends it{constructor(e){super(e),this.name="InvalidShippingAddressError",this.type="invalid_shipping_address"}}class jm{constructor(e){this._requestSender=e}loadOrder(e,{timeout:t}={}){const n=`/api/storefront/orders/${e}`,i=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.get(n,{params:{include:Ft(["payments","lineItems.physicalItems.socialMedia","lineItems.physicalItems.options","lineItems.physicalItems.categories","lineItems.digitalItems.socialMedia","lineItems.digitalItems.options","lineItems.digitalItems.categories"])},headers:i,timeout:t})}submitOrder(e,{headers:t,timeout:n}={}){return this._requestSender.post("/internalapi/v1/checkout/order",{body:e,headers:ue(Object.assign({"X-Checkout-Variant":t&&t.checkoutVariant},Xe),J),timeout:n}).catch(e=>{var t,n;if("tax_provider_unavailable"===e.body.type)throw new Fm;if("cart_has_changed"===e.body.type)throw new xm;if("cart_stock_positions_changed"===e.body.type){const i=null!==(n=null===(t=e.body.errors)||void 0===t?void 0:t.changedItemIds)&&void 0!==n?n:[];throw new Rm(i)}if("missing_shipping_method"===e.body.type)throw new Lm(e.body.detail);if("invalid_shipping_address"===e.body.type)throw new Bm(e.body.detail);if("empty_cart"===e.body.type)throw new dt;throw e})}finalizeOrder(e,{timeout:t}={}){const n=`/internalapi/v1/checkout/order/${e}`;return this._requestSender.post(n,{timeout:t,headers:Xe})}}class Um extends it{constructor(){super("You haven't complete our spam check. Please try again."),this.name="SpamProtectionNotCompletedError",this.type="spam_protection_not_completed"}}!function(e){e.LoadOrderRequested="LOAD_ORDER_REQUESTED",e.LoadOrderSucceeded="LOAD_ORDER_SUCCEEDED",e.LoadOrderFailed="LOAD_ORDER_FAILED",e.LoadOrderPaymentsRequested="LOAD_ORDER_PAYMENTS_REQUESTED",e.LoadOrderPaymentsSucceeded="LOAD_ORDER_PAYMENTS_SUCCEEDED",e.LoadOrderPaymentsFailed="LOAD_ORDER_PAYMENTS_FAILED",e.SubmitOrderRequested="SUBMIT_ORDER_REQUESTED",e.SubmitOrderSucceeded="SUBMIT_ORDER_SUCCEEDED",e.SubmitOrderFailed="SUBMIT_ORDER_FAILED",e.FinalizeOrderRequested="FINALIZE_ORDER_REQUESTED",e.FinalizeOrderSucceeded="FINALIZE_ORDER_SUCCEEDED",e.FinalizeOrderFailed="FINALIZE_ORDER_FAILED"}(Mm||(Mm={}));var qm;class Vm{constructor(e,t){this._orderRequestSender=e,this._checkoutValidator=t}loadOrder(e,t){return new m(n=>{n.next(l(Mm.LoadOrderRequested)),this._orderRequestSender.loadOrder(e,t).then(e=>{n.next(l(Mm.LoadOrderSucceeded,e.body)),n.complete()}).catch(e=>{n.error(h(Mm.LoadOrderFailed,e))})})}loadOrderPayments(e,t){return new m(n=>{n.next(l(Mm.LoadOrderPaymentsRequested)),this._orderRequestSender.loadOrder(e,t).then(e=>{n.next(l(Mm.LoadOrderPaymentsSucceeded,e.body)),n.complete()}).catch(e=>{n.error(h(Mm.LoadOrderPaymentsFailed,e))})})}loadCurrentOrder(e){return t=>v(()=>{const n=this._getCurrentOrderId(t.getState());if(!n)throw new rt(et.MissingOrderId);return this.loadOrder(n,e)})}submitOrder(e,t){return n=>g(C(l(Mm.SubmitOrderRequested)),v(()=>{const i=n.getState(),r=i.config.getExternalSource(),o=i.config.getVariantIdentificationToken(),a=i.checkout.getCheckout();if(!a)throw new rt(et.MissingCheckout);if(a.shouldExecuteSpamCheck)throw new Um;return S(this._checkoutValidator.validate(a,t).then(()=>this._orderRequestSender.submitOrder(this._mapToOrderRequestBody(null!=e?e:{},a.id,a.customerMessage,r),Object.assign(Object.assign({},t),{headers:{checkoutVariant:o}})))).pipe(M(e=>g(this.loadOrder(e.body.data.order.orderId,t),C(l(Mm.SubmitOrderSucceeded,e.body.data,Object.assign(Object.assign({},e.body.meta),{token:e.headers.token}))))))}).pipe(P(e=>Je(Mm.SubmitOrderFailed,e))))}finalizeOrder(e,t){return g(C(l(Mm.FinalizeOrderRequested)),S(this._orderRequestSender.finalizeOrder(e,t)).pipe(M(n=>g(this.loadOrder(e,t),C(l(Mm.FinalizeOrderSucceeded,n.body.data)))))).pipe(P(e=>Je(Mm.FinalizeOrderFailed,e)))}_getCurrentOrderId(e){const t=e.order.getOrder(),n=e.checkout.getCheckout();return t&&t.orderId||n&&n.orderId}_mapToOrderRequestBody(e,t,n,i){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const n=e.config.getStoreConfig();n&&t.setHost(n.paymentSettings.bigpayBaseUrl)},e=>e.config.getStoreConfig()),t}!function(e){e.LoadPaymentMethodRequested="LOAD_PAYMENT_METHOD_REQUESTED",e.LoadPaymentMethodSucceeded="LOAD_PAYMENT_METHOD_SUCCEEDED",e.LoadPaymentMethodFailed="LOAD_PAYMENT_METHOD_FAILED",e.LoadPaymentMethodsRequested="LOAD_PAYMENT_METHODS_REQUESTED",e.LoadPaymentMethodsSucceeded="LOAD_PAYMENT_METHODS_SUCCEEDED",e.LoadPaymentMethodsFailed="LOAD_PAYMENT_METHODS_FAILED"}(qm||(qm={}));const Hm=e=>!!e;class Wm{constructor(e){this._requestSender=e}loadPaymentMethodsById(e,t){return n=>new m(i=>{var r;const o=null===(r=n.getState().cart.getCart())||void 0===r?void 0:r.id,a=o?Object.assign(Object.assign({},null==t?void 0:t.params),{cartId:o}):Object.assign({},null==t?void 0:t.params);i.next(l(qm.LoadPaymentMethodsRequested)),Promise.all(e.map(e=>{return n=this,i=void 0,o=function*(){try{return(yield this._requestSender.loadPaymentMethod(e,Object.assign(Object.assign({},t),{params:a}))).body}catch(e){return}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).then(e=>{const t=e.filter(Hm);i.next(l(qm.LoadPaymentMethodsSucceeded,t)),i.complete()}).catch(e=>{i.next(l(qm.LoadPaymentMethodsFailed,e)),i.complete()})})}loadPaymentMethods(e){return t=>m.create(n=>{const i=t.getState().cart.getCartOrThrow();n.next(l(qm.LoadPaymentMethodsRequested)),this._requestSender.loadPaymentMethods(Object.assign(Object.assign({},e),{params:Object.assign(Object.assign({},null==e?void 0:e.params),{cartId:i.id})})).then(e=>{const t={deviceSessionId:e.headers["x-device-session-id"],sessionHash:e.headers["x-session-hash"]},i=e.body;n.next(l(qm.LoadPaymentMethodsSucceeded,i,t)),n.complete()}).catch(e=>{n.error(h(qm.LoadPaymentMethodsFailed,e))})})}loadPaymentMethod(e,t){return n=>m.create(i=>{var r;const o=null===(r=n.getState().cart.getCart())||void 0===r?void 0:r.id,a=o?Object.assign(Object.assign({},null==t?void 0:t.params),{cartId:o}):Object.assign({},null==t?void 0:t.params);i.next(l(qm.LoadPaymentMethodRequested,void 0,{methodId:e})),this._requestSender.loadPaymentMethod(e,Object.assign(Object.assign({},t),{params:a})).then(t=>{i.next(l(qm.LoadPaymentMethodSucceeded,t.body,{methodId:e})),i.complete()}).catch(t=>{i.error(h(qm.LoadPaymentMethodFailed,t,{methodId:e}))})})}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([It],Wm.prototype,"loadPaymentMethod",null);class $m{constructor(e){this._requestSender=e}loadPaymentMethods({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/payments",{timeout:e,headers:Object.assign({Accept:ct.JsonV1,"X-API-INTERNAL":At},Xe),params:t})}loadPaymentMethod(e,{timeout:t,params:n}={}){const i=`/api/storefront/payments/${e}`;return this._requestSender.get(i,{timeout:t,headers:Object.assign({Accept:ct.JsonV1,"X-API-INTERNAL":At},Xe),params:n})}}class Ym extends it{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}var Km,Jm;!function(e){e.ExecuteFailed="PAYMENT_STRATEGY_EXECUTE_FAILED",e.ExecuteRequested="PAYMENT_STRATEGY_EXECUTE_REQUESTED",e.ExecuteSucceeded="PAYMENT_STRATEGY_EXECUTE_SUCCEEDED",e.FinalizeFailed="PAYMENT_STRATEGY_FINALIZE_FAILED",e.FinalizeRequested="PAYMENT_STRATEGY_FINALIZE_REQUESTED",e.FinalizeSucceeded="PAYMENT_STRATEGY_FINALIZE_SUCCEEDED",e.InitializeFailed="PAYMENT_STRATEGY_INITIALIZE_FAILED",e.InitializeRequested="PAYMENT_STRATEGY_INITIALIZE_REQUESTED",e.InitializeSucceeded="PAYMENT_STRATEGY_INITIALIZE_SUCCEEDED",e.DeinitializeFailed="PAYMENT_STRATEGY_DEINITIALIZE_FAILED",e.DeinitializeRequested="PAYMENT_STRATEGY_DEINITIALIZE_REQUESTED",e.DeinitializeSucceeded="PAYMENT_STRATEGY_DEINITIALIZE_SUCCEEDED",e.WidgetInteractionStarted="PAYMENT_STRATEGY_WIDGET_INTERACTION_STARTED",e.WidgetInteractionFinished="PAYMENT_STRATEGY_WIDGET_INTERACTION_FINISHED",e.WidgetInteractionFailed="PAYMENT_STRATEGY_WIDGET_INTERACTION_FAILED"}(Km||(Km={})),function(e){e.ADYENV2="adyenv2",e.ADYENV2_GOOGLEPAY="googlepayadyenv2",e.ADYENV3="adyenv3",e.ADYENV3_GOOGLEPAY="googlepayadyenv3",e.AFFIRM="affirm",e.AFTERPAY="afterpay",e.AUTHORIZENET_GOOGLE_PAY="googlepayauthorizenet",e.AMAZONPAY="amazonpay",e.APPLEPAY="applepay",e.BLUESNAPV2="bluesnapv2",e.BOLT="bolt",e.CBA_MPGS="cba_mpgs",e.CHECKOUTCOM="checkoutcom",e.CHECKOUTCOM_APM="checkoutcomapm",e.CHECKOUTCOM_FAWRY="checkoutcomfawry",e.CHECKOUTCOM_SEPA="checkoutcomsepa",e.CHECKOUTCOM_IDEAL="checkoutcomideal",e.CREDIT_CARD="creditcard",e.CHECKOUTCOM_GOOGLE_PAY="googlepaycheckoutcom",e.CLEARPAY="clearpay",e.CONVERGE="converge",e.CYBERSOURCE="cybersource",e.CYBERSOURCEV2="cybersourcev2",e.BNZ="bnz",e.BNZ_GOOGLEPAY="googlepaybnz",e.CYBERSOURCEV2_GOOGLE_PAY="googlepaycybersourcev2",e.HUMM="humm",e.KLARNA="klarna",e.KLARNAV2="klarnav2",e.LEGACY="legacy",e.MOLLIE="mollie",e.MONERIS="moneris",e.NO_PAYMENT_DATA_REQUIRED="nopaymentdatarequired",e.OFFLINE="offline",e.OFFSITE="offsite",e.ORBITAL_GOOGLE_PAY="googlepayorbital",e.PAYPAL_EXPRESS="paypalexpress",e.PAYPAL_EXPRESS_CREDIT="paypalexpresscredit",e.PAYPAL_COMMERCE="paypalcommerce",e.PAYPAL_COMMERCE_CREDIT="paypalcommercecredit",e.PAYPAL_COMMERCE_CREDIT_CARD="paypalcommercecreditcards",e.PAYPAL_COMMERCE_ALTERNATIVE_METHODS="paypalcommercealternativemethods",e.PAYPAL_COMMERCE_VENMO="paypalcommercevenmo",e.PPSDK="PAYMENT_TYPE_SDK",e.QUADPAY="quadpay",e.SAGE_PAY="sagepay",e.SQUARE="squarev2",e.STRIPEV3="stripev3",e.STRIPE_UPE="stripeupe",e.STRIPE_UPE_GOOGLE_PAY="googlepaystripeupe",e.BRAINTREE="braintree",e.BRAINTREE_PAYPAL="braintreepaypal",e.BRAINTREE_VENMO="braintreevenmo",e.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",e.BRAINTREE_VISA_CHECKOUT="braintreevisacheckout",e.BRAINTREE_GOOGLE_PAY="googlepaybraintree",e.WORLDPAYACCESS="worldpayaccess",e.WORLDPAYACCESS_GOOGLE_PAY="googlepayworldpayaccess",e.STRIPE_GOOGLE_PAY="googlepaystripe",e.SEZZLE="sezzle",e.ZIP="zip"}(Jm||(Jm={}));const Zm=Jm;class Qm{widgetInteraction(e,t){const n={methodId:t&&t.methodId};return g(C(l(Km.WidgetInteractionStarted,void 0,n)),v(()=>e().then(()=>l(Km.WidgetInteractionFinished,void 0,n)))).pipe(P(e=>Je(Km.WidgetInteractionFailed,e,n)))}}class Xm{constructor(e,t,n,i,r){this._strategyRegistry=e,this._strategyRegistryV2=t,this._orderActionCreator=n,this._spamProtectionActionCreator=i,this._paymentIntegrationService=r,this._paymentStrategyWidgetActionCreator=new Qm}execute(e,t){const{payment:n={},useStoreCredit:i}=e,r={methodId:n.methodId};return o=>{const{checkout:a}=o.getState(),{shouldExecuteSpamCheck:s}=a.getCheckoutOrThrow();return g(s?this._spamProtectionActionCreator.verifyCheckoutSpamProtection()(o):f(),C(l(Km.ExecuteRequested,void 0,r)),v(()=>{const a=o.getState();let s;if(a.payment.isPaymentDataRequired(i)){const e=a.paymentMethods.getPaymentMethod(n.methodId,n.gatewayId);if(!e)throw new rt(et.MissingPaymentMethod);s=this._getStrategy(e)}else s=this._strategyRegistryV2.get({id:Zm.NO_PAYMENT_DATA_REQUIRED});return s.execute(e,Object.assign(Object.assign({},t),{methodId:n.methodId,gatewayId:n.gatewayId})).then(()=>l(Km.ExecuteSucceeded,void 0,r))})).pipe(P(e=>Je(Km.ExecuteFailed,e,r)))}}finalize(e){const{integrations:t}=null!=e?e:{};return n=>g(C(l(Km.FinalizeRequested)),this._loadOrderPaymentsIfNeeded(n,e),v(()=>{return i=this,r=void 0,a=function*(){const i=n.getState(),{providerId:r="",gatewayId:o=""}=i.payment.getPaymentId()||{},a=i.paymentMethods.getPaymentMethod(r,o);if(!a)throw new Ym;let s;Zt(this._strategyRegistryV2,null!=t?t:[],this._paymentIntegrationService);try{s=this._getStrategy(a)}catch(e){throw new Ym}return yield s.finalize(Object.assign(Object.assign({},e),{methodId:a.id,gatewayId:a.gateway})),l(Km.FinalizeSucceeded,void 0,{methodId:a.id})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a})).pipe(P(e=>{const t=n.getState().payment.getPaymentId();return Je(Km.FinalizeFailed,e,{methodId:t&&t.providerId})}))}initialize(e){const{methodId:t,gatewayId:n,integrations:i}=e;return r=>v(()=>{const o=r.getState(),a=o.paymentMethods.getPaymentMethod(t,n);if(!a)throw new rt(et.MissingPaymentMethod);if(t&&o.paymentStrategies.isInitialized({methodId:t,gatewayId:n}))return f();Zt(this._strategyRegistryV2,null!=i?i:[],this._paymentIntegrationService);const s=this._getStrategy(a).initialize(Object.assign(Object.assign({},e),{methodId:t,gatewayId:n}));return g(C(l(Km.InitializeRequested,void 0,{methodId:t,gatewayId:n})),s.then(()=>l(Km.InitializeSucceeded,void 0,{methodId:t,gatewayId:n})))}).pipe(P(e=>Je(Km.InitializeFailed,e,{methodId:t,gatewayId:n})))}deinitialize(e){const{methodId:t,gatewayId:n}=e;return i=>v(()=>{const r=i.getState(),o=r.paymentMethods.getPaymentMethod(t,n);if(!o)throw new rt(et.MissingPaymentMethod);if(t&&!r.paymentStrategies.isInitialized({methodId:t,gatewayId:n}))return f();const a=this._getStrategy(o).deinitialize(Object.assign(Object.assign({},e),{methodId:t,gatewayId:n}));return g(C(l(Km.DeinitializeRequested,void 0,{methodId:t,gatewayId:n})),a.then(()=>l(Km.DeinitializeSucceeded,void 0,{methodId:t,gatewayId:n})))}).pipe(P(e=>Je(Km.DeinitializeFailed,e,{methodId:t,gatewayId:n})))}widgetInteraction(e,t){return this._paymentStrategyWidgetActionCreator.widgetInteraction(e,t)}_getStrategy(e){let t;try{t=this._strategyRegistry.getByMethod(e)}catch(n){try{t=this._strategyRegistryV2.get({id:e.id,gateway:e.gateway,type:e.type})}catch(t){throw wt().error(`[PaymentStrategyActionCreator] Unable to resolve V2 strategy for id: ${e.id}, gateway: ${e.gateway}, type: ${e.type}`),t}}return t}_loadOrderPaymentsIfNeeded(e,t){const n=e.getState().checkout.getCheckout();return n&&n.orderId?this._orderActionCreator.loadOrderPayments(n.orderId,t):f()}}class ey{isEqual(e,t){return Y(this._normalize(e),this._normalize(t))}_normalize(e){return{cartAmount:e.cartAmount,currency:e.currency,id:e.id,lineItems:{digitalItems:e.lineItems.digitalItems.slice().sort((e,t)=>`${e.productId}${e.variantId}`.localeCompare(`${t.productId}${t.variantId}`)).map(e=>({extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId})),giftCertificates:e.lineItems.giftCertificates.slice().sort((e,t)=>`${e.id}`.localeCompare(`${t.id}`)).map(e=>({amount:e.amount,recipient:e.recipient})),physicalItems:e.lineItems.physicalItems.slice().sort((e,t)=>`${e.productId}${e.variantId}`.localeCompare(`${t.productId}${t.variantId}`)).map(e=>({extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId,giftWrapping:e.giftWrapping}))}}}}class ty extends it{constructor(e,t){super("An update to your shopping cart has been detected and your available shipping costs have been updated."),this.name="CartChangedError",this.type="cart_changed",this.data={previous:e,updated:t}}}class ny{constructor(e){this._checkoutRequestSender=e}validate(e,t){if(!e)throw new rt(et.MissingCheckout);return this._checkoutRequestSender.loadCheckout(e.id,t).then(t=>{const n=new ey;if(!(e.outstandingBalance===t.body.outstandingBalance&&this._compareCoupons(e.coupons,t.body.coupons)&&this._compareGiftCertificates(e.giftCertificates,t.body.giftCertificates)&&n.isEqual(e.cart,t.body.cart)))throw new ty(this._getComparableCheckout(e),this._getComparableCheckout(t.body))})}_compareCoupons(e,t){return Y(oe(e,"code"),oe(t,"code"))}_compareGiftCertificates(e,t){return Y(oe(e,"code"),oe(t,"code"))}_getComparableCheckout(e){const{cart:t,coupons:n,giftCertificates:i,outstandingBalance:r}=e;return{cart:{cartAmount:t.cartAmount,currency:t.currency,lineItems:t.lineItems},coupons:n,giftCertificates:i,outstandingBalance:r}}}class iy{constructor(e){this._namespace=e}getItem(e){const t=Te.getItem(this.withNamespace(e));if(null===t)return null;try{return JSON.parse(t)}catch(t){return this.removeItem(this.withNamespace(e)),null}}getItemOnce(e){const t=this.getItem(e);return this.removeItem(e),t}setItem(e,t){return Te.setItem(this.withNamespace(e),JSON.stringify(t))}removeItem(e){return Te.removeItem(this.withNamespace(e))}withNamespace(e){return`${this._namespace}.${e}`}}class ry extends it{constructor(){super("Please complete our human verification challenge and try again."),this.name="CardingProtectionChallengeNotCompletedError",this.type="carding_protection_challenge_not_completed"}}class oy extends it{constructor(){super("We were not able to verify that you are not a robot. Please try again."),this.name="CardingProtectionFailedError",this.type="carding_protection_failed"}}var ay,sy,dy=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class cy{constructor(e){this._googleRecaptcha=e}handle(e,t){return dy(this,void 0,void 0,function*(){return"string"==typeof e?this.handleWithRecaptchaSitekey(e,t):this.handleWithPaymentHumanVerificationRequestError(e)})}handleWithPaymentHumanVerificationRequestError(e){return dy(this,void 0,void 0,function*(){if(!this._isPaymentHumanVerificationRequest(e))throw e;return yield this._initialize(e.body.additional_action_required.data.key),this._performRecaptcha()})}handleWithRecaptchaSitekey(e,t){return dy(this,void 0,void 0,function*(){if("recaptcha_v2"!==e)throw Error("Human verification method is not supported.");if(!t)throw Error("Recaptcha site key is missing.");return yield this._initialize(t),this._performRecaptcha()})}_performRecaptcha(){return this._googleRecaptcha.execute().pipe(z(1)).pipe(M(({error:e,token:t})=>dy(this,void 0,void 0,function*(){if(e instanceof sn)throw new ry;if(e||!t)throw new oy;return{type:"recaptcha_v2_verification",data:{human_verification_token:t}}}))).toPromise()}_initialize(e){const t="cardingProtectionContainer";let n=document.getElementById(t);return n&&n.parentNode&&n.parentNode.removeChild(n),n=document.createElement("div"),n.setAttribute("id",t),document.body.appendChild(n),this._googleRecaptcha.load(t,e)}_isPaymentHumanVerificationRequest(e){const{additional_action_required:t,status:n}=e.body||{};return"additional_action_required"===n&&t&&"recaptcha_v2_verification"===t.type}}function ly(e,t){const{body:n}=e,{errors:i=[]}=n;return new Ot(e,{message:uy(i)||t,errors:i})}function uy(e){if(Array.isArray(e))return e.reduce((e,t)=>t&&t.message?[...e,t.message]:e,[]).join(" ")}class hy extends it{constructor(e){super(e||"Unable to proceed due to invalid configuration provided for the hosted payment form."),this.name="InvalidHostedFormConfigError",this.type="invalid_hosted_form_config"}}class py extends it{constructor(e){super(e||"Unable to proceed due to an unknown error with the hosted payment form."),this.name="InvalidHostedFormError",this.type="invalid_hosted_form"}}class my extends it{constructor(e){super(["Unable to proceed due to invalid user input values",...U(Ce(e),e=>oe(e,({message:e})=>e))].join(". ")),this.errors=e,this.name="InvalidHostedFormValueError",this.type="invalid_hosted_form_value"}}!function(e){e.AttachRequested="HOSTED_FIELD:ATTACH_REQUESTED",e.SubmitRequested="HOSTED_FIELD:SUBMITTED_REQUESTED",e.ValidateRequested="HOSTED_FIELD:VALIDATE_REQUESTED",e.StoredCardRequested="HOSTED_FIELD:STORED_CARD_REQUESTED"}(ay||(ay={})),function(e){e.AttachSucceeded="HOSTED_INPUT:ATTACH_SUCCEEDED",e.AttachFailed="HOSTED_INPUT:ATTACH_FAILED",e.BinChanged="HOSTED_INPUT:BIN_CHANGED",e.Blurred="HOSTED_INPUT:BLURRED",e.Changed="HOSTED_INPUT:CHANGED",e.CardTypeChanged="HOSTED_INPUT:CARD_TYPE_CHANGED",e.Entered="HOSTED_INPUT:ENTERED",e.Focused="HOSTED_INPUT:FOCUSED",e.SubmitSucceeded="HOSTED_INPUT:SUBMIT_SUCCEEDED",e.SubmitFailed="HOSTED_INPUT:SUBMIT_FAILED",e.Validated="HOSTED_INPUT:VALIDATED",e.StoredCardSucceeded="HOSTED_INPUT:STORED_CARD_SUCCEEDED",e.StoredCardFailed="HOSTED_INPUT:STORED_CARD_FAILED"}(sy||(sy={}));var yy=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class gy{constructor(e,t,n,i,r,o,a,s,d,c){this._type=e,this._containerId=t,this._placeholder=n,this._accessibilityLabel=i,this._styles=r,this._eventPoster=o,this._eventListener=a,this._detachmentObserver=s,this._checkoutId=d,this._cardInstrument=c,this._iframe=document.createElement("iframe");const l=this._checkoutId?`/checkout/payment/hosted-field?version=1.909.5&checkoutId=${this._checkoutId}`:"/checkout/payment/hosted-field?version=1.909.5";this._iframe.src=l,this._iframe.style.border="none",this._iframe.style.height="100%",this._iframe.style.overflow="hidden",this._iframe.style.width="100%"}getType(){return this._type}attach(){return yy(this,void 0,void 0,function*(){const e=document.getElementById(this._containerId);if(!e)throw new hy("Unable to proceed because the provided container ID is not valid.");e.appendChild(this._iframe),this._eventListener.listen();const t=_(this._iframe,"load").pipe(M(({target:e})=>yy(this,void 0,void 0,function*(){const t=e&&e.contentWindow;if(!t)throw new Error("The content window of the iframe cannot be accessed.");this._eventPoster.setTarget(t),yield this._eventPoster.post({type:ay.AttachRequested,payload:{accessibilityLabel:this._accessibilityLabel,cardInstrument:this._cardInstrument,fontUrls:this._getFontUrls(),placeholder:this._placeholder,styles:this._styles,origin:document.location.origin,type:this._type}},{successType:sy.AttachSucceeded,errorType:sy.AttachFailed})})),z(1)).toPromise();yield this._detachmentObserver.ensurePresence([this._iframe],t)})}detach(){this._iframe.parentElement&&(this._iframe.parentElement.removeChild(this._iframe),this._eventListener.stopListen())}submitForm(e,t){return yy(this,void 0,void 0,function*(){try{const n=this._eventPoster.post({type:ay.SubmitRequested,payload:{fields:e,data:t}},{successType:sy.SubmitSucceeded,errorType:sy.SubmitFailed});return yield this._detachmentObserver.ensurePresence([this._iframe],n)}catch(e){if(this._isSubmitErrorEvent(e)){if("hosted_form_error"===e.payload.error.code)throw new py(e.payload.error.message);if(e.payload.response)throw ly(e.payload.response);throw new Error(e.payload.error.message)}throw e}})}submitStoredCardForm(e,t){return yy(this,void 0,void 0,function*(){const n=this._eventPoster.post({type:ay.StoredCardRequested,payload:{fields:e,data:t}},{successType:sy.StoredCardSucceeded,errorType:sy.StoredCardFailed});return this._detachmentObserver.ensurePresence([this._iframe],n)})}validateForm(){return yy(this,void 0,void 0,function*(){const e=this._eventPoster.post({type:ay.ValidateRequested},{successType:sy.Validated}),{payload:t}=yield this._detachmentObserver.ensurePresence([this._iframe],e);if(!t.isValid)throw new my(t.errors)})}_getFontUrls(){const e="fonts.googleapis.com",t=document.querySelectorAll(`link[href*='${e}'][rel='stylesheet']`);return Array.prototype.slice.call(t).filter(t=>In(t.href).hostname===e).filter(e=>Ce(this._styles).map(e=>e&&e.fontFamily).filter(e=>"string"==typeof e).some(t=>t.split(/,\s/).some(t=>-1!==e.href.indexOf(t.replace(" ","+"))))).map(e=>e.href)}_isSubmitErrorEvent(e){return e.type===sy.SubmitFailed}}var vy,fy=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Sy{constructor(e,t,n,i,r){this._fields=e,this._eventListener=t,this._payloadTransformer=n,this._eventCallbacks=i,this._paymentHumanVerificationHandler=r,this._handleEnter=({payload:e})=>fy(this,void 0,void 0,function*(){try{yield this.validate()}catch(e){if(e instanceof Error&&"InvalidHostedFormValueError"!==e.name)throw e}const{onEnter:t=ce}=this._eventCallbacks;t(e)});const{onBlur:o=ce,onCardTypeChange:a=ce,onFocus:s=ce,onValidate:d=ce}=this._eventCallbacks;this._eventListener.addListener(sy.Blurred,({payload:e})=>o(e)),this._eventListener.addListener(sy.CardTypeChanged,({payload:e})=>a(e)),this._eventListener.addListener(sy.Focused,({payload:e})=>s(e)),this._eventListener.addListener(sy.Validated,({payload:e})=>d(e)),this._eventListener.addListener(sy.Entered,this._handleEnter),this._eventListener.addListener(sy.CardTypeChanged,({payload:e})=>this._cardType=e.cardType),this._eventListener.addListener(sy.BinChanged,({payload:e})=>this._bin=e.bin)}getBin(){return this._bin}getCardType(){return this._cardType}attach(){return fy(this,void 0,void 0,function*(){this._eventListener.listen();const e=this._getFirstField(),t=be(this._fields,e);yield e.attach(),yield Promise.all(t.map(e=>e.attach()))})}detach(){this._eventListener.stopListen(),this._fields.forEach(e=>{e.detach()})}submit(e,t){return fy(this,void 0,void 0,function*(){try{return yield this._getFirstField().submitForm(this._fields.map(e=>e.getType()),this._payloadTransformer.transform(e,t))}catch(t){const n=yield this._paymentHumanVerificationHandler.handle(t);return yield this._getFirstField().submitForm(this._fields.map(e=>e.getType()),this._payloadTransformer.transform(e,n))}})}submitStoredCard(e){return fy(this,void 0,void 0,function*(){return this._getFirstField().submitStoredCardForm(e.fields,e.data)})}validate(){return fy(this,void 0,void 0,function*(){return this._getFirstField().validateForm()})}_getFirstField(){const e=this._fields[0];if(!e)throw new hy("Unable to proceed because the payment form has no field defined.");return e}}function _y(e){return Boolean(e.instrumentId)}class wy{constructor(e){this._store=e}transform(e,t){const n=this._store.getState(),i=n.checkout.getCheckout(),r=n.config.getConfig(),o=n.instruments.getInstrumentsMeta(),a=n.order.getOrder(),s=n.order.getOrderMeta(),d=le(e.paymentData,"ccExpiry","ccName","ccNumber","ccCvv");let c=n.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId);"worldpayaccess"===(null==c?void 0:c.gateway)&&"credit_card"===(null==c?void 0:c.id)&&(c=Object.assign(Object.assign({},c),{id:"worldpayaccess",method:"credit-card"}));const l=n.paymentMethods.getPaymentMethodsMeta(),u=o&&d&&_y(d)?`${n.payment.getPaymentToken()}, ${o.vaultAccessToken}`:n.payment.getPaymentToken();if(!u)throw new rt(et.MissingPaymentToken);return{additionalAction:t,authToken:u,checkout:i,config:r,order:a,orderMeta:s,payment:d,paymentMethod:c,paymentMethodMeta:l}}}class Iy{constructor(e){this._store=e}create(e,t,n){const i=Object.keys(t.fields).reduce((i,r)=>{const o=t.fields[r];return o?[...i,new gy(r,o.containerId,o.placeholder||"",o.accessibilityLabel||"",t.styles||{},new Pn(e),new Yn(e),new kn(new mn),n,"instrumentId"in o?this._getCardInstrument(o.instrumentId):void 0)]:i},[]);return new Sy(i,new Yn(e),new wy(this._store),pe(t,"onBlur","onEnter","onFocus","onCardTypeChange","onValidate"),new cy(Sn(o())))}_getCardInstrument(e){const{instruments:{getCardInstrument:t}}=this._store.getState(),n=t(e);if(!n)throw new rt(et.MissingPaymentInstrument);return n}}!function(e){e.SubmitPaymentRequested="SUBMIT_PAYMENT_REQUESTED",e.SubmitPaymentSucceeded="SUBMIT_PAYMENT_SUCCEEDED",e.SubmitPaymentFailed="SUBMIT_PAYMENT_FAILED",e.InitializeOffsitePaymentRequested="INITIALIZE_OFFSITE_PAYMENT_REQUESTED",e.InitializeOffsitePaymentSucceeded="INITIALIZE_OFFSITE_PAYMENT_SUCCEEDED",e.InitializeOffsitePaymentFailed="INITIALIZE_OFFSITE_PAYMENT_FAILED"}(vy||(vy={}));class Cy{constructor(e,t,n,i){this._paymentRequestSender=e,this._orderActionCreator=t,this._paymentRequestTransformer=n,this._paymentHumanVerificationHandler=i,this.initializeOffsitePayment=({methodId:e,gatewayId:t,instrumentId:n,target:i,promise:r,shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a})=>s=>{let d;n?d={formattedPayload:{bigpay_token:n}}:o&&(d={formattedPayload:{vault_payment_instrument:o,set_as_default_stored_instrument:a||null}});const c=this._paymentRequestTransformer.transform({gatewayId:t,methodId:e,paymentData:d},s.getState());return g(C(l(vy.InitializeOffsitePaymentRequested)),Promise.race([this._paymentRequestSender.initializeOffsitePayment(c,i),r].filter(Boolean)).then(()=>l(vy.InitializeOffsitePaymentSucceeded))).pipe(P(e=>Je(vy.InitializeOffsitePaymentFailed,e)))}}submitPayment(e){return t=>g(C(l(vy.SubmitPaymentRequested)),v(()=>{return n=this,i=void 0,o=function*(){try{return yield this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(e,t.getState()))}catch(n){const i=yield this._paymentHumanVerificationHandler.handle(n);return yield this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(Object.assign(Object.assign({},e),{additionalAction:i}),t.getState()))}},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}).pipe(M(({body:e})=>g(this._orderActionCreator.loadCurrentOrder()(t),C(l(vy.SubmitPaymentSucceeded,e)))))).pipe(P(e=>Je(vy.SubmitPaymentFailed,e)))}}class by{constructor(e){this._client=e}submitPayment(e){return new Promise((t,n)=>{this._client.submitPayment(e,(e,i)=>{e?n(this._transformResponse(e)):t(this._transformResponse(i))})})}initializeOffsitePayment(e,t){return new Promise(()=>{this._client.initializeOffsitePayment(e,null,t)})}_transformResponse(e){return{headers:e.headers,body:e.data,status:e.status,statusText:e.statusText}}}function Py(e,t){let n;return function(e){return void 0!==e.id}(e)?n=e.id:t&&t.length&&(n=t[0].id),{id:n,firstName:e.firstName,lastName:e.lastName,company:e.company,addressLine1:e.address1,addressLine2:e.address2,city:e.city,province:e.stateOrProvince,provinceCode:e.stateOrProvinceCode,postCode:e.postalCode,country:e.country,countryCode:e.countryCode,phone:e.phone,customFields:e.customFields}}const Oy=["per_item_discount","percentage_discount","per_total_discount","shipping_discount","free_shipping"];function Ey(e){return{code:e.code,discount:e.displayName,discountType:Oy.indexOf(e.couponType)}}function Ay(e){return{code:e.code,discountedAmount:e.used,remainingBalance:e.remaining,giftCertificate:{balance:e.balance,code:e.code,purchaseDate:e.purchaseDate}}}function Ty(e){const t=[];return(e||[]).forEach(e=>{(e.banners||[]).forEach(e=>{t.push({placeholders:[],discountType:null,message:"",messageHtml:e.text})})}),t}function ky(e,t,n="id"){return Object.keys(e).reduce((i,r)=>[...i,...e[r].map(e=>"giftCertificates"===r?function(e,t){const n=new fd(t);return{id:e.id,imageUrl:"",name:e.name,amount:e.amount,amountAfterDiscount:e.amount,discount:0,integerAmount:n.toInteger(e.amount),integerAmountAfterDiscount:n.toInteger(e.amount),integerUnitPrice:n.toInteger(e.amount),integerUnitPriceAfterDiscount:n.toInteger(e.amount),integerDiscount:0,quantity:1,sender:e.sender,recipient:e.recipient,type:"ItemGiftCertificateEntity",attributes:[],variantId:null}}(e,t):function(e,t,n,i="id"){const r=new fd(n);return{id:e[i],imageUrl:e.imageUrl,amount:e.extendedListPrice,amountAfterDiscount:e.extendedSalePrice,discount:e.discountAmount,integerAmount:r.toInteger(e.extendedListPrice),integerAmountAfterDiscount:r.toInteger(e.extendedSalePrice),integerDiscount:r.toInteger(e.discountAmount),integerUnitPrice:r.toInteger(e.listPrice),integerUnitPriceAfterDiscount:r.toInteger(e.salePrice),downloadsPageUrl:e.downloadPageUrl,name:e.name,quantity:e.quantity,brand:e.brand,sku:e.sku,categoryNames:e.categoryNames,variantId:e.variantId,productId:e.productId,attributes:(e.options||[]).map(e=>({name:e.name,value:e.value})),addedByPromotion:e.addedByPromotion,type:t}}(e,function(e){switch(e){case"physicalItems":return"ItemPhysicalEntity";case"digitalItems":return"ItemDigitalEntity";case"giftCertificates":return"ItemGiftCertificateEntity";default:return""}}(r),t,n))],[])}function Dy(e){const t=e.cart.currency.decimalPlaces,n=new fd(t);return{id:e.cart.id,items:ky(e.cart.lineItems,t),currency:e.cart.currency.code,coupon:{discountedAmount:ye(e.cart.coupons,(e,t)=>e+t.discountedAmount,0),coupons:e.cart.coupons.map(Ey)},discount:{amount:e.cart.discountAmount,integerAmount:n.toInteger(e.cart.discountAmount)},discountNotifications:Ty(e.promotions),giftCertificate:{totalDiscountedAmount:ye(e.giftCertificates,(e,t)=>e+t.used,0),appliedGiftCertificates:ne(e.giftCertificates.map(Ay),"code")},shipping:{amount:e.shippingCostTotal,integerAmount:n.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:n.toInteger(e.shippingCostBeforeDiscount),required:ve(e.cart.lineItems.physicalItems,e=>e.isShippingRequired)},subtotal:{amount:e.subtotal,integerAmount:n.toInteger(e.subtotal)},storeCredit:{amount:e.customer?e.customer.storeCredit:0},taxSubtotal:{amount:e.taxTotal,integerAmount:n.toInteger(e.taxTotal)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:n.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:n.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.grandTotal,integerAmount:n.toInteger(e.grandTotal)}}}var My;!function(e){e.APPLEPAY="applepay",e.AMAZON_PAY_V2="amazonpay",e.BRAINTREE_PAYPAL="braintreepaypal",e.BRAINTREE_VENMO="braintreevenmo",e.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",e.GOOGLEPAY_ADYENV2="googlepayadyenv2",e.GOOGLEPAY_ADYENV3="googlepayadyenv3",e.GOOGLEPAY_AUTHORIZENET="googlepayauthorizenet",e.GOOGLEPAY_BNZ="googlepaybnz",e.GOOGLEPAY_BRAINTREE="googlepaybraintree",e.GOOGLEPAY_CHECKOUTCOM="googlepaycheckoutcom",e.GOOGLEPAY_CYBERSOURCEV2="googlepaycybersourcev2",e.GOOGLEPAY_ORBITAL="googlepayorbital",e.GOOGLEPAY_STRIPE="googlepaystripe",e.GOOGLEPAY_STRIPEUPE="googlepaystripeupe",e.GOOGLEPAY_WORLDPAYACCESS="googlepayworldpayaccess",e.PAYPALEXPRESS="paypalexpress"}(My||(My={}));const zy=My;function Ny(e,t){const n=e.firstName||t.firstName||"",i=e.lastName||t.lastName||"";return{addresses:(e.addresses||[]).map(e=>Py(e)),customerId:e.id,isGuest:e.isGuest,storeCredit:e.storeCredit,email:e.email||t.email||"",firstName:n,lastName:i,name:e.fullName||[n,i].join(" "),customerGroupName:e.customerGroup&&e.customerGroup.name}}class xy{format(e){const[t="",n=""]=e.split(new RegExp("\\s*/\\s*")),i=t.slice(0,2),r=4===n.length?n.slice(-2):n?n.slice(0,2):t.slice(2);return e.length<2?t:e.length>3&&!r?i:`${i} / ${r}`}toObject(e){const[t="",n=""]=e.split(new RegExp("\\s*/\\s*"));return/^\d+$/.test(t)&&/^\d+$/.test(n)?{month:1===t.length?`0${t}`:t.slice(0,2),year:2===n.length?`20${n}`:n.slice(0,4)}:{month:"",year:""}}}class Ry{format(e){const{card:t}=Me(e);if(!t)return e;const n=ae(De(e).map(e=>ae(e.lengths))),i=this.unformat(e).slice(0,n);return t.gaps.filter(e=>i.length>e).reduce((e,t,n)=>[e.slice(0,t+n),e.slice(t+n)].join(" "),i)}unformat(e){const{card:t}=Me(e);return t?e.replace(new RegExp(" ","g"),""):e}}function Fy(e,t={}){const n=e.currency.decimalPlaces,i=new fd(n);return{id:e.orderId,items:ky(e.lineItems,e.currency.decimalPlaces,"productId"),orderId:e.orderId,currency:e.currency.code,customerCanBeCreated:e.customerCanBeCreated,payment:jy(e.payments,t.payment),subtotal:{amount:e.baseAmount,integerAmount:i.toInteger(e.baseAmount)},coupon:{discountedAmount:ye(e.coupons,(e,t)=>e+t.discountedAmount,0),coupons:e.coupons.map(Ey)},discount:{amount:e.discountAmount,integerAmount:i.toInteger(e.discountAmount)},token:t.orderToken,callbackUrl:t.callbackUrl,discountNotifications:[],giftCertificate:By(e.payments),socialData:qy(e),status:e.status,hasDigitalItems:e.hasDigitalItems,isDownloadable:e.isDownloadable,isComplete:e.isComplete,shipping:{amount:e.shippingCostTotal,integerAmount:i.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:i.toInteger(e.shippingCostBeforeDiscount)},storeCredit:{amount:Ly(e.payments)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:i.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:i.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.orderAmount,integerAmount:e.orderAmountAsInteger}}}function Ly(e){const t=B(e,{providerId:"storecredit"});return t?t.amount:0}function By(e){const t=L(e,{providerId:"giftcertificate"});return{totalDiscountedAmount:ye(t,(e,t)=>t.amount+e,0),appliedGiftCertificates:ne(t.map(e=>({code:e.detail.code,discountedAmount:e.amount,remainingBalance:e.detail.remaining,giftCertificate:{balance:e.amount+e.detail.remaining,code:e.detail.code,purchaseDate:""}})),"code")}}function jy(e,t={}){const n=B(e,Uy);return n?{id:n.providerId,status:(i=n.detail.step,`PAYMENT_STATUS_${i}`),helpText:n.detail.instructions,returnUrl:t.returnUrl}:{};var i}function Uy(e){return"giftcertificate"!==e.providerId&&"storecredit"!==e.providerId}function qy(e){const t={};return[...e.lineItems.physicalItems,...e.lineItems.digitalItems].forEach(e=>{var n;t[e.id]=(n=e,["fb","tw","gp"].reduce((e,t)=>{const i=n.socialMedia&&B(n.socialMedia,e=>e.code===t);return i?(e[t]={name:n.name,description:n.name,image:n.imageUrl,url:i.link,shareText:i.text,sharingLink:i.link,channelName:i.channel,channelCode:i.code},e):e},{}))}),t}function Vy(e,t){return{description:e.description,module:e.type,price:e.cost,id:e.id,selected:t,isRecommended:e.isRecommended,imageUrl:e.imageUrl,transitTime:e.transitTime}}class Gy{constructor(){this._cardExpiryFormatter=new xy,this._cardNumberFormatter=new Ry}transform(e,t){const n=t.billingAddress.getBillingAddress(),i=t.checkout.getCheckout(),r=t.customer.getCustomer(),o=t.order.getOrder(),a=t.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId),s=this._mapShippingAddress(t,a),d=t.consignments.getConsignments(),c=t.consignments.getShippingOption(),l=t.config.getStoreConfig(),u=t.config.getContextConfig(),h=t.instruments.getInstrumentsMeta(),p=t.paymentMethods.getPaymentMethodsMeta(),m=t.order.getOrderMeta(),y=r&&n&&Ny(r,n),g=h&&e.paymentData&&(_y(e.paymentData)||function(e){const t=e.formattedPayload;return!!t&&("string"==typeof t.bigpay_token||Boolean(t.bigpay_token&&t.bigpay_token.token))}(e.paymentData))?`${t.payment.getPaymentToken()}, ${h.vaultAccessToken}`:t.payment.getPaymentToken();if(!g)throw new rt(et.MissingPaymentToken);return{additionalAction:e.additionalAction,authToken:g,customer:y,billingAddress:n&&Py(n),shippingAddress:s&&Py(s,d),shippingOption:c&&Vy(c,!0),cart:i&&Dy(i),order:o&&Fy(o,m),orderMeta:m,payment:e.paymentData,paymentMethod:a&&this._transformPaymentMethod(a),quoteMeta:{request:Object.assign(Object.assign({},p),{geoCountryCode:u&&u.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:pe(l&&l.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}}transformWithHostedFormData(e,t,n){const{additionalAction:i,authToken:r,checkout:o,config:a,order:s,orderMeta:d,payment:c={},paymentMethod:l,paymentMethodMeta:u}=t,h=o&&o.consignments[0],p=h&&h.shippingAddress,m=h&&h.selectedShippingOption;return{additionalAction:i,authToken:r,paymentMethod:l&&this._transformPaymentMethod(l),customer:s&&s.billingAddress&&o&&Ny(o.customer,s.billingAddress),billingAddress:s&&s.billingAddress&&Py(s.billingAddress),shippingAddress:p&&o&&Py(p,o.consignments),shippingOption:m&&Vy(m,!0),cart:o&&Dy(o),order:s&&Fy(s,d),orderMeta:d,payment:this._transformHostedInputValues(e,c,n),quoteMeta:{request:Object.assign(Object.assign({},u),{geoCountryCode:a&&a.context.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:a&&pe(a.storeConfig.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}}_transformPaymentMethod(e){if("multi-option"===e.method&&!e.gateway)return Object.assign(Object.assign({},e),{gateway:e.id});if(e.initializationData&&e.initializationData.gateway)return Object.assign(Object.assign({},e),{id:e.initializationData.gateway});if("worldpayaccess"===e.gateway){if("credit_card"===e.id)return Object.assign(Object.assign({},e),{id:"worldpayaccess",method:"credit-card"});if("open_banking"===e.id)return Object.assign(Object.assign({},e),{id:"worldpayaccess",method:"open_banking"})}return e.id===zy.BRAINTREE_VENMO?Object.assign(Object.assign({},e),{id:zy.BRAINTREE_PAYPAL}):e}_transformHostedInputValues(e,t,n){return"instrumentId"in t?Object.assign(Object.assign({},t),{ccCvv:e.cardCodeVerification,ccNumber:e.cardNumberVerification&&this._cardNumberFormatter.unformat(e.cardNumberVerification),hostedFormNonce:n}):Object.assign(Object.assign({},t),{ccCvv:e.cardCode,ccExpiry:this._cardExpiryFormatter.toObject(e.cardExpiry||""),ccName:e.cardName||"",ccNumber:this._cardNumberFormatter.unformat(e.cardNumber||""),hostedFormNonce:n})}_mapShippingAddress(e,t){var n,i,r,o;if(t){const a=null===(i=null===(n=t.initializationData)||void 0===n?void 0:n.bopis)||void 0===i?void 0:i.enabled,s=null===(o=null===(r=t.initializationData)||void 0===r?void 0:r.bopis)||void 0===o?void 0:o.requiredAddress,d=e.consignments.getConsignments(),c=null==d?void 0:d.every(e=>e.selectedPickupOption);if(a&&c&&"none"===s)return}return e.shippingAddress.getShippingAddress()}}const Hy=e=>{const{type:t,initializationStrategy:n}=e;return t===Zm.PPSDK&&"string"==typeof(null==n?void 0:n.type)};class Wy extends Vt{getByMethod(e){if(!e)return this.get();const t=this._getToken(e),n=[e.gateway,e.id].filter(e=>null!=e).join("-");return this.get(t,n)}_getToken(e){if(Hy(e))return Zm.PPSDK;if("klarna"===e.gateway)return Zm.KLARNAV2;const t=e.gateway||e.id;if(this._hasFactoryForMethod(t))return t;if("PAYMENT_TYPE_OFFLINE"===e.type)return Zm.OFFLINE;throw new qt(`'${t}' is not registered.`)}_hasFactoryForMethod(e){return this._hasFactory(e)}}const $y="FINALIZE";class Yy extends qt{constructor(e){let t="Unable to submit payment for the order because the payload is invalid.";e&&(t=`${t} Make sure the following fields are provided correctly: ${e.join(", ")}.`),super(t),this.name="PaymentArgumentInvalidError"}}var Ky=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r(this._shouldRenderHostedForm=!0,this._hostedForm=r,this._store.getState()))}deinitialize(e){return this._hostedForm&&this._hostedForm.detach(),Promise.resolve(this._store.getState())}_executeWithoutHostedForm(e,t){const{payment:n}=e,i=Ky(e,["payment"]),r=n&&n.paymentData;if(!n||!r)throw new Yy(["payment.paymentData"]);return this._store.dispatch(this._orderActionCreator.submitOrder(i,t)).then(()=>this._store.dispatch(this._paymentActionCreator.submitPayment(Object.assign(Object.assign({},n),{paymentData:r}))))}_executeWithHostedForm(e,t){const{payment:n}=e,i=Ky(e,["payment"]),r=this._hostedForm;if(!r)throw new yn(cn.PaymentNotInitialized);if(!n||!n.methodId)throw new Yy(["payment.methodId"]);return r.validate().then(()=>this._store.dispatch(this._orderActionCreator.submitOrder(i,t))).then(()=>r.submit(n)).then(()=>this._store.dispatch(this._orderActionCreator.loadCurrentOrder()))}_isHostedPaymentFormEnabled(e,t){if(!e)return!1;const{paymentMethods:{getPaymentMethodOrThrow:n}}=this._store.getState();return!0===n(e,t).config.isHostedFormEnabled}_isHostedFieldAvailable(e){return!Ce(e&&e.creditCard&&e.creditCard.form.fields).every(J)}}class Zy extends Jy{constructor(e,t,n,i,r){super(e,t,n,i),this._formPoster=r}execute(e,t){return super.execute(e,t).catch(e=>e instanceof Ot&&ve(e.body.errors,{code:"three_d_secure_required"})?new Promise(()=>{this._formPoster.postForm(e.body.three_ds_result.acs_url,{PaReq:e.body.three_ds_result.payer_auth_request,TermUrl:e.body.three_ds_result.callback_url,MD:e.body.three_ds_result.merchant_data})}):Promise.reject(e))}finalize(e){const t=this._store.getState(),n=t.order.getOrder();return n&&t.payment.getPaymentStatus()===$y?this._store.dispatch(this._orderActionCreator.finalizeOrder(n.orderId,e)):Promise.reject(new Ym)}}class Qy extends it{constructor(e){super(e||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}const Xy="redirecting";class eg{constructor(){this._isRedirecting=this.currentUrlHasRedirectingParam()}isRedirecting(){return this._isRedirecting}setRedirecting(e){e?this.setRedirectingParamOnUrl():this.removeRedirectingParamFromUrl(),this._isRedirecting=e}currentUrlHasRedirectingParam(){return Xy in this.getCurrentUrl().query}getCurrentUrl(){return Ne(window.location.href)}replaceCurrentUrl(e){window.history.replaceState(null,"",e)}setRedirectingParamOnUrl(){if(this.currentUrlHasRedirectingParam())return;const e=this.getCurrentUrl(),t=Object.assign(Object.assign({},e),{query:Object.assign(Object.assign({},e.query),{[Xy]:"true"})});this.replaceCurrentUrl(xe(t))}removeRedirectingParamFromUrl(){this.currentUrlHasRedirectingParam()&&this.replaceCurrentUrl(ze(window.location.href,[Xy]))}}const tg=he([e=>"continue"===V(e,"type")&&"redirect"===V(e,"code")&&(e=>{const t=V(e,"form_fields");return X(V(e,"url"))&&(ee(t)||Z(t))})(V(e,"parameters")),e=>"continue"===V(e,"type")&&"resubmit_with_human_verification"===V(e,"code")&&(e=>{const t=V(e,"available_methods");return W(t)})(V(e,"parameters"))]);class ng{constructor(e,t){this._formPoster=e,this._humanVerificationHandler=t}handle(e,t){switch(e.code){case"redirect":return(({url:e,form_fields:t},n)=>{const i=new eg;return i.isRedirecting()?(i.setRedirecting(!1),Promise.reject(new Qy)):(i.setRedirecting(!0),t?n.postForm(e,t):window.location.assign(e),new Promise(ce))})(e.parameters,this._formPoster);case"resubmit_with_human_verification":return(({available_methods:e},t,n)=>{return i=void 0,r=void 0,a=function*(){if(!n)throw new Error("PPSDK human verification callback function is missing.");if(!t)throw new Error("PPSDK human verification handler is missing.");if(0===e.length)throw Error("Human verification method is missing.");const{id:i,parameters:r}=e[0],o=yield t.handle(i,r.key);return n(o)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a})(e.parameters,this._humanVerificationHandler,null==t?void 0:t.humanVerification)}}}class ig{constructor(e){this._continueHandler=e}handle(e,t){const{body:n}=e;return(e=>"success"===V(e,"type"))(n)?Promise.resolve():(e=>tg(e))(n)?this._continueHandler.handle(n,null==t?void 0:t.continue):(e=>"failure"===V(e.body,"type")&&X(V(e.body,"code")))(e)?(e=>{return Promise.reject(new Ot((t=e,Object.assign(Object.assign({},t),{body:{errors:[{code:t.body.code}]}}))));var t})(e):((e=>{V(e.body,"type")})(e),(e=>Promise.reject(new Ot(e)))(e))}}const rg="completed-payments";class og{constructor(e){this._browserStorage=e}isCompleted(e){return this.getCompletedPayments().indexOf(e)>=0}setCompleted(e){const t=this.getCompletedPayments();t.push(e),this.setCompletedPayments(t)}getCompletedPayments(){return this._browserStorage.getItem(rg)||[]}setCompletedPayments(e){this._browserStorage.setItem(rg,e)}}var ag,sg=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class dg{constructor(e,t,n,i,r){this._store=e,this._orderActionCreator=t,this._subStrategyRegistry=n,this._paymentResumer=i,this._completedPayments=new og(r)}execute(e,t){var n;return sg(this,void 0,void 0,function*(){const{bigpayBaseUrl:i}=this._store.getState().config.getStoreConfigOrThrow().paymentSettings;if(!(null==t?void 0:t.methodId))throw new qt('Unable to submit payment because "options.methodId" argument is not provided.');const{methodId:r}=t,{payment:o}=e,a=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{throw this._completedPayments.setCompleted(i),e}),this._store.getState()})}initialize(e){return sg(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new qt('Unable to submit payment because "options.methodId" argument is not provided.');const t=((e,t)=>{const n=e.getState().paymentMethods.getPaymentMethod(t);if(n&&Hy(n))return n})(this._store,e.methodId);if(!t)throw new yn(cn.PaymentNotInitialized);if(this._subStrategy=this._subStrategyRegistry.getByMethod(t),!this._subStrategy)throw new yn(cn.PaymentNotInitialized);return yield this._subStrategy.initialize(e),this._store.getState()})}deinitialize(e){var t;return sg(this,void 0,void 0,function*(){return null===(t=this._subStrategy)||void 0===t||t.deinitialize(),this._store.getState()})}}!function(e){e.CARD="card_ui",e.NONE="none",e.UNSUPPORTED="unsupported"}(ag||(ag={}));const cg=N([[e=>"card_ui"===e.type,x(ag.CARD)],[e=>"none"===e.type,x(ag.NONE)],[fe,x(ag.UNSUPPORTED)]]);class lg extends Vt{getByMethod(e){const t=cg(e.initializationStrategy);return this.get(t)}}var ug=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class hg{constructor(e,t,n,i){this._store=e,this._orderActionCreator=t,this._hostedFormFactory=n,this._ppsdkStepHandler=i}execute(e){return ug(this,void 0,void 0,function*(){const t=this._hostedForm;if(!t)throw new yn(cn.PaymentNotInitialized);const{additionalAction:n,payment:i}=e;if(!i||!i.methodId)throw new Yy(["payment.methodId"]);yield t.validate();const{payload:r}=yield t.submit(i,n),{response:o}=r;yield this._ppsdkStepHandler.handle(o,{continue:{humanVerification:t=>ug(this,void 0,void 0,function*(){return this.execute(Object.assign({additionalAction:t},e))})}}),yield this._store.dispatch(this._orderActionCreator.loadCurrentOrder())})}initialize(e){return ug(this,void 0,void 0,function*(){const t=e&&e.creditCard&&e.creditCard.form,{config:n,checkout:i}=this._store.getState(),{paymentSettings:{bigpayBaseUrl:r=""}={}}=n.getStoreConfig()||{},o=i.getCheckoutOrThrow().id;if(!t)throw new qt;const a=t&&this._hostedFormFactory.create(r,t,o);yield a.attach(),this._hostedForm=a})}deinitialize(){this._hostedForm&&this._hostedForm.detach()}}class pg{constructor(e,t){this._requestSender=e,this._stepHandler=t}execute({methodId:e,bigpayBaseUrl:t,token:n}){const i={credentials:!1,body:{payment_method_id:e},headers:{authorization:n,"X-XSRF-TOKEN":null}};return this._requestSender.post(`${t}/payments`,i).then(e=>this._stepHandler.handle(e))}initialize(){return Promise.resolve()}deinitialize(){}}var mg,yg,gg=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vg{constructor(e,t){this._requestSender=e,this._stepHandler=t}resume({paymentId:e,bigpayBaseUrl:t,orderId:n}){return gg(this,void 0,void 0,function*(){const i={credentials:!1,headers:{authorization:yield this._getToken(n).catch(()=>{throw new Ym}),"X-XSRF-TOKEN":null}};return this._requestSender.get(`${t}/payments/${e}`,i).then(e=>this._stepHandler.handle(e))})}_getToken(e){return gg(this,void 0,void 0,function*(){const t={params:{order_id:e}};return this._requestSender.get("/api/storefront/payments/auth-token",t).then(({body:e})=>e.auth_token)})}}class fg{constructor(e){this._requestSender=e}createBuyNowCart(e,{timeout:t}={}){const n=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post("/api/storefront/carts",{body:e,headers:n,timeout:t})}}!function(e){e.UpdatePaymentProviderCustomer="UPDATE_PAYMENT_PROVIDER_CUSTOMER"}(mg||(mg={}));class Sg{updatePaymentProviderCustomer(e){return C(l(mg.UpdatePaymentProviderCustomer,e))}}!function(e){e.ForgetCheckoutRemoteCustomerRequested="FORGET_CHECKOUT_REMOTE_CUSTOMER_REQUESTED",e.ForgetCheckoutRemoteCustomerSucceeded="FORGET_CHECKOUT_REMOTE_CUSTOMER_SUCCEEDED",e.ForgetCheckoutRemoteCustomerFailed="FORGET_CHECKOUT_REMOTE_CUSTOMER_FAILED",e.InitializeRemoteBillingRequested="INITIALIZE_REMOTE_BILLING_REQUESTED",e.InitializeRemoteBillingSucceeded="INITIALIZE_REMOTE_BILLING_SUCCEEDED",e.InitializeRemoteBillingFailed="INITIALIZE_REMOTE_BILLING_FAILED",e.InitializeRemoteShippingRequested="INITIALIZE_REMOTE_SHIPPING_REQUESTED",e.InitializeRemoteShippingSucceeded="INITIALIZE_REMOTE_SHIPPING_SUCCEEDED",e.InitializeRemoteShippingFailed="INITIALIZE_REMOTE_SHIPPING_FAILED",e.InitializeRemotePaymentRequested="INITIALIZE_REMOTE_PAYMENT_REQUESTED",e.InitializeRemotePaymentSucceeded="INITIALIZE_REMOTE_PAYMENT_SUCCEEDED",e.InitializeRemotePaymentFailed="INITIALIZE_REMOTE_PAYMENT_FAILED",e.LoadRemoteSettingsRequested="LOAD_REMOTE_SETTINGS_REQUESTED",e.LoadRemoteSettingsSucceeded="LOAD_REMOTE_SETTINGS_SUCCEEDED",e.LoadRemoteSettingsFailed="LOAD_REMOTE_SETTINGS_FAILED",e.SignOutRemoteCustomerRequested="SIGN_OUT_REMOTE_CUSTOMER_REQUESTED",e.SignOutRemoteCustomerSucceeded="SIGN_OUT_REMOTE_CUSTOMER_SUCCEEDED",e.SignOutRemoteCustomerFailed="SIGN_OUT_REMOTE_CUSTOMER_FAILED",e.UpdateRemoteCheckout="UPDATE_REMOTE_CHECKOUT"}(yg||(yg={}));var _g;class wg{constructor(e,t){this._remoteCheckoutRequestSender=e,this._checkoutActionCreator=t}initializeBilling(e,t,n){return m.create(i=>{i.next(l(yg.InitializeRemoteBillingRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializeBilling(e,t,n).then(({body:t={}})=>{i.next(l(yg.InitializeRemoteBillingSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(yg.InitializeRemoteBillingFailed,t,{methodId:e}))})})}initializeShipping(e,t,n){return m.create(i=>{i.next(l(yg.InitializeRemoteShippingRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializeShipping(e,t,n).then(({body:t={}})=>{i.next(l(yg.InitializeRemoteShippingSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(yg.InitializeRemoteShippingFailed,t,{methodId:e}))})})}initializePayment(e,t,n){return m.create(i=>{i.next(l(yg.InitializeRemotePaymentRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializePayment(e,t,n).then(({body:t={}})=>{i.next(l(yg.InitializeRemotePaymentSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(yg.InitializeRemotePaymentFailed,t,{methodId:e}))})})}loadSettings(e,t){return m.create(n=>{n.next(l(yg.LoadRemoteSettingsRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.loadSettings(e,t).then(({body:t})=>{n.next(l(yg.LoadRemoteSettingsSucceeded,t,{methodId:e})),n.complete()}).catch(t=>{n.error(h(yg.LoadRemoteSettingsFailed,t,{methodId:e}))})})}signOut(e,t){return m.create(n=>{n.next(l(yg.SignOutRemoteCustomerRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.signOut(e,t).then(()=>{n.next(l(yg.SignOutRemoteCustomerSucceeded,void 0,{methodId:e})),n.complete()}).catch(t=>{n.error(h(yg.SignOutRemoteCustomerFailed,t,{methodId:e}))})})}forgetCheckout(e,t){return g(C(l(yg.ForgetCheckoutRemoteCustomerRequested,void 0,{methodId:e})),v(()=>{return n=this,i=void 0,o=function*(){return yield this._remoteCheckoutRequestSender.forgetCheckout(t),yield this._checkoutActionCreator.loadCurrentCheckout(),l(yg.ForgetCheckoutRemoteCustomerSucceeded,void 0,{methodId:e})},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(t=>Je(yg.ForgetCheckoutRemoteCustomerFailed,t,{methodId:e})))}updateCheckout(e,t){return l(yg.UpdateRemoteCheckout,t,{methodId:e})}}class Ig{constructor(e){this._requestSender=e}initializeBilling(e,t,{timeout:n}={}){const i=`/remote-checkout/${e}/billing`;return this._requestSender.get(i,{params:t,timeout:n,headers:Xe})}initializeShipping(e,t,{timeout:n}={}){const i=`/remote-checkout/${e}/shipping`;return this._requestSender.get(i,{params:t,timeout:n,headers:Xe})}initializePayment(e,t,{timeout:n}={}){const i=`/remote-checkout/${e}/payment`;return this._requestSender.get(i,{params:t,timeout:n,headers:Xe})}loadSettings(e,{timeout:t}={}){const n=`/remote-checkout/${e}/settings`;return this._requestSender.get(n,{timeout:t,headers:Xe})}signOut(e,{timeout:t}={}){const n=`/remote-checkout/${e}/signout`;return this._requestSender.get(n,{timeout:t,headers:Xe})}generateToken({timeout:e}={}){return this._requestSender.get("/remote-checkout-token",{timeout:e,headers:Xe})}trackAuthorizationEvent({timeout:e}={}){return this._requestSender.post("/remote-checkout/events/shopper-checkout-service-provider-authorization-requested",{timeout:e,headers:Xe})}forgetCheckout({timeout:e}={}){return this._requestSender.post("/remote-checkout/forget-checkout",{timeout:e,headers:Xe})}}!function(e){e.CreateConsignmentsRequested="CREATE_CONSIGNMENTS_REQUESTED",e.CreateConsignmentsSucceeded="CREATE_CONSIGNMENTS_SUCCEEDED",e.CreateConsignmentsFailed="CREATE_CONSIGNMENTS_FAILED",e.UpdateConsignmentRequested="UPDATE_CONSIGNMENT_REQUESTED",e.UpdateConsignmentSucceeded="UPDATE_CONSIGNMENT_SUCCEEDED",e.UpdateConsignmentFailed="UPDATE_CONSIGNMENT_FAILED",e.DeleteConsignmentRequested="DELETE_CONSIGNMENT_REQUESTED",e.DeleteConsignmentSucceeded="DELETE_CONSIGNMENT_SUCCEEDED",e.DeleteConsignmentFailed="DELETE_CONSIGNMENT_FAILED",e.UpdateShippingOptionRequested="UPDATE_SHIPPING_OPTION_REQUESTED",e.UpdateShippingOptionSucceeded="UPDATE_SHIPPING_OPTION_SUCCEEDED",e.UpdateShippingOptionFailed="UPDATE_SHIPPING_OPTION_FAILED",e.LoadShippingOptionsRequested="LOAD_SHIPPING_OPTIONS_REQUESTED",e.LoadShippingOptionsSucceeded="LOAD_SHIPPING_OPTIONS_SUCCEEDED",e.LoadShippingOptionsFailed="LOAD_SHIPPING_OPTIONS_FAILED"}(_g||(_g={}));class Cg{constructor(e,t){this._consignmentRequestSender=e,this._checkoutRequestSender=t}unassignItemsByAddress(e,t){return n=>{const i=n.getState();if(!i.checkout.getCheckout())throw new rt(et.MissingCheckout);const r=this._consignmentHasAddress(e)?e.address:e.shippingAddress,o=i.consignments.getConsignmentByAddress(r);if(!o)throw new qt("No consignment found for the specified address");const a=this._removeLineItems(e.lineItems,o,i.cart.getCart());return a.length?this.updateConsignment({id:o.id,address:r,lineItems:a},t)(n):this.deleteConsignment(o.id,t)(n)}}assignItemsByAddress(e,t){return n=>{const i=n.getState(),r=this._consignmentHasAddress(e)?e.address:e.shippingAddress,o=i.consignments.getConsignmentByAddress(r);return this._createOrUpdateConsignment({id:o&&o.id,address:r,lineItems:this._addLineItems(e.lineItems,o,i.cart.getCart())},t)(n)}}selectShippingOption(e,t){return n=>m.create(i=>{const r=n.getState(),o=r.checkout.getCheckout(),a=r.consignments.getConsignments();if(!o)throw new rt(et.MissingCheckout);if(!a||!a.length)throw new rt(et.MissingConsignments);const s={id:a[0].id,shippingOptionId:e},d={id:a[0].id};i.next(l(_g.UpdateShippingOptionRequested,void 0,d)),this._consignmentRequestSender.updateConsignment(o.id,s,t).then(({body:e})=>{i.next(l(_g.UpdateShippingOptionSucceeded,e,d)),i.complete()}).catch(e=>{i.error(h(_g.UpdateShippingOptionFailed,e,d))})})}loadShippingOptions(e){return t=>m.create(n=>{const i=t.getState().checkout.getCheckout();if(!i)throw new rt(et.MissingCheckout);n.next(l(_g.LoadShippingOptionsRequested)),this._checkoutRequestSender.loadCheckout(i.id,Object.assign(Object.assign({},e),{params:{include:[zt.AvailableShippingOptions]}})).then(({body:e})=>{n.next(l(_g.LoadShippingOptionsSucceeded,e)),n.complete()}).catch(e=>{n.error(h(_g.LoadShippingOptionsFailed,e))})})}updateAddress(e,t){return n=>{const i=this._getUpdateAddressRequestBody(e,n),r=n.getState().consignments.getConsignments();return r&&r.length&&(i.id=r[0].id),this._createOrUpdateConsignment(i,t)(n)}}createConsignments(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r||!r.id)throw new rt(et.MissingCheckout);i.next(l(_g.CreateConsignmentsRequested)),this._consignmentRequestSender.createConsignments(r.id,e,t).then(({body:e})=>{i.next(l(_g.CreateConsignmentsSucceeded,e)),i.complete()}).catch(e=>{i.error(h(_g.CreateConsignmentsFailed,e))})})}updateConsignment(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r||!r.id)throw new rt(et.MissingCheckout);const o={id:e.id};i.next(l(_g.UpdateConsignmentRequested,void 0,o)),this._consignmentRequestSender.updateConsignment(r.id,e,t).then(({body:e})=>{i.next(l(_g.UpdateConsignmentSucceeded,e,o)),i.complete()}).catch(e=>{i.error(h(_g.UpdateConsignmentFailed,e,o))})})}deleteConsignment(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout(),o={id:e};if(!r||!r.id)throw new rt(et.MissingCheckout);i.next(l(_g.DeleteConsignmentRequested,void 0,o)),this._consignmentRequestSender.deleteConsignment(r.id,e,t).then(({body:e})=>{i.next(l(_g.DeleteConsignmentSucceeded,e,o)),i.complete()}).catch(e=>{i.error(h(_g.DeleteConsignmentFailed,e,o))})})}updateShippingOption(e,t){return n=>m.create(i=>{var r;const o=n.getState().checkout.getCheckout(),a=n.getState().consignments.getConsignmentById(e.id);if((null===(r=null==a?void 0:a.selectedShippingOption)||void 0===r?void 0:r.id)===e.shippingOptionId)return void i.complete();if(!o||!o.id)throw new rt(et.MissingCheckout);const s={id:e.id};i.next(l(_g.UpdateShippingOptionRequested,void 0,s)),this._consignmentRequestSender.updateConsignment(o.id,e,t).then(({body:e})=>{i.next(l(_g.UpdateShippingOptionSucceeded,e,s)),i.complete()}).catch(e=>{i.error(h(_g.UpdateShippingOptionFailed,e,s))})})}_createOrUpdateConsignment(e,t){return n=>{const i=n.getState().checkout.getCheckout();if(!i||!i.id)throw new rt(et.MissingCheckout);return this._isUpdateConsignmentRequest(e)?this.updateConsignment(e,t)(n):this.createConsignments([e],t)(n)}}_getUpdateAddressRequestBody(e,t){const n=t.getState().cart.getCart();if(!n)throw new rt(et.MissingCart);const{physicalItems:i,customItems:r=[]}=n.lineItems;return{address:e,lineItems:[...i,...r].map(e=>({itemId:e.id,quantity:e.quantity}))}}_removeLineItems(e,t,n){if(!n)throw new rt(et.MissingCart);return this._hydrateLineItems(t.lineItemIds,n).map(t=>{const n=B(e,e=>e.itemId===t.itemId);return Object.assign(Object.assign({},t),{quantity:n?t.quantity-n.quantity:t.quantity})}).filter(e=>e.quantity>0)}_addLineItems(e,t,n){if(!t)return e;if(!n)throw new rt(et.MissingCart);return e.concat(this._hydrateLineItems(t.lineItemIds,n)).filter(e=>e.quantity>0)}_hydrateLineItems(e,t){return e.map(e=>{const n=B(t.lineItems.physicalItems,t=>t.id===e);return{itemId:e,quantity:n?n.quantity:0}})}_isUpdateConsignmentRequest(e){return!!e.id}_consignmentHasAddress(e){return"object"==typeof e&&"address"in e}}const bg=["consignments.availableShippingOptions","cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","promotions.banners"];class Pg{constructor(e){this._requestSender=e}createConsignments(e,t,{timeout:n,params:{include:i}={}}={}){const r=`/api/storefront/checkouts/${e}/consignments`,o=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(r,{body:t,params:{include:Xt(bg,i)},headers:o,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}updateConsignment(e,t,{timeout:n,params:{include:i}={}}={}){const{id:r}=t,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{if("empty_cart"===e.body.type)throw new dt;throw e})}deleteConsignment(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/consignments/${t}`,r=Object.assign({Accept:ct.JsonV1},Xe),o=Ft(bg);return this._requestSender.delete(i,{params:{include:o},headers:r,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new dt;throw e})}}var Og,Eg;!function(e){e.LoadShippingCountriesRequested="LOAD_SHIPPING_COUNTRIES_REQUESTED",e.LoadShippingCountriesSucceeded="LOAD_SHIPPING_COUNTRIES_SUCCEEDED",e.LoadShippingCountriesFailed="LOAD_SHIPPING_COUNTRIES_FAILED"}(Og||(Og={}));class Ag{constructor(e,t){this._shippingCountryRequestSender=e,this._store=t}loadCountries(e){const{checkout:t}=this._store.getState(),n=t.getCheckout(),i=n?n.channelId:null;return m.create(t=>{t.next(l(Og.LoadShippingCountriesRequested)),this._shippingCountryRequestSender.loadCountries(i,e).then(e=>{t.next(l(Og.LoadShippingCountriesSucceeded,e.body.data)),t.complete()}).catch(e=>{t.error(h(Og.LoadShippingCountriesFailed,e))})})}}class Tg{constructor(e,t){this._requestSender=e,this._config=t}loadCountries(e,{timeout:t}={}){const n="/internalapi/v1/shipping/countries"+(e?`?channel_id=${e}`:""),i=Object.assign({"Accept-Language":this._config.locale},Xe);return this._requestSender.get(n,{headers:i,timeout:t})}}!function(e){e.ApplyStoreCreditRequested="APPLY_STORE_CREDIT_REQUESTED",e.ApplyStoreCreditSucceeded="APPLY_STORE_CREDIT_SUCCEEDED",e.ApplyStoreCreditFailed="APPLY_STORE_CREDIT_FAILED"}(Eg||(Eg={}));var kg;class Dg{constructor(e){this._storeCreditRequestSender=e}applyStoreCredit(e,t){return n=>g(C(l(Eg.ApplyStoreCreditRequested)),v(()=>{return i=this,r=void 0,a=function*(){var i;const r=n.getState().checkout.getCheckout();if(!r)throw new rt(et.MissingCheckout);const{id:o}=r,a=null!==(i=null==t?void 0:t.version)&&void 0!==i?i:r.version,{body:s}=yield e?this._storeCreditRequestSender.applyStoreCredit(o,Object.assign(Object.assign({},t),{version:a})):this._storeCreditRequestSender.removeStoreCredit(o,Object.assign(Object.assign({},t),{version:a}));return l(Eg.ApplyStoreCreditSucceeded,s)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a})).pipe(P(e=>Je(Eg.ApplyStoreCreditFailed,e)))}}class Mg{constructor(e){this._requestSender=e}applyStoreCredit(e,{timeout:t,version:n}={}){const i=`/api/storefront/checkouts/${e}/store-credit`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post(i,{headers:r,timeout:t,params:{include:Ft(Mt)},body:{version:n}})}removeStoreCredit(e,{timeout:t,version:n}={}){const i=`/api/storefront/checkouts/${e}/store-credit`,r=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.delete(i,{headers:r,timeout:t,params:{include:Ft(Mt)},body:{version:n}})}}!function(e){e.UpdateSubscriptionsRequested="UPDATE_SUBSCRIPTIONS_REQUESTED",e.UpdateSubscriptionsSucceeded="UPDATE_SUBSCRIPTIONS_SUCCEEDED",e.UpdateSubscriptionsFailed="UPDATE_SUBSCRIPTIONS_FAILED"}(kg||(kg={}));class zg extends Ot{constructor(e){super(e),this.name="UpdateSubscriptionsError",this.type="update_subscriptions"}}class Ng{constructor(e){this._subscriptionsRequestSender=e}updateSubscriptions(e,t){return g(C(l(kg.UpdateSubscriptionsRequested)),v(()=>{return n=this,i=void 0,o=function*(){const{body:n}=yield this._subscriptionsRequestSender.updateSubscriptions(e,t);return l(kg.UpdateSubscriptionsSucceeded,n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Je(kg.UpdateSubscriptionsFailed,new zg(e))))}}class xg{constructor(e){this._requestSender=e}updateSubscriptions(e,{timeout:t}={}){const n=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post("/api/storefront/subscriptions",{body:e,headers:n,timeout:t})}}function Rg(e){return Q(e)}const Fg=se(e=>Array.isArray(e)?e.map(e=>Lg(e)):Rg(e)?Object.keys(e).reduce((t,n)=>Object.assign(Object.assign({},t),{[n]:Lg(e[n])}),{}):e);Fg.cache=new WeakMap;const Lg=e=>"object"==typeof e&&null!==e?Fg(e):e;function Bg(e){return(...t)=>Lg(e(...t))}function jg({billingAddress:{getBillingAddress:e,getBillingAddressOrThrow:t},cart:{getCart:n,getCartOrThrow:i,getLocale:r},checkout:{getCheckout:o,getCheckoutOrThrow:a,getOutstandingBalance:s},config:{getContextConfig:d,getHost:c,getLocale:l,getStoreConfig:u,getStoreConfigOrThrow:h,getConfig:p},consignments:{getConsignments:m,getConsignmentsOrThrow:y},countries:{getCountries:g},customer:{getCustomer:v,getCustomerOrThrow:f},instruments:{getCardInstrument:S,getCardInstrumentOrThrow:_,getInstruments:w,getInstrumentsMeta:I},order:{getOrder:C,getOrderOrThrow:b,getOrderMeta:P},payment:{getPaymentToken:O,getPaymentTokenOrThrow:E,getPaymentId:A,getPaymentIdOrThrow:T,getPaymentStatus:k,getPaymentStatusOrThrow:D,getPaymentRedirectUrl:M,getPaymentRedirectUrlOrThrow:z,isPaymentDataRequired:N},paymentMethods:{getPaymentMethod:x,getPaymentMethodOrThrow:R,getPaymentMethodsMeta:F},paymentProviderCustomer:{getPaymentProviderCustomer:L,getPaymentProviderCustomerOrThrow:B},paymentStrategies:{isInitialized:j},shippingAddress:{getShippingAddress:U,getShippingAddressOrThrow:q,getShippingAddresses:V,getShippingAddressesOrThrow:G},shippingCountries:{getShippingCountries:H}}){return{getHost:Bg(c),getLocale:Bg(l),getCartLocale:Bg(r),getBillingAddress:Bg(e),getBillingAddressOrThrow:Bg(t),getCart:Bg(n),getCartOrThrow:Bg(i),getCheckout:Bg(o),getCheckoutOrThrow:Bg(a),getCountries:Bg(g),getStoreConfig:Bg(u),getStoreConfigOrThrow:Bg(h),getConfig:Bg(p),getConsignments:Bg(m),getConsignmentsOrThrow:Bg(y),getContextConfig:Bg(d),getCustomer:Bg(v),getCustomerOrThrow:Bg(f),getCardInstrument:Bg(S),getInstruments:Bg(w),getCardInstrumentOrThrow:Bg(_),getOrder:Bg(C),getOrderOrThrow:Bg(b),getOrderMeta:Bg(P),getInstrumentsMeta:Bg(I),getPaymentToken:O,getPaymentTokenOrThrow:E,getPaymentId:A,getPaymentIdOrThrow:T,getPaymentStatus:k,getPaymentStatusOrThrow:D,getPaymentRedirectUrl:M,getPaymentRedirectUrlOrThrow:z,getPaymentMethod:Bg(x),getPaymentMethodOrThrow:Bg(R),getPaymentMethodsMeta:Bg(F),getPaymentProviderCustomer:Bg(L),getPaymentProviderCustomerOrThrow:Bg(B),getShippingAddress:Bg(U),getShippingAddressOrThrow:Bg(q),getShippingAddresses:Bg(V),getShippingAddressesOrThrow:Bg(G),getShippingCountries:Bg(H),getOutstandingBalance:Bg(s),isPaymentDataRequired:N,isPaymentMethodInitialized:j}}var Ug,qg=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vg{constructor(e,t,n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S){this._store=e,this._storeProjectionFactory=t,this._checkoutActionCreator=n,this._checkoutValidator=i,this._hostedFormFactory=r,this._orderActionCreator=o,this._billingAddressActionCreator=a,this._consignmentActionCreator=s,this._paymentMethodActionCreator=d,this._paymentActionCreator=c,this._paymentHumanVerificationHandler=l,this._customerActionCreator=u,this._cartRequestSender=h,this._storeCreditActionCreator=p,this._couponActionCreator=m,this._spamProtectionActionCreator=y,this._paymentProviderCustomerActionCreator=g,this._shippingCountryActionCreator=v,this._remoteCheckoutActionCreator=f,this._paymentStrategyWidgetActionCreator=S,this._storeProjection=this._storeProjectionFactory.create(this._store)}createHostedForm(e,t){const n=this._storeProjection.getState().getCheckoutOrThrow().id;return this._hostedFormFactory.create(e,t,n)}subscribe(e,...t){return this._storeProjection.subscribe(e,...t)}getState(){return this._storeProjection.getState()}initializeOffsitePayment(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentActionCreator.initializeOffsitePayment(e)),this._storeProjection.getState()})}loadCheckout(e){return qg(this,void 0,void 0,function*(){return e?yield this._store.dispatch(this._checkoutActionCreator.loadCheckout(e)):yield this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),this._storeProjection.getState()})}loadDefaultCheckout(){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()),this._storeProjection.getState()})}loadPaymentMethod(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e,t)),this._storeProjection.getState()})}loadPaymentMethods(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethods(e)),this._storeProjection.getState()})}submitOrder(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._orderActionCreator.submitOrder(e,t)),this._storeProjection.getState()})}submitPayment(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentActionCreator.submitPayment(e)),this._storeProjection.getState()})}finalizeOrder(e){return qg(this,void 0,void 0,function*(){const{order:{getOrderOrThrow:t}}=this._store.getState();return yield this._store.dispatch(this._orderActionCreator.finalizeOrder(t().orderId,e)),this._storeProjection.getState()})}updateBillingAddress(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(e)),this._storeProjection.getState()})}updateShippingAddress(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.updateAddress(e)),this._storeProjection.getState()})}selectShippingOption(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t)),this._storeProjection.getState()})}signInCustomer(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._customerActionCreator.signInCustomer(e,t)),this._storeProjection.getState()})}signOutCustomer(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._customerActionCreator.signOutCustomer(e)),this._storeProjection.getState()})}createBuyNowCart(e,t){return qg(this,void 0,void 0,function*(){const{body:n}=yield this._cartRequestSender.createBuyNowCart(e,t);return n})}applyStoreCredit(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(e,t)),this._storeProjection.getState()})}applyCoupon(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._couponActionCreator.applyCoupon(e,t)),this._storeProjection.getState()})}removeCoupon(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._couponActionCreator.removeCoupon(e,t)),this._storeProjection.getState()})}verifyCheckoutSpamProtection(){return qg(this,void 0,void 0,function*(){const{checkout:e}=this._store.getState(),{shouldExecuteSpamCheck:t}=e.getCheckoutOrThrow();return t&&(yield this._store.dispatch(this._spamProtectionActionCreator.verifyCheckoutSpamProtection())),this._storeProjection.getState()})}loadCurrentOrder(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._orderActionCreator.loadCurrentOrder(e)),this._storeProjection.getState()})}updatePaymentProviderCustomer(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(e)),this._storeProjection.getState()})}loadShippingCountries(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._shippingCountryActionCreator.loadCountries(e)),this._storeProjection.getState()})}deleteConsignment(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.deleteConsignment(e,t)),this._storeProjection.getState()})}initializePayment(e,t,n){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.initializePayment(e,t,n)),this._storeProjection.getState()})}forgetCheckout(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.forgetCheckout(e,t)),this._storeProjection.getState()})}remoteCheckoutSignOut(e,t){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.signOut(e,t)),this._storeProjection.getState()})}validateCheckout(e,t){return qg(this,void 0,void 0,function*(){yield this._checkoutValidator.validate(e,t)})}handlePaymentHumanVerification(e,t){return qg(this,void 0,void 0,function*(){return"string"==typeof e?this._paymentHumanVerificationHandler.handle(e,null!=t?t:""):this._paymentHumanVerificationHandler.handle(e)})}widgetInteraction(e){return qg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentStrategyWidgetActionCreator.widgetInteraction(e),{queueId:"widgetInteraction"}),this._storeProjection.getState()})}}class Gg{constructor(e){this._transformSelectors=e}create(e){return mt(e,this._transformSelectors)}}function Hg(e,t){const{config:{getHost:i,getLocale:r}}=e.getState();t||(t=n({host:i()}));const a=new Gg(jg),s=new nn(new en(t),new bt(new Tt(t)),new on(new an(t))),d=new ny(new en(t)),c=new Iy(e),l=new Vm(new jm(t),new ny(new en(t))),u=new st(new ut(t),new Ng(new xg(t))),h=new Cg(new Pg(t),new en(t)),p=new Wm(new $m(t)),m=new Cy(new by(Gm(e)),l,new Gy,new cy(Sn(o()))),y=new cy(Sn(o())),g=new Kt(new Jt(t),s,new pn(Sn(o()),new _n(t))),v=new Dg(new Mg(t)),f=new Dt(new Lt(t)),S=Sn(o()),_=new _n(t),w=new pn(S,_),I=new fg(t),C=new Sg,b=new Ag(new Tg(t,{locale:r()}),e),P=new wg(new Ig(t),s),O=new Qm;return new Vg(e,a,s,d,c,l,u,h,p,m,y,g,I,v,f,w,C,b,P,O)}!function(e){e.LoadInstrumentsRequested="LOAD_INSTRUMENTS_REQUESTED",e.LoadInstrumentsSucceeded="LOAD_INSTRUMENTS_SUCCEEDED",e.LoadInstrumentsFailed="LOAD_INSTRUMENTS_FAILED",e.DeleteInstrumentRequested="DELETE_INSTRUMENT_REQUESTED",e.DeleteInstrumentSucceeded="DELETE_INSTRUMENT_SUCCEEDED",e.DeleteInstrumentFailed="DELETE_INSTRUMENT_FAILED"}(Ug||(Ug={}));class Wg{constructor(e){this._instrumentRequestSender=e}loadInstruments(){return e=>m.create(t=>{t.next(l(Ug.LoadInstrumentsRequested));const n=this._getSessionContext(e),i=this._getCurrentAccessToken(e),r=this._getShippingAddress(e);return this._getValidAccessToken(i).then(e=>this._instrumentRequestSender.loadInstruments(Object.assign(Object.assign({},n),{authToken:e.vaultAccessToken}),r).then(({body:n})=>{t.next(l(Ug.LoadInstrumentsSucceeded,n,e)),t.complete()})).catch(e=>{t.error(h(Ug.LoadInstrumentsFailed,e))})})}deleteInstrument(e){return t=>m.create(n=>{n.next(l(Ug.DeleteInstrumentRequested,void 0,{instrumentId:e}));const i=this._getSessionContext(t),r=this._getCurrentAccessToken(t);return this._getValidAccessToken(r).then(t=>this._instrumentRequestSender.deleteInstrument(Object.assign(Object.assign({},i),{authToken:t.vaultAccessToken}),e).then(({body:i})=>{n.next(l(Ug.DeleteInstrumentSucceeded,i,Object.assign({instrumentId:e},t))),n.complete()})).catch(t=>{n.error(h(Ug.DeleteInstrumentFailed,t,{instrumentId:e}))})})}_isValidVaultAccessToken(e){if(!e||!e.vaultAccessToken)return!1;return function(e){const t=new Date(e.getTime());return t.setMinutes(e.getMinutes()+2),t}(new Date(e.vaultAccessExpiry)).valueOf()>Date.now()}_getCurrentAccessToken(e){const{instruments:t}=e.getState(),n=t.getInstrumentsMeta();if(n)return{vaultAccessToken:n.vaultAccessToken,vaultAccessExpiry:n.vaultAccessExpiry}}_getValidAccessToken(e){return e&&this._isValidVaultAccessToken(e)?Promise.resolve(e):this._instrumentRequestSender.getVaultAccessToken().then(({body:e})=>e)}_getShippingAddress(e){const t=e.getState(),n=t.shippingAddress.getShippingAddresses();return n.length>1?n:t.shippingAddress.getShippingAddress()}_getSessionContext(e){const t=e.getState(),n=t.config.getStoreConfig(),i=t.cart.getCart();if(!n)throw new rt(et.MissingCheckoutConfig);if(!i)throw new rt(et.MissingCart);const{customerId:r}=i,{storeId:o}=n.storeProfile,{code:a}=n.shopperCurrency.isTransactional?n.shopperCurrency:n.currency;return{customerId:r,storeId:o,currencyCode:a}}}var $g,Yg,Kg=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);rthis._isPayPalInstrument(e)?function(e){return{bigpayToken:e.bigpay_token,defaultInstrument:e.default_instrument,provider:e.provider,externalId:e.external_id,trustedShippingAddress:e.trusted_shipping_address,method:"paypal",type:"account"}}(e):this._isBankInstrument(e)?function(e){return{bigpayToken:e.bigpay_token,defaultInstrument:e.default_instrument,provider:e.provider,trustedShippingAddress:e.trusted_shipping_address,accountNumber:e.account_number,issuer:e.issuer,iban:e.iban,method:e.method,type:"bank"}}(e):function(e){return{bigpayToken:e.bigpay_token,defaultInstrument:e.default_instrument,provider:e.provider,iin:e.iin,last4:e.last_4,expiryMonth:e.expiry_month,expiryYear:e.expiry_year,brand:e.brand,trustedShippingAddress:e.trusted_shipping_address,untrustedShippingCardVerificationMode:e.untrusted_shipping_address_card_verification_mode,method:e.method,type:"card"}}(e))}_isPayPalInstrument(e){return"paypal"===e.method_type}_isBankInstrument(e){return"bank"===e.method_type}_transformResponse(e){const{data:t}=e,n=Kg(e,["data"]);return Object.assign(Object.assign({},n),{body:t})}}class Zg{constructor(e,t){this._client=e,this._requestSender=t,this._transformer=new Jg}getVaultAccessToken({timeout:e}={}){return this._requestSender.get("/internalapi/v1/checkout/payments/vault-access-token",{timeout:e}).then(e=>Object.assign(Object.assign({},e),{body:{vaultAccessToken:e.body.data.token,vaultAccessExpiry:e.body.data.expires_at}}))}loadInstruments(e,t){return t?this._loadInstrumentsWithAddress(e,t):this._loadInstruments(e)}deleteInstrument(e,t){const n=Object.assign(Object.assign({},e),{instrumentId:t});return new Promise((e,t)=>{this._client.deleteShopperInstrument(n,(n,i)=>n?t(this._transformer.transformErrorResponse(n)):e(this._transformer.transformResponse(i)))})}_loadInstruments(e){return new Promise((t,n)=>{this._client.loadInstruments(e,(e,i)=>e?n(this._transformer.transformErrorResponse(e)):t(this._transformer.transformResponse(i)))})}_loadInstrumentsWithAddress(e,t){const n=Object.assign(Object.assign({},e),{shippingAddress:Array.isArray(t)?t.map(e=>Py(e)):Py(t)});return new Promise((e,t)=>{this._client.loadInstrumentsWithAddress(n,(n,i)=>n?t(this._transformer.transformErrorResponse(n)):e(this._transformer.transformResponse(i)))})}}!function(e){e.LoadPickupOptionsRequested="LOAD_PICKUP_OPTIONS_REQUESTED",e.LoadPickupOptionsSucceeded="LOAD_PICKUP_OPTIONS_SUCCEEDED",e.LoadPickupOptionsFailed="LOAD_PICKUP_OPTIONS_FAILED"}($g||($g={}));class Qg{constructor(e){this._pickupOptionRequestSender=e}loadPickupOptions(e){return t=>new m(n=>{const i=this._hydrateApiQuery(t,e);n.next(l($g.LoadPickupOptionsRequested)),this._pickupOptionRequestSender.fetchPickupOptions(i).then(t=>{n.next(l($g.LoadPickupOptionsSucceeded,t.body.results,e)),n.complete()}).catch(e=>{n.error(h($g.LoadPickupOptionsFailed,e))})})}_hydrateApiQuery(e,t){const n=e.getState(),i=n.cart.getCartOrThrow();if(!i)throw new rt(et.MissingCart);const r=n.consignments.getConsignmentById(t.consignmentId);if(!r)throw new rt(et.MissingConsignments);const o=r.lineItemIds,a=i.lineItems.physicalItems.filter(e=>H(o,e.id)).map(e=>({variantId:e.variantId,quantity:e.quantity}));return{searchArea:t.searchArea,items:a}}}class Xg{constructor(e){this._requestSender=e}fetchPickupOptions(e){return this._requestSender.post("/api/storefront/pickup-options",{headers:Object.assign({Accept:ct.Json},Xe),body:e})}}!function(e){e.UpdateAddressFailed="SHIPPING_STRATEGY_UPDATE_ADDRESS_FAILED",e.UpdateAddressRequested="SHIPPING_STRATEGY_UPDATE_ADDRESS_REQUESTED",e.UpdateAddressSucceeded="SHIPPING_STRATEGY_UPDATE_ADDRESS_SUCCEEDED",e.SelectOptionFailed="SHIPPING_STRATEGY_SELECT_OPTION_FAILED",e.SelectOptionRequested="SHIPPING_STRATEGY_SELECT_OPTION_REQUESTED",e.SelectOptionSucceeded="SHIPPING_STRATEGY_SELECT_OPTION_SUCCEEDED",e.InitializeFailed="SHIPPING_STRATEGY_INITIALIZE_FAILED",e.InitializeRequested="SHIPPING_STRATEGY_INITIALIZE_REQUESTED",e.InitializeSucceeded="SHIPPING_STRATEGY_INITIALIZE_SUCCEEDED",e.DeinitializeFailed="SHIPPING_STRATEGY_DEINITIALIZE_FAILED",e.DeinitializeRequested="SHIPPING_STRATEGY_DEINITIALIZE_REQUESTED",e.DeinitializeSucceeded="SHIPPING_STRATEGY_DEINITIALIZE_SUCCEEDED",e.WidgetInteractionStarted="SHIPPING_STRATEGY_WIDGET_INTERACTION_STARTED",e.WidgetInteractionFinished="SHIPPING_STRATEGY_WIDGET_INTERACTION_FINISHED",e.WidgetInteractionFailed="SHIPPING_STRATEGY_WIDGET_INTERACTION_FAILED"}(Yg||(Yg={}));class ev{constructor(e){this._strategyRegistry=e}updateAddress(e,t){return n=>m.create(i=>{const r=n.getState().payment.getPaymentId(),o=t&&t.methodId||r&&r.providerId;i.next(l(Yg.UpdateAddressRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).updateAddress(e,Object.assign(Object.assign({},t),{methodId:o})).then(()=>{i.next(l(Yg.UpdateAddressSucceeded,void 0,{methodId:o})),i.complete()}).catch(e=>{i.error(h(Yg.UpdateAddressFailed,e,{methodId:o}))})})}selectOption(e,t){return n=>m.create(i=>{const r=n.getState().payment.getPaymentId(),o=t&&t.methodId||r&&r.providerId;i.next(l(Yg.SelectOptionRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).selectOption(e,Object.assign(Object.assign({},t),{methodId:o})).then(()=>{i.next(l(Yg.SelectOptionSucceeded,void 0,{methodId:o})),i.complete()}).catch(e=>{i.error(h(Yg.SelectOptionFailed,e,{methodId:o}))})})}initialize(e){return t=>m.create(n=>{const i=t.getState(),r=i.payment.getPaymentId(),o=e&&e.methodId||r&&r.providerId,a=Object.assign(Object.assign({},e),{methodId:o});if(o&&i.shippingStrategies.isInitialized(o))return n.complete();n.next(l(Yg.InitializeRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).initialize(a).then(()=>{n.next(l(Yg.InitializeSucceeded,void 0,{methodId:o})),n.complete()}).catch(e=>{n.error(h(Yg.InitializeFailed,e,{methodId:o}))})})}deinitialize(e){return t=>m.create(n=>{const i=t.getState(),r=i.payment.getPaymentId(),o=e&&e.methodId||r&&r.providerId;if(o&&!i.shippingStrategies.isInitialized(o))return n.complete();n.next(l(Yg.DeinitializeRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).deinitialize(Object.assign(Object.assign({},e),{methodId:o})).then(()=>{n.next(l(Yg.DeinitializeSucceeded,void 0,{methodId:o})),n.complete()}).catch(e=>{n.error(h(Yg.DeinitializeFailed,e,{methodId:o}))})})}widgetInteraction(e,t){return m.create(n=>{const i={methodId:t&&t.methodId};n.next(l(Yg.WidgetInteractionStarted,void 0,i)),e().then(()=>{n.next(l(Yg.WidgetInteractionFinished,void 0,i)),n.complete()}).catch(e=>{n.error(h(Yg.WidgetInteractionFailed,e,i))})})}}var tv,nv=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class iv{constructor(e,t,n,i,r){this._store=e,this._consignmentActionCreator=t,this._paymentMethodActionCreator=n,this._amazonPayV2PaymentProcessor=i,this._shippingStrategyActionCreator=r}updateAddress(e,t){const n=this._store.getState().shippingAddress.getShippingAddress();if(!n)throw new rt(et.MissingShippingAddress);const i=Object.assign(Object.assign({},n),{customFields:e.customFields});return this._store.dispatch(this._consignmentActionCreator.updateAddress(i,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(e){return nv(this,void 0,void 0,function*(){const{amazonpay:t,methodId:n}=e;if(!t||!n)throw new qt('Unable to proceed because "options.amazonpay" argument is not provided.');const i=(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n))).paymentMethods.getPaymentMethodOrThrow(n);yield this._amazonPayV2PaymentProcessor.initialize(i);const{paymentToken:r,region:o}=i.initializationData,a=t.editAddressButtonId;if(r&&a){const e=this._shouldShowLoadingSpinner(o);this._bindEditButton(a,r,"changeAddress",e)}return this._store.getState()})}deinitialize(){return nv(this,void 0,void 0,function*(){return yield this._amazonPayV2PaymentProcessor.deinitialize(),Promise.resolve(this._store.getState())})}_bindEditButton(e,t,n,i){const r=document.getElementById(e);if(r&&r.parentNode){if(i){const e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener("click",()=>this._showLoadingSpinner())}this._amazonPayV2PaymentProcessor.bindButton(e,t,n)}}_showLoadingSpinner(){return this._store.dispatch(this._shippingStrategyActionCreator.widgetInteraction(()=>new Promise(I)),{queueId:"widgetInteraction"})}_shouldShowLoadingSpinner(e){return"us"!==e}}!function(e){e.CVV="cvv",e.PAN="pan"}(tv||(tv={}));var rv=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ov{constructor(e,t,n,i,r,o){this._store=e,this._billingAddressActionCreator=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=i,this._paymentProviderCustomerActionCreator=r,this._braintreeIntegrationService=o}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}deinitialize(){return Promise.resolve(this._store.getState())}initialize(e){var t;return rv(this,void 0,void 0,function*(){const{methodId:n,braintreefastlane:i,fastlane:r}=e||{},o=r||i,{onPayPalFastlaneAddressChange:a}=o||{};if(!n)throw new qt('Unable to proceed because "methodId" argument is not provided.');const s=this._store.getState();if(!s.customer.getCustomerOrThrow().isGuest)return Promise.resolve(this._store.getState());try{if(this._shouldRunAuthenticationFlow()){const e=s.paymentMethods.getPaymentMethod(n),{clientToken:i,isFastlaneStylingEnabled:r}=(null==e?void 0:e.initializationData)||{};i||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n)));const a=Ao(r?null===(t=null==e?void 0:e.initializationData)||void 0===t?void 0:t.fastlaneStyles:void 0,null==o?void 0:o.styles);yield this._runAuthenticationFlowOrThrow(n,a)}"function"==typeof a&&(yield this._shouldUseBraintreeFastlaneShippingComponent(n))&&a(()=>this._handleBraintreeFastlaneShippingAddressChange())}catch(e){}return Promise.resolve(this._store.getState())})}_shouldRunAuthenticationFlow(){var e;const t=this._store.getState(),n=null===(e=t.cart.getCart())||void 0===e?void 0:e.id,i=Fr.get("bc-fastlane-sessionId")||"",r=t.paymentProviderCustomer.getPaymentProviderCustomer(),o=xl(r)?r:{};return(null==o?void 0:o.authenticationState)!==Mi.CANCELED&&!(null==o?void 0:o.authenticationState)&&i===n}_runAuthenticationFlowOrThrow(e,t){var n,i;return rv(this,void 0,void 0,function*(){const r=this._store.getState(),o=r.cart.getCartOrThrow(),a=r.countries.getCountries()||[],s=r.paymentMethods.getPaymentMethodOrThrow(e),{clientToken:d,config:c}=s;if(!d)throw new rt(et.MissingPaymentMethod);this._braintreeIntegrationService.initialize(d);const l=yield this._braintreeIntegrationService.getBraintreeFastlane(null==o?void 0:o.id,null==c?void 0:c.testMode,t),u=(null===(n=r.customer.getCustomer())||void 0===n?void 0:n.email)||(null===(i=r.billingAddress.getBillingAddress())||void 0===i?void 0:i.email);if(!u)return;const{lookupCustomerByEmail:h,triggerAuthenticationFlow:p}=l.identity,{customerContextId:m}=yield h(u);if(!m)return;const{authenticationState:y,profileData:g}=yield p(m);if(y===Mi.CANCELED)return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:y,addresses:[],instruments:[]})),void Fr.remove("bc-fastlane-sessionId");const v=this._getPayPalBillingAddress(g),f=g.shippingAddress,S=g.shippingAddress.phoneNumber,_=this._mapPayPalToBcAddress(f,a,S),w=this._mapPayPalToBcAddress(v,a,S);if(w&&_){const t=this._mergeShippingAndBillingAddresses(_,w),n=this._mapPayPalToBcInstrument(e,g.card),i=n?[n]:[];yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:y,addresses:t,instruments:i})),w&&(yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(Object.assign(Object.assign({},w),{id:String(w.id)})))),_&&o.lineItems.physicalItems.length>0&&(yield this._store.dispatch(this._consignmentActionCreator.updateAddress(_)))}})}_getPayPalBillingAddress(e){const{name:t,card:n}=e,i=n.paymentSource.card.billingAddress;return Object.assign(Object.assign({},i),{firstName:i.firstName||(null==t?void 0:t.firstName),lastName:i.lastName||(null==t?void 0:t.lastName)})}_getCountryNameByCountryCode(e,t){const n=t.find(t=>t.code===e);return(null==n?void 0:n.name)||""}_mapPayPalToBcAddress(e,t,n,i){return{id:Number(Date.now()),type:"paypal-address",firstName:e.firstName||"",lastName:e.lastName||"",company:e.company||"",address1:e.streetAddress,address2:e.extendedAddress||"",city:e.locality,stateOrProvince:e.region,stateOrProvinceCode:e.region,country:this._getCountryNameByCountryCode(e.countryCodeAlpha2,t),countryCode:e.countryCodeAlpha2,postalCode:e.postalCode,phone:n||"",customFields:i||[]}}_normalizeAddress(e){return le(e,["id"])}_mergeShippingAndBillingAddresses(e,t){return Y(this._normalizeAddress(e),this._normalizeAddress(t))?[e]:[e,t]}_mapPayPalToBcInstrument(e,t){if(!t)return;const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a}=i.card,[s,d]=o.split("-");return{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:tv.CVV,type:"card"}}_handleBraintreeFastlaneShippingAddressChange(){var e;return rv(this,void 0,void 0,function*(){const t=this._store.getState().countries.getCountries()||[],n=yield this._braintreeIntegrationService.getBraintreeFastlane(),{selectionChanged:i,selectedAddress:r}=yield n.profile.showShippingAddressSelector();if(i){const n=this._store.getState(),i=n.shippingAddress.getShippingAddressesOrThrow(),o=n.paymentProviderCustomer.getPaymentProviderCustomer(),a=xl(o)?o:{},s=this._mapPayPalToBcAddress(r,t,r.phoneNumber,null===(e=i[0])||void 0===e?void 0:e.customFields);if(s){const e=this._filterAddresses([s,...a.addresses||[]]);return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(Object.assign(Object.assign({},a),{addresses:e}))),yield this._store.dispatch(this._consignmentActionCreator.updateAddress(s)),s}}})}_filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this._isEqualAddresses(e,t))?e:[...e,t]:e,[])}_isEqualAddresses(e,t){return Y(this._normalizeAddress(e),this._normalizeAddress(t))}_shouldUseBraintreeFastlaneShippingComponent(e){var t;return rv(this,void 0,void 0,function*(){const n=this._store.getState().paymentProviderCustomer.getPaymentProviderCustomer(),i=xl(n)?n:{};if(i&&(null==i?void 0:i.authenticationState)!==Mi.CANCELED){const n=yield this._getBraintreePaymentMethodOrThrow(e);return!!(null===(t=null==n?void 0:n.initializationData)||void 0===t?void 0:t.isFastlaneEnabled)}return!1})}_getBraintreePaymentMethodOrThrow(e){return rv(this,void 0,void 0,function*(){const t=this._store.getState().paymentMethods.getPaymentMethod(e);return t||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e))).paymentMethods.getPaymentMethodOrThrow(e)})}}class av{constructor(e,t){this._store=e,this._consignmentActionCreator=t}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(){return Promise.resolve(this._store.getState())}deinitialize(){return Promise.resolve(this._store.getState())}}var sv=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class dv{constructor(e,t,n,i,r,o,a){this._store=e,this._billingAddressActionCreator=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=i,this._paymentProviderCustomerActionCreator=r,this._paypalSdkScriptLoader=o,this._paypalCommerceFastlaneUtils=a}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}deinitialize(){return Promise.resolve(this._store.getState())}initialize(e){return sv(this,void 0,void 0,function*(){const{methodId:t,paypalcommercefastlane:n,fastlane:i}=e||{},r=i||n,{onPayPalFastlaneAddressChange:o,styles:a}=r||{};if(!t)throw new qt('Unable to proceed because "methodId" argument is not provided.');const s=this._store.getState().customer.getCustomerOrThrow();if(!(null==s?void 0:s.isGuest))return Promise.resolve(this._store.getState());try{this._shouldAuthenticateUserWithFastlane()&&(yield this._initializePayPalSdk(t,a),yield this._authenticateUserWithFastlaneOtp(t)),"function"==typeof o&&this._shouldUsePayPalFastlaneShippingComponent()&&(yield this._initializePayPalSdk(t,a),o(()=>this._handlePayPalShippingAddressChange()))}catch(e){}return Promise.resolve(this._store.getState())})}_getPayPalPaymentMethodOrThrow(e){return sv(this,void 0,void 0,function*(){const t=this._store.getState().paymentMethods.getPaymentMethod(e);return t||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e))).paymentMethods.getPaymentMethodOrThrow(e)})}_getPayPalCustomerAuthenticationState(){const e=this._store.getState().paymentProviderCustomer.getPaymentProviderCustomerOrThrow();var t;return((t=e)&&("authenticationState"in t||"addresses"in t||"instruments"in t)?e:{}).authenticationState}_shouldAuthenticateUserWithFastlane(){const e=this._store.getState().cart.getCartOrThrow(),t=this._paypalCommerceFastlaneUtils.getStorageSessionId();return!this._getPayPalCustomerAuthenticationState()&&t===e.id}_shouldUsePayPalFastlaneShippingComponent(){const e=this._getPayPalCustomerAuthenticationState();return!!e&&e!==fs.CANCELED}_initializePayPalSdk(e,t){var n;return sv(this,void 0,void 0,function*(){const i=this._store.getState().cart.getCartOrThrow(),r=yield this._getPayPalPaymentMethodOrThrow(e),{isDeveloperModeApplicable:o,isFastlaneStylingEnabled:a}=(null==r?void 0:r.initializationData)||{},s=!!o,d=rd(a?null===(n=null==r?void 0:r.initializationData)||void 0===n?void 0:n.fastlaneStyles:{},t),c=yield this._paypalSdkScriptLoader.getPayPalFastlaneSdk(r,i.currency.code,i.id,i.locale);yield this._paypalCommerceFastlaneUtils.initializePayPalFastlane(c,s,d)})}_authenticateUserWithFastlaneOtp(e){var t,n;return sv(this,void 0,void 0,function*(){const i=this._store.getState(),r=i.cart.getCartOrThrow(),o=null===(t=i.customer.getCustomer())||void 0===t?void 0:t.email,a=null===(n=i.billingAddress.getBillingAddress())||void 0===n?void 0:n.email,s=o||a||"",{customerContextId:d}=yield this._paypalCommerceFastlaneUtils.lookupCustomerOrThrow(s),c=yield this._paypalCommerceFastlaneUtils.triggerAuthenticationFlowOrThrow(d),{authenticationState:l,addresses:u,billingAddress:h,shippingAddress:p,instruments:m}=this._paypalCommerceFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,c);yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:l,addresses:u,instruments:m})),c.authenticationState===fs.CANCELED?this._paypalCommerceFastlaneUtils.removeStorageSessionId():this._paypalCommerceFastlaneUtils.updateStorageSessionId(r.id),h&&(yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(Object.assign(Object.assign({},h),{id:String(h.id)})))),p&&r.lineItems.physicalItems.length>0&&(yield this._store.dispatch(this._consignmentActionCreator.updateAddress(p)))})}_handlePayPalShippingAddressChange(){var e;return sv(this,void 0,void 0,function*(){const t=this._paypalCommerceFastlaneUtils.getPayPalFastlaneOrThrow(),{selectionChanged:n,selectedAddress:i}=yield t.profile.showShippingAddressSelector();if(n){const t=this._store.getState(),n=t.shippingAddress.getShippingAddressesOrThrow(),r=t.paymentProviderCustomer.getPaymentProviderCustomer(),o=vp(r)?r:{},a=this._paypalCommerceFastlaneUtils.mapPayPalToBcAddress(i.address,i.name,i.phoneNumber,null===(e=n[0])||void 0===e?void 0:e.customFields),s=this._paypalCommerceFastlaneUtils.filterAddresses([a,...o.addresses||[]]);return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(Object.assign(Object.assign({},o),{addresses:s}))),yield this._store.dispatch(this._consignmentActionCreator.updateAddress(a)),a}})}}var cv;class lv{constructor(e,t,n,i){this._store=e,this._stripeScriptLoader=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=i}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(e){return t=this,n=void 0,r=function*(){if(!e.stripeupe)throw new qt('Unable to proceed because "options" argument is not provided.');const{container:t,gatewayId:n,methodId:i,onChangeShipping:r,getStyles:o,availableCountries:a,getStripeState:s}=e.stripeupe;Object.entries(e.stripeupe).forEach(([e,t])=>{if(!t)throw new qt(`Unable to proceed because "${e}" argument is not provided.`)});const d=yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n,{params:{method:i}})),c=d.paymentMethods.getPaymentMethodOrThrow(i,n),{initializationData:l}=c;if(!c||!c.initializationData.stripePublishableKey||!c.clientToken)throw new rt(et.MissingPaymentMethod);let u;this._stripeUPEClient=yield this._stripeScriptLoader.getStripeClient(l,d.cart.getLocale(),ka.V3,Fa,La);const h=o&&o(),{form:{getShippingAddressFields:p},shippingAddress:{getShippingAddress:m}}=this._store.getState(),y=p([],"");u=h?{variables:{colorPrimary:h.fieldInnerShadow,colorBackground:h.fieldBackground,colorText:h.labelText,colorDanger:h.fieldErrorText,colorTextSecondary:h.labelText,colorTextPlaceholder:h.fieldPlaceholderText,spacingUnit:"4px",borderRadius:"4px"},rules:{".Input":{borderColor:h.fieldBorder,color:h.fieldText,boxShadow:h.fieldInnerShadow}}}:{variables:{spacingUnit:"4px",borderRadius:"4px"}},this._stripeElements=yield this._stripeScriptLoader.getElements(this._stripeUPEClient,{clientSecret:c.clientToken,appearance:u});const g=m(),v=y.find(e=>"phone"===e.name);let f={mode:Ca.SHIPPING,allowedCountries:[a],fields:{phone:"always"},validation:{phone:{required:v&&v.required?"always":"never"}},display:{name:ba.SPLIT}};if(g){const{stateOrProvinceCode:e,countryCode:t,lastName:n,firstName:i,phone:r,address1:o,address2:a,city:d,postalCode:c}=g,l=e&&t?s(t,e):e;f=Object.assign(Object.assign({},f),{defaultValues:{firstName:i,lastName:n,phone:r,address:{line1:o,line2:a,city:d,state:l,postal_code:c,country:t}}})}let S=this._stripeElements.getElement(Da.SHIPPING);return S&&S.destroy(),S=this._stripeElements.create(Da.SHIPPING,f),S.on(za.CHANGE,e=>{if(!("isNewAddress"in e))throw new rt(et.MissingShippingAddress);(e.complete||e.isNewAddress)&&(this.sendData&&clearTimeout(this.sendData),this.sendData=setTimeout(()=>{r(Object.assign(Object.assign({},e),{phoneFieldRequired:!!v&&v.required}))},1e3))}),S.mount(`#${t}`),Promise.resolve(this._store.getState())},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}deinitialize(){return Promise.resolve(this._store.getState())}}!function(e){e.SendSignInEmailRequested="SEND_SIGNIN_EMAIL_REQUESTED",e.SendSignInEmailSucceeded="SEND_SIGNIN_EMAIL_SUCCEEDED",e.SendSignInEmailFailed="SEND_SIGNIN_EMAIL_FAILED"}(cv||(cv={}));class uv{constructor(e){this._requestSender=e}sendSignInEmail(e,t){return g(C(l(cv.SendSignInEmailRequested)),v(()=>{return n=this,i=void 0,o=function*(){const{body:n}=yield this._requestSender.sendSignInEmail(e,t);return l(cv.SendSignInEmailSucceeded,n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Je(cv.SendSignInEmailFailed,e)))}}class hv{constructor(e){this._requestSender=e}sendSignInEmail({email:e,redirectUrl:t},{timeout:n}={}){const i=Object.assign({Accept:ct.JsonV1},Xe);return this._requestSender.post("/login.php?action=passwordless_login",{body:{email:e,redirect_url:t||In(window.top?window.top.location.href:"").pathname},headers:i,timeout:n})}}class pv{constructor(e){this._messageCustomizer=e}transform(e){var t;return e.message=(t=this._messageCustomizer(e))?t.split(/(?:\r\n|\n|\r)/).map(e=>e.replace(/^\s+/gm,"")).join(" ").trim():"",e}}let mv=class{constructor(e,t,n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,_,w,I,C,b,P,O,E,A){this._store=e,this._storeProjection=t,this._extensionMessenger=n,this._extensionEventBroadcaster=i,this._b2bTokenActionCreator=r,this._billingAddressActionCreator=o,this._checkoutActionCreator=a,this._configActionCreator=s,this._customerActionCreator=d,this._consignmentActionCreator=c,this._countryActionCreator=l,this._couponActionCreator=u,this._customerStrategyActionCreator=h,this._errorActionCreator=p,this._giftCertificateActionCreator=m,this._instrumentActionCreator=y,this._orderActionCreator=g,this._paymentMethodActionCreator=v,this._paymentStrategyActionCreator=f,this._pickupOptionActionCreator=S,this._shippingCountryActionCreator=_,this._shippingStrategyActionCreator=w,this._signInEmailActionCreator=I,this._spamProtectionActionCreator=C,this._storeCreditActionCreator=b,this._subscriptionsActionCreator=P,this._formFieldsActionCreator=O,this._extensionActionCreator=E,this._workerExtensionMessenger=A,this._errorTransformer=function(e="development"===vt()){return new pv(t=>{if(!e||!function(e){return!(!e.subtype&&!e.type)}(t))return t.message;switch(t.subtype||t.type){case et.MissingConsignments:return`\n ${t.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 `;case et.MissingCart:case et.MissingCheckout:return`\n ${t.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 `;case et.MissingCheckoutConfig:return`\n ${t.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 `;case et.MissingOrder:return`\n ${t.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 `;case et.MissingOrderId:return`\n ${t.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 `;case et.MissingPaymentMethod:return`\n ${t.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 `;case cn.CustomerNotInitialized: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 ";case cn.PaymentNotInitialized:return`\n ${t.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 `;case cn.ShippingNotInitialized:return`\n ${t.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 `;default:return t.message}})}()}getState(){return this._storeProjection.getState()}notifyState(){this._storeProjection.notifyState()}subscribe(e,...t){return this._storeProjection.subscribe(e,...t)}hydrateInitialState(e){return this._dispatch(this._checkoutActionCreator.hydrateInitialState(e))}loadCheckout(e,t){return this._dispatch(e?this._checkoutActionCreator.loadCheckout(e,t):this._checkoutActionCreator.loadDefaultCheckout(t))}updateCheckout(e,t){const n=this._checkoutActionCreator.updateCheckout(e,t);return this._dispatch(n)}loadOrder(e,t){const n=this._orderActionCreator.loadOrder(e,t),i=this._formFieldsActionCreator.loadFormFields(t),r=this._configActionCreator.loadConfig(t);return Promise.all([this._dispatch(n),this._dispatch(r,{queueId:"config"}),this._dispatch(i,{queueId:"formFields"})]).then(()=>this.getState())}submitOrder(e,t){const n=this._paymentStrategyActionCreator.execute(e,t);return this._dispatch(n,{queueId:"paymentStrategy"})}finalizeOrderIfNeeded(e){const t=this._paymentStrategyActionCreator.finalize(e);return this._dispatch(t,{queueId:"paymentStrategy"})}loadPaymentMethods(e){const t=this._paymentMethodActionCreator.loadPaymentMethods(e);return this._dispatch(t,{queueId:"paymentMethods"})}loadPaymentMethodByIds(e,t){const n=this._paymentMethodActionCreator.loadPaymentMethodsById(e,t);return this._dispatch(n,{queueId:"paymentMethods"})}loadPaymentMethod(e,t){const n=this._paymentMethodActionCreator.loadPaymentMethod(e,t);return this._dispatch(n,{queueId:"paymentMethods"})}initializePayment(e){const t=this._paymentStrategyActionCreator.initialize(e);return this._dispatch(t,{queueId:"paymentStrategy"})}deinitializePayment(e){const t=this._paymentStrategyActionCreator.deinitialize(e);return this._dispatch(t,{queueId:"paymentStrategy"})}loadBillingCountries(e){const t=this._countryActionCreator.loadCountries(e);return this._dispatch(t,{queueId:"billingCountries"})}loadShippingCountries(e){const t=this._shippingCountryActionCreator.loadCountries(e);return this._dispatch(t,{queueId:"shippingCountries"})}loadPickupOptions(e){const t=this._pickupOptionActionCreator.loadPickupOptions(e);return this._dispatch(t,{queueId:"pickupOptions"})}loadBillingAddressFields(e){return this.loadBillingCountries(e)}loadShippingAddressFields(e){return this.loadShippingCountries(e)}initializeCustomer(e){const t=this._customerStrategyActionCreator.initialize(e);return this._dispatch(t,{queueId:"customerStrategy"})}deinitializeCustomer(e){const t=this._customerStrategyActionCreator.deinitialize(e);return this._dispatch(t,{queueId:"customerStrategy"})}sendSignInEmail(e,t){const n=this._signInEmailActionCreator.sendSignInEmail(e,t);return this._dispatch(n,{queueId:"signInEmail"})}getB2BToken(e){const t=this._b2bTokenActionCreator.loadB2BToken(e);return this._dispatch(t,{queueId:"b2bToken"})}createCustomerAccount(e,t){const n=this._customerActionCreator.createCustomer(e,t);return this._dispatch(n)}createCustomerAddress(e,t){const n=this._customerActionCreator.createAddress(e,t);return this._dispatch(n)}updateSubscriptions(e,t){const n=this._subscriptionsActionCreator.updateSubscriptions(e,t);return this._dispatch(n,{queueId:"subscriptions"})}continueAsGuest(e,t){const n=this._billingAddressActionCreator.continueAsGuest(e,t);return this._dispatch(n)}signInCustomer(e,t){const n=this._customerStrategyActionCreator.signIn(e,t);return this._dispatch(n,{queueId:"customerStrategy"})}signOutCustomer(e){const t=this._customerStrategyActionCreator.signOut(e);return this._dispatch(t,{queueId:"customerStrategy"})}executePaymentMethodCheckout(e){const t=this._customerStrategyActionCreator.executePaymentMethodCheckout(e);return this._dispatch(t,{queueId:"customerStrategy"})}loadShippingOptions(e){const t=this._consignmentActionCreator.loadShippingOptions(e);return this._dispatch(t)}initializeShipping(e){const t=this._shippingStrategyActionCreator.initialize(e);return this._dispatch(t,{queueId:"shippingStrategy"})}deinitializeShipping(e){const t=this._shippingStrategyActionCreator.deinitialize(e);return this._dispatch(t,{queueId:"shippingStrategy"})}selectShippingOption(e,t){const n=this._shippingStrategyActionCreator.selectOption(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}updateShippingAddress(e,t){const n=this._shippingStrategyActionCreator.updateAddress(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}createConsignments(e,t){const n=this._consignmentActionCreator.createConsignments(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}deleteConsignment(e,t){const n=this._consignmentActionCreator.deleteConsignment(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}updateConsignment(e,t){const n=this._consignmentActionCreator.updateConsignment(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}assignItemsToAddress(e,t){const n=this._consignmentActionCreator.assignItemsByAddress(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}unassignItemsToAddress(e,t){const n=this._consignmentActionCreator.unassignItemsByAddress(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}selectConsignmentShippingOption(e,t,n){const i=this._consignmentActionCreator.updateShippingOption({id:e,shippingOptionId:t},n);return this._dispatch(i,{queueId:"shippingStrategy"})}updateBillingAddress(e,t={}){const n=this._billingAddressActionCreator.updateAddress(e,t);return this._dispatch(n)}applyStoreCredit(e,t){const n=this._storeCreditActionCreator.applyStoreCredit(e,t);return this._dispatch(n)}applyCoupon(e,t){const n=this._couponActionCreator.applyCoupon(e,t);return this._dispatch(n)}removeCoupon(e,t){const n=this._couponActionCreator.removeCoupon(e,t);return this._dispatch(n)}applyGiftCertificate(e,t){const n=this._giftCertificateActionCreator.applyGiftCertificate(e,t);return this._dispatch(n)}removeGiftCertificate(e,t){const n=this._giftCertificateActionCreator.removeGiftCertificate(e,t);return this._dispatch(n)}loadInstruments(){const e=this._instrumentActionCreator.loadInstruments();return this._dispatch(e)}deleteInstrument(e){const t=this._instrumentActionCreator.deleteInstrument(e);return this._dispatch(t).then(()=>this.loadInstruments())}clearError(e){const t=this._errorActionCreator.clearError(e);return this._dispatch(t)}initializeSpamProtection(e){const t=this._spamProtectionActionCreator.initialize(e);return this._dispatch(t,{queueId:"spamProtection"})}executeSpamCheck(){const e=this._spamProtectionActionCreator.verifyCheckoutSpamProtection();return this._dispatch(e,{queueId:"spamProtection"})}loadExtensions(e){const t=this._extensionActionCreator.loadExtensions(e);return this._dispatch(t,{queueId:"extensions"})}renderExtension(e,t){return n=this,i=void 0,o=function*(){const n=this._extensionActionCreator.renderExtension(e,t,this._workerExtensionMessenger),i=yield this._dispatch(n,{queueId:"extensions"});return this._extensionEventBroadcaster.listen(),i},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}clearExtensionCache(e){this._extensionMessenger.clearCacheByRegion(e)}postMessageToExtension(e,t){this._extensionMessenger.post(e,t)}handleExtensionCommand(e,t,n){return this._extensionMessenger.listenForCommand(e,t,n)}handleExtensionQuery(e,t,n){return this._extensionMessenger.listenForQuery(e,t,n)}_dispatch(e,t){return this._store.dispatch(e,t).then(()=>this.getState()).catch(e=>{throw this._errorTransformer.transform(e)})}};mv=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],mv);const yv=mv;function gv(e){return(...t)=>{const n=t.pop();return e(...t,(...e)=>{const t=n(...e);return"function"==typeof t?Pe(t):t})}}const vv=gv(Re),fv=gv(Fe(Le,(e,t)=>Be(e,t)));class Sv extends Ot{constructor(e,t){super(e,{message:t||"An unexpected error has occurred. The checkout process cannot continue as a result."}),this.name="UnrecoverableError",this.type="unrecoverable"}}function _v(e){return e.reduce((e,t)=>t?[...e,t]:e,[]).join(" ")}class wv extends Ot{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}class Iv{constructor(){this._factoryMethods={},this.register("default",(e,t)=>new Ot(e,{message:t})),this.register("internal",(e,t)=>function(e,t){const{body:n}=e,{errors:i=[]}=n;return new Ot(e,{message:_v(i)||n.detail||n.title||t,errors:i.length?i.map(e=>({code:n.type,message:e})):[{code:n.type,message:n.detail||n.title}]})}(e,t)),this.register("storefront",(e,t)=>function(e,t){const{body:n}=e;return new Ot(e,{message:t||n.detail||n.title,errors:[{code:n.code||n.type,message:n.detail||n.title}]})}(e,t)),this.register("payment",(e,t)=>ly(e,t)),this.register("timeout",e=>new wv(e))}register(e,t){this._factoryMethods[e]=t}createError(e,t){return(this._factoryMethods[this._getType(e)]||this._factoryMethods.default)(e,t)}_getType(e){if(0===e.status)return"timeout";if(this._isStorefrontErrorResponseBody(e.body))return"storefront";if(this._isInternalErrorResponseBody(e.body)){const t=re(e.body.type.split("/"));return t&&this._factoryMethods[t]?t:"internal"}const t=re(e.body&&e.body.errors);return t&&t.code&&this._factoryMethods[t.code]?t.code:"payment"}_isStorefrontErrorResponseBody(e){const t=e;return!this._isInternalErrorResponseBody(e)&&"string"==typeof t.title&&"string"==typeof t.type&&"number"==typeof t.status&&"string"==typeof t.detail}_isInternalErrorResponseBody(e){const t=e;return"object"==typeof t.errors&&"string"==typeof t.title&&"string"==typeof t.type&&"number"==typeof t.status}}function Cv(e,t){return Array.isArray(e)?e.map(e=>Cv(e,t)):Q(e)?Se(ue(e,t),(e,n,i)=>{e[i]=Cv(n,t)},{}):e}function bv(e,t){return function(e){return e.type===pt.ClearError}(t)?Cv(e,e=>e===t.payload):e}function Pv(e,t,n){return e===t||(e&&t&&"object"==typeof e&&"object"==typeof t?Array.isArray(e)&&Array.isArray(t)?function(e,t,n){if(e.length!==t.length)return!1;for(let i=0,r=e.length;ivoid 0!==e.id&&e.id===t.id}=i||{};if(!t)return n;if(!n||t===n)return t;let o=0,a=0;const s=(e,t,n)=>(o+=e===t?1:0,a+=e===n?1:0,e),d=n.map((n,i)=>{const o=t&&t[i];return Rg(o)&&Rg(n)?r(o,n)?s(Bv(o,n),o,n):s(Mv(o,n),o,n):W(o)&&W(n)?s(e(o,n),o,n):s(Mv(o,n),o,n)});return o===n.length&&t&&t.length===n.length?t:a===n.length?n:d},Bv=function e(t,n){return t?n&&t!==n?Object.keys(n).reduce((t,i)=>{const r=t[i],o=n[i];return Rg(r)&&Rg(o)?Ov(t,i,e(r,o)):W(r)&&W(o)?Ov(t,i,Lv(r,o)):Ov(t,i,o)},t):t:n},jv={errors:{},statuses:{}};function Uv(e=jv,t){return d({data:qv,errors:c(Gv,bv),statuses:Vv})(e,t)}function qv(e,t){var n,i;switch(t.type){case tt.UpdateBillingAddressSucceeded:case $t.LoadCheckoutSucceeded:case _g.CreateConsignmentsSucceeded:case _g.DeleteConsignmentSucceeded:case _g.UpdateConsignmentSucceeded:case _g.UpdateShippingOptionSucceeded:case _g.LoadShippingOptionsSucceeded:case kt.ApplyCouponSucceeded:case kt.RemoveCouponSucceeded:case Nt.ApplyGiftCertificateSucceeded:case Nt.RemoveGiftCertificateSucceeded:return Bv(e,t.payload&&t.payload.cart);case Yt.HydrateInitialState:return Bv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.cart);default:return e}}function Vv(e=jv.statuses,t){switch(t.type){case $t.LoadCheckoutRequested:return Ov(e,"isLoading",!0);case $t.LoadCheckoutFailed:case $t.LoadCheckoutSucceeded:return Ov(e,"isLoading",!1);default:return e}}function Gv(e=jv.errors,t){switch(t.type){case $t.LoadCheckoutRequested:case $t.LoadCheckoutSucceeded:return Ov(e,"loadError",void 0);case $t.LoadCheckoutFailed:return Ov(e,"loadError",t.payload);default:return e}}var Hv;!function(e){e.InitializeButtonFailed="INITIALIZE_BUTTON_FAILED",e.InitializeButtonRequested="INITIALIZE_BUTTON_REQUESTED",e.InitializeButtonSucceeded="INITIALIZE_BUTTON_SUCCEEDED",e.DeinitializeButtonFailed="DEINITIALIZE_BUTTON_FAILED",e.DeinitializeButtonRequested="DEINITIALIZE_BUTTON_REQUESTED",e.DeinitializeButtonSucceeded="DEINITIALIZE_BUTTON_SUCCEEDED"}(Hv||(Hv={}));const Wv={data:{},errors:{},statuses:{}},$v={initializedContainers:{}},Yv={},Kv={};function Jv(e=Wv,t){return t.meta&&t.meta.methodId?d({data:d({[t.meta.methodId]:Zv}),errors:d({[t.meta.methodId]:Qv}),statuses:d({[t.meta.methodId]:Xv})})(e,t):e}function Zv(e=$v,t){switch(t.type){case Hv.InitializeButtonSucceeded:return t.meta&&t.meta.containerId?Bv(e,{initializedContainers:{[t.meta.containerId]:!0}}):e;case Hv.DeinitializeButtonSucceeded:return Ov(e,"initializedContainers",{})}return e}function Qv(e=Yv,t){switch(t.type){case Hv.InitializeButtonRequested:case Hv.InitializeButtonSucceeded:return Ov(e,"initializeError",void 0);case Hv.InitializeButtonFailed:return Ov(e,"initializeError",t.payload);case Hv.DeinitializeButtonRequested:case Hv.DeinitializeButtonSucceeded:return Ov(e,"deinitializeError",void 0);case Hv.DeinitializeButtonFailed:return Ov(e,"deinitializeError",t.payload);default:return e}}function Xv(e=Kv,t){switch(t.type){case Hv.InitializeButtonRequested:return Ov(e,"isInitializing",!0);case Hv.InitializeButtonFailed:case Hv.InitializeButtonSucceeded:return Ov(e,"isInitializing",!1);case Hv.DeinitializeButtonRequested:return Ov(e,"isDeinitializing",!0);case Hv.DeinitializeButtonFailed:case Hv.DeinitializeButtonSucceeded:return Ov(e,"isDeinitializing",!1);default:return e}}const ef={meta:{},errors:{},statuses:{}};function tf(e=ef,t){return d({data:nf,errors:c(rf,bv),statuses:of})(e,t)}function nf(e,t){var n,i;switch(t.type){case Ct.LoadConfigSucceeded:return Bv(e,t.payload);case Yt.HydrateInitialState:{const r=Bv(e,null===(n=t.payload)||void 0===n?void 0:n.config);return r&&(null===(i=t.payload)||void 0===i?void 0:i.b2bApiSettings)?Object.assign(Object.assign({},r),{storeConfig:Object.assign(Object.assign({},r.storeConfig),{b2bApiSettings:t.payload.b2bApiSettings})}):r}default:return e}}function rf(e=ef.errors,t){switch(t.type){case Ct.LoadConfigSucceeded:return Ov(e,"loadError",void 0);case Ct.LoadConfigFailed:return Ov(e,"loadError",t.payload);default:return e}}function of(e=ef.statuses,t){switch(t.type){case Ct.LoadConfigRequested:return Ov(e,"isLoading",!0);case Ct.LoadConfigSucceeded:case Ct.LoadConfigFailed:return Ov(e,"isLoading",!1);default:return e}}const af={errors:{},statuses:{}};function sf(e=af,t){return d({data:df,errors:c(cf,bv),statuses:lf})(e,t)}function df(e,t){var n,i;switch(t.type){case $t.LoadCheckoutSucceeded:case kt.ApplyCouponSucceeded:case _g.UpdateShippingOptionSucceeded:case kt.RemoveCouponSucceeded:case Mm.LoadOrderSucceeded:return Lv(e,t.payload&&t.payload.coupons);case Yt.HydrateInitialState:return Lv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.coupons);default:return e}}function cf(e={},t){switch(t.type){case kt.ApplyCouponRequested:case kt.ApplyCouponSucceeded:return Ov(e,"applyCouponError",void 0);case kt.ApplyCouponFailed:return Ov(e,"applyCouponError",t.payload);case kt.RemoveCouponRequested:case kt.RemoveCouponSucceeded:return Ov(e,"removeCouponError",void 0);case kt.RemoveCouponFailed:return Ov(e,"removeCouponError",t.payload);default:return e}}function lf(e={},t){switch(t.type){case kt.ApplyCouponRequested:return Ov(e,"isApplyingCoupon",!0);case kt.ApplyCouponSucceeded:case kt.ApplyCouponFailed:return Ov(e,"isApplyingCoupon",!1);case kt.RemoveCouponRequested:return Ov(e,"isRemovingCoupon",!0);case kt.RemoveCouponSucceeded:case kt.RemoveCouponFailed:return Ov(e,"isRemovingCoupon",!1);default:return e}}const uf={errors:{},statuses:{}};function hf(e=uf,t){return d({data:pf,errors:c(mf,bv),statuses:yf})(e,t)}function pf(e,t){var n,i;switch(t.type){case $t.LoadCheckoutSucceeded:case _g.CreateConsignmentsSucceeded:case _g.UpdateConsignmentSucceeded:case _g.DeleteConsignmentSucceeded:case _g.UpdateShippingOptionSucceeded:case kt.ApplyCouponSucceeded:case kt.RemoveCouponSucceeded:case Nt.ApplyGiftCertificateSucceeded:case Nt.RemoveGiftCertificateSucceeded:return Lv(e,t.payload&&t.payload.giftCertificates);case Yt.HydrateInitialState:return Lv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.giftCertificates);default:return e}}function mf(e=uf.errors,t){switch(t.type){case Nt.ApplyGiftCertificateRequested:case Nt.ApplyGiftCertificateSucceeded:return Ov(e,"applyGiftCertificateError",void 0);case Nt.ApplyGiftCertificateFailed:return Ov(e,"applyGiftCertificateError",t.payload);case Nt.RemoveGiftCertificateRequested:case Nt.RemoveGiftCertificateSucceeded:return Ov(e,"removeGiftCertificateError",void 0);case Nt.RemoveGiftCertificateFailed:return Ov(e,"removeGiftCertificateError",t.payload);default:return e}}function yf(e=uf.statuses,t){switch(t.type){case Nt.ApplyGiftCertificateRequested:return Ov(e,"isApplyingGiftCertificate",!0);case Nt.ApplyGiftCertificateSucceeded:case Nt.ApplyGiftCertificateFailed:return Ov(e,"isApplyingGiftCertificate",!1);case Nt.RemoveGiftCertificateRequested:return Ov(e,"isRemovingGiftCertificate",!0);case Nt.RemoveGiftCertificateSucceeded:case Nt.RemoveGiftCertificateFailed:return Ov(e,"isRemovingGiftCertificate",!1);default:return e}}const gf={errors:{},statuses:{}};function vf(e=gf,t){return d({data:ff,errors:c(Sf,bv),statuses:_f})(e,t)}function ff(e,t){var n,i;switch(t.type){case tt.ContinueAsGuestSucceeded:case $t.LoadCheckoutSucceeded:return Bv(e,t.payload&&t.payload.customer);case Rt.CreateCustomerAddressSucceeded:return Bv(e,t.payload);case Yt.HydrateInitialState:return Bv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.customer);default:return e}}function Sf(e=gf.errors,t){switch(t.type){case Rt.CreateCustomerRequested:case Rt.CreateCustomerSucceeded:return Ov(e,"createError",void 0);case Rt.CreateCustomerFailed:return Ov(e,"createError",t.payload);case Rt.CreateCustomerAddressRequested:case Rt.CreateCustomerAddressSucceeded:return Ov(e,"createAddressError",void 0);case Rt.CreateCustomerAddressFailed:return Ov(e,"createAddressError",t.payload);default:return e}}function _f(e=gf.statuses,t){switch(t.type){case Rt.CreateCustomerRequested:return Ov(e,"isCreating",!0);case Rt.CreateCustomerFailed:case Rt.CreateCustomerSucceeded:return Ov(e,"isCreating",!1);case Rt.CreateCustomerAddressRequested:return Ov(e,"isCreatingAddress",!0);case Rt.CreateCustomerAddressFailed:case Rt.CreateCustomerAddressSucceeded:return Ov(e,"isCreatingAddress",!1);default:return e}}const wf={data:{},errors:{},statuses:{}};function If(e=wf,t){return d({data:Cf,errors:c(bf,bv),statuses:Pf})(e,t)}function Cf(e=wf.data,t){switch(t.type){case Wt.InitializeSucceeded:return Bv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!0}});case Wt.DeinitializeSucceeded:return Bv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!1}})}return e}function bf(e=wf.errors,t){switch(t.type){case Wt.InitializeRequested:case Wt.InitializeSucceeded:return Bv(e,{initializeErrors:Object.assign({},e.initializeErrors),initializeMethodId:e.initializeMethodId?e.initializeMethodId:void 0});case Wt.InitializeFailed:return Bv(e,{initializeErrors:Object.assign(Object.assign({},e.initializeErrors),{[t.meta&&t.meta.methodId]:t.payload}),initializeMethodId:t.meta&&t.meta.methodId});case Wt.DeinitializeRequested:case Wt.DeinitializeSucceeded:return Bv(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Wt.DeinitializeFailed:return Bv(e,{deinitializeError:t.payload,deinitializeMethodId:t.meta&&t.meta.methodId});case Wt.SignInRequested:case Wt.SignInSucceeded:return Bv(e,{signInError:void 0,signInMethodId:void 0});case Wt.SignInFailed:return Bv(e,{signInError:t.payload,signInMethodId:t.meta&&t.meta.methodId});case Wt.SignOutRequested:case Wt.SignOutSucceeded:return Bv(e,{signOutError:void 0,signOutMethodId:void 0});case Wt.SignOutFailed:return Bv(e,{signOutError:t.payload,signOutMethodId:t.meta&&t.meta.methodId});case Wt.ExecutePaymentMethodCheckoutRequested:case Wt.ExecutePaymentMethodCheckoutSucceeded:return Bv(e,{executePaymentMethodCheckoutError:void 0,executePaymentMethodCheckoutMethodId:void 0});case Wt.ExecutePaymentMethodCheckoutFailed:return Bv(e,{executePaymentMethodCheckoutError:t.payload,executePaymentMethodCheckoutMethodId:t.meta&&t.meta.methodId});case Wt.WidgetInteractionStarted:case Wt.WidgetInteractionFinished:return Bv(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Wt.WidgetInteractionFailed:return Bv(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta.methodId});default:return e}}function Pf(e=wf.statuses,t){switch(t.type){case Wt.InitializeRequested:return Bv(e,{isInitializing:!0,initializeMethodId:t.meta&&t.meta.methodId});case Wt.InitializeFailed:case Wt.InitializeSucceeded:return Bv(e,{isInitializing:!1,initializeMethodId:void 0});case Wt.DeinitializeRequested:return Bv(e,{isDeinitializing:!0,deinitializeMethodId:t.meta&&t.meta.methodId});case Wt.DeinitializeFailed:case Wt.DeinitializeSucceeded:return Bv(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Wt.SignInRequested:return Bv(e,{isSigningIn:!0,signInMethodId:t.meta&&t.meta.methodId});case Wt.SignInFailed:case Wt.SignInSucceeded:return Bv(e,{isSigningIn:!1,signInMethodId:void 0});case Wt.SignOutRequested:return Bv(e,{isSigningOut:!0,signOutMethodId:t.meta&&t.meta.methodId});case Wt.SignOutFailed:case Wt.SignOutSucceeded:return Bv(e,{isSigningOut:!1,signOutMethodId:void 0});case Wt.ExecutePaymentMethodCheckoutRequested:return Bv(e,{isExecutingPaymentMethodCheckout:!0,executePaymentMethodCheckoutMethodId:t.meta&&t.meta.methodId});case Wt.ExecutePaymentMethodCheckoutFailed:case Wt.ExecutePaymentMethodCheckoutSucceeded:return Bv(e,{isExecutingPaymentMethodCheckout:!1,executePaymentMethodCheckoutMethodId:void 0});case Wt.WidgetInteractionStarted:return Bv(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta.methodId});case Wt.WidgetInteractionFinished:case Wt.WidgetInteractionFailed:return Bv(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const Of={errors:{},statuses:{}};function Ef(e=Of,t){return d({data:Af,errors:c(Tf,bv),statuses:kf})(e,t)}function Af(e,t){var n;return t.type===ln.LoadExtensionsSucceeded?Lv(e,t.payload):t.type===Yt.HydrateInitialState?Lv(e,null===(n=t.payload)||void 0===n?void 0:n.extensions):e}function Tf(e=Of.errors,t){switch(t.type){case ln.LoadExtensionsRequested:case ln.LoadExtensionsSucceeded:return Ov(e,"loadError",void 0);case ln.RenderExtensionRequested:case ln.RenderExtensionSucceeded:return Ov(e,"renderError",void 0);case ln.LoadExtensionsFailed:return Ov(e,"loadError",t.payload);case ln.RenderExtensionFailed:return Ov(e,"renderError",t.payload);default:return e}}function kf(e=Of.statuses,t){switch(t.type){case ln.LoadExtensionsRequested:return Ov(e,"isLoading",!0);case ln.LoadExtensionsSucceeded:case ln.LoadExtensionsFailed:return Ov(e,"isLoading",!1);default:return e}}const Df={errors:{},statuses:{}};function Mf(e=Df,t){return d({data:zf,extraFields:Nf,errors:c(xf,bv),statuses:Rf})(e,t)}function zf(e,t){var n;switch(t.type){case tn.LoadFormFieldsSucceeded:return Bv(e,t.payload);case Yt.HydrateInitialState:return Bv(e,null===(n=t.payload)||void 0===n?void 0:n.formFields);default:return e}}function Nf(e,t){var n,i;return t.type===Yt.HydrateInitialState&&null!==(i=null===(n=t.payload)||void 0===n?void 0:n.extraFields)&&void 0!==i?i:e}function xf(e=Df.errors,t){switch(t.type){case tn.LoadFormFieldsSucceeded:return Ov(e,"loadError",void 0);case tn.LoadFormFieldsFailed:return Ov(e,"loadError",t.payload);default:return e}}function Rf(e=Df.statuses,t){switch(t.type){case tn.LoadFormFieldsRequested:return Ov(e,"isLoading",!0);case tn.LoadFormFieldsSucceeded:case tn.LoadFormFieldsFailed:return Ov(e,"isLoading",!1);default:return e}}const Ff={errors:{},statuses:{}};function Lf(e=Ff,t){return d({data:Bf,errors:c(jf,bv),statuses:Uf})(e,t)}function Bf(e,t){return t.type===Dm.LoadCountriesSucceeded?Lv(e,t.payload):e}function jf(e=Ff.errors,t){switch(t.type){case Dm.LoadCountriesRequested:case Dm.LoadCountriesSucceeded:return Ov(e,"loadError",void 0);case Dm.LoadCountriesFailed:return Ov(e,"loadError",t.payload);default:return e}}function Uf(e=Ff.statuses,t){switch(t.type){case Dm.LoadCountriesRequested:return Ov(e,"isLoading",!0);case Dm.LoadCountriesSucceeded:case Dm.LoadCountriesFailed:return Ov(e,"isLoading",!1);default:return e}}const qf={errors:{},meta:{},statuses:{}};function Vf(e=qf,t){return d({data:Gf,errors:c(Wf,bv),meta:Hf,statuses:$f})(e,t)}function Gf(e,t){switch(t.type){case Mm.LoadOrderSucceeded:case Mm.LoadOrderPaymentsSucceeded:return Bv(e,le(t.payload,["billingAddress","coupons"]));default:return e}}function Hf(e,t){switch(t.type){case Mm.FinalizeOrderSucceeded:case Mm.SubmitOrderSucceeded:return Bv(e,Object.assign(Object.assign({},t.meta),{callbackUrl:t.payload&&t.payload.order.callbackUrl,orderToken:t.payload&&t.payload.order.token,payment:t.payload&&t.payload.order&&t.payload.order.payment}));default:return e}}function Wf(e=qf.errors,t){switch(t.type){case Mm.LoadOrderRequested:case Mm.LoadOrderSucceeded:case Mm.LoadOrderPaymentsSucceeded:case Mm.LoadOrderPaymentsRequested:return Ov(e,"loadError",void 0);case Mm.LoadOrderFailed:case Mm.LoadOrderPaymentsFailed:return Ov(e,"loadError",t.payload);default:return e}}function $f(e=qf.statuses,t){switch(t.type){case Mm.LoadOrderRequested:case Mm.LoadOrderPaymentsRequested:return Ov(e,"isLoading",!0);case Mm.LoadOrderSucceeded:case Mm.LoadOrderFailed:case Mm.LoadOrderPaymentsSucceeded:case Mm.LoadOrderPaymentsFailed:return Ov(e,"isLoading",!1);default:return e}}const Yf={};function Kf(e=Yf,t){return d({data:Jf})(e,t)}function Jf(e,t){switch(t.type){case Mm.LoadOrderPaymentsSucceeded:case Mm.LoadOrderSucceeded:return Mv(e,t.payload&&t.payload.billingAddress);default:return e}}function Zf(e={},t){return d({data:Qf})(e,t)}function Qf(e,t){return t.type===vy.SubmitPaymentSucceeded?t.payload:e}const Xf={errors:{},statuses:{}};function eS(e=Xf,t){return d({data:tS,errors:c(iS,bv),meta:nS,statuses:rS})(e,t)}function tS(e,t){switch(t.type){case qm.LoadPaymentMethodSucceeded:return function(e,t,n){if(!t)return e;const i=pe(t,"id"),r="object"==typeof n?me(n):n||i,o=j(e,r),a=[...e];if(-1===o)a.push(t);else{const n=e[o];a[o]=Rg(n)&&Rg(t)?Bv(n,t):t}return a}(e||[],t.payload,t.payload&&{id:t.payload.id,gateway:t.payload.gateway});case qm.LoadPaymentMethodsSucceeded:return Lv(e,t.payload,{matchObject:(e,t)=>e.id===t.id&&e.gateway===t.gateway});default:return e}}function nS(e,t){return t.type===qm.LoadPaymentMethodsSucceeded?Bv(e,t.meta):e}function iS(e=Xf.errors,t){switch(t.type){case qm.LoadPaymentMethodsRequested:case qm.LoadPaymentMethodsSucceeded:return Ov(e,"loadError",void 0);case qm.LoadPaymentMethodsFailed:return Ov(e,"loadError",t.payload);case qm.LoadPaymentMethodRequested:case qm.LoadPaymentMethodSucceeded:return Bv(e,{loadMethodId:void 0,loadMethodError:void 0});case qm.LoadPaymentMethodFailed:return Bv(e,{loadMethodId:t.meta.methodId,loadMethodError:t.payload});default:return e}}function rS(e=Xf.statuses,t){switch(t.type){case qm.LoadPaymentMethodsRequested:return Ov(e,"isLoading",!0);case qm.LoadPaymentMethodsSucceeded:case qm.LoadPaymentMethodsFailed:return Ov(e,"isLoading",!1);case qm.LoadPaymentMethodRequested:return Bv(e,{isLoadingMethod:!0,loadMethodId:t.meta.methodId});case qm.LoadPaymentMethodSucceeded:case qm.LoadPaymentMethodFailed:return Bv(e,{isLoadingMethod:!1,loadMethodId:void 0});default:return e}}const oS={data:{},errors:{},statuses:{}};function aS(e=oS,t){return d({data:sS,errors:c(dS,bv),statuses:cS})(e,t)}function sS(e=oS.data,t){switch(t.type){case Km.InitializeSucceeded:if(t.meta){const{methodId:n,gatewayId:i}=t.meta,r=i?`${n}.${i}`:n;return Bv(e,{[r]:{isInitialized:!0}})}break;case Km.DeinitializeSucceeded:if(t.meta){const{methodId:n,gatewayId:i}=t.meta,r=i?`${n}.${i}`:n;return Bv(e,{[r]:{isInitialized:!1}})}}return e}function dS(e=oS.errors,t){switch(t.type){case Km.InitializeRequested:case Km.InitializeSucceeded:return Bv(e,{initializeError:void 0,initializeMethodId:void 0});case Km.InitializeFailed:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return Bv(e,{initializeError:t.payload,initializeMethodId:n})}case Km.DeinitializeRequested:case Km.DeinitializeSucceeded:return Bv(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Km.DeinitializeFailed:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return Bv(e,{deinitializeError:t.payload,deinitializeMethodId:n})}case Km.ExecuteRequested:case Km.ExecuteSucceeded:return Bv(e,{executeError:void 0,executeMethodId:void 0});case Km.ExecuteFailed:return Bv(e,{executeError:t.payload,executeMethodId:t.meta&&t.meta.methodId});case Km.FinalizeRequested:case Km.FinalizeSucceeded:return Bv(e,{finalizeError:void 0,finalizeMethodId:void 0});case Km.FinalizeFailed:return Bv(e,{finalizeError:t.payload,finalizeMethodId:t.meta&&t.meta.methodId});case Km.WidgetInteractionStarted:case Km.WidgetInteractionFinished:return Bv(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Km.WidgetInteractionFailed:return Bv(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta.methodId});default:return e}}function cS(e=oS.statuses,t){switch(t.type){case Km.InitializeRequested:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return Bv(e,{isInitializing:!0,initializeMethodId:n})}case Km.InitializeFailed:case Km.InitializeSucceeded:return Bv(e,{isInitializing:!1,initializeMethodId:void 0});case Km.DeinitializeRequested:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return Bv(e,{isDeinitializing:!0,deinitializeMethodId:n})}case Km.DeinitializeFailed:case Km.DeinitializeSucceeded:return Bv(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Km.ExecuteRequested:return Bv(e,{isExecuting:!0,executeMethodId:t.meta&&t.meta.methodId});case Km.ExecuteFailed:case Km.ExecuteSucceeded:return Bv(e,{isExecuting:!1,executeMethodId:void 0});case Km.FinalizeRequested:return Bv(e,{isFinalizing:!0,finalizeMethodId:t.meta&&t.meta.methodId});case Km.FinalizeFailed:case Km.FinalizeSucceeded:return Bv(e,{isFinalizing:!1,finalizeMethodId:void 0});case Km.WidgetInteractionStarted:return Bv(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta.methodId});case Km.WidgetInteractionFinished:case Km.WidgetInteractionFailed:return Bv(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const lS={data:{}};function uS(e=lS,t){return d({data:hS})(e,t)}function hS(e=lS.data,t){return t.type===mg.UpdatePaymentProviderCustomer?Bv(e,t.payload):e}const pS={data:[],errors:{},statuses:{}};function mS(e=pS,t){return d({data:yS,errors:c(vS,bv),meta:gS,statuses:fS})(e,t)}function yS(e=pS.data,t){return t.type===Ug.LoadInstrumentsSucceeded?Lv(e,t.payload&&t.payload.vaultedInstruments||[]):e}function gS(e,t){switch(t.type){case Ug.LoadInstrumentsSucceeded:case Ug.DeleteInstrumentSucceeded:return Bv(e,t.meta);default:return e}}function vS(e=pS.errors,t){switch(t.type){case Ug.LoadInstrumentsRequested:case Ug.LoadInstrumentsSucceeded:return Ov(e,"loadError",void 0);case Ug.DeleteInstrumentRequested:case Ug.DeleteInstrumentSucceeded:return Bv(e,{deleteError:void 0,failedInstrument:void 0});case Ug.LoadInstrumentsFailed:return Ov(e,"loadError",t.payload);case Ug.DeleteInstrumentFailed:return Bv(e,{deleteError:t.payload,failedInstrument:t.meta.instrumentId});default:return e}}function fS(e=pS.statuses,t){switch(t.type){case Ug.LoadInstrumentsRequested:return Ov(e,"isLoading",!0);case Ug.DeleteInstrumentRequested:return Bv(e,{isDeleting:!0,deletingInstrument:t.meta.instrumentId});case Ug.LoadInstrumentsSucceeded:case Ug.LoadInstrumentsFailed:return Ov(e,"isLoading",!1);case Ug.DeleteInstrumentSucceeded:case Ug.DeleteInstrumentFailed:return Bv(e,{isDeleting:!1,deletingInstrument:void 0});default:return e}}const SS={data:{}};function _S(e=SS,t){return t.meta&&t.meta.methodId?d({data:d({[t.meta.methodId]:wS})})(e,t):e}function wS(e,t){switch(t.type){case yg.InitializeRemoteBillingSucceeded:return Ov(e,"billing",t.payload&&t.payload.billing);case yg.InitializeRemoteShippingSucceeded:return Ov(e,"shipping",t.payload&&t.payload.shipping);case yg.LoadRemoteSettingsSucceeded:return Ov(e,"settings",t.payload);case yg.UpdateRemoteCheckout:return Bv(e,t.payload);default:return e}}const IS={errors:{updateShippingOptionError:{},updateError:{},deleteError:{}},statuses:{isUpdating:{},isUpdatingShippingOption:{},isDeleting:{}}};function CS(e=IS,t){return d({data:bS,errors:c(PS,bv),statuses:OS})(e,t)}function bS(e,t){var n,i;switch(t.type){case $t.LoadCheckoutSucceeded:case _g.LoadShippingOptionsSucceeded:case _g.CreateConsignmentsSucceeded:case _g.UpdateConsignmentSucceeded:case _g.DeleteConsignmentSucceeded:case _g.UpdateShippingOptionSucceeded:case kt.ApplyCouponSucceeded:case kt.RemoveCouponSucceeded:return Lv(e,t.payload&&t.payload.consignments);case Rt.SignOutCustomerSucceeded:return Lv(e,[]);case Yt.HydrateInitialState:return Lv(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.consignments);default:return e}}function PS(e=IS.errors,t){switch(t.type){case $t.LoadCheckoutRequested:case $t.LoadCheckoutSucceeded:case _g.LoadShippingOptionsSucceeded:case _g.LoadShippingOptionsRequested:return Ov(e,"loadError",void 0);case $t.LoadCheckoutFailed:case _g.LoadShippingOptionsFailed:return Ov(e,"loadError",t.payload);case _g.CreateConsignmentsRequested:case _g.CreateConsignmentsSucceeded:return Ov(e,"createError",void 0);case _g.CreateConsignmentsFailed:return Ov(e,"createError",t.payload);case _g.UpdateConsignmentSucceeded:case _g.UpdateConsignmentRequested:return t.meta?Bv(e,{updateError:{[t.meta.id]:void 0}}):e;case _g.UpdateConsignmentFailed:return t.meta?Bv(e,{updateError:{[t.meta.id]:t.payload}}):e;case _g.DeleteConsignmentSucceeded:case _g.DeleteConsignmentRequested:return t.meta?Bv(e,{deleteError:{[t.meta.id]:void 0}}):e;case _g.DeleteConsignmentFailed:return t.meta?Bv(e,{deleteError:{[t.meta.id]:t.payload}}):e;case _g.UpdateShippingOptionRequested:case _g.UpdateShippingOptionSucceeded:return t.meta?Bv(e,{updateShippingOptionError:{[t.meta.id]:void 0}}):e;case _g.UpdateShippingOptionFailed:return t.meta?Bv(e,{updateShippingOptionError:{[t.meta.id]:t.payload}}):e;default:return e}}function OS(e=IS.statuses,t){switch(t.type){case $t.LoadCheckoutRequested:return Ov(e,"isLoading",!0);case _g.LoadShippingOptionsRequested:return Ov(e,"isLoadingShippingOptions",!0);case $t.LoadCheckoutSucceeded:case $t.LoadCheckoutFailed:return Ov(e,"isLoading",!1);case _g.LoadShippingOptionsSucceeded:case _g.LoadShippingOptionsFailed:return Ov(e,"isLoadingShippingOptions",!1);case _g.CreateConsignmentsRequested:return Ov(e,"isCreating",!0);case _g.CreateConsignmentsSucceeded:case _g.CreateConsignmentsFailed:return Ov(e,"isCreating",!1);case _g.UpdateConsignmentRequested:return t.meta?Bv(e,{isUpdating:{[t.meta.id]:!0}}):e;case _g.UpdateConsignmentSucceeded:case _g.UpdateConsignmentFailed:return t.meta?Bv(e,{isUpdating:{[t.meta.id]:!1}}):e;case _g.DeleteConsignmentRequested:return t.meta?Bv(e,{isDeleting:{[t.meta.id]:!0}}):e;case _g.DeleteConsignmentSucceeded:case _g.DeleteConsignmentFailed:return t.meta?Bv(e,{isDeleting:{[t.meta.id]:!1}}):e;case _g.UpdateShippingOptionRequested:return t.meta?Bv(e,{isUpdatingShippingOption:{[t.meta.id]:!0}}):e;case _g.UpdateShippingOptionSucceeded:case _g.UpdateShippingOptionFailed:return t.meta?Bv(e,{isUpdatingShippingOption:{[t.meta.id]:!1}}):e;default:return e}}function ES(e,t){const n={};return Object.keys(e).forEach(i=>{const r=e[i],o=t?`${t}.${i}`:i;"object"==typeof r?Object.assign(n,ES(r,o)):n[o]=r}),n}function AS(e){return Object.keys(e).sort().reduce((t,n)=>Object.assign(Object.assign({},t),{[n]:e[n]}),{})}const TS={errors:{},statuses:{}};function kS(e=TS,t){return d({data:DS,errors:c(MS,bv),statuses:zS})(e,t)}function DS(e,t){if(t.type!==$g.LoadPickupOptionsSucceeded)return e;if(t.meta){const n=AS(ES({consignmentId:t.meta.consignmentId,searchArea:t.meta.searchArea}));return Ov(e,btoa(`${JSON.stringify(n)}`),t.payload)}}function MS(e=TS.errors,t){switch(t.type){case $g.LoadPickupOptionsRequested:case $g.LoadPickupOptionsSucceeded:return Ov(e,"loadError",void 0);case $g.LoadPickupOptionsFailed:return Ov(e,"loadError",t.payload);default:return e}}function zS(e=TS.statuses,t){switch(t.type){case $g.LoadPickupOptionsRequested:return Ov(e,"isLoading",!0);case $g.LoadPickupOptionsSucceeded:case $g.LoadPickupOptionsFailed:return Ov(e,"isLoading",!1);default:return e}}const NS={errors:{},statuses:{}};function xS(e=NS,t){return d({data:RS,errors:c(FS,bv),statuses:LS})(e,t)}function RS(e,t){return t.type===Og.LoadShippingCountriesSucceeded?Lv(e,t.payload):e}function FS(e=NS.errors,t){switch(t.type){case Og.LoadShippingCountriesRequested:case Og.LoadShippingCountriesSucceeded:return Ov(e,"loadError",void 0);case Og.LoadShippingCountriesFailed:return Ov(e,"loadError",t.payload);default:return e}}function LS(e=NS.statuses,t){switch(t.type){case Og.LoadShippingCountriesRequested:return Ov(e,"isLoading",!0);case Og.LoadShippingCountriesSucceeded:case Og.LoadShippingCountriesFailed:return Ov(e,"isLoading",!1);default:return e}}const BS={data:{},errors:{},statuses:{}};function jS(e=BS,t){return d({data:US,errors:c(qS,bv),statuses:VS})(e,t)}function US(e=BS.data,t){switch(t.type){case Yg.InitializeSucceeded:return Bv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!0}});case Yg.DeinitializeSucceeded:return Bv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!1}})}return e}function qS(e=BS.errors,t){switch(t.type){case Yg.InitializeRequested:case Yg.InitializeSucceeded:return Bv(e,{initializeError:void 0,initializeMethodId:void 0});case Yg.InitializeFailed:return Bv(e,{initializeError:t.payload,initializeMethodId:t.meta&&t.meta.methodId});case Yg.DeinitializeRequested:case Yg.DeinitializeSucceeded:return Bv(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Yg.DeinitializeFailed:return Bv(e,{deinitializeError:t.payload,deinitializeMethodId:t.meta&&t.meta.methodId});case Yg.UpdateAddressRequested:case Yg.UpdateAddressSucceeded:return Bv(e,{updateAddressError:void 0,updateAddressMethodId:void 0});case Yg.UpdateAddressFailed:return Bv(e,{updateAddressError:t.payload,updateAddressMethodId:t.meta&&t.meta.methodId});case Yg.SelectOptionRequested:case Yg.SelectOptionSucceeded:return Bv(e,{selectOptionError:void 0,selectOptionMethodId:void 0});case Yg.SelectOptionFailed:return Bv(e,{selectOptionError:t.payload,selectOptionMethodId:t.meta&&t.meta.methodId});case Yg.WidgetInteractionStarted:case Yg.WidgetInteractionFinished:return Bv(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Yg.WidgetInteractionFailed:return Bv(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta&&t.meta.methodId});default:return e}}function VS(e=BS.statuses,t){switch(t.type){case Yg.InitializeRequested:return Bv(e,{isInitializing:!0,initializeMethodId:t.meta&&t.meta.methodId});case Yg.InitializeFailed:case Yg.InitializeSucceeded:return Bv(e,{isInitializing:!1,initializeMethodId:void 0});case Yg.DeinitializeRequested:return Bv(e,{isDeinitializing:!0,deinitializeMethodId:t.meta&&t.meta.methodId});case Yg.DeinitializeFailed:case Yg.DeinitializeSucceeded:return Bv(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Yg.UpdateAddressRequested:return Bv(e,{isUpdatingAddress:!0,updateAddressMethodId:t.meta&&t.meta.methodId});case Yg.UpdateAddressFailed:case Yg.UpdateAddressSucceeded:return Bv(e,{isUpdatingAddress:!1,updateAddressMethodId:void 0});case Yg.SelectOptionRequested:return Bv(e,{isSelectingOption:!0,selectOptionMethodId:t.meta&&t.meta.methodId});case Yg.SelectOptionFailed:case Yg.SelectOptionSucceeded:return Bv(e,{isSelectingOption:!1,selectOptionMethodId:void 0});case Yg.WidgetInteractionStarted:return Bv(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta&&t.meta.methodId});case Yg.WidgetInteractionFinished:case Yg.WidgetInteractionFailed:return Bv(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const GS={errors:{},statuses:{}};function HS(e=GS,t){return d({data:WS,errors:c($S,bv),statuses:YS})(e,t)}function WS(e,t){return t.type===cv.SendSignInEmailSucceeded?Bv(e,t.payload):e}function $S(e=GS.errors,t){switch(t.type){case cv.SendSignInEmailRequested:case cv.SendSignInEmailSucceeded:return Ov(e,"sendError",void 0);case cv.SendSignInEmailFailed:return Ov(e,"sendError",t.payload);default:return e}}function YS(e=GS.statuses,t){switch(t.type){case cv.SendSignInEmailRequested:return Ov(e,"isSending",!0);case cv.SendSignInEmailFailed:case cv.SendSignInEmailSucceeded:return Ov(e,"isSending",!1);default:return e}}const KS={errors:{},statuses:{}};function JS(e=KS,t){return d({errors:c(ZS,bv),statuses:QS})(e,t)}function ZS(e=KS.errors,t){switch(t.type){case Eg.ApplyStoreCreditRequested:case Eg.ApplyStoreCreditSucceeded:return Ov(e,"applyError",void 0);case Eg.ApplyStoreCreditFailed:return Ov(e,"applyError",t.payload);default:return e}}function QS(e=KS.statuses,t){switch(t.type){case Eg.ApplyStoreCreditRequested:return Ov(e,"isApplying",!0);case Eg.ApplyStoreCreditSucceeded:case Eg.ApplyStoreCreditFailed:return Ov(e,"isApplying",!1);default:return e}}const XS={errors:{},statuses:{}};function e_(e=XS,t){return d({errors:c(t_,bv),statuses:n_})(e,t)}function t_(e=XS.errors,t){switch(t.type){case kg.UpdateSubscriptionsRequested:case kg.UpdateSubscriptionsSucceeded:return Ov(e,"updateError",void 0);case kg.UpdateSubscriptionsFailed:return Ov(e,"updateError",t.payload);default:return e}}function n_(e=XS.statuses,t){switch(t.type){case kg.UpdateSubscriptionsRequested:return Ov(e,"isUpdating",!0);case kg.UpdateSubscriptionsFailed:case kg.UpdateSubscriptionsSucceeded:return Ov(e,"isUpdating",!1);default:return e}}const i_={errors:{},statuses:{}};function r_(e=i_,t){return d({data:o_,errors:c(a_,bv),statuses:s_})(e,t)}function o_(e,t){var n;switch(t.type){case $t.LoadCheckoutSucceeded:case $t.UpdateCheckoutSucceeded:case Eg.ApplyStoreCreditSucceeded:case tt.UpdateBillingAddressSucceeded:case kt.ApplyCouponSucceeded:case kt.RemoveCouponSucceeded:case _g.CreateConsignmentsSucceeded:case _g.UpdateConsignmentSucceeded:case _g.DeleteConsignmentSucceeded:case _g.UpdateShippingOptionSucceeded:case _g.LoadShippingOptionsSucceeded:case Nt.ApplyGiftCertificateSucceeded:case Nt.RemoveGiftCertificateSucceeded:case rn.VerifyCheckoutSucceeded:return Bv(e,le(t.payload,["billingAddress","cart","consignments","customer","coupons","giftCertificates"]));case Mm.SubmitOrderSucceeded:return Ov(e,"orderId",t.payload&&t.payload.order.orderId);case Yt.HydrateInitialState:return Bv(e,le(null===(n=t.payload)||void 0===n?void 0:n.checkout,["billingAddress","cart","consignments","customer","coupons","giftCertificates"]));default:return e}}function a_(e=i_.errors,t){switch(t.type){case $t.LoadCheckoutRequested:case $t.LoadCheckoutSucceeded:return Ov(e,"loadError",void 0);case $t.LoadCheckoutFailed:return Ov(e,"loadError",t.payload);case $t.UpdateCheckoutRequested:case $t.UpdateCheckoutSucceeded:return Ov(e,"updateError",void 0);case $t.UpdateCheckoutFailed:return Ov(e,"updateError",t.payload);default:return e}}function s_(e=i_.statuses,t){switch(t.type){case $t.LoadCheckoutRequested:return Ov(e,"isLoading",!0);case $t.LoadCheckoutFailed:case $t.LoadCheckoutSucceeded:return Ov(e,"isLoading",!1);case $t.UpdateCheckoutRequested:return Ov(e,"isUpdating",!0);case $t.UpdateCheckoutFailed:case $t.UpdateCheckoutSucceeded:return Ov(e,"isUpdating",!1);case rn.ExecuteRequested:return Ov(e,"isExecutingSpamCheck",!0);case rn.ExecuteFailed:case rn.ExecuteSucceeded:return Ov(e,"isExecutingSpamCheck",!1);default:return e}}function d_(e,t){if(null==e)throw t?t():new Error("An unexpected error has occurred.");return e}function c_(e){return function(e){const t=Object.create(e);return function(e,t){let n=Object.getPrototypeOf(e);for(;n;)t(n),n=Object.getPrototypeOf(n)}(e,n=>{Object.getOwnPropertyNames(n).forEach(n=>{"constructor"!==n&&"function"==typeof t[n]&&"_"!==n.charAt(0)&&(t[n]=((e,t)=>(...n)=>p(e[t].call(e,...n)))(e,n))})}),t}(e)}const l_={"mollie.credit_card":{provider:"mollie",method:"credit_card"},"adyenv2.scheme":{provider:"adyenv2",method:"scheme"},"adyenv3.scheme":{provider:"adyenv3",method:"scheme"},"adyenv2.bcmc":{provider:"adyenv2",method:"bcmc"},"adyenv2.ideal":{provider:"adyenv2",method:"ideal"},"adyenv2.sepadirectdebit":{provider:"adyenv2",method:"sepadirectdebit"},"adyenv2.directEbanking":{provider:"adyenv2",method:"directEbanking"},"adyenv2.giropay":{provider:"adyenv2",method:"giropay"},braintree:{provider:"braintree",method:"credit_card"},braintreepaypal:{provider:"braintree",method:"paypal"},braintreeach:{provider:"braintree",method:"ach"},authorizenet:{provider:"authorizenet",method:"credit_card"},elavon:{provider:"elavon",method:"credit_card"},checkoutcom:{provider:"checkoutcom",method:"credit_card"},"checkoutcom.credit_card":{provider:"checkoutcom",method:"credit_card"},"checkoutcom.card":{provider:"checkoutcom",method:"card"},sagepay:{provider:"sagepay",method:"credit_card"},stripe:{provider:"stripe",method:"credit_card"},"stripev3.card":{provider:"stripev3",method:"card"},"stripeupe.card":{provider:"stripeupe",method:"card"},cybersource:{provider:"cybersource",method:"credit_card"},cybersourcev2:{provider:"cybersourcev2",method:"credit_card"},bnz:{provider:"bnz",method:"credit_card"},converge:{provider:"converge",method:"credit_card"},bluesnapv2:{provider:"bluesnapv2",method:"credit_card"},"bluesnapdirect.credit_card":{provider:"bluesnapdirect",method:"credit_card"},"bluesnapdirect.ecp":{provider:"bluesnapdirect",method:"ecp"},"bluesnapdirect.sepa_direct_debit":{provider:"bluesnapdirect",method:"sepa_direct_debit"},orbital:{provider:"orbital",method:"credit_card"},paymetric:{provider:"paymetric",method:"credit_card"},bolt:{provider:"bolt",method:"credit_card"},"barclaycard.credit_card":{provider:"barclaycard",method:"credit_card"},moneris:{provider:"moneris",method:"credit_card"},cba_mpgs:{provider:"cba_mpgs",method:"credit_card"},worldpayaccess:{provider:"worldpayaccess",method:"credit_card"},"worldpayaccess.credit_card":{provider:"worldpayaccess",method:"credit_card"},squarev2:{provider:"squarev2",method:"credit_card"},paypalcommercecreditcards:{provider:"paypalcommerce",method:"credit_card"},paypalcommerce:{provider:"paypalcommerce",method:"paypal"},bigcommerce_payments_creditcards:{provider:"bigcommerce_payments",method:"credit_card"},bigcommerce_payments:{provider:"bigcommerce_payments",method:"paypal"},tdonlinemart:{provider:"tdonlinemart",method:"credit_card"}};function u_(e){return me({firstName:e.firstName,lastName:e.lastName,company:e.company,address1:e.address1,address2:e.address2,city:e.city,stateOrProvince:e.stateOrProvince,countryCode:e.countryCode,postalCode:e.postalCode,phone:e.phone,customFields:e.customFields},G)}const h_={errors:{},statuses:{}};function p_(){const e=function(){const e=vv(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.token},e=>()=>e),t=vv(e=>e.errors.loadError,e=>()=>e),n=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((i=Ev)=>({getToken:e(i),getLoadError:t(i),isLoading:n(i)}))}(),t=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingBillingAddress))),n=vv(e=>e.errors.updateError,e=>()=>e),i=vv(e=>e.errors.continueAsGuestError,e=>()=>e),r=vv(e=>e.errors.loadError,e=>()=>e),o=vv(e=>!!e.statuses.isUpdating,e=>()=>e),a=vv(e=>!!e.statuses.isContinuingAsGuest,e=>()=>e),s=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((d=zv)=>({getBillingAddress:e(d),getBillingAddressOrThrow:t(d),getUpdateError:n(d),getContinueAsGuestError:i(d),getLoadError:r(d),isUpdating:o(d),isContinuingAsGuest:a(d),isLoading:s(d)}))}(),n=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingCart))),n=vv(e=>e.errors.loadError,e=>()=>e),i=vv(e=>!!e.statuses.isLoading,e=>()=>e),r=vv(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.locale},e=>()=>e);return Oe((o=jv)=>({getCart:e(o),getCartOrThrow:t(o),getLoadError:n(o),isLoading:i(o),getLocale:r(o)}))}(),i=function(){const e=vv(e=>e,e=>()=>e),t=vv(e=>e.statuses,e=>Pe(t=>{if(t){const n=e[t];return!0===(n&&n.isInitializing)}return ve(e,{isInitializing:!0})})),n=vv(e=>e.data,e=>Pe((t,n)=>{const i=e[t];return!!i&&(n?!0===i.initializedContainers[n]:ve(i.initializedContainers,e=>!0===e))})),i=vv(e=>e.statuses,e=>Pe(t=>{if(t){const n=e[t];return!0===(n&&n.isDeinitializing)}return ve(e,{isDeinitializing:!0})})),r=vv(e=>e.errors,e=>Pe(t=>{const n=t?e[t]:B(Ce(e),e=>!(!e||!e.initializeError));return n&&n.initializeError})),o=vv(e=>e.errors,e=>Pe(t=>{const n=t?e[t]:B(Ce(e),e=>!(!e||!e.deinitializeError));return n&&n.deinitializeError}));return Oe((a=Wv)=>({getState:e(a),isInitializing:t(a),isInitialized:n(a),isDeinitializing:i(a),getInitializeError:r(a),getDeinitializeError:o(a)}))}(),r=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.data,e=>t=>{if(!e)return;const{flashMessages:n}=e.context;return n?void 0!==t?n.filter(({type:e})=>t===e):n:void 0}),n=vv(e=>e.data,(e,{formState:t})=>t&&t.data,(e,t={customerAccount:[],shippingAddress:[],billingAddress:[]})=>()=>e?Object.assign(Object.assign({},e.storeConfig),{formFields:t}):void 0),i=vv(n,e=>()=>d_(e(),()=>new rt(et.MissingCheckoutConfig))),r=vv(e=>e.data&&e.data.context,e=>()=>e),o=vv(e=>e.meta&&e.meta.externalSource,e=>()=>e),a=vv(e=>{var t;return null===(t=e.meta)||void 0===t?void 0:t.host},e=>()=>e),s=vv(e=>{var t;return null===(t=e.meta)||void 0===t?void 0:t.locale},e=>()=>e),d=vv(e=>e.meta&&e.meta.variantIdentificationToken,e=>()=>e),c=vv(e=>e.errors.loadError,e=>()=>e),l=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((u=ef,h)=>({getConfig:e(u),getFlashMessages:t(u),getStoreConfig:n(u,{formState:h}),getStoreConfigOrThrow:i(u,{formState:h}),getContextConfig:r(u),getExternalSource:o(u),getHost:a(u),getLocale:s(u),getVariantIdentificationToken:d(u),getLoadError:c(u),isLoading:l(u)}))}(),o=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.loadError,e=>()=>e),n=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((i=Ff)=>({getCountries:e(i),getLoadError:t(i),isLoading:n(i)}))}(),a=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.removeCouponError,e=>()=>e),n=vv(e=>e.errors.applyCouponError,e=>()=>e),i=vv(e=>!!e.statuses.isApplyingCoupon,e=>()=>e),r=vv(e=>!!e.statuses.isRemovingCoupon,e=>()=>e);return Oe((o=af)=>({getCoupons:e(o),getRemoveError:t(o),getApplyError:n(o),isApplying:i(o),isRemoving:r(o)}))}(),s=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingCustomer))),n=vv(e=>e.errors.createError,e=>()=>e),i=vv(e=>!!e.statuses.isCreating,e=>()=>e),r=vv(e=>e.errors.createAddressError,e=>()=>e),o=vv(e=>!!e.statuses.isCreatingAddress,e=>()=>e);return Oe((a=gf)=>({getCustomer:e(a),getCustomerOrThrow:t(a),getCreateAccountError:n(a),isCreatingCustomerAccount:i(a),getCreateAddressError:r(a),isCreatingCustomerAddress:o(a)}))}(),d=function(){const e=vv(e=>e.errors.signInMethodId,e=>e.errors.signInError,(e,t)=>n=>{if(!n||e===n)return t}),t=vv(e=>e.errors.signOutMethodId,e=>e.errors.signOutError,(e,t)=>n=>{if(!n||e===n)return t}),n=vv(e=>e.errors.executePaymentMethodCheckoutMethodId,e=>e.errors.executePaymentMethodCheckoutError,(e,t)=>n=>{if(!n||e===n)return t}),i=vv(e=>e.errors.initializeMethodId,e=>e.errors.initializeErrors,(e,t)=>n=>{if(e&&t)return n?t[n]:t[e]}),r=vv(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>n=>{if(!n||e===n)return t}),o=vv(e=>e.statuses.signInMethodId,e=>e.statuses.isSigningIn,(e,t)=>n=>!(n&&e!==n||!t)),a=vv(e=>e.statuses.signOutMethodId,e=>e.statuses.isSigningOut,(e,t)=>n=>!(n&&e!==n||!t)),s=vv(e=>e.statuses.executePaymentMethodCheckoutMethodId,e=>e.statuses.isExecutingPaymentMethodCheckout,(e,t)=>n=>!(n&&e!==n||!t)),d=vv(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>n=>!(n&&e!==n||!t)),c=vv(e=>e.data,e=>t=>!(!e[t]||!e[t].isInitialized)),l=vv(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((u=wf)=>({getSignInError:e(u),getSignOutError:t(u),getExecutePaymentMethodCheckoutError:n(u),getInitializeError:i(u),getWidgetInteractionError:r(u),isSigningIn:o(u),isSigningOut:a(u),isExecutingPaymentMethodCheckout:s(u),isInitializing:d(u),isInitialized:c(u),isWidgetInteracting:l(u)}))}(),c=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.removeGiftCertificateError,e=>()=>e),n=vv(e=>e.errors.applyGiftCertificateError,e=>()=>e),i=vv(e=>!!e.statuses.isApplyingGiftCertificate,e=>()=>e),r=vv(e=>!!e.statuses.isRemovingGiftCertificate,e=>()=>e);return Oe((o=uf)=>({getGiftCertificates:e(o),getRemoveError:t(o),getApplyError:n(o),isApplying:i(o),isRemoving:r(o)}))}(),l=function(){const e=vv(e=>e.data,e=>t=>{if(!e)return;const n=t.gateway?`${t.gateway}.${t.id}`:t.id,i=l_[n];return i?L(e,i):[]}),t=vv(e=>e.data,(e=[])=>t=>{const n=Ce(l_);return e.find(e=>e.bigpayToken===t&&"card"===e.type&&n.some(t=>K(e,t)))}),n=vv(t,e=>t=>d_(e(t),()=>new rt(et.MissingPaymentInstrument))),i=vv(e=>e.data,e=>()=>{if(e)return U(l_,t=>L(e,e=>K(e,t)))}),r=vv(e=>e.meta,e=>()=>e),o=vv(e=>e.errors.loadError,e=>()=>e),a=vv(e=>e.errors.failedInstrument,e=>e.errors.deleteError,(e,t)=>n=>{if(!n||e===n)return t}),s=vv(e=>e.statuses.isLoading,e=>()=>!!e),d=vv(e=>e.statuses.deletingInstrument,e=>e.statuses.isDeleting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((c=pS)=>({getCardInstrument:t(c),getCardInstrumentOrThrow:n(c),getInstruments:i(c),getInstrumentsByPaymentMethod:e(c),getInstrumentsMeta:r(c),getLoadError:o(c),getDeleteError:a(c),isLoading:s(c),isDeleting:d(c)}))}(),u=function(){const e=vv(e=>e.data,e=>(t=[],n)=>{const i=B(t,{code:n});return(e?e.shippingAddress:[]).map(e=>a(e,t,i))}),t=vv(e=>e.data,e=>(t=[],n)=>{const i=B(t,{code:n});return(e?e.billingAddress:[]).map(e=>a(e,t,i))}),n=vv(e=>e.data,e=>()=>e?e.customerAccount:[]),i=vv(e=>e.extraFields,e=>()=>e&&e.address.length?e.address.map(Ke):[]),r=vv(e=>e.errors.loadError,e=>()=>e),o=vv(e=>!!e.statuses.isLoading,e=>()=>e);function a(e,t,n){return"countryCode"===e.name?function(e,t=[],n){if(!t.length)return e;const{code:i=""}=n||{},r=t.map(({code:e,name:t})=>({value:e,label:t}));return Object.assign(Object.assign({},e),{options:{items:r},default:i,type:"array",fieldType:"dropdown",itemtype:"string"})}(e,t,n):"stateOrProvince"===e.name?function(e,t){const{subdivisions:n=[],requiresState:i}=t||{};if(!n.length)return Object.assign(Object.assign({},e),{required:null!=i&&i});const r=n.map(({code:e,name:t})=>({value:e,label:t}));return Object.assign(Object.assign({},e),{name:"stateOrProvinceCode",options:{items:r},required:null==i||i,type:"array",fieldType:"dropdown",itemtype:"string"})}(e,n):"postalCode"===e.name?function(e,t){const{hasPostalCodes:n=[]}=t||{};return void 0===n?e:Object.assign(Object.assign({},e),{required:Boolean(n)})}(e,n):e}return Oe((a=Df)=>({getShippingAddressFields:e(a),getBillingAddressFields:t(a),getCustomerAccountFields:n(a),getAddressExtraFields:i(a),getLoadError:r(a),isLoading:o(a)}))}(),h=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.meta,e=>()=>e),n=vv(e=>e.data,e=>(t,n)=>B(e,n?{id:t,gateway:n}:{id:t})),i=vv(n,e=>(t,n)=>d_(e(t,n),()=>new rt(et.MissingPaymentMethod))),r=vv(e=>e.errors.loadError,e=>()=>e),o=vv(e=>e.errors.loadMethodId,e=>e.errors.loadMethodError,(e,t)=>n=>{if(!n||e===n)return t}),a=vv(e=>e.statuses.isLoading,e=>()=>!!e),s=vv(e=>e.statuses.loadMethodId,e=>e.statuses.isLoadingMethod,(e,t)=>n=>!(n&&e!==n||!t));return Oe((d=Xf)=>({getPaymentMethods:e(d),getPaymentMethodsMeta:t(d),getPaymentMethod:n(d),getPaymentMethodOrThrow:i(d),getLoadError:r(d),getLoadMethodError:o(d),isLoading:a(d),isLoadingMethod:s(d)}))}(),p=function(){const e=vv(e=>e.errors.initializeMethodId,e=>e.errors.initializeError,(e,t)=>n=>{if(!n||e===n)return t}),t=vv(e=>e.errors.executeMethodId,e=>e.errors.executeError,(e,t)=>n=>{if(!n||e===n)return t}),n=vv(e=>e.errors.finalizeMethodId,e=>e.errors.finalizeError,(e,t)=>n=>{if(!n||e===n)return t}),i=vv(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>n=>{if(!n||e===n)return t}),r=vv(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>n=>!(n&&e!==n||!t)),o=vv(e=>e.data,e=>t=>{const n=t.gatewayId?`${t.methodId}.${t.gatewayId}`:t.methodId;return!(!e[n]||!e[n].isInitialized)}),a=vv(e=>e.statuses.executeMethodId,e=>e.statuses.isExecuting,(e,t)=>n=>!(n&&e!==n||!t)),s=vv(e=>e.statuses.finalizeMethodId,e=>e.statuses.isFinalizing,(e,t)=>n=>!(n&&e!==n||!t)),d=vv(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((c=oS)=>({getInitializeError:e(c),getExecuteError:t(c),getFinalizeError:n(c),getWidgetInteractingError:i(c),isInitializing:r(c),isInitialized:o(c),isExecuting:a(c),isFinalizing:s(c),isWidgetInteracting:d(c)}))}(),m=function(){const e=vv(e=>e.data,e=>(t,n)=>{if(!e)return;const i=AS(ES({consignmentId:t,searchArea:n})),r=btoa(`${JSON.stringify(i)}`);return e[r]}),t=vv(e=>e.errors.loadError,e=>()=>e),n=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((i=TS)=>({getPickupOptions:e(i),getLoadError:t(i),isLoading:n(i)}))}(),y=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingPaymentProviderCustomer)));return Oe((n=lS)=>({getPaymentProviderCustomer:e(n),getPaymentProviderCustomerOrThrow:t(n)}))}(),g=function(){const e=vv(e=>e.data,e=>t=>e[t]);return Oe((t=SS)=>({getCheckout:e(t)}))}(),v=function(){const e=vv(e=>e.data,e=>()=>{const t=null==e?void 0:e.find(e=>!e.selectedPickupOption);return null==t?void 0:t.shippingAddress}),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingShippingAddress))),n=vv(e=>e.data,e=>()=>{const t=null==e?void 0:e.filter(e=>!e.selectedPickupOption);return t?t.map(e=>e.shippingAddress):[]}),i=vv(n,e=>()=>d_(e(),()=>new rt(et.MissingShippingAddress)));return Oe((r=IS)=>({getShippingAddress:e(r),getShippingAddressOrThrow:t(r),getShippingAddresses:n(r),getShippingAddressesOrThrow:i(r)}))}(),f=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.loadError,e=>()=>e),n=vv(e=>e.statuses.isLoading,e=>()=>!!e);return Oe((i=NS)=>({getShippingCountries:e(i),getLoadError:t(i),isLoading:n(i)}))}(),S=function(){const e=vv(e=>e.errors.updateAddressMethodId,e=>e.errors.updateAddressError,(e,t)=>n=>{if(!n||e===n)return t}),t=vv(e=>e.errors.selectOptionMethodId,e=>e.errors.selectOptionError,(e,t)=>n=>{if(!n||e===n)return t}),n=vv(e=>e.errors.initializeMethodId,e=>e.errors.initializeError,(e,t)=>n=>{if(!n||e===n)return t}),i=vv(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>n=>{if(!n||e===n)return t}),r=vv(e=>e.statuses.updateAddressMethodId,e=>e.statuses.isUpdatingAddress,(e,t)=>n=>!(n&&e!==n||!t)),o=vv(e=>e.statuses.selectOptionMethodId,e=>e.statuses.isSelectingOption,(e,t)=>n=>!(n&&e!==n||!t)),a=vv(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>n=>!(n&&e!==n||!t)),s=vv(e=>e.data,e=>t=>!(!e[t]||!e[t].isInitialized)),d=vv(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((c=BS)=>({getUpdateAddressError:e(c),getSelectOptionError:t(c),getInitializeError:n(c),getWidgetInteractionError:i(c),isUpdatingAddress:r(c),isSelectingOption:o(c),isInitializing:a(c),isInitialized:s(c),isWidgetInteracting:d(c)}))}(),_=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingConsignments))),n=vv(e=>e.data,e=>t=>{if(e&&e.length)return B(e,{id:t})}),i=vv(e=>e.data,e=>t=>{if(e&&e.length)return B(e,e=>{return n=e.shippingAddress,i=t,Y(u_(n),u_(i));var n,i})}),r=vv(e=>e.data,e=>()=>{if(e&&e.length)return e[0].selectedShippingOption}),o=vv(e=>e.errors.loadError,e=>()=>e),a=vv(e=>e.errors.createError,e=>()=>e),s=vv(e=>e.errors.loadShippingOptionsError,e=>()=>e),d=vv(e,(e,{cart:t})=>t.getCart,(e,t)=>()=>{const n=t();if(!n)return[];const i=(e()||[]).reduce((e,t)=>e.concat(t.lineItemIds),[]);return(n.lineItems.physicalItems||[]).filter(e=>i.indexOf(e.id)<0)}),c=vv(e=>e.errors.updateError,e=>t=>t?e[t]:B(e)),l=vv(e=>e.errors.deleteError,e=>t=>t?e[t]:B(e)),u=vv(i,c,a,(e,t,n)=>i=>{const r=e(i);return r?t(r.id):n()}),h=vv(e=>e.errors.updateShippingOptionError,e=>t=>t?e[t]:B(e)),p=vv(e=>e.statuses.isLoading,e=>()=>!0===e),m=vv(e=>e.statuses.isLoadingShippingOptions,e=>()=>!0===e),y=vv(e=>e.statuses.isCreating,e=>()=>!0===e),g=vv(e=>e.statuses.isUpdating,e=>t=>t?!0===e[t]:!0===B(e)),v=vv(e=>e.statuses.isDeleting,e=>t=>t?!0===e[t]:!0===B(e)),f=vv(i,g,y,(e,t,n)=>i=>{const r=e(i);return r?t(r.id):n()}),S=vv(e=>e.statuses.isUpdatingShippingOption,e=>t=>t?!0===e[t]:!0===B(e));return Oe((_=IS,w)=>({getConsignments:e(_),getConsignmentsOrThrow:t(_),getConsignmentById:n(_),getConsignmentByAddress:i(_),getShippingOption:r(_),getLoadError:o(_),getCreateError:a(_),getLoadShippingOptionsError:s(_),getUnassignedItems:d(_,{cart:w}),getUpdateError:c(_),getDeleteError:l(_),getItemAssignmentError:u(_),getUpdateShippingOptionError:h(_),isLoading:p(_),isLoadingShippingOptions:m(_),isCreating:y(_),isUpdating:g(_),isDeleting:v(_),isAssigningItems:f(_),isUpdatingShippingOption:S(_)}))}(),w=function(){const e=vv(e=>e.data,(e,{billingAddress:t})=>t.getBillingAddress,(e,{cart:t})=>t.getCart,(e,{customer:t})=>t.getCustomer,(e,{consignments:t})=>t.getConsignments,(e,{coupons:t})=>t.getCoupons,(e,{giftCertificates:t})=>t.getGiftCertificates,(e,t,n,i,r,o,a)=>()=>{const s=t(),d=n(),c=i(),l=r()||[],u=o()||[],h=a()||[];if(e&&d&&c)return Object.assign(Object.assign({},e),{billingAddress:s,cart:d,customer:c,consignments:l,coupons:u,giftCertificates:h})}),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingCheckout))),n=vv(e,e=>t=>{const n=e();if(!n)return;const i=n.grandTotal||0,r=n.customer.storeCredit||0;return t?Math.max(i-r,0):n.outstandingBalance}),i=vv(e=>e.errors.loadError,e=>()=>e),r=vv(e=>e.errors.updateError,e=>()=>e),o=vv(e=>e.statuses.isExecutingSpamCheck,e=>()=>!0===e),a=vv(e=>e.statuses.isLoading,e=>()=>!0===e),s=vv(e=>e.statuses.isUpdating,e=>()=>!0===e);return Oe((d=i_,c,l,u,h,p,m)=>({getCheckout:e(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getCheckoutOrThrow:t(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getOutstandingBalance:n(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getLoadError:i(d),getUpdateError:r(d),isExecutingSpamCheck:o(d),isLoading:a(d),isUpdating:s(d)}))}(),I=function(){const e=vv(e=>e.data,(e,{billingAddress:t})=>t.getOrderBillingAddress(),(e,{coupons:t})=>t.getCoupons(),(e,t,n=[])=>()=>{if(e&&t)return Object.assign(Object.assign({},e),{billingAddress:t,coupons:n})}),t=vv(e,e=>()=>d_(e(),()=>new rt(et.MissingOrder))),n=vv(e=>e.meta,e=>()=>e),i=vv(e=>e.errors.loadError,e=>()=>e),r=vv(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.payments},(e=[])=>t=>{const n=e.find(({providerId:e})=>e===t);return null==n?void 0:n.paymentId}),o=vv(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((a=qf,s,d)=>({getOrder:e(a,{billingAddress:s,coupons:d}),getOrderOrThrow:t(a,{billingAddress:s,coupons:d}),getOrderMeta:n(a),getLoadError:i(a),getPaymentId:r(a),isLoading:o(a)}))}(),C=function(){const e=vv(e=>e.data,e=>()=>e);return Oe((t=Yf)=>({getOrderBillingAddress:e(t)}))}(),b=function(){const e=vv(({order:e})=>e.getOrderMeta,e=>()=>{const t=e();return t&&t.payment}),t=vv(({order:e})=>e.getOrder,e=>()=>{const t=e();return B(t&&t.payments,({providerId:e})=>"giftcertificate"!==e&&"storecredit"!==e)}),n=vv(({checkout:e})=>e.getCheckout,e=>()=>{const t=e();return B(t&&t.payments,({providerType:e})=>"PAYMENT_TYPE_HOSTED"===e)}),i=vv(e,n,t,(e,t,n)=>()=>{const i=e();if(i&&i.id)return{providerId:i.id,gatewayId:i.gateway};const r=t()||n();return r&&r.providerId?{providerId:r.providerId,gatewayId:r.gatewayId}:void 0}),r=vv(i,e=>()=>d_(e(),()=>new rt(et.MissingPaymentId))),o=vv(e,n,t,(e,t,n)=>()=>{const i=e();if(i&&i.status)return i.status.replace("PAYMENT_STATUS_","");const r=t()||n();return r?r.detail.step:void 0}),a=vv(o,e=>()=>d_(e(),()=>new rt(et.MissingPaymentStatus))),s=vv(({order:e})=>e.getOrderMeta,e=>()=>{const t=e();return t&&t.token}),d=vv(s,e=>()=>d_(e(),()=>new rt(et.MissingPaymentToken))),c=vv(e,e=>()=>{const t=e();return t&&t.redirectUrl}),l=vv(c,e=>()=>d_(e(),()=>new rt(et.MissingPaymentRedirectUrl))),u=vv(({checkout:e})=>e.getOutstandingBalance,e=>(t=!1)=>{const n=e(t);return!!n&&n>0}),h=vv(o,e=>t=>!(!t||!t.nonce)||"ACKNOWLEDGE"===e()||e()===$y);return Oe((e,t)=>({getPaymentId:i({checkout:e,order:t}),getPaymentIdOrThrow:r({checkout:e,order:t}),getPaymentStatus:o({checkout:e,order:t}),getPaymentStatusOrThrow:a({checkout:e,order:t}),getPaymentToken:s({checkout:e,order:t}),getPaymentTokenOrThrow:d({checkout:e,order:t}),getPaymentRedirectUrl:c({checkout:e,order:t}),getPaymentRedirectUrlOrThrow:l({checkout:e,order:t}),isPaymentDataRequired:u({checkout:e,order:t}),isPaymentDataSubmitted:h({checkout:e,order:t})}))}(),P=function(){const e=vv(e=>e.errors.applyError,e=>()=>e),t=vv(e=>!!e.statuses.isApplying,e=>()=>e);return Oe((n=h_)=>({getApplyError:e(n),isApplying:t(n)}))}(),O=function(){const e=vv(e=>e.errors.updateError,e=>()=>e),t=vv(e=>!!e.statuses.isUpdating,e=>()=>e);return Oe((n=XS)=>({getUpdateError:e(n),isUpdating:t(n)}))}(),E=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.errors.sendError,e=>()=>e),n=vv(e=>!!e.statuses.isSending,e=>()=>e);return Oe((i=GS)=>({getEmail:e(i),getSendError:t(i),isSending:n(i)}))}(),A=function(){const e=vv(e=>e.data,e=>()=>e),t=vv(e=>e.data,e=>t=>null==e?void 0:e.find(e=>e.region===t)),n=vv(e=>e.errors.loadError,e=>()=>e),i=vv(e=>e.statuses.isLoading,e=>()=>!!e);return Oe((r=Of)=>({getExtensions:e(r),getExtensionByRegion:t(r),getLoadError:n(r),isLoading:i(r)}))}();return(T,k={})=>{const D=e(T.b2bToken),M=t(T.billingAddress),z=n(T.cart),N=i(T.checkoutButton),x=o(T.countries),R=a(T.coupons),F=s(T.customer),L=d(T.customerStrategies),B=A(T.extensions),j=u(T.formFields),U=c(T.giftCertificates),q=l(T.instruments),V=C(T.orderBillingAddress),G=h(T.paymentMethods),H=y(T.paymentProviderCustomer),W=p(T.paymentStrategies),$=m(T.pickupOptions),Y=g(T.remoteCheckout),K=v(T.consignments),J=f(T.shippingCountries),Z=S(T.shippingStrategies),Q=O(T.subscriptions),X=P(T.storeCredit),ee=E(T.signInEmail),te=_(T.consignments,z),ne=w(T.checkout,M,z,te,R,F,U),ie=I(T.order,V,R),re=b(ne,ie),oe={b2bToken:D,billingAddress:M,cart:z,checkout:ne,checkoutButton:N,config:r(T.config,T.formFields),consignments:te,countries:x,coupons:R,customer:F,customerStrategies:L,extensions:B,form:j,giftCertificates:U,instruments:q,order:ie,orderBillingAddress:V,payment:re,paymentMethods:G,paymentProviderCustomer:H,paymentStrategies:W,pickupOptions:$,remoteCheckout:Y,shippingAddress:K,shippingCountries:J,shippingStrategies:Z,signInEmail:ee,subscriptions:Q,storeCredit:X};return k.shouldWarnMutation?(ae=oe,Object.keys(ae).reduce((e,t)=>(e[t]=c_(ae[t]),e),{})):oe;var ae}}function m_(e={},t){const n=(o=function(){const e=new Iv;return["catalog_only","empty_cart","invalid_order_id","invalid_order_token","missing_order_token","missing_provider_token","missing_shipping_method","order_completion_error","order_could_not_be_finalized_error","order_create_failed","provider_fatal_error","provider_setup_error","stock_too_low"].forEach(t=>{e.register(t,(e,t)=>new Sv(e,t))}),e.register("invalid_payment_provider",e=>new Xr(e)),e.register("payment_config_not_found",e=>new Xr(e)),e}(),e=>S(e).pipe(P(e=>{if(e instanceof Error||e.payload instanceof Error)throw e;if((t=e.payload)&&"object"==typeof t&&["body","headers","status","statusText"].every(e=>Object.prototype.hasOwnProperty.call(t,e))){const t=e.payload.body&&e.payload.body.detail;throw Object.assign(Object.assign({},e),{payload:o.createError(e.payload,t)})}var t;throw e}))),i=p_(),r=d({b2bToken:Av,billingAddress:Nv,cart:Uv,checkout:r_,checkoutButton:Jv,config:tf,consignments:CS,countries:Lf,coupons:sf,customer:vf,customerStrategies:If,extensions:Ef,formFields:Mf,giftCertificates:hf,instruments:mS,orderBillingAddress:Kf,order:Vf,payment:Zf,paymentMethods:eS,paymentStrategies:aS,pickupOptions:kS,paymentProviderCustomer:uS,remoteCheckout:_S,shippingCountries:xS,shippingStrategies:jS,signInEmail:HS,subscriptions:e_,storeCredit:JS});var o;return u(r,e,Object.assign({actionTransformer:n,stateTransformer:e=>i(e)},t))}function y_(e){"https:"!==document.location.protocol&&wt().warn("The BigCommerce Checkout SDK should not be used on a non-HTTPS page"),"production"!==vt()&&wt().warn("Note that the development build is not optimized. To create a production build, set process​.env.NODE_ENV to `production`.");const t={meta:{externalSource:e&&e.externalSource,host:null==e?void 0:e.host,locale:null==e?void 0:e.locale,variantIdentificationToken:window.checkoutVariantIdentificationToken},errors:{},statuses:{}},{locale:i="",shouldWarnMutation:r=!0}=e||{},s=n({host:e&&e.host}),d=m_({config:t},{shouldWarnMutation:r}),c=new gt(s,{getBasePath:()=>{var e,t;return null!==(t=null===(e=d.getState().config.getStoreConfig())||void 0===e?void 0:e.links.baseUrl)&&void 0!==t?t:void 0},getFeatures:()=>{var e,t,n;return null!==(n=null===(t=null===(e=d.getState().config.getStoreConfig())||void 0===e?void 0:e.checkoutSettings)||void 0===t?void 0:t.features)&&void 0!==n?n:{}}}),l=Gm(d),u=new jm(c),h=new en(c),p=new bt(new Tt(s)),m=Sn(o()),y=new _n(c),g=new pn(m,y),v=new Vm(u,new ny(h)),f=new Ng(new xg(c)),S=new on(new an(c)),_=new nn(h,p,S),w=Hg(d,c),I=function(e,t,n={useFallback:!1}){const{useFallback:i}=n,r=new Gt(i);for(const[,n]of Object.entries(t))if(Ut(n))for(const t of n.resolveIds)r.register(t,()=>n(e));return r}(w,He,{useFallback:!0}),C=function(e,t){const n=new Gt;for(const[,i]of Object.entries(t))if(Ut(i))for(const t of i.resolveIds)n.register(t,()=>i(e));return n}(w,Ge),b=new xn(new Rn(c)),P=new Hn,O=new Kn(d,P),E=mt(d,function(){const e=function(){const e=vv(({checkout:e})=>e.getCheckout,e=>Bg(e)),t=vv(({order:e})=>e.getOrder,e=>Bg(e)),n=vv(({config:e})=>e.getStoreConfig,e=>Bg(e)),i=vv(({shippingAddress:e})=>e.getShippingAddress,({config:e})=>e.getContextConfig,(e,t)=>Bg(()=>{const n=e(),i=t();if(!n){if(!i||!i.geoCountryCode)return;return{firstName:"",lastName:"",company:"",address1:"",address2:"",city:"",stateOrProvince:"",stateOrProvinceCode:"",postalCode:"",country:"",phone:"",customFields:[],countryCode:i.geoCountryCode}}return n})),r=vv(({consignments:e})=>e.getConsignments,e=>Bg(()=>{const t=e(),n=null==t?void 0:t.find(e=>!e.selectedPickupOption);return null==n?void 0:n.availableShippingOptions})),o=vv(({consignments:e})=>e.getConsignments,e=>Bg(e)),a=vv(({consignments:e})=>e.getConsignments,e=>Bg(()=>{const t=e(),n=null==t?void 0:t.find(e=>!e.selectedPickupOption);return null==n?void 0:n.selectedShippingOption})),s=vv(({shippingCountries:e})=>e.getShippingCountries,e=>Bg(e)),d=vv(({billingAddress:e})=>e.getBillingAddress,({config:e})=>e.getContextConfig,(e,t)=>Bg(()=>{const n=e(),i=t();return(!n||Ce(le(n,"shouldSaveAddress","email","id")).every(e=>!e||!e.length))&&i&&i.geoCountryCode?{id:n?n.id:"",firstName:"",lastName:"",company:"",address1:"",address2:"",city:"",email:n?n.email:"",stateOrProvince:"",stateOrProvinceCode:"",postalCode:"",country:"",phone:"",customFields:[],countryCode:i.geoCountryCode}:n})),c=vv(({countries:e})=>e.getCountries,e=>Bg(e)),l=vv(({paymentMethods:e})=>e.getPaymentMethods,e=>Bg(e)),u=vv(({paymentMethods:e})=>e.getPaymentMethod,e=>Bg(e)),h=vv(({payment:e})=>e.getPaymentId,({paymentMethods:e})=>e.getPaymentMethod,(e,t)=>Bg(()=>{const n=e();return n&&t(n.providerId,n.gatewayId)})),p=vv(({cart:e})=>e.getCart,e=>Bg(e)),m=vv(({coupons:e})=>e.getCoupons,e=>Bg(e)),y=vv(({giftCertificates:e})=>e.getGiftCertificates,e=>Bg(e)),g=vv(({customer:e})=>e.getCustomer,e=>Bg(e)),v=vv(({signInEmail:e})=>e.getEmail,e=>Bg(e)),f=vv(({b2bToken:e})=>e.getToken,e=>Bg(e)),S=vv(({payment:e})=>e.isPaymentDataRequired,e=>Bg(e)),_=vv(({payment:e})=>e.isPaymentDataSubmitted,({paymentMethods:e})=>e.getPaymentMethod,(e,t)=>Bg((n,i)=>e(t(n,i)))),w=vv(({instruments:e})=>e.getInstruments,({instruments:e})=>e.getInstrumentsByPaymentMethod,(e,t)=>Bg(function(n){return n?t(n):e()})),I=vv(({form:e})=>e.getCustomerAccountFields,e=>Bg(e)),C=vv(({form:e})=>e.getBillingAddressFields,({countries:e})=>e.getCountries,(e,t)=>Bg(n=>e(t(),n))),b=vv(({form:e})=>e.getShippingAddressFields,({shippingCountries:e})=>e.getShippingCountries,(e,t)=>Bg(n=>e(t(),n))),P=vv(({form:e})=>e.getAddressExtraFields,e=>Bg(e)),O=vv(({config:e})=>e.getFlashMessages,e=>Bg(e)),E=vv(({pickupOptions:e})=>e.getPickupOptions,e=>Bg(e)),A=vv(({config:e})=>e.getStoreConfig,e=>Bg(()=>{const t=e();if(t)return t.checkoutSettings.checkoutUserExperienceSettings})),T=vv(({extensions:e})=>e.getExtensions,e=>Bg(e)),k=vv(({paymentProviderCustomer:e})=>e.getPaymentProviderCustomer,e=>Bg(e)),D=vv(({extensions:e})=>e.getExtensionByRegion,e=>Bg(e));return Oe(M=>({getCheckout:e(M),getOrder:t(M),getConfig:n(M),getExtensions:T(M),getExtensionByRegion:D(M),getFlashMessages:O(M),getShippingAddress:i(M),getShippingOptions:r(M),getConsignments:o(M),getSelectedShippingOption:a(M),getShippingCountries:s(M),getBillingAddress:d(M),getBillingCountries:c(M),getPaymentMethods:l(M),getPaymentMethod:u(M),getSelectedPaymentMethod:h(M),getCart:p(M),getCoupons:m(M),getGiftCertificates:y(M),getCustomer:g(M),isPaymentDataRequired:S(M),isPaymentDataSubmitted:_(M),getSignInEmail:v(M),getB2BToken:f(M),getInstruments:w(M),getCustomerAccountFields:I(M),getBillingAddressFields:C(M),getShippingAddressFields:b(M),getAddressExtraFields:P(M),getPickupOptions:E(M),getUserExperienceSettings:A(M),getPaymentProviderCustomer:k(M)}))}(),t=function(){const e=fv(e=>e,e=>()=>{for(const t of Object.keys(e)){const n=e[t]();if(n)return n}}),t=vv(({shippingStrategies:e})=>e.getSelectOptionError,({consignments:e})=>e.getUpdateShippingOptionError,(e,t)=>n=>e()||t(n));return Oe(n=>{const i={getLoadCheckoutError:n.checkout.getLoadError,getUpdateCheckoutError:n.checkout.getUpdateError,getSubmitOrderError:n.paymentStrategies.getExecuteError,getFinalizeOrderError:n.paymentStrategies.getFinalizeError,getLoadOrderError:n.order.getLoadError,getLoadCartError:n.cart.getLoadError,getLoadBillingCountriesError:n.countries.getLoadError,getLoadShippingCountriesError:n.shippingCountries.getLoadError,getLoadPaymentMethodsError:n.paymentMethods.getLoadError,getLoadPaymentMethodError:n.paymentMethods.getLoadMethodError,getInitializePaymentError:n.paymentStrategies.getInitializeError,getSignInError:n.customerStrategies.getSignInError,getSignOutError:n.customerStrategies.getSignOutError,getInitializeCustomerError:n.customerStrategies.getInitializeError,getLoadShippingOptionsError:n.consignments.getLoadShippingOptionsError,getSelectShippingOptionError:t(n),getContinueAsGuestError:n.billingAddress.getContinueAsGuestError,getUpdateBillingAddressError:n.billingAddress.getUpdateError,getUpdateSubscriptionsError:n.subscriptions.getUpdateError,getUpdateShippingAddressError:n.shippingStrategies.getUpdateAddressError,getDeleteConsignmentError:n.consignments.getDeleteError,getUpdateConsignmentError:n.consignments.getUpdateError,getCreateConsignmentsError:n.consignments.getCreateError,getInitializeShippingError:n.shippingStrategies.getInitializeError,getApplyStoreCreditError:n.storeCredit.getApplyError,getApplyCouponError:n.coupons.getApplyError,getRemoveCouponError:n.coupons.getRemoveError,getApplyGiftCertificateError:n.giftCertificates.getApplyError,getRemoveGiftCertificateError:n.giftCertificates.getRemoveError,getLoadInstrumentsError:n.instruments.getLoadError,getDeleteInstrumentError:n.instruments.getDeleteError,getLoadConfigError:n.config.getLoadError,getSignInEmailError:n.signInEmail.getSendError,getLoadB2BTokenError:n.b2bToken.getLoadError,getCreateCustomerAccountError:n.customer.getCreateAccountError,getCreateCustomerAddressError:n.customer.getCreateAddressError,getPickupOptionsError:n.pickupOptions.getLoadError,getLoadExtensionsError:n.extensions.getLoadError};return Object.assign({getError:e(i)},i)})}(),n=function(){const e=fv(e=>e,e=>()=>Object.keys(e).some(t=>e[t]())),t=vv(({shippingStrategies:e})=>e.isSelectingOption,({consignments:e})=>e.isUpdatingShippingOption,(e,t)=>n=>e()||t(n)),n=vv(({customerStrategies:e})=>e.isInitializing,({customerStrategies:e})=>e.isSigningIn,({customerStrategies:e})=>e.isSigningOut,({customerStrategies:e})=>e.isExecutingPaymentMethodCheckout,({customerStrategies:e})=>e.isWidgetInteracting,(e,t,n,i,r)=>o=>e(o)||t(o)||n(o)||i(o)||r(o)),i=vv(({shippingStrategies:e})=>e.isInitializing,({shippingStrategies:e})=>e.isUpdatingAddress,({shippingStrategies:e})=>e.isSelectingOption,({shippingStrategies:e})=>e.isWidgetInteracting,(e,t,n,i)=>r=>e(r)||t(r)||n(r)||i(r)),r=vv(({paymentStrategies:e})=>e.isInitializing,({paymentStrategies:e})=>e.isExecuting,({paymentStrategies:e})=>e.isFinalizing,({paymentStrategies:e})=>e.isWidgetInteracting,(e,t,n,i)=>r=>e(r)||t(r)||n(r)||i(r)),o=vv(({paymentStrategies:e})=>e.isExecuting,({checkout:e})=>e.isExecutingSpamCheck,(e,t)=>n=>e(n)||t());return Oe(a=>{const s={isLoadingCheckout:a.checkout.isLoading,isUpdatingCheckout:a.checkout.isUpdating,isExecutingSpamCheck:a.checkout.isExecutingSpamCheck,isSubmittingOrder:o(a),isFinalizingOrder:a.paymentStrategies.isFinalizing,isLoadingOrder:a.order.isLoading,isLoadingCart:a.cart.isLoading,isLoadingBillingCountries:a.countries.isLoading,isLoadingShippingCountries:a.shippingCountries.isLoading,isLoadingPaymentMethods:a.paymentMethods.isLoading,isLoadingPaymentMethod:a.paymentMethods.isLoadingMethod,isInitializingPayment:a.paymentStrategies.isInitializing,isSigningIn:a.customerStrategies.isSigningIn,isSigningOut:a.customerStrategies.isSigningOut,isExecutingPaymentMethodCheckout:a.customerStrategies.isExecutingPaymentMethodCheckout,isInitializingCustomer:a.customerStrategies.isInitializing,isInitializedCustomer:a.customerStrategies.isInitialized,isLoadingShippingOptions:a.consignments.isLoadingShippingOptions,isSelectingShippingOption:t(a),isUpdatingBillingAddress:a.billingAddress.isUpdating,isUpdatingSubscriptions:a.subscriptions.isUpdating,isCreatingCustomerAccount:a.customer.isCreatingCustomerAccount,isCreatingCustomerAddress:a.customer.isCreatingCustomerAddress,isContinuingAsGuest:a.billingAddress.isContinuingAsGuest,isUpdatingShippingAddress:a.shippingStrategies.isUpdatingAddress,isUpdatingConsignment:a.consignments.isUpdating,isDeletingConsignment:a.consignments.isDeleting,isCreatingConsignments:a.consignments.isCreating,isInitializingShipping:a.shippingStrategies.isInitializing,isApplyingStoreCredit:a.storeCredit.isApplying,isApplyingCoupon:a.coupons.isApplying,isRemovingCoupon:a.coupons.isRemoving,isApplyingGiftCertificate:a.giftCertificates.isApplying,isRemovingGiftCertificate:a.giftCertificates.isRemoving,isLoadingInstruments:a.instruments.isLoading,isDeletingInstrument:a.instruments.isDeleting,isLoadingConfig:a.config.isLoading,isSendingSignInEmail:a.signInEmail.isSending,isLoadingB2BToken:a.b2bToken.isLoading,isCustomerStepPending:n(a),isShippingStepPending:i(a),isPaymentStepPending:r(a),isLoadingPickupOptions:a.pickupOptions.isLoading};return Object.assign({isPending:e(s)},s)})}();return i=>({data:e(i),errors:t(i),statuses:n(i)})}());return new yv(d,E,O,function(e,t){const n={[$n.ConsignmentsChanged]:Zn};return new Jn(e,t,n)}(E,O),new Qe(new nt(s)),new st(new ut(c),f),_,p,new Kt(new Jt(c),_,g),new Cg(new Pg(c),h),new zm(new Nm(c,{locale:i})),new Dt(new Lt(c)),new Qt(function(e,t){const n=new Vt,i=a(),r=new en(t),o=new nn(r,new bt(new Tt(t)),new on(new an(t))),s=new pn(Sn(i),new _n(t)),d=new Kt(new Jt(t),o,s);return n.register("default",()=>new wn(e,d)),n}(d,c),C,w),new yt,new Bt(new jt(c)),new Wg(new Zg(l,c)),v,new Wm(new $m(c)),new Xm(function(e,t,n){const i=new Wy({defaultToken:Zm.CREDIT_CARD}),r=new Gy,a=new by(t),s=new en(n),d=new ny(s),c=new Vm(new jm(n),d),l=new cy(Sn(o())),u=new Cy(a,c,r,l),h=Ee(),p=((e,t)=>new ig(new ng(e,t)))(h,l),m=new Iy(e);return i.register(Zm.CONVERGE,()=>new Zy(e,c,u,m,h)),i.register(Zm.PPSDK,()=>new dg(e,c,((e,t,n,i,r)=>{const o=new lg;return o.register(ag.CARD,()=>new hg(e,t,r,i)),o.register(ag.NONE,()=>new pg(n,i)),o.register(ag.UNSUPPORTED,()=>{}),o})(e,c,n,p,m),new vg(n,p),new iy("PPSDK"))),i}(d,l,c),I,v,g,w),new Qg(new Xg(c)),new Ag(new Tg(c,{locale:i}),d),new ev(function(e,t){const n=new Vt,i=Hg(e),r=new en(t),o=new Pg(t),s=new Cg(o,r),d=new Wm(new $m(t)),c=a(),l=new Ng(new xg(t)),u=new st(new ut(t),l),h=window,p=new Ei(i);return n.register("amazonpay",()=>new iv(e,s,new Wm(new $m(t)),gi(),new ev(n))),n.register("stripeupe",()=>new lv(e,new Ra(c),s,d)),n.register("braintreeacceleratedcheckout",()=>new ov(e,u,s,d,new Sg,new _o(new Hi(a(),h,p),h))),n.register("paypalcommerceacceleratedcheckout",()=>new dv(e,u,s,d,new Sg,Cs(),nd())),n.register("default",()=>new av(e,s)),n}(d,c)),new uv(new hv(c)),g,new Dg(new Mg(c)),f,S,b,P)}class g_ extends Qn{constructor(e){super(e||"An unexpected error has occurred during config creation process. Please try again later."),this.name="AmazonPayV2ConfigCreationError",this.type="amazon_pay_v2_config_creation_error"}}function v_(e){return e instanceof Object&&"buyNowInitializeOptions"in e}var f_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class S_{constructor(e,t,n){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t,this.amazonPayV2ConfigRequestSender=n}initialize(e){var t;return f_(this,void 0,void 0,function*(){const{methodId:n,containerId:i,amazonpay:r}=e,{buttonColor:o}=r||{};if(!n||!i)throw new fi('Unable to proceed because "methodId" or "containerId" argument is not provided.');const{getPaymentMethodOrThrow:a}=this.paymentIntegrationService.getState(),s=a(n),{initializationData:d}=s;yield this.amazonPayV2PaymentProcessor.initialize(s),r||(yield this.paymentIntegrationService.loadDefaultCheckout());const c=v_(r)?void 0:r;v_(r)&&"function"==typeof(null===(t=r.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody)&&(this._buyNowInitializeOptions=r.buyNowInitializeOptions,this.amazonPayV2PaymentProcessor.updateBuyNowFlowFlag(!0)),this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:this.paymentIntegrationService.getState(),containerId:i,methodId:n,options:c,placement:si.Cart,buttonColor:o,isButtonMicroTextDisabled:null==d?void 0:d.isButtonMicroTextDisabled}),this._buyNowInitializeOptions&&this.amazonPayV2PaymentProcessor.prepareCheckoutWithCreationRequestConfig(this._getCheckoutCreationRequestConfig.bind(this))})}deinitialize(){return this.amazonPayV2PaymentProcessor.deinitialize()}_createBuyNowCartOrThrow(){var e,t;return f_(this,void 0,void 0,function*(){const n=null===(t=null===(e=this._buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody)||void 0===t?void 0:t.call(e);if(!n)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(n)}catch(e){throw new er}})}_createCheckoutConfig(e){return f_(this,void 0,void 0,function*(){try{const t=(yield this.amazonPayV2ConfigRequestSender.createCheckoutConfig(e)).body,{payload:n,public_key:i}=t,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const t=n(),i=new __(t),r=gi();return new S_(e,r,i)},[{id:"amazonpay"}]);var I_,C_,b_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}(I_||(I_={})),function(e){e.Black="black",e.White="white",e.WhiteBorder="white-border"}(C_||(C_={}));class P_{constructor(e,t,n,i,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._braintreeSdk=i,this._applePayScriptLoader=r,this._onAuthorizeCallback=ce,this._subTotalLabel=I_.Subtotal,this._shippingLabel=I_.Shipping}initialize(e){var t,n;return b_(this,void 0,void 0,function*(){const{methodId:i,containerId:r,applepay:o}=e;if(!i||!o)throw new ti(Xn.MissingPaymentMethod);yield this._applePayScriptLoader.loadSdk();const{onPaymentAuthorize:a,buyNowInitializeOptions:s,requiresShipping:d}=o;this._requiresShipping=d,this._buyNowInitializeOptions=s,this._onAuthorizeCallback=a,s||(yield this._paymentIntegrationService.loadDefaultCheckout()),yield this._paymentIntegrationService.loadPaymentMethod(i);const c=this._paymentIntegrationService.getState();return this._paymentMethod=c.getPaymentMethodOrThrow(i),c.getCart()&&(yield this._paymentIntegrationService.verifyCheckoutSpamProtection()),(null===(t=this._paymentMethod.initializationData)||void 0===t?void 0:t.gateway)===Vi.BRAINTREE&&this._paymentMethod.clientToken&&this._braintreeSdk.initialize(this._paymentMethod.clientToken),this._applePayButton=this._createButton(r,null===(n=this._paymentMethod.initializationData)||void 0===n?void 0:n.styleOption),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),Promise.resolve()})}deinitialize(){return Promise.resolve()}_createButton(e,t){const n=document.getElementById(e);if(!n)throw new fi("Unable to create wallet button without valid container ID.");const i=this._createApplePayButtonElement(t);return n.appendChild(i),i}_createApplePayButtonElement(e){const t=document.createElement("apple-pay-button");return t.setAttribute("buttonstyle",(e=>{switch(e){case C_.White:return"white";case C_.WhiteBorder:return"white-outline";case C_.Black:default:return"black"}})(e)),t.setAttribute("type","plain"),t.setAttribute("style","--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;"),t}_handleWalletButtonClick(e){var t;return b_(this,void 0,void 0,function*(){if(e.preventDefault(),!this._paymentMethod||!this._paymentMethod.initializationData)throw new ti(Xn.MissingPaymentMethod);if(this._buyNowInitializeOptions&&"function"==typeof this._buyNowInitializeOptions.getBuyNowCartRequestBody){const{countryCode:e,currencyCode:n,merchantCapabilities:i,supportedNetworks:r,storeName:o}=this._paymentMethod.initializationData,a=this._getRequestWithEmptyTotal(e,n,r,i);this._requiresShipping&&(null===(t=a.requiredShippingContactFields)||void 0===t||t.push("postalAddress"));const s=this._sessionFactory.create(a);this._handleApplePayEvents(s,this._paymentMethod,o),s.begin()}else{const e=this._paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getStoreConfigOrThrow(),i=e.getCheckoutOrThrow(),r=this._getBaseRequest(t,i,n,this._paymentMethod),o=this._sessionFactory.create(r);this._handleApplePayEvents(o,this._paymentMethod,n.storeProfile.storeName),o.begin()}})}_getRequestWithEmptyTotal(e,t,n,i){return{countryCode:e,currencyCode:t,supportedNetworks:n,merchantCapabilities:i,total:{label:"",amount:"0",type:"pending"},requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"]}}_getBaseRequest(e,t,n,i){var r;const{storeProfile:{storeCountryCode:o,storeName:a}}=n,{currency:{code:s,decimalPlaces:d}}=e,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=i,u=e.lineItems.physicalItems.length>0,h={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:o,currencyCode:s,merchantCapabilities:c,supportedNetworks:l,lineItems:[],total:u?{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"pending"}:{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"final"}};if(u)null===(r=h.requiredShippingContactFields)||void 0===r||r.push("postalAddress");else{const e=[{label:this._subTotalLabel,amount:`${t.subtotal.toFixed(d)}`}];t.taxes.forEach(t=>e.push({label:t.name,amount:`${t.amount.toFixed(d)}`})),h.lineItems=e}return h}_handleApplePayEvents(e,t,n){e.onvalidatemerchant=n=>b_(this,void 0,void 0,function*(){try{const{body:i}=yield this._onValidateMerchant(t,n);e.completeMerchantValidation(i)}catch(e){throw new Error("Merchant validation failed")}}),this._buyNowInitializeOptions&&!this._requiresShipping&&(e.onpaymentmethodselected=()=>b_(this,void 0,void 0,function*(){yield this._createBuyNowCart(),this._handlePaymentMethodSelected(e)})),e.onshippingcontactselected=t=>b_(this,void 0,void 0,function*(){this._buyNowInitializeOptions&&this._requiresShipping&&(yield this._createBuyNowCart()),yield this._handleShippingContactSelected(e,n,t)}),e.onshippingmethodselected=t=>b_(this,void 0,void 0,function*(){yield this._handleShippingMethodSelected(e,n,t)}),e.oncancel=()=>b_(this,void 0,void 0,function*(){try{const e=`/remote-checkout/${t.id}/signout`;return yield this._requestSender.get(e),yield this._paymentIntegrationService.loadCheckout()}catch(e){throw new Wi}}),e.onpaymentauthorized=n=>b_(this,void 0,void 0,function*(){return this._onPaymentAuthorized(n,e,t)})}_createBuyNowCart(){var e,t;return b_(this,void 0,void 0,function*(){try{const n=null===(t=null===(e=this._buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody)||void 0===t?void 0:t.call(e);if(!n)throw new ti(Xn.MissingCart);const i=yield this._paymentIntegrationService.createBuyNowCart(n);yield this._paymentIntegrationService.loadCheckout(i.id);const r=this._paymentIntegrationService.getState(),{shouldExecuteSpamCheck:o}=r.getCheckoutOrThrow();o&&(yield this._paymentIntegrationService.verifyCheckoutSpamProtection())}catch(e){throw new er}})}_handlePaymentMethodSelected(e){const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getStoreConfigOrThrow(),r=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new ti(Xn.MissingPaymentMethod);const o=this._getBaseRequest(n,r,i,this._paymentMethod);delete o.total.type,e.completePaymentMethodSelection({newTotal:o.total,newLineItems:o.lineItems})}_handleShippingContactSelected(e,t,n){var i;return b_(this,void 0,void 0,function*(){const r=this._transformContactToAddress(n.shippingContact);try{yield this._paymentIntegrationService.updateShippingAddress(r)}catch(t){throw e.abort(),new Error("Shipping address update failed")}let o=this._paymentIntegrationService.getState();const{currency:{decimalPlaces:a}}=o.getCartOrThrow();let s=o.getCheckoutOrThrow();const d=null===(i=s.consignments[0].selectedShippingOption)||void 0===i?void 0:i.id,c=s.consignments[0].availableShippingOptions,l=null==c?void 0:c.find(({id:e})=>e===d),u=null==c?void 0:c.filter(e=>e.id!==d),h=l?[{label:l.description,amount:`${l.cost.toFixed(a)}`,detail:l.additionalDescription,identifier:l.id}]:[];if(u&&[...u.filter(e=>e.isRecommended),...u.filter(e=>!e.isRecommended)].forEach(e=>h.push({label:e.description,amount:`${e.cost.toFixed(a)}`,detail:e.additionalDescription,identifier:e.id})),!(c instanceof Array))throw new Error("Shipping options not available.");if(0===c.length)return void e.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:t,amount:`${s.grandTotal.toFixed(a)}`},[]);const p=c.find(e=>e.isRecommended),m=p?p.id:c[0].id,y=l?l.id:m;try{yield this._updateShippingOption(y)}catch(e){throw new Error("Shipping options update failed")}o=this._paymentIntegrationService.getState(),s=o.getCheckoutOrThrow(),e.completeShippingContactSelection({newShippingMethods:h,newTotal:{type:"final",label:t,amount:`${s.grandTotal.toFixed(a)}`},newLineItems:this._getUpdatedLineItems(s,a)})})}_handleShippingMethodSelected(e,t,n){return b_(this,void 0,void 0,function*(){const{shippingMethod:{identifier:i}}=n;try{yield this._updateShippingOption(i)}catch(t){throw e.abort(),new Error("Shipping option selection update failed.")}const r=this._paymentIntegrationService.getState(),{currency:{decimalPlaces:o}}=r.getCartOrThrow(),a=r.getCheckoutOrThrow();e.completeShippingMethodSelection({newTotal:{type:"final",label:t,amount:`${a.grandTotal.toFixed(o)}`},newLineItems:this._getUpdatedLineItems(a,o)})})}_getUpdatedLineItems(e,t){const n=[{label:this._subTotalLabel,amount:`${e.subtotal.toFixed(t)}`}];return e.taxes.forEach(e=>n.push({label:e.name,amount:`${e.amount.toFixed(t)}`})),n.push({label:this._shippingLabel,amount:`${e.shippingCostTotal.toFixed(t)}`}),n}_updateShippingOption(e){return b_(this,void 0,void 0,function*(){return this._paymentIntegrationService.selectShippingOption(e)})}_onValidateMerchant(e,t){return b_(this,void 0,void 0,function*(){const n=[`validationUrl=${t.validationURL}`,`merchantIdentifier=${e.initializationData.merchantId}`,`displayName=${e.initializationData.storeName}`,`domainName=${window.location.hostname}`].join("&");return this._requestSender.post(`${e.initializationData.paymentsUrl}/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})})}_onPaymentAuthorized(e,t,n){var i;return b_(this,void 0,void 0,function*(){const{token:r,billingContact:o,shippingContact:a}=e.payment,s=this._paymentIntegrationService.getState().getCartOrThrow().lineItems.physicalItems.length>0;let d;(null===(i=n.initializationData)||void 0===i?void 0:i.gateway)===Vi.BRAINTREE&&(d=yield this._getBraintreeDeviceData());const c={methodId:n.id,paymentData:{deviceSessionId:d,formattedPayload:{apple_pay_token:{payment_data:r.paymentData,payment_method:r.paymentMethod,transaction_id:r.transactionIdentifier}}}},l=this._transformContactToAddress(o),u=this._transformContactToAddress(a),h=null==a?void 0:a.emailAddress,p=(null==a?void 0:a.phoneNumber)||"";try{return yield this._paymentIntegrationService.updateBillingAddress(Object.assign(Object.assign({},l),{email:h,phone:p})),s&&(yield this._paymentIntegrationService.updateShippingAddress(u)),yield this._paymentIntegrationService.submitOrder({useStoreCredit:!1}),yield this._paymentIntegrationService.submitPayment(c),t.completePayment(ApplePaySession.STATUS_SUCCESS),this._onAuthorizeCallback()}catch(e){throw t.completePayment(ApplePaySession.STATUS_FAILURE),new Error("Payment cannot complete")}})}_transformContactToAddress(e){return{firstName:(null==e?void 0:e.givenName)||"",lastName:(null==e?void 0:e.familyName)||"",city:(null==e?void 0:e.locality)||"",company:"",address1:(null==e?void 0:e.addressLines)&&e.addressLines[0]||"",address2:(null==e?void 0:e.addressLines)&&e.addressLines[1]||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||"",phone:(null==e?void 0:e.phoneNumber)||"",stateOrProvince:(null==e?void 0:e.administrativeArea)||"",stateOrProvinceCode:(null==e?void 0:e.administrativeArea)||"",customFields:[]}}_getBraintreeDeviceData(){return b_(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}const O_=vi(e=>{const{getHost:t}=e.getState(),i=new Ei(e);return new P_(n({host:t()}),e,new Zi,new Ui(new Hi(a(),window,i)),new Qi(new r))},[{id:"applepay"}]);var E_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class A_{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){var t;return E_(this,void 0,void 0,function*(){const{bigcommerce_payments:n,containerId:i,methodId:r}=e,o=Boolean(null==n?void 0:n.buyNowInitializeOptions);if(!r)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');if(o&&!n.currencyCode)throw new fi('Unable to initialize payment because "options.bigcommerce_payments.currencyCode" argument is not provided.');if(o&&"function"!=typeof(null===(t=n.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.bigcommerce_payments.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');o||(yield this.paymentIntegrationService.loadDefaultCheckout());const a=o?n.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(r,a,!1),this.renderButton(i,r,n,o)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n,i){var r,o;const{buyNowInitializeOptions:a,style:s,onComplete:d,onEligibilityFailure:c}=n,l=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),u=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:h,isAppSwitchEnabled:p}=u.initializationData||{},m=Object.assign(Object.assign({},!i&&this.isPaypalCommerceAppSwitchEnabled(t)&&{appSwitchWhenAvailable:!0}),{createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)}),y={onClick:()=>this.handleClick(a),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},g=Object.assign(Object.assign({},!p&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(e,n)=>this.onHostedCheckoutApprove(e,n,t,d)}),v=Object.assign(Object.assign(Object.assign({fundingSource:l.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(s)},m),a&&y),h&&g),f=l.Buttons(v);f.isEligible()?(null===(r=f.hasReturned)||void 0===r?void 0:r.call(f))&&this.isPaypalCommerceAppSwitchEnabled(t)?null===(o=f.resume)||void 0===o||o.call(f):f.render(`#${e}`):c&&"function"==typeof c?c():this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return E_(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,n,i){return E_(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return E_(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return E_(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}isPaypalCommerceAppSwitchEnabled(e){var t,n;return null!==(n=null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)&&void 0!==n&&n}}const T_=vi(e=>new A_(e,_r(e)),[{id:"bigcommerce_payments"}]);var k_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class D_{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return k_(this,void 0,void 0,function*(){const{bigcommerce_payments_paylater:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');if(a&&!o)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.bigcommerce_payments_paylater.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=this.paymentIntegrationService.getState(),d=a?o:s.getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i,d,!1),this.renderButton(n,i,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){const{buyNowInitializeOptions:i,style:r,onComplete:o,onEligibilityFailure:a}=n,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:c}=d.initializationData||{},l={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},u={onClick:()=>this.handleClick(i),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},h={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(e,n)=>this.onHostedCheckoutApprove(e,n,t,o)},p=[s.FUNDING.PAYLATER,s.FUNDING.CREDIT];let m=!1;p.forEach(t=>{if(!m){const n=Object.assign(Object.assign(Object.assign({fundingSource:t,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(r)},l),i&&u),c&&h),o=s.Buttons(n);o.isEligible()?(o.render(`#${e}`),m=!0):a&&"function"==typeof a&&a()}}),m||this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return k_(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,n,i){return k_(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return k_(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return k_(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}}const M_=vi(e=>new D_(e,_r(e)),[{id:"bigcommerce_payments_paylater"}]);var z_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class N_{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return z_(this,void 0,void 0,function*(){const{bigcommerce_payments_venmo:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');if(a&&!o)throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.bigcommerce_payments_venmo.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=a?o:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i,s,!1),this.renderButton(n,i,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){const{buyNowInitializeOptions:i,style:r,onEligibilityFailure:o}=n,a=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),s=a.FUNDING.VENMO,d={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},c={onClick:()=>this.handleClick(i),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},l=Object.assign(Object.assign({fundingSource:s,style:this.getValidVenmoButtonStyles(r)},d),i&&c),u=a.Buttons(l);u.isEligible()?u.render(`#${e}`):o&&"function"==typeof o?o():this.bigCommercePaymentsIntegrationService.removeElement(e)}getValidVenmoButtonStyles(e){const t=this.bigCommercePaymentsIntegrationService.getValidButtonStyle(e);return t.color===ar.gold?Object.assign(Object.assign({},t),{color:void 0}):t}handleClick(e){return z_(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const x_=vi(e=>new N_(e,_r(e)),[{id:"bigcommerce_payments_venmo"}]);class R_{constructor(e,t,n=window){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=n}initialize(e){return t=this,n=void 0,r=function*(){const{bolt:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,style:o}=t||{};if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.bolt" argument is not provided.');if(!Boolean(r))throw new Si("Only buy now flow is implemented for Bolt button");if(!(null==r?void 0:r.storefrontApiToken)||"string"!=typeof r.storefrontApiToken)throw new fi('Unable to initialize payment because "options.storefrontApiToken" argument is not provided.');const a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i),{initializationData:s,config:d}=a,{publishableKey:c,developerConfig:l}=s||{};yield this.boltScriptLoader.loadBoltClient(c,d.testMode,l,"BigCommerce",r.storefrontApiToken),this.renderButton(n,a,o)},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}deinitialize(){return Promise.resolve()}renderButton(e,t,n){var i;"function"==typeof(null===(i=this.boltHostWindow.BoltConnect)||void 0===i?void 0:i.setupProductPageCheckout)&&(this.addButtonContainer(e,t,n),this.boltHostWindow.BoltConnect.setupProductPageCheckout())}addButtonContainer(e,t,n){const i=document.getElementById(e);if(!i)return;const r=document.createElement("div"),o=document.createElement("object");r.setAttribute("id","product-page-checkout-wrapper"),r.setAttribute("class","bolt-button-wrapper"),r.setAttribute("style","display:none"),r.setAttribute("data-tid","product-page-checkout-wrapper"),o.setAttribute("data",this.getBoltObjectData(t,n)),o.setAttribute("class","bolt-product-checkout-button"),r.append(o),i.innerHTML="",i.append(r)}getBoltObjectData(e,t){const{initializationData:n,config:i}=e,{publishableKey:r,developerConfig:o}=n||{},a=this.boltScriptLoader.getDomainURL(!!i.testMode,o),s=this.getButtonHeight(null==t?void 0:t.size),d=this.getButtonBorderRadius(null==t?void 0:t.shape,s);return xe({url:`https://${a}/v1/checkout_button`,query:{publishable_key:r,variant:"ppc",height:s,border_radius:d}})}getButtonHeight(e){if(e)switch(e){case to.Small:return 25;case to.Large:return 45;case to.Medium:default:return 40}}getButtonBorderRadius(e,t){if(e)switch(e){case no.Pill:return t?Math.round(t/2):void 0;case no.Rect:default:return 4}}}const F_=vi(e=>new R_(e,new ao(a())),[{id:"bolt"}]);function L_(e){const{color:t,fundingicons:n,height:i=40,layout:r,shape:o,size:a,tagline:s}=e||{},d={color:t,fundingicons:n,height:B_(i),layout:r,shape:o||"rect",size:a,tagline:s};return ue(d,J)}function B_(e){const t=Number(e);return!t||Number.isNaN(t)?40:t>55?55:t<25?25:t}var j_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class U_{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return j_(this,void 0,void 0,function*(){const{braintreepaypal:t,containerId:n,methodId:i}=e;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');let r,o=this.paymentIntegrationService.getState();if(t.buyNowInitializeOptions){if(!t.currencyCode)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');r=t.currencyCode}else yield this.paymentIntegrationService.loadDefaultCheckout(),o=this.paymentIntegrationService.getState(),r=o.getCartOrThrow().currency.code;const a=o.getPaymentMethodOrThrow(i),{clientToken:s,config:d,initializationData:c}=a;if(!s||!c)throw new ti(Xn.MissingPaymentMethod);const l={currency:r,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(l,e=>{this.renderPayPalButton(e,t,n,i,!!d.testMode)},e=>this.handleError(e,n,t.onError))})}deinitialize(){return j_(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}renderPayPalButton(e,t,n,i,r){const{style:o,shouldProcessPayment:a,onAuthorizeError:s,onEligibilityFailure:d}=t,{paypal:c}=this.braintreeHostWindow;if(c){const l=c.Buttons({env:r?"sandbox":"production",fundingSource:c.FUNDING.PAYPAL,style:L_(o),createOrder:()=>this.setupPayment(e,t,i),onApprove:t=>this.tokenizePayment(t,e,i,a,s)});l.isEligible()?l.render(`#${n}`):d&&"function"==typeof d&&d()}else this.braintreeIntegrationService.removeElement(n)}setupPayment(e,t,n){var i;return j_(this,void 0,void 0,function*(){const{onPaymentError:r,shippingAddress:o,buyNowInitializeOptions:a}=t;try{const r="function"==typeof(null==a?void 0:a.getBuyNowCartRequestBody)?yield this.createBuyNowCart(a.getBuyNowCartRequestBody()):void 0;this.buyNowCartId=null==r?void 0:r.id;const s=this.paymentIntegrationService.getState(),d=s.getCustomer(),c=s.getPaymentMethodOrThrow(n),l=r?r.cartAmount:s.getCartOrThrow().cartAmount,u=r?t.currencyCode:s.getCartOrThrow().currency.code,h=o||(null==d?void 0:d.addresses[0]),p=h?El(h):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:p,amount:l,currency:u,offerCredit:!1,intent:null===(i=c.initializationData)||void 0===i?void 0:i.intent})}catch(e){throw r&&(Ri(e)||e instanceof Qn)&&r(e),e}})}tokenizePayment(e,t,n,i,r){return j_(this,void 0,void 0,function*(){try{const{deviceData:r}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),o=yield t.tokenizePayment(e),{details:a,nonce:s}=o,d=this.braintreeIntegrationService.mapToLegacyBillingAddress(a),c=this.braintreeIntegrationService.mapToLegacyShippingAddress(a);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",provider:n,action:i?"process_payment":"set_external_checkout",nonce:s,device_data:r,billing_address:JSON.stringify(d),shipping_address:JSON.stringify(c)},this.buyNowCartId&&{cart_id:this.buyNowCartId})),o}catch(e){throw r&&(Ri(e)||e instanceof Qn)&&r(e),e}})}createBuyNowCart(e){return j_(this,void 0,void 0,function*(){if(!e)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(e)}catch(e){throw new er}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const q_=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t);return new U_(e,Ee(),i,t)},[{id:"braintreepaypal"}]);var V_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class G_{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return V_(this,void 0,void 0,function*(){const{braintreepaypalcredit:t,containerId:n,methodId:i}=e;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');let r,o=this.paymentIntegrationService.getState();if(t.buyNowInitializeOptions){if(!t.currencyCode)throw new fi('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');r=t.currencyCode}else yield this.paymentIntegrationService.loadDefaultCheckout(),o=this.paymentIntegrationService.getState(),r=o.getCartOrThrow().currency.code;const a=o.getPaymentMethodOrThrow(i),{clientToken:s,config:d,initializationData:c}=a;if(!s||!c)throw new ti(Xn.MissingPaymentMethod);const l={currency:r,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(l,e=>{this.renderPayPalButton(e,t,n,i,!!d.testMode)},e=>this.handleError(e,n,t.onError))})}deinitialize(){return V_(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}renderPayPalButton(e,t,n,i,r){const{style:o,shouldProcessPayment:a,onAuthorizeError:s,onEligibilityFailure:d}=t,{paypal:c}=this.braintreeHostWindow;let l=!1;c&&[c.FUNDING.PAYLATER,c.FUNDING.CREDIT].forEach(u=>{const h=u===c.FUNDING.CREDIT?Object.assign({label:go.CREDIT},L_(o)):L_(o);if(!l){const o=c.Buttons({env:r?"sandbox":"production",fundingSource:u,style:h,createOrder:()=>this.setupPayment(e,t,i),onApprove:t=>this.tokenizePayment(t,e,i,a,s)});o.isEligible()?(o.render(`#${n}`),l=!0):c.FUNDING.CREDIT&&d&&"function"==typeof d&&d()}}),c&&l||this.braintreeIntegrationService.removeElement(n)}setupPayment(e,t,n){var i;return V_(this,void 0,void 0,function*(){const{onPaymentError:r,shippingAddress:o,buyNowInitializeOptions:a}=t;try{const r="function"==typeof(null==a?void 0:a.getBuyNowCartRequestBody)?yield this.createBuyNowCart(a.getBuyNowCartRequestBody()):void 0;this.buyNowCartId=null==r?void 0:r.id;const s=this.paymentIntegrationService.getState(),d=s.getCustomer(),c=s.getPaymentMethodOrThrow(n),l=r?r.cartAmount:s.getCartOrThrow().cartAmount,u=r?t.currencyCode:s.getCartOrThrow().currency.code,h=o||(null==d?void 0:d.addresses[0]),p=h?El(h):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:p,amount:l,currency:u,offerCredit:!0,intent:null===(i=c.initializationData)||void 0===i?void 0:i.intent})}catch(e){throw r&&(Ri(e)||e instanceof Qn)&&r(e),e}})}tokenizePayment(e,t,n,i,r){return V_(this,void 0,void 0,function*(){try{const{deviceData:r}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),o=yield t.tokenizePayment(e),{details:a,nonce:s}=o,d=this.braintreeIntegrationService.mapToLegacyBillingAddress(a),c=this.braintreeIntegrationService.mapToLegacyShippingAddress(a);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",provider:n,action:i?"process_payment":"set_external_checkout",nonce:s,device_data:r,billing_address:JSON.stringify(d),shipping_address:JSON.stringify(c)},this.buyNowCartId&&{cart_id:this.buyNowCartId})),o}catch(e){throw r&&(Ri(e)||e instanceof Qn)&&r(e),e}})}createBuyNowCart(e){return V_(this,void 0,void 0,function*(){if(!e)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(e)}catch(e){throw new er}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const H_=vi(e=>{const t=window,n=new Ei(e),i=new _o(new Hi(a(),t,n),t);return new G_(e,Ee(),i,t)},[{id:"braintreepaypalcredit"}]);var W_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class $_{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n}initialize(e){return W_(this,void 0,void 0,function*(){const{containerId:t,methodId:n}=e;if(!n)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState(),{clientToken:r,initializationData:o,config:a}=i.getPaymentMethodOrThrow(n);if(!r||!o)throw new ti(Xn.MissingPaymentMethod);this.braintreeSdk.initialize(r);const s=yield this.braintreeSdk.getBraintreeVisaCheckout(),{currency:{code:d},cartAmount:c}=i.getCartOrThrow(),l=yield this.braintreeSdk.getVisaCheckoutSdk(a.testMode),u=s.createInitOptions({paymentRequest:{currencyCode:d,subtotal:String(c)},settings:{shipping:{collectShipping:!0}}});this.createSignInButton(t),yield l.init(u),l.on("payment.success",e=>W_(this,void 0,void 0,function*(){yield this.paymentSuccess(s,e)}))})}deinitialize(){return Promise.resolve()}paymentSuccess(e,t){return W_(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const n=this.paymentIntegrationService.getState(),i=n.getShippingAddress(),r=n.getBillingAddress(),{shippingAddress:o=this.toVisaCheckoutAddress(i),billingAddress:a=this.toVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}postForm(e,t){const{userData:n,billingAddress:i,shippingAddress:r,details:o}=e,{userEmail:a}=n,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,i)),shipping_address:JSON.stringify(this.getAddress(a,r))})}toVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}createSignInButton(e){const t=document.querySelector(`#${e}`);if(!t)throw new Error("Need a container to place the button");return this.insertVisaCheckoutButton(t)}insertVisaCheckoutButton(e){const t=document.createElement("div");return t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="flex-end",t.innerHTML='\n \n Tell Me More',e.appendChild(t),t}}const Y_=vi(e=>{const t=window,n=new Ei(e),i=new Ui(new Hi(a(),t,n));return new $_(e,Ee(),i)},[{id:"braintreevisacheckout"}]);function K_(e){const{billingAddress:t,email:n,firstName:i,lastName:r,phone:o,shippingAddress:a}=e,s=t||a;return{email:n,first_name:i,last_name:r,phone_number:o,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 J_(e){const{email:t,phone:n,shippingAddress:i}=e,r=(null==i?void 0:i.recipientName)||"",[o,a]=r.split(" ");return{email:t,first_name:o||"",last_name:a||"",phone_number:n,address_line_1:null==i?void 0:i.line1,address_line_2:null==i?void 0:i.line2,city:null==i?void 0:i.city,state:null==i?void 0:i.state,country_code:null==i?void 0:i.countryCode,postal_code:null==i?void 0:i.postalCode}}var Z_=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const Q_=e=>{const{color:t,height:n}=e;return{backgroundColor:(i=t||"",i===yo.WHITE?"#FFFFFF":"#3D95CE"),backgroundPosition:"50% 50%",backgroundSize:"80px auto",backgroundImage:`url("/app/assets/img/payment-providers/venmo-logo-${t===yo.WHITE?yo.BLUE:yo.WHITE}.svg")`,backgroundRepeat:"no-repeat",borderRadius:"4px",cursor:"pointer",transition:"0.2s ease",minHeight:`${n||40}px`,minWidth:"150px",height:"100%",width:"100%",border:t===yo.WHITE?"1px solid black":"none"};var i};class X_{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n,this.onError=ce}initialize(e){return Z_(this,void 0,void 0,function*(){const{braintreevenmo:t,containerId:n,methodId:i}=e;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i),{clientToken:o,initializationData:a}=r,{paymentButtonStyles:s}=a,{cartButtonStyles:d}=s||{},c=(null==t?void 0:t.style)||d;if(!o||!a)throw new ti(Xn.MissingPaymentMethod);if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');yield this.paymentIntegrationService.loadDefaultCheckout(),this.onError=(null==t?void 0:t.onError)||this.handleError,this.braintreeSdk.initialize(o);try{const e=yield this.braintreeSdk.getVenmoCheckoutOrThrow();this.renderVenmoButton(e,n,null==t?void 0:t.buyNowInitializeOptions,c)}catch(e){(Ol(e)||function(e){return e instanceof Ai}(e))&&this.handleInitializationVenmoError(e,n)}})}deinitialize(){return Z_(this,void 0,void 0,function*(){return yield this.braintreeSdk.deinitialize(),Promise.resolve()})}handleError(e){throw new Error(e.message)}createBuyNowCart(e){return Z_(this,void 0,void 0,function*(){if("function"==typeof(null==e?void 0:e.getBuyNowCartRequestBody)){const t=null==e?void 0:e.getBuyNowCartRequestBody();if(!t)throw new ti(Xn.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}}})}handleInitializationVenmoError(e,t){return this.removeVenmoContainer(t),this.onError(e)}removeVenmoContainer(e){const t=document.getElementById(e);t&&t.remove()}renderVenmoButton(e,t,n,i){const r=document.getElementById(t),{color:o}=i||{};if(!r)throw new fi("Unable to create wallet button without valid container ID.");r.setAttribute("aria-label","Venmo"),Object.assign(r.style,Q_(i||{})),r.addEventListener("click",()=>Z_(this,void 0,void 0,function*(){r.setAttribute("disabled","true");const t=yield this.createBuyNowCart(n);e.tokenize&&e.tokenize((e,n)=>Z_(this,void 0,void 0,function*(){r.removeAttribute("disabled"),e&&this.onError(e),yield this.handlePostForm(n,null==t?void 0:t.id)}))})),o===yo.BLUE&&(r.addEventListener("mouseenter",()=>{r.style.backgroundColor="#0a7fc2"}),r.addEventListener("mouseleave",()=>{r.style.backgroundColor=Q_(i||{}).backgroundColor}))}handlePostForm(e,t){return Z_(this,void 0,void 0,function*(){const{deviceData:n}=yield this.braintreeSdk.getDataCollectorOrThrow(),{nonce:i,details:r}=e;this.formPoster.postForm("/checkout.php",Object.assign({nonce:i,provider:"braintreevenmo",payment_type:"paypal",device_data:n,action:"set_external_checkout",billing_address:JSON.stringify(K_(r)),shipping_address:JSON.stringify(J_(r))},t&&{cart_id:t}))})}}const ew=vi(e=>{const t=window,n=a(),i=new Ei(e),r=new Hi(n,t,i),o=new Ui(r);return new X_(e,Ee(),o)},[{id:"braintreevenmo"}]);var tw=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class nw{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t}initialize(e){var t,n,i;return tw(this,void 0,void 0,function*(){if(!e.methodId||!na(e.methodId))throw new fi('Unable to proceed because "methodId" is not a valid key.');if(this._methodId=e.methodId,!e.containerId)throw new fi('Unable to proceed because "containerId" is not a valid key.');const r=e[this._getMethodOrThrow()];if(!r)throw new fi("Unable to proceed without valid options.");const{buyNowInitializeOptions:o,currencyCode:a,buttonColor:s,buttonType:d,onError:c}=r;let l,u=this._paymentIntegrationService.getState();try{l=u.getPaymentMethodOrThrow(this._getMethodOrThrow())}catch(e){u=yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodOrThrow()),l=u.getPaymentMethodOrThrow(this._getMethodOrThrow())}if(this._countryCode=null===(t=l.initializationData)||void 0===t?void 0:t.storeCountry,this._googlePayPaymentProcessor.setIsWebViewExperimentOn(!!(null===(n=l.initializationData)||void 0===n?void 0:n.isWebViewExperimentOn)),o){if(!a)throw new fi('Unable to initialize payment because "options.currencyCode" argument is not provided.');this._currencyCode=a,this._buyNowInitializeOptions=o,yield this._googlePayPaymentProcessor.initialize(()=>l,this._getGooglePayClientOptions(),!!o,a)}else yield this._paymentIntegrationService.loadDefaultCheckout(),yield this._googlePayPaymentProcessor.initialize(()=>l,this._getGooglePayClientOptions());this._paymentButton=null!==(i=this._paymentButton)&&void 0!==i?i:this._googlePayPaymentProcessor.addPaymentButton(e.containerId,{buttonColor:null!=s?s:"default",buttonType:null!=d?d:"plain",onClick:this._handleClick(c)})})}deinitialize(){var e;return null===(e=this._paymentButton)||void 0===e||e.remove(),this._paymentButton=void 0,this._methodId=void 0,Promise.resolve()}_handleClick(e){return t=>tw(this,void 0,void 0,function*(){t.preventDefault();try{this._buyNowInitializeOptions?yield this._createBuyNowCartOrThrow(this._buyNowInitializeOptions):yield this._paymentIntegrationService.loadDefaultCheckout(),yield this._googlePayPaymentProcessor.initializeWidget(),yield this._interactWithPaymentSheet()}catch(t){let n=t;if(ta(t)){if("CANCELED"===t.statusCode)throw new Wi;n=new Qr(JSON.stringify(t))}throw null==e||e(new Qr("An error occurred while requesting your Google Pay payment details.")),n}})}_interactWithPaymentSheet(){var e;return tw(this,void 0,void 0,function*(){const t=yield this._googlePayPaymentProcessor.showPaymentSheet(),n=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(t),i=this._googlePayPaymentProcessor.mapToShippingAddressRequestBody(t),r="/embedded-checkout"===window.location.pathname?this._paymentIntegrationService.getState().getStoreConfigOrThrow().links.siteLink:void 0;n&&(yield this._paymentIntegrationService.updateBillingAddress(n)),i&&!(null===(e=this._buyNowCart)||void 0===e?void 0:e.lineItems.digitalItems.length)&&(yield this._paymentIntegrationService.updateShippingAddress(i)),yield this._googlePayPaymentProcessor.setExternalCheckoutForm(this._getMethodOrThrow(),t,r)})}_getGooglePayClientOptions(){return this._googlePayPaymentProcessor.isWebViewWithRestrictions()?{}:{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:e,shippingAddress:t,shippingOptionData:n,offerData:i})=>tw(this,void 0,void 0,function*(){const{availableTriggers:r,addressChangeTriggers:o,shippingOptionsChangeTriggers:a,offerChangeTriggers:s}=this._googlePayPaymentProcessor.getCallbackTriggers();if(!r.includes(e))return;const d=o.includes(e)?yield this._googlePayPaymentProcessor.handleShippingAddressChange(t):void 0;a.includes(e)&&(yield this._googlePayPaymentProcessor.handleShippingOptionChange(n.id));const{newOfferInfo:c,error:l}=s.includes(e)?yield this._googlePayPaymentProcessor.handleCoupons(i):{},u=l;return this._buyNowInitializeOptions?this._getBuyNowTransactionInfo(d,c,u):this._getTransactionInfo(d,c,u)})}}}_createBuyNowCartOrThrow(e){return tw(this,void 0,void 0,function*(){if("function"==typeof(null==e?void 0:e.getBuyNowCartRequestBody)){const t=e.getBuyNowCartRequestBody();try{this._buyNowCart=yield this._paymentIntegrationService.createBuyNowCart(t),yield this._paymentIntegrationService.loadCheckout(this._buyNowCart.id)}catch(e){if("string"==typeof e)throw new er(e);throw e}}})}_getBuyNowTransactionInfo(e,t,n){if(!this._buyNowCart)return;const{cartAmount:i}=this._buyNowCart,r=this._googlePayPaymentProcessor.getTotalPrice();return Object.assign(Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},this._countryCode&&{countryCode:this._countryCode}),{currencyCode:this._getCurrencyCodeOrThrow(),totalPrice:r||String(i),totalPriceStatus:Wo.FINAL})},e&&{newShippingOptionParameters:e}),t&&{newOfferInfo:t}),n&&{error:n})}_getTransactionInfo(e,t,n){return tw(this,void 0,void 0,function*(){yield this._paymentIntegrationService.loadCheckout();const i=this._googlePayPaymentProcessor.getTotalPrice(),{code:r}=this._paymentIntegrationService.getState().getCartOrThrow().currency;return Object.assign(Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},this._countryCode&&{countryCode:this._countryCode}),{currencyCode:r,totalPriceStatus:Wo.FINAL,totalPrice:i})},e&&{newShippingOptionParameters:e}),t&&{newOfferInfo:t}),n&&{error:n})})}_getMethodOrThrow(){return ii(this._methodId,()=>new ri(ei.PaymentNotInitialized))}_getCurrencyCodeOrThrow(){return ii(this._currencyCode,()=>new fi('Unable to initialize payment because "options.currencyCode" argument is not provided.'))}}const iw=vi(e=>{const t=n(),i=window,r=new Ei(e),o=new Ui(new Hi(a(),i,r));return new nw(e,new aa(da(),new $a(e,o),t,Ee()))},[{id:"googlepaybraintree"}]),rw=vi(e=>new nw(e,new aa(da(),new ns(e,new Xa(a())),n(),Ee())),[{id:"googlepaypaypalcommerce"}]),ow=vi(e=>new nw(e,new aa(da(),new os(e,new xr(a())),n(),Ee())),[{id:"googlepay_bigcommerce_payments"}]),aw=vi(e=>{const t=n();return new nw(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv2"}]),sw=vi(e=>{const t=n();return new nw(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv3"}]),dw=vi(e=>new nw(e,new aa(da(),new ua(e),n(),Ee())),[{id:"googlepayauthorizenet"}]),cw=vi(e=>{const t=n();return new nw(e,new aa(da(),new ga(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]),lw=vi(e=>new nw(e,new aa(da(),new fa(e),n(),Ee())),[{id:"googlepaycybersourcev2"},{id:"googlepaybnz"}]),uw=vi(e=>new nw(e,new aa(da(),new wa(e),n(),Ee())),[{id:"googlepayorbital"}]),hw=vi(e=>new nw(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeupe"},{id:"googlepaystripeocs"}]),pw=vi(e=>new nw(e,new aa(da(),new Ga(e),n(),Ee())),[{id:"googlepayworldpayaccess"}]),mw=vi(e=>new nw(e,new aa(da(),new cs(e,Ee()),n(),Ee())),[{id:"googlepaytdonlinemart"}]);class yw{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.paypalButtonCreationService=n}initialize(e){var t,n,i,r,o;return n=this,i=void 0,o=function*(){const{paypalcommerce:n,containerId:i,methodId:r}=e,o=Boolean(null==n?void 0:n.buyNowInitializeOptions);if(!r)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(o&&!n.currencyCode)throw new fi('Unable to initialize payment because "options.paypalcommerce.currencyCode" argument is not provided.');if(o&&"function"!=typeof(null===(t=n.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.paypalcommerce.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');o||(yield this.paymentIntegrationService.loadDefaultCheckout());const a=o?n.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.paypalIntegrationService.loadPayPalSdk(r,a,!1),this.renderButton(i,r,n)},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){var i,r;const{buyNowInitializeOptions:o,style:a,onComplete:s,onEligibilityFailure:d}=n,c=this.paypalIntegrationService.getPayPalSdkOrThrow(),l=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:u,isAppSwitchEnabled:h}=l.initializationData||{},p={onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},m=Object.assign(Object.assign({fundingSource:c.FUNDING.PAYPAL,style:this.paypalIntegrationService.getValidButtonStyle(a),isAppSwitchEnabled:h,isHostedCheckoutEnabled:u},o&&p),u&&s&&{onPaymentComplete:()=>s()}),y=this.paypalButtonCreationService.createPayPalButton("paypalcommerce",t,m,o);y.isEligible()?(null===(i=y.hasReturned)||void 0===i?void 0:i.call(y))&&h?null===(r=y.resume)||void 0===r||r.call(y):y.render(`#${e}`):d&&"function"==typeof d?d():this.paypalIntegrationService.removeElement(e)}}const gw=vi(e=>{const t=As(e),n=new ks(e,t);return new yw(e,t,n)},[{id:"paypalcommerce"}]);var vw=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class fw{constructor(e,t){this.paymentIntegrationService=e,this.paypalIntegrationService=t}initialize(e){return vw(this,void 0,void 0,function*(){const{paypalcommercecredit:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(a&&!o)throw new fi('Unable to initialize payment because "options.paypalcommercecredit.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.paypalcommercecredit.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=this.paymentIntegrationService.getState(),d=a?o:s.getCartOrThrow().currency.code;yield this.paypalIntegrationService.loadPayPalSdk(i,d,!1),this.renderButton(n,i,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){const{buyNowInitializeOptions:i,style:r,onComplete:o,onEligibilityFailure:a}=n,s=this.paypalIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:c,isAppSwitchEnabled:l}=d.initializationData||{},u={createOrder:()=>this.paypalIntegrationService.createOrder("paypalcommercecredit"),onApprove:({orderID:e})=>this.paypalIntegrationService.tokenizePayment(t,e)},h={onClick:()=>this.handleClick(i),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},p=Object.assign(Object.assign({},!l&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(e,n)=>this.onHostedCheckoutApprove(e,n,t,o)}),m=[s.FUNDING.PAYLATER,s.FUNDING.CREDIT];let y=!1;m.forEach(t=>{if(!y){const n=Object.assign(Object.assign(Object.assign({fundingSource:t,style:this.paypalIntegrationService.getValidButtonStyle(r)},u),i&&h),c&&p),o=s.Buttons(n);o.isEligible()?(o.render(`#${e}`),y=!0):a&&"function"==typeof a&&a()}}),y||this.paypalIntegrationService.removeElement(e)}handleClick(e){return vw(this,void 0,void 0,function*(){if(e){const t=yield this.paypalIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,n,i){return vw(this,void 0,void 0,function*(){if(!e.orderID)throw new ti(Xn.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.paypalIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.paypalIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.paypalIntegrationService.updateOrder("paypalcommerce")}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.paypalIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return vw(this,void 0,void 0,function*(){const t=this.paypalIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.paypalIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.paypalIntegrationService.updateOrder("paypalcommerce")}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return vw(this,void 0,void 0,function*(){const t=this.paypalIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.paypalIntegrationService.updateOrder("paypalcommerce")}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}}const Sw=vi(e=>new fw(e,As(e)),[{id:"paypalcommercecredit"}]);var _w=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ww{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}initialize(e){return _w(this,void 0,void 0,function*(){const{paypalcommercevenmo:t,containerId:n,methodId:i}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!i)throw new fi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new fi('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(a&&!o)throw new fi('Unable to initialize payment because "options.paypalcommercevenmo.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new fi('Unable to initialize payment because "options.paypalcommercevenmo.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=a?o:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.paypalCommerceIntegrationService.loadPayPalSdk(i,s,!1),this.renderButton(n,i,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,n){const{buyNowInitializeOptions:i,style:r,onEligibilityFailure:o}=n,a=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),s=a.FUNDING.VENMO,d={createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo"),onApprove:({orderID:e})=>this.paypalCommerceIntegrationService.tokenizePayment(t,e)},c={onClick:()=>this.handleClick(i),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},l=Object.assign(Object.assign({fundingSource:s,style:this.getValidVenmoButtonStyles(r)},d),i&&c),u=a.Buttons(l);u.isEligible()?u.render(`#${e}`):o&&"function"==typeof o?o():this.paypalCommerceIntegrationService.removeElement(e)}getValidVenmoButtonStyles(e){const t=this.paypalCommerceIntegrationService.getValidButtonStyle(e);return t.color===Fs.gold?Object.assign(Object.assign({},t),{color:void 0}):t}handleClick(e){return _w(this,void 0,void 0,function*(){if(e){const t=yield this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const Iw=vi(e=>new ww(e,$s(e)),[{id:"paypalcommercevenmo"}]);var Cw=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class bw{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalExpressScriptLoader=t,this.formPoster=n}initialize(e){return Cw(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);if(!e.paypal)throw new fi;if(!t.config.merchantId)throw new ti(Xn.MissingPaymentMethod);const n=yield this.paypalExpressScriptLoader.loadPaypalSDK(t.config.merchantId);this.renderButton(e,n)})}deinitialize(){return Promise.resolve()}renderButton(e,t){const{containerId:n,methodId:i,paypal:r}=e,{allowCredit:o,clientId:a,onPaymentError:s,shouldProcessPayment:d,style:c}=r,l=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);if(!l.config.merchantId)throw new ti(Xn.MissingPaymentMethod);const u=l.config.merchantId,h=l.config.testMode?"sandbox":"production",p={[h]:a},m=t.FUNDING.CREDIT||"credit",y=o?[m]:[],g=o?[]:[m];return t.Button.render({env:h,client:p,commit:d,funding:{allowed:y,disallowed:g},style:this.getStyle(c),payment:(e,t)=>this.setupPayment(u,t,s),onAuthorize:(e,t)=>this.tokenizePayment(e,i,t,d)},n)}getStyle(e){const{color:t,fundingicons:n,label:i,layout:r,shape:o,size:a,tagline:s}=e||{};return{color:t,fundingicons:n,label:i,layout:r,shape:o||Pp.RECT,size:"small"===a?Ip.RESPONSIVE:a,tagline:s}}setupPayment(e,t,n){return Cw(this,void 0,void 0,function*(){if(!t)throw new ri(ei.CheckoutButtonNotInitialized);try{const n=yield this.paymentIntegrationService.loadDefaultCheckout(),{id:i}=n.getCartOrThrow(),r=n.getHost()||"";return(yield t.request.post(`${r}/api/storefront/payment/paypalexpress`,{merchantId:e,cartId:i},{headers:Object.assign({"X-API-INTERNAL":hr},yr)})).id}catch(e){throw n&&e instanceof Qn&&n(e),e}})}tokenizePayment(e,t,n,i){return Cw(this,void 0,void 0,function*(){if(!n)throw new ri(ei.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new ti(Xn.MissingPayment);const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),o=yield n.payment.get(e.paymentID);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:r.id,action:i?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(o.payer.payer_info)})})}}const Pw=vi(e=>new bw(e,new Tp(a()),Ee()),[{id:"paypalexpress"}]);var Ow=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ew{constructor(e,t,n,i){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n,this.loadingIndicator=i}initialize(e){return Ow(this,void 0,void 0,function*(){const{stripeocs:t,containerId:n}=e||{};if(!t||!n)throw new ri(ei.PaymentNotInitialized);const{gatewayId:i}=t;if(!i)throw new ti(Xn.MissingPaymentMethod);const r=this._getMethodId(i),o=yield this.paymentIntegrationService.loadPaymentMethod(i,{params:{method:r}}),a=o.getPaymentMethodOrThrow(r,i),{loadingContainerId:s,buttonHeight:d,onComplete:c}=t;if(this._loadingIndicatorContainer=s,this._onComplete=c,!dd(a))throw new ti(Xn.MissingPaymentMethod);const{initializationData:l}=a,{captureMethod:u}=l,h=this.stripeIntegrationService.getStripeJsVersion(l);this._captureMethod=u,this._stripeClient=yield this.scriptLoader.getStripeClient(l,o.getCartLocale(),h),yield this.paymentIntegrationService.loadDefaultCheckout(),yield this._mountExpressCheckoutElement(n,this._stripeClient,d),this._initializeEvents(r)})}signIn(){return Promise.resolve()}signOut(){return Promise.resolve()}executePaymentMethodCheckout(){return Promise.resolve()}deinitialize(){return Promise.resolve()}_mountExpressCheckoutElement(e,t,n=40){return Ow(this,void 0,void 0,function*(){const i=this._shouldRequireShippingAddress(),r=Object.assign(Object.assign(Object.assign({shippingAddressRequired:i},i?{allowedShippingCountries:yield this._getAvailableCountries()}:{}),i?{shippingRates:[{id:"_",amount:0,displayName:"Pending rates"}]}:{}),{billingAddressRequired:!0,emailRequired:!0,phoneNumberRequired:!0,paymentMethods:{link:Ta.AUTO,applePay:Ta.NEVER,googlePay:Ta.NEVER,amazonPay:Ta.NEVER,paypal:Ta.NEVER,klarna:Ta.NEVER},buttonHeight:n}),{cartAmount:o=1}=this.paymentIntegrationService.getState().getCart()||{},a=Object.assign({mode:"payment",amount:this._toCents(o),currency:this._getCurrency()},this._captureMethod?{captureMethod:this._captureMethod}:{});this._stripeElements=t.elements(a),this._linkV2Element=this._stripeElements.create(Da.EXPRESS_CHECKOUT,r),this._linkV2Element.mount(`#${e}`)})}_initializeEvents(e){this._linkV2Element&&(this._shouldRequireShippingAddress()&&(this._linkV2Element.on(za.SHIPPING_ADDRESS_CHANGE,e=>Ow(this,void 0,void 0,function*(){return this._onShippingAddressChange(e)})),this._linkV2Element.on(za.SHIPPING_RATE_CHANGE,e=>Ow(this,void 0,void 0,function*(){return this._onShippingRateChange(e)}))),this._linkV2Element.on(za.CONFIRM,t=>Ow(this,void 0,void 0,function*(){return this._onConfirm(t,e)})),this._linkV2Element.on(za.CANCEL,this._onCancel))}_onShippingAddressChange(e){return Ow(this,void 0,void 0,function*(){if(!("address"in e))return;const t=e.address,n={firstName:"",lastName:"",phone:"",company:"",address1:"",address2:"",city:(null==t?void 0:t.city)||"",countryCode:(null==t?void 0:t.country)||"",postalCode:(null==t?void 0:t.postal_code)||"",stateOrProvince:(null==t?void 0:t.state)||"",stateOrProvinceCode:(null==t?void 0:t.state)||"",customFields:[]};yield this.paymentIntegrationService.updateShippingAddress(n);const i=yield this._getAvailableShippingOptions();yield this._updateDisplayedPrice(),(null==i?void 0:i.length)?e.resolve({shippingRates:i}):e.reject()})}_onCancel(){throw new Wi}_onShippingRateChange(e){return Ow(this,void 0,void 0,function*(){if("shippingRate"in e){const{shippingRate:t}=e;yield this._handleShippingOptionChange(null==t?void 0:t.id),yield this._updateDisplayedPrice(),e.resolve({})}})}_onConfirm(e,t){return Ow(this,void 0,void 0,function*(){if("billingDetails"in e&&"shippingAddress"in e&&this._stripeClient&&this._stripeElements){yield this._updateShippingAndBillingAddress(e),yield this.paymentIntegrationService.submitOrder();const n=this._getPaymentPayload(t);try{yield this.paymentIntegrationService.submitPayment(n)}catch(e){yield this._processAdditionalAction(e,t)}}return Promise.resolve()})}_updateShippingAndBillingAddress(e){var t,n,i,r,o,a,s,d;return Ow(this,void 0,void 0,function*(){const c=this._shouldRequireShippingAddress(),l=(null===(n=null===(t=e.shippingAddress)||void 0===t?void 0:t.name)||void 0===n?void 0:n.split(" ")[0])||(null===(r=null===(i=e.billingDetails)||void 0===i?void 0:i.name)||void 0===r?void 0:r.split(" ")[0])||"",u=(null===(a=null===(o=e.shippingAddress)||void 0===o?void 0:o.name)||void 0===a?void 0:a.split(" ")[1])||(null===(d=null===(s=e.billingDetails)||void 0===s?void 0:s.name)||void 0===d?void 0:d.split(" ")[1])||"";if(c){const t=this._mapShippingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateShippingAddress(t)}const h=this._mapBillingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateBillingAddress(h)})}_mapShippingAddress(e,t,n,i){var r,o,a,s,d,c,l;return{firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==e?void 0:e.address)||void 0===r?void 0:r.line1)||"",address2:(null===(o=null==e?void 0:e.address)||void 0===o?void 0:o.line2)||"",city:(null===(a=null==e?void 0:e.address)||void 0===a?void 0:a.city)||"",countryCode:(null===(s=null==e?void 0:e.address)||void 0===s?void 0:s.country)||"",postalCode:(null===(d=null==e?void 0:e.address)||void 0===d?void 0:d.postal_code)||"",stateOrProvince:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",stateOrProvinceCode:(null===(l=null==e?void 0:e.address)||void 0===l?void 0:l.state)||"",customFields:[]}}_mapBillingAddress(e,t,n,i){var r,o,a,s,d,c;return{email:(null==t?void 0:t.email)||"",firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==t?void 0:t.address)||void 0===r?void 0:r.line1)||"",address2:"",city:(null===(o=null==t?void 0:t.address)||void 0===o?void 0:o.city)||"",countryCode:(null===(a=null==t?void 0:t.address)||void 0===a?void 0:a.country)||"",postalCode:(null===(s=null==t?void 0:t.address)||void 0===s?void 0:s.postal_code)||"",stateOrProvince:(null===(d=null==t?void 0:t.address)||void 0===d?void 0:d.state)||"",stateOrProvinceCode:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",customFields:[]}}_processAdditionalAction(e,t){return Ow(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeClient||!this._stripeElements)throw new ri(ei.PaymentNotInitialized);const{data:n}=e.body.additional_action_required,{token:i}=n,{paymentIntent:r}=yield this._confirmStripePaymentOrThrow(n,t),o=this._getPaymentPayload(t,(null==r?void 0:r.id)||i);try{this._toggleLoadingIndicator(!0),yield this.paymentIntegrationService.submitPayment(o),yield this._completeCheckoutFlow()}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}finally{this._toggleLoadingIndicator(!1)}})}_confirmStripePaymentOrThrow(e,t){var n,i,r;return Ow(this,void 0,void 0,function*(){const{token:o,redirect_url:a}=e,s=this.stripeIntegrationService.mapStripePaymentData(this._stripeElements,a);let d;try{const e=(yield this.stripeIntegrationService.isPaymentCompleted(t,this._stripeClient))?yield null===(r=this._stripeClient)||void 0===r?void 0:r.retrievePaymentIntent(o||""):yield null===(n=this._stripeClient)||void 0===n?void 0:n.confirmPayment({elements:s.elements,clientSecret:o,redirect:Ta.IF_REQUIRED,confirmParams:{return_url:null===(i=s.confirmParams)||void 0===i?void 0:i.return_url}});if(d=null==e?void 0:e.error,d||!(null==e?void 0:e.paymentIntent))throw new Qr;return e}catch(e){return this.stripeIntegrationService.throwStripeError(d)}})}_completeCheckoutFlow(){return Ow(this,void 0,void 0,function*(){return"function"==typeof this._onComplete?this._onComplete():(window.location.replace("/checkout/order-confirmation"),Promise.resolve())})}_getPaymentPayload(e,t){var n;const i=(null===(n=this.paymentIntegrationService.getState().getCart())||void 0===n?void 0:n.id)||"";return{methodId:e,paymentData:{formattedPayload:Object.assign(Object.assign({cart_id:i},t?{credit_card_token:{token:t}}:{}),{confirm:!1,method:Aa.Link})}}}_shouldRequireShippingAddress(){const{getCart:e}=this.paymentIntegrationService.getState(),{lineItems:t}=e()||{};return!!(null==t?void 0:t.physicalItems.length)}_updateDisplayedPrice(){return Ow(this,void 0,void 0,function*(){this._stripeElements&&this._stripeElements.update({currency:this._getCurrency(),mode:"payment",amount:yield this._getTotalPrice()})})}_getCurrency(){var e;if(!this._currencyCode){const t=null===(e=this.paymentIntegrationService.getState().getCart())||void 0===e?void 0:e.currency;t&&(this._currencyCode=t.code.toLowerCase())}return this._currencyCode}_getTotalPrice(){var e;return Ow(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const{getCheckoutOrThrow:t,getCart:n}=this.paymentIntegrationService.getState(),{decimalPlaces:i}=(null===(e=n())||void 0===e?void 0:e.currency)||{},r=ge(t().outstandingBalance,i).toFixed(i);return this._toCents(+r)})}_getAvailableCountries(){var e;return Ow(this,void 0,void 0,function*(){const t=yield this.paymentIntegrationService.loadShippingCountries();return((null===(e=t.getShippingCountries())||void 0===e?void 0:e.map(e=>e.code))||[]).filter(e=>Sd.includes(e))})}_getAvailableShippingOptions(){var e,t,n;return Ow(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getConsignments();if(!(null==i?void 0:i[0]))return;const r=i[0],o=(r.availableShippingOptions||[]).map(this._getStripeShippingOption.bind(this)),a=null===(e=r.availableShippingOptions)||void 0===e?void 0:e.find(e=>e.isRecommended),s=null===(t=r.selectedShippingOption)||void 0===t?void 0:t.id,d=null==a?void 0:a.id;return s?o.sort(e=>e.id===s?-1:0):d?(o.sort(e=>e.id===d?-1:0),yield this._handleShippingOptionChange(d)):yield this._handleShippingOptionChange(null===(n=o[0])||void 0===n?void 0:n.id),o.slice(0,9)})}_getStripeShippingOption({id:e,cost:t,description:n}){return{id:e,displayName:n,amount:this._toCents(t)}}_handleShippingOptionChange(e){return Ow(this,void 0,void 0,function*(){if(e&&"shipping_option_unselected"!==e)return this.paymentIntegrationService.selectShippingOption(e)})}_getAmountTransformer(){if(this._amountTransformer)return this._amountTransformer;const{getCart:e}=this.paymentIntegrationService.getState(),{currency:t}=e()||{};return t?new fd(t.decimalPlaces):void 0}_toCents(e){const t=Math.round(100*e),n=this._getAmountTransformer();return n?n.toInteger(e):t}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this.loadingIndicator.show(this._loadingIndicatorContainer):this.loadingIndicator.hide()}_getMethodId(e){const{initializationData:{checkoutSessionEnabled:t}={}}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e);return t?Aa.CHECKOUT_SESSION:Aa.OCS}}const Aw=vi(e=>{const t=new Ra(a()),n=new vd({containerStyles:yd});return new Ew(e,t,new pd(e,t),n)},[{id:"stripeocs"}]),Tw=e=>{const t=Ie(e);return document.getElementById(t)?Tw(e):t};function kw(e){return Object.prototype.hasOwnProperty.call(e,"cacheKey")}class Dw{constructor(e){this._lastId=0,this._map={maps:[]},this._usedMaps=[],this._options=Object.assign({maxSize:0,isEqual:Be,onExpire:ce},e)}getKey(...e){const t=this._resolveMap(...e),{index:n,parentMap:i}=t;let{map:r}=t;return r&&r.cacheKey?r.usedCount++:r=this._generateMap(i,e.slice(n)),this._removeLeastUsedMap(r),r.cacheKey}getUsedCount(...e){const{map:t}=this._resolveMap(...e);return t?t.usedCount:0}_resolveMap(...e){let t=0,n=this._map;for(;n.maps.length;){let i=!1;for(let r=0;r{const i=Object.getOwnPropertyDescriptor(e.prototype,n);i&&"constructor"!==n&&Object.defineProperty(t.prototype,n,function(e,t,n){if("function"!=typeof n.value)return n;let i=new Dw,r=n.value,o=Pe(r);return Fn(e,t,{get(){const e=(...e)=>{const t=o.call(this,...e);if(1===i.getUsedCount(...e))return t;const n=r.call(this,...e);return Pv(n,t,{keyFilter:e=>!function(e){return 0===`${e}`.indexOf("$$")||0===`${e}`.indexOf("_")}(e)})?t:(o.cache.set(i.getKey(...e),n),n)};return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e},set(e){i=new Dw,r=e,o=Pe(r)}})}(e.prototype,n,i))}),t}let zw=class{constructor(e){this._checkoutButton=e.checkoutButton}getInitializeButtonError(e){return this._checkoutButton.getInitializeError(e)}getDeinitializeButtonError(e){return this._checkoutButton.getDeinitializeError(e)}};zw=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Mw],zw);const Nw=zw;let xw=class{constructor(e){this._checkoutButton=e.checkoutButton}isInitializingButton(e){return this._checkoutButton.isInitializing(e)}isDeinitializingButton(e){return this._checkoutButton.isDeinitializing(e)}};xw=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Mw],xw);const Rw=xw;function Fw(e){return{errors:new Nw(e),statuses:new Rw(e)}}let Lw=class{constructor(e,t){this._store=e,this._buttonStrategyActionCreator=t,this._state=Fw(this._store.getState()),this._store.subscribe(e=>{this._state=Fw(e)})}getState(){return this._state}subscribe(e,...t){return this._store.subscribe(()=>e(this.getState()),e=>e.checkoutButton.getState(),...t.map(e=>t=>e(Fw(t))))}initializeButton(e){const t=(n=e.containerId,/^\w[\w\-\:\.]*$/.test(n)?[e.containerId]:function(e,t){const n=document.querySelectorAll(e);if(!n.length)throw new qt(`Unable to find any element with the specified selector: ${e}`);return Array.prototype.slice.call(n).map(e=>(e.id||(e.id=Tw(t)),e.id))}(e.containerId,`${e.methodId}-container`));var n;return Promise.all(t.map(t=>{const n=this._buttonStrategyActionCreator.initialize(Object.assign(Object.assign({},e),{containerId:t})),i=`checkoutButtonStrategy:${e.methodId}:${t}`;return this._store.dispatch(n,{queueId:i})})).then(()=>this.getState())}deinitializeButton(e){const t=this._buttonStrategyActionCreator.deinitialize(e),n=`checkoutButtonStrategy:${e.methodId}`;return this._store.dispatch(t,{queueId:n}).then(()=>this.getState())}};Lw=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],Lw);const Bw=Lw;class jw{constructor(e,t,n){this._registry=e,this._registryV2=t,this._paymentMethodActionCreator=n}initialize(e){return t=>{const n={methodId:e.methodId,containerId:e.containerId};if(t.getState().checkoutButton.isInitialized(e.methodId,e.containerId))return f();const i=e.currencyCode?{params:{currencyCode:e.currencyCode}}:{},r=Object.assign(Object.assign({},i),{timeout:e.timeout,useCache:!0});return g(C(l(Hv.InitializeButtonRequested,void 0,n)),this._paymentMethodActionCreator.loadPaymentMethod(e.methodId,r)(t),v(()=>this._getStrategy(e.methodId).initialize(e).then(()=>l(Hv.InitializeButtonSucceeded,void 0,n)))).pipe(P(e=>Je(Hv.InitializeButtonFailed,e,n)))}}deinitialize(e){return t=>{const n={methodId:e.methodId};return t.getState().checkoutButton.isInitialized(e.methodId)?g(C(l(Hv.DeinitializeButtonRequested,void 0,n)),v(()=>this._getStrategy(e.methodId).deinitialize().then(()=>l(Hv.DeinitializeButtonSucceeded,void 0,n)))).pipe(P(e=>Je(Hv.DeinitializeButtonFailed,e,n))):f()}}_getStrategy(e){let t;try{t=this._registryV2.get({id:e})}catch(n){t=this._registry.get(e)}return t}}class Uw extends it{constructor(e){super(e||"Unable to proceed because the client library of a payment method is not loaded or ready to be used."),this.name="PaymentMethodClientUnavailableError",this.type="payment_method_client_unavailable"}}var qw,Vw,Gw,Hw,Ww,$w,Yw,Kw;class Jw{constructor(e){this._scriptLoader=e,this._window=window}loadPaypal(e=""){return t=this,n=void 0,r=function*(){const t="//www.paypalobjects.com/api/checkout.min.js",n={async:!0,attributes:{"data-merchant-id":e}};if(e?yield this._scriptLoader.loadScript(t,n):yield this._scriptLoader.loadScript(t),!this._window.paypal)throw new Uw;return this._window.paypal},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(qw||(qw={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(Vw||(Vw={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black",e.WHITE="white"}(Gw||(Gw={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(Hw||(Hw={})),function(e){e.PILL="pill",e.RECT="rect"}(Ww||(Ww={}));class Zw{constructor(e,t,n,i,r=""){this._store=e,this._checkoutActionCreator=t,this._paypalScriptLoader=n,this._formPoster=i,this._host=r}initialize(e){const t=e.paypal,n=this._store.getState(),i=this._paymentMethod=n.paymentMethods.getPaymentMethod(e.methodId);if(!t)throw new qt;if(!i)throw new rt(et.MissingPaymentMethod);return this._paypalScriptLoader.loadPaypal(i.config.merchantId).then(n=>{var r,o;if(!i||!i.config.merchantId)throw new rt(et.MissingPaymentMethod);const a=i.config.merchantId,s=i.config.testMode?"sandbox":"production",d={[s]:t.clientId},c=n.FUNDING.CREDIT||"credit",l=t.allowCredit?[c]:[],u=t.allowCredit?[]:[c];return n.Button.render({env:s,client:d,commit:t.shouldProcessPayment,funding:{allowed:l,disallowed:u},style:Object.assign(Object.assign({shape:Ww.RECT},pe(t.style,"layout","color","label","shape","tagline","fundingicons")),{size:"paypalexpress"===i.id&&"small"===(null===(r=t.style)||void 0===r?void 0:r.size)?Vw.RESPONSIVE:null===(o=t.style)||void 0===o?void 0:o.size}),payment:(e,n)=>this._setupPayment(a,n,t.onPaymentError),onAuthorize:(e,n)=>this._tokenizePayment(e,n,t.shouldProcessPayment,t.onAuthorizeError)},e.containerId)})}deinitialize(){return this._paymentMethod=void 0,Promise.resolve()}_setupPayment(e,t,n){if(!t)throw new yn(cn.CheckoutButtonNotInitialized);return this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then(n=>{const i=n.cart.getCart(),r=i?i.id:"";return t.request.post(`${this._host}/api/storefront/payment/paypalexpress`,{merchantId:e,cartId:r},{headers:Object.assign({"X-API-INTERNAL":At},Xe)})}).then(e=>e.id).catch(e=>{throw n&&n(e),e})}_tokenizePayment(e,t,n,i){if(!this._paymentMethod)throw new yn(cn.CheckoutButtonNotInitialized);if(!t)throw new yn(cn.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new rt(et.MissingPayment);const r=this._paymentMethod.id;return t.payment.get(e.paymentID).then(t=>{this._formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:r,action:n?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(t.payer.payer_info)})})}}function Qw(e){const{host:t}=null!=e?e:{},i=m_({config:{meta:{host:null==e?void 0:e.host,locale:null==e?void 0:e.locale},errors:{},statuses:{}}}),r=n({host:t}),o=Ee({host:t}),s=function(e,t){const n=new Gt;for(const[,i]of Object.entries(t))if(Ut(i))for(const t of i.resolveIds)n.register(t,()=>i(e));return n}(Hg(i),We);return new Bw(i,new jw(function(e,t,n,i){const r=new Vt,o=a(),s=new en(t),d=new nn(s,new bt(new Tt(t)),new on(new an(t)));return r.register(zy.PAYPALEXPRESS,()=>new Zw(e,d,new Jw(o),n,i)),r}(i,r,o,t),s,new Wm(new $m(r))))}!function(e){e.CheckoutComplete="CHECKOUT_COMPLETE",e.CheckoutError="CHECKOUT_ERROR",e.CheckoutLoaded="CHECKOUT_LOADED",e.FrameError="FRAME_ERROR",e.FrameLoaded="FRAME_LOADED",e.SignedOut="SIGNED_OUT"}($w||($w={}));class Xw extends Ot{constructor(e){super(e,{message:e.body.title}),this.name="InvalidLoginTokenError",this.type="invalid_login_token"}}!function(e){e.MissingContainer="missing_container",e.MissingContent="missing_content",e.UnknownError="unknown_error"}(Yw||(Yw={}));class eI extends it{constructor(e,t=Yw.UnknownError){super(e||"Unable to embed the checkout form."),this.subtype=t,this.name="NotEmbeddableError",this.type="not_embeddable"}}!function(e){e.StyleConfigured="STYLE_CONFIGURED"}(Kw||(Kw={}));const tI="isCookieAllowed",nI="lastAllowCookieAttempt";let iI=class{constructor(e,t,n,i,r,o,a,s){this._iframeCreator=e,this._messageListener=t,this._messagePoster=n,this._loadingIndicator=i,this._requestSender=r,this._storage=o,this._location=a,this._options=s,this._isAttached=!1,this._options.onComplete&&this._messageListener.addListener($w.CheckoutComplete,this._options.onComplete),this._options.onError&&this._messageListener.addListener($w.CheckoutError,this._options.onError),this._options.onLoad&&this._messageListener.addListener($w.CheckoutLoaded,this._options.onLoad),this._options.onFrameLoad&&this._messageListener.addListener($w.FrameLoaded,this._options.onFrameLoad),this._options.onSignOut&&this._messageListener.addListener($w.SignedOut,this._options.onSignOut),this._messageListener.addListener($w.FrameLoaded,()=>this._configureStyles())}attach(){return this._isAttached?Promise.resolve(this):(this._isAttached=!0,this._messageListener.listen(),this._loadingIndicator.show(this._options.containerId),this._allowCookie().then(()=>this._attemptLogin()).then(e=>this._iframeCreator.createFrame(e,this._options.containerId)).then(e=>{this._iframe=e,this._configureStyles(),this._loadingIndicator.hide()}).catch(e=>(this._isAttached=!1,this._retryAllowCookie(e).catch(()=>{throw this._messageListener.trigger({type:$w.FrameError,payload:e}),this._loadingIndicator.hide(),e}))).then(()=>this))}detach(){this._isAttached&&(this._isAttached=!1,this._messageListener.stopListen(),this._iframe&&this._iframe.parentNode&&(this._iframe.parentNode.removeChild(this._iframe),this._iframe.iFrameResizer.close()))}_configureStyles(){this._iframe&&this._iframe.contentWindow&&this._options.styles&&(this._messagePoster.setTarget(this._iframe.contentWindow),this._messagePoster.post({type:Kw.StyleConfigured,payload:this._options.styles}))}_attemptLogin(){return/^\/login\/token/.test(In(this._options.url).pathname)?this._requestSender.post(this._options.url).then(({body:{redirectUrl:e}})=>e).catch(e=>Promise.reject(new Xw(e))):Promise.resolve(this._options.url)}_allowCookie(){if(this._storage.getItem(tI))return Promise.resolve();this._storage.setItem(tI,!0),this._storage.setItem(nI,Date.now());const{origin:e}=In(this._options.url),t=`${e}/embedded-checkout/allow-cookie?returnUrl=${encodeURIComponent(this._location.href)}`;return document.body.style.visibility="hidden",this._location.replace(t),new Promise(()=>{})}_retryAllowCookie(e){const t=Number(this._storage.getItem(nI));return(!t||Date.now()-t>6e5)&&e instanceof eI&&e.subtype===Yw.MissingContent?(this._storage.removeItem(nI),this._storage.removeItem(tI),this._allowCookie()):Promise.reject()}};iI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],iI);const rI=iI;class oI{constructor(e){this._options=e}createFrame(e,t){const n=document.getElementById(t),{timeout:i=6e4}=this._options||{};if(!n)throw new eI("Unable to embed the iframe because the container element could not be found.",Yw.MissingContainer);const r=document.createElement("iframe");return r.src=e,r.style.border="none",r.style.display="none",r.style.width="100%",r.allowPaymentRequest=!0,r.allow="payment",n.appendChild(r),this._toResizableFrame(r,i).catch(e=>{throw n.removeChild(r),e})}_toResizableFrame(e,t){return new Promise((n,i)=>{const r=window.setTimeout(()=>{i(new eI("Unable to embed the iframe because the content could not be loaded."))},t),o=t=>{if((t.origin===In(e.src).origin||t.origin===Wn(In(e.src)).origin)&&(bn(t.data,$w.FrameError)&&(a(),i(new eI(t.data.payload.message,Yw.MissingContent))),bn(t.data,$w.FrameLoaded))){e.style.display="";const i=Dn({scrolling:!1,sizeWidth:!1,heightCalculationMethod:t.data.payload&&t.data.payload.contentId?"taggedElement":"lowestElement"},e);a(),n(i[i.length-1])}},a=()=>{window.removeEventListener("message",o),window.clearTimeout(r)};window.addEventListener("message",o)})}}function aI(e){const t=In(e.url).origin;return new rI(new oI,new Yn(t),new Pn(t),new vd({styles:e.styles&&e.styles.loadingIndicator}),n(),new iy("BigCommerce.EmbeddedCheckout"),window.location,e).attach()}function sI(e){if(!e.payload||!e.payload.contentId)return;const t=document.getElementById(e.payload.contentId);t&&!t.hasAttribute("data-iframe-height")&&t.setAttribute("data-iframe-height","")}function dI(e){return"object"==typeof e&&null!==e&&"message"in e&&"type"in e}let cI=class{constructor(e,t,n,i={}){this._messageListener=e,this._messagePoster=t,this._untargetedMessagePoster=n,this._messageHandlers=i,this._messageListener.listen()}postComplete(){const e={type:$w.CheckoutComplete};this._postMessage(e)}postError(e){const t={type:$w.CheckoutError,payload:this._transformError(e)};this._postMessage(t)}postFrameError(e){const t={type:$w.FrameError,payload:this._transformError(e)};this._postMessage(t,{untargeted:!0})}postFrameLoaded(e){const t={type:$w.FrameLoaded,payload:e};this._postMessage(t)}postLoaded(){const e={type:$w.CheckoutLoaded};this._postMessage(e)}postSignedOut(){const e={type:$w.SignedOut};this._postMessage(e)}receiveStyles(e){this._messageListener.addListener(Kw.StyleConfigured,({payload:t})=>{e(t)})}_postMessage(e,t){if(this._notifyMessageHandlers(e),t&&t.untargeted)return this._untargetedMessagePoster.post(e);this._messagePoster.post(e)}_notifyMessageHandlers(e){Object.keys(this._messageHandlers).forEach(t=>{if(e.type!==t)return;const n=this._messageHandlers[t];n&&n.call(null,e)})}_transformError(e){return{message:e.message,type:dI(e)?e.type:void 0,subtype:dI(e)?e.subtype:void 0}}};cI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],cI);const lI=cI;let uI=class{postComplete(){}postError(){}postFrameError(){}postFrameLoaded(){}postLoaded(){}postSignedOut(){}receiveStyles(){}};uI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],uI);const hI=uI;function pI(e){Ve(939);const t=e.parentWindow||window.parent;return window===t?new hI:new lI(new Yn(e.parentOrigin),new Pn(e.parentOrigin,t),new Pn("*",t),{[$w.FrameLoaded]:sI})}const mI="en",yI="optimized_checkout";let gI=class{constructor(e,t){this._logger=t;const{locale:n,locales:i,translations:r}=this._transformConfig(e);this._locale=n,this._locales=i,this._translations=r,this._formatters={}}mapKeys(e){Object.keys(e).forEach(t=>{const n=`${yI}.${e[t]}`;this._translations[`${yI}.${t}`]=this._translations[n]})}getLocale(){return this._hasTranslations()?this._locale:mI}translate(e,t={}){var n;const i=`${yI}.${e}`;if("string"!=typeof this._translations[i])return this._logger.warn(`Translation key "${i}" is missing`),i;this._formatters[i]||(this._formatters[i]=new je(this._escapeSpecialCharacters(this._translations[i]||""),this._locales[i],void 0,{ignoreTag:!0}));try{return this._formatters[i].format(this._transformData(t))}catch(e){if(this._isFormatError(e))return null!==(n=e.originalMessage)&&void 0!==n?n:"";throw e}}_transformConfig(e={}){const t={defaultLocale:"",defaultTranslations:{},translations:{},locales:{},locale:e.locale||mI},n=e.locales||{},i=this._flattenObject(e.translations||{}),r=this._flattenObject(e.defaultTranslations||{}),o=this._flattenObject(e.fallbackTranslations||{});return _e(Object.keys(o),Object.keys(r),Object.keys(i)).forEach(a=>{var s,d;i&&i[a]?(t.translations[a]=i[a],t.locales[a]=n[a]||t.locale):r[a]?(t.translations[a]=r[a],t.locales[a]=null!==(s=e.defaultLocale)&&void 0!==s?s:mI):(t.translations[a]=o[a],t.locales[a]=null!==(d=e.fallbackLocale)&&void 0!==d?d:mI)}),t}_flattenObject(e,t={},n=""){try{Object.keys(e).forEach(i=>{const r=e[i],o=n?`${n}.${i}`:i;if(Z(r))return this._flattenObject(r,t,o);t[o]=r})}catch(e){this._logger.warn(`Unable to parse object: ${e}`)}return t}_transformData(e){return Object.keys(e).reduce((t,n)=>{const i=e[n];return t[n]=null==i?"":i,t},{})}_hasTranslations(){return Object.keys(this._locales).map(e=>this._locales[e]).filter(e=>e.split("-")[0]===this._locale.split("-")[0]).length>0}_isFormatError(e){return"object"==typeof e&&null!==e&&"originalMessage"in e}_escapeSpecialCharacters(e){return e.replace(/(\w+)='([^']*)'/g,"$1=''$2''")}};gI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],gI);const vI=gI;function fI(e={}){return new vI(e,wt())}let SI=class{constructor(e){this._storeConfig=e,this._customerFormatter=new Fo(this._storeConfig.shopperCurrency),this._storeFormatter=new Fo(this._storeConfig.currency)}toCustomerCurrency(e){const t=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(e*t)}toStoreCurrency(e){return this._storeFormatter.format(e)}};SI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Fn],SI);const _I=SI;function wI(e){return new _I(e)}function II(e){return e&&"ga"in e&&"function"==typeof e.ga}function CI(e,t){II(window)&&window.ga("send",e,Object.assign(Object.assign({},t),{nonInteraction:!1}))}function bI(e){return PI(e).length>=8096}function PI(e){return Object.keys(e).reduce((t,n)=>{const i=typeof e[n];return"string"===i||"number"===i?[...t,`${n}=${e[n]}`]:"object"===i&&null!==e[n]?[...t,PI(e[n])]:t},[]).join("&")}var OI;!function(e){e[e.CUSTOMER=1]="CUSTOMER",e[e.SHIPPING=2]="SHIPPING",e[e.BILLING=3]="BILLING",e[e.PAYMENT=4]="PAYMENT"}(OI||(OI={}));const EI={customer:OI.CUSTOMER,shipping:OI.SHIPPING,billing:OI.BILLING,payment:OI.PAYMENT};class AI{constructor(e,t,n,{checkoutSteps:i}={}){if(this.checkoutService=e,this.analyticsExtraItemsManager=t,this.analytics=n,this._checkoutStarted=!1,this._completedSteps={},this._viewedSteps={},this._analyticStepOrder=["customer","shipping","billing","payment"],void 0!==i){if(i.some(e=>!(e in EI)))throw new qt(`Invalid checkout steps provided. Valid values are: ${ie(EI).join(", ")}.`);this._analyticStepOrder=i}}trackCheckoutStarted(){if(this._checkoutStarted)return;const e=this.getCheckout();if(!e)return;const{coupons:t,grandTotal:n,shippingCostTotal:i,taxTotal:r,cart:{lineItems:o,discountAmount:a,id:s}}=e,d=this.analyticsExtraItemsManager.saveExtraItemsData(s,o);this.analytics.track("Checkout Started",this.getTrackingPayload({revenue:n,shipping:i,tax:r,discount:a,coupons:t,lineItems:o,extraItemsData:d})),this._checkoutStarted=!0}trackOrderComplete(){var e;const t=this.getOrder();if(!t)return;const{isComplete:n,orderId:i,orderAmount:r,shippingCostTotal:o,taxTotal:a,discountAmount:s,coupons:d,lineItems:c,cartId:l}=t;if(!n)return;const u=this.analyticsExtraItemsManager.readExtraItemsData(l);if(null===u)return;const h=null===(e=this.checkoutService.getState().data.getConfig())||void 0===e?void 0:e.checkoutSettings.features["DATA-6891.missing_orders_within_GA"],p=this.getTrackingPayload({orderId:i,revenue:r,shipping:o,tax:a,discount:s,coupons:d,extraItemsData:u,lineItems:c});if(h&&pl(window)&&II(window)&&bI(p))return CI("transaction",{"&ti":p.order_id,"&ta":p.affiliation,"&tr":p.revenue,"&ts":p.shipping,"&tt":p.tax,"&tcc":p.coupon,"&cu":p.currency}),p.products.forEach(e=>{CI("item",{"&ti":p.order_id,"&in":e.name,"&ic":e.sku,"&iv":`${e.category}`,"&ip":e.price,"&iq":e.quantity})}),this.analyticsExtraItemsManager.clearExtraItemData(l);this.analytics.track("Order Completed",p),this.analyticsExtraItemsManager.clearExtraItemData(l)}trackStepViewed(e){const t=this.getIdFromStep(e);t&&!this.hasStepViewed(t)&&(this.trackViewed(t),this.backfill(t))}trackStepCompleted(e){const t=this.getIdFromStep(e);t&&!this.hasStepCompleted(t)&&(this.backfill(t),this.trackCompleted(t))}backfill(e){for(const t of this._analyticStepOrder){const n=this.getIdFromStep(t);if(!n)break;if(this.hasStepViewed(n)||this.trackViewed(n),n===e)break;this.hasStepCompleted(n)||this.trackCompleted(n)}}trackCompleted(e){const t=this.getSelectedShippingOption(),{code:n=""}=this.getShopperCurrency()||{},i=this.getPaymentMethodName(),r={step:e,currency:n};t&&(r.shipping_method=t.description),i&&(r.payment_method=i),r.shipping_method||r.payment_method||(r.shipping_method=" "),this.analytics.track("Checkout Step Completed",r);const o=t?t.id:"",a=e===OI.SHIPPING?`${e}-${o}`:e;this._completedSteps[a]=!0}getTrackingPayload({orderId:e,revenue:t,shipping:n,tax:i,discount:r,coupons:o,extraItemsData:a,lineItems:s}){const{code:d=""}=this.getShopperCurrency()||{},{storeName:c=""}=this.getStoreProfile()||{};return{order_id:String(e),affiliation:c,revenue:this.toShopperCurrency(t),shipping:this.toShopperCurrency(n),tax:this.toShopperCurrency(i),discount:this.toShopperCurrency(r),coupon:(o||[]).map(e=>e.code.toUpperCase()).join(","),currency:d,products:this.getProducts(a,s)}}hasStepCompleted(e){const t=this.getSelectedShippingOption(),n=t?t.id:"";return Object.prototype.hasOwnProperty.call(this._completedSteps,e)||e===OI.SHIPPING&&Object.prototype.hasOwnProperty.call(this._completedSteps,`${e}-${n}`)}hasStepViewed(e){return!!this._viewedSteps[e]}getIdFromStep(e){const t=e.split(".");return EI[t[0]]||null}trackViewed(e){const t=this.getShopperCurrency();this.analytics.track("Checkout Step Viewed",{step:e,currency:t?t.code:""}),this._viewedSteps[e]=!0}getOrder(){const{data:{getOrder:e}}=this.checkoutService.getState();return e()}getCheckout(){const{data:{getCheckout:e}}=this.checkoutService.getState();return e()}getShopperCurrency(){const{data:{getConfig:e}}=this.checkoutService.getState(),t=e();return t&&t.shopperCurrency}getStoreProfile(){const{data:{getConfig:e}}=this.checkoutService.getState(),t=e();return t&&t.storeProfile}toShopperCurrency(e){const{exchangeRate:t=1}=this.getShopperCurrency()||{};return Math.round(e*t*100)/100}getSelectedShippingOption(){const{data:e}=this.checkoutService.getState(),t=e.getSelectedShippingOption();return t&&t.id&&t.description?t:null}getPaymentMethodName(){const{data:e}=this.checkoutService.getState(),t=e.getSelectedPaymentMethod();return t&&t.config&&t.config.displayName||""}getProducts(e,t){const n=(t.customItems||[]).map(e=>({product_id:e.id,sku:e.sku,price:e.listPrice,quantity:e.quantity,name:e.name})),i=t.giftCertificates.map(e=>({product_id:e.id,price:this.toShopperCurrency(e.amount),name:e.name,quantity:1}));return[...n,...[...t.physicalItems,...t.digitalItems].map(t=>{let n;t.options&&t.options.length&&(n=t.options.map(e=>`${e.name}:${e.value}`),n.sort());const i=Array.isArray(n)&&n.length?n.join(", "):"single-product-option",r=e[t.productId]&&e[t.productId].brand;return Object.assign({product_id:String(t.productId),sku:t.sku,price:t.salePrice,image_url:t.imageUrl,name:t.name,quantity:t.quantity,category:e[t.productId]?e[t.productId].category:"",variant:i},r&&{brand:r})}),...i]}}class TI{trackCheckoutStarted(){}trackOrderComplete(){}trackStepViewed(){}trackStepCompleted(){}}function kI(e,t){const{data:n}=e.getState(),i=n.getConfig();if(!i)throw new rt(et.MissingCheckoutConfig);const{isAnalyticsEnabled:r}=i.checkoutSettings;return r&&pl(window)?new AI(e,new hl(Te),window.analytics,t):new TI}function DI(e){return Boolean(e.hasOwnProperty("braintreeFastlane"))}class MI{constructor(e){this.checkoutService=e,this._selectedPaymentMethodId=""}customerPaymentMethodExecuted(){this._shouldTrackFastlaneEvent()&&this._trackEmailSubmitted()}paymentComplete(){this._shouldTrackFastlaneEvent()&&this._trackOrderPlaced(this._selectedPaymentMethodId)}selectedPaymentMethod(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!1))}walletButtonClick(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!0))}_shouldTrackFastlaneEvent(){const e=this.checkoutService.getState(),t=e.data.getPaymentMethod("braintree")||e.data.getPaymentMethod("braintreeacceleratedcheckout"),n=null==t?void 0:t.initializationData.isBraintreeAnalyticsV2Enabled,i=DI(window)&&window.braintreeFastlane.events;return n&&i}_getBraintreeEventsOrThrow(){if(DI(window))return window.braintreeFastlane.events;throw new mi}_trackEmailSubmitted(){const{emailSubmitted:e}=this._getBraintreeEventsOrThrow();e(this._getEmailSubmittedEventOptions())}_trackApmSelected(e,t){const{apmSelected:n}=this._getBraintreeEventsOrThrow();n(this._getApmSelectedEventOptions(e,t))}_trackOrderPlaced(e){const{orderPlaced:t}=this._getBraintreeEventsOrThrow();t(this._getOrderPlacedEventOptions(e))}_getEventCommonOptions(){var e,t;const n=this.checkoutService.getState(),i=n.data.getCart(),r=null===(e=n.data.getConfig())||void 0===e?void 0:e.storeProfile,o=null===(t=n.data.getCustomer())||void 0===t?void 0:t.isGuest,a=n.data.getPaymentMethod("braintreeacceleratedcheckout"),s=[{treatment_group:!n.errors.getLoadPaymentMethodError("braintreeacceleratedcheckout")&&(null==a?void 0:a.initializationData.shouldRunAcceleratedCheckout)?"test":"control"}];return{context_type:"cs_id",context_id:(null==i?void 0:i.id)||"",page_type:"checkout_page",page_name:window.document.title,partner_name:"bigc",user_type:o?"store_guest":"store_member",store_id:(null==r?void 0:r.storeId)||"",merchant_name:(null==r?void 0:r.storeName)||"",experiment:JSON.stringify(s)}}_getEmailSubmittedEventOptions(){const e=(this.checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{user_email_saved:!1,apm_shown:e.length>1?"1":"0",apm_list:e.join(",")})}_getApmSelectedEventOptions(e,t){const n=(this.checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{apm_shown:n.length>1?"1":"0",apm_list:n.join(","),apm_selected:e,apm_location:t?"pre-email section":"payment section"})}_getOrderPlacedEventOptions(e){const t=this.checkoutService.getState().data.getCart();return Object.assign(Object.assign({},this._getEventCommonOptions()),{selected_payment_method:e,currency_code:(null==t?void 0:t.currency.code)||""})}}function zI(e){return new MI(e)}class NI{constructor(e){this._checkoutService=e,this._selectedPaymentMethodId=""}customerPaymentMethodExecuted(){this._shouldTrackFastlaneEvent()&&this._trackEmailSubmitted()}paymentComplete(){this._shouldTrackFastlaneEvent()&&this._trackOrderPlaced(this._selectedPaymentMethodId)}selectedPaymentMethod(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!1))}walletButtonClick(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!0))}_shouldTrackFastlaneEvent(){const e=this._checkoutService.getState().data.getPaymentMethod("paypalcommerce"),t=((null==e?void 0:e.initializationData)||{}).isPayPalCommerceAnalyticsV2Enabled,n=window,i=!!n.paypalFastlane&&!!n.paypalFastlane.events;return t&&i}_getPayPalEventsOrThrow(){const e=window;if(e.paypalFastlane&&e.paypalFastlane.events)return e.paypalFastlane.events;throw new mi}_trackEmailSubmitted(){const{emailSubmitted:e}=this._getPayPalEventsOrThrow();e(this._getEmailSubmittedEventOptions())}_trackApmSelected(e,t){const{apmSelected:n}=this._getPayPalEventsOrThrow();n(this._getApmSelectedEventOptions(e,t))}_trackOrderPlaced(e){const{orderPlaced:t}=this._getPayPalEventsOrThrow();t(this._getOrderPlacedEventOptions(e))}_getEventCommonOptions(){var e,t;const n=this._checkoutService.getState(),i=n.data.getCart(),r=null===(e=n.data.getConfig())||void 0===e?void 0:e.storeProfile,o=null===(t=n.data.getCustomer())||void 0===t?void 0:t.isGuest,a="paypalcommerceacceleratedcheckout",s=n.data.getPaymentMethod(a),d=[{treatment_group:!n.errors.getLoadPaymentMethodError(a)&&(null==s?void 0:s.initializationData.shouldRunAcceleratedCheckout)?"test":"control"}];return{context_type:"cs_id",context_id:(null==i?void 0:i.id.replace(/-/g,""))||"",page_type:"checkout_page",page_name:window.document.title,partner_name:"bigc",user_type:o?"store_guest":"store_member",store_id:(null==r?void 0:r.storeId)||"",merchant_name:(null==r?void 0:r.storeName)||"",experiment:JSON.stringify(d)}}_getEmailSubmittedEventOptions(){const e=(this._checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{user_email_saved:!1,apm_shown:e.length>1?"1":"0",apm_list:e.join(",")})}_getApmSelectedEventOptions(e,t){const n=(this._checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{apm_shown:n.length>1?"1":"0",apm_list:n.join(","),apm_selected:e,apm_location:t?"pre-email section":"payment section"})}_getOrderPlacedEventOptions(e){const t=this._checkoutService.getState().data.getCart();return Object.assign(Object.assign({},this._getEventCommonOptions()),{selected_payment_method:e,currency_code:(null==t?void 0:t.currency.code)||""})}}function xI(e){return new NI(e)}var RI;class FI{constructor(e,t){this._host=e,this._hostedFormFactory=t}submitStoredCard(e,t){return n=this,i=void 0,o=function*(){const n=this._hostedForm;if(!n)throw new yn(cn.PaymentNotInitialized);yield n.validate().then(()=>n.submitStoredCard({fields:e,data:t}))},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}initialize(e){const t=this._hostedFormFactory.create(this._host,e);return t.attach().then(()=>{this._hostedForm=t})}deinitialize(){this._hostedForm&&this._hostedForm.detach()}}function LI(e){const t=m_();return new FI(e,new Iy(t))}!function(e){e.CUSTOMER="customer",e.SHIPPING="shipping",e.BILLING="billing",e.PAYMENT="payment"}(RI||(RI={}));const BI=[RI.CUSTOMER,RI.SHIPPING,RI.BILLING,RI.PAYMENT];class jI{constructor(e,t){this.subscribe=e,this.bodlEvents=t,this._checkoutStarted=!1,this._emailEntryBegan=!1,this._shippingOptionsShown=!1,this._completedSteps={},this.subscribe(e=>{var t;if(this.setState(e.data),!(null===(t=this.state)||void 0===t?void 0:t.getConfig()))throw new rt(et.MissingCheckoutConfig)})}setState(e){this.state=e}checkoutBegin(){const e=this._getCommonCheckoutData();!this._checkoutStarted&&e&&(this.bodlEvents.emitCheckoutBeginEvent(e),this._checkoutStarted=!0)}orderPurchased(){var e;const t=null===(e=this.state)||void 0===e?void 0:e.getOrder();if(!t)return;const{currency:n,isComplete:i,orderId:r,orderAmount:o,shippingCostTotal:a,lineItems:s,cartId:d,coupons:c,channelId:l,taxTotal:u}=t;i&&this.bodlEvents.emitOrderPurchasedEvent({event_id:d,currency:n.code,order_id:r,tax:u,channel_id:l,cart_value:o,coupon_codes:c.map(e=>e.code.toUpperCase()),shipping_cost:a,line_items:this._getProducts(s,n.code)})}stepCompleted(e){e&&BI.some(t=>(this._hasStepCompleted(t)||this._trackCompletedStep(t),t===e))}customerEmailEntry(e){!this._emailEntryBegan&&(null==e?void 0:e.length)&&(this._emailEntryBegan=!0,this.bodlEvents.emit("bodl_checkout_email_entry_began"))}customerSuggestionInit(e){this.bodlEvents.emit("bodl_checkout_customer_suggestion_initialization",e)}customerSuggestionExecute(){this.bodlEvents.emit("bodl_checkout_customer_suggestion_execute")}customerPaymentMethodExecuted(e){this.bodlEvents.emit("bodl_checkout_customer_payment_method_executed",e)}showShippingMethods(){this._shippingOptionsShown||(this._shippingOptionsShown=!0,this.bodlEvents.emit("bodl_checkout_show_shipping_options"))}selectedPaymentMethod(e){const t=this._getCommonCheckoutData();t&&e&&this.bodlEvents.emitPaymentDetailsProvidedEvent(Object.assign(Object.assign({},t),{payment_type:e}))}clickPayButton(e){this.bodlEvents.emit("bodl_checkout_click_pay_button",e)}paymentRejected(){this.bodlEvents.emit("bodl_checkout_payment_rejected")}paymentComplete(){this.bodlEvents.emit("bodl_checkout_payment_complete")}exitCheckout(){this.bodlEvents.emit("bodl_checkout_exit")}_trackCompletedStep(e){this._completedSteps[e]=!0;const t={[RI.SHIPPING]:this._trackShippingStepCompleted.bind(this)}[e];t?t():this.bodlEvents.emit("bodl_checkout_step_completed",{step:e})}_trackShippingStepCompleted(){var e,t;const n=null===(t=null===(e=this.state)||void 0===e?void 0:e.getSelectedShippingOption())||void 0===t?void 0:t.description,i=this._getCommonCheckoutData();i&&n&&this.bodlEvents.emitShippingDetailsProvidedEvent(Object.assign(Object.assign({},i),{shipping_method:n}))}_getCommonCheckoutData(){var e;const t=null===(e=this.state)||void 0===e?void 0:e.getCheckout();if(!t)return null;const{cart:{cartAmount:n,currency:i,lineItems:r,id:o,coupons:a},channelId:s}=t;return{event_id:o,currency:i.code,cart_value:n,coupon_codes:a.map(e=>e.code.toUpperCase()),line_items:this._getProducts(r,i.code),channel_id:s}}_getProducts(e,t){const n=(e.customItems||[]).map(e=>({product_id:e.id,sku:e.sku,base_price:e.listPrice,sale_price:e.listPrice,purchase_price:e.listPrice,quantity:e.quantity,product_name:e.name,currency:t})),i=e.giftCertificates.map(e=>({product_id:e.id,gift_certificate_id:e.id,base_price:e.amount,sale_price:e.amount,purchase_price:e.amount,product_name:e.name,gift_certificate_name:e.name,gift_certificate_theme:e.theme,quantity:1,currency:t}));return[...n,...[...e.physicalItems,...e.digitalItems].map(e=>{let n;return e.options&&e.options.length&&(n=e.options.map(e=>`${e.name}:${e.value}`),n.sort()),{product_id:e.productId,quantity:e.quantity,product_name:e.name,base_price:e.listPrice,sale_price:e.salePrice,purchase_price:e.salePrice>0?e.salePrice:e.listPrice,sku:e.sku,variant_id:e.variantId,discount:e.discountAmount,coupon_amount:e.couponAmount,brand_name:e.brand,currency:t,category_names:(i=e,Array.isArray(i.categoryNames)?i.categoryNames:Array.isArray(i.categories)?q(i.categories).map(({name:e})=>e):[]),retail_price:e.retailPrice};var i}),...i].map(e=>Object.assign(Object.assign({},e),{product_id:String(e.product_id)}))}_hasStepCompleted(e){return this._completedSteps[e]}}class UI{checkoutBegin(){}orderPurchased(){}stepCompleted(){}customerEmailEntry(){}customerSuggestionInit(){}customerSuggestionExecute(){}customerPaymentMethodExecuted(){}showShippingMethods(){}selectedPaymentMethod(){}clickPayButton(){}paymentRejected(){}paymentComplete(){}exitCheckout(){}}function qI(e){return function(e){return"bodlEvents"in e}(window)?new jI(e,window.bodlEvents.checkout):new UI}export{Bn as ExtensionCommandType,jn as ExtensionQueryType,qI as createBodlService,zI as createBraintreeAnalyticTracker,Qw as createCheckoutButtonInitializer,y_ as createCheckoutService,wI as createCurrencyService,pI as createEmbeddedCheckoutMessenger,fI as createLanguageService,xI as createPayPalCommerceAnalyticTracker,kI as createStepTracker,LI as createStoredCardHostedFormService,i as createTimeout,aI as embedCheckout,Ye as isExtraField}; //# sourceMappingURL=checkout-sdk.js.map \ No newline at end of file diff --git a/dist/esm/checkout-sdk.js.map b/dist/esm/checkout-sdk.js.map index 3d376e8bd9..cb7984bfff 100644 --- a/dist/esm/checkout-sdk.js.map +++ b/dist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QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,SC3mBW,SAASC,GACpBxX,GAEA,IAAKA,EACD,OAGJ,IAAID,EAEJ,GAAIC,EAAcj8C,SAAS,KAAM,CAC7B,MAAO0zD,EAAUj7C,GAAUwjC,EAAcngB,MAAM,KAE/CkgB,EAAS,GAAG0X,KAAYj7C,EAAOk7C,qBAE/B3X,EAAS,GAAGC,KAAiBA,EAAc0X,gBAG/C,OAAOH,GAA6BxzD,SAASg8C,GAAUA,OAAS3tD,CACpE,wSCPe,MAAMulE,GAGjB,WAAAxhE,CAAoBsf,GAAApf,KAAAof,aAAAA,EAChBpf,KAAKgc,OAASA,MAClB,CAEM,oBAAA2zB,CACFphB,EACA0E,EACAnE,EACA66B,4CAEA,IAAK3pD,KAAKgc,OAAOk2B,kBAAmB,CAChC,MAAMr0C,EAASmC,KAAK6vC,kCAChBthB,EACA0E,EACAnE,EACA66B,GAKJ,SAFM3pD,KAAK+lC,cAAcloC,IAEpBmC,KAAKgc,OAAOk2B,kBACb,MAAM,IAAIze,GAIlB,OAAOzzB,KAAKgc,OAAOk2B,iBACvB,GAEM,qBAAApC,CACFvhB,EACA0E,EACA02B,EACA1jB,EACAC,4CAEA,IAAKlmC,KAAKgc,OAAOulD,iBAAmBr7B,EAAW,CAC3C,MAAMyE,EAAwB3qC,KAAKgwC,yCAC/BzhB,EACA0E,EACA02B,EACA1jB,SAGEjmC,KAAK+lC,cAAc4E,GAG7B,IAAK3qC,KAAKgc,OAAO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,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,6SC/LW,MAAMC,GAUjB,WAAAjvE,CACYiV,EACAqK,EACA4vD,EACAC,GAHAjvE,KAAA+U,0BAAAA,EACA/U,KAAAof,aAAAA,EACApf,KAAAgvE,yBAAAA,EACAhvE,KAAAivE,iBAAAA,CACT,CAEG,UAAA94D,CACFvY,4CAEA,MAAMsxE,UAAEA,GAActxE,GAAW,GAEjC,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1lI,EA8BWrgC,EA7B7B5V,MAAMC,QAAQg2C,EAASw0C,eAChBx0C,EAASw0C,cACTzqF,MAAMC,QAAQg2C,EAAS0yB,YACvBizG,EAAQ3lI,EAAS0yB,YAAY5hF,IAAI,EAAGhB,UAAWA,GAGnD,IAwBP81L,aAAcjmK,EAAKkmK,aA/BE,IAAC7lI,OAmCyBg/H,GAAsBluL,IACxE6uB,GAAS7wB,OAAA8B,OAAA9B,OAAA8B,OAAA,GACH+uB,GAAI,CACPo/J,WAAYttL,OAAOkuB,EAAKo/J,cAGpC,CAEQ,iBAAAgF,CAAkBn0G,GACtB,OAAOl9E,KAAKuqL,gBAAgBrtG,EAChC,EChSW,MAAMk2G,GACjB,aAAA7C,GAAuB,CAEvB,cAAAG,GAAwB,CAExB,aAAAS,GAAuB,CAEvB,kBAAAI,GAA4B,CAE5B,sBAAAE,GAAgC,CAEhC,yBAAAC,GAAmC,CAEnC,6BAAA3E,GAAuC,CAEvC,mBAAA4E,GAA6B,CAE7B,qBAAAvE,GAA+B,CAE/B,cAAA2E,GAAwB,CAExB,eAAAC,GAAyB,CAEzB,eAAA9E,GAAyB,CAEzB,YAAA+E,GAAsB,ECNX,SAASoB,GACpBjrL,GAEA,OCtBG,SAAuB4T,GAC1B,MAAO,eAAgBA,CAC3B,CDoBQs3K,CAAct3K,QACP,IAAIk0K,GAAmB9nL,EAAW4T,OAAOm0K,WAAWjvL,UAGxD,IAAIkyL,EACf","sources":["webpack://@bigcommerce/checkout-sdk/external module \"iframe-resizer\"","webpack://@bigcommerce/checkout-sdk/external module \"iframe-resizer/js/iframeResizer.contentWindow\"","webpack://@bigcommerce/checkout-sdk/webpack/bootstrap","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/./packages/core/src/form/map-extra-field-to-form-field.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/throw-error-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/b2b-token/b2b-token-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/b2b-token/b2b-token-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/sdk-version-headers.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/b2b-token/b2b-token-request-sender.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/billing/errors/unable-to-continue-as-guest-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/content-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/empty-cart-error.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/http-request/experiment-aware-request-sender.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/./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-actions.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/coupon/gift-certificate-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/cart/cart-source.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-actions.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-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/core/src/spam-protection/is-spam-protection-succeeded-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-hydrate-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/payment-integration/register-integrations.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/form/form-fields-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/spam-protection-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/spam-protection/errors/spam-protection-challenge-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-failed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/not-initialized-error.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/spam-protection/spam-protection-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/mutation-observer.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/spam-protection/spam-protection-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/default/default-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/parse-url.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/extension-not-found-error.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/extension/create-extension-event-poster.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/cancellable-promise/cancellable-promise.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/errors/unexpected-detachment-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-internal-commands.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/detachment-observer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-resizer.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-iframe.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/create-extension-web-worker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/bind-decorator/bind-decorator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-commands.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-queries.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/worker/worker-event-listener.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/worker/worker-event-poster.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/unsupported-extension-command-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/unsupported-extension-query-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/worker-extension-messenger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/append-www.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-listener.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-messenger.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/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/missing-data-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/not-initialized-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/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/invalid-argument-error.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/utility/src/is-experiment-enabled/is-experiment-enabled.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk-verison.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk-version-manager.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.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk-scripts-integrity.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/isManageableBraintreeSDKVersion.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-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-session-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/is-apple-pay-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/is-apple-pay-sdk-window.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/buy-now-cart-creation-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/internal-api-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/content-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/sdk-version-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/create-bigcommerce-payments-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/checkout-buttons/default-checkout-button-height.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/bigcommerce-payments-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/create-bigcommerce-payments-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/bigcommerce-payments-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/paypal-sdk-helper.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/create-bigcommerce-payments-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/storage/src/cookie-storage.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/bigcommerce-payments-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/create-bigcommerce-payments-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/get-fastlane-styles.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-fastlane/bigcommerce-payments-fastlane-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-fastlane/create-bigcommerce-payments-fastlane-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/bigcommerce-payments-paylater-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/create-bigcommerce-payments-paylater-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/bigcommerce-payments-venmo-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/create-bigcommerce-payments-venmo-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/payment-method-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt.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-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/create-bolt-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-argument-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-invalid-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/load-paypal-sdk-once.ts","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/braintree-utils/src/utils/is-credit-card-instrument-like.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/./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/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/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/utility/src/is-web-view/is-web-view.ts","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/is-react-native-window/is-react-native-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/is-opera-window/is-opera-window.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/google-pay-payment-initialize-options.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/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/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/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/stripe-utils/src/stripe.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/stripe-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/stripe-upe/stripe-upe-constants.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/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/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/paypal-utils/src/paypal-commerce-constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/utils/transform-locale-to-paypal-format.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/paypal-commerce-sdk.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-gateway.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/google-pay-integration/src/google-pay-bigcommerce-payments/google-pay-bigcommerce-payments-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-bigcommerce-payments/create-google-pay-bigcommerce-payments-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/paypal-utils/src/paypal-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/paypal-sdk-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/create-paypal-sdk-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/paypal-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/paypal-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/create-paypal-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/paypal-button-creation-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-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-integration-service.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-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-utils/src/paypal-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/create-paypal-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-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-utils/src/is-stripe-payment-method-like.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/stripe-upe-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/create-stripe-upe-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/stripe-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/is-stripe-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/ui/src/loading-indicator/loading-indicator.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/utility/amount-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/stripe-link-v2-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/create-stripe-link-v2-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/order-finalization-not-required-error.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/adyen-utils/src/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-utils/src/adyenv2/adyenv2-script-loader.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/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.ts","webpack://@bigcommerce/checkout-sdk/./packages/affirm-integration/src/affirm-payment-strategy.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/bigcommerce-payments-integration/src/bigcommerce-payments-constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/get-paypal-messages-styles-from-bnpl-config.ts","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/is-base-instrument/is-base-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/bigcommerce-payments-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-bigcommerce-payments-provider-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/create-bigcommerce-payments-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-paypal-fastlane-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-fastlane/bigcommerce-payments-fastlane-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-bigcommerce-fastlane-request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-fastlane/create-bigcommerce-payments-fastlane-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/bigcommerce-payments-paylater-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/create-bigcommerce-payments-paylater-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/timeout-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-ratepay/bigcommerce-payments-ratepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-ratepay/create-bigcommerce-payments-ratepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/hosted-form/hosted-field-type.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/bigcommerce-payments-integration/src/bigcommerce-payments-credit-cards/bigcommerce-payments-credit-cards-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-bigcommerce-payments-fastlane-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-credit-cards/create-bigcommerce-payments-credit-cards-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-alternative-methods/bigcommerce-payments-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-alternative-methods/create-bigcommerce-payments-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-redirect-alternative-methods/bigcomemrce-payments-redirect-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-redirect-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-redirect-alternative-methods/create-bigcommerce-payments-redirect-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/bigcommerce-payments-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/create-bigcommerce-payments-venmo-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/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/types.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/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/braintree-utils/src/braintree-messages.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/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-request-sender.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/braintree-integration/src/braintree-visa-checkout/braintree-visa-checkout-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-visa-checkout/create-braintree-visa-checkout-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-venmo/braintree-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-venmo/create-braintree-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-credit-card/braintree-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-payment-request-3ds-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-form-fields-map.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-hosted-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-hosted-form/braintree-hosted-form.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-supported-card-brand.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-credit-card/create-braintree-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/credit-card-integration/src/credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/cba-mpgs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/is-cba-mpgs-payment-method-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/cba-mpgs.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/cba-mpgs-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/create-cba-mpgs-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/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/google-pay-bigcommerce-payments/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-bigcommerce-payments/google-pay-bigcommerce-payments-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-bigcommerce-payments/create-google-pay-bigcommerce-payments-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/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-utils/src/utils/get-paypal-messages-styles-from-bnpl-config.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/paypal-commerce-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/utils/is-redirect-action-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/utils/is-paypal-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-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-constants.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/paypal-commerce-integration/src/paypal-commerce-credit-card/paypal-commerce-credit-cards-payment-strategy.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/create-paypal-commerce-credit-cards-payment-strategy.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-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-utils/src/utils/is-paypal-fastlane-request-error.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-express-integration/src/paypal-express-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/paypal-express-payment-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-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/external-integration/src/external-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/external-integration/src/is-additional-action.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-utils/src/stripe-supported-locales.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/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-utils/src/is-stripe-payment-event.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/stripe-ocs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/create-stripe-ocs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-cs/stripe-cs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-cs/create-stripe-cs-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/worldpayaccess-integration/src/worldpayaccess-open-banking-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/worldpayaccess-integration/src/create-worldpayaccess-open-banking-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/order/order-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/cart/errors/cart-consistency-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/cart-stock-positions-changed-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/errors/missing-shipping-method-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/errors/invalid-shipping-address-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/create-payment-client.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-request-sender.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-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-widget-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-action-creator.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/storage/browser-storage.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/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/spam-protection/payment-human-verification-handler.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.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-actions.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/payment/payment-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-request-sender.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/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/promotion/map-to-discount-notifications.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/generated/checkout-button-method-type.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/./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/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/payment-status-types.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/converge/converge-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-method-cancelled-error.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/redirect/redirect.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/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-sub-strategy-type.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-provider-customer/payment-provider-customer-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-payment-resumer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-provider-customer/payment-provider-customer-actions-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-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-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/store-credit/store-credit-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/subscription/subscriptions-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/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/instrument/instrument-actions.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/payment/instrument/instrument-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/date-time/add-minutes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/date-time/is-future.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-actions.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-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-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument.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/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/paypal-utils/src/utils/is-paypal-accelerated-checkout-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-actions.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-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/./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/./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/object-set.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/b2b-token/b2b-token-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/b2b-token/b2b-token-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/replace.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/cart/cart-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-actions.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/b2b-token/b2b-token-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-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/coupon/coupon-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-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/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/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/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/store-credit/store-credit-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-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/checkout/create-action-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/create-request-error-factory.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/payment/create-payment-strategy-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/create-customer-strategy-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-selectors.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/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/ppsdk/create-ppsdk-sub-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/create-shipping-strategy-registry.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/bigcommerce-payments-integration/src/bigcommerce-payments/bigcommerce-payments-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/create-bigcommerce-payments-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/bigcommerce-payments-paylater-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/create-bigcommerce-payments-paylater-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/bigcommerce-payments-venmo-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/create-bigcommerce-payments-venmo-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/get-valid-button-style.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/braintree-paypal-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/create-braintree-paypal-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal-credit/braintree-paypal-credit-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal-credit/create-braintree-paypal-credit-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/google-pay-bigcommerce-payments/create-google-pay-bigcommerce-payments-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-express-integration/src/paypal-express-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/create-paypal-express-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/stripe-link-v2-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/create-stripe-link-v2-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/set-unique-element-id.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/checkout-buttons/checkout-button-strategy-action-creator.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/paypal/paypal-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/embedded-checkout-events.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/payment/strategies/paypal/paypal-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/paypal/paypal-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/errors/invalid-login-token-error.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/./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/bodl/analytics-steps.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/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":["var x = (y) => {\n\tvar x = {}; __webpack_require__.d(x, y); return x\n} \nvar y = (x) => (() => (x))\nmodule.exports = x({ [\"iframeResizer\"]: () => (__WEBPACK_EXTERNAL_MODULE_iframe_resizer_1512d797__.iframeResizer) });","module.exports = __WEBPACK_EXTERNAL_MODULE_iframe_resizer_js_iframeResizer_contentWindow_a6cfc03f__;","// 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","// 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};","import { ExtraField, ExtraFieldType } from './extra-field';\nimport FormField, { FormFieldFieldType, FormFieldType } from './form-field';\n\nexport const B2B_EXTRA_FIELD_PREFIX = 'b2bExtraField_';\n\nexport function isExtraField(field: FormField): boolean {\n return field.name.startsWith(B2B_EXTRA_FIELD_PREFIX);\n}\n\nexport default function mapExtraFieldToFormField(extraField: ExtraField): FormField {\n const { fieldType, type } = getFieldTypeInfo(extraField.type);\n\n let options: FormField['options'];\n\n if (extraField.config.numberOfRows) {\n options = { rows: extraField.config.numberOfRows };\n }\n\n if (extraField.config.options?.length) {\n options = {\n ...options,\n items: extraField.config.options.map((val) => ({\n value: val,\n label: val,\n })),\n };\n }\n\n return {\n id: `${B2B_EXTRA_FIELD_PREFIX}${extraField.id}`,\n name: `${B2B_EXTRA_FIELD_PREFIX}${extraField.id}`,\n custom: false,\n label: extraField.name,\n hidden: !extraField.visibleToStorefront,\n required: extraField.isRequired,\n default:\n extraField.config.defaultValue != null\n ? String(extraField.config.defaultValue)\n : undefined,\n fieldType,\n type,\n maxLength: extraField.config.maxLength,\n max: extraField.config.maxValue,\n options,\n };\n}\n\nfunction getFieldTypeInfo(extraFieldType: ExtraFieldType): {\n fieldType: FormFieldFieldType;\n type: FormFieldType;\n} {\n switch (extraFieldType) {\n case 'multiline_text':\n return { fieldType: 'multiline', type: 'string' };\n\n case 'number':\n return { fieldType: 'text', type: 'integer' };\n\n case 'dropdown':\n return { fieldType: 'dropdown', type: 'array' };\n\n case 'text':\n default:\n return { fieldType: 'text', type: 'string' };\n }\n}\n","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 { Action } from '@bigcommerce/data-store';\n\nimport { B2BToken } from './b2b-token-state';\n\nexport enum B2BTokenActionType {\n LoadB2BTokenRequested = 'LOAD_B2B_TOKEN_REQUESTED',\n LoadB2BTokenSucceeded = 'LOAD_B2B_TOKEN_SUCCEEDED',\n LoadB2BTokenFailed = 'LOAD_B2B_TOKEN_FAILED',\n}\n\nexport type LoadB2BTokenAction =\n | LoadB2BTokenRequestedAction\n | LoadB2BTokenSucceededAction\n | LoadB2BTokenFailedAction;\n\nexport interface LoadB2BTokenRequestedAction extends Action {\n type: B2BTokenActionType.LoadB2BTokenRequested;\n}\n\nexport interface LoadB2BTokenSucceededAction extends Action {\n type: B2BTokenActionType.LoadB2BTokenSucceeded;\n}\n\nexport interface LoadB2BTokenFailedAction extends Action {\n type: B2BTokenActionType.LoadB2BTokenFailed;\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 { RequestOptions } from '../common/http-request';\n\nimport { B2BTokenActionType, LoadB2BTokenAction } from './b2b-token-actions';\nimport B2BTokenRequestSender from './b2b-token-request-sender';\n\nexport default class B2BTokenActionCreator {\n constructor(private _requestSender: B2BTokenRequestSender) {}\n\n loadB2BToken(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const storeConfig = state.config.getStoreConfigOrThrow();\n const { storeHash } = storeConfig.storeProfile;\n const { baseUrl: b2bBaseUrl = '', clientId: b2bClientId = '' } =\n storeConfig.b2bApiSettings ?? {};\n const { id: customerId } = state.customer.getCustomerOrThrow();\n const { channelId } = state.checkout.getCheckoutOrThrow();\n\n return concat(\n of(createAction(B2BTokenActionType.LoadB2BTokenRequested)),\n defer(async () => {\n const { body } = await this._requestSender.getB2BToken(\n b2bClientId,\n customerId,\n storeHash,\n channelId,\n b2bBaseUrl,\n options,\n );\n\n return createAction(B2BTokenActionType.LoadB2BTokenSucceeded, {\n token: body.data.token,\n });\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(B2BTokenActionType.LoadB2BTokenFailed, error),\n ),\n );\n };\n }\n}\n","export const SDK_VERSION_HEADERS = { 'X-Checkout-SDK-Version': LIBRARY_VERSION };\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 { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nexport interface B2BTokenResponseBody {\n code: number;\n data: {\n token: string;\n };\n}\n\nexport default class B2BTokenRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n async getB2BToken(\n appClientId: string,\n customerId: number,\n storeHash: string,\n channelId: number,\n b2bBaseUrl: string,\n options?: RequestOptions,\n ): Promise> {\n const { body: jwtBody } = await this._requestSender.get<{ token: string }>(\n '/customer/current.jwt',\n {\n timeout: options?.timeout,\n params: { app_client_id: appClientId },\n headers: SDK_VERSION_HEADERS,\n },\n );\n\n return this._requestSender.post(`${b2bBaseUrl}/api/v2/login`, {\n timeout: options?.timeout,\n credentials: false,\n headers: { 'Content-Type': 'application/json' },\n body: {\n bcToken: jwtBody.token,\n customerId,\n storeHash,\n channelId,\n },\n });\n }\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 '../../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","enum ContentType {\n Json = 'application/json',\n JsonV1 = 'application/vnd.bc.v1+json',\n}\n\nexport default ContentType;\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\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 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\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 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 hasBillingAddress: boolean,\n options?: RequestOptions,\n ): Promise> {\n if (!hasBillingAddress) {\n return this._requestSender.createAddress(checkoutId, address, options);\n }\n\n return this._requestSender.updateAddress(checkoutId, address, options);\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error is thrown when cart is removed or empty.\n */\nexport default class EmptyCartError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Your checkout could not be processed because your cart is empty. Please add items to your cart and try again.',\n );\n\n this.name = 'EmptyCartError';\n this.type = 'empty_cart';\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { AddressRequestBody } from '../address';\nimport { EmptyCartError } from '../cart/errors';\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.physicalItems.stockPosition',\n 'cart.lineItems.digitalItems.options',\n 'cart.lineItems.digitalItems.stockPosition',\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\n .post(url, {\n body: address,\n params: DEFAULT_PARAMS,\n headers,\n timeout,\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .put(url, { params: DEFAULT_PARAMS, body, headers, timeout })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\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","import { RequestOptions, RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { StoreConfig } from '../../config';\n\nexport interface ExperimentConfig {\n getBasePath: () => string | undefined;\n getFeatures: () => StoreConfig['checkoutSettings']['features'];\n}\n\nexport default class ExperimentAwareRequestSender {\n constructor(private _requestSender: RequestSender, private _config: ExperimentConfig) {}\n\n sendRequest(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.sendRequest(url, options);\n }\n\n get(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.get(url, options);\n }\n\n post(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.post(this._prefixed(url), options);\n }\n\n put(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.put(this._prefixed(url), options);\n }\n\n patch(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.patch(this._prefixed(url), options);\n }\n\n delete(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.delete(this._prefixed(url), options);\n }\n\n private _prefixed(url: string): string {\n const basePath = this._config.getBasePath();\n\n const isExperimentEnabled =\n this._config.getFeatures()['CHECKOUT-9950.update_sf_checkout_url_for_subfolder'];\n\n if (\n !isExperimentEnabled ||\n !basePath ||\n basePath.endsWith('/checkout') ||\n /^https?:\\/\\//.test(url)\n ) {\n return url;\n }\n\n return `${basePath}${url}`;\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","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 { 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 { 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 | object;\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.physicalItems.stockPosition',\n 'cart.lineItems.digitalItems.options',\n 'cart.lineItems.digitalItems.stockPosition',\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 { 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","export enum CartSource {\n BuyNow = 'BUY_NOW',\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 { 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 { EmptyCartError } from '../cart/errors';\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\n .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 .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes([\n ...CHECKOUT_DEFAULT_INCLUDES,\n CheckoutIncludes.AvailableShippingOptions,\n ]),\n },\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\n }\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 { EmptyCartError } from '../cart/errors';\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\n .post(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n body: { giftCertificateCode },\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\n }\n}\n","import ResolvableModule from './resolvable-module';\n\nexport default function isResolvableModule(\n module: TModule,\n): module is ResolvableModule {\n return module && '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: (\n token: string,\n registeredTokens: string[],\n exactMatch?: boolean,\n ) => 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 getFactory(token: string, exactMatch?: boolean): Factory | undefined {\n const resolvedToken = this._tokenResolver(token, Object.keys(this._factories), exactMatch);\n const factory = resolvedToken ? this._factories[resolvedToken] : undefined;\n\n return factory;\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 factory = this.getFactory(token);\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 defaultToken: this._encodeToken({ default: true } as unknown as TToken),\n useFallback: this._useFallback,\n });\n }\n\n get(resolveId: TToken): TType {\n return this._registry.get(this._encodeToken(resolveId));\n }\n\n getFactory(resolveId: TToken, exactMatch?: boolean): Factory | undefined {\n try {\n return this._registry.getFactory(this._encodeToken(resolveId), exactMatch);\n } catch (error) {\n return undefined;\n }\n }\n\n getUseFallback(): boolean {\n return this._useFallback;\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(\n token: string,\n registeredTokens: string[],\n exactMatch?: boolean,\n ): string | undefined {\n const query = this._decodeToken(token);\n\n const results: Array<{\n token: string;\n matches: number;\n default: boolean;\n totalKeys: number;\n }> = [];\n\n registeredTokens.forEach((registeredToken) => {\n const resolverId = this._decodeToken(registeredToken);\n\n const result = {\n token: registeredToken,\n matches: 0,\n default: false,\n totalKeys: Object.keys(resolverId).length,\n };\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 queryKeyCount = Object.keys(query).length;\n\n if (exactMatch) {\n const exactResult = matchedResults.find(\n (result) => result.matches === queryKeyCount && result.matches === result.totalKeys,\n );\n\n if (!exactResult) {\n throw new Error(\n `Unable to resolve to a registered token with the provided token for ${JSON.stringify(\n query,\n )} with exact match.`,\n );\n }\n\n return exactResult.token;\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(\n `Unable to resolve to a registered token with the provided token for ${JSON.stringify(\n query,\n )}.`,\n );\n }\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\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 { 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 { Action } from '@bigcommerce/data-store';\n\nimport CheckoutInitialState from './checkout-initial-state';\n\nexport enum CheckoutHydrateActionType {\n HydrateInitialState = 'HYDRATE_INITIAL_STATE',\n}\n\nexport interface CheckoutHydrateAction extends Action {\n type: CheckoutHydrateActionType.HydrateInitialState;\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 { CartSource } from '@bigcommerce/checkout-sdk/payment-integration-api';\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 const checkout = store.getState().checkout.getCheckoutOrThrow();\n const cartId = checkout.cart.source === CartSource.BuyNow ? checkout.id : undefined;\n\n return concat(\n of(createAction(CustomerActionType.SignInCustomerRequested)),\n from(\n this._customerRequestSender.signInCustomer({ ...credentials, cartId }, options),\n ).pipe(\n switchMap(({ body }) => {\n if (body.data.persistentCartRetrievalInformation) {\n return concat(\n this._checkoutActionCreator.loadCheckout(\n body.data.persistentCartRetrievalInformation.id,\n options,\n )(store),\n of(\n createAction(\n CustomerActionType.SignInCustomerSucceeded,\n body.data,\n ),\n ),\n );\n }\n\n return 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\n signOutCustomer(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const checkout = store.getState().checkout.getCheckoutOrThrow();\n const cartId = checkout.cart.source === CartSource.BuyNow ? checkout.id : undefined;\n\n return concat(\n of(createAction(CustomerActionType.SignOutCustomerRequested)),\n from(this._customerRequestSender.signOutCustomer(options, cartId)).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}\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(\n { timeout }: RequestOptions = {},\n cartId?: string,\n ): Promise> {\n const url = '/internalapi/v1/checkout/customer';\n\n return this._requestSender.delete(url, {\n timeout,\n headers: SDK_VERSION_HEADERS,\n ...(cartId && { body: { cartId } }),\n });\n }\n}\n","import {\n isResolvableModule,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\n\nexport type StrategyFactory = (\n paymentIntegrationService: PaymentIntegrationService,\n) => TStrategy;\n\nexport function registerIntegrations(\n registry: ResolveIdRegistry,\n integrations: Array>,\n paymentIntegrationService: PaymentIntegrationService,\n): void {\n integrations.forEach((factory) => {\n if (!isResolvableModule, TResolveId>(factory)) {\n return;\n }\n\n factory.resolveIds.forEach((resolveId) => {\n if (registry.getFactory(resolveId, true)) {\n return;\n }\n\n registry.register(resolveId, () => factory(paymentIntegrationService));\n });\n });\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport {\n CustomerStrategy as CustomerStrategyV2,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { registerIntegrations } from '../payment-integration';\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 private _paymentIntegrationService: PaymentIntegrationService,\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 registerIntegrations(\n this._strategyRegistryV2,\n options?.integrations ?? [],\n this._paymentIntegrationService,\n );\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 { EmptyCartError } from '../cart/errors';\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\n .put(url, {\n params: {\n include: joinOrMergeIncludes(CHECKOUT_DEFAULT_INCLUDES, include),\n },\n body,\n headers,\n timeout,\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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 { Action, 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 } from '../config';\nimport { FormFieldsActionCreator } from '../form';\n\nimport Checkout, { CheckoutRequestBody } from './checkout';\nimport { CheckoutActionType, LoadCheckoutAction, UpdateCheckoutAction } from './checkout-actions';\nimport { CheckoutHydrateActionType } from './checkout-hydrate-actions';\nimport CheckoutInitialState from './checkout-initial-state';\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 () => {\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._transformCustomerAddresses(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._transformCustomerAddresses(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 hydrateInitialState(state: CheckoutInitialState): Action {\n return {\n type: CheckoutHydrateActionType.HydrateInitialState,\n payload: state,\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 { 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 } 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 { 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 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 './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 { 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 { 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 return concat(\n of(createAction(SpamProtectionActionType.InitializeRequested, undefined)),\n defer(async () => {\n const spamProtectionElementId = options\n ? options.containerId\n : 'spamProtectionContainer';\n\n const element = document.getElementById(spamProtectionElementId);\n\n if (element) {\n this._googleRecaptcha.reset(spamProtectionElementId);\n }\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\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","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 { 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\n .load()\n .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 .catch((err) => {\n throw err;\n });\n }\n\n reset(containerId: string): void {\n const element = document.getElementById(containerId);\n\n element?.remove();\n this._recaptcha?.reset(this._widgetId);\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 { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { EmptyCartError } from '../cart/errors';\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\n .post(url, { body: { token }, headers, timeout })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\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","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 { 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 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 { 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","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 { 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 { 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 { 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","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 { 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","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 { createExtensionWebWorker } from './create-extension-web-worker';\nimport { ExtensionNotFoundError } from './errors';\nimport { ExtensionRegion, ExtensionType } from './extension';\nimport { ExtensionAction, ExtensionActionType } from './extension-actions';\nimport { ExtensionIframe } from './extension-iframe';\nimport { ExtensionRequestSender } from './extension-request-sender';\nimport { WorkerExtensionMessenger } from './worker-extension-messenger';\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 workerExtensionMessenger: WorkerExtensionMessenger,\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 } = state.config.getStoreConfigOrThrow();\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 if (extension.type === ExtensionType.Worker) {\n const worker = createExtensionWebWorker(extension.url);\n\n workerExtensionMessenger.add(extension.id, worker);\n } else {\n const iframe = new ExtensionIframe(container, extension, {\n cartId,\n parentOrigin: parseUrl(checkoutLink).origin,\n });\n\n await iframe.attach();\n }\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","export function createExtensionWebWorker(url: string): Worker {\n if (!window.Worker) {\n throw new Error(\n `Unable to load the extension's web worker: your browser does not support Web Workers.`,\n );\n }\n\n try {\n const blob = URL.createObjectURL(\n new Blob(\n [\n `importScripts=((i)=>(...a)=>i(...a.map((u)=>''+new URL(u,\"${url}\"))))(importScripts);importScripts(\"${url}\")`,\n ],\n { type: 'text/javascript' },\n ),\n );\n\n return new Worker(blob);\n } catch (error) {\n throw new Error(`Unable to load the extension's web worker`);\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","/**\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","export type ExtensionCommand =\n | ReloadCheckoutCommand\n | ShowLoadingIndicatorCommand\n | SetIframeStyleCommand\n | ReRenderShippingForm\n | ReRenderShippingStep;\n\nexport enum ExtensionCommandType {\n ReloadCheckout = 'EXTENSION:RELOAD_CHECKOUT',\n ShowLoadingIndicator = 'EXTENSION:SHOW_LOADING_INDICATOR',\n SetIframeStyle = 'EXTENSION:SET_IFRAME_STYLE',\n ReRenderShippingForm = 'EXTENSION:RE_RENDER_SHIPPING_FORM',\n ReRenderShippingStep = 'EXTENSION:RE_RENDER_SHIPPING_STEP',\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 ReRenderShippingForm {\n type: ExtensionCommandType.ReRenderShippingForm;\n}\n\nexport interface ReRenderShippingStep {\n type: ExtensionCommandType.ReRenderShippingStep;\n}\nexport interface ExtensionCommandMap {\n [ExtensionCommandType.ReloadCheckout]: ReloadCheckoutCommand;\n [ExtensionCommandType.ShowLoadingIndicator]: ShowLoadingIndicatorCommand;\n [ExtensionCommandType.SetIframeStyle]: SetIframeStyleCommand;\n [ExtensionCommandType.ReRenderShippingForm]: ReRenderShippingForm;\n [ExtensionCommandType.ReRenderShippingStep]: ReRenderShippingStep;\n}\n","export type ExtensionQuery = GetConsignmentsQuery;\n\nexport enum ExtensionQueryType {\n GetConsignments = 'EXTENSION:GET_CONSIGNMENTS',\n}\n\nexport interface GetConsignmentsQuery {\n type: ExtensionQueryType.GetConsignments;\n payload?: {\n useCache?: boolean;\n };\n}\n\nexport interface ExtensionQueryMap {\n [ExtensionQueryType.GetConsignments]: GetConsignmentsQuery;\n}\n","import { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { WorkerEventListeners, WorkerEventMap } from './WorkerEvent';\n\nexport class WorkerEventListener<\n TEventMap extends WorkerEventMap,\n TContext = undefined,\n> {\n private _isListening: boolean;\n private _listeners: WorkerEventListeners;\n\n constructor(private _worker: Worker) {\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 this._worker.addEventListener('message', this._handleMessage);\n }\n\n stopListen(): void {\n if (!this._isListening) {\n return;\n }\n\n this._isListening = false;\n this._worker.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 const { context, ...event } = messageEvent.data;\n\n this.trigger(event, context);\n }\n}\n","export class WorkerEventPoster {\n constructor(private _worker: Worker, private _context: TContext) {}\n\n post(event: TEvent): void {\n if (!this._worker) {\n throw new Error(\n 'WorkerPoster: Worker is not initialized or creation failed. Cannot post message.',\n );\n }\n\n this._worker.postMessage({ ...event, context: this._context });\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 { StandardError } from '../../common/error/errors';\n\nexport class UnsupportedExtensionQueryError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unable to proceed due to unsupported extension query.');\n\n this.name = 'UnsupportedExtensionQueryError';\n this.type = 'unsupported_extension_query_error';\n }\n}\n","import { WorkerEventListener, WorkerEventPoster } from '../common/worker';\n\nimport {\n ExtensionNotFoundError,\n UnsupportedExtensionCommandError,\n UnsupportedExtensionQueryError,\n} from './errors';\nimport { ExtensionCommandMap, ExtensionCommandType } from './extension-commands';\nimport { ExtensionCommandOrQueryContext, ExtensionMessage } from './extension-message';\nimport { ExtensionQueryMap, ExtensionQueryType } from './extension-queries';\n\nexport class WorkerExtensionMessenger {\n constructor(\n private _workers: { [extensionId: string]: Worker } = {},\n private _commandListeners: {\n [extensionId: string]: WorkerEventListener;\n } = {},\n private _queryListeners: {\n [extensionId: string]: WorkerEventListener;\n } = {},\n ) {}\n\n add(extensionId: string, worker: Worker): void {\n this._workers[extensionId] = worker;\n }\n\n listenForCommand(\n extensionId: string,\n command: T,\n commandHandler: (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => Promise | void,\n ): () => void {\n const worker = this._getWorkerById(extensionId);\n\n if (!this._commandListeners[extensionId]) {\n this._commandListeners[extensionId] = new WorkerEventListener(worker);\n }\n\n const listener = this._commandListeners[extensionId];\n\n listener.listen();\n\n const validCommandType = this._validateCommand(command);\n\n const commandHandlerProxy = (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandOrQueryContext,\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 listenForQuery(\n extensionId: string,\n query: T,\n queryHandler: (\n query: ExtensionQueryMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => Promise | void,\n ): () => void {\n const worker = this._getWorkerById(extensionId);\n\n if (!this._queryListeners[extensionId]) {\n this._queryListeners[extensionId] = new WorkerEventListener(worker);\n }\n\n const listener = this._queryListeners[extensionId];\n\n listener.listen();\n\n const validQueryType = this._validateQuery(query);\n\n const queryHandlerProxy = (\n query: ExtensionQueryMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => {\n if (context?.extensionId === extensionId) {\n queryHandler(query, context);\n }\n };\n\n listener.addListener(validQueryType, queryHandlerProxy);\n\n return () => {\n listener.removeListener(validQueryType, queryHandlerProxy);\n };\n }\n\n stopListen(extensionId: string): void {\n if (this._commandListeners[extensionId]) {\n this._commandListeners[extensionId].stopListen();\n }\n\n if (this._queryListeners[extensionId]) {\n this._queryListeners[extensionId].stopListen();\n }\n }\n\n post(extensionId: string, message: ExtensionMessage): void {\n if (!this._workers[extensionId]) {\n throw new Error(`Worker with extensionId ${extensionId} not found`);\n }\n\n const workerPoster = new WorkerEventPoster(this._workers[extensionId], extensionId);\n\n workerPoster.post(message);\n }\n\n clearCacheById(extensionId: string): void {\n delete this._workers[extensionId];\n }\n\n private _getWorkerById(extensionId: string): Worker {\n const worker = this._workers[extensionId];\n\n if (!worker) {\n throw new ExtensionNotFoundError(`Worker with extensionId ${extensionId} not found`);\n }\n\n return worker;\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 private _validateQuery(query: T): T {\n if (Object.values(ExtensionQueryType).includes(query)) {\n return query;\n }\n\n throw new UnsupportedExtensionQueryError();\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 { 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 { 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\nexport type EventListeners = {\n [key in keyof TEventMap]?: Array<(event: TEventMap[key], context?: TContext) => void>;\n};\n","import { ReadableCheckoutStore } from '../checkout';\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\n\nimport { createExtensionEventPoster } from './create-extension-event-poster';\nimport {\n ExtensionNotFoundError,\n UnsupportedExtensionCommandError,\n UnsupportedExtensionQueryError,\n} from './errors';\nimport { Extension, ExtensionType } from './extension';\nimport { ExtensionCommandMap, ExtensionCommandType } from './extension-commands';\nimport { ExtensionCommandOrQueryContext, ExtensionMessage } from './extension-message';\nimport { ExtensionQueryMap, ExtensionQueryType } from './extension-queries';\nimport { WorkerExtensionMessenger } from './worker-extension-messenger';\n\nexport class ExtensionMessenger {\n private _extensions: Extension[] | undefined;\n\n constructor(\n private _store: ReadableCheckoutStore,\n private _workerExtensionMessenger: WorkerExtensionMessenger,\n private _commandListeners: {\n [extensionId: string]: IframeEventListener;\n } = {},\n private _queryListeners: {\n [extensionId: string]: IframeEventListener;\n } = {},\n private _posters: { [extensionId: string]: IframeEventPoster } = {},\n ) {}\n\n clearCacheByRegion(region: string): void {\n const extension = this._getExtensionByRegion(region);\n\n if (extension.type === ExtensionType.Worker) {\n this._workerExtensionMessenger.clearCacheById(extension.id);\n\n return;\n }\n\n this.clearCacheById(extension.id);\n }\n\n clearCacheById(extensionId: string): void {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n this._workerExtensionMessenger.clearCacheById(extension.id);\n\n return;\n }\n\n if (this._commandListeners[extensionId]) {\n delete this._commandListeners[extensionId];\n }\n\n if (this._queryListeners[extensionId]) {\n delete this._queryListeners[extensionId];\n }\n\n if (this._posters[extensionId]) {\n delete this._posters[extensionId];\n }\n }\n\n listenForCommand(\n extensionId: string,\n command: T,\n commandHandler: (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => Promise | void,\n ): () => void {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n return this._workerExtensionMessenger.listenForCommand(\n extensionId,\n command,\n commandHandler,\n );\n }\n\n if (!this._commandListeners[extensionId]) {\n this._commandListeners[extensionId] = new IframeEventListener(extension.url);\n }\n\n const listener = this._commandListeners[extensionId];\n\n listener.listen();\n\n const validCommandType = this._validateCommand(command);\n\n const commandHandlerProxy = (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandOrQueryContext,\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 listenForQuery(\n extensionId: string,\n query: T,\n queryHandler: (\n query: ExtensionQueryMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => Promise | void,\n ): () => void {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n return this._workerExtensionMessenger.listenForQuery(extensionId, query, queryHandler);\n }\n\n if (!this._queryListeners[extensionId]) {\n this._queryListeners[extensionId] = new IframeEventListener(extension.url);\n }\n\n const listener = this._queryListeners[extensionId];\n\n listener.listen();\n\n const validQueryType = this._validateQuery(query);\n\n const queryHandlerProxy = (\n query: ExtensionQueryMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => {\n if (context?.extensionId === extensionId) {\n queryHandler(query, context);\n }\n };\n\n listener.addListener(validQueryType, queryHandlerProxy);\n\n return () => {\n listener.removeListener(validQueryType, queryHandlerProxy);\n };\n }\n\n stopListen(extensionId: string): void {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n this._workerExtensionMessenger.stopListen(extensionId);\n\n return;\n }\n\n if (this._commandListeners[extensionId]) {\n this._commandListeners[extensionId].stopListen();\n }\n\n if (this._queryListeners[extensionId]) {\n this._queryListeners[extensionId].stopListen();\n }\n }\n\n post(extensionId: string, message: ExtensionMessage): void {\n try {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n this._workerExtensionMessenger.post(extensionId, message);\n\n return;\n }\n\n if (!this._posters[extensionId]) {\n this._posters[extensionId] =\n createExtensionEventPoster(extension);\n }\n\n this._posters[extensionId].post(message);\n } catch (error) {\n this.clearCacheById(extensionId);\n // eslint-disable-next-line no-console\n console.log(\n `Unable to post event to extension(${extensionId}) because extension iframe is not mounted.\\nThe event that could not be delivered:`,\n message,\n );\n }\n }\n\n private _getExtensionById(extensionId: string): Extension {\n this._getExtensions();\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 _getExtensionByRegion(region: string): Extension {\n this._getExtensions();\n\n const extension = this._extensions?.find((e) => e.region === region);\n\n if (!extension) {\n throw new ExtensionNotFoundError(\n `Unable to proceed due to no extension found for region: ${region}.`,\n );\n }\n\n return extension;\n }\n\n private _getExtensions(): void {\n if (this._extensions) {\n return;\n }\n\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\n private _validateCommand(command: T): T {\n if (Object.values(ExtensionCommandType).includes(command)) {\n return command;\n }\n\n throw new UnsupportedExtensionCommandError();\n }\n private _validateQuery(query: T): T {\n if (Object.values(ExtensionQueryType).includes(query)) {\n return query;\n }\n\n throw new UnsupportedExtensionQueryError();\n }\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 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\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 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 { 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: number, 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 {\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 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 | undefined {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n return;\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) {\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 if (!createCheckoutSessionConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\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: `${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 * 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\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 let paymentMethod: PaymentMethod;\n\n try {\n paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n } catch (_e) {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n paymentMethod = this.paymentIntegrationService\n .getState()\n .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","export interface Features {\n [featureName: string]: boolean | undefined;\n}\n\nexport default function isExperimentEnabled(\n features: Features,\n experimentName: string,\n fallbackValue = true,\n): boolean {\n return features[experimentName] ?? fallbackValue;\n}\n","export const BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION = '3.128.0';\nexport const BRAINTREE_SDK_DEFAULT_VERSION = '3.123.2';\nexport const BRAINTREE_SDK_STABLE_VERSION = '3.106.0';\n","import { find } from 'lodash';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport { BraintreeHostWindow } from './braintree';\nimport {\n BRAINTREE_SDK_DEFAULT_VERSION,\n BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION,\n BRAINTREE_SDK_STABLE_VERSION,\n} from './braintree-sdk-verison';\n\nexport default class BraintreeSDKVersionManager {\n private braintreeWindow: BraintreeHostWindow = window;\n\n constructor(private paymentIntegrationService: PaymentIntegrationService) {}\n\n getSDKVersion() {\n const state = this.paymentIntegrationService.getState();\n const storeConfig = state.getStoreConfig();\n const features = storeConfig?.checkoutSettings.features || {};\n\n const preloadedVersion = this.getPreloadedSDKVersion();\n\n if (preloadedVersion) {\n return preloadedVersion;\n }\n\n if (isExperimentEnabled(features, 'PAYPAL-5809.braintree_hosted_fields_fix_version')) {\n return BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION;\n }\n\n if (isExperimentEnabled(features, 'PAYPAL-5636.update_braintree_sdk_version')) {\n return BRAINTREE_SDK_DEFAULT_VERSION;\n }\n\n return BRAINTREE_SDK_STABLE_VERSION;\n }\n\n private getPreloadedSDKVersion(): void | string {\n const braintree = this.braintreeWindow.braintree;\n\n if (braintree) {\n const preloadedVersion = find<{ VERSION?: string }>(\n Object.values(braintree),\n (module) => !!module.VERSION,\n );\n\n return preloadedVersion?.VERSION;\n }\n }\n}\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","import { Address } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport * 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(\n options: BraintreeThreeDSecureOptions,\n callback?: Braintree3DSVerifyCardCallback,\n ): Promise;\n cancelVerifyCard(): Promise;\n on(\n event: K,\n handler: BraintreeThreeDSecureEventMap[K],\n ): void;\n}\n\nexport type Braintree3DSVerifyCardCallback = (\n verifyError: Braintree3DSVerifyCardError,\n payload: Braintree3DSVerifyCardPayload,\n) => void;\n\nexport interface BraintreeThreeDSecureEventMap {\n 'customer-canceled': () => void;\n}\n\nexport interface Braintree3DSVerifyCardError {\n code: string;\n}\n\nexport interface Braintree3DSVerifyCardPayload {\n nonce: string;\n}\n\nexport interface BraintreeThreeDSecureCreatorConfig extends BraintreeModuleCreatorConfig {\n version?: number;\n}\n\nexport interface BraintreeThreeDSecureOptions {\n nonce: string;\n amount: number | string;\n challengeRequested?: boolean;\n showLoader?: boolean;\n bin?: string;\n additionalInformation?: {\n acsWindowSize?: '01' | '02' | '03' | '04' | '05';\n };\n collectDeviceData?: boolean;\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\nexport enum BraintreeOrderStatus {\n Completed = 'COMPLETED',\n Pending = 'PENDING',\n Failed = 'FAILED',\n}\n\nexport interface BraintreeOrderStatusData {\n status: BraintreeOrderStatus;\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 non-instant payment methods\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 BraintreeOrderSavedResponse {\n body: {\n additional_action_required: {\n data: {\n order_id_saved_successfully: string;\n };\n };\n };\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 binDetails?: {\n bin: string;\n };\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\nexport interface BraintreeRedirectError {\n body: {\n additional_action_required: {\n data: {\n redirect_url: string;\n };\n };\n };\n}\n\nexport default interface BillingAddress extends Address {\n id: string;\n email?: string;\n}\n\nexport enum BraintreeSupportedCardBrands {\n Visa = 'visa',\n Mastercard = 'mastercard',\n AmericanExpress = 'american-express',\n DinersClub = 'diners-club',\n Discover = 'discover',\n Jcb = 'jcb',\n UnionPay = 'union-pay',\n Maestro = 'maestro',\n Elo = 'elo',\n Mir = 'mir',\n Hiper = 'hiper',\n Hipercard = 'hipercard',\n}\n\nexport 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 interface BraintreeRequestData {\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","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 { 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 enableCheckoutPaywallBanner?: boolean;\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 paypalBNPLConfiguration?: PayPalBNPLConfigurationItem[] | null;\n nonce?: string;\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 preventCursorJumps?: boolean;\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: (err: null | undefined | BraintreeError) => 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 BNPL Configurator related types\n *\n */\nexport interface PayPalBNPLConfigurationItem {\n id: string;\n name: string;\n status: boolean;\n styles: Record;\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 {\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 { BraintreeModuleName } from './braintree';\nimport {\n BRAINTREE_SDK_DEFAULT_VERSION,\n BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION,\n BRAINTREE_SDK_STABLE_VERSION,\n} from './braintree-sdk-verison';\n\nexport const BRAINTREE_SDK_SCRIPTS_INTEGRITY = {\n [BRAINTREE_SDK_STABLE_VERSION]: {\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 [BRAINTREE_SDK_DEFAULT_VERSION]: {\n [BraintreeModuleName.Client]:\n 'sha384-o+nbQGcwNNxIBeXeu3+XmbSq+Cg8R3EN3N0l5hXCgMMU2RGY0t1z0LroSEIAbfAO',\n [BraintreeModuleName.PaypalCheckout]:\n 'sha384-WrfbWPBS4mH86GAoycPSgiH8hQ8KH7A67C93Hjhunv/xhNk2YpBn3wbFA4Fhg9U/',\n [BraintreeModuleName.Paypal]:\n 'sha384-VF389nvvrRUgDsTXMxTYORDtVegB9IQa3Cxr//DyJnLYnz8/X8VCzEvck2c+Megt',\n [BraintreeModuleName.LocalPayment]:\n 'sha384-tZKx2rEQbfmZpoPSY5VPmJEhaq4X75dLvwHMs3VE9U+C8lPyw+hWTIL1+GPvWCIH',\n [BraintreeModuleName.DataCollector]:\n 'sha384-E6k3wOpP7syCDDwaRDLF06942Y00NkbwJvWi2OQXwwKzGwG5fd3E7RFUvCCecfvO',\n [BraintreeModuleName.UsBankAccount]:\n 'sha384-258FON8LZGG0W9Qaz4Jij83pZHu30YnKjJA7gNulLBh6CclkucgF+tHDQuYFRYfW',\n [BraintreeModuleName.GooglePayment]:\n 'sha384-taJ2p/0+n0VH328POAoBiuEbL3tnHUTE9S42hK1V+Txs3X+QYjZOyKW35JgHRFfO',\n [BraintreeModuleName.ThreeDSecure]:\n 'sha384-+NSZH4Zj3sO5bdWvPKhU5N16QDxeueTVTnUVeleeESkhLSaz4Ob1hh/5myecc9Ym',\n [BraintreeModuleName.VisaCheckout]:\n 'sha384-66DiBjghxk1OmBj8aksN8gbQ+CwoQcx1vPfiXUN08g1iQVM+BwewF0p7toM3i7SS',\n [BraintreeModuleName.Venmo]:\n 'sha384-B5UwY42kE4RoLoWbQ7YpqosUlUad2/DlGWiw0HhoZbSPk30CQAaSA10ohyLDTkDU',\n [BraintreeModuleName.HostedFields]:\n 'sha384-Aw9EesSaUeWxe36PqEHiOyOyOq8M6CIb1gw7/yHNVPRzGtFXXcd2OQ8qXrIlOj2P',\n [BraintreeModuleName.Fastlane]:\n 'sha384-rhBL1hpZ71JqG+2TsT0Dih47mbjx8cjJCpeZjk9tw3df1gFMKfCTmMyZunhr7H4Y',\n },\n [BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION]: {\n [BraintreeModuleName.Client]:\n 'sha384-0WNxksIpRP+fYZiIdr12g6DBUQfLDzYCQJZtR/C8KkcwSGhPHfcFp3tTaGcMyFTq',\n [BraintreeModuleName.PaypalCheckout]:\n 'sha384-lWM1jk4BOxoDNV6Kop7tVNvQgINlmEVz0c/OwM+HNHK3QC8xqwd54Ovrt2QRDTjh',\n [BraintreeModuleName.Paypal]:\n 'sha384-fXUmVxC2EMZBDXZ7eTHSTL/LFBrHej/MSXT/vTBXvra4lzgLNGvREAp+x0GYObuH',\n [BraintreeModuleName.LocalPayment]:\n 'sha384-pha1xGuGSkmZH5x9aqHvRaO4xLea7rmQ/79PFj9zxNzxuFcOWZg7gOP7FibygOEC',\n [BraintreeModuleName.DataCollector]:\n 'sha384-Q6PI2F9eekWbAxhroybl+aEcvqhdowN/EQlGwBUyJOzPFn9982u9xl6SU6XfGKzc',\n [BraintreeModuleName.UsBankAccount]:\n 'sha384-W3RLQSKJL1tQ3+Y7mP6tmkamtZ8bV4Yw/XxL9Jj5JtXHraD8loMF8hAIG5m2zK7F',\n [BraintreeModuleName.GooglePayment]:\n 'sha384-TITQMsFWA3elDNGP2mWz2oKBo4qjt+TlqzovcaPoeBiAh/wPBi6nae50ADdgU1/i',\n [BraintreeModuleName.ThreeDSecure]:\n 'sha384-YiycYN89ZlL/Evcaq4y1ajW1mhd7JYfZBDuOwHtIn4/Jnm20GL+/XCM+zYAwWD8D',\n [BraintreeModuleName.VisaCheckout]:\n 'sha384-/OdaTv9qrkKzjObtUe6yzfDhHozFW/+uXlrSl736sOZRJpjGQETvpYXqMFFg69xv',\n [BraintreeModuleName.Venmo]:\n 'sha384-dA+ojdW9vbJS4JavcXyOs9d5uZHJg5dNtYupoPSH2zsXIiYDVS5amLb/u8qmQ6oz',\n [BraintreeModuleName.HostedFields]:\n 'sha384-31ZkS58+iaWsW06ftW52zzVZFp43WPd7pNYRiddYynSNg6Oh7WGbSFGorAUH6T1z',\n [BraintreeModuleName.Fastlane]:\n 'sha384-jlbrwNvL3HvLAUCtLSmrnQ2GH1udCUrRS/bVmReAS5fuIVvcW8Pko/Gkg82tlgtr',\n },\n};\n","export enum ApplePayGatewayType {\n BRAINTREE = 'braintree',\n BRAINTREE_FASTLANE = 'braintreeacceleratedcheckout',\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 BraintreeSDKVersionManager from './braintree-sdk-version-manager';\nimport isManageableBraintreeSDKVersion from './isManageableBraintreeSDKVersion';\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 constructor(\n private scriptLoader: ScriptLoader,\n private braintreeHostWindow: BraintreeHostWindow,\n private braintreeSDKVersionManager: BraintreeSDKVersionManager,\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 braintreeSdkVersion = this.braintreeSDKVersionManager.getSDKVersion();\n\n const scriptPath = `//js.braintreegateway.com/web/${braintreeSdkVersion}/js/${fileName}`;\n\n const integrity = isManageableBraintreeSDKVersion(braintreeSdkVersion)\n ? this.getIntegrityValuesByModuleName(braintreeModuleName, braintreeSdkVersion)\n : undefined;\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(\n moduleName: BraintreeModuleName,\n version: keyof typeof BRAINTREE_SDK_SCRIPTS_INTEGRITY,\n ): string {\n const integrity = BRAINTREE_SDK_SCRIPTS_INTEGRITY[version][moduleName];\n\n if (!integrity) {\n throw new Error('Unexpected fileName value');\n }\n\n return integrity;\n }\n}\n","import { BRAINTREE_SDK_SCRIPTS_INTEGRITY } from './braintree-sdk-scripts-integrity';\n\nfunction isManageableBraintreeSDKVersion(\n version: string,\n): version is keyof typeof BRAINTREE_SDK_SCRIPTS_INTEGRITY {\n return version in BRAINTREE_SDK_SCRIPTS_INTEGRITY;\n}\n\nexport default isManageableBraintreeSDKVersion;\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","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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory 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 private _applePayScriptLoader: ApplePayScriptLoader,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithApplePayCustomerInitializeOptions,\n ): Promise {\n const { methodId, applepay } = options;\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 await this._applePayScriptLoader.loadSdk();\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 (\n this._paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE &&\n this._paymentMethod.clientToken\n ) {\n this._braintreeSdk.initialize(this._paymentMethod.clientToken);\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 applePayButton = this._createApplePayButtonElement();\n\n container.appendChild(applePayButton);\n\n return applePayButton;\n }\n\n private _createApplePayButtonElement(): HTMLElement {\n const applePayButton = document.createElement('apple-pay-button');\n\n applePayButton.setAttribute('buttonstyle', 'black');\n applePayButton.setAttribute('type', 'plain');\n applePayButton.setAttribute(\n 'style',\n '--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;',\n );\n\n return applePayButton;\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","import ApplePayWindow from './apple-pay-window';\nimport isApplePayWindow from './is-apple-pay-window';\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 ApplePayWindow from './apple-pay-window';\n\nexport default function isApplePayWindow(window: Window): window is ApplePayWindow {\n return 'ApplePaySession' in window;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { assertApplePayWindow } from './apple-pay-session-factory';\nimport isApplePaySdkWindow from './is-apple-pay-sdk-window';\n\nexport default class ApplePayScriptLoader {\n private sdkVersion = '1.latest';\n\n constructor(private scriptLoader: ScriptLoader) {}\n\n async loadSdk() {\n if (isApplePaySdkWindow(window)) {\n return;\n }\n\n await this.scriptLoader.loadScript(\n `https://applepay.cdn-apple.com/jsapi/${this.sdkVersion}/apple-pay-sdk.js`,\n );\n\n assertApplePayWindow(window);\n }\n}\n","interface ApplePaySdkWindow extends Window {\n ApplePaySDK?: {\n origin: string;\n publicPath: string;\n token: string | undefined;\n };\n}\n\nexport default function isApplePaySdkWindow(window: Window): window is ApplePaySdkWindow {\n return 'ApplePaySDK' in window;\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\n} 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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayCustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n\n return new ApplePayCustomerStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), window, braintreeSDKVersionManager),\n ),\n new ApplePayScriptLoader(new ScriptLoader()),\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 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 { 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 | object;\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 { PayPalBNPLConfigurationItem } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n BuyNowCartRequestBody,\n HostedInstrument,\n ShippingOption,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n/**\n *\n * BigCommerce Payments Funding sources\n *\n */\nexport type FundingType = string;\n// TODO: rename BigCommercePaymentsSDKFunding to PayPalSDKFunding\nexport interface BigCommercePaymentsSDKFunding {\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 * BigCommerce Payments SDK\n *\n */\n\nexport interface BigCommercePaymentsCardFieldsConfig {\n inputEvents: {\n onChange(data: BigCommercePaymentsCardFieldsState): void;\n onFocus(data: BigCommercePaymentsCardFieldsState): void;\n onBlur(data: BigCommercePaymentsCardFieldsState): void;\n onInputSubmitRequest(data: BigCommercePaymentsCardFieldsState): void;\n };\n createVaultSetupToken?: (data: BigCommercePaymentsCardFieldsState) => void;\n createOrder?: () => Promise;\n style: BigCommercePaymentsHostedFieldsRenderOptions['styles'];\n onApprove(data: BigCommercePaymentsCardFieldsOnApproveData): void;\n onError(): void;\n}\n\nexport interface BigCommercePaymentsCardFieldsOnApproveData {\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 BigCommercePaymentsCardFieldsFieldData {\n isFocused: boolean;\n isEmpty: boolean;\n isValid: boolean;\n isPotentiallyValid: boolean;\n}\n\ntype BigCommercePaymentsCardFieldsCard = BigCommercePaymentsHostedFieldsCard;\n\nexport interface BigCommercePaymentsCardFieldsState {\n cards: BigCommercePaymentsCardFieldsCard[];\n emittedBy: string;\n isFormValid: boolean;\n errors: string[];\n fields: {\n cardCvvField: BigCommercePaymentsCardFieldsFieldData;\n cardNumberField: BigCommercePaymentsCardFieldsFieldData;\n cardNameField?: BigCommercePaymentsCardFieldsFieldData;\n cardExpiryField: BigCommercePaymentsCardFieldsFieldData;\n };\n}\n\nexport interface BigCommercePaymentsFields {\n render(container: HTMLElement | string): Promise;\n clear(): void;\n removeClass(className: string): Promise;\n close(): Promise;\n}\n\ninterface BigCommercePaymentsFieldsInitializationData {\n placeholder?: string;\n}\n\nexport interface BigCommercePaymentsCardFields {\n isEligible(): boolean;\n CVVField(config?: BigCommercePaymentsFieldsInitializationData): BigCommercePaymentsFields;\n ExpiryField(config?: BigCommercePaymentsFieldsInitializationData): BigCommercePaymentsFields;\n NameField(config?: BigCommercePaymentsFieldsInitializationData): BigCommercePaymentsFields;\n NumberField(config?: BigCommercePaymentsFieldsInitializationData): BigCommercePaymentsFields;\n submit(config?: BigCommercePaymentsCardFieldsSubmitConfig): Promise;\n getState(): Promise;\n}\n\nexport interface BigCommercePaymentsCardFieldsSubmitConfig {\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: (\n data: BigCommercePaymentsCardFieldsConfig,\n ) => 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: BigCommercePaymentsSDKFunding;\n HostedFields: {\n isEligible(): boolean;\n render(\n data: BigCommercePaymentsHostedFieldsRenderOptions,\n ): Promise;\n };\n Legal: PayPalLegal & LegalFunding;\n Buttons(options: BigCommercePaymentsButtonsOptions): BigCommercePaymentsButtons;\n PaymentFields(\n options: BigCommercePaymentsPaymentFieldsOptions,\n ): BigCommercePaymentsPaymentFields;\n Messages(options: BigCommercePaymentsMessagesOptions): BigCommercePaymentsMessages;\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 BigCommercePaymentsScriptParams {\n options: {\n 'client-id'?: string;\n 'merchant-id'?: string;\n 'buyer-country'?: string;\n 'disable-funding'?: FundingType[];\n 'enable-funding'?: FundingType[];\n currency?: string;\n commit?: boolean;\n intent?: BigCommercePaymentsIntent;\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 'data-namespace'?: string;\n };\n}\n\nexport enum BigCommercePaymentsIntent {\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 BigCommercePaymentsHostWindow extends Window {\n bigCommercePaymentsPayPalSDK?: PayPalSDK;\n}\n\n/**\n *\n * BigCommerce Payments Initialization Data\n *\n */\nexport interface BigCommercePaymentsInitializationData {\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?: BigCommercePaymentsIntent;\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 isAppSwitchEnabled?: boolean;\n paypalBNPLConfiguration?: PayPalBNPLConfigurationItem[];\n}\n\n/**\n *\n * BigCommerce Payments BuyNow\n *\n */\nexport interface PayPalBuyNowInitializeOptions {\n getBuyNowCartRequestBody(): BuyNowCartRequestBody;\n}\n\n/**\n *\n * BigCommerce Payments Hosted Fields\n *\n */\nexport interface BigCommercePaymentsHostedFieldsRenderOptions {\n fields?: {\n number?: BigCommercePaymentsHostedFieldOption;\n cvv?: BigCommercePaymentsHostedFieldOption;\n expirationDate?: BigCommercePaymentsHostedFieldOption;\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 BigCommercePaymentsHostedFieldOption {\n selector: string;\n placeholder?: string;\n}\n\nexport interface BigCommercePaymentsHostedFields {\n submit(\n options?: BigCommercePaymentsHostedFieldsSubmitOptions,\n ): Promise;\n getState(): BigCommercePaymentsHostedFieldsState;\n on(eventName: string, callback: (event: BigCommercePaymentsHostedFieldsState) => void): void;\n}\n\nexport interface BigCommercePaymentsHostedFieldsSubmitOptions {\n contingencies?: Array<'3D_SECURE'>;\n cardholderName?: string;\n}\n\nexport interface BigCommercePaymentsHostedFieldsApprove {\n orderId: string;\n liabilityShift?: 'POSSIBLE' | 'NO' | 'UNKNOWN';\n}\n\nexport interface BigCommercePaymentsHostedFieldsState {\n cards: BigCommercePaymentsHostedFieldsCard[];\n emittedBy: string;\n fields: {\n number?: BigCommercePaymentsHostedFieldsFieldData;\n expirationDate?: BigCommercePaymentsHostedFieldsFieldData;\n expirationMonth?: BigCommercePaymentsHostedFieldsFieldData;\n expirationYear?: BigCommercePaymentsHostedFieldsFieldData;\n cvv?: BigCommercePaymentsHostedFieldsFieldData;\n postalCode?: BigCommercePaymentsHostedFieldsFieldData;\n };\n}\n\nexport interface BigCommercePaymentsHostedFieldsCard {\n type: string;\n niceType: string;\n code: {\n name: string;\n size: number;\n };\n}\n\nexport interface BigCommercePaymentsHostedFieldsFieldData {\n container: HTMLElement;\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\n/**\n *\n * BigCommerce Payments Buttons\n *\n */\nexport interface BigCommercePaymentsButtons {\n render(id: string): void;\n close(): void;\n isEligible(): boolean;\n hasReturned?(): boolean;\n resume?(): void;\n}\n\nexport interface BigCommercePaymentsButtonsOptions {\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 phone?: {\n phone_number: {\n national_number: string;\n };\n };\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 * BigCommerce Payments Payment fields\n *\n */\nexport interface BigCommercePaymentsPaymentFields {\n render(id: string): void;\n}\n\nexport interface BigCommercePaymentsPaymentFieldsOptions {\n style?: BigCommercePaymentsFieldsStyleOptions;\n fundingSource: string;\n fields: {\n name?: {\n value?: string;\n };\n email?: {\n value?: string;\n };\n };\n}\n\nexport interface BigCommercePaymentsFieldsStyleOptions {\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 * BigCommercePayments Messages\n */\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface BigCommercePaymentsMessages {\n render(id: string): void;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface BigCommercePaymentsMessagesOptions {\n amount: number;\n placement: string;\n style?: BigCommercePaymentsMessagesStyleOptions;\n fundingSource?: string;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface BigCommercePaymentsMessagesStyleOptions {\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 fastlaneToken?: string;\n methodId?: string;\n gatewayId?: string;\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 BigCommercePaymentsRequestSender from './bigcommerce-payments-request-sender';\nimport BigCommercePaymentsScriptLoader from './bigcommerce-payments-script-loader';\nimport {\n BigCommercePaymentsInitializationData,\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n PayPalCreateOrderCardFieldsResponse,\n PayPalCreateOrderRequestBody,\n PayPalOrderDetails,\n PayPalOrderStatus,\n PayPalSDK,\n StyleButtonColor,\n StyleButtonLabel,\n StyleButtonShape,\n} from './bigcommerce-payments-types';\n\nexport default class BigCommercePaymentsIntegrationService {\n private paypalSdk?: PayPalSDK;\n\n constructor(\n private formPoster: FormPoster,\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsRequestSender: BigCommercePaymentsRequestSender,\n private bigCommercePaymentsScriptLoader: BigCommercePaymentsScriptLoader,\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.bigCommercePaymentsScriptLoader.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.bigCommercePaymentsRequestSender.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.bigCommercePaymentsRequestSender.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.bigCommercePaymentsRequestSender.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.bigCommercePaymentsRequestSender.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: address?.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 phone: payer.phone?.phone_number?.national_number,\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","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 } 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 './bigcommerce-payments-types';\n\nexport default class BigCommercePaymentsRequestSender {\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/bigcommerce_payments`;\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 = 'bigcommerce_payments',\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 BigCommercePaymentsHostWindow,\n BigCommercePaymentsInitializationData,\n BigCommercePaymentsScriptParams,\n ComponentsScriptType,\n FundingType,\n PayPalSDK,\n} from './bigcommerce-payments-types';\n\nexport default class BigCommercePaymentsScriptLoader {\n private window: BigCommercePaymentsHostWindow;\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: BigCommercePaymentsScriptParams,\n forceLoad = false,\n ): Promise {\n if (!this.window.bigCommercePaymentsPayPalSDK || 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.bigCommercePaymentsPayPalSDK) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.bigCommercePaymentsPayPalSDK;\n }\n\n private getPayPalSdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage = true,\n ): BigCommercePaymentsScriptParams {\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 === 'bigcommerce_payments_creditcards';\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 enableVenmoFunding = isVenmoEnabled ? ['venmo'] : [];\n const disableVenmoFunding = !isVenmoEnabled ? ['venmo'] : [];\n const disableAPMsFunding = availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n );\n const googlePayComponent: ComponentsScriptType = isGooglePayEnabled ? ['googlepay'] : [];\n const cardFieldsComponent: ComponentsScriptType = initializesOnCheckoutPage\n ? ['card-fields']\n : [];\n const disableFunding: FundingType[] = this.filterFundingOptions([\n ...disableCardFunding,\n ...disableCreditFunding,\n ...disableVenmoFunding,\n ...disableAPMsFunding,\n ]);\n const enableFunding: FundingType[] = this.filterFundingOptions([\n ...enableCardFunding,\n ...enableCreditFunding,\n ...enableVenmoFunding,\n ...enabledAlternativePaymentMethods,\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 'data-namespace': 'bigCommercePaymentsPayPalSDK',\n },\n };\n }\n\n private filterFundingOptions(fundingOptions: FundingType[] | undefined): FundingType[] {\n const fundingTypesToBeFiltered = ['klarna', 'afterpay'];\n\n if (!fundingOptions) {\n return [];\n }\n\n return fundingOptions.filter(\n (fundingOption: FundingType) => !fundingTypesToBeFiltered.includes(fundingOption),\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 BigCommercePaymentsIntegrationService,\n BigCommercePaymentsRequestSender,\n BigCommercePaymentsScriptLoader,\n} from './index';\n\nconst createBigCommercePaymentsIntegrationService = (\n paymentIntegrationService: PaymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new BigCommercePaymentsIntegrationService(\n createFormPoster(),\n paymentIntegrationService,\n new BigCommercePaymentsRequestSender(createRequestSender({ host: getHost() })),\n new BigCommercePaymentsScriptLoader(getScriptLoader()),\n );\n};\n\nexport default createBigCommercePaymentsIntegrationService;\n","const DefaultCheckoutButtonHeight = 40;\n\nexport default DefaultCheckoutButtonHeight;\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsCustomerInitializeOptions, {\n WithBigCommercePaymentsCustomerInitializeOptions,\n} from './bigcommerce-payments-customer-initialize-options';\n\nexport default class BigCommercePaymentsCustomerStrategy implements CustomerStrategy {\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBigCommercePaymentsCustomerInitializeOptions,\n ): Promise {\n const { bigcommerce_payments, 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 (!bigcommerce_payments) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments\" argument is not provided.',\n );\n }\n\n if (!bigcommerce_payments.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments.container\" argument is not provided.',\n );\n }\n\n if (bigcommerce_payments.onClick && typeof bigcommerce_payments.onClick !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments.onClick\" argument is not a function.',\n );\n }\n\n this.onError = bigcommerce_payments.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 const paypalSdk = await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n // eslint-disable-next-line no-console\n console.error(\n '[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n this.renderButton(methodId, bigcommerce_payments);\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 bigcommerce_payments: BigCommercePaymentsCustomerInitializeOptions,\n ): void {\n const { container, onClick, onComplete } = bigcommerce_payments;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const {\n isHostedCheckoutEnabled,\n paymentButtonStyles,\n isAppSwitchEnabled = false,\n } = paymentMethod.initializationData || {};\n const { checkoutTopButtonStyles } = paymentButtonStyles || {};\n\n const defaultCallbacks = {\n ...(isAppSwitchEnabled && {\n appSwitchWhenAvailable: true,\n }),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder('bigcommerce_payments'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.tokenizePayment(methodId, orderID),\n ...(onClick && { onClick: () => onClick() }),\n };\n\n const hostedCheckoutCallbacks = {\n ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n }),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const buttonRenderOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.bigCommercePaymentsIntegrationService.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 if (paypalButton.hasReturned?.() && isAppSwitchEnabled) {\n paypalButton.resume?.();\n } else {\n paypalButton.render(`#${container}`);\n }\n } else {\n this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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 =\n this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsCustomerStrategy from './bigcommerce-payments-customer-strategy';\n\nconst createBigCommercePaymentsCustomerStrategy: CustomerStrategyFactory<\n BigCommercePaymentsCustomerStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsCustomerStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsCustomerStrategy, [\n { id: 'bigcommerce_payments' },\n]);\n","import { HostedInstrument, NonceInstrument } from './payment';\n\ntype PaymentInstrument = CardInstrument | AccountInstrument | HostedInstrument | NonceInstrument;\n\nexport default PaymentInstrument;\n\nexport interface 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 { CardInstrument, CustomerAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n/**\n *\n * BigCommerce Payments Funding sources\n *\n */\nexport type FundingType = string;\n\n/**\n *\n * BigCommerce Payments Initialization Data\n *\n */\nexport interface BigCommercePaymentsInitializationData {\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 BCP Fastlane A/B test will be finished\n enabledAlternativePaymentMethods: FundingType[];\n isDeveloperModeApplicable?: boolean;\n intent?: BigCommercePaymentsIntent;\n isAcceleratedCheckoutEnabled?: boolean; // PayPal Fastlane related\n isFastlaneShippingOptionAutoSelectEnabled?: boolean; // PayPal Fastlane related\n isFastlaneStylingEnabled?: boolean;\n isHostedCheckoutEnabled?: boolean;\n isBigCommercePaymentsAnalyticsV2Enabled?: 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 BCP Fastlane A/B test will be finished\n paymentButtonStyles?: Record;\n paypalBNPLConfiguration?: PayPalBNPLConfigurationItem[];\n threeDSVerificationMethod?: string;\n}\n\n/**\n *\n * PayPalHostWindow contains different\n * PayPal Sdk instances for different purposes\n *\n */\nexport interface PayPalHostWindow extends Window {\n bigCommercePaymentsFastlane?: PayPalFastlane;\n bigCommercePaymentsFastlaneSdk?: PayPalFastlaneSdk;\n bigCommercePaymentsMessages?: PayPalMessagesSdk;\n bigCommercePaymentsApms?: PayPalApmSdk;\n bigCommercePaymentsGooglePay?: PayPalGooglePaySdk;\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'?: FundingType[];\n 'disable-funding'?: FundingType[];\n currency?: string;\n commit?: boolean;\n intent?: BigCommercePaymentsIntent;\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 'data-sdk-client-token'?: string;\n };\n}\n\nexport enum BigCommercePaymentsIntent {\n AUTHORIZE = 'authorize',\n CAPTURE = 'capture',\n}\n\nexport type PayPalSdkComponents = Array<\n 'fastlane' | 'messages' | 'buttons' | 'payment-fields' | 'googlepay' | 'three-domain-secure'\n>;\n\n/**\n *\n * PayPal Sdk instances\n *\n */\nexport enum LiabilityShiftEnum {\n Possible = 'POSSIBLE',\n No = 'NO',\n Unknown = 'UNKNOWN',\n Yes = 'YES',\n}\n\nexport interface threeDSecureParameters {\n amount: string;\n currency: string;\n nonce: string;\n threeDSRequested: boolean;\n transactionContext: {\n experience_context: {\n brand_name?: string;\n locale: string;\n return_url: string;\n cancel_url: string;\n };\n };\n}\n\nexport interface PayPalFastlaneSdk {\n ThreeDomainSecureClient: {\n isEligible(params: threeDSecureParameters): Promise;\n show(): Promise;\n };\n Fastlane(options?: PayPalFastlaneOptions): Promise;\n}\n\ninterface ThreeDomainSecureClientShowResponse {\n liabilityShift: LiabilityShiftEnum;\n authenticationState: TDSecureAuthenticationState;\n nonce: string; // Enriched nonce or the original nonce\n}\n\nexport interface PayPalMessagesSdk {\n Messages(options: MessagingOptions): MessagingRender;\n}\n\nexport interface PayPalApmSdk {\n Buttons(options: BigCommercePaymentsButtonsOptions): BigCommercePaymentsButtons;\n PaymentFields(\n options: BigCommercePaymentsPaymentFieldsOptions,\n ): BigCommercePaymentsPaymentFields;\n}\n\nexport interface PayPalGooglePaySdk {\n Googlepay(): GooglePay;\n}\n\nexport enum TDSecureVerificationMethod {\n Always = 'SCA_ALWAYS',\n}\n\nexport enum TDSecureAuthenticationState {\n Succeeded = 'succeeded',\n Cancelled = 'cancelled',\n Errored = 'errored',\n}\n\n/**\n *\n * Google Pay related types\n *\n */\n\ninterface GooglePay {\n config: () => Promise;\n confirmOrder: (confirmOrderConfig: ConfirmOrderConfig) => Promise<{ status: string }>;\n initiatePayerAction: (payerActionConfig: PayerActionConfig) => Promise;\n}\n\ninterface ConfirmOrderConfig {\n orderId: string;\n paymentMethodData: ConfirmOrderData;\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\ninterface PayerActionConfig {\n orderId: 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\n/**\n *\n * BigCommerce Payments Buttons\n *\n */\nexport interface BigCommercePaymentsButtons {\n render(id: string): void;\n close(): void;\n isEligible(): boolean;\n}\n\nexport interface BigCommercePaymentsButtonsOptions {\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 * BigCommerce Payments PaymentFields fields\n *\n */\nexport interface BigCommercePaymentsPaymentFields {\n render(id: string): void;\n}\n\nexport interface BigCommercePaymentsPaymentFieldsOptions {\n style?: BigCommercePaymentsFieldsStyleOptions;\n fundingSource: string;\n fields: {\n name?: {\n value?: string;\n };\n email?: {\n value?: string;\n };\n };\n}\n\nexport interface BigCommercePaymentsFieldsStyleOptions {\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 = 'canceled',\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\nexport interface RedirectError {\n body: {\n additional_action_required: {\n data: {\n redirect_url: string;\n };\n };\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 BigCommercePaymentsInitializationData,\n FundingType,\n PayPalFastlaneSdk,\n PayPalGooglePaySdk,\n PayPalHostWindow,\n PayPalMessagesSdk,\n PayPalSdkConfig,\n} from './bigcommerce-payments-types';\n\nexport default class PayPalSdkHelper {\n private window: PayPalHostWindow;\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.bigCommercePaymentsFastlaneSdk) {\n const config = this.getPayPalFastlaneSdkConfiguration(\n paymentMethod,\n currencyCode,\n sessionId,\n );\n\n await this.loadPayPalSdk(config);\n\n if (!this.window.bigCommercePaymentsFastlaneSdk) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.window.bigCommercePaymentsFastlaneSdk;\n }\n\n async getPayPalGooglePaySdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n if (!this.window.bigCommercePaymentsGooglePay || forceLoad) {\n const paypalSdkScriptConfig = this.getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n initializesOnCheckoutPage,\n );\n\n await this.loadPayPalSdk(paypalSdkScriptConfig);\n }\n\n if (!this.window.bigCommercePaymentsGooglePay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.bigCommercePaymentsGooglePay;\n }\n\n async getPayPalApmsSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n ) {\n if (!this.window.bigCommercePaymentsApms) {\n const config = this.getPayPalApmSdkConfiguration(paymentMethod, currencyCode);\n\n await this.loadPayPalSdk(config);\n\n if (!this.window.bigCommercePaymentsApms) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.window.bigCommercePaymentsApms;\n }\n\n async getPayPalMessages(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n ): Promise {\n if (!this.window.bigCommercePaymentsMessages) {\n const paypalSdkMessagesConfig = this.getPayPalSdkMessagesConfiguration(\n paymentMethod,\n currencyCode,\n );\n\n await this.loadPayPalSdk(paypalSdkMessagesConfig);\n }\n\n if (!this.window.bigCommercePaymentsMessages) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.bigCommercePaymentsMessages;\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 { intent, clientId, merchantId, attributionId } = initializationData;\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit: true,\n components: ['fastlane', 'three-domain-secure'],\n currency: currencyCode,\n intent,\n },\n attributes: {\n 'data-client-metadata-id': sessionId.replace(/-/g, ''),\n 'data-namespace': 'bigCommercePaymentsFastlaneSdk',\n 'data-partner-attribution-id': attributionId,\n 'data-sdk-client-token': clientToken,\n },\n };\n }\n\n private getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage = true,\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 buyerCountry,\n attributionId,\n isHostedCheckoutEnabled,\n isDeveloperModeApplicable,\n } = initializationData;\n\n const commit = isHostedCheckoutEnabled || initializesOnCheckoutPage;\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit,\n components: ['googlepay'],\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 'data-namespace': 'bigCommercePaymentsGooglePay',\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 = this.filterFundingOptions(enabledAlternativePaymentMethods);\n const disableAPMsFunding = this.filterFundingOptions(\n availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n ),\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': 'bigCommercePaymentsApms',\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': 'bigCommercePaymentsMessages',\n 'data-partner-attribution-id': attributionId,\n },\n };\n }\n\n /**\n *\n * Utils methods\n *\n */\n private filterFundingOptions(fundingOptions: FundingType[] | undefined): FundingType[] {\n const fundingTypesToBeFiltered = ['klarna', 'afterpay'];\n\n if (!fundingOptions) {\n return [];\n }\n\n return fundingOptions.filter(\n (fundingOption: FundingType) => !fundingTypesToBeFiltered.includes(fundingOption),\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 { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport PayPalSdkHelper from './paypal-sdk-helper';\n\nexport default function createBigCommercePaymentsSdk(): PayPalSdkHelper {\n return new PayPalSdkHelper(createScriptLoader());\n}\n","interface CookieOptions {\n expires?: Date;\n path?: string;\n domain?: string;\n secure?: boolean;\n}\n\nexport default class CookieStorage {\n static get(name: string): string | null {\n const cookieKey = `${encodeURIComponent(`${name}`)}=`;\n const cookie = document.cookie;\n\n let value = null;\n\n const firstIndex = cookie.indexOf(cookieKey);\n\n if (firstIndex > -1) {\n let lastIndex = cookie.indexOf(';', firstIndex);\n\n if (lastIndex === -1) {\n lastIndex = cookie.length;\n }\n\n value = decodeURIComponent(cookie.substring(firstIndex + cookieKey.length, lastIndex));\n }\n\n return value;\n }\n\n static set(name: string, value: string, options: CookieOptions = { secure: true }) {\n let cookieText = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;\n\n const { expires, path, domain, secure } = options;\n\n if (expires) {\n cookieText += `; expires=${expires.toUTCString()}`;\n } else {\n const now = new Date();\n // info: default cookie expiration time after setup\n const minutes = 60;\n\n now.setTime(now.getTime() + minutes * 60 * 1000);\n\n cookieText += `; expires=${now.toUTCString()}`;\n }\n\n if (path) {\n cookieText += `; path=${path}`;\n }\n\n if (domain) {\n cookieText += `; domain=${domain}`;\n }\n\n if (secure) {\n cookieText += '; secure';\n }\n\n document.cookie = cookieText;\n }\n\n static remove(name: string, options?: CookieOptions) {\n CookieStorage.set(name, '', { expires: new Date(0), ...options });\n }\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 { CookieStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport {\n PayPalFastlane,\n PayPalFastlaneAddress,\n PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneLookupCustomerByEmailResult,\n PayPalFastlaneProfileCard,\n PayPalFastlaneProfileName,\n PayPalFastlaneProfilePhone,\n PayPalFastlaneProfileToBcCustomerDataMappingResult,\n PayPalFastlaneSdk,\n PayPalFastlaneStylesOption,\n PayPalHostWindow,\n} from './bigcommerce-payments-types';\n\nexport default class BigCommercePaymentsFastlaneUtils {\n private window: PayPalHostWindow;\n\n constructor() {\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.bigCommercePaymentsFastlane) {\n const defaultStyles = {\n root: {\n backgroundColorPrimary: 'transparent',\n },\n };\n\n this.window.bigCommercePaymentsFastlane = await paypalFastlaneSdk.Fastlane({\n styles: styles || defaultStyles,\n });\n }\n\n return this.window.bigCommercePaymentsFastlane;\n }\n\n getPayPalFastlaneOrThrow(): PayPalFastlane {\n if (!this.window.bigCommercePaymentsFastlane) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.bigCommercePaymentsFastlane;\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 *\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(sessionId: string): void {\n const expires = new Date();\n\n expires.setDate(expires.getDate() + 14); // 2 weeks expiry\n\n const cookiesOption = {\n expires,\n secure: true,\n };\n\n CookieStorage.set('bc-fastlane-sessionId', sessionId, cookiesOption);\n }\n\n removeStorageSessionId(): void {\n CookieStorage.remove('bc-fastlane-sessionId');\n }\n\n getStorageSessionId(): string {\n return CookieStorage.get('bc-fastlane-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 BigCommercePaymentsFastlaneUtils from './bigcommerce-payments-fastlane-utils';\n\nexport default function createBigCommercePaymentsFastlaneUtils(): BigCommercePaymentsFastlaneUtils {\n return new BigCommercePaymentsFastlaneUtils();\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 BigCommercePaymentsFastlaneUtils,\n BigCommercePaymentsInitializationData,\n getFastlaneStyles,\n PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneStylesOption,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsFastlaneCustomerInitializeOptions, {\n WithBigCommercePaymentsFastlaneCustomerInitializeOptions,\n} from './bigcommerce-payments-fastlane-customer-initialize-options';\n\nexport default class BigCommercePaymentsFastlaneCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsSdk: PayPalSdkHelper,\n private bigCommercePaymentsFastlaneUtils: BigCommercePaymentsFastlaneUtils,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions &\n WithBigCommercePaymentsFastlaneCustomerInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_fastlane } = 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.bigCommercePaymentsSdk.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n );\n\n await this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(\n paypalFastlaneSdk,\n isTestModeEnabled,\n this.getFastlaneStyles(methodId, bigcommerce_payments_fastlane),\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 await this.paymentIntegrationService.updatePaymentProviderCustomer({\n authenticationState: undefined,\n addresses: undefined,\n instruments: undefined,\n });\n\n this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId();\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 } =\n await this.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(customerEmail);\n\n const authenticationResult =\n await this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(\n customerContextId,\n );\n\n const isAuthenticationFlowCanceled =\n authenticationResult.authenticationState === PayPalFastlaneAuthenticationState.CANCELED;\n\n await this.updateCustomerDataState(methodId, authenticationResult);\n\n if (isAuthenticationFlowCanceled) {\n this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId();\n } else {\n this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(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.bigCommercePaymentsFastlaneUtils.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(\n methodId,\n );\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 bigcommerce_payments_fastlane:\n | BigCommercePaymentsFastlaneCustomerInitializeOptions\n | 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 bigcommerce_payments_fastlane?.styles,\n );\n }\n}\n","import {\n createBigCommercePaymentsFastlaneUtils,\n createBigCommercePaymentsSdk,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsFastlaneCustomerStrategy from './bigcommerce-payments-fastlane-customer-strategy';\n\nconst createBigCommercePaymentsFastlaneCustomerStrategy: CustomerStrategyFactory<\n BigCommercePaymentsFastlaneCustomerStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsFastlaneCustomerStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsSdk(),\n createBigCommercePaymentsFastlaneUtils(),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsFastlaneCustomerStrategy, [\n { id: 'bigcommerce_payments_fastlane' }, // this method id will be provided for users from test group\n { id: 'bigcommerce_payments_creditcards' }, // this method id will be provided for users from control group\n]);\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsPayLaterCustomerInitializeOptions, {\n WithBigCommercePaymentsPayLaterCustomerInitializeOptions,\n} from './bigcommerce-payments-paylater-customer-initialize-options';\n\nexport default class BigCommercePaymentsPayLaterCustomerStrategy implements CustomerStrategy {\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions &\n WithBigCommercePaymentsPayLaterCustomerInitializeOptions,\n ): Promise {\n const { bigcommerce_payments_paylater, 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 (!bigcommerce_payments_paylater) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_paylater\" argument is not provided.',\n );\n }\n\n if (!bigcommerce_payments_paylater.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_paylater.container\" argument is not provided.',\n );\n }\n\n if (\n bigcommerce_payments_paylater.onClick &&\n typeof bigcommerce_payments_paylater.onClick !== 'function'\n ) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_paylater.onClick\" argument is not a function.',\n );\n }\n\n this.onError = bigcommerce_payments_paylater.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 const paypalSdk = await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n // eslint-disable-next-line no-console\n console.error(\n '[BC BigCommercePayments PayLater]: button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n this.renderButton(methodId, bigcommerce_payments_paylater);\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 bigCommercePaymentsPayLater: BigCommercePaymentsPayLaterCustomerInitializeOptions,\n ): void {\n const { container, onComplete, onClick } = bigCommercePaymentsPayLater;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_paylater',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.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: BigCommercePaymentsButtonsOptions = {\n fundingSource,\n style: this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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 =\n this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsPayLaterCustomerStrategy from './bigcommerce-payments-paylater-customer-strategy';\n\nconst createBigCommercePaymentsPayLaterCustomerStrategy: CustomerStrategyFactory<\n BigCommercePaymentsPayLaterCustomerStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsPayLaterCustomerStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsPayLaterCustomerStrategy, [\n { id: 'bigcommerce_payments_paylater' },\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsVenmoCustomerInitializeOptions, {\n WithBigCommercePaymentsVenmoCustomerInitializeOptions,\n} from './bigcommerce-payments-venmo-customer-initialize-options';\n\nexport default class BigCommercePaymentsVenmoCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBigCommercePaymentsVenmoCustomerInitializeOptions,\n ): Promise {\n const { bigcommerce_payments_venmo, 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 (!bigcommerce_payments_venmo) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_venmo\" argument is not provided.',\n );\n }\n\n if (!bigcommerce_payments_venmo.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_venmo.container\" argument is not provided.',\n );\n }\n\n if (\n bigcommerce_payments_venmo.onClick &&\n typeof bigcommerce_payments_venmo.onClick !== 'function'\n ) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_venmo.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 const paypalSdk = await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n // eslint-disable-next-line no-console\n console.error(\n '[BC Payments Venmo]: Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n this.renderButton(methodId, bigcommerce_payments_venmo);\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 bigcommerce_payments_venmo: BigCommercePaymentsVenmoCustomerInitializeOptions,\n ): void {\n const { container, onClick } = bigcommerce_payments_venmo;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.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: BigCommercePaymentsButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle({\n ...checkoutTopButtonStyles,\n height: DefaultCheckoutButtonHeight,\n }),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_venmo',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.removeElement(container);\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsVenmoCustomerStrategy from './bigcommerce-payments-venmo-customer-strategy';\n\nconst createBigCommercePaymentsVenmoCustomerStrategy: CustomerStrategyFactory<\n BigCommercePaymentsVenmoCustomerStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsVenmoCustomerStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsVenmoCustomerStrategy, [\n { id: 'bigcommerce_payments_venmo' },\n]);\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 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 {\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 { 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 { 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","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 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 { BraintreePaypalCheckout, BraintreePaypalSdkCreatorConfig } from './braintree';\nimport { BraintreeError } from './types';\n\nlet paypalSdkPromise: Promise | null = null;\n\nexport default function loadPayPalSDKOnce(\n paypalCheckout: BraintreePaypalCheckout,\n config: BraintreePaypalSdkCreatorConfig,\n): Promise {\n if (!paypalSdkPromise) {\n paypalSdkPromise = new Promise((resolve, reject) => {\n paypalCheckout.loadPayPalSDK(config, (err: null | undefined | BraintreeError) => {\n if (err) {\n paypalSdkPromise = null;\n\n reject(err);\n } else {\n resolve(paypalCheckout);\n }\n });\n });\n }\n\n return paypalSdkPromise;\n}\n\n// for testing purposes\nexport function resetLoadPayPalSDKOncePromise() {\n paypalSdkPromise = null;\n}\n","// 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 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 enum MessagingPlacements {\n CART = 'cart',\n HOME = 'homepage',\n PAYMENT = 'payment',\n PRODUCT = 'product',\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 | string;\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';\nimport { isEmpty } from 'lodash';\n\nimport {\n Address,\n CancellablePromise,\n CreditCardInstrument,\n LegacyAddress,\n NonceInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethodCancelledError,\n UnsupportedBrowserError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { Overlay } from '@bigcommerce/checkout-sdk/ui';\n\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport loadPayPalSDKOnce from './load-paypal-sdk-once';\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 BraintreeRequestData,\n BraintreeShippingAddressOverride,\n BraintreeThreeDSecure,\n BraintreeThreeDSecureOptions,\n BraintreeTokenizationDetails,\n BraintreeTokenizePayload,\n BraintreeVenmoCheckout,\n BraintreeVenmoCreatorConfig,\n BraintreeVerifyPayload,\n PAYPAL_COMPONENTS,\n TokenizationPayload,\n} from './types';\nimport isBraintreeError from './utils/is-braintree-error';\nimport isCreditCardInstrumentLike from './utils/is-credit-card-instrument-like';\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 private threeDSecureOptions?: BraintreeThreeDSecureOptions;\n private threeDS?: Promise;\n private venmoCheckout?: BraintreeVenmoCheckout;\n\n constructor(\n private braintreeScriptLoader: BraintreeScriptLoader,\n private braintreeHostWindow: BraintreeHostWindow,\n private overlay?: Overlay,\n ) {}\n\n initialize(clientToken: string, threeDSecureOptions?: BraintreeThreeDSecureOptions) {\n this.clientToken = clientToken;\n this.threeDSecureOptions = threeDSecureOptions;\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 void loadPayPalSDKOnce(braintreePaypalCheckout, paypalSdkLoadConfig).then(\n paypalSdkLoadCallback,\n );\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 async get3DS(): Promise {\n if (!this.threeDS) {\n this.threeDS = Promise.all([\n this.getClient(),\n this.braintreeScriptLoader.load3DS(),\n ]).then(([client, threeDSecure]) => threeDSecure.create({ client, version: 2 }));\n }\n\n return this.threeDS;\n }\n\n async getVenmoCheckout(\n venmoConfig?: BraintreeVenmoCreatorConfig,\n ): Promise {\n if (!this.venmoCheckout) {\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 ...(venmoConfig || {}),\n };\n\n this.venmoCheckout = await new Promise((resolve, reject) => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n venmoCheckout.create(\n venmoCheckoutConfig,\n (error: BraintreeError, braintreeVenmoCheckout: BraintreeVenmoCheckout) => {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (error) {\n return reject(error);\n }\n\n if (!braintreeVenmoCheckout.isBrowserSupported()) {\n return reject(new UnsupportedBrowserError());\n }\n\n resolve(braintreeVenmoCheckout);\n },\n );\n });\n }\n\n return this.venmoCheckout;\n }\n\n /*\n Braintree Credit Card and Braintree Hosted Form\n */\n async verifyCard(\n payment: Payment,\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 async tokenizeCard(payment: Payment, billingAddress: Address): 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.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 challenge3DSVerification(\n tokenizationPayload: TokenizationPayload,\n amount: number,\n ): Promise {\n const threeDSecure = await this.get3DS();\n\n return this.present3DSChallenge(threeDSecure, amount, tokenizationPayload);\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 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 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\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 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 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 // eslint-disable-next-line @typescript-eslint/no-use-before-define\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 if (addFrame) {\n addFrame(error, iframe, cancelVerifyCard);\n }\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","import { CreditCardInstrument } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isCreditCardInstrumentLike(\n instrument: unknown,\n): instrument is CreditCardInstrument {\n if (typeof instrument !== 'object' || instrument === null) {\n return false;\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const creditCardInstrument = instrument as Partial>;\n\n return (\n typeof creditCardInstrument.ccExpiry === 'object' &&\n creditCardInstrument.ccExpiry !== null &&\n typeof creditCardInstrument.ccNumber === 'string' &&\n typeof creditCardInstrument.ccName === 'string'\n );\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 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\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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-initialize-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\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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","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","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 { CookieStorage } 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 ) {}\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.saveSessionIdToCookies(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.removeSessionIdFromCookies();\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.saveSessionIdToCookies(cart.id);\n\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 * Session id management\n *\n */\n getSessionIdFromCookies(): string {\n return CookieStorage.get('bc-fastlane-sessionId') || '';\n }\n\n saveSessionIdToCookies(sessionId: string): void {\n const expires = new Date();\n\n expires.setDate(expires.getDate() + 14); // 2 weeks expiry\n\n CookieStorage.set('bc-fastlane-sessionId', sessionId, {\n expires,\n secure: true,\n });\n }\n\n removeSessionIdFromCookies(): void {\n CookieStorage.remove('bc-fastlane-sessionId');\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, binDetails } = 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: binDetails?.bin || '',\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 BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n );\n const braintreeFastlaneUtils = new BraintreeFastlaneUtils(\n paymentIntegrationService,\n braintreeIntegrationService,\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), hostWindow, braintreeSDKVersionManager),\n );\n\n return new BraintreeVisaCheckoutCustomerStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeSdk,\n );\n};\n\nexport default toResolvableModule(createBraintreeVisaCheckoutCustomerStrategy, [\n { id: 'braintreevisacheckout' },\n]);\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 { isOperaWindow } from '../is-opera-window';\nimport { isReactNativeWindow } from '../is-react-native-window';\n\nexport function isWebView(): boolean {\n if (typeof window === 'undefined') {\n return false;\n }\n\n if (isReactNativeWindow(window)) {\n return true;\n }\n\n const userAgent =\n navigator.userAgent || navigator.vendor || (isOperaWindow(window) ? window.opera : '');\n\n const isAndroidWebView = /android.+; wv/i.test(userAgent);\n const isIOSWebView =\n /iPhone|iPod|iPad/i.test(userAgent) &&\n /AppleWebKit/i.test(userAgent) &&\n !/Safari/i.test(userAgent);\n\n return isAndroidWebView || isIOSWebView;\n}\n","interface ReactNativeWindow extends Window {\n ReactNativeWebView: {\n postMessage(msg: string): void;\n };\n}\n\nexport function isReactNativeWindow(window: Window): window is ReactNativeWindow {\n return 'ReactNativeWebView' in window;\n}\n","interface OperaWindow extends Window {\n opera: string;\n}\n\nexport function isOperaWindow(window: Window): window is OperaWindow {\n return 'opera' in window;\n}\n","import { BigCommercePaymentsIntent } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 offerInfo?: Offers;\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 NewOfferInfo {\n newOfferInfo?: Offers;\n}\n\nexport interface Offers {\n offers: OfferInfoItem[];\n}\n\nexport interface GooglePayError {\n message: string;\n reason: ErrorReasonType;\n intent: CallbackTriggerType;\n}\n\nexport enum ErrorReasonType {\n OFFER_INVALID = 'OFFER_INVALID',\n PAYMENT_DATA_INVALID = 'PAYMENT_DATA_INVALID',\n SHIPPING_ADDRESS_INVALID = 'SHIPPING_ADDRESS_INVALID',\n SHIPPING_ADDRESS_UNSERVICEABLE = 'SHIPPING_ADDRESS_UNSERVICEABLE',\n SHIPPING_OPTION_INVALID = 'SHIPPING_OPTION_INVALID',\n OTHER_ERROR = 'OTHER_ERROR',\n}\n\nexport interface OfferInfoItem {\n redemptionCode: string;\n description: string;\n}\n\nexport interface HandleCouponsOut {\n newOfferInfo: GooglePayPaymentDataRequest['offerInfo'];\n error?: GooglePayError;\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 offerData: {\n redemptionCodes: string[];\n };\n}\n\nexport interface GooglePayPaymentOptions {\n paymentDataCallbacks?: {\n onPaymentDataChanged(\n intermediatePaymentData: IntermediatePaymentData,\n ): onPaymentDataChangedOut;\n };\n}\n\nexport type onPaymentDataChangedOut = Promise<\n | (NewTransactionInfo & NewShippingOptionParameters & NewOfferInfo & { error?: GooglePayError })\n | void\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) => Promise;\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 isWebViewExperimentOn?: boolean;\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 GooglePayBigCommercePaymentsInitializationData\n 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?: BigCommercePaymentsIntent;\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 shopperLanguage: string;\n useNewStripeJsVersion?: boolean;\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 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 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 | GooglePayBigCommercePaymentsInitializationData;\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","/**\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 * A container for loading spinner.\n */\n loadingContainerId?: string;\n\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 BIGCOMMERCE_PAYMENTS = 'googlepay_bigcommerce_payments',\n CHECKOUT_COM = 'googlepaycheckoutcom',\n CYBERSOURCE_V2 = 'googlepaycybersourcev2',\n ORBITAL = 'googlepayorbital',\n STRIPE = 'googlepaystripe',\n STRIPE_UPE = 'googlepaystripeupe',\n STRIPE_OCS = 'googlepaystripeocs',\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 { 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';\nimport { isExperimentEnabled, isWebView } from '@bigcommerce/checkout-sdk/utility';\n\nimport isGooglePayCardNetworkKey from '../guards/is-google-pay-card-network-key';\nimport {\n CallbackIntentsType,\n CallbackTriggerType,\n ErrorReasonType,\n ExtraPaymentData,\n GooglePayCardDataResponse,\n GooglePayCardNetwork,\n GooglePayCardParameters,\n GooglePayError,\n GooglePayFullBillingAddress,\n GooglePayGatewayParameters,\n GooglePayInitializationData,\n GooglePayMerchantInfo,\n GooglePayPaymentDataRequest,\n GooglePayRequiredPaymentData,\n GooglePaySetExternalCheckoutData,\n GooglePayTransactionInfo,\n HandleCouponsOut,\n IntermediatePaymentData,\n ShippingOptionParameters,\n TotalPriceStatusType,\n} from '../types';\n\nexport default class GooglePayGateway {\n private _getPaymentMethodFn?: () => PaymentMethod;\n private _isBuyNowFlow = false;\n private _shouldRequestShipping = true;\n private _currencyCode?: string;\n private _currencyService?: CurrencyService;\n private _isWebViewExperimentOn: null | boolean = null;\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 customFields = [],\n } = this._paymentIntegrationService.getState().getBillingAddress() || {};\n\n return {\n ...this._mapToAddressRequestBody(billingAddress, company, phone, customFields),\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 if (!nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\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 CallbackTriggerType.OFFER,\n ];\n\n const initializationTrigger = [CallbackTriggerType.INITIALIZE];\n const addressChangeTriggers = [\n CallbackTriggerType.INITIALIZE,\n CallbackTriggerType.SHIPPING_ADDRESS,\n ];\n const shippingOptionsChangeTriggers = [CallbackTriggerType.SHIPPING_OPTION];\n const offerChangeTriggers = [CallbackTriggerType.OFFER];\n\n return {\n availableTriggers,\n initializationTrigger,\n addressChangeTriggers,\n shippingOptionsChangeTriggers,\n offerChangeTriggers,\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 const { getCartOrThrow } = this._paymentIntegrationService.getState();\n\n if (this._isBuyNowFlow) {\n currencyCode = this._getCurrencyCodeOrThrow();\n } else {\n currencyCode = getCartOrThrow().currency.code;\n }\n\n const countryCode = this.getGooglePayInitializationData().storeCountry;\n\n if (this.isWebViewWithRestrictions()) {\n const totalPrice = this.getTotalPrice();\n\n return {\n ...(countryCode && { countryCode }),\n currencyCode,\n totalPrice,\n totalPriceStatus: TotalPriceStatusType.ESTIMATED,\n };\n }\n\n return {\n ...(countryCode && { countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.ESTIMATED,\n totalPrice: '0',\n };\n }\n\n isWebViewWithRestrictions(): boolean {\n if (this._isWebViewExperimentOn !== null) {\n return this._isWebViewExperimentOn && isWebView();\n }\n\n return isWebView();\n }\n\n setIsWebViewExperimentOn(isWebViewExperimentOn: boolean): void {\n this._isWebViewExperimentOn = isWebViewExperimentOn;\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, getStoreConfigOrThrow } =\n this._paymentIntegrationService.getState();\n const { decimalPlaces } = getCartOrThrow().currency;\n const isRoundingExperimentOn = isExperimentEnabled(\n getStoreConfigOrThrow().checkoutSettings.features,\n 'PI-5075.google_pay_round_total_price_to_max_2_decimal_places',\n );\n const maxDecimalPlaces = isRoundingExperimentOn\n ? Math.min(decimalPlaces, 2)\n : decimalPlaces;\n const totalPrice = round(getCheckoutOrThrow().outstandingBalance, maxDecimalPlaces).toFixed(\n maxDecimalPlaces,\n );\n\n return totalPrice;\n }\n\n async handleCoupons(\n offerData: IntermediatePaymentData['offerData'],\n ): Promise {\n const { redemptionCodes: newCouponsState = [] } = offerData;\n const { offers: appliedCoupons } = this.getAppliedCoupons() || {};\n let error;\n\n await newCouponsState.reduce(async (promise, code) => {\n await promise;\n\n const exists = (appliedCoupons || []).some(\n ({ redemptionCode }) => redemptionCode === code,\n );\n\n if (exists) {\n return;\n }\n\n const appliedCouponError = await this.applyCoupon(code);\n\n if (appliedCouponError) {\n error = appliedCouponError;\n }\n }, Promise.resolve());\n\n await (appliedCoupons || []).reduce(async (promise, coupon) => {\n await promise;\n\n const stillExists = newCouponsState.includes(coupon.redemptionCode);\n\n if (!stillExists) {\n await this._paymentIntegrationService.removeCoupon(coupon.redemptionCode);\n }\n }, Promise.resolve());\n\n return {\n newOfferInfo: this.getAppliedCoupons(),\n error,\n };\n }\n\n getAppliedCoupons(): GooglePayPaymentDataRequest['offerInfo'] {\n const state = this._paymentIntegrationService.getState();\n const { coupons } = state.getCheckout() || {};\n\n const offers = (coupons || []).map((coupon) => {\n const { displayName, code } = coupon;\n\n return {\n redemptionCode: code,\n description: displayName,\n };\n });\n\n return {\n offers,\n };\n }\n\n async applyCoupon(code: string): Promise {\n let error: GooglePayError | undefined;\n\n try {\n await this._paymentIntegrationService.applyCoupon(code);\n } catch (e) {\n if (e instanceof Error) {\n error = {\n reason: ErrorReasonType.OFFER_INVALID,\n message: e.message,\n intent: CallbackTriggerType.OFFER,\n };\n }\n\n return error;\n }\n }\n\n setShouldRequestShipping(isRequired: boolean): void {\n this._shouldRequestShipping = isRequired;\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, getStoreConfigOrThrow, getShippingAddress } =\n this._paymentIntegrationService.getState();\n const storeConfig = getStoreConfigOrThrow();\n const features = storeConfig.checkoutSettings.features;\n const checkWithExperiment = isExperimentEnabled(\n features,\n 'PI-4290.google_pay_require_shipping_address',\n );\n\n let shippingContextRequiresCheck: boolean;\n\n if (checkWithExperiment) {\n shippingContextRequiresCheck = this._shouldRequestShipping;\n } else {\n shippingContextRequiresCheck = getShippingAddress() === undefined;\n }\n\n return shippingContextRequiresCheck && itemsRequireShipping(getCartOrThrow(), storeConfig);\n }\n\n private _mapToAddressRequestBody(\n address: GooglePayFullBillingAddress,\n company: string,\n phone: string,\n customFields?: AddressRequestBody['customFields'],\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: 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({\n id,\n cost,\n description,\n additionalDescription,\n }: ShippingOption) {\n const formattedCost = this._currencyService?.toCustomerCurrency(cost);\n\n return {\n id,\n label: `${formattedCost || cost} ${description}`,\n description: additionalDescription,\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","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 GooglePayError,\n GooglePayInitializationData,\n GooglePayPaymentOptions,\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 this._googlePayPaymentProcessor.setIsWebViewExperimentOn(\n !!paymentMethod.initializationData?.isWebViewExperimentOn,\n );\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 if (this._googlePayPaymentProcessor.isWebViewWithRestrictions()) {\n return {};\n }\n\n return {\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({\n callbackTrigger,\n shippingAddress,\n shippingOptionData,\n offerData,\n }) => {\n const {\n availableTriggers,\n addressChangeTriggers,\n shippingOptionsChangeTriggers,\n offerChangeTriggers,\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 const { newOfferInfo = undefined, error: couponsError = undefined } =\n offerChangeTriggers.includes(callbackTrigger)\n ? await this._googlePayPaymentProcessor.handleCoupons(offerData)\n : {};\n\n // We can add another errors if needed 'couponsError || shippingError || anotherError'\n const error: GooglePayError | undefined = couponsError;\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 ...(newOfferInfo && {\n newOfferInfo,\n }),\n ...(error && {\n error,\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) => Promise {\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\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","import { FormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\n\nimport {\n AddressRequestBody,\n BillingAddressRequestBody,\n guard,\n NotInitializedError,\n NotInitializedErrorType,\n Omit,\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 HandleCouponsOut,\n IntermediatePaymentData,\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 | undefined {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n return;\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 setShouldRequestShipping(isRequired: boolean): void {\n return this._gateway.setShouldRequestShipping(isRequired);\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 async handleCoupons(\n offerData: IntermediatePaymentData['offerData'],\n ): Promise {\n return this._gateway.handleCoupons(offerData);\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 isWebViewWithRestrictions(): boolean {\n return this._gateway.isWebViewWithRestrictions();\n }\n\n setIsWebViewExperimentOn(isWebViewExperimentOn: boolean): void {\n return this._gateway.setIsWebViewExperimentOn(isWebViewExperimentOn);\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\n const isWebViewLogic = this._gateway.isWebViewWithRestrictions()\n ? {\n shippingOptionRequired: false,\n }\n : {\n callbackIntents: this._gateway.getCallbackIntents(),\n offerInfo: this._gateway.getAppliedCoupons(),\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 ...isWebViewLogic,\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","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 { PaymentMethod } from '@bigcommerce/checkout-sdk/payment-integration-api';\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\n/**\n * The PaymentIntent object.\n */\nexport interface PaymentIntent {\n /**\n * Unique identifier for the object.\n */\n id: string;\n\n /**\n * The client secret of the PaymentIntent. Used for client-side retrieval using a publishable key.\n */\n client_secret?: 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 payment_method_options?: StripePIPaymentMethodOptions;\n}\n\nexport interface StripePIPaymentMethodSavingOptions {\n setup_future_usage?: StripeInstrumentSetupFutureUsage;\n verification_method?: string;\n}\n\nexport interface StripePIPaymentMethodOptions {\n card?: StripePIPaymentMethodSavingOptions;\n us_bank_account?: StripePIPaymentMethodSavingOptions;\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 * 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 StripeCustomFont = CssFontSource | CustomFontSource;\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 StripeCheckoutSessionConfirmationError {\n code?: string;\n message: string;\n paymentFailed?: {\n declineCode?: string;\n };\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: StripeElementEvent, 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\nexport interface StripeCurrencyEvent extends StripeEvent {\n value: {\n currency: string;\n };\n}\n\nexport interface 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 =\n | StripeCurrencyEvent\n | StripeShippingEvent\n | StripeCustomerEvent\n | StripePaymentEvent\n | StripeLinkV2Event;\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
& { country: string };\n\nexport interface StripeAddressValues {\n name?: string;\n address?: AddressOptions;\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 allow_redisplay?: 'always' | 'limited' | 'unspecified';\n}\n\n/**\n * Parameters that will be passed on to the Stripe API to confirm the PaymentIntent.\n */\nexport interface StripeConfirmParams {\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?: StripeConfirmParams;\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 clientSecret?: string;\n}\n\nexport interface StripeCheckoutSessionConfirmPaymentData {\n redirect?: StripeStringConstants.ALWAYS | StripeStringConstants.IF_REQUIRED;\n returnUrl?: string;\n}\n\nexport interface FieldsOptions {\n billingDetails?: AutoOrNever | BillingDetailsProperties;\n phone?: string;\n}\n\nexport interface WalletOptions {\n applePay?: AutoOrNever;\n googlePay?: AutoOrNever;\n link?: AutoOrNever;\n}\n\nexport interface TermOptions {\n card?: AutoOrNever;\n}\n\nexport interface StripeLayoutOptions {\n type?: 'accordion' | 'tabs';\n linkInAccordion?: boolean;\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 | PaymentDefaultValues;\n validation?: validationElement;\n display?: { name: StripeDisplayName };\n terms?: TermOptions;\n layout?: StripeLayoutOptions;\n paymentMethodOrder?: string[];\n // Link v2 options\n lineItems?: LineItem[];\n allowedShippingCountries?: string[];\n shippingAddressRequired?: boolean;\n shippingRates?: StripeLinkV2ShippingRate[];\n billingAddressRequired?: boolean;\n emailRequired?: boolean;\n phoneNumberRequired?: boolean;\n paymentMethods?: {\n link: StripeStringConstants.AUTO;\n applePay: StripeStringConstants.NEVER;\n googlePay: StripeStringConstants.NEVER;\n amazonPay: StripeStringConstants.NEVER;\n paypal: StripeStringConstants.NEVER;\n klarna: StripeStringConstants.NEVER;\n };\n buttonHeight?: number;\n savePaymentMethod?: StripeSavePaymentMethod;\n}\n\ninterface validationElement {\n phone?: validationRequiredElement;\n}\n\ninterface validationRequiredElement {\n required?: string;\n}\n\ninterface PaymentDefaultValues {\n savePaymentMethod?: boolean;\n billingDetails?: BillingDetailsOptions;\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 StripeDisplayName {\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: StripeDisplayName;\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\nexport enum StripeCheckoutSessionStatusType {\n Open = 'open',\n Expired = 'expired',\n Complete = 'complete',\n}\n\nexport enum StripeCheckoutSessionPaymentStatus {\n Paid = 'paid',\n UnPaid = 'unpaid',\n NoPaymentRequired = 'no_payment_required',\n}\n\nexport interface StripeCheckoutSessionStatus {\n type: StripeCheckoutSessionStatusType;\n paymentStatus: StripeCheckoutSessionPaymentStatus;\n}\n\nexport interface StripeCheckoutSessionAmount {\n minorUnitsAmount: number;\n amount: string;\n}\n\nexport interface StripeCheckoutSessionTotal {\n appliedBalance: StripeCheckoutSessionAmount;\n balanceAppliedToNextInvoice: boolean;\n discount: StripeCheckoutSessionAmount;\n shippingRate: StripeCheckoutSessionAmount;\n subtotal: StripeCheckoutSessionAmount;\n taxExclusive: StripeCheckoutSessionAmount;\n taxInclusive: StripeCheckoutSessionAmount;\n total: StripeCheckoutSessionAmount;\n}\n\nexport interface StripeCheckoutSession {\n id: string;\n savedPaymentMethods?: StripeSavedPaymentMethod[];\n billingAddress: StripeAddressValues;\n businessName: string;\n canConfirm: boolean;\n currency: string;\n email: string;\n phoneNumber: string;\n shipping: unknown;\n shippingAddress: StripeAddressValues;\n shippingOptions: unknown;\n status: StripeCheckoutSessionStatus;\n tax: unknown;\n taxAmounts: unknown;\n total: StripeCheckoutSessionTotal;\n}\n\nexport interface StripeCheckoutInstance {\n loadActions(): Promise;\n createPaymentElement(options?: StripeElementsCreateOptions): StripeElement;\n getPaymentElement(): StripeElement | null;\n getCurrencySelectorElement(): StripeElement | null;\n createCurrencySelectorElement(): StripeElement;\n}\n\nexport enum StripeLoadActionsResultType {\n SUCCESS = 'success',\n ERROR = 'error',\n}\n\nexport interface StripeLoadActionsResult {\n type: StripeLoadActionsResultType;\n error?: { message: string };\n actions?: StripeCheckoutSessionActions;\n}\n\nexport interface StripeCheckoutSessionActionResult {\n type: StripeLoadActionsResultType;\n error?: StripeCheckoutSessionConfirmationError;\n session?: StripeCheckoutSession;\n}\n\nexport interface StripeCheckoutSessionActions {\n updateEmail(email: string): Promise;\n updateShippingAddress(\n shippingAddress: StripeAddressValues,\n ): Promise;\n updateBillingAddress(\n billingAddress: StripeAddressValues,\n ): Promise;\n getSession(): Promise;\n confirm(\n options: StripeCheckoutSessionConfirmPaymentData,\n ): Promise;\n}\n\nexport interface StripeSavedPaymentMethod {\n id: string;\n type: string;\n billingDetails: BillingDetailsOptions;\n card?: StripeCardDetails;\n usBankAccount?: StripeUsBankAccountDetails;\n}\n\nexport interface StripeCardDetails {\n brand: string;\n last4: string;\n expMonth: number;\n expYear: number;\n}\n\nexport interface StripeUsBankAccountDetails {\n accountHolderType: string;\n accountType: string;\n bankName: string;\n last4: string;\n}\n\n/**\n * All available options are here https://stripe.com/docs/stripe-js/appearance-api#supported-css-properties\n */\nexport interface StripeAppearanceOptions {\n variables?: Record;\n\n rules?: Record>;\n}\n\nexport type StripeAppearanceValues = string | string[] | number | undefined;\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?: StripeCustomFont[];\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 * A token that represents the Stripe customer session.\n * Stripe documentation: https://docs.stripe.com/api/checkout/sessions\n */\n customerSessionClientSecret?: 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?: StripeAppearanceOptions;\n\n mode?: string;\n amount?: number;\n currency?: string;\n paymentMethodTypes?: string[];\n}\n\nexport interface StripeInitCheckoutOptions {\n clientSecret: string;\n elementsOptions?: StripeCheckoutSessionElementOptions;\n adaptivePricing?: {\n allowed: boolean;\n };\n defaultValues?: StripeCheckoutSessionDefaultValues;\n wallets?: any;\n}\n\nexport interface StripeCheckoutSessionElementOptions {\n appearance?: StripeAppearanceOptions;\n loader?: StripeStringConstants;\n fonts?: StripeCustomFont[];\n savedPaymentMethod?: {\n enableRedisplay?: StripeStringConstants;\n enableSave?: StripeStringConstants;\n };\n}\n\nexport interface StripeCheckoutSessionDefaultValues {\n billingAddress?: StripeAddressValues;\n shippingAddress?: StripeAddressValues;\n email?: string;\n phoneNumber?: 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?: StripeAppearanceOptions;\n mode?: string;\n amount?: number;\n currency?: string;\n}\n\nexport interface StripeClient {\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 initCheckout(options: StripeInitCheckoutOptions): Promise;\n}\n\nexport interface StripeResult {\n paymentIntent?: PaymentIntent;\n error?: StripeError;\n}\n\nexport interface StripeHostWindow extends Window {\n bcStripeClient?: StripeClient;\n bcStripeElements?: StripeElements;\n bcStripeCheckout?: StripeCheckoutInstance;\n Stripe?(\n stripePublishableKey: string,\n options?: StripeConfigurationOptions,\n ): T;\n}\n\nexport enum StripePaymentMethodType {\n CreditCard = 'card',\n ACH = 'us_bank_account',\n Link = 'link',\n EPS = 'eps',\n GRABPAY = 'grabpay',\n BANCONTACT = 'bancontact',\n IDEAL = 'ideal',\n ALIPAY = 'alipay',\n KLARNA = 'klarna',\n OCS = 'optimized_checkout',\n CHECKOUT_SESSION = 'checkout_session',\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 StripeJsVersion {\n V3 = 'v3',\n ACACIA = 'acacia',\n BASIL = 'basil',\n CLOVER = 'clover',\n}\n\nexport enum StripeElementType {\n PAYMENT = 'payment',\n AUTHENTICATION = 'linkAuthentication',\n SHIPPING = 'address',\n EXPRESS_CHECKOUT = 'expressCheckout',\n}\n\nexport enum StripePaymentIntentStatus {\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 StripePaymentMethod extends PaymentMethod {\n initializationData: StripeInitializationData;\n}\n\nexport interface StripeInitializationData {\n stripePublishableKey: string;\n stripeConnectedAccount: string;\n shopperLanguage: string;\n customerSessionToken?: string;\n enableLink?: boolean;\n allowRedisplayForStoredInstruments?: boolean;\n captureMethod?: 'automatic' | 'manual';\n useNewStripeJsVersion?: boolean;\n checkoutSessionEnabled?: boolean;\n sendSecondPaymentRequestOnStripeError?: boolean;\n adaptivePricingEnabled?: boolean;\n hasSectionOnTopOfPaymentsList?: 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\nexport enum StripeElementEvent {\n CLICK = 'click',\n CHANGE = 'change',\n READY = 'ready',\n SHIPPING_ADDRESS_CHANGE = 'shippingaddresschange',\n SHIPPING_RATE_CHANGE = 'shippingratechange',\n CONFIRM = 'confirm',\n CANCEL = 'cancel',\n LOADER_START = 'loaderstart',\n}\n\nexport interface LineItem {\n name: string;\n amount: number;\n}\n\nexport interface StripeSavePaymentMethod {\n maxVisiblePaymentMethods?: number;\n}\n\nexport enum StripeInstrumentSetupFutureUsage {\n ON_SESSION = 'on_session',\n OFF_SESSION = 'off_session',\n}\n\nexport interface StripeLinkV2Event {\n value?: null;\n billingDetails?: {\n name?: string;\n email?: string;\n phone?: string;\n address?: {\n line1?: string;\n city?: string;\n country?: string;\n postal_code?: string;\n state?: string;\n };\n };\n shippingAddress?: {\n name?: string;\n address?: {\n line1?: string;\n line2?: string;\n city?: string;\n country?: string;\n postal_code?: string;\n state?: string;\n };\n };\n address?: {\n line1?: string;\n city?: string;\n country?: string;\n postal_code?: string;\n state?: string;\n };\n shippingRate?: StripeLinkV2ShippingRate;\n elementType: string;\n expressPaymentType: string;\n resolve(data: StripeLinkV2EventResolveData): void;\n reject(): void;\n}\n\nexport interface StripeLinkV2EventResolveData {\n lineItems?: LineItem[];\n allowedShippingCountries?: string[];\n shippingAddressRequired?: boolean;\n shippingRates?: StripeLinkV2ShippingRate[];\n billingAddressRequired?: boolean;\n emailRequired?: boolean;\n phoneNumberRequired?: boolean;\n}\n\nexport interface StripeLinkV2ShippingRate {\n id: string;\n amount: number;\n displayName: string;\n}\n\nexport interface StripeLinkV2Options {\n clientSecret?: string;\n mode?: string;\n currency?: string;\n captureMethod?: 'automatic' | 'manual';\n amount?: number;\n}\n\nexport interface StripeFormattedPaymentPayload {\n cart_id: string;\n confirm: boolean;\n method?: string;\n credit_card_token?: { token: string };\n tokenized_ach?: { token: string };\n vault_payment_instrument?: boolean;\n set_as_default_stored_instrument?: boolean;\n client_side_error?: boolean;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n StripeCheckoutInstance,\n StripeClient,\n StripeElements,\n StripeElementsOptions,\n StripeHostWindow,\n StripeInitCheckoutOptions,\n StripeInitializationData,\n StripeJsVersion,\n} from './stripe';\n\nexport default class StripeScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private stripeWindow: StripeHostWindow = window,\n ) {}\n\n async getStripeClient(\n initializationData: StripeInitializationData,\n locale?: string,\n stripeJsVersion?: string,\n betas?: string[],\n apiVersion?: string,\n ): Promise {\n if (this.stripeWindow.bcStripeClient) {\n return this.stripeWindow.bcStripeClient;\n }\n\n const stripe = await this.load(stripeJsVersion);\n const { stripePublishableKey, stripeConnectedAccount } = initializationData;\n const options = {\n ...(stripeConnectedAccount ? { stripeAccount: stripeConnectedAccount } : {}),\n ...(locale ? { locale } : {}),\n ...(betas ? { betas } : {}),\n ...(apiVersion ? { apiVersion } : {}),\n };\n\n const stripeClient = stripe(stripePublishableKey, options);\n\n Object.assign(this.stripeWindow, { bcStripeClient: stripeClient });\n\n return stripeClient;\n }\n\n async getElements(\n stripeClient: StripeClient,\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 async getStripeCheckout(\n stripeClient: StripeClient,\n options: StripeInitCheckoutOptions,\n ): Promise {\n let stripeCheckout = await this.getStoredStripeCheckout(options);\n\n if (!stripeCheckout) {\n stripeCheckout = await stripeClient.initCheckout(options);\n\n Object.assign(this.stripeWindow, { bcStripeCheckout: stripeCheckout });\n }\n\n return stripeCheckout;\n }\n\n private async load(stripeJsVersion?: string) {\n if (!this.stripeWindow.Stripe) {\n await this.scriptLoader.loadScript(this.getScriptUrl(stripeJsVersion));\n\n if (!this.stripeWindow.Stripe) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.stripeWindow.Stripe;\n }\n\n private getScriptUrl(stripeJsVersion?: string) {\n if (!stripeJsVersion || stripeJsVersion === StripeJsVersion.V3) {\n return 'https://js.stripe.com/v3/';\n }\n\n return `https://js.stripe.com/${stripeJsVersion}/stripe.js`;\n }\n\n private async getStoredStripeCheckout(\n options: StripeInitCheckoutOptions,\n ): Promise {\n const stripeCheckout = this.stripeWindow.bcStripeCheckout;\n\n if (!stripeCheckout) {\n return undefined;\n }\n\n try {\n const { actions, error } = await stripeCheckout.loadActions();\n\n if (error || !actions) {\n this.logErrorToConsole(error);\n\n return undefined;\n }\n\n const stripeCheckoutSession = await actions.getSession();\n const stripeSessionIdFromOptions = options.clientSecret.split('_secret_')[0];\n\n if (stripeCheckoutSession.id === stripeSessionIdFromOptions) {\n return stripeCheckout;\n }\n } catch (error) {\n this.logErrorToConsole(error);\n\n return undefined;\n }\n\n return undefined;\n }\n\n private logErrorToConsole(error?: unknown) {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n error\n ? console.error(error)\n : console.error('No stripe checkout actions available on loadActions().');\n }\n}\n","export const STRIPE_UPE_CLIENT_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\nexport const STRIPE_UPE_CLIENT_API_VERSION = '2020-03-02;alipay_beta=v1;link_beta=v1';\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';\nimport {\n STRIPE_UPE_CLIENT_API_VERSION,\n STRIPE_UPE_CLIENT_BETAS,\n StripeJsVersion,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\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 GooglePayStripeInitializationData,\n} from '../types';\n\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: StripeScriptLoader,\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 shouldTrigger3DS = some(error.body.errors, { code: 'three_d_secure_required' });\n\n if (shouldTrigger3DS) {\n const initialization = this.getGooglePayInitializationData();\n\n assertsIsGooglePayStripeInitializationData(initialization);\n\n this.stripeUPEClient = await this.loadStripeJs(initialization, methodId);\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 initializationData: GooglePayStripeInitializationData,\n methodId: string,\n ): Promise {\n if (this.stripeUPEClient) {\n return this.stripeUPEClient;\n }\n\n const locale = this.paymentIntegrationService.getState().getCartLocale();\n\n if (methodId === 'googlepaystripeocs' && !!initializationData.useNewStripeJsVersion) {\n return this.scriptLoader.getStripeClient(\n initializationData,\n locale,\n StripeJsVersion.CLOVER,\n );\n }\n\n return this.scriptLoader.getStripeClient(\n initializationData,\n locale,\n StripeJsVersion.V3,\n STRIPE_UPE_CLIENT_BETAS,\n STRIPE_UPE_CLIENT_API_VERSION,\n );\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 { 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';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\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';\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 StripeScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayStripeCustomerStrategy, [\n { id: 'googlepaystripe' },\n { id: 'googlepaystripeocs' },\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';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\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';\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 StripeScriptLoader(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","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 { GooglePayKey } from '../google-pay-payment-initialize-options';\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 private _methodId = GooglePayKey.BRAINTREE;\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 let paymentMethod = super.getPaymentMethod();\n\n if (!paymentMethod.clientToken) {\n const state = await this._service.loadPaymentMethod(this._methodId);\n\n paymentMethod = state.getPaymentMethodOrThrow(this._methodId);\n }\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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","export const LOADING_INDICATOR_STYLES = {\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\n};\n\n/**\n * PayPal SDK supported locales\n * https://developer.paypal.com/sdk/js/configuration/#link-locale\n */\nexport const PAYPAL_SDK_SUPPORTED_LOCALES = [\n 'ar_BH',\n 'ar_DZ',\n 'ar_EG',\n 'ar_JO',\n 'ar_KW',\n 'ar_MA',\n 'ar_OM',\n 'ar_QA',\n 'ar_SA',\n 'ar_TN',\n 'ar_YE',\n 'ar_AE',\n 'bg_BG',\n 'cs_CZ',\n 'da_DK',\n 'da_FO',\n 'da_GL',\n 'de_AT',\n 'de_CH',\n 'de_DE',\n 'de_LU',\n 'el_GR',\n 'en_AD',\n 'en_AE',\n 'en_AG',\n 'en_AI',\n 'en_AL',\n 'en_AM',\n 'en_AN',\n 'en_AO',\n 'en_AT',\n 'en_AU',\n 'en_AW',\n 'en_AZ',\n 'en_BB',\n 'en_BE',\n 'en_BH',\n 'en_BJ',\n 'en_BM',\n 'en_BN',\n 'en_BS',\n 'en_BT',\n 'en_BW',\n 'en_BY',\n 'en_BZ',\n 'en_C2',\n 'en_CA',\n 'en_CD',\n 'en_CG',\n 'en_CH',\n 'en_CI',\n 'en_CK',\n 'en_CL',\n 'en_CM',\n 'en_CN',\n 'en_CO',\n 'en_CR',\n 'en_CV',\n 'en_CY',\n 'en_CZ',\n 'en_DE',\n 'en_DJ',\n 'en_DK',\n 'en_DM',\n 'en_DO',\n 'en_DZ',\n 'en_EC',\n 'en_EE',\n 'en_EG',\n 'en_ER',\n 'en_ES',\n 'en_ET',\n 'en_FI',\n 'en_FJ',\n 'en_FK',\n 'en_FM',\n 'en_FO',\n 'en_FR',\n 'en_GA',\n 'en_GB',\n 'en_GD',\n 'en_GE',\n 'en_GF',\n 'en_GI',\n 'en_GL',\n 'en_GM',\n 'en_GN',\n 'en_GP',\n 'en_GR',\n 'en_GT',\n 'en_GW',\n 'en_GY',\n 'en_HK',\n 'en_HN',\n 'en_HR',\n 'en_HU',\n 'en_ID',\n 'en_IE',\n 'en_IL',\n 'en_IN',\n 'en_IS',\n 'en_IT',\n 'en_JM',\n 'en_JO',\n 'en_JP',\n 'en_KE',\n 'en_KG',\n 'en_KH',\n 'en_KI',\n 'en_KM',\n 'en_KN',\n 'en_KR',\n 'en_KW',\n 'en_KY',\n 'en_KZ',\n 'en_LA',\n 'en_LC',\n 'en_LI',\n 'en_LK',\n 'en_LS',\n 'en_LT',\n 'en_LU',\n 'en_LV',\n 'en_MA',\n 'en_MC',\n 'en_MD',\n 'en_ME',\n 'en_MG',\n 'en_MH',\n 'en_MK',\n 'en_ML',\n 'en_MN',\n 'en_MQ',\n 'en_MR',\n 'en_MS',\n 'en_MT',\n 'en_MU',\n 'en_MV',\n 'en_MW',\n 'en_MY',\n 'en_MZ',\n 'en_NA',\n 'en_NC',\n 'en_NE',\n 'en_NF',\n 'en_NG',\n 'en_NI',\n 'en_NL',\n 'en_NO',\n 'en_NP',\n 'en_NR',\n 'en_NU',\n 'en_NZ',\n 'en_OM',\n 'en_PA',\n 'en_PE',\n 'en_PF',\n 'en_PG',\n 'en_PH',\n 'en_PL',\n 'en_PM',\n 'en_PN',\n 'en_PT',\n 'en_PW',\n 'en_PY',\n 'en_QA',\n 'en_RE',\n 'en_RO',\n 'en_RS',\n 'en_RU',\n 'en_RW',\n 'en_SA',\n 'en_SB',\n 'en_SC',\n 'en_SE',\n 'en_SG',\n 'en_SH',\n 'en_SI',\n 'en_SJ',\n 'en_SK',\n 'en_SL',\n 'en_SM',\n 'en_SN',\n 'en_SO',\n 'en_SR',\n 'en_ST',\n 'en_SV',\n 'en_SZ',\n 'en_TC',\n 'en_TD',\n 'en_TG',\n 'en_TH',\n 'en_TJ',\n 'en_TM',\n 'en_TN',\n 'en_TO',\n 'en_TR',\n 'en_TT',\n 'en_TV',\n 'en_TW',\n 'en_TZ',\n 'en_UA',\n 'en_UG',\n 'en_US',\n 'en_UY',\n 'en_VA',\n 'en_VC',\n 'en_VE',\n 'en_VG',\n 'en_VN',\n 'en_VU',\n 'en_WF',\n 'en_WS',\n 'en_YE',\n 'en_YT',\n 'en_ZA',\n 'en_ZM',\n 'en_ZW',\n 'es_AD',\n 'es_AI',\n 'es_AO',\n 'es_AR',\n 'es_AW',\n 'es_BB',\n 'es_BJ',\n 'es_BM',\n 'es_BO',\n 'es_BS',\n 'es_BZ',\n 'es_CD',\n 'es_CG',\n 'es_CK',\n 'es_CL',\n 'es_CO',\n 'es_CR',\n 'es_CV',\n 'es_DJ',\n 'es_DM',\n 'es_DO',\n 'es_DZ',\n 'es_EC',\n 'es_EG',\n 'es_ER',\n 'es_ES',\n 'es_ET',\n 'es_FJ',\n 'es_FK',\n 'es_FO',\n 'es_GA',\n 'es_GD',\n 'es_GE',\n 'es_GI',\n 'es_GL',\n 'es_GM',\n 'es_GN',\n 'es_GT',\n 'es_GW',\n 'es_GY',\n 'es_HN',\n 'es_IE',\n 'es_JM',\n 'es_JO',\n 'es_KE',\n 'es_KG',\n 'es_KI',\n 'es_KM',\n 'es_KN',\n 'es_KW',\n 'es_KY',\n 'es_KZ',\n 'es_LC',\n 'es_LI',\n 'es_LS',\n 'es_LU',\n 'es_MA',\n 'es_MG',\n 'es_MH',\n 'es_ML',\n 'es_MR',\n 'es_MS',\n 'es_MU',\n 'es_MW',\n 'es_MX',\n 'es_MZ',\n 'es_NA',\n 'es_NC',\n 'es_NE',\n 'es_NF',\n 'es_NI',\n 'es_NR',\n 'es_NU',\n 'es_NZ',\n 'es_OM',\n 'es_PA',\n 'es_PE',\n 'es_PF',\n 'es_PG',\n 'es_PM',\n 'es_PN',\n 'es_PW',\n 'es_PY',\n 'es_QA',\n 'es_RS',\n 'es_RW',\n 'es_SA',\n 'es_SB',\n 'es_SC',\n 'es_SH',\n 'es_SJ',\n 'es_SL',\n 'es_SM',\n 'es_SN',\n 'es_SO',\n 'es_SR',\n 'es_ST',\n 'es_SV',\n 'es_SZ',\n 'es_TC',\n 'es_TD',\n 'es_TG',\n 'es_TJ',\n 'es_TM',\n 'es_TN',\n 'es_TT',\n 'es_TV',\n 'es_UA',\n 'es_UG',\n 'es_US',\n 'es_UY',\n 'es_VA',\n 'es_VC',\n 'es_VE',\n 'es_VG',\n 'es_VU',\n 'es_WF',\n 'es_YE',\n 'es_ZM',\n 'et_EE',\n 'fi_FI',\n 'fr_AD',\n 'fr_AE',\n 'fr_AI',\n 'fr_AM',\n 'fr_AO',\n 'fr_AW',\n 'fr_AZ',\n 'fr_BB',\n 'fr_BE',\n 'fr_BF',\n 'fr_BI',\n 'fr_BJ',\n 'fr_BM',\n 'fr_BS',\n 'fr_BZ',\n 'fr_CA',\n 'fr_CD',\n 'fr_CG',\n 'fr_CH',\n 'fr_CI',\n 'fr_CK',\n 'fr_CM',\n 'fr_CV',\n 'fr_DJ',\n 'fr_DM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h_NE',\n 'zh_NF',\n 'zh_NI',\n 'zh_NR',\n 'zh_NU',\n 'zh_NZ',\n 'zh_OM',\n 'zh_PA',\n 'zh_PE',\n 'zh_PF',\n 'zh_PG',\n 'zh_PM',\n 'zh_PN',\n 'zh_PW',\n 'zh_QA',\n 'zh_RS',\n 'zh_RW',\n 'zh_SA',\n 'zh_SB',\n 'zh_SC',\n 'zh_SH',\n 'zh_SJ',\n 'zh_SL',\n 'zh_SM',\n 'zh_SN',\n 'zh_SO',\n 'zh_SR',\n 'zh_ST',\n 'zh_SV',\n 'zh_SZ',\n 'zh_TC',\n 'zh_TD',\n 'zh_TG',\n 'zh_TJ',\n 'zh_TM',\n 'zh_TN',\n 'zh_TT',\n 'zh_TV',\n 'zh_UA',\n 'zh_UG',\n 'zh_US',\n 'zh_UY',\n 'zh_VA',\n 'zh_VC',\n 'zh_VE',\n 'zh_VG',\n 'zh_VU',\n 'zh_WF',\n 'zh_YE',\n 'zh_ZA',\n 'zh_ZM',\n];\n","import { PAYPAL_SDK_SUPPORTED_LOCALES } from '../paypal-commerce-constants';\n\n/**\n * Transforms store language to PayPal SDK locale format.\n * PayPal SDK expects locale in format 'en_US' (underscore separator).\n * Returns undefined if the locale is not supported by PayPal SDK.\n * Examples: 'fr-CA' -> 'fr_CA', 'fr' -> 'fr_FR'\n */\nexport default function transformLocaleToPayPalFormat(\n storeLanguage: string | undefined,\n): string | undefined {\n if (!storeLanguage) {\n return undefined;\n }\n\n let locale: string;\n\n if (storeLanguage.includes('-')) {\n const [language, region] = storeLanguage.split('-');\n\n locale = `${language}_${region.toUpperCase()}`;\n } else {\n locale = `${storeLanguage}_${storeLanguage.toUpperCase()}`;\n }\n\n return PAYPAL_SDK_SUPPORTED_LOCALES.includes(locale) ? locale : undefined;\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';\nimport { transformLocaleToPayPalFormat } from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport {\n PayPalCommerceHostWindow,\n PayPalCommerceInitializationData,\n PayPalFastlaneSdk,\n PayPalGooglePaySdk,\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 storeLanguage: string | undefined,\n ): Promise {\n if (!this.window.paypalFastlaneSdk) {\n const config = this.getPayPalFastlaneSdkConfiguration(\n paymentMethod,\n currencyCode,\n sessionId,\n storeLanguage,\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 getPayPalGooglePaySdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n if (!this.window.paypalGooglePay || forceLoad) {\n const paypalSdkScriptConfig = this.getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n storeLanguage,\n initializesOnCheckoutPage,\n );\n\n await this.loadPayPalSdk(paypalSdkScriptConfig);\n }\n\n if (!this.window.paypalGooglePay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypalGooglePay;\n }\n\n async getPayPalApmsSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n ) {\n if (!this.window.paypalApms) {\n const config = this.getPayPalApmSdkConfiguration(\n paymentMethod,\n currencyCode,\n storeLanguage,\n );\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 storeLanguage: string | undefined,\n ): Promise {\n if (!this.window.paypalMessages) {\n const paypalSdkMessagesConfig = this.getPayPalSdkMessagesConfiguration(\n paymentMethod,\n currencyCode,\n storeLanguage,\n );\n\n await this.loadPayPalSdk(paypalSdkMessagesConfig);\n }\n\n if (!this.window.paypalMessages) {\n throw new PaymentMethodClientUnavailableError();\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 storeLanguage: string | undefined,\n ): PayPalSdkConfig {\n const { clientToken, initializationData } = paymentMethod;\n\n if (!initializationData || !initializationData.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { intent, clientId, merchantId, attributionId } = initializationData;\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit: true,\n components: [\n 'fastlane',\n 'buttons',\n 'payment-fields',\n 'hosted-fields',\n 'three-domain-secure',\n ],\n currency: currencyCode,\n intent,\n ...(locale && { locale }),\n },\n attributes: {\n 'data-client-metadata-id': sessionId.replace(/-/g, ''),\n 'data-namespace': 'paypalFastlaneSdk',\n 'data-partner-attribution-id': attributionId,\n 'data-sdk-client-token': clientToken,\n },\n };\n }\n\n private getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage = true,\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 buyerCountry,\n attributionId,\n isHostedCheckoutEnabled,\n isDeveloperModeApplicable,\n } = initializationData;\n\n const commit = isHostedCheckoutEnabled || initializesOnCheckoutPage;\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit,\n components: ['googlepay'],\n currency: currencyCode,\n intent,\n ...(isDeveloperModeApplicable && { 'buyer-country': buyerCountry }),\n ...(locale && { locale }),\n },\n attributes: {\n 'data-partner-attribution-id': attributionId,\n 'data-client-token': clientToken,\n 'data-namespace': 'paypalGooglePay',\n },\n };\n }\n\n private getPayPalApmSdkConfiguration(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\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 const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 storeLanguage: string | undefined,\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 const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 {\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 {\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\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 { GooglePayConfig } from './types';\n\nexport default class GooglePayPaypalCommerceGateway extends GooglePayGateway {\n private googlepayConfig?: GooglePayConfig;\n private service: PaymentIntegrationService;\n\n constructor(service: PaymentIntegrationService, private payPalCommerceSdk: PayPalCommerceSdk) {\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 state = this.service.getState();\n const currency = state.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 const googlePaySdk = await this.payPalCommerceSdk.getPayPalGooglePaySdk(\n paymentMethod,\n currency,\n state.getLocale(),\n );\n\n this.googlepayConfig = await googlePaySdk.Googlepay().config();\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 { 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';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\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';\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 PayPalCommerceSdk(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayPayPalCommerceCustomerStrategy, [\n { id: 'googlepaypaypalcommerce' },\n]);\n","import {\n BigCommercePaymentsInitializationData,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 GooglePayConfig,\n GooglePayPayPalCommerceGatewayParameters,\n GooglePayPayPalCommerceInitializationData,\n GooglePaySetExternalCheckoutData,\n} from '../types';\n\nexport default class GooglePayBigCommercePaymentsGateway extends GooglePayGateway {\n private googlepayConfig?: GooglePayConfig;\n private service: PaymentIntegrationService;\n\n constructor(service: PaymentIntegrationService, private payPalSdkHelper: PayPalSdkHelper) {\n super('googlepay_bigcommerce_payments', 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 const googlePaySdk = await this.payPalSdkHelper.getPayPalGooglePaySdk(\n paymentMethod as PaymentMethod,\n currency,\n );\n\n this.googlepayConfig = await googlePaySdk.Googlepay().config();\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 { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PayPalSdkHelper } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\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 GooglePayBigCommercePaymentsGateway from './google-pay-bigcommerce-payments-gateway';\n\nconst createGooglePayBigCommercePaymentsCustomerStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayBigCommercePaymentsGateway(\n paymentIntegrationService,\n new PayPalSdkHelper(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayBigCommercePaymentsCustomerStrategy, [\n { id: 'googlepay_bigcommerce_payments' },\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 {\n BuyNowCartRequestBody,\n CardInstrument,\n CustomerAddress,\n HostedInstrument,\n ShippingOption,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n/**\n *\n * PayPal 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 BuyNow\n *\n */\nexport interface PayPalBuyNowInitializeOptions {\n getBuyNowCartRequestBody(): BuyNowCartRequestBody;\n}\n\n/**\n *\n * PayPal Initialization Data\n *\n */\nexport interface PayPalInitializationData {\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?: PayPalIntent;\n isAcceleratedCheckoutEnabled?: boolean; // PayPal Fastlane related\n isFastlaneShippingOptionAutoSelectEnabled?: boolean; // PayPal Fastlane related\n isFastlaneStylingEnabled?: boolean;\n isHostedCheckoutEnabled?: boolean;\n isPayPalAnalyticsV2Enabled?: boolean; // PayPal Fastlane related\n isPayPalCreditAvailable?: boolean;\n isPayPalCommerceAnalyticsV2Enabled?: boolean; // PayPal Fastlane related\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 threeDSVerificationMethod?: string;\n isAppSwitchEnabled?: boolean;\n}\n\n/**\n *\n * PayPalHostWindow contains different\n * PayPal Sdk instances for different purposes\n *\n */\nexport interface PayPalHostWindow extends Window {\n paypal?: PayPalSDK;\n paypalFastlane?: PayPalFastlane;\n paypalFastlaneSdk?: PayPalFastlaneSdk;\n paypalMessages?: PayPalMessagesSdk;\n paypalApms?: PayPalApmSdk;\n paypalGooglePay?: PayPalGooglePaySdk;\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?: PayPalIntent;\n components?: PayPalSdkComponents;\n locale?: string;\n };\n attributes: {\n 'data-client-metadata-id'?: string;\n 'data-partner-attribution-id'?: string;\n 'data-sdk-client-token'?: string;\n 'data-namespace'?: string;\n 'data-client-token'?: string;\n };\n}\n\nexport enum PayPalIntent {\n AUTHORIZE = 'authorize',\n CAPTURE = 'capture',\n}\n\nexport type PayPalSdkComponents = Array<\n | 'fastlane'\n | 'three-domain-secure'\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 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\n/**\n *\n * PayPal Sdk instances\n *\n */\nexport interface PayPalSDK {\n CardFields: (data: PaypalCardFieldsConfig) => 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: PayPalHostedFieldsRenderOptions): Promise;\n };\n Legal: PayPalLegal & LegalFunding;\n Buttons(options: PayPalButtonsOptions): PayPalButtons;\n PaymentFields(options: PayPalPaymentFieldsOptions): PayPalPaymentFields;\n Messages(options: PayPalMessagesOptions): PayPalMessages;\n}\n\nexport interface PaypalCardFieldsConfig {\n inputEvents: {\n onChange(data: PayPalCardFieldsState): void;\n onFocus(data: PayPalCardFieldsState): void;\n onBlur(data: PayPalCardFieldsState): void;\n onInputSubmitRequest(data: PayPalCardFieldsState): void;\n };\n createVaultSetupToken?: (data: PayPalCardFieldsState) => void;\n createOrder?: () => Promise;\n style: PayPalHostedFieldsRenderOptions['styles'];\n onApprove(data: PayPalCardFieldsOnApproveData): void;\n onError(): void;\n}\n\ninterface PayPalFieldsInitializationData {\n placeholder?: string;\n}\n\nexport interface PayPalCardFields {\n isEligible(): boolean;\n CVVField(config?: PayPalFieldsInitializationData): PayPalFields;\n ExpiryField(config?: PayPalFieldsInitializationData): PayPalFields;\n NameField(config?: PayPalFieldsInitializationData): PayPalFields;\n NumberField(config?: PayPalFieldsInitializationData): PayPalFields;\n submit(config?: PayPalCardFieldsSubmitConfig): Promise;\n getState(): Promise;\n}\n\nexport interface PayPalCardFieldsSubmitConfig {\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 PayPalCardFieldsOnApproveData {\n vaultSetupToken?: string;\n orderID: string;\n liabilityShift?: LiabilityShiftEnum;\n}\n\ninterface PayPalCardFieldsFieldData {\n isFocused: boolean;\n isEmpty: boolean;\n isValid: boolean;\n isPotentiallyValid: boolean;\n}\n\ntype PayPalCardFieldsCard = PayPalHostedFieldsCard;\n\nexport interface PayPalCardFieldsState {\n cards: PayPalCardFieldsCard[];\n emittedBy: string;\n isFormValid: boolean;\n errors: string[];\n fields: {\n cardCvvField: PayPalCardFieldsFieldData;\n cardNumberField: PayPalCardFieldsFieldData;\n cardNameField?: PayPalCardFieldsFieldData;\n cardExpiryField: PayPalCardFieldsFieldData;\n };\n}\n\nexport interface PayPalFields {\n render(container: HTMLElement | string): Promise;\n clear(): void;\n removeClass(className: string): Promise;\n close(): Promise;\n}\n\nexport interface PayPalFastlaneSdk {\n ThreeDomainSecureClient: {\n isEligible(params: threeDSecureParameters): Promise;\n show(): Promise;\n };\n Fastlane(options?: PayPalFastlaneOptions): Promise;\n}\n\ninterface ThreeDomainSecureClientShowResponse {\n liabilityShift: LiabilityShiftEnum;\n authenticationState: TDSecureAuthenticationState;\n nonce: string; // Enriched nonce or the original nonce\n}\n\nexport enum TDSecureVerificationMethod {\n Always = 'SCA_ALWAYS',\n}\n\nexport enum TDSecureAuthenticationState {\n Succeeded = 'succeeded',\n Cancelled = 'cancelled',\n Errored = 'errored',\n}\n\nexport enum LiabilityShiftEnum {\n Possible = 'POSSIBLE',\n No = 'NO',\n Unknown = 'UNKNOWN',\n Yes = 'YES',\n}\n\nexport interface threeDSecureParameters {\n amount: string;\n currency: string;\n nonce: string;\n threeDSRequested: boolean;\n transactionContext: {\n experience_context: {\n brand_name?: string;\n locale: string;\n return_url: string;\n cancel_url: string;\n };\n };\n}\n\nexport interface PayPalMessagesSdk {\n Messages(options: MessagingOptions): MessagingRender;\n}\n\nexport interface PayPalApmSdk {\n Buttons(options: PayPalButtonsOptions): PayPalButtons;\n PaymentFields(options: PayPalPaymentFieldsOptions): PayPalPaymentFields;\n}\n\nexport interface PayPalGooglePaySdk {\n Googlepay(): GooglePay;\n}\n\n/**\n *\n * PayPal Payments Hosted Fields\n *\n */\nexport interface PayPalHostedFieldsRenderOptions {\n fields?: {\n number?: PayPalHostedFieldOption;\n cvv?: PayPalHostedFieldOption;\n expirationDate?: PayPalHostedFieldOption;\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 PayPalHostedFieldOption {\n selector: string;\n placeholder?: string;\n}\n\nexport interface PayPalHostedFields {\n submit(options?: PayPalHostedFieldsSubmitOptions): Promise;\n getState(): PayPalHostedFieldsState;\n on(eventName: string, callback: (event: PayPalHostedFieldsState) => void): void;\n}\n\nexport interface PayPalHostedFieldsSubmitOptions {\n contingencies?: Array<'3D_SECURE'>;\n cardholderName?: string;\n}\n\nexport interface PayPalHostedFieldsApprove {\n orderId: string;\n liabilityShift?: 'POSSIBLE' | 'NO' | 'UNKNOWN';\n}\n\nexport interface PayPalHostedFieldsState {\n cards: PayPalHostedFieldsCard[];\n emittedBy: string;\n fields: {\n number?: PayPalHostedFieldsFieldData;\n expirationDate?: PayPalHostedFieldsFieldData;\n expirationMonth?: PayPalHostedFieldsFieldData;\n expirationYear?: PayPalHostedFieldsFieldData;\n cvv?: PayPalHostedFieldsFieldData;\n postalCode?: PayPalHostedFieldsFieldData;\n };\n}\n\nexport interface PayPalHostedFieldsCard {\n type: string;\n niceType: string;\n code: {\n name: string;\n size: number;\n };\n}\n\nexport interface PayPalHostedFieldsFieldData {\n container: HTMLElement;\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\n/**\n *\n * PayPal Buttons\n *\n */\nexport interface PayPalButtons {\n render(id: string): void;\n close(): void;\n isEligible(): boolean;\n hasReturned?(): boolean;\n resume?(): void;\n}\n\nexport interface PayPalButtonsOptions {\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 phone?: {\n phone_number: {\n national_number: string;\n };\n };\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\nexport interface PayPalButtonOptions {\n fundingSource: string;\n style?: PayPalButtonStyleOptions;\n isAppSwitchEnabled?: boolean;\n isHostedCheckoutEnabled?: boolean;\n onClick?: () => void;\n onCancel?: () => void;\n onPaymentComplete?: () => void;\n onError?(error?: Error | unknown): void;\n}\n\n/**\n *\n * PayPal Messages\n */\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface PayPalMessages {\n render(id: string): void;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface PayPalMessagesOptions {\n amount: number;\n placement: string;\n style?: PayPalMessagesStyleOptions;\n fundingSource?: string;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface PayPalMessagesStyleOptions {\n layout?: string;\n}\n\n/**\n *\n * Google Pay related types\n *\n */\n\ninterface GooglePay {\n config: () => Promise;\n confirmOrder: (confirmOrderConfig: ConfirmOrderConfig) => Promise<{ status: string }>;\n initiatePayerAction: (payerActionConfig: PayerActionConfig) => Promise;\n}\n\ninterface ConfirmOrderConfig {\n orderId: string;\n paymentMethodData: ConfirmOrderData;\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\ninterface PayerActionConfig {\n orderId: 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\n/**\n *\n * PayPal Payment fields\n *\n */\nexport interface PayPalPaymentFields {\n render(id: string): void;\n}\n\nexport interface PayPalPaymentFieldsOptions {\n style?: PayPalFieldsStyleOptions;\n fundingSource: string;\n fields: {\n name?: {\n value?: string;\n };\n email?: {\n value?: string;\n };\n };\n}\n\nexport interface PayPalFieldsStyleOptions {\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 = 'canceled',\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\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 methodId?: string;\n orderId?: number;\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 fastlaneToken?: string;\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 { 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 FundingType,\n PayPalFastlaneSdk,\n PayPalGooglePaySdk,\n PayPalHostWindow,\n PayPalInitializationData,\n PayPalMessagesSdk,\n PayPalSDK,\n PayPalSdkComponents,\n PayPalSdkConfig,\n} from './paypal-types';\nimport { transformLocaleToPayPalFormat } from './utils';\n\nexport default class PayPalSdkScriptLoader {\n private window: PayPalHostWindow;\n\n constructor(private scriptLoader: ScriptLoader) {\n this.window = window;\n }\n\n async getPayPalSDK(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n if (!this.window.paypal || forceLoad) {\n const paypalSdkScriptConfig = this.getPayPalSdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n storeLanguage,\n initializesOnCheckoutPage,\n );\n\n await this.loadPayPalSdk(paypalSdkScriptConfig);\n\n if (!this.window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.window.paypal;\n }\n\n async getPayPalFastlaneSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n sessionId: string,\n storeLanguage: string | undefined,\n ): Promise {\n if (!this.window.paypalFastlaneSdk) {\n const config = this.getPayPalFastlaneSdkConfiguration(\n paymentMethod,\n currencyCode,\n sessionId,\n storeLanguage,\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 getPayPalGooglePaySdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n if (!this.window.paypalGooglePay || forceLoad) {\n const paypalSdkScriptConfig = this.getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n storeLanguage,\n initializesOnCheckoutPage,\n );\n\n await this.loadPayPalSdk(paypalSdkScriptConfig);\n }\n\n if (!this.window.paypalGooglePay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypalGooglePay;\n }\n\n async getPayPalApmsSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n ) {\n if (!this.window.paypalApms) {\n const config = this.getPayPalApmSdkConfiguration(\n paymentMethod,\n currencyCode,\n storeLanguage,\n );\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 storeLanguage: string | undefined,\n ): Promise {\n if (!this.window.paypalMessages) {\n const paypalSdkMessagesConfig = this.getPayPalSdkMessagesConfiguration(\n paymentMethod,\n currencyCode,\n storeLanguage,\n );\n\n await this.loadPayPalSdk(paypalSdkMessagesConfig);\n }\n\n if (!this.window.paypalMessages) {\n throw new PaymentMethodClientUnavailableError();\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 getPayPalSdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage = true,\n ): PayPalSdkConfig {\n const { id, 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 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 =\n id === 'paypalcommercecreditcards' || id === 'bigcommerce_payments_creditcards';\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 enableVenmoFunding = isVenmoEnabled ? ['venmo'] : [];\n const disableVenmoFunding = !isVenmoEnabled ? ['venmo'] : [];\n const disableAPMsFunding = availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n );\n const googlePayComponent: PayPalSdkComponents = isGooglePayEnabled ? ['googlepay'] : [];\n const cardFieldsComponent: PayPalSdkComponents = 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 ...enabledAlternativePaymentMethods,\n ];\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\n },\n attributes: {\n 'data-partner-attribution-id': attributionId,\n 'data-client-token': clientToken,\n },\n };\n }\n\n private getPayPalFastlaneSdkConfiguration(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n sessionId: string,\n storeLanguage: string | undefined,\n ): PayPalSdkConfig {\n const { clientToken, initializationData } = paymentMethod;\n\n if (!initializationData || !initializationData.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { intent, clientId, merchantId, attributionId } = initializationData;\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit: true,\n components: [\n 'fastlane',\n 'buttons',\n 'payment-fields',\n 'hosted-fields',\n 'three-domain-secure',\n ],\n currency: currencyCode,\n ...(locale && { locale }),\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-sdk-client-token': clientToken,\n },\n };\n }\n\n private getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage = true,\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 buyerCountry,\n attributionId,\n isHostedCheckoutEnabled,\n isDeveloperModeApplicable,\n } = initializationData;\n\n const commit = isHostedCheckoutEnabled || initializesOnCheckoutPage;\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit,\n components: ['googlepay'],\n currency: currencyCode,\n intent,\n ...(isDeveloperModeApplicable && { 'buyer-country': buyerCountry }),\n ...(locale && { locale }),\n },\n attributes: {\n 'data-partner-attribution-id': attributionId,\n 'data-client-token': clientToken,\n 'data-namespace': 'paypalGooglePay',\n },\n };\n }\n\n private getPayPalApmSdkConfiguration(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\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 const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 storeLanguage: string | undefined,\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 const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport PayPalSdkScriptLoader from './paypal-sdk-script-loader';\n\nexport default function createPayPalSdkScriptLoader(): PayPalSdkScriptLoader {\n return new PayPalSdkScriptLoader(getScriptLoader());\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 PayPalRequestSender from './paypal-request-sender';\nimport PayPalSdkScriptLoader from './paypal-sdk-script-loader';\nimport {\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n PayPalCreateOrderCardFieldsResponse,\n PayPalCreateOrderRequestBody,\n PayPalInitializationData,\n PayPalOrderDetails,\n PayPalOrderStatus,\n PayPalSDK,\n StyleButtonColor,\n StyleButtonLabel,\n StyleButtonShape,\n} from './paypal-types';\n\nexport default class PayPalIntegrationService {\n private paypalSdk?: PayPalSDK;\n\n constructor(\n private formPoster: FormPoster,\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalRequestSender: PayPalRequestSender,\n private paypalSdkLoader: PayPalSdkScriptLoader,\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 = state.getPaymentMethodOrThrow(methodId);\n const storeLanguage = state.getLocale();\n\n this.paypalSdk = await this.paypalSdkLoader.getPayPalSDK(\n paymentMethod,\n currencyCode,\n storeLanguage,\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.paypalRequestSender.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.paypalRequestSender.createOrder(providerId, {\n cartId,\n ...requestBody,\n });\n\n return { orderId, ...(setupToken ? { setupToken } : {}) };\n }\n\n async updateOrder(providerId: string, methodId?: string, orderId?: number): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const consignment = state.getConsignmentsOrThrow()[0];\n\n try {\n await this.paypalRequestSender.updateOrder(providerId, {\n availableShippingOptions: consignment.availableShippingOptions,\n cartId: cart.id,\n selectedShippingOption: consignment.selectedShippingOption,\n ...(methodId ? { methodId } : {}),\n ...(orderId ? { orderId } : {}),\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.paypalRequestSender.getOrderStatus(methodId, options);\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((option) => {\n if (consignment.selectedShippingOption) {\n const shippingOptionId = consignment.selectedShippingOption.id;\n\n return option.id === shippingOptionId;\n }\n\n return false;\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: address?.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 phone: payer.phone?.phone_number?.national_number,\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","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-types';\n\nexport default class PayPalRequestSender {\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 methodId: string,\n requestBody: PayPalUpdateOrderRequestBody,\n ): Promise {\n const url = `/api/storefront/initialization/${methodId}`;\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: string,\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 { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalSdkScriptLoader from './create-paypal-sdk-script-loader';\nimport PaypalIntegrationService from './paypal-integration-service';\nimport PaypalRequestSender from './paypal-request-sender';\n\nconst createPayPalIntegrationService = (paymentIntegrationService: PaymentIntegrationService) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new PaypalIntegrationService(\n createFormPoster(),\n paymentIntegrationService,\n new PaypalRequestSender(createRequestSender({ host: getHost() })),\n createPayPalSdkScriptLoader(),\n );\n};\n\nexport default createPayPalIntegrationService;\n","import {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalIntegrationService from './paypal-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalButtonOptions,\n PayPalButtons,\n PayPalBuyNowInitializeOptions,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from './paypal-types';\n\nclass PaypalButtonCreationService {\n private onError?: PayPalButtonOptions['onError'];\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\n ) {}\n\n createPayPalButton(\n providerId: string,\n methodId: string,\n buttonOptions: PayPalButtonOptions,\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): PayPalButtons {\n const {\n style,\n fundingSource,\n isAppSwitchEnabled,\n isHostedCheckoutEnabled,\n onClick,\n onCancel,\n onPaymentComplete,\n onError,\n } = buttonOptions;\n\n this.onError = onError;\n\n const paypalSdk = this.paypalIntegrationService.getPayPalSdkOrThrow();\n const isAvailableFundingSource = Object.values(paypalSdk.FUNDING).includes(fundingSource);\n\n if (!isAvailableFundingSource) {\n throw new InvalidArgumentError(\n `Unable to initialize PayPal button because \"fundingSource\" argument is not valid funding source.`,\n );\n }\n\n const hostedCheckoutCallbacks = {\n ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data, providerId),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data, providerId),\n }),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(\n data,\n actions,\n methodId,\n providerId,\n onPaymentComplete,\n ),\n };\n\n return paypalSdk.Buttons({\n fundingSource,\n style: this.paypalIntegrationService.getValidButtonStyle(style),\n ...(isAppSwitchEnabled && {\n appSwitchWhenAvailable: true,\n }),\n createOrder: async () => {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n\n return this.paypalIntegrationService.createOrder(providerId);\n },\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalIntegrationService.tokenizePayment(methodId, orderID),\n ...(onClick ? { onClick } : {}),\n ...(onCancel ? { onCancel } : {}),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n });\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n providerId: 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.paypalIntegrationService.getBillingAddressFromOrderDetails(orderDetails);\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalIntegrationService.getShippingAddressFromOrderDetails(orderDetails);\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalIntegrationService.updateOrder(providerId);\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalIntegrationService.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 providerId: string,\n ): Promise {\n const address = this.paypalIntegrationService.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.paypalIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalIntegrationService.updateOrder(providerId);\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n providerId: string,\n ): Promise {\n const shippingOption = this.paypalIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalIntegrationService.updateOrder(providerId);\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\nexport default PaypalButtonCreationService;\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';\nimport {\n PaypalButtonCreationService,\n PayPalButtonOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceCustomerInitializeOptions, {\n WithPayPalCommerceCustomerInitializeOptions,\n} from './paypal-commerce-customer-initialize-options';\n\nexport default class PayPalCommerceCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\n private paypalButtonCreationService: PaypalButtonCreationService,\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 const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethod(methodId);\n\n if (!paymentMethod) {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n }\n\n const paypalSdk = await this.paypalIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n console.error(\n '[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\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, onError } = paypalcommerce;\n\n const paypalSdk = this.paypalIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, paymentButtonStyles, isAppSwitchEnabled } =\n paymentMethod.initializationData || {};\n const { checkoutTopButtonStyles } = paymentButtonStyles || {};\n\n const buttonOptions: PayPalButtonOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n isAppSwitchEnabled,\n isHostedCheckoutEnabled,\n style: {\n ...checkoutTopButtonStyles,\n height: DefaultCheckoutButtonHeight,\n },\n ...(onClick && { onClick: () => onClick() }),\n ...(isHostedCheckoutEnabled && onComplete && { onPaymentComplete: () => onComplete() }),\n onError,\n };\n\n const paypalButton = this.paypalButtonCreationService.createPayPalButton(\n 'paypalcommerce',\n methodId,\n buttonOptions,\n );\n\n if (paypalButton.isEligible()) {\n if (paypalButton.hasReturned?.() && isAppSwitchEnabled) {\n paypalButton.resume?.();\n } else {\n paypalButton.render(`#${container}`);\n }\n } else {\n this.paypalIntegrationService.removeElement(container);\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalIntegrationService,\n PaypalButtonCreationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceCustomerStrategy from './paypal-commerce-customer-strategy';\n\nconst createPayPalCommerceCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceCustomerStrategy\n> = (paymentIntegrationService) => {\n const paypalIntegrationService = createPayPalIntegrationService(paymentIntegrationService);\n const paypalButtonCreationService = new PaypalButtonCreationService(\n paymentIntegrationService,\n paypalIntegrationService,\n );\n\n return new PayPalCommerceCustomerStrategy(\n paymentIntegrationService,\n paypalIntegrationService,\n paypalButtonCreationService,\n );\n};\n\nexport default toResolvableModule(createPayPalCommerceCustomerStrategy, [{ id: 'paypalcommerce' }]);\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 locale?: string;\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}\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 paypalBNPLConfiguration?: PayPalBNPLConfigurationItem[];\n isAppSwitchEnabled?: boolean;\n}\n\nexport interface PayPalBNPLConfigurationItem {\n id: string;\n name: string;\n status: boolean;\n styles: 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 hasReturned?(): boolean;\n resume?(): void;\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 phone?: {\n phone_number: {\n national_number: string;\n };\n };\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 IDEAL = 'ideal',\n}\n\nexport interface PayPalOrderData {\n orderId: string;\n setupToken?: string;\n approveUrl: string;\n fastlaneToken?: 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 fastlaneToken?: string;\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 state.getLocale(),\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: address?.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 phone: payer.phone?.phone_number?.national_number,\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","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';\nimport { transformLocaleToPayPalFormat } from '@bigcommerce/checkout-sdk/paypal-utils';\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 storeLanguage: string | undefined,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n const paypalSdkScriptConfig = this.getPayPalSdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n storeLanguage,\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 storeLanguage: string | undefined,\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 enableVenmoFunding = isVenmoEnabled ? ['venmo'] : [];\n const disableVenmoFunding = !isVenmoEnabled ? ['venmo'] : [];\n const disableAPMsFunding = availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n );\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 ...enabledAlternativePaymentMethods,\n ];\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 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 const paypalSdk = await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n console.error(\n '[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\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, isAppSwitchEnabled } =\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 ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n }),\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 const paypalSdk = await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n console.error(\n '[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\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 { 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 { CookieStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport {\n PayPalFastlane,\n PayPalFastlaneAddress,\n PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneLookupCustomerByEmailResult,\n PayPalFastlaneProfileCard,\n PayPalFastlaneProfileName,\n PayPalFastlaneProfilePhone,\n PayPalFastlaneProfileToBcCustomerDataMappingResult,\n PayPalFastlaneSdk,\n PayPalFastlaneStylesOption,\n PayPalHostWindow,\n} from './paypal-types';\n\nexport default class PaypalFastlaneUtils {\n private window: PayPalHostWindow;\n\n constructor() {\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 *\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(sessionId: string): void {\n const expires = new Date();\n\n expires.setDate(expires.getDate() + 14); // 2 weeks expiry\n\n const cookiesOption = {\n expires,\n secure: true,\n };\n\n CookieStorage.set('bc-fastlane-sessionId', sessionId, cookiesOption);\n }\n\n removeStorageSessionId(): void {\n CookieStorage.remove('bc-fastlane-sessionId');\n }\n\n getStorageSessionId(): string {\n return CookieStorage.get('bc-fastlane-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 PaypalFastlaneUtils from './paypal-fastlane-utils';\n\nexport default function createPaypalFastlaneUtils(): PaypalFastlaneUtils {\n return new PaypalFastlaneUtils();\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 PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneStylesOption,\n PayPalFastlaneUtils,\n PayPalInitializationData,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-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 paypalSdkScriptLoader: PayPalSdkScriptLoader,\n private paypalFastlaneUtils: PayPalFastlaneUtils,\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 = state.getPaymentMethodOrThrow(methodId);\n\n const isTestModeEnabled = !!paymentMethod.initializationData?.isDeveloperModeApplicable;\n\n const paypalFastlaneSdk = await this.paypalSdkScriptLoader.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n state.getLocale(),\n );\n\n await this.paypalFastlaneUtils.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 await this.paymentIntegrationService.updatePaymentProviderCustomer({\n authenticationState: undefined,\n addresses: undefined,\n instruments: undefined,\n });\n\n this.paypalFastlaneUtils.removeStorageSessionId();\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.paypalFastlaneUtils.lookupCustomerOrThrow(\n customerEmail,\n );\n\n const authenticationResult =\n await this.paypalFastlaneUtils.triggerAuthenticationFlowOrThrow(customerContextId);\n\n const isAuthenticationFlowCanceled =\n authenticationResult.authenticationState === PayPalFastlaneAuthenticationState.CANCELED;\n\n await this.updateCustomerDataState(methodId, authenticationResult);\n\n if (isAuthenticationFlowCanceled) {\n this.paypalFastlaneUtils.removeStorageSessionId();\n } else {\n this.paypalFastlaneUtils.updateStorageSessionId(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.paypalFastlaneUtils.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 = 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 createPayPalFastlaneUtils,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceFastlaneCustomerStrategy from './paypal-commerce-fastlane-customer-strategy';\n\nconst createPayPalCommerceFastlaneCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceFastlaneCustomerStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceFastlaneCustomerStrategy(\n paymentIntegrationService,\n createPayPalSdkScriptLoader(),\n createPayPalFastlaneUtils(),\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 { PaymentMethod } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { StripePaymentMethod } from './stripe';\n\nexport function isStripePaymentMethodLike(\n paymentMethod: PaymentMethod,\n): paymentMethod is StripePaymentMethod {\n return (\n typeof paymentMethod === 'object' &&\n paymentMethod !== null &&\n 'initializationData' in paymentMethod &&\n (paymentMethod as StripePaymentMethod).initializationData !== undefined &&\n (paymentMethod as StripePaymentMethod).initializationData !== null &&\n typeof (paymentMethod as StripePaymentMethod).initializationData === 'object' &&\n 'stripePublishableKey' in (paymentMethod as StripePaymentMethod).initializationData &&\n 'stripeConnectedAccount' in (paymentMethod as StripePaymentMethod).initializationData &&\n 'shopperLanguage' in (paymentMethod as StripePaymentMethod).initializationData &&\n typeof (paymentMethod as StripePaymentMethod).initializationData.stripePublishableKey !==\n 'undefined' &&\n typeof (paymentMethod as StripePaymentMethod).initializationData.stripeConnectedAccount !==\n 'undefined' &&\n typeof (paymentMethod as StripePaymentMethod).initializationData.shopperLanguage !==\n 'undefined'\n );\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 {\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';\nimport {\n isStripePaymentMethodLike,\n STRIPE_UPE_CLIENT_API_VERSION,\n STRIPE_UPE_CLIENT_BETAS,\n StripeAppearanceOptions,\n StripeClient,\n StripeElementEvent,\n StripeElements,\n StripeElementType,\n StripeEventType,\n StripeFormMode,\n StripeJsVersion,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport isStripeAcceleratedCheckoutCustomer from './is-stripe-accelerated-checkout-customer';\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: StripeScriptLoader,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithStripeUPECustomerInitializeOptions,\n ): Promise {\n let stripeUPEClient: StripeClient;\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 (!isStripePaymentMethodLike(paymentMethod) || !clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\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: StripeAppearanceOptions | 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 paymentMethod.initializationData,\n state.getCartLocale(),\n StripeJsVersion.V3,\n STRIPE_UPE_CLIENT_BETAS,\n STRIPE_UPE_CLIENT_API_VERSION,\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(StripeElementEvent.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 { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeUPECustomerStrategy from './stripe-upe-customer-strategy';\n\nconst createStripeUPECustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new StripeUPECustomerStrategy(\n paymentIntegrationService,\n new StripeScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createStripeUPECustomerStrategy, [{ id: 'stripeupe' }]);\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 StripeClient,\n StripeConfirmPaymentData,\n StripeElement,\n StripeElements,\n StripeElementType,\n StripeError,\n StripeInitializationData,\n StripeJsVersion,\n StripePaymentIntentStatus,\n StripeStringConstants,\n} from './stripe';\nimport StripePaymentInitializeOptions from './stripe-initialize-options';\nimport StripeScriptLoader from './stripe-script-loader';\n\nexport default class StripeIntegrationService {\n private isMounted = false;\n private checkoutEventsUnsubscribe?: () => void;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n ) {}\n\n deinitialize(): void {\n this.checkoutEventsUnsubscribe?.();\n this.isMounted = false;\n }\n\n initCheckoutEventsSubscription(\n gatewayId: string,\n methodId: string,\n stripeInitializationOptions: StripePaymentInitializeOptions,\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 stripeInitializationOptions.onError?.(error);\n }\n\n return;\n }\n\n if (!this.isMounted) {\n await stripeElements?.fetchUpdates();\n this.mountElement(paymentElement, stripeInitializationOptions.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(methodId: string, stripeUPEClient?: StripeClient): 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 === StripePaymentIntentStatus.SUCCEEDED;\n }\n\n mapStripePaymentData(\n stripeElements?: StripeElements,\n returnUrl?: string,\n shouldAllowRedisplay = false,\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 ...(shouldAllowRedisplay ? { allow_redisplay: 'always' } : {}),\n billing_details: {\n email,\n address,\n name: this.getShopperFullName(billingAddress),\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 // INFO: no need to update Stripe Element if client token is not present\n return;\n }\n\n this.scriptLoader.updateStripeElements({ clientSecret: clientToken });\n }\n\n getStripeJsVersion(initializationData: StripeInitializationData): StripeJsVersion {\n return initializationData.useNewStripeJsVersion\n ? StripeJsVersion.CLOVER\n : StripeJsVersion.V3;\n }\n\n mapStripeAddress(address?: Address): AddressOptions {\n if (address) {\n const {\n city,\n address1,\n address2,\n countryCode: country,\n postalCode,\n stateOrProvinceCode,\n } = address;\n\n return {\n city,\n country,\n postal_code: postalCode,\n line1: address1,\n line2: address2,\n ...(stateOrProvinceCode ? { state: stateOrProvinceCode } : {}),\n };\n }\n\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n getShopperFullName(address?: Address): string {\n const { firstName = '', lastName = '' } = address || {};\n\n return `${firstName} ${lastName}`.trim();\n }\n}\n","import { StripeError } from './stripe';\n\nexport function isStripeError(error: unknown): error is StripeError {\n return typeof error === 'object' && error !== null && 'type' in error;\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\nexport const DEFAULT_CONTAINER_STYLES = {\n position: 'fixed',\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\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 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","export const expressCheckoutAllowedCountryCodes = [\n 'AC',\n 'AD',\n 'AE',\n 'AF',\n 'AG',\n 'AI',\n 'AL',\n 'AM',\n 'AO',\n 'AQ',\n 'AR',\n 'AT',\n 'AU',\n 'AW',\n 'AX',\n 'AZ',\n 'BA',\n 'BB',\n 'BD',\n 'BE',\n 'BF',\n 'BG',\n 'BH',\n 'BI',\n 'BJ',\n 'BL',\n 'BM',\n 'BN',\n 'BO',\n 'BQ',\n 'BR',\n 'BS',\n 'BT',\n 'BV',\n 'BW',\n 'BY',\n 'BZ',\n 'CA',\n 'CD',\n 'CF',\n 'CG',\n 'CH',\n 'CI',\n 'CK',\n 'CL',\n 'CM',\n 'CN',\n 'CO',\n 'CR',\n 'CV',\n 'CW',\n 'CY',\n 'CZ',\n 'DE',\n 'DJ',\n 'DK',\n 'DM',\n 'DO',\n 'DZ',\n 'EC',\n 'EE',\n 'EG',\n 'EH',\n 'ER',\n 'ES',\n 'ET',\n 'FI',\n 'FJ',\n 'FK',\n 'FO',\n 'FR',\n 'GA',\n 'GB',\n 'GD',\n 'GE',\n 'GF',\n 'GG',\n 'GH',\n 'GI',\n 'GL',\n 'GM',\n 'GN',\n 'GP',\n 'GQ',\n 'GR',\n 'GS',\n 'GT',\n 'GU',\n 'GW',\n 'GY',\n 'HK',\n 'HN',\n 'HR',\n 'HT',\n 'HU',\n 'ID',\n 'IE',\n 'IL',\n 'IM',\n 'IN',\n 'IO',\n 'IQ',\n 'IS',\n 'IT',\n 'JE',\n 'JM',\n 'JO',\n 'JP',\n 'KE',\n 'KG',\n 'KH',\n 'KI',\n 'KM',\n 'KN',\n 'KR',\n 'KW',\n 'KY',\n 'KZ',\n 'LA',\n 'LB',\n 'LC',\n 'LI',\n 'LK',\n 'LR',\n 'LS',\n 'LT',\n 'LU',\n 'LV',\n 'LY',\n 'MA',\n 'MC',\n 'MD',\n 'ME',\n 'MF',\n 'MG',\n 'MK',\n 'ML',\n 'MM',\n 'MN',\n 'MO',\n 'MQ',\n 'MR',\n 'MS',\n 'MT',\n 'MU',\n 'MV',\n 'MW',\n 'MX',\n 'MY',\n 'MZ',\n 'NA',\n 'NC',\n 'NE',\n 'NG',\n 'NI',\n 'NL',\n 'NO',\n 'NP',\n 'NR',\n 'NU',\n 'NZ',\n 'OM',\n 'PA',\n 'PE',\n 'PF',\n 'PG',\n 'PH',\n 'PK',\n 'PL',\n 'PM',\n 'PN',\n 'PR',\n 'PS',\n 'PT',\n 'PY',\n 'QA',\n 'RE',\n 'RO',\n 'RS',\n 'RU',\n 'RW',\n 'SA',\n 'SB',\n 'SC',\n 'SD',\n 'SE',\n 'SG',\n 'SH',\n 'SI',\n 'SJ',\n 'SK',\n 'SL',\n 'SM',\n 'SN',\n 'SO',\n 'SR',\n 'SS',\n 'ST',\n 'SV',\n 'SX',\n 'SZ',\n 'TA',\n 'TC',\n 'TD',\n 'TF',\n 'TG',\n 'TH',\n 'TJ',\n 'TK',\n 'TL',\n 'TM',\n 'TN',\n 'TO',\n 'TR',\n 'TT',\n 'TV',\n 'TW',\n 'TZ',\n 'UA',\n 'UG',\n 'US',\n 'UY',\n 'UZ',\n 'VA',\n 'VC',\n 'VE',\n 'VG',\n 'VN',\n 'VU',\n 'WF',\n 'WS',\n 'XK',\n 'YE',\n 'YT',\n 'ZA',\n 'ZM',\n 'ZW',\n 'ZZ',\n];\n\n// Stripe has restricted the number of shipping rates to 9.\nexport const stripeAllowedShippingOptionsLength = 9;\n","import { round } from 'lodash';\n\nimport {\n AmountTransformer,\n CustomerInitializeOptions,\n CustomerStrategy,\n InvalidArgumentError,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n Payment,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n ShippingOption,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n isStripePaymentMethodLike,\n StripeAdditionalActionRequired,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeError,\n StripeEventType,\n StripeInitializationData,\n StripeIntegrationService,\n StripeLinkV2Event,\n StripeLinkV2Options,\n StripeLinkV2ShippingRate,\n StripePaymentMethodType,\n StripeResult,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport {\n expressCheckoutAllowedCountryCodes,\n stripeAllowedShippingOptionsLength,\n} from './constants';\nimport { WithStripeOCSCustomerInitializeOptions } from './stripe-ocs-customer-initialize-options';\n\nexport default class StripeLinkV2CustomerStrategy implements CustomerStrategy {\n private _stripeClient?: StripeClient;\n private _stripeElements?: StripeElements;\n private _linkV2Element?: StripeElement;\n private _amountTransformer?: AmountTransformer;\n private _onComplete?: (orderId?: number) => Promise;\n private _loadingIndicatorContainer?: string;\n private _captureMethod?: 'automatic' | 'manual';\n private _currencyCode?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n private stripeIntegrationService: StripeIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithStripeOCSCustomerInitializeOptions,\n ): Promise {\n const { stripeocs } = options || {};\n\n if (!stripeocs) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"options\" argument is not provided.`,\n );\n }\n\n const { gatewayId, container } = stripeocs;\n\n if (!container || !gatewayId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const methodId = this._getMethodId(gatewayId);\n const state = await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n const paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n const { loadingContainerId, buttonHeight, onComplete } = stripeocs;\n\n this._loadingIndicatorContainer = loadingContainerId;\n\n this._onComplete = onComplete;\n\n if (!isStripePaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { initializationData } = paymentMethod;\n const { captureMethod } = initializationData;\n const stripeJsVersion =\n this.stripeIntegrationService.getStripeJsVersion(initializationData);\n\n this._captureMethod = captureMethod;\n this._stripeClient = await this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n stripeJsVersion,\n );\n\n await this._mountExpressCheckoutElement(container, this._stripeClient, buttonHeight);\n\n this._initializeEvents(methodId);\n }\n\n signIn() {\n return Promise.resolve();\n }\n\n signOut() {\n return Promise.resolve();\n }\n\n executePaymentMethodCheckout() {\n return Promise.resolve();\n }\n\n deinitialize() {\n return Promise.resolve();\n }\n\n private async _mountExpressCheckoutElement(\n container: string,\n stripeExpressCheckoutClient: StripeClient,\n buttonHeight = 40,\n ) {\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n const expressCheckoutOptions: StripeElementsCreateOptions = {\n shippingAddressRequired: shouldRequireShippingAddress,\n ...(shouldRequireShippingAddress\n ? { allowedShippingCountries: await this._getAvailableCountries() }\n : {}),\n ...(shouldRequireShippingAddress\n ? { shippingRates: [{ id: '_', amount: 0, displayName: 'Pending rates' }] }\n : {}),\n billingAddressRequired: true,\n emailRequired: true,\n phoneNumberRequired: true,\n paymentMethods: {\n link: StripeStringConstants.AUTO,\n applePay: StripeStringConstants.NEVER,\n googlePay: StripeStringConstants.NEVER,\n amazonPay: StripeStringConstants.NEVER,\n paypal: StripeStringConstants.NEVER,\n klarna: StripeStringConstants.NEVER,\n },\n // Minimal buttonHeight value is 40\n buttonHeight,\n };\n\n const { cartAmount } = this.paymentIntegrationService.getState().getCartOrThrow();\n\n const elementsOptions: StripeLinkV2Options = {\n mode: 'payment',\n amount: this._toCents(cartAmount),\n currency: this._getCurrency(),\n ...(this._captureMethod ? { captureMethod: this._captureMethod } : {}),\n };\n\n this._stripeElements = stripeExpressCheckoutClient.elements(elementsOptions);\n\n this._linkV2Element = this._stripeElements.create(\n StripeElementType.EXPRESS_CHECKOUT,\n expressCheckoutOptions,\n );\n this._linkV2Element.mount(`#${container}`);\n\n return this._linkV2Element;\n }\n\n /** Events * */\n\n private _initializeEvents(methodId: string): void {\n if (!this._linkV2Element) {\n return;\n }\n\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n\n if (shouldRequireShippingAddress) {\n this._linkV2Element.on(StripeElementEvent.SHIPPING_ADDRESS_CHANGE, async (event) =>\n this._onShippingAddressChange(event),\n );\n this._linkV2Element.on(StripeElementEvent.SHIPPING_RATE_CHANGE, async (event) =>\n this._onShippingRateChange(event),\n );\n }\n\n this._linkV2Element.on(StripeElementEvent.CONFIRM, async (event) =>\n this._onConfirm(event, methodId),\n );\n\n this._linkV2Element.on(StripeElementEvent.CANCEL, this._onCancel);\n }\n\n private async _onShippingAddressChange(event: StripeEventType): Promise {\n if (!('address' in event)) {\n return;\n }\n\n const shippingAddress = event.address;\n // Depending on the country, some fields can be missing or partially redacted.\n // For example, the shipping address in the US can only contain a city, state, and ZIP code.\n // The full shipping address appears in the confirm event object after the purchase is confirmed in the browser’s payment interface.\n const result = {\n firstName: '',\n lastName: '',\n phone: '',\n company: '',\n address1: '',\n address2: '',\n city: shippingAddress?.city || '',\n countryCode: shippingAddress?.country || '',\n postalCode: shippingAddress?.postal_code || '',\n stateOrProvince: shippingAddress?.state || '',\n stateOrProvinceCode: shippingAddress?.state || '',\n customFields: [],\n };\n\n await this.paymentIntegrationService.updateShippingAddress(result);\n\n const shippingRates = await this._getAvailableShippingOptions();\n\n await this._updateDisplayedPrice();\n\n if (!shippingRates?.length) {\n event.reject();\n } else {\n event.resolve({\n shippingRates,\n });\n }\n }\n\n private _onCancel() {\n throw new PaymentMethodCancelledError();\n }\n\n private async _onShippingRateChange(event: StripeEventType) {\n if ('shippingRate' in event) {\n const { shippingRate } = event;\n\n await this._handleShippingOptionChange(shippingRate?.id);\n\n await this._updateDisplayedPrice();\n\n event.resolve({});\n }\n }\n\n /** Confirm methods * */\n private async _onConfirm(event: StripeEventType, methodId: string) {\n if (\n 'billingDetails' in event &&\n 'shippingAddress' in event &&\n this._stripeClient &&\n this._stripeElements\n ) {\n await this._updateShippingAndBillingAddress(event);\n await this.paymentIntegrationService.submitOrder();\n\n const paymentPayload = this._getPaymentPayload(methodId);\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._processAdditionalAction(error, methodId);\n }\n }\n\n return Promise.resolve();\n }\n\n private async _updateShippingAndBillingAddress(event: StripeLinkV2Event) {\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n\n const firstName =\n event.shippingAddress?.name?.split(' ')[0] ||\n event.billingDetails?.name?.split(' ')[0] ||\n '';\n const lastName =\n event.shippingAddress?.name?.split(' ')[1] ||\n event.billingDetails?.name?.split(' ')[1] ||\n '';\n\n if (shouldRequireShippingAddress) {\n const shippingAddress = this._mapShippingAddress(\n event.shippingAddress,\n event.billingDetails,\n firstName,\n lastName,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n }\n\n const billingAddress = this._mapBillingAddress(\n event.shippingAddress,\n event.billingDetails,\n firstName,\n lastName,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n private _mapShippingAddress(\n shippingAddress: StripeLinkV2Event['shippingAddress'],\n billingDetails: StripeLinkV2Event['billingDetails'],\n firstName: string,\n lastName: string,\n ) {\n return {\n firstName,\n lastName,\n phone: billingDetails?.phone || '',\n company: '',\n address1: shippingAddress?.address?.line1 || '',\n address2: shippingAddress?.address?.line2 || '',\n city: shippingAddress?.address?.city || '',\n countryCode: shippingAddress?.address?.country || '',\n postalCode: shippingAddress?.address?.postal_code || '',\n stateOrProvince: shippingAddress?.address?.state || '',\n stateOrProvinceCode: shippingAddress?.address?.state || '',\n customFields: [],\n };\n }\n\n private _mapBillingAddress(\n shippingAddress: StripeLinkV2Event['shippingAddress'],\n billingDetails: StripeLinkV2Event['billingDetails'],\n firstName: string,\n lastName: string,\n ) {\n return {\n email: billingDetails?.email || '',\n firstName,\n lastName,\n phone: billingDetails?.phone || '',\n company: '',\n address1: billingDetails?.address?.line1 || '',\n address2: '',\n city: billingDetails?.address?.city || '',\n countryCode: billingDetails?.address?.country || '',\n postalCode: billingDetails?.address?.postal_code || '',\n stateOrProvince: billingDetails?.address?.state || '',\n stateOrProvinceCode: shippingAddress?.address?.state || '',\n customFields: [],\n };\n }\n\n private async _processAdditionalAction(error: unknown, methodId: string): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n if (!this._stripeClient || !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 additionalActionData,\n methodId,\n );\n\n const paymentPayload = this._getPaymentPayload(methodId, paymentIntent?.id || token);\n\n try {\n this._toggleLoadingIndicator(true);\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n await this._completeCheckoutFlow();\n } catch (error) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n } finally {\n this._toggleLoadingIndicator(false);\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n additionalActionData: StripeAdditionalActionRequired['data'],\n methodId: string,\n ): Promise {\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeIntegrationService.mapStripePaymentData(\n this._stripeElements,\n redirect_url,\n );\n let stripeError: StripeError | undefined;\n\n try {\n const isPaymentCompleted = await this.stripeIntegrationService.isPaymentCompleted(\n methodId,\n this._stripeClient,\n );\n\n const confirmationResult = !isPaymentCompleted\n ? await this._stripeClient?.confirmPayment({\n elements: stripePaymentData.elements,\n clientSecret: token,\n redirect: StripeStringConstants.IF_REQUIRED,\n confirmParams: {\n return_url: stripePaymentData.confirmParams?.return_url,\n },\n })\n : await this._stripeClient?.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 return this.stripeIntegrationService.throwStripeError(stripeError);\n }\n }\n\n private async _completeCheckoutFlow() {\n if (typeof this._onComplete === 'function') {\n return this._onComplete();\n }\n\n window.location.replace('/order-confirmation');\n\n return Promise.resolve();\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 ...(token ? { credit_card_token: { token } } : {}),\n confirm: false,\n method: StripePaymentMethodType.Link,\n };\n\n return {\n methodId,\n paymentData: {\n formattedPayload,\n },\n };\n }\n\n /** Utils * */\n\n private _shouldRequireShippingAddress() {\n const { getCartOrThrow } = this.paymentIntegrationService.getState();\n const { lineItems } = getCartOrThrow();\n\n return !!lineItems.physicalItems.length;\n }\n\n private async _updateDisplayedPrice() {\n if (this._stripeElements) {\n this._stripeElements.update({\n currency: this._getCurrency(),\n mode: 'payment',\n amount: await this._getTotalPrice(),\n });\n }\n }\n\n private _getCurrency() {\n if (!this._currencyCode) {\n const { code: currencyCode } = this.paymentIntegrationService\n .getState()\n .getCartOrThrow().currency;\n\n this._currencyCode = currencyCode.toLowerCase();\n }\n\n return this._currencyCode;\n }\n\n private async _getTotalPrice(): Promise {\n await this.paymentIntegrationService.loadCheckout();\n\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 this._toCents(+totalPrice);\n }\n\n private async _getAvailableCountries(): Promise {\n const countries = await this.paymentIntegrationService.loadShippingCountries();\n const deliverableCountries =\n countries.getShippingCountries()?.map((country) => country.code) || [];\n\n return deliverableCountries.filter((code) => {\n return expressCheckoutAllowedCountryCodes.includes(code);\n });\n }\n\n private async _getAvailableShippingOptions(): Promise {\n const state = this.paymentIntegrationService.getState();\n const consignments = state.getConsignments();\n\n if (!consignments?.[0]) {\n return;\n }\n\n const consignment = consignments[0];\n const options = (consignment.availableShippingOptions || []).map(\n this._getStripeShippingOption.bind(this),\n );\n const recommendedShippingOption = consignment.availableShippingOptions?.find(\n (shippingOption) => shippingOption.isRecommended,\n );\n const selectedId = consignment.selectedShippingOption?.id;\n const recommendedId = recommendedShippingOption?.id;\n\n if (selectedId) {\n // Set selected shipping option first in the array, as it will be selected by default\n options.sort((option) => (option.id === selectedId ? -1 : 0));\n } else if (recommendedId) {\n // Set recommended shipping option first in the array, as it will be selected by default\n options.sort((option) => (option.id === recommendedId ? -1 : 0));\n await this._handleShippingOptionChange(recommendedId);\n } else {\n await this._handleShippingOptionChange(options[0]?.id);\n }\n\n // Stripe has restricted the number of shipping rates.\n return options.slice(0, stripeAllowedShippingOptionsLength);\n }\n\n private _getStripeShippingOption({ id, cost, description }: ShippingOption) {\n return {\n id,\n displayName: description,\n amount: this._toCents(cost),\n };\n }\n\n private async _handleShippingOptionChange(optionId?: string) {\n if (!optionId || optionId === 'shipping_option_unselected') {\n return;\n }\n\n return this.paymentIntegrationService.selectShippingOption(optionId);\n }\n\n private _getAmountTransformer() {\n if (this._amountTransformer) {\n return this._amountTransformer;\n }\n\n const { getCart } = this.paymentIntegrationService.getState();\n const { currency } = getCart() || {};\n\n if (currency) {\n const amountTransformer = new AmountTransformer(currency.decimalPlaces);\n\n return amountTransformer;\n }\n }\n\n private _toCents(amount: number) {\n const fallbackValue = Math.round(amount * 100);\n const amountTransformer = this._getAmountTransformer();\n\n if (amountTransformer) {\n return amountTransformer.toInteger(amount);\n }\n\n return fallbackValue;\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 _getMethodId(gatewayId: string): string {\n const { initializationData: { checkoutSessionEnabled } = {} } =\n this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(gatewayId);\n\n return checkoutSessionEnabled\n ? StripePaymentMethodType.CHECKOUT_SESSION\n : StripePaymentMethodType.OCS;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\nimport { DEFAULT_CONTAINER_STYLES, LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport StripeLinkV2CustomerStrategy from './stripe-link-v2-customer-strategy';\n\nconst createStripeLinkV2CustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n const loadingIndicator = new LoadingIndicator({\n containerStyles: DEFAULT_CONTAINER_STYLES,\n });\n\n return new StripeLinkV2CustomerStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n loadingIndicator,\n );\n};\n\nexport default toResolvableModule(createStripeLinkV2CustomerStrategy, [{ id: 'stripeocs' }]);\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 { 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","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: [{ code: string }];\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 type AdyenComponentFieldVisibility = 'hidden' | 'readOnly' | 'editable';\n\nexport interface AdyenOpenInvoiceComponentVisibility {\n personalDetails?: AdyenComponentFieldVisibility;\n billingAddress?: AdyenComponentFieldVisibility;\n deliveryAddress?: AdyenComponentFieldVisibility;\n}\n\nexport interface AdyenBoletoComponentOptions extends AdyenComponentEvents {\n personalDetailsRequired?: boolean;\n billingAddressRequired?: boolean;\n showEmailAddress?: boolean;\n visibility?: AdyenOpenInvoiceComponentVisibility;\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 { 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","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 { 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.71.1/adyen.css`,\n {\n prepend: false,\n attributes: {\n integrity:\n 'sha384-5MvB4RnzvviA3VBT4KYABZ4HXNZG5LRqREEgd41xt/pf/QvKmsj2O9GuNuywRXx9',\n crossorigin: 'anonymous',\n },\n },\n ),\n this._scriptLoader.loadScript(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/5.71.1/adyen.js`,\n {\n async: true,\n attributes: {\n integrity:\n 'sha384-yvY2yFNR4WqIjPqP9MzjI+gJimmaJnAvj4rLHKvgJbgFD5fMuf8zIJrFJOW8Lhhf',\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 static readonly mountContainerMaxWaitMs = 5000;\n private static readonly mountContainerPollIntervalMs = 50;\n\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._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 paymentData.instrumentId,\n bigpayToken,\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 _getLocale(): string | undefined {\n const locale = this.paymentIntegrationService.getState().getLocale();\n\n if (locale && locale.substring(0, 2) === 'es') {\n return 'es';\n }\n\n return locale;\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 void this._mountElement(additionalActionComponent, containerId)\n .then(() => {\n if (onLoad && typeof onLoad === 'function') {\n onLoad(() => {\n reject(new PaymentMethodCancelledError());\n additionalActionComponent.unmount();\n });\n }\n })\n .catch(reject);\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 async _mountCardVerificationComponent(): Promise {\n const adyenv3 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n\n if (!adyenv3.cardVerificationContainerId) {\n return undefined;\n }\n\n const 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 await this._mountElement(\n cardVerificationComponent,\n adyenv3.cardVerificationContainerId,\n );\n } catch {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return cardVerificationComponent;\n }\n\n private async _mountPaymentComponent(paymentMethod: PaymentMethod): Promise {\n const adyenv3 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n const billingAddress = this.paymentIntegrationService.getState().getBillingAddress();\n const { prefillCardHolderName } = paymentMethod.initializationData;\n\n const paymentComponent = adyenClient.create(paymentMethod.method, {\n ...(this._isOneyPaymentMethod(paymentMethod.method)\n ? {\n visibility: {\n personalDetails: 'hidden',\n billingAddress: 'hidden',\n deliveryAddress: 'hidden',\n },\n }\n : {}),\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 await this._mountElement(paymentComponent, adyenv3.containerId);\n } catch {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return paymentComponent;\n }\n\n private _isOneyPaymentMethod(method: string): boolean {\n return method.startsWith('facilypay');\n }\n\n private async _processAdditionalAction(\n error: unknown,\n shouldSaveInstrument?: boolean,\n shouldSetAsDefaultInstrument?: boolean,\n paymentToken?: string,\n bigpayToken?: Record,\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 const basePaymentData = {\n ...payment.paymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n };\n\n const tokenData =\n shouldSetAsDefaultInstrument && !shouldSaveInstrument\n ? {\n instrumentId: paymentToken,\n formattedPayload: {\n bigpay_token: {\n ...bigpayToken,\n token: paymentToken,\n },\n },\n }\n : {};\n\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...basePaymentData,\n ...tokenData,\n },\n });\n } catch (paymentError) {\n return this._processAdditionalAction(\n paymentError,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n paymentToken,\n bigpayToken,\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 async _mountElement(\n adyenComponent: AdyenComponent,\n containerId: string,\n ): Promise {\n await this._waitForMountContainer(containerId);\n\n try {\n adyenComponent.mount(`#${containerId}`);\n } catch {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n }\n\n private async _waitForMountContainer(containerId: string): Promise {\n const maxAttempts = Math.ceil(\n Adyenv3PaymentStrategy.mountContainerMaxWaitMs /\n Adyenv3PaymentStrategy.mountContainerPollIntervalMs,\n );\n const pollIntervalMs = Adyenv3PaymentStrategy.mountContainerPollIntervalMs;\n\n let step = 0;\n\n const poll = async (): Promise => {\n if (step === maxAttempts) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (document.getElementById(containerId)) {\n return;\n }\n\n await new Promise((resolve) => {\n setTimeout(resolve, pollIntervalMs);\n });\n\n step += 1;\n await poll();\n };\n\n await poll();\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","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 {\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","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';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const withHttpsExperimentName = 'PI-4789.afterpay_script_use_https';\n const withHttps = isExperimentEnabled(features, withHttpsExperimentName, false);\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._afterpaySdk = await this._afterpayScriptLoader.load(\n paymentMethod,\n countryCode,\n withHttps,\n );\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.js',\n HTTPS_PROD = 'https://portal.afterpay.com/afterpay-async.js',\n HTTPS_SANDBOX = 'https://portal.sandbox.afterpay.com/afterpay.js',\n}\n\nenum SCRIPTS_US {\n PROD = '//portal.afterpay.com/afterpay-async.js',\n SANDBOX = '//portal.sandbox.afterpay.com/afterpay.js',\n HTTPS_PROD = 'https://portal.afterpay.com/afterpay-async.js',\n HTTPS_SANDBOX = 'https://portal.sandbox.afterpay.com/afterpay.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(\n method: PaymentMethod,\n countryCode: string,\n withHttps = false,\n ): Promise {\n const testMode = method.config.testMode || false;\n const scriptURI = this._getScriptURI(countryCode, testMode, withHttps);\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, withHttps = false): string {\n if (countryCode === 'US') {\n if (withHttps) {\n return testMode ? SCRIPTS_US.HTTPS_SANDBOX : SCRIPTS_US.HTTPS_PROD;\n }\n\n return testMode ? SCRIPTS_US.SANDBOX : SCRIPTS_US.PROD;\n }\n\n if (withHttps) {\n return testMode ? SCRIPTS_DEFAULT.HTTPS_SANDBOX : SCRIPTS_DEFAULT.HTTPS_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 if (!this._amazonPayButton) {\n throw new InvalidArgumentError(\n 'Unable to render the Amazon Pay button to an invalid HTML container element.',\n );\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 ApplePayScriptLoader from './apple-pay-script-loader';\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 private _applePayScriptLoader: ApplePayScriptLoader,\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 await this._applePayScriptLoader.loadSdk();\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 (\n paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE &&\n paymentMethod.clientToken\n ) {\n this._braintreeSdk.initialize(paymentMethod.clientToken);\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","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\n} 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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n\n return new ApplePayPaymentStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), window, braintreeSDKVersionManager),\n ),\n new ApplePayScriptLoader(new ScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createApplePayPaymentStrategy, [{ id: 'applepay' }]);\n","export const LOADING_INDICATOR_STYLES = {\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\n};\n","import { MessagesStyleOptions, PayPalBNPLConfigurationItem } from '../bigcommerce-payments-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","export interface BaseInstrument {\n bigpayToken: string;\n defaultInstrument: boolean;\n provider: string;\n trustedShippingAddress: boolean;\n method: string;\n type: string;\n}\n\nexport function isBaseInstrument(instrument: unknown): instrument is BaseInstrument {\n if (typeof instrument !== 'object' || instrument === null) {\n return false;\n }\n\n return (\n 'bigpayToken' in instrument &&\n 'defaultInstrument' in instrument &&\n 'provider' in instrument &&\n 'trustedShippingAddress' in instrument &&\n 'method' in instrument &&\n 'type' in instrument\n );\n}\n","import {\n getPaypalMessagesStylesFromBNPLConfig,\n isBigCommercePaymentsProviderError,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalMessagesSdk,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isBaseInstrument } from '@bigcommerce/checkout-sdk/utility';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtons,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n ClickCallbackActions,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsPaymentInitializeOptions, {\n WithBigCommercePaymentsPaymentInitializeOptions,\n} from './bigcommerce-payments-payment-initialize-options';\n\nexport default class BigCommercePaymentsPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: BigCommercePaymentsButtons;\n private bigcommerce_payments?: BigCommercePaymentsPaymentInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private paypalSdkHelper: PayPalSdkHelper,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithBigCommercePaymentsPaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments } = options || {};\n\n this.bigcommerce_payments = bigcommerce_payments;\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 (!bigcommerce_payments) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments\" 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 const { container, bannerContainerId } = bigcommerce_payments;\n\n const {\n orderId,\n paypalBNPLConfiguration = [],\n isPayPalCreditAvailable,\n } = paymentMethod.initializationData || {};\n\n if (bannerContainerId !== undefined) {\n if (!document.getElementById(bannerContainerId)) {\n // eslint-disable-next-line no-console\n console.error('Unable to create banner without valid banner container ID.');\n\n return;\n }\n\n const bannerConfiguration = paypalBNPLConfiguration?.find(\n ({ id }) => id === 'checkout',\n );\n\n if (isPayPalCreditAvailable || !bannerConfiguration?.status) {\n return;\n }\n\n const paypalMessages = await this.paypalSdkHelper.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n );\n\n if (!paypalMessages || typeof paypalMessages?.Messages !== 'function') {\n console.error(\n '[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n return this.renderMessages(paypalMessages, bannerContainerId, bannerConfiguration);\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 this.loadingIndicatorContainer = container?.split('#')[1];\n\n await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n if (bigcommerce_payments.onInit && typeof bigcommerce_payments.onInit === 'function') {\n bigcommerce_payments.onInit(() => this.renderButton(methodId, bigcommerce_payments));\n }\n\n if (\n bigcommerce_payments.shouldRenderPayPalButtonOnInitialization === undefined ||\n bigcommerce_payments.shouldRenderPayPalButtonOnInitialization\n ) {\n this.renderButton(methodId, bigcommerce_payments);\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const { onError } = this.bigcommerce_payments || {};\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)) {\n await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(payment.methodId);\n\n await new Promise((_resolve, reject) => {\n if (this.bigcommerce_payments) {\n this.paypalButton?.close();\n this.renderButton(payment.methodId, this.bigcommerce_payments);\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 bigcommerce_payments: BigCommercePaymentsPaymentInitializeOptions,\n ): void {\n const paypalSdk = this.bigCommercePaymentsIntegrationService.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 } = bigcommerce_payments;\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"container\" argument is not provided.',\n );\n }\n\n const buttonOptions: BigCommercePaymentsButtonsOptions = {\n ...(this.isAppSwitchEnabled(methodId) && {\n appSwitchWhenAvailable: true,\n }),\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.bigCommercePaymentsIntegrationService.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 if (this.paypalButton.hasReturned?.() && this.isAppSwitchEnabled(methodId)) {\n this.paypalButton.resume?.();\n } else {\n this.paypalButton.render(container);\n }\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: BigCommercePaymentsPaymentInitializeOptions['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: BigCommercePaymentsPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm?.();\n }\n\n private handleError(\n error: unknown,\n onError: BigCommercePaymentsPaymentInitializeOptions['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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_paymentscheckout',\n {\n shouldSaveInstrument: fieldsValues?.shouldSaveInstrument || false,\n },\n );\n }\n\n /**\n *\n * Vaulting flow methods\n *\n * */\n private getFieldsValues(): HostedInstrument | undefined {\n const { getFieldsValues } = this.bigcommerce_payments || {};\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 findInstrument = instruments?.find(\n (instrument) =>\n isBaseInstrument(instrument) &&\n instrument.bigpayToken === paymentData.instrumentId,\n );\n const trustedShippingAddress = isBaseInstrument(findInstrument)\n ? findInstrument.trustedShippingAddress\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 /**\n *\n * Render Pay Later Messages\n *\n * */\n private renderMessages(\n paypalMessages: PayPalMessagesSdk,\n bannerContainerId: string,\n bannerConfiguration: PayPalBNPLConfigurationItem,\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: checkout.outstandingBalance,\n placement: 'payment',\n style: getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\n };\n\n paypalMessages.Messages(paypalMessagesOptions).render(`#${bannerContainerId}`);\n }\n\n private isProviderError(error: unknown): boolean {\n if (isBigCommercePaymentsProviderError(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 /**\n *\n * AppSwitch enabling handling\n *\n */\n private isAppSwitchEnabled(methodId: string): boolean {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n return paymentMethod.initializationData?.isAppSwitchEnabled ?? 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 isBigCommercePaymentsProviderError(error: unknown): error is ProviderError {\n return typeof error === 'object' && error !== null && 'errors' in error;\n}\n","import { createBigCommercePaymentsSdk } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport { LOADING_INDICATOR_STYLES } from '../bigcommerce-payments-constants';\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsPaymentStrategy from './bigcommerce-payments-payment-strategy';\n\nconst createBigCommercePaymentsPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n createBigCommercePaymentsSdk(),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsPaymentStrategy, [\n { id: 'bigcommerce_payments' },\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 BigCommercePaymentsFastlaneUtils,\n BigCommercePaymentsInitializationData,\n getFastlaneStyles,\n isBigcommerceFastlaneRequestError,\n isPayPalFastlaneCustomer,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneCardComponentMethods,\n PayPalFastlaneCardComponentOptions,\n PayPalFastlanePaymentFormattedPayload,\n PayPalFastlaneSdk,\n PayPalSdkHelper,\n TDSecureAuthenticationState,\n TDSecureVerificationMethod,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport BigCommercePaymentsRequestSender from '../bigcommerce-payments-request-sender';\nimport { LiabilityShiftEnum } from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsFastlanePaymentInitializeOptions, {\n WithBigCommercePaymentsFastlanePaymentInitializeOptions,\n} from './bigcommerce-payments-fastlane-payment-initialize-options';\n\nexport default class BigCommercePaymentsFastlanePaymentStrategy implements PaymentStrategy {\n private paypalComponentMethods?: PayPalFastlaneCardComponentMethods;\n private threeDSVerificationMethod?: string;\n private paypalFastlaneSdk?: PayPalFastlaneSdk;\n private bigcommerce_payments_fastlane?: BigCommercePaymentsFastlanePaymentInitializeOptions;\n private methodId?: string;\n private orderId?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsRequestSender: BigCommercePaymentsRequestSender,\n private bigCommercePaymentsSdk: PayPalSdkHelper,\n private bigCommercePaymentsFastlaneUtils: BigCommercePaymentsFastlaneUtils,\n ) {}\n\n /**\n *\n * Default methods\n *\n * */\n async initialize(\n options: PaymentInitializeOptions & WithBigCommercePaymentsFastlanePaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_fastlane } = 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.methodId = methodId;\n\n if (!bigcommerce_payments_fastlane) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_fastlane\" argument is not provided.',\n );\n }\n\n this.bigcommerce_payments_fastlane = bigcommerce_payments_fastlane;\n\n if (\n !bigcommerce_payments_fastlane.onInit ||\n typeof bigcommerce_payments_fastlane.onInit !== 'function'\n ) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_fastlane.onInit\" argument is not provided or it is not a function.',\n );\n }\n\n if (\n !bigcommerce_payments_fastlane.onChange ||\n typeof bigcommerce_payments_fastlane.onChange !== 'function'\n ) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_fastlane.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 this.threeDSVerificationMethod =\n paymentMethod.initializationData?.threeDSVerificationMethod;\n\n this.paypalFastlaneSdk = await this.bigCommercePaymentsSdk.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 bigcommerce_payments_fastlane?.styles,\n );\n\n await this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(\n this.paypalFastlaneSdk,\n !!isDeveloperModeApplicable,\n fastlaneStyles,\n );\n\n if (this.shouldRunAuthenticationFlow()) {\n await this.runPayPalAuthenticationFlowOrThrow(methodId);\n }\n\n await this.initializePayPalPaymentComponent();\n\n bigcommerce_payments_fastlane.onInit((container: string) =>\n this.renderPayPalPaymentComponent(container),\n );\n bigcommerce_payments_fastlane.onChange(() =>\n this.handlePayPalStoredInstrumentChange(methodId),\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 { paymentData, methodId } = payment;\n\n const isVaultedFlow = paymentData && isVaultedInstrument(paymentData);\n\n try {\n await this.paymentIntegrationService.submitOrder(order, options);\n\n const paymentPayload = isVaultedFlow\n ? await this.prepareVaultedInstrumentPaymentPayload(methodId, paymentData)\n : await this.preparePaymentPayload(methodId, paymentData);\n\n await this.paymentIntegrationService.submitPayment(\n paymentPayload,\n );\n\n this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId();\n } catch (error) {\n if (\n isBigcommerceFastlaneRequestError(error) &&\n error.response.name === 'INVALID_REQUEST'\n ) {\n const invalidRequestError = {\n translationKey: 'payment.errors.invalid_request_error',\n };\n\n this.handleError(invalidRequestError);\n\n return Promise.reject();\n }\n\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.bigCommercePaymentsFastlaneUtils.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.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(customerEmail);\n\n const authenticationResult =\n await this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(\n customerContextId,\n );\n\n const { authenticationState, addresses, instruments } =\n this.bigCommercePaymentsFastlaneUtils.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 if (isAuthenticationFlowCanceled) {\n this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId();\n } else {\n this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(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 * BigCommercePayments 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.bigCommercePaymentsFastlaneUtils.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 paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n const is3DSEnabled =\n this.isBigcommercePaymentsFastlaneThreeDSAvailable() &&\n paymentMethod.config.is3dsEnabled;\n\n const nonce = is3DSEnabled ? await this.get3DSNonce(instrumentId) : instrumentId;\n\n await this.createOrder(nonce);\n\n return {\n methodId,\n paymentData: {\n formattedPayload: {\n paypal_fastlane_token: {\n order_id: this.orderId,\n token: nonce,\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 billingAddress = state.getBillingAddressOrThrow();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\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:\n this.bigCommercePaymentsFastlaneUtils.mapBcToPayPalAddress(billingAddress),\n });\n\n const is3DSEnabled =\n this.isBigcommercePaymentsFastlaneThreeDSAvailable() &&\n paymentMethod.config.is3dsEnabled;\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n const nonce = is3DSEnabled ? await this.get3DSNonce(id) : id;\n\n await this.createOrder(nonce);\n\n return {\n methodId,\n paymentData: {\n ...paymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n formattedPayload: {\n paypal_fastlane_token: {\n order_id: this.orderId,\n token: nonce,\n },\n },\n },\n };\n }\n\n private async createOrder(id: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cartId = state.getCartOrThrow().id;\n\n if (this.methodId) {\n const { orderId } = await this.bigCommercePaymentsRequestSender.createOrder(\n this.methodId,\n {\n cartId,\n fastlaneToken: id,\n },\n );\n\n this.orderId = orderId;\n }\n }\n\n /**\n *\n * 3DSecure methods\n *\n * */\n private async get3DSNonce(nonce: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const order = state.getOrderOrThrow();\n const checkoutUrl = state.getStoreConfigOrThrow().links.checkoutLink;\n\n const threeDomainSecureComponent = this.paypalFastlaneSdk?.ThreeDomainSecureClient;\n\n if (!threeDomainSecureComponent) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n const threeDomainSecureParameters = {\n amount: order.orderAmount.toFixed(2),\n currency: cart.currency.code,\n nonce,\n threeDSRequested: this.threeDSVerificationMethod === TDSecureVerificationMethod.Always,\n transactionContext: {\n experience_context: {\n locale: 'en-US',\n return_url: checkoutUrl,\n cancel_url: checkoutUrl,\n },\n },\n };\n\n const isThreeDomainSecureEligible = await threeDomainSecureComponent.isEligible(\n threeDomainSecureParameters,\n );\n\n if (\n this.threeDSVerificationMethod === TDSecureVerificationMethod.Always &&\n !isThreeDomainSecureEligible\n ) {\n throw new PaymentMethodInvalidError();\n }\n\n if (isThreeDomainSecureEligible) {\n const {\n liabilityShift,\n authenticationState,\n nonce: threeDSNonce,\n } = await threeDomainSecureComponent.show();\n\n if (\n liabilityShift === LiabilityShiftEnum.No ||\n liabilityShift === LiabilityShiftEnum.Unknown ||\n authenticationState === TDSecureAuthenticationState.Errored ||\n authenticationState === TDSecureAuthenticationState.Cancelled\n ) {\n throw new PaymentMethodInvalidError();\n }\n\n if (\n authenticationState === TDSecureAuthenticationState.Succeeded &&\n [LiabilityShiftEnum.Yes, LiabilityShiftEnum.Possible].includes(liabilityShift)\n ) {\n return threeDSNonce;\n }\n }\n\n return nonce;\n }\n\n /**\n *\n * BigCommercePayments Fastlane instrument change\n *\n */\n private async handlePayPalStoredInstrumentChange(\n methodId: string,\n ): Promise {\n const paypalAxoSdk = this.bigCommercePaymentsFastlaneUtils.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 =\n this.bigCommercePaymentsFastlaneUtils.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 /**\n *\n * Bigcommerce Payments Fastlane experiments handling\n *\n */\n private isBigcommercePaymentsFastlaneThreeDSAvailable(): boolean {\n const state = this.paymentIntegrationService.getState();\n const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n\n return isExperimentEnabled(features, 'PROJECT-7080.bcp_fastlane_three_ds');\n }\n\n private handleError(error: unknown): void {\n if (\n this.bigcommerce_payments_fastlane?.onError &&\n typeof this.bigcommerce_payments_fastlane.onError === 'function'\n ) {\n this.bigcommerce_payments_fastlane.onError(error);\n }\n }\n}\n","export interface BigcommerceFastlaneRequestError {\n name: string;\n message: string;\n response: {\n name: string;\n };\n}\n\nexport default function isBigcommerceFastlaneRequestError(\n error: unknown,\n): error is BigcommerceFastlaneRequestError {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'message' in error &&\n 'response' in error &&\n 'name' in (error as BigcommerceFastlaneRequestError).response\n );\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n createBigCommercePaymentsFastlaneUtils,\n createBigCommercePaymentsSdk,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsRequestSender from '../bigcommerce-payments-request-sender';\n\nimport BigCommercePaymentsFastlanePaymentStrategy from './bigcommerce-payments-fastlane-payment-strategy';\n\nconst createBigCommercePaymentsFastlanePaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsFastlanePaymentStrategy\n> = (paymentIntegrationService) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new BigCommercePaymentsFastlanePaymentStrategy(\n paymentIntegrationService,\n new BigCommercePaymentsRequestSender(createRequestSender({ host: getHost() })),\n createBigCommercePaymentsSdk(),\n createBigCommercePaymentsFastlaneUtils(),\n );\n};\n\nexport default toResolvableModule(createBigCommercePaymentsFastlanePaymentStrategy, [\n { id: 'bigcommerce_payments_fastlane' }, // BigCommercePayments Fastlane relates to 'bigcommerce_payments_fastlane' method id\n]);\n","import {\n BigCommercePaymentsInitializationData,\n getPaypalMessagesStylesFromBNPLConfig,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalMessagesSdk,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtons,\n BigCommercePaymentsButtonsOptions,\n ClickCallbackActions,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsPayLaterPaymentInitializeOptions, {\n WithBigCommercePaymentsPayLaterPaymentInitializeOptions,\n} from './bigcommerce-payments-paylater-payment-initialize-options';\n\nexport default class BigCommercePaymentsPayLaterPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private bigCommercePaymentsButtons?: BigCommercePaymentsButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private loadingIndicator: LoadingIndicator,\n private paypalSdkHelper: PayPalSdkHelper,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions &\n WithBigCommercePaymentsPayLaterPaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_paylater } = 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 (!bigcommerce_payments_paylater) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_paylater\" 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 const { paypalBNPLConfiguration = [], orderId } = paymentMethod.initializationData || {};\n const { bannerContainerId, container } = bigcommerce_payments_paylater;\n\n if (bannerContainerId !== undefined) {\n if (!document.getElementById(bannerContainerId)) {\n // eslint-disable-next-line no-console\n console.error('Unable to create banner without valid banner container ID.');\n\n return;\n }\n\n const bannerConfiguration =\n paypalBNPLConfiguration &&\n paypalBNPLConfiguration.find(({ id }) => id === 'checkout');\n\n if (!bannerConfiguration?.status) {\n return;\n }\n\n const paypalMessages = await this.paypalSdkHelper.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n );\n\n return this.renderMessages(paypalMessages, bannerContainerId, bannerConfiguration);\n }\n\n // Info:\n // The BigCommercePayments 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 BigCommercePayments button.\n if (orderId) {\n this.orderId = orderId;\n\n return;\n }\n\n await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = container?.split('#')[1];\n\n this.renderButton(methodId, bigcommerce_payments_paylater);\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.bigCommercePaymentsIntegrationService.submitPayment(\n payment.methodId,\n this.orderId,\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.orderId = undefined;\n\n this.bigCommercePaymentsButtons?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n bigcommerce_payments_paylater: BigCommercePaymentsPayLaterPaymentInitializeOptions,\n ): void {\n if (!bigcommerce_payments_paylater?.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"container\" argument is not provided.',\n );\n }\n\n const bigCommerceSdk = this.bigCommercePaymentsIntegrationService.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 } =\n bigcommerce_payments_paylater;\n\n const fundingSources = [bigCommerceSdk.FUNDING.PAYLATER, bigCommerceSdk.FUNDING.CREDIT];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (hasRenderedSmartButton) {\n return;\n }\n\n const buttonOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(\n checkoutPaymentButtonStyles,\n ),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_paylater',\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.bigCommercePaymentsButtons = bigCommerceSdk.Buttons(buttonOptions);\n\n if (\n !this.bigCommercePaymentsButtons.isEligible() &&\n fundingSource === bigCommerceSdk.FUNDING.PAYLATER\n ) {\n return;\n }\n\n if (\n !this.bigCommercePaymentsButtons.isEligible() &&\n fundingSource === bigCommerceSdk.FUNDING.CREDIT\n ) {\n throw new NotImplementedError(\n `BigCommercePayments ${fundingSource} is not available for your region. Please use BigCommercePayments Checkout instead.`,\n );\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.bigCommercePaymentsButtons.render(container);\n hasRenderedSmartButton = true;\n });\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: BigCommercePaymentsPayLaterPaymentInitializeOptions['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: BigCommercePaymentsPayLaterPaymentInitializeOptions['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: BigCommercePaymentsPayLaterPaymentInitializeOptions['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,\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: checkout.outstandingBalance,\n placement: 'payment',\n style: getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\n };\n\n paypalMessages.Messages(paypalMessagesOptions).render(`#${bannerContainerId}`);\n }\n}\n","import { createBigCommercePaymentsSdk } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport { LOADING_INDICATOR_STYLES } from '../bigcommerce-payments-constants';\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsPayLaterPaymentStrategy from './bigcommerce-payments-paylater-payment-strategy';\n\nconst createBigCommercePaymentsPayLaterPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsPayLaterPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsPayLaterPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n createBigCommercePaymentsSdk(),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsPayLaterPaymentStrategy, [\n { id: 'bigcommerce_payments_paylater' },\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n BigCommercePaymentsInitializationData,\n BirthDate,\n PayPalOrderStatus,\n} from '../bigcommerce-payments-types';\n\nimport {\n BigCommercePaymentsRatePayPaymentInitializeOptions,\n WithBigCommercePaymentsRatePayPaymentInitializeOptions,\n} from './bigcommerce-payments-ratepay-initialize-options';\n\nconst POLLING_INTERVAL = 3000;\nconst MAX_POLLING_TIME = 300000;\n\nexport default class BigCommercePaymentsRatePayPaymentStrategy implements PaymentStrategy {\n private guid?: string;\n private bigcommerce_payments_ratepay?: BigCommercePaymentsRatePayPaymentInitializeOptions;\n private loadingIndicatorContainer?: string;\n private pollingTimer = 0;\n private stopPolling = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\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 & WithBigCommercePaymentsRatePayPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, bigcommerce_payments_ratepay } = 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 (!bigcommerce_payments_ratepay) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_ratepay\" argument is not provided.`,\n );\n }\n\n const { legalTextContainer, container, loadingContainerId } = bigcommerce_payments_ratepay;\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.bigcommerce_payments_ratepay = bigcommerce_payments_ratepay;\n\n await this.bigCommercePaymentsIntegrationService.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.bigcommerce_payments_ratepay || {};\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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_apmscheckout',\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.bigcommerce_payments_ratepay || {};\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 bigCommercePaymentsSdk =\n this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const ratePayButton = bigCommercePaymentsSdk.Legal({\n fundingSource: bigCommercePaymentsSdk.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.bigcommerce_payments_ratepay || {};\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 & WithBigCommercePaymentsRatePayPaymentInitializeOptions,\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.bigCommercePaymentsIntegrationService.getOrderStatus(\n 'bigcommerce_payments_apms',\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 bigcommerce_payments_ratepay: this.bigcommerce_payments_ratepay,\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 { LOADING_INDICATOR_STYLES } from '../bigcommerce-payments-constants';\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsRatePayPaymentStrategy from './bigcommerce-payments-ratepay-payment-strategy';\n\nconst createBigCommercePaymentsRatePayPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsRatePayPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsRatePayPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n new LoadingIndicator({\n containerStyles: { ...LOADING_INDICATOR_STYLES, position: 'fixed' },\n }),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsRatePayPaymentStrategy, [\n { gateway: 'bigcommerce_payments_apms', id: 'ratepay' },\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 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 { isNil, omitBy } from 'lodash';\n\nimport {\n BigCommercePaymentsFastlaneUtils,\n BigCommercePaymentsInitializationData,\n isBigCommercePaymentsFastlaneCustomer,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\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';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n BigCommercePaymentsCardFields,\n BigCommercePaymentsCardFieldsConfig,\n BigCommercePaymentsCardFieldsOnApproveData,\n BigCommercePaymentsCardFieldsState,\n BigCommercePaymentsFields,\n BigCommercePaymentsHostedFieldsRenderOptions,\n LiabilityShiftEnum,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsCreditCardsPaymentInitializeOptions, {\n WithBigCommercePaymentsCreditCardsPaymentInitializeOptions,\n} from './bigcommerce-payments-credit-cards-payment-initialize-options';\n\nexport default class BigCommercePaymentsCreditCardsPaymentStrategy implements PaymentStrategy {\n private executionPaymentData?: OrderPaymentRequestBody['paymentData'];\n private isCreditCardForm?: boolean;\n private isCreditCardVaultedForm?: boolean;\n\n private cardFields?: BigCommercePaymentsCardFields;\n private cvvField?: BigCommercePaymentsFields;\n private expiryField?: BigCommercePaymentsFields;\n private numberField?: BigCommercePaymentsFields;\n private nameField?: BigCommercePaymentsFields;\n\n private hostedFormOptions?: HostedFormOptions;\n private returnedOrderId?: string;\n private returnedVaultedToken?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private bigCommercePaymentsSdk: PayPalSdkHelper,\n private bigCommercePaymentsFastlaneUtils: BigCommercePaymentsFastlaneUtils,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions &\n WithBigCommercePaymentsCreditCardsPaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_creditcards } = options;\n const bigCommercePaymentsInitializationOptions = bigcommerce_payments_creditcards;\n\n const { form, onCreditCardFieldsRenderingError, onLoadComplete } =\n bigCommercePaymentsInitializationOptions || {};\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.bigcommerce_payments_creditcards.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.bigCommercePaymentsIntegrationService.loadPayPalSdk(\n methodId,\n undefined,\n true,\n true,\n );\n\n if (this.isCreditCardForm || this.isCreditCardVaultedForm) {\n await this.initializeFields(form, onCreditCardFieldsRenderingError);\n }\n\n onLoadComplete?.();\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 // The condition gets triggered when customer pays with vaulted instrument and shipping address is trusted\n const { orderId } =\n await this.bigCommercePaymentsIntegrationService.createOrderCardFields(\n 'bigcommerce_payments_creditcardscheckout',\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?: BigCommercePaymentsCreditCardsPaymentInitializeOptions['onCreditCardFieldsRenderingError'],\n ): Promise {\n const { fields, styles } = formOptions;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const executeCallback = this.getExecuteCallback(fields);\n\n const cardFieldsConfig: BigCommercePaymentsCardFieldsConfig = {\n style: this.getInputStyles(styles),\n onApprove: ({\n orderID,\n vaultSetupToken,\n liabilityShift,\n }: BigCommercePaymentsCardFieldsOnApproveData) => {\n if (\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.bigCommercePaymentsIntegrationService.createOrderCardFields(\n 'bigcommerce_payments_creditcardscheckout',\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.bigCommercePaymentsIntegrationService.createOrderCardFields(\n 'bigcommerce_payments_creditcardscheckout',\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({\n orderID,\n vaultSetupToken,\n }: BigCommercePaymentsCardFieldsOnApproveData) {\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 }: BigCommercePaymentsCardFieldsState):\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 * */\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 }: BigCommercePaymentsCardFieldsState): HostedFieldValidateEventData {\n const updatedFields = { ...fields };\n\n delete updatedFields.cardNameField;\n\n const fieldsKeys = Object.keys(updatedFields) as Array<\n keyof BigCommercePaymentsCardFieldsState['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(): BigCommercePaymentsCardFields {\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 ): BigCommercePaymentsHostedFieldsRenderOptions['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: BigCommercePaymentsCardFieldsState,\n ): void {\n formOptions?.onValidate?.(this.getValidityData(event));\n }\n\n private onFocusHandler(\n formOptions: HostedFormOptions,\n event: BigCommercePaymentsCardFieldsState,\n ): void {\n formOptions?.onFocus?.(this.getFieldTypeByEmittedField(event));\n }\n\n private onBlurHandler(\n formOptions: HostedFormOptions,\n event: BigCommercePaymentsCardFieldsState,\n ): void {\n formOptions?.onBlur?.(this.getFieldTypeByEmittedField(event));\n }\n\n private onInputSubmitRequest(\n formOptions: HostedFormOptions,\n event: BigCommercePaymentsCardFieldsState,\n ): void {\n formOptions?.onEnter?.(this.getFieldTypeByEmittedField(event));\n }\n\n /**\n *\n * BigCommercePayments Accelerated checkout related methods\n *\n */\n // TODO: remove this part when BCP Fastlane 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 bigCommercePaymentsPaymentProviderCustomer = isBigCommercePaymentsFastlaneCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n return (\n paymentMethod?.initializationData?.isAcceleratedCheckoutEnabled &&\n paymentMethod?.initializationData?.isBigCommercePaymentsAnalyticsV2Enabled &&\n !bigCommercePaymentsPaymentProviderCustomer?.authenticationState\n );\n }\n\n // TODO: remove this part when BCP Fastlane 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.bigCommercePaymentsSdk.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n );\n\n await this.bigCommercePaymentsFastlaneUtils.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 PaymentProviderCustomer,\n PayPalConnectCustomer,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isBigCommercePaymentsFastlaneCustomer(\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 createBigCommercePaymentsFastlaneUtils,\n createBigCommercePaymentsSdk,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsCreditCardsPaymentStrategy from './bigcommerce-payments-credit-cards-payment-strategy';\n\nconst createBigCommercePaymentsCreditCardsPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsCreditCardsPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsCreditCardsPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n createBigCommercePaymentsSdk(),\n createBigCommercePaymentsFastlaneUtils(),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsCreditCardsPaymentStrategy, [\n { id: 'bigcommerce_payments_creditcards' },\n]);\n","import { noop } from 'lodash';\n\nimport {\n PayPalApmSdk,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodClientUnavailableError,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n TimeoutError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtons,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n NonInstantAlternativePaymentMethods,\n PayPalOrderStatus,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions, {\n WithBigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\n} from './bigcommerce-payments-alternative-methods-payment-initialize-options';\n\nconst POLLING_INTERVAL = 3000;\nconst MAX_POLLING_TIME = 300000;\n\nexport default class BigCommercePaymentsAlternativeMethodsPaymentStrategy\n implements PaymentStrategy\n{\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private bigCommercePaymentsButton?: BigCommercePaymentsButtons;\n private paypalApms?: PayPalApmSdk;\n private pollingTimer = 0;\n private stopPolling = noop;\n private isPollingEnabled = false;\n private bigCommercePaymentsAlternativeMethods?: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private bigCommercePaymentsSdkHelper: PayPalSdkHelper,\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 &\n WithBigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, bigcommerce_payments_apms } = options;\n\n this.bigCommercePaymentsAlternativeMethods = bigcommerce_payments_apms;\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 (!bigcommerce_payments_apms) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_apms\" 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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n\n this.isPollingEnabled = isExperimentEnabled(features, 'PAYPAL-5624.bcp_ideal_polling');\n\n // Info:\n // The APM 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 the button.\n if (orderId) {\n this.orderId = orderId;\n\n return;\n }\n\n this.paypalApms = await this.bigCommercePaymentsSdkHelper.getPayPalApmsSdk(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n );\n\n this.loadingIndicatorContainer = bigcommerce_payments_apms.container.split('#')[1];\n\n this.renderButton(methodId, gatewayId, bigcommerce_payments_apms);\n\n if (shouldRenderFields) {\n this.renderFields(methodId, bigcommerce_payments_apms);\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.isPollingEnabled && methodId === 'ideal') {\n await new Promise((resolve, reject) => {\n void this.initializePollingMechanism(methodId, resolve, reject, gatewayId);\n });\n }\n\n if (!this.isNonInstantPaymentMethod(methodId)) {\n await this.paymentIntegrationService.submitOrder(order, options);\n }\n\n await this.bigCommercePaymentsIntegrationService.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 if (this.isPollingEnabled) {\n this.resetPollingMechanism();\n }\n\n this.bigCommercePaymentsButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Polling mechanism\n *\n *\n * */\n private async initializePollingMechanism(\n methodId: string,\n resolvePromise: (value?: unknown) => void,\n rejectPromise: (value?: unknown) => 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.bigCommercePaymentsIntegrationService.getOrderStatus(\n gatewayId,\n );\n\n const isOrderApproved = orderStatus === PayPalOrderStatus.Approved;\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 bigCommercePaymentsAlternativeMethods: this.bigCommercePaymentsAlternativeMethods,\n });\n\n this.handleError(new TimeoutError());\n } catch (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 private async reinitializeStrategy(\n options: PaymentInitializeOptions &\n WithBigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\n ) {\n await this.deinitialize();\n await this.initialize(options);\n }\n\n private handleError(error: unknown) {\n const { onError } = this.bigCommercePaymentsAlternativeMethods || {};\n\n if (this.isPollingEnabled) {\n this.resetPollingMechanism();\n }\n\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n gatewayId: string,\n bigcommerce_payments_apms: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\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 } = bigcommerce_payments_apms;\n\n const buttonOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource: methodId,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(buttonStyle),\n onInit: (_, actions) => bigcommerce_payments_apms.onInitButton(actions),\n createOrder: () => this.onCreateOrder(methodId, gatewayId, bigcommerce_payments_apms),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onCancel: () => {\n this.toggleLoadingIndicator(false);\n this.deInitializePollingMechanism();\n },\n onError: (error) => {\n this.deInitializePollingMechanism();\n this.handleFailure(error, onError);\n },\n onClick: async (_, actions) =>\n bigcommerce_payments_apms.onValidate(actions.resolve, actions.reject),\n };\n\n this.bigCommercePaymentsButton = paypalAmpsSdk.Buttons(buttonOptions);\n\n if (!this.bigCommercePaymentsButton.isEligible()) {\n return;\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.bigCommercePaymentsButton.render(container);\n }\n\n private async onCreateOrder(\n methodId: string,\n gatewayId: string,\n bigcommerce_payments_apms: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\n ): Promise {\n const { onValidate } = bigcommerce_payments_apms;\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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_apms',\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.bigCommercePaymentsIntegrationService.submitPayment(\n methodId,\n orderId,\n gatewayId,\n );\n }\n\n return orderId;\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n }\n\n private handleFailure(\n error: Error,\n onError: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions['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 bigcommerce_payments_apms: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\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 } = bigcommerce_payments_apms;\n\n if (!apmFieldsContainer) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_apms\" 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 { createBigCommercePaymentsSdk } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport { LOADING_INDICATOR_STYLES } from '../bigcommerce-payments-constants';\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsAlternativeMethodsPaymentStrategy from './bigcommerce-payments-alternative-methods-payment-strategy';\n\nconst createBigCommercePaymentsAlternativeMethodsPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsAlternativeMethodsPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsAlternativeMethodsPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n createBigCommercePaymentsSdk(),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsAlternativeMethodsPaymentStrategy, [\n { gateway: 'bigcommerce_payments_apms' },\n]);\n","import { isRedirectError } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsRedirectAlternativeMethodsPaymentInitializeOptions, {\n WithBigCommercePaymentsRedirectAlternativeMethodsPaymentInitializeOptions,\n} from './bigcomemrce-payments-redirect-alternative-methods-payment-initialize-options';\n\nexport default class BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy\n implements PaymentStrategy\n{\n private bigCommercePaymentsAlternativeMethods?: BigCommercePaymentsRedirectAlternativeMethodsPaymentInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n initialize(\n options: PaymentInitializeOptions &\n WithBigCommercePaymentsRedirectAlternativeMethodsPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, bigcommerce_payments_apms } = options;\n\n this.bigCommercePaymentsAlternativeMethods = bigcommerce_payments_apms;\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 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, gatewayId } = payment;\n\n try {\n const orderId = await this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_apms',\n {\n gatewayId: 'bigcommerce_payments_apms',\n methodId,\n },\n );\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: methodId,\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,\n gatewayId,\n paymentData,\n });\n } catch (error: unknown) {\n if (isRedirectError(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 reject();\n });\n }\n\n this.handleError(error);\n\n return Promise.reject(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 handleError(error: unknown) {\n const { onError } = this.bigCommercePaymentsAlternativeMethods || {};\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n}\n","import { isRequestError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RedirectError } from '../bigcommerce-payments-types';\n\nexport default function isRedirectError(error: unknown): error is RedirectError {\n return isRequestError(error) && error.body?.additional_action_required?.data.redirect_url;\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy from './bigcomemrce-payments-redirect-alternative-methods-payment-strategy';\n\nconst createBigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(\n createBigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy,\n [\n { gateway: 'bigcommerce_payments_apms', id: 'klarna' },\n { gateway: 'bigcommerce_payments_apms', id: 'afterpay' },\n ],\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtons,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n ClickCallbackActions,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsVenmoPaymentInitializeOptions, {\n WithBigCommercePaymentsVenmoPaymentInitializeOptions,\n} from './bigcommerce-payments-venmo-payment-initialize-options';\n\nexport default class BigCommercePaymentsVenmoPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: BigCommercePaymentsButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithBigCommercePaymentsVenmoPaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_venmo } = 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 (!bigcommerce_payments_venmo) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_venmo\" 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.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = bigcommerce_payments_venmo.container.split('#')[1];\n\n this.renderButton(methodId, bigcommerce_payments_venmo);\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.bigCommercePaymentsIntegrationService.submitPayment(\n payment.methodId,\n this.orderId,\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 bigcommerce_payments_venmo: BigCommercePaymentsVenmoPaymentInitializeOptions,\n ): void {\n const paypalSdk = this.bigCommercePaymentsIntegrationService.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 } =\n bigcommerce_payments_venmo;\n\n const buttonOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(\n checkoutPaymentButtonStyles,\n ),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_venmocheckout',\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()) {\n throw new NotImplementedError(\n `Venmo is not available for your region. Please another payment method 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: BigCommercePaymentsVenmoPaymentInitializeOptions['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: BigCommercePaymentsVenmoPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n this.toggleLoadingIndicator(false);\n }\n\n private handleError(\n error: Error,\n onError: BigCommercePaymentsVenmoPaymentInitializeOptions['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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsVenmoPaymentStrategy from './bigcommerce-payments-venmo-payment-strategy';\n\nconst createBigCommercePaymentsVenmoPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsVenmoPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsVenmoPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsVenmoPaymentStrategy, [\n { id: 'bigcommerce_payments_venmo' },\n]);\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","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","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 { 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 try {\n await this._blueSnapDirectHostedForm.attach(\n this._getPaymentFieldsToken(),\n creditCard,\n is3dsEnabled,\n );\n } catch (error) {\n if (error instanceof InvalidArgumentError) {\n return;\n }\n throw error;\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","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 ...(payment.paymentData.companyName\n ? { company_name: payment.paymentData.companyName }\n : {}),\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(\n paymentIntegrationService,\n createBraintreeSdk(paymentIntegrationService),\n );\n};\n\nexport default toResolvableModule(createBraintreeAchPaymentStrategy, [{ id: 'braintreeach' }]);\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport BraintreeSdk from './braintree-sdk';\nimport BraintreeSDKVersionManager from './braintree-sdk-version-manager';\n\nconst createBraintreeSdk = (paymentIntegrationService: PaymentIntegrationService) => {\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeScriptLoader = new BraintreeScriptLoader(\n getScriptLoader(),\n window,\n braintreeSDKVersionManager,\n );\n\n return new BraintreeSdk(braintreeScriptLoader);\n};\n\nexport default createBraintreeSdk;\n","import { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BraintreeHostWindow,\n BraintreeInitializationData,\n PayPalBNPLConfigurationItem,\n} from './braintree';\nimport { MessagesStyleOptions, MessagingPlacements } from './paypal';\n\nexport default class BraintreeMessages {\n private braintreeHostWindow: BraintreeHostWindow = window;\n\n constructor(private paymentIntegrationService: PaymentIntegrationService) {}\n\n render(methodId: string, containerId: string, placement: MessagingPlacements): void {\n const messagingContainer = containerId && document.getElementById(containerId);\n\n if (this.braintreeHostWindow.paypal && messagingContainer) {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const billingAddress = state.getBillingAddressOrThrow();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n if (!paymentMethod.initializationData) {\n return;\n }\n\n const { paypalBNPLConfiguration = [] } = paymentMethod.initializationData;\n\n const bannedId = placement === MessagingPlacements.PAYMENT ? 'checkout' : placement;\n const bannerConfiguration =\n paypalBNPLConfiguration &&\n paypalBNPLConfiguration.find(({ id }) => id === bannedId);\n\n if (!bannerConfiguration || !bannerConfiguration.status) {\n return;\n }\n\n // TODO: remove this code when this data attributes will be removed from banner div container in content service\n if (placement === MessagingPlacements.CART) {\n messagingContainer.removeAttribute('data-pp-style-logo-type');\n messagingContainer.removeAttribute('data-pp-style-logo-position');\n messagingContainer.removeAttribute('data-pp-style-text-color');\n messagingContainer.removeAttribute('data-pp-style-text-size');\n }\n\n this.braintreeHostWindow.paypal\n .Messages({\n amount: cart.cartAmount,\n buyerCountry: billingAddress.countryCode,\n placement,\n style: this.getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\n })\n .render(`#${containerId}`);\n }\n }\n\n private 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}\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","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 BraintreeInitializationData,\n BraintreeIntegrationService,\n BraintreeMessages,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n MessagingPlacements,\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 braintreeButtonOptions?: 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 braintreeMessages: BraintreeMessages,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreePaypalPaymentInitializeOptions,\n ) {\n const { braintree: braintreeOptions, methodId } = options;\n\n if (braintreeOptions?.containerId) {\n this.braintreeButtonOptions = braintreeOptions;\n }\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(braintreeOptions);\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(braintreeOptions);\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 if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { onError } = this.braintreeButtonOptions || {};\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)) {\n await this.loadPaypal();\n\n this.paypalButtonRender?.close();\n\n await this.loadPaypalCheckoutInstance(this.braintreeButtonOptions);\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(options?: BraintreePaypalPaymentInitializeOptions) {\n const { clientToken, initializationData, id: paymentMethodId } = 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 const isBraintreePaypalCredit = paymentMethodId === 'braintreepaypalcredit';\n const shouldShowPayPalCreditBanner =\n isBraintreePaypalCredit || !initializationData?.isCreditEnabled;\n\n await this.braintreeIntegrationService.getPaypalCheckout(\n paypalCheckoutConfig,\n (braintreePaypalCheckout) => {\n if (\n shouldShowPayPalCreditBanner &&\n paymentMethodId &&\n options?.bannerContainerId\n ) {\n this.renderPayPalMessages(paymentMethodId, options.bannerContainerId);\n }\n\n this.renderPayPalButton(braintreePaypalCheckout, options);\n },\n this.handleError,\n );\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private renderPayPalMessages(methodId: string, containerId: string) {\n this.braintreeMessages.render(methodId, containerId, MessagingPlacements.PAYMENT);\n }\n\n private renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n options?: BraintreePaypalPaymentInitializeOptions,\n ) {\n const { onPaymentError, submitForm, onRenderButton, containerId, onError } = options || {};\n\n if (!containerId) {\n return;\n }\n\n const container = this.getSmartButtonContainerId(containerId);\n const smartButtonContainer = document.getElementById(container);\n\n if (!smartButtonContainer) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because element with id ${containerId} does not exist.`,\n );\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 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 private getSmartButtonContainerId(container: string) {\n return container.split('#')[1] ?? container;\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 BraintreeMessages,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n overlay,\n );\n const braintreeMessages = new BraintreeMessages(paymentIntegrationService);\n\n return new BraintreePaypalPaymentStrategy(\n paymentIntegrationService,\n braintreeIntegrationService,\n braintreeMessages,\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 { RequestSender } from '@bigcommerce/request-sender';\n\nimport { BraintreeOrderStatusData } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class BraintreeRequestSender {\n constructor(private requestSender: RequestSender) {}\n\n async getOrderStatus(\n methodId = 'braintreelocalmethods',\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 { noop } from 'lodash';\n\nimport {\n BraintreeInitializationData,\n BraintreeLocalPayment,\n BraintreeLocalPaymentConfig,\n BraintreeLocalPaymentMethodRedirectAction,\n BraintreeLocalPaymentsPayload,\n BraintreeLPMPaymentStartData,\n BraintreeLPMStartPaymentError,\n BraintreeOrderSavedResponse,\n BraintreeOrderStatus,\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 TimeoutError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport BraintreeRequestSender from '../braintree-request-sender';\n\nimport {\n BraintreeLocalMethodsPaymentInitializeOptions,\n WithBraintreeLocalMethodsPaymentInitializeOptions,\n} from './braintree-local-methods-payment-initialize-options';\n\nconst POLLING_INTERVAL = 3000;\nconst MAX_POLLING_TIME = 300000;\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 gatewayId?: string;\n private isLPMsUpdateExperimentEnabled = false;\n private pollingTimer = 0;\n private stopPolling = noop;\n private isPollingEnabled = false;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeSdk: BraintreeSdk,\n private braintreeRequestSender: BraintreeRequestSender,\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 & WithBraintreeLocalMethodsPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, braintreelocalmethods } = options;\n\n this.gatewayId = gatewayId;\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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n\n this.isPollingEnabled = isExperimentEnabled(\n features,\n 'PAYPAL-5258.braintree_local_methods_polling',\n );\n\n this.isLPMsUpdateExperimentEnabled = isExperimentEnabled(\n features,\n 'PAYPAL-4853.add_new_payment_flow_for_braintree_lpms',\n );\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 const checkoutUrl = state.getStoreConfigOrThrow().links.checkoutLink;\n\n return {\n paymentType: methodId,\n amount: grandTotal,\n fallback: {\n url: checkoutUrl,\n buttonText: 'Complete Payment',\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 if (this.isPollingEnabled) {\n return new Promise((resolve, reject) => {\n void this.initializePollingMechanism(\n methodId,\n resolve,\n reject,\n this.gatewayId,\n );\n });\n }\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 this.resetPollingMechanism();\n\n return reject();\n }\n\n if (this.isPollingEnabled) {\n this.resetPollingMechanism();\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 if (this.isPollingEnabled) {\n this.resetPollingMechanism();\n }\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 /**\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.braintreeRequestSender.getOrderStatus(gatewayId, {\n params: {\n useMetadata: false,\n },\n });\n\n const isOrderPending = orderStatus.status === BraintreeOrderStatus.Pending;\n const isOrderApproved = orderStatus.status === BraintreeOrderStatus.Completed;\n const isPollingError = orderStatus.status === BraintreeOrderStatus.Failed;\n\n if (isOrderApproved) {\n this.deinitializePollingMechanism();\n\n return resolvePromise();\n }\n\n if (isPollingError) {\n return rejectPromise();\n }\n\n if (\n !isOrderApproved &&\n isOrderPending &&\n this.pollingTimer < this.maxPollingIntervalTime\n ) {\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 braintreelocalmethods: this.braintreelocalmethods,\n });\n\n this.handleError(new TimeoutError());\n } catch (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 private async reinitializeStrategy(\n options: PaymentInitializeOptions & WithBraintreeLocalMethodsPaymentInitializeOptions,\n ) {\n await this.deinitialize();\n await this.initialize(options);\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\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 BraintreeRequestSender from '../braintree-request-sender';\n\nimport BraintreeLocalMethodsPaymentStrategy from './braintree-local-methods-payment-strategy';\n\nconst createBraintreeLocalMethodsPaymentStrategy: PaymentStrategyFactory<\n BraintreeLocalMethodsPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n );\n const requestSender = createRequestSender();\n const braintreeRequestSender = new BraintreeRequestSender(requestSender);\n\n return new BraintreeLocalMethodsPaymentStrategy(\n paymentIntegrationService,\n braintreeSdk,\n braintreeRequestSender,\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 Braintree3DSVerifyCardError,\n Braintree3DSVerifyCardPayload,\n BraintreeFastlaneAddress,\n BraintreeFastlaneAuthenticationState,\n BraintreeFastlaneCardComponent,\n BraintreeFastlaneCardComponentOptions,\n BraintreeInitializationData,\n BraintreeSdk,\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 PaymentMethodCancelledError,\n PaymentMethodClientUnavailableError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\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 private is3DSEnabled?: boolean;\n private onError?: (error: Error) => void;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeFastlaneUtils: BraintreeFastlaneUtils,\n private braintreeSdk: BraintreeSdk,\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 await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { initializationData, clientToken } = paymentMethod || {};\n const { isFastlaneStylingEnabled } = initializationData || {};\n const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const isThreeDSExperimentEnabled = isExperimentEnabled(\n features,\n 'PROJECT-7080.braintree_fastlane_three_ds',\n );\n\n this.is3DSEnabled = paymentMethod.config.is3dsEnabled;\n\n if (clientToken && isThreeDSExperimentEnabled) {\n this.braintreeSdk.initialize(clientToken);\n }\n\n const paypalFastlaneStyleSettings = isFastlaneStylingEnabled\n ? paymentMethod.initializationData?.fastlaneStyles\n : undefined;\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 this.onError = braintreefastlane.onError;\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 await this.paymentIntegrationService.submitOrder(order, options);\n\n const paymentPayload = await this.preparePaymentPayload(payment.methodId);\n\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n\n this.braintreeFastlaneUtils.removeSessionIdFromCookies();\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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const isThreeDSExperimentEnabled = isExperimentEnabled(\n features,\n 'PROJECT-7080.braintree_fastlane_three_ds',\n );\n\n if (paypalInstrument) {\n const threeDSToken =\n this.is3DSEnabled && isThreeDSExperimentEnabled\n ? await this.get3DS(paypalInstrument.bigpayToken, paypalInstrument?.iin || '')\n : undefined;\n\n return {\n methodId,\n paymentData: {\n deviceSessionId,\n formattedPayload: {\n paypal_fastlane_token: {\n token: threeDSToken || paypalInstrument.bigpayToken,\n },\n },\n },\n };\n }\n\n const { getPaymentToken } = this.getBraintreeCardComponentOrThrow();\n\n const paymentToken = await getPaymentToken({\n name: { fullName },\n billingAddress: this.mapToPayPalAddress(billingAddress),\n });\n\n const binGuest = paymentToken.paymentSource.card?.binDetails?.bin || '';\n const threeDSToken =\n this.is3DSEnabled && isThreeDSExperimentEnabled\n ? await this.get3DS(paymentToken.id, binGuest)\n : undefined;\n\n return {\n methodId,\n paymentData: {\n deviceSessionId,\n nonce: threeDSToken || paymentToken.id,\n },\n };\n }\n\n /**\n * 3DS\n */\n private async get3DS(nonce: string, bin: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const threeDSecure = await this.braintreeSdk.getBraintreeThreeDS();\n const order = state.getOrderOrThrow();\n\n return new Promise((resolve, reject) => {\n void threeDSecure.verifyCard(\n {\n amount: order?.orderAmount,\n nonce,\n bin,\n onLookupComplete: (_data, next) => {\n threeDSecure.on('customer-canceled', () => {\n if (typeof this.onError === 'function') {\n this.onError(new PaymentMethodCancelledError());\n }\n\n reject(new PaymentMethodCancelledError());\n });\n\n next();\n },\n },\n (\n verifyError: Braintree3DSVerifyCardError,\n payload: Braintree3DSVerifyCardPayload,\n ) => {\n if (\n verifyError &&\n verifyError.code === 'THREEDS_VERIFY_CARD_CANCELED_BY_MERCHANT'\n ) {\n if (typeof this.onError === 'function') {\n this.onError(new PaymentMethodCancelledError());\n }\n\n reject(new PaymentMethodCancelledError());\n }\n\n return resolve(payload.nonce);\n },\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.braintreeFastlaneUtils.getSessionIdFromCookies();\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 BraintreeSdk,\n BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n );\n\n const braintreeFastlaneUtils = new BraintreeFastlaneUtils(\n paymentIntegrationService,\n braintreeIntegrationService,\n );\n\n const braintreeScriptLoader = new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n );\n\n const braintreeSdk = new BraintreeSdk(braintreeScriptLoader);\n\n return new BraintreeFastlanePaymentStrategy(\n paymentIntegrationService,\n braintreeFastlaneUtils,\n braintreeSdk,\n );\n};\n\nexport default toResolvableModule(createBraintreeFastlanePaymentStrategy, [\n { id: 'braintreeacceleratedcheckout' },\n]);\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { noop } from 'lodash';\n\nimport {\n BraintreeDataCollector,\n BraintreeInitializationData,\n BraintreeSdk,\n BraintreeVisaCheckout,\n VisaCheckoutAddress,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutTokenizedPayload,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n Address,\n InvalidArgumentError,\n LegacyAddress,\n MissingDataError,\n MissingDataErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithBraintreeVisaCheckoutPaymentInitializeOptions } from './braintree-visa-checkout-payment-options';\n\nexport default class BraintreeVisaCheckoutPaymentStrategy implements PaymentStrategy {\n private paymentMethod?: PaymentMethod;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private formPoster: FormPoster,\n private braintreeSdk: BraintreeSdk,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeVisaCheckoutPaymentInitializeOptions,\n ): 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 await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n\n this.paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n const checkout = state.getCheckoutOrThrow();\n const storeConfig = state.getStoreConfigOrThrow();\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 this.braintreeSdk.initialize(clientToken);\n\n const braintreeVisaCheckout = await this.braintreeSdk.getBraintreeVisaCheckout();\n\n const visaCheckoutSdk = await this.braintreeSdk.getVisaCheckoutSdk(config?.testMode);\n\n const initOptions = braintreeVisaCheckout.createInitOptions({\n settings: {\n locale: storeConfig.storeProfile.storeLanguage,\n shipping: {\n collectShipping: false,\n },\n },\n paymentRequest: {\n currencyCode: storeConfig.currency.code,\n subtotal: String(checkout.subtotal),\n },\n });\n\n await visaCheckoutSdk.init(initOptions);\n\n visaCheckoutSdk.on(\n 'payment.success',\n (paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) =>\n this.tokenizePayment(braintreeVisaCheckout, paymentSuccessPayload)\n .then(() =>\n Promise.all([\n this.paymentIntegrationService.loadCheckout(),\n this.paymentIntegrationService.loadPaymentMethod(methodId),\n ]),\n )\n .then(() => onPaymentSelect())\n .catch((error) => onError(error)),\n );\n visaCheckoutSdk.on('payment.error', (_, error) => onError(error));\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\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 (!this.paymentMethod?.initializationData?.nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { nonce } = this.paymentMethod.initializationData;\n\n try {\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: { nonce },\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.braintreeSdk.deinitialize();\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 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 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 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 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","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\n VisaCheckoutHostWindow,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeVisaCheckoutPaymentStrategy from './braintree-visa-checkout-payment-strategy';\n\nconst createBraintreeVisaCheckoutPaymentStrategy: PaymentStrategyFactory<\n BraintreeVisaCheckoutPaymentStrategy\n> = (paymentIntegrationService) => {\n const hostWindow: VisaCheckoutHostWindow & BraintreeHostWindow = window;\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), hostWindow, braintreeSDKVersionManager),\n );\n\n return new BraintreeVisaCheckoutPaymentStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeSdk,\n );\n};\n\nexport default toResolvableModule(createBraintreeVisaCheckoutPaymentStrategy, [\n { id: 'braintreevisacheckout' },\n]);\n","import {\n BraintreeError,\n BraintreeIntegrationService,\n BraintreeTokenizePayload,\n BraintreeVenmoCheckout,\n isBraintreeError,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n FormattedPayload,\n MissingDataError,\n MissingDataErrorType,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n PaymentStrategy,\n PaypalInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\nimport BraintreeVenmoPaymentStrategyInitializeOptions, {\n WithBraintreeVenmoInitializeOptions,\n} from './braintree-venmo-payment-strategy-initialize-options';\n\nexport default class BraintreeVenmoPaymentStrategy implements PaymentStrategy {\n private braintreeVenmoCheckout?: BraintreeVenmoCheckout;\n private venmoOptions?: BraintreeVenmoPaymentStrategyInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeIntegrationService: BraintreeIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeVenmoInitializeOptions,\n ): Promise {\n const { methodId } = options;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n const state = this.paymentIntegrationService.getState();\n\n this.venmoOptions = options.braintreevenmo;\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n await this.initializeBraintreeVenmo(paymentMethod);\n }\n\n async execute(orderRequest: OrderRequestBody): 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 await this.paymentIntegrationService.submitOrder(order);\n await this.paymentIntegrationService.submitPayment(paymentData);\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.braintreeIntegrationService.teardown();\n\n return Promise.resolve();\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 const state = this.paymentIntegrationService.getState();\n const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const isBraintreeVenmoWebFallbackSupport = isExperimentEnabled(\n features,\n 'PAYPAL-5406.braintree_venmo_web_fallback_support',\n );\n\n try {\n this.braintreeIntegrationService.initialize(clientToken);\n this.braintreeVenmoCheckout = await this.braintreeIntegrationService.getVenmoCheckout({\n ...(this.venmoOptions?.allowDesktop !== undefined\n ? { allowDesktop: this.venmoOptions.allowDesktop }\n : {}),\n ...(isBraintreeVenmoWebFallbackSupport\n ? {\n mobileWebFallBack: isBraintreeVenmoWebFallbackSupport,\n }\n : {}),\n });\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async preparePaymentData(payment: OrderPaymentRequestBody): Promise {\n const state = this.paymentIntegrationService.getState();\n const { nonce } = state.getPaymentMethodOrThrow(payment.methodId);\n\n if (nonce) {\n return { ...payment, paymentData: this.formattedPayload(nonce) };\n }\n const tokenizeResult = await this.braintreeVenmoTokenize();\n const sessionId = await this.braintreeIntegrationService.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 {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport BraintreeVenmoPaymentStrategy from './braintree-venmo-payment-strategy';\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nconst createBraintreeVenmoPaymentStrategy: CheckoutButtonStrategyFactory<\n BraintreeVenmoPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const scriptLoader = getScriptLoader();\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeScriptLoader = new BraintreeScriptLoader(\n scriptLoader,\n braintreeHostWindow,\n braintreeSDKVersionManager,\n );\n const braintreeIntegrationService = new BraintreeIntegrationService(\n braintreeScriptLoader,\n braintreeHostWindow,\n );\n\n return new BraintreeVenmoPaymentStrategy(\n paymentIntegrationService,\n braintreeIntegrationService,\n );\n};\n\nexport default toResolvableModule(createBraintreeVenmoPaymentStrategy, [{ id: 'braintreevenmo' }]);\n","import { some } from 'lodash';\n\nimport {\n BraintreeIntegrationService,\n BraintreeThreeDSecureOptions,\n isBraintreeAcceleratedCheckoutCustomer,\n isBraintreePaymentRequest3DSError,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n Address,\n isHostedInstrumentLike,\n isRequestError,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NonceInstrument,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentInstrument,\n PaymentInstrumentMeta,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodFailedError,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeHostedForm from '../braintree-hosted-form/braintree-hosted-form';\nimport isBraintreeError from '../is-braintree-error';\n\nimport {\n BraintreeCreditCardPaymentInitializeOptions,\n WithBraintreeCreditCardPaymentInitializeOptions,\n} from './braintree-credit-card-payment-initialize-options';\n\nexport default class BraintreeCreditCardPaymentStrategy implements PaymentStrategy {\n private is3dsEnabled?: boolean;\n private isHostedFormInitialized?: boolean;\n private deviceSessionId?: string;\n private paymentMethod?: PaymentMethod;\n private threeDSecure?: BraintreeThreeDSecureOptions;\n private onPaymentError?: BraintreeCreditCardPaymentInitializeOptions['onPaymentError'];\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeIntegrationService: BraintreeIntegrationService,\n private braintreeHostedForm: BraintreeHostedForm,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeCreditCardPaymentInitializeOptions,\n ): Promise {\n const { methodId, gatewayId, braintree } = options;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n\n this.paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n const { clientToken } = this.paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.threeDSecure = braintree?.threeDSecure;\n this.onPaymentError = braintree?.onPaymentError;\n\n try {\n this.braintreeIntegrationService.initialize(clientToken, this.threeDSecure);\n\n if (this.isHostedPaymentFormEnabled(methodId, gatewayId) && braintree?.form) {\n await this.braintreeHostedForm.initialize(\n braintree.form,\n braintree.unsupportedCardBrands,\n clientToken,\n );\n\n this.isHostedFormInitialized = this.braintreeHostedForm.isInitialized();\n }\n\n this.is3dsEnabled = this.paymentMethod.config.is3dsEnabled;\n this.deviceSessionId = await this.braintreeIntegrationService.getSessionId();\n\n // TODO: Remove when BT AXO A/B testing is finished\n if (this.shouldInitializeBraintreeFastlane()) {\n await this.initializeBraintreeFastlaneOrThrow(methodId);\n }\n } catch (error) {\n return this.handleError(error, methodId);\n }\n }\n\n async execute(orderRequest: OrderRequestBody): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (this.isHostedFormInitialized) {\n this.braintreeHostedForm.validate();\n }\n\n await this.paymentIntegrationService.submitOrder(order);\n\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddressOrThrow();\n const orderAmount = state.getOrderOrThrow().orderAmount;\n\n try {\n const paymentData = this.isHostedFormInitialized\n ? await this.prepareHostedPaymentData(payment, billingAddress, orderAmount)\n : await this.preparePaymentData(payment, billingAddress, orderAmount);\n\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData,\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.braintreeIntegrationService.teardown(),\n this.braintreeHostedForm.deinitialize(),\n ]);\n\n return Promise.resolve();\n }\n\n private handleError(error: unknown, methodId?: string): void | Promise {\n if (isBraintreeError(error)) {\n const isPaymentMethodInitialized = !!(\n methodId &&\n this.paymentIntegrationService.getState().isPaymentMethodInitialized({ methodId })\n );\n\n if (\n !isPaymentMethodInitialized &&\n error.code === 'HOSTED_FIELDS_INVALID_FIELD_SELECTOR'\n ) {\n return;\n }\n\n if (error.code.startsWith('THREEDS_')) {\n this.onPaymentError?.(new PaymentMethodFailedError('THREEDS_VERIFICATION_FAILED'));\n\n return Promise.reject();\n }\n\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.braintreeIntegrationService.verifyCard(\n payment,\n billingAddress,\n orderAmount,\n )\n : await this.braintreeIntegrationService.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 } = await this.braintreeHostedForm.tokenizeForStoredCardVerification();\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.verifyCardWithHostedForm(billingAddress, orderAmount)\n : await this.braintreeHostedForm.tokenize(billingAddress);\n\n return {\n ...commonPaymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n nonce,\n };\n }\n\n private prepareAdditionalActionPaymentData(\n payment: OrderPaymentRequestBody,\n nonce: string,\n ): PaymentInstrument & PaymentInstrumentMeta {\n const { paymentData } = payment;\n const commonPaymentData = { deviceSessionId: this.deviceSessionId, nonce };\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n if (\n this.isSubmittingWithStoredCard(payment) &&\n (shouldSaveInstrument || shouldSetAsDefaultInstrument)\n ) {\n return {\n ...paymentData,\n ...commonPaymentData,\n };\n }\n\n return {\n ...commonPaymentData,\n };\n }\n\n private async verifyCardWithHostedForm(\n billingAddress: Address,\n orderAmount: number,\n ): Promise {\n const tokenizationPayload = await this.braintreeHostedForm.tokenize(billingAddress);\n\n return this.braintreeIntegrationService.challenge3DSVerification(\n tokenizationPayload,\n orderAmount,\n );\n }\n\n private async processAdditionalAction(\n error: unknown,\n payment: OrderPaymentRequestBody,\n orderAmount: number,\n ): Promise {\n if (\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return this.handleError(error);\n }\n\n try {\n const { payer_auth_request: storedCreditCardNonce } =\n (isBraintreePaymentRequest3DSError(error) && error.body.three_ds_result) || {};\n const { paymentData } = payment;\n const state = this.paymentIntegrationService.getState();\n\n if (!paymentData || !isVaultedInstrument(paymentData)) {\n throw new PaymentArgumentInvalidError(['instrumentId']);\n }\n\n const instrument = state.getCardInstrumentOrThrow(paymentData.instrumentId);\n const { nonce } = await this.braintreeIntegrationService.challenge3DSVerification(\n {\n nonce: storedCreditCardNonce || '',\n bin: instrument.iin,\n },\n orderAmount,\n );\n\n const newPaymentData = this.prepareAdditionalActionPaymentData(payment, nonce);\n\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: newPaymentData,\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 state = this.paymentIntegrationService.getState();\n const paymentMethod = state.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 when BT AXO A/B testing is finished\n private shouldInitializeBraintreeFastlane(): boolean {\n const state = this.paymentIntegrationService.getState();\n const paymentProviderCustomer = state.getPaymentProviderCustomerOrThrow();\n const braintreeCustomer = isBraintreeAcceleratedCheckoutCustomer(paymentProviderCustomer)\n ? paymentProviderCustomer\n : {};\n const isFastlaneEnabled: boolean =\n this.paymentMethod?.initializationData.isAcceleratedCheckoutEnabled;\n\n return isFastlaneEnabled && !braintreeCustomer?.authenticationState;\n }\n\n // TODO: Remove when BT AXO A/B testing is finished\n private async initializeBraintreeFastlaneOrThrow(methodId: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { clientToken, config } = paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.braintreeIntegrationService.initialize(clientToken, this.threeDSecure);\n\n await this.braintreeIntegrationService.getBraintreeFastlane(cart.id, config.testMode);\n }\n}\n","export interface BraintreePayment3DSRequestErrors {\n code: string;\n}\n\nexport interface BraintreePaymentRequest3DSError {\n name: string;\n body: {\n status: string;\n three_ds_result: {\n payer_auth_request: string;\n };\n errors: BraintreePayment3DSRequestErrors[];\n };\n}\n\nexport default function isBraintreePaymentRequest3DSError(\n error: unknown,\n): error is BraintreePaymentRequest3DSError {\n if (typeof error !== 'object' || error === null) {\n return false;\n }\n /* eslint-disable @typescript-eslint/consistent-type-assertions */\n return (\n 'name' in error &&\n 'body' in error &&\n 'status' in (error as BraintreePaymentRequest3DSError).body &&\n 'three_ds_result' in (error as BraintreePaymentRequest3DSError).body &&\n 'payer_auth_request' in (error as BraintreePaymentRequest3DSError).body.three_ds_result &&\n 'errors' in (error as BraintreePaymentRequest3DSError).body\n );\n}\n","import { BraintreeFormFieldsMap, BraintreeStoredCardFieldsMap } from '../index';\n\nexport function isBraintreeFormFieldsMap(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n): fields is BraintreeFormFieldsMap {\n return 'cardNumber' in fields;\n}\n\nexport function isBraintreeStoredCardFieldsMap(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n): fields is BraintreeStoredCardFieldsMap {\n return !!(\n Object.keys(fields).length > 0 &&\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n ((fields as BraintreeStoredCardFieldsMap).cardCodeVerification ||\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n (fields as BraintreeStoredCardFieldsMap).cardNumberVerification)\n );\n}\n","import isBraintreeError from './is-braintree-error';\nimport { BraintreeHostedFormError } from '../types';\n\nfunction isValidInvalidFieldKeys(invalidFieldKeys: unknown): invalidFieldKeys is string[] {\n return (\n Array.isArray(invalidFieldKeys) && invalidFieldKeys.every((key) => typeof key === 'string')\n );\n}\n\nexport default function isBraintreeHostedFormError(\n error: unknown,\n): 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 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n (details as { invalidFieldKeys?: unknown }).invalidFieldKeys === undefined) ||\n isValidInvalidFieldKeys(details)\n );\n}\n","import { Dictionary, isEmpty, isNil, omitBy } from 'lodash';\n\nimport {\n BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION,\n BraintreeBillingAddressRequestData,\n BraintreeClient,\n BraintreeFormErrorDataKeys,\n BraintreeFormErrorsData,\n BraintreeFormFieldsMap,\n BraintreeFormFieldStyles,\n BraintreeFormFieldStylesMap,\n BraintreeFormFieldType,\n BraintreeFormFieldValidateErrorData,\n BraintreeFormFieldValidateEventData,\n BraintreeFormOptions,\n BraintreeHostedFields,\n BraintreeHostedFieldsCreatorConfig,\n BraintreeHostedFieldsState,\n BraintreeHostedFormError,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\n BraintreeStoredCardFieldsMap,\n isBraintreeFormFieldsMap,\n isBraintreeHostedFormError,\n isBraintreeSupportedCardBrand,\n TokenizationPayload,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n Address,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\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 client?: Promise;\n private clientToken?: string;\n private isInitializedHostedForm = false;\n\n constructor(\n private braintreeScriptLoader: BraintreeScriptLoader,\n private braintreeSDKVersionManager: BraintreeSDKVersionManager,\n ) {}\n\n async initialize(\n options: BraintreeFormOptions,\n unsupportedCardBrands?: string[],\n clientToken?: string,\n ): Promise {\n this.clientToken = clientToken;\n this.formOptions = options;\n this.type = isBraintreeFormFieldsMap(options.fields)\n ? BraintreeHostedFormType.CreditCard\n : BraintreeHostedFormType.StoredCardVerification;\n\n const fields = this.mapFieldOptions(options.fields, unsupportedCardBrands);\n\n if (isEmpty(fields)) {\n this.isInitializedHostedForm = false;\n\n return;\n }\n\n this.cardFields = await this.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 await this.cardFields?.teardown();\n }\n }\n\n validate(): void {\n if (!this.cardFields) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const state = this.cardFields.getState();\n\n if (!this.isValidForm(state)) {\n this.handleValidityChange(state);\n\n const errors = this.mapValidationErrors(state.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 payload = await this.cardFields.tokenize(\n omitBy(\n {\n billingAddress: billingAddress && this.mapBillingAddress(billingAddress),\n },\n isNil,\n ),\n );\n\n this.formOptions?.onValidate?.({ isValid: true, errors: {} });\n\n return {\n nonce: payload.nonce,\n bin: payload.details?.bin,\n };\n } catch (error) {\n if (isBraintreeHostedFormError(error)) {\n const errors = this.mapTokenizeError(error);\n\n if (errors) {\n this.formOptions?.onValidate?.({ isValid: false, errors });\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 payload = await this.cardFields.tokenize();\n\n this.formOptions?.onValidate?.({ isValid: true, errors: {} });\n\n return {\n nonce: payload.nonce,\n bin: payload.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?.({ isValid: false, errors });\n throw new PaymentInvalidFormError(errors as PaymentInvalidFormErrorDetails);\n }\n }\n\n throw error;\n }\n }\n\n async createHostedFields(\n options: Pick,\n ): Promise {\n const client = await this.getClient();\n const hostedFields = await this.braintreeScriptLoader.loadHostedFields();\n\n const currentSdkVersion = this.braintreeSDKVersionManager.getSDKVersion();\n const hostedFieldsOptions =\n currentSdkVersion === BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION\n ? { ...options, preventCursorJumps: true }\n : options;\n\n return hostedFields.create({ ...hostedFieldsOptions, client });\n }\n\n async getClient(): Promise {\n if (!this.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!this.client) {\n const client = await this.braintreeScriptLoader.loadClient();\n\n this.client = client.create({ authorization: this.clientToken });\n }\n\n return this.client;\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 unsupportedCardBrands?: string[],\n ): BraintreeHostedFieldsCreatorConfig['fields'] {\n if (isBraintreeFormFieldsMap(fields)) {\n const supportedCardBrands: Partial> = {};\n\n unsupportedCardBrands?.forEach((cardBrand) => {\n if (isBraintreeSupportedCardBrand(cardBrand)) {\n supportedCardBrands[cardBrand] = false;\n }\n });\n\n return omitBy(\n {\n number: {\n container: `#${fields.cardNumber.containerId}`,\n placeholder: fields.cardNumber.placeholder,\n internalLabel: fields.cardNumber.accessibilityLabel,\n ...(Object.keys(supportedCardBrands).length > 0\n ? { supportedCardBrands }\n : {}),\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 // eslint-disable-next-line no-restricted-syntax\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 cvv = [this.createRequiredError(this.mapFieldType('cvv'))];\n\n if (isStoredCard) {\n return { [this.mapFieldType('cvv')]: cvv };\n }\n\n return {\n [this.mapFieldType('cvv')]: cvv,\n [this.mapFieldType('expirationDate')]: [\n this.createRequiredError(this.mapFieldType('expirationDate')),\n ],\n [this.mapFieldType('number')]: [\n this.createRequiredError(this.mapFieldType('number')),\n ],\n [this.mapFieldType('cardholderName')]: [\n this.createRequiredError(this.mapFieldType('cardholderName')),\n ],\n };\n }\n\n return error.details?.invalidFieldKeys?.reduce((result, key) => {\n const type = this.mapFieldType(key);\n\n return {\n ...result,\n [type]: [this.createInvalidError(type)],\n };\n }, {});\n }\n\n private createRequiredError(\n fieldType: BraintreeFormFieldType,\n ): BraintreeFormFieldValidateErrorData {\n const messages = {\n [BraintreeFormFieldType.CardCode]: 'CVV is required',\n [BraintreeFormFieldType.CardCodeVerification]: 'CVV is required',\n [BraintreeFormFieldType.CardNumber]: 'Credit card number is required',\n [BraintreeFormFieldType.CardNumberVerification]: 'Credit card number is required',\n [BraintreeFormFieldType.CardExpiry]: 'Expiration date is required',\n [BraintreeFormFieldType.CardName]: 'Full name is required',\n };\n\n return {\n fieldType,\n message: messages[fieldType] ?? 'Field is required',\n type: 'required',\n };\n }\n\n private createInvalidError(\n fieldType: BraintreeFormFieldType,\n ): BraintreeFormFieldValidateErrorData {\n const formFields = {\n [BraintreeFormFieldType.CardCode]: {\n message: 'Invalid card code',\n type: 'invalid_card_code',\n },\n [BraintreeFormFieldType.CardCodeVerification]: {\n message: 'Invalid card code',\n type: 'invalid_card_code',\n },\n [BraintreeFormFieldType.CardNumber]: {\n message: 'Invalid card number',\n type: 'invalid_card_number',\n },\n [BraintreeFormFieldType.CardNumberVerification]: {\n message: 'Invalid card number',\n type: 'invalid_card_number',\n },\n [BraintreeFormFieldType.CardExpiry]: {\n message: 'Invalid card expiry',\n type: 'invalid_card_expiry',\n },\n [BraintreeFormFieldType.CardName]: {\n message: 'Invalid card name',\n type: 'invalid_card_name',\n },\n };\n\n return {\n fieldType,\n message: formFields[fieldType]?.message ?? 'Invalid field',\n type: formFields[fieldType]?.type ?? 'invalid',\n };\n }\n\n private handleBlur = (event: BraintreeHostedFieldsState): void => {\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 => {\n this.formOptions?.onFocus?.({\n fieldType: this.mapFieldType(event.emittedBy),\n });\n };\n\n private handleCardTypeChange = (event: BraintreeHostedFieldsState): void => {\n const cardType =\n event.cards.length === 1\n ? event.cards[0].type.replace(/^master-card$/, 'mastercard')\n : undefined;\n\n this.formOptions?.onCardTypeChange?.({ cardType });\n };\n\n private handleInputSubmitRequest = (event: BraintreeHostedFieldsState): void => {\n this.formOptions?.onEnter?.({\n fieldType: this.mapFieldType(event.emittedBy),\n });\n };\n\n private handleValidityChange = (event: BraintreeHostedFieldsState): void => {\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(key: string): key is BraintreeFormErrorDataKeys {\n return [\n 'number',\n 'cvv',\n 'expirationDate',\n 'postalCode',\n 'cardholderName',\n 'cardType',\n ].includes(key);\n }\n}\n","import { BraintreeSupportedCardBrands } from '../types';\n\nexport const isBraintreeSupportedCardBrand = (\n cardBrand: string,\n): cardBrand is BraintreeSupportedCardBrands => {\n const supportedCardBrands = Object.values(BraintreeSupportedCardBrands);\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return supportedCardBrands.includes(cardBrand as BraintreeSupportedCardBrands);\n};\n\nexport default isBraintreeSupportedCardBrand;\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeCreditCardPaymentStrategy from './braintree-credit-card-payment-strategy';\nimport BraintreeHostedForm from '../braintree-hosted-form/braintree-hosted-form';\n\nconst createBraintreeCreditCardPaymentStrategy: PaymentStrategyFactory<\n BraintreeCreditCardPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n\n const braintreeScriptLoader = new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n );\n\n const braintreeIntegrationService = new BraintreeIntegrationService(\n braintreeScriptLoader,\n braintreeHostWindow,\n );\n\n const braintreeHostedForm = new BraintreeHostedForm(\n braintreeScriptLoader,\n braintreeSDKVersionManager,\n );\n\n return new BraintreeCreditCardPaymentStrategy(\n paymentIntegrationService,\n braintreeIntegrationService,\n braintreeHostedForm,\n );\n};\n\nexport default toResolvableModule(createBraintreeCreditCardPaymentStrategy, [{ id: 'braintree' }]);\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 { noop, some } from 'lodash';\n\nimport { CreditCardPaymentStrategy } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStatusTypes,\n RequestError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\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';\nimport { isCBAMPGSPaymentMethodLike, isThreeDSErrorBody } from './is-cba-mpgs-payment-method-like';\n\nexport default class CBAMPGSPaymentStrategy extends CreditCardPaymentStrategy {\n private threeDSjs?: ThreeDSjs;\n\n private sessionId = '';\n private locale?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private cbaMGPSScriptLoader: CBAMPGSScriptLoader,\n ) {\n super(paymentIntegrationService);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const { methodId } = options;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n if (!isCBAMPGSPaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\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 this.locale = state.getLocale();\n\n if (!this.locale) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n await this.threeDSjs.configure({\n merchantId,\n sessionId: this.sessionId,\n callback: () => {\n if (this.threeDSjs?.isConfigured()) {\n return this.paymentIntegrationService.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();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): 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 state = this.paymentIntegrationService.getState();\n const paymentMethod = state.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 !isRequestError(error) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n const retryState = this.paymentIntegrationService.getState();\n const order = retryState.getOrder();\n\n const {\n storeProfile: { storeId },\n } = retryState.getStoreConfigOrThrow();\n\n if (!order || !this.sessionId) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const orderId = `${storeId}_${order.orderId}`;\n\n if (!isThreeDSErrorBody(error.body)) {\n throw new RequestError();\n }\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 async finalize(options?: PaymentRequestOptions): Promise {\n const state = this.paymentIntegrationService.getState();\n const order = state.getOrder();\n\n if (order && state.getPaymentStatus() === PaymentStatusTypes.FINALIZE) {\n await this.paymentIntegrationService.finalizeOrder(options);\n\n return Promise.resolve();\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(orderId: string, transactionId: string): 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 PaymentMethodFailedError(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 PaymentMethodFailedError());\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 PaymentMethodFailedError();\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 // eslint-disable-next-line @typescript-eslint/no-misused-promises\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 // eslint-disable-next-line no-plusplus, no-param-reassign\n return this.authenticatePayer(orderId, transactionId, ++attempt);\n }\n\n return reject(new PaymentMethodFailedError());\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","/* eslint-disable @typescript-eslint/consistent-type-assertions */\nimport { PaymentMethod } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CBAMPGSPaymentMethod, ThreeDSErrorBody } from './cba-mpgs';\n\nexport function isCBAMPGSPaymentMethodLike(\n paymentMethod: PaymentMethod,\n): paymentMethod is CBAMPGSPaymentMethod {\n return (\n typeof paymentMethod === 'object' &&\n paymentMethod !== null &&\n 'initializationData' in paymentMethod &&\n typeof (paymentMethod as CBAMPGSPaymentMethod).initializationData === 'object' &&\n (paymentMethod as CBAMPGSPaymentMethod).initializationData !== null &&\n 'merchantId' in (paymentMethod as CBAMPGSPaymentMethod).initializationData &&\n typeof (paymentMethod as CBAMPGSPaymentMethod).initializationData.merchantId === 'string' &&\n (typeof (paymentMethod as CBAMPGSPaymentMethod).initializationData.isTestModeFlagEnabled ===\n 'boolean' ||\n typeof (paymentMethod as CBAMPGSPaymentMethod).initializationData\n .isTestModeFlagEnabled === 'undefined')\n );\n}\n\nexport function isThreeDSErrorBody(body: unknown): body is ThreeDSErrorBody {\n return (\n typeof body === 'object' &&\n body !== null &&\n 'three_ds_result' in body &&\n typeof (body as ThreeDSErrorBody).three_ds_result === 'object' &&\n (body as ThreeDSErrorBody).three_ds_result !== null &&\n 'token' in (body as ThreeDSErrorBody).three_ds_result &&\n typeof (body as ThreeDSErrorBody).three_ds_result.token === 'string'\n );\n}\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport { PaymentMethod } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport 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\nexport interface CBAMPGSPaymentMethod extends PaymentMethod {\n initializationData: CBAMPGSInitializationData;\n}\n\nexport interface CBAMPGSInitializationData {\n isTestModeFlagEnabled?: boolean;\n merchantId: string;\n}\n\nexport interface ThreeDSErrorBody {\n three_ds_result: {\n token: string;\n };\n}\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\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 { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CBAMPGSPaymentStrategy from './cba-mpgs-payment-strategy';\nimport CBAMPGSScriptLoader from './cba-mpgs-script-loader';\n\nconst createCBAMPGSPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new CBAMPGSPaymentStrategy(\n paymentIntegrationService,\n new CBAMPGSScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createCBAMPGSPaymentStrategy, [{ id: 'cba_mpgs' }]);\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 skipRedirectConfirmationAlert: true,\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\n if (\n methodId === CHECKOUTCOM_SEPA_PAYMENT_METHOD &&\n document &&\n 'iban' in paymentData &&\n 'bic' in paymentData\n ) {\n const { iban, bic } = paymentData as unknown as WithCheckoutcomSEPAInstrument;\n\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 const features = this._paymentIntegrationService.getState().getStoreConfigOrThrow()\n .checkoutSettings.features;\n\n this._clearpaySdk = await this._clearpayScriptLoader.load(paymentMethod, features);\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';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\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 HTTPS_SANDBOX: 'https://portal.sandbox.clearpay.co.uk/afterpay-async.js',\n HTTPS_PROD: 'https://portal.clearpay.co.uk/afterpay-async.js',\n};\n\nconst CLEARPAY_HTTPS_PROD_SCRIPT_EXPERIMENT = 'PI-4555.clearpay_add_https_to_prod_script';\n\nexport default class ClearpayScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, public _window: ClearpayWindow = window) {}\n\n async load(method: PaymentMethod, features = {}): Promise {\n await this._scriptLoader.loadScript(this._getScriptUrl(method.config.testMode, features));\n\n if (!this._window.AfterPay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.AfterPay;\n }\n\n private _getScriptUrl(testMode?: boolean, features = {}): string {\n const httpsEnabled = isExperimentEnabled(\n features,\n CLEARPAY_HTTPS_PROD_SCRIPT_EXPERIMENT,\n false,\n );\n\n if (testMode) {\n return httpsEnabled ? SCRIPTS_DEFAULT.HTTPS_SANDBOX : SCRIPTS_DEFAULT.SANDBOX;\n }\n\n return httpsEnabled ? SCRIPTS_DEFAULT.HTTPS_PROD : 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';\n\nconst SDK_PROD_URL = 'https://static.client.cardinaltrusted.com/songbird/v2.0.0/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, [\n { id: 'cybersourcev2' },\n { id: 'bnz' },\n]);\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 {\n guard,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n Omit,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { DEFAULT_CONTAINER_STYLES, LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\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 ErrorReasonType,\n GooglePayError,\n GooglePayInitializationData,\n GooglePayPaymentOptions,\n HandleCouponsOut,\n IntermediatePaymentData,\n TotalPriceStatusType,\n} from './types';\n\nexport default class GooglePayPaymentStrategy implements PaymentStrategy {\n private _loadingIndicator: LoadingIndicator;\n private _loadingIndicatorContainer?: string;\n private _paymentButton?: HTMLElement;\n private _clickListener?: (event: MouseEvent) => unknown;\n private _methodId?: keyof WithGooglePayPaymentInitializeOptions;\n private _isDeinitializationBlocked = false;\n\n constructor(\n protected _paymentIntegrationService: PaymentIntegrationService,\n protected _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n ) {\n this._loadingIndicator = new LoadingIndicator({\n containerStyles: DEFAULT_CONTAINER_STYLES,\n });\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, loadingContainerId, ...callbacks } = googlePayOptions;\n\n this._loadingIndicatorContainer = loadingContainerId;\n\n await this._paymentIntegrationService.loadPaymentMethod(this._getMethodId());\n\n const paymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(this._getMethodId());\n\n this._googlePayPaymentProcessor.setIsWebViewExperimentOn(\n !!paymentMethod.initializationData?.isWebViewExperimentOn,\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._isDeinitializationBlocked) {\n return Promise.resolve();\n }\n\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 this._googlePayPaymentProcessor.setShouldRequestShipping(false);\n await this._googlePayPaymentProcessor.initializeWidget();\n\n if (this._isDirectPayOnClickEnabled()) {\n await this._interactWithPaymentSheetAndPay();\n } else {\n await this._interactWithPaymentSheet();\n }\n } catch (error) {\n let err: unknown = error;\n\n this._toggleLoadingIndicator(false);\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 } finally {\n this._toggleBlockDeinitialization(false);\n }\n\n onPaymentSelect?.();\n };\n }\n\n protected async _interactWithPaymentSheetAndPay(): Promise {\n const response = await this._googlePayPaymentProcessor.showPaymentSheet();\n\n this._toggleBlockDeinitialization(true);\n this._toggleLoadingIndicator(true);\n\n const methodId = this._getMethodId();\n\n const state = this._paymentIntegrationService.getState();\n const { features } = state.getStoreConfigOrThrow().checkoutSettings;\n const isGooglePayDontOverrideAddresssExperimentOn = isExperimentEnabled(\n features,\n 'PI-5031.google_pay_dont_override_address',\n );\n\n const billingAddress =\n this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(response);\n\n if (billingAddress && !isGooglePayDontOverrideAddresssExperimentOn) {\n await this._paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n await this._googlePayPaymentProcessor.setExternalCheckoutXhr(methodId, response);\n\n await this._paymentIntegrationService.loadCheckout();\n await this._paymentIntegrationService.loadPaymentMethod(methodId);\n\n const freshPaymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n\n await this._googlePayPaymentProcessor.initialize(() => freshPaymentMethod);\n\n await this.execute({ useStoreCredit: false, payment: { methodId } });\n\n this._completeCheckoutFlow();\n }\n\n protected _completeCheckoutFlow(): void {\n window.location.replace('/checkout/order-confirmation');\n this._toggleLoadingIndicator(false);\n this._toggleBlockDeinitialization(false);\n }\n\n protected async _interactWithPaymentSheet(): Promise {\n const response = await this._googlePayPaymentProcessor.showPaymentSheet();\n const state = this._paymentIntegrationService.getState();\n const { features } = state.getStoreConfigOrThrow().checkoutSettings;\n const isGooglePayDontOverrideAddresssExperimentOn = isExperimentEnabled(\n features,\n 'PI-5031.google_pay_dont_override_address',\n );\n\n this._toggleBlockDeinitialization(true);\n this._toggleLoadingIndicator(true);\n\n const billingAddress =\n this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(response);\n\n if (billingAddress && !isGooglePayDontOverrideAddresssExperimentOn) {\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 this._toggleLoadingIndicator(false);\n this._toggleBlockDeinitialization(false);\n }\n\n protected _getMethodId(): keyof WithGooglePayPaymentInitializeOptions {\n return guard(\n this._methodId,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n protected async _getIsSignedInOrThrow(): Promise {\n try {\n return !!(await this._googlePayPaymentProcessor.getNonce(this._getMethodId()));\n } catch (e) {\n if (\n e instanceof MissingDataError &&\n e.subtype === MissingDataErrorType.MissingPaymentToken\n ) {\n return false;\n }\n\n throw e;\n }\n }\n\n protected async _handleOfferTrigger(\n offerData: IntermediatePaymentData['offerData'],\n ): Promise> {\n let isSignedIn = false;\n let errorMessage = 'Sign in to Google Pay first to apply or remove promo codes.';\n\n try {\n isSignedIn = await this._getIsSignedInOrThrow();\n } catch (error) {\n if (error instanceof MissingDataError) {\n errorMessage = error.message;\n }\n }\n\n // We can only apply/remove coupons on the payment step only if we are logged into Google Pay, otherwise we will get an error\n if (isSignedIn) {\n const { newOfferInfo, error } = await this._googlePayPaymentProcessor.handleCoupons(\n offerData,\n );\n\n return {\n newOfferInfo,\n error,\n };\n }\n\n return {\n error: {\n reason: ErrorReasonType.OFFER_INVALID,\n message: errorMessage,\n intent: CallbackTriggerType.OFFER,\n },\n };\n }\n\n protected _getGooglePayClientOptions(countryCode?: string): GooglePayPaymentOptions {\n if (this._googlePayPaymentProcessor.isWebViewWithRestrictions()) {\n return {};\n }\n\n return {\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({ callbackTrigger, offerData }) => {\n if (\n callbackTrigger !== CallbackTriggerType.INITIALIZE &&\n callbackTrigger !== CallbackTriggerType.OFFER\n ) {\n return;\n }\n\n const { offerChangeTriggers } =\n this._googlePayPaymentProcessor.getCallbackTriggers();\n\n const { newOfferInfo = undefined, error: couponsError = undefined } =\n offerChangeTriggers.includes(callbackTrigger)\n ? await this._handleOfferTrigger(offerData)\n : {};\n\n // We can add another errors if needed 'couponsError || shippingError || anotherError'\n const error: GooglePayError | undefined = couponsError;\n\n await this._paymentIntegrationService.loadCheckout();\n\n const { code: currencyCode } = this._paymentIntegrationService\n .getState()\n .getCartOrThrow().currency;\n const totalPrice = this._googlePayPaymentProcessor.getTotalPrice();\n\n return {\n newTransactionInfo: {\n ...(countryCode && { countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n ...(newOfferInfo && {\n newOfferInfo,\n }),\n ...(error && {\n error,\n }),\n };\n },\n },\n };\n }\n\n private _isDirectPayOnClickEnabled(): boolean {\n const { features } = this._paymentIntegrationService\n .getState()\n .getStoreConfigOrThrow().checkoutSettings;\n\n return isExperimentEnabled(features, 'PI-5111.google_pay_direct_pay_on_click');\n }\n\n private _toggleBlockDeinitialization(isBlocked: boolean) {\n this._isDeinitializationBlocked = isBlocked;\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 { 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';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\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';\n\nconst createGooglePayStripePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayStripeGateway(\n paymentIntegrationService,\n new StripeScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayStripePaymentStrategy, [\n { id: 'googlepaystripe' },\n { id: 'googlepaystripeupe' },\n { id: 'googlepaystripeocs' },\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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 MissingDataError,\n MissingDataErrorType,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../google-pay-payment-strategy';\nimport { GooglePayInitializationData, GooglePayPayPalCommerceInitializationData } from '../types';\n\nimport { ConfirmOrderData, ConfirmOrderStatus } from './types';\n\nexport default class GooglePayPaypalCommercePaymentStrategy extends GooglePayPaymentStrategy {\n constructor(\n _paymentIntegrationService: PaymentIntegrationService,\n _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n private _payPalCommerceSdk: PayPalCommerceSdk,\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 if (!paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const currencyCode = state.getCartOrThrow().currency.code;\n\n const payPalSDK = await this._payPalCommerceSdk.getPayPalGooglePaySdk(\n paymentMethod,\n currencyCode,\n state.getLocale(),\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';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\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';\n\nconst createGooglePayPayPalCommercePaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) => {\n const payPalCommerceSdk = new PayPalCommerceSdk(getScriptLoader());\n\n return new GooglePayPaypalCommercePaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayPaypalCommerceGateway(paymentIntegrationService, payPalCommerceSdk),\n createRequestSender(),\n createFormPoster(),\n ),\n payPalCommerceSdk,\n createRequestSender(),\n );\n};\n\nexport default toResolvableModule(createGooglePayPayPalCommercePaymentStrategy, [\n { id: 'googlepaypaypalcommerce' },\n]);\n","import { GooglePayConfig } from '../types';\n\nexport type FundingType = string;\n\n/**\n *\n * BigCommercePayments 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 BigCommercePaymentsHostWindow extends Window {\n paypal?: PayPalSDK;\n}\n\nexport interface BigCommercePaymentsScriptParams {\n options: {\n 'client-id'?: string;\n 'merchant-id'?: string;\n 'buyer-country'?: string;\n 'disable-funding'?: FundingType[];\n 'enable-funding'?: FundingType[];\n currency?: string;\n commit?: boolean;\n intent?: BigCommercePaymentsIntent;\n components?: ComponentsScriptType;\n };\n attributes: {\n 'data-client-token'?: string;\n 'data-partner-attribution-id'?: string;\n };\n}\n\nexport enum BigCommercePaymentsIntent {\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 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 BigCommercePaymentsInitializationData,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentMethod,\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 {\n GooglePayBigCommercePaymentsInitializationData,\n GooglePayInitializationData,\n} from '../types';\n\nimport { ConfirmOrderData, ConfirmOrderStatus } from './types';\n\nexport default class GooglePayBigCommercePaymentsPaymentStrategy extends GooglePayPaymentStrategy {\n constructor(\n _paymentIntegrationService: PaymentIntegrationService,\n _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n private _payPalSdkHelper: PayPalSdkHelper,\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 if (!paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const currencyCode = state.getCartOrThrow().currency.code;\n\n const payPalSDK = await this._payPalSdkHelper.getPayPalGooglePaySdk(\n paymentMethod as 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/googlepay_bigcommerce_paymentscheckout';\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 { PayPalSdkHelper } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\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 GooglePayBigCommercePaymentsGateway from './google-pay-bigcommerce-payments-gateway';\nimport GooglePayBigCommercePaymentsPaymentStrategy from './google-pay-bigcommerce-payments-payment-strategy';\n\nconst createGooglePayBigCommercePaymentsPaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) => {\n const payPalSdkHelper = new PayPalSdkHelper(getScriptLoader());\n\n return new GooglePayBigCommercePaymentsPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayBigCommercePaymentsGateway(paymentIntegrationService, payPalSdkHelper),\n createRequestSender(),\n createFormPoster(),\n ),\n payPalSdkHelper,\n createRequestSender(),\n );\n};\n\nexport default toResolvableModule(createGooglePayBigCommercePaymentsPaymentStrategy, [\n { id: 'googlepay_bigcommerce_payments' },\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","import { 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';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport KlarnaPayments, {\n KlarnaAddress,\n KlarnaAuthorizationResponse,\n KlarnaInitializationData,\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, initializationData } =\n state.getPaymentMethodOrThrow(methodId);\n const { klarnaMultipleRadioButton } = initializationData || {};\n\n await this.klarnav2TokenUpdater.klarnaOrderInitialization(cartId, clientToken);\n\n const paymentMethodСategory = this.isKlarnaMultipleRadioButtonEnabled(\n klarnaMultipleRadioButton,\n gatewayId,\n methodId,\n );\n const { authorization_token: authorizationToken } = await this.authorizeOrThrow(\n paymentMethodСategory,\n methodId,\n );\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 const { klarnaMultipleRadioButton } = paymentMethod.initializationData || {};\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 {\n container,\n payment_method_category: this.isKlarnaMultipleRadioButtonEnabled(\n klarnaMultipleRadioButton,\n gatewayId,\n methodId,\n ),\n },\n (response) => {\n if (onLoad) {\n onLoad(response);\n }\n\n resolve(response);\n },\n );\n });\n }\n\n private getUpdateSessionData(\n methodId: string,\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(\n methodId,\n billingAddress,\n billingAddress.email,\n ),\n };\n\n if (shippingAddress) {\n data.shipping_address = this.mapToKlarnaAddress(\n methodId,\n shippingAddress,\n billingAddress.email,\n );\n }\n\n return data;\n }\n\n private needsStateCode(countryCode: string) {\n return includes(supportedCountriesRequiringStates, countryCode);\n }\n\n private isKlarnaMultipleRadioButtonEnabled(\n klarnaMultipleRadioButton: boolean | undefined,\n gatewayId: string,\n methodId: string,\n ): string {\n return klarnaMultipleRadioButton ? methodId : gatewayId;\n }\n\n private mapToKlarnaAddress(methodId: string, address: Address, email?: string): KlarnaAddress {\n const state = this.paymentIntegrationService.getState();\n const { checkoutSettings } = state.getStoreConfigOrThrow();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { enableBillie } = paymentMethod.initializationData || {};\n\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 if (\n address.company &&\n enableBillie &&\n isExperimentEnabled(checkoutSettings.features, 'PI-3915.b2b_payment_session_for_klarna')\n ) {\n klarnaAddress.organization_name = address.company;\n }\n\n return klarnaAddress;\n }\n\n private async authorizeOrThrow(\n paymentMethodСategory: string,\n methodId: string,\n ): 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(\n methodId,\n billingAddress,\n shippingAddress,\n );\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 {\n payment_method_category: paymentMethodСategory,\n },\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 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 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\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 (\n typeof response.data !== 'string' ||\n response.origin !== `https://${testMode ? 'esqa' : 'www3'}.moneris.com`\n ) {\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 iframe.allow = 'payment';\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 {\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\n console.log('payload =======1', payload)\n\n await this._paymentIntegrationService.submitOrder(\n {\n ...payload,\n payment: payload.payment\n ? {\n methodId: payload.payment.methodId,\n ...(payload.payment.methodId === 'purchaseorder' && {\n paymentData: payload.payment.paymentData,\n }),\n }\n : 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 payment.gatewayId === 'adyen' || payment.gatewayId === 'barclaycard';\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","import { MessagesStyleOptions, PayPalBNPLConfigurationItem } from '../paypal-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 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 {\n ApproveCallbackPayload,\n ClickCallbackActions,\n getPaypalMessagesStylesFromBNPLConfig,\n isPaypalProviderError,\n isRedirectActionError,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalButtons,\n PayPalButtonsOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalMessagesSdk,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isBaseInstrument } from '@bigcommerce/checkout-sdk/utility';\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?: PayPalButtons;\n private paypalcommerce?: PayPalCommercePaymentInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\n private payPalSdkScriptLoader: PayPalSdkScriptLoader,\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 = state.getPaymentMethodOrThrow(methodId);\n\n const { container, bannerContainerId } = paypalcommerce;\n\n const {\n orderId,\n paypalBNPLConfiguration = [],\n isPayPalCreditAvailable,\n } = paymentMethod.initializationData || {};\n\n if (bannerContainerId !== undefined) {\n if (!document.getElementById(bannerContainerId)) {\n // eslint-disable-next-line no-console\n console.error('Unable to create banner without valid banner container ID.');\n\n return;\n }\n\n const bannerConfiguration = paypalBNPLConfiguration?.find(\n ({ id }) => id === 'checkout',\n );\n\n if (isPayPalCreditAvailable || !bannerConfiguration?.status) {\n return;\n }\n\n const paypalMessages = await this.payPalSdkScriptLoader.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n state.getLocale(),\n );\n\n if (!paypalMessages || typeof paypalMessages?.Messages !== 'function') {\n console.error(\n '[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n return this.renderMessages(paypalMessages, bannerContainerId, bannerConfiguration);\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 = paymentMethod.initializationData?.orderId;\n\n return;\n }\n\n this.loadingIndicatorContainer = container?.split('#')[1];\n\n await this.paypalIntegrationService.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\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 (isRedirectActionError(error)) {\n const redirectUrl = error.body.additional_action_required?.data?.redirect_url;\n\n return new Promise(() => window.location.replace(redirectUrl));\n }\n\n if (this.isProviderError(error)) {\n await this.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { paymentButtonStyles } = paymentMethod.initializationData || {};\n const { checkoutPaymentButtonStyles } = paymentButtonStyles || {};\n const { container, onError, onRenderButton, onValidate, submitForm } = paypalcommerce;\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"container\" argument is not provided.',\n );\n }\n\n const containerId = this.getSmartButtonContainerId(container);\n const smartButtonContainer = document.getElementById(containerId);\n\n if (!smartButtonContainer) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because element with id ${containerId} does not exist.`,\n );\n }\n\n const buttonOptions: PayPalButtonsOptions = {\n ...(this.isPaypalCommerceAppSwitchEnabled(methodId) && {\n appSwitchWhenAvailable: true,\n }),\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalIntegrationService.getValidButtonStyle(checkoutPaymentButtonStyles),\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 if (this.paypalButton.hasReturned?.() && this.isPaypalCommerceAppSwitchEnabled(methodId)) {\n this.paypalButton.resume?.();\n } else {\n this.paypalButton.render(container);\n }\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 return 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.paypalIntegrationService.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 const findInstrument = instruments?.find(\n (instrument) =>\n isBaseInstrument(instrument) &&\n instrument.bigpayToken === paymentData.instrumentId,\n );\n const trustedShippingAddress = isBaseInstrument(findInstrument)\n ? findInstrument.trustedShippingAddress\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 /**\n *\n * Render Pay Later Messages\n *\n * */\n private renderMessages(\n paypalMessages: PayPalMessagesSdk,\n bannerContainerId: string,\n bannerConfiguration: PayPalBNPLConfigurationItem,\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: checkout.outstandingBalance,\n placement: 'payment',\n style: getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\n };\n\n paypalMessages.Messages(paypalMessagesOptions).render(`#${bannerContainerId}`);\n }\n\n /**\n *\n * Error handling\n *\n */\n private isProviderError(error: unknown): boolean {\n if (isPaypalProviderError(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 /**\n *\n * PayPal AppSwitch enabling handling\n *\n */\n private isPaypalCommerceAppSwitchEnabled(methodId: string): boolean {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n return paymentMethod.initializationData?.isAppSwitchEnabled || false;\n }\n\n private getSmartButtonContainerId(container: string) {\n return container.split('#')[1] ?? container;\n }\n}\n","import { isRequestError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ProviderError } from './is-paypal-provider-error';\n\nexport interface RedirectActionError extends ProviderError {\n body: {\n additional_action_required: {\n type: 'offsite_redirect';\n data: {\n redirect_url: string;\n };\n };\n };\n}\n\nexport default function isRedirectActionError(error: unknown): error is RedirectActionError {\n return (\n isRequestError(error) && error.body.additional_action_required?.type === 'offsite_redirect'\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 isPaypalProviderError(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 PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalIntegrationService,\n LOADING_INDICATOR_STYLES,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommercePaymentStrategy from './paypal-commerce-payment-strategy';\n\nconst createPayPalCommercePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new PayPalCommercePaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\n new PayPalSdkScriptLoader(getScriptLoader()),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createPayPalCommercePaymentStrategy, [{ id: 'paypalcommerce' }]);\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 ApproveCallbackPayload,\n ClickCallbackActions,\n getPaypalMessagesStylesFromBNPLConfig,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalButtons,\n PayPalButtonsOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalMessagesSdk,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\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?: PayPalButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\n private loadingIndicator: LoadingIndicator,\n private payPalSdkScriptLoader: PayPalSdkScriptLoader,\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 = state.getPaymentMethodOrThrow(methodId);\n\n const { paypalBNPLConfiguration = [], orderId } = paymentMethod.initializationData || {};\n const { bannerContainerId, container } = paypalOptions;\n\n if (bannerContainerId !== undefined) {\n if (!document.getElementById(bannerContainerId)) {\n // eslint-disable-next-line no-console\n console.error('Unable to create banner without valid banner container ID.');\n\n return;\n }\n\n const bannerConfiguration =\n paypalBNPLConfiguration &&\n paypalBNPLConfiguration.find(({ id }) => id === 'checkout');\n\n if (!bannerConfiguration?.status) {\n return;\n }\n\n const paypalMessages = await this.payPalSdkScriptLoader.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n state.getLocale(),\n );\n\n return this.renderMessages(paypalMessages, bannerContainerId, bannerConfiguration);\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.paypalIntegrationService.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.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = 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: PayPalButtonsOptions = {\n fundingSource,\n style: this.paypalIntegrationService.getValidButtonStyle(\n checkoutPaymentButtonStyles,\n ),\n createOrder: () =>\n this.paypalIntegrationService.createOrder('paypalcommercecreditcheckout'),\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 return 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,\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: checkout.outstandingBalance,\n placement: 'payment',\n style: getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\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 {\n createPayPalIntegrationService,\n createPayPalSdkScriptLoader,\n LOADING_INDICATOR_STYLES,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceCreditPaymentStrategy from './paypal-commerce-credit-payment-strategy';\n\nconst createPayPalCommerceCreditPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceCreditPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditPaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n createPayPalSdkScriptLoader(),\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 {\n ApproveCallbackPayload,\n ClickCallbackActions,\n PayPalButtons,\n PayPalButtonsOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\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?: PayPalButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\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 = 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.paypalIntegrationService.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.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = 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: PayPalButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.paypalIntegrationService.getValidButtonStyle(checkoutPaymentButtonStyles),\n createOrder: () =>\n this.paypalIntegrationService.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 return 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 { createPayPalIntegrationService } from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceVenmoPaymentStrategy from './paypal-commerce-venmo-payment-strategy';\n\nconst createPayPalCommerceVenmoPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceVenmoPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceVenmoPaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n\nexport default toResolvableModule(createPayPalCommerceVenmoPaymentStrategy, [\n { id: 'paypalcommercevenmo' },\n]);\n","export const LOADING_INDICATOR_STYLES = {\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\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 TimeoutError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n PayPalApmSdk,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport {\n ApproveCallbackPayload,\n NonInstantAlternativePaymentMethods,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n PayPalOrderStatus,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceAlternativeMethodsPaymentOptions, {\n WithPayPalCommerceAlternativeMethodsPaymentInitializeOptions,\n} from './paypal-commerce-alternative-methods-payment-initialize-options';\n\nconst POLLING_INTERVAL = 3000;\nconst MAX_POLLING_TIME = 300000;\n\nexport default class PayPalCommerceAlternativeMethodsPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n private paypalApms?: PayPalApmSdk;\n private pollingTimer = 0;\n private stopPolling = noop;\n private isOrderApprovedProcessing = false;\n private paypalcommercealternativemethods?: PayPalCommerceAlternativeMethodsPaymentOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalIntegrationService,\n private paypalSdkScriptLoader: PayPalSdkScriptLoader,\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 &\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 this.paypalcommercealternativemethods = paypalcommercealternativemethods;\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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n\n this.isOrderApprovedProcessing = isExperimentEnabled(\n features,\n 'PAYPAL-5431.order_approved_processing',\n false,\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 this.paypalApms = await this.paypalSdkScriptLoader.getPayPalApmsSdk(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n state.getLocale(),\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.isOrderApprovedProcessing && methodId === 'ideal') {\n await new Promise((resolve, reject) => {\n void this.initializePollingMechanism(methodId, resolve, reject, gatewayId);\n });\n }\n\n if (\n !this.isNonInstantPaymentMethod(methodId) ||\n (methodId === NonInstantAlternativePaymentMethods.IDEAL &&\n !this.isOrderApprovedProcessing)\n ) {\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 if (!this.isOrderApprovedProcessing) {\n this.resetPollingMechanism();\n }\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Polling mechanism\n *\n *\n * */\n private async initializePollingMechanism(\n methodId: string,\n resolvePromise: (value?: unknown) => void,\n rejectPromise: (value?: unknown) => 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 gatewayId ?? 'paypalcommerce',\n );\n\n const isOrderApproved = orderStatus === PayPalOrderStatus.Approved;\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 paypalcommercealternativemethods: this.paypalcommercealternativemethods,\n });\n\n this.handleError(new TimeoutError());\n } catch (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 private async reinitializeStrategy(\n options: PaymentInitializeOptions &\n WithPayPalCommerceAlternativeMethodsPaymentInitializeOptions,\n ) {\n await this.deinitialize();\n await this.initialize(options);\n }\n\n private handleError(error: unknown) {\n const { onError } = this.paypalcommercealternativemethods || {};\n\n if (!this.isOrderApprovedProcessing) {\n this.resetPollingMechanism();\n }\n\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\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: () => {\n this.toggleLoadingIndicator(false);\n this.deinitializePollingMechanism();\n },\n onError: (error) => {\n this.deinitializePollingMechanism();\n this.handleFailure(error, onError);\n },\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 (\n this.isNonInstantPaymentMethod(methodId) &&\n ((methodId === NonInstantAlternativePaymentMethods.IDEAL &&\n this.isOrderApprovedProcessing) ||\n methodId === NonInstantAlternativePaymentMethods.OXXO)\n ) {\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\n if (methodId === NonInstantAlternativePaymentMethods.IDEAL) {\n const state = this.paymentIntegrationService.getState();\n const bcOrderId = state.getOrder()?.orderId;\n\n await this.paypalCommerceIntegrationService.updateOrder(\n 'paypalcommercealternativemethods',\n methodId,\n bcOrderId,\n );\n }\n\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 {\n createPayPalIntegrationService,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\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 createPayPalIntegrationService(paymentIntegrationService),\n createPayPalSdkScriptLoader(),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createPayPalCommerceAlternativeMethodsPaymentStrategy, [\n { gateway: 'paypalcommercealternativemethods' },\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 { isPayPalCommerceAcceleratedCheckoutCustomer } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\nimport {\n PayPalFastlaneUtils,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\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 paypalIntegrationService: PayPalIntegrationService,\n private paypalSdkScriptLoader: PayPalSdkScriptLoader,\n private paypalFastlaneUtils: PayPalFastlaneUtils,\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, onLoadComplete } =\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.paypalIntegrationService.loadPayPalSdk(methodId, undefined, true, true);\n\n if (this.isCreditCardForm || this.isCreditCardVaultedForm) {\n await this.initializeFields(form, onCreditCardFieldsRenderingError);\n }\n\n onLoadComplete?.();\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.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n const executeCallback = this.getExecuteCallback(fields);\n\n const cardFieldsConfig: PayPalCommerceCardFieldsConfig = {\n style: this.getInputStyles(styles),\n onApprove: ({\n orderID,\n vaultSetupToken,\n liabilityShift,\n }: PayPalCommerceCardFieldsOnApproveData) => {\n if (\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.paypalIntegrationService.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.paypalIntegrationService.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 = 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 = state.getPaymentMethodOrThrow(methodId);\n const { initializationData } = paymentMethod;\n\n if (!initializationData?.connectClientToken) {\n return;\n }\n\n const payPalFastlaneSdk = await this.paypalSdkScriptLoader.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n state.getLocale(),\n );\n\n await this.paypalFastlaneUtils.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 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 {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalFastlaneUtils,\n createPayPalIntegrationService,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceCreditCardsPaymentStrategy from './paypal-commerce-credit-cards-payment-strategy';\n\nconst createPaypalCommerceCreditCardsPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceCreditCardsPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditCardsPaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\n createPayPalSdkScriptLoader(),\n createPayPalFastlaneUtils(),\n );\n\nexport default toResolvableModule(createPaypalCommerceCreditCardsPaymentStrategy, [\n { id: 'paypalcommercecreditcards' },\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 {\n BirthDate,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalOrderStatus,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\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 paypalCommerceService: PayPalIntegrationService,\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.paypalCommerceService.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.paypalCommerceService.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.paypalCommerceService.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.paypalCommerceService.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 {\n createPayPalIntegrationService,\n LOADING_INDICATOR_STYLES,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PaypalCommerceRatepayPaymentStrategy from './paypal-commerce-ratepay-payment-strategy';\n\nconst createPaypalCommerceRatepayPaymentStrategy: PaymentStrategyFactory<\n PaypalCommerceRatepayPaymentStrategy\n> = (paymentIntegrationService) =>\n new PaypalCommerceRatepayPaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(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 PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n getFastlaneStyles,\n isPayPalFastlaneCustomer,\n isPaypalFastlaneRequestError,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneCardComponentMethods,\n PayPalFastlaneCardComponentOptions,\n PayPalFastlanePaymentFormattedPayload,\n PayPalFastlaneSdk,\n PayPalFastlaneUtils,\n PayPalInitializationData,\n PayPalSdkScriptLoader,\n TDSecureAuthenticationState,\n TDSecureVerificationMethod,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceRequestSender from '../paypal-commerce-request-sender';\nimport { LiabilityShiftEnum } from '../paypal-commerce-types';\n\nimport PayPalCommerceFastlanePaymentInitializeOptions, {\n WithPayPalCommerceFastlanePaymentInitializeOptions,\n} from './paypal-commerce-fastlane-payment-initialize-options';\n\nexport default class PaypalCommerceFastlanePaymentStrategy implements PaymentStrategy {\n private paypalComponentMethods?: PayPalFastlaneCardComponentMethods;\n private paypalFastlaneSdk?: PayPalFastlaneSdk;\n private threeDSVerificationMethod?: string;\n private paypalcommercefastlane?: PayPalCommerceFastlanePaymentInitializeOptions;\n private orderId?: string;\n private methodId?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceRequestSender: PayPalCommerceRequestSender,\n private paypalSdkScriptLoader: PayPalSdkScriptLoader,\n private paypalFastlaneUtils: PayPalFastlaneUtils,\n ) {}\n\n /**\n *\n * Default methods\n *\n * */\n async initialize(\n options: PaymentInitializeOptions & WithPayPalCommerceFastlanePaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommercefastlane } = options;\n\n this.methodId = methodId;\n\n this.paypalcommercefastlane = paypalcommercefastlane;\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 = state.getPaymentMethodOrThrow(methodId);\n const { isDeveloperModeApplicable, isFastlaneStylingEnabled } =\n paymentMethod.initializationData || {};\n\n this.threeDSVerificationMethod =\n paymentMethod.initializationData?.threeDSVerificationMethod;\n\n this.paypalFastlaneSdk = await this.paypalSdkScriptLoader.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n state.getLocale(),\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.paypalFastlaneUtils.initializePayPalFastlane(\n this.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 await this.paymentIntegrationService.submitOrder(order, options);\n\n const paymentPayload = isVaultedFlow\n ? await this.prepareVaultedInstrumentPaymentPayload(methodId, paymentData)\n : await this.preparePaymentPayload(methodId, paymentData);\n\n await this.paymentIntegrationService.submitPayment(\n paymentPayload,\n );\n\n this.paypalFastlaneUtils.removeStorageSessionId();\n } catch (error) {\n if (\n isPaypalFastlaneRequestError(error) &&\n error.response.body.name === 'INVALID_REQUEST'\n ) {\n const invalidRequestError = {\n translationKey: 'payment.errors.invalid_request_error',\n };\n\n this.handleError(invalidRequestError);\n\n return Promise.reject();\n }\n\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.paypalFastlaneUtils.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 } = await this.paypalFastlaneUtils.lookupCustomerOrThrow(\n customerEmail,\n );\n\n const authenticationResult =\n await this.paypalFastlaneUtils.triggerAuthenticationFlowOrThrow(customerContextId);\n\n const { authenticationState, addresses, instruments } =\n this.paypalFastlaneUtils.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 if (isAuthenticationFlowCanceled) {\n this.paypalFastlaneUtils.removeStorageSessionId();\n } else {\n this.paypalFastlaneUtils.updateStorageSessionId(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.paypalFastlaneUtils.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 paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const is3DSEnabled = paymentMethod.config.is3dsEnabled;\n\n const nonce = is3DSEnabled ? await this.get3DSNonce(instrumentId) : instrumentId;\n\n await this.createOrder(nonce);\n\n return {\n methodId,\n paymentData: {\n formattedPayload: {\n paypal_fastlane_token: {\n order_id: this.orderId,\n token: nonce,\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 billingAddress = state.getBillingAddressOrThrow();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\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.paypalFastlaneUtils.mapBcToPayPalAddress(billingAddress),\n });\n\n const is3DSEnabled = paymentMethod.config.is3dsEnabled;\n\n const nonce = is3DSEnabled ? await this.get3DSNonce(id) : id;\n\n await this.createOrder(nonce);\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: this.orderId,\n token: nonce,\n },\n },\n },\n };\n }\n\n private async createOrder(id: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cartId = state.getCartOrThrow().id;\n\n if (this.methodId) {\n const { orderId } = await this.paypalCommerceRequestSender.createOrder(this.methodId, {\n cartId,\n fastlaneToken: id,\n });\n\n this.orderId = orderId;\n }\n }\n\n /**\n *\n * 3DSecure methods\n *\n * */\n private async get3DSNonce(nonce: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const order = state.getOrderOrThrow();\n const checkoutUrl = state.getStoreConfigOrThrow().links.checkoutLink;\n\n const threeDomainSecureComponent = this.paypalFastlaneSdk?.ThreeDomainSecureClient;\n\n if (!threeDomainSecureComponent) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n const threeDomainSecureParameters = {\n amount: order.orderAmount.toFixed(2),\n currency: cart.currency.code,\n nonce,\n threeDSRequested: this.threeDSVerificationMethod === TDSecureVerificationMethod.Always,\n transactionContext: {\n experience_context: {\n locale: 'en-US',\n return_url: checkoutUrl,\n cancel_url: checkoutUrl,\n },\n },\n };\n\n const isThreeDomainSecureEligible = await threeDomainSecureComponent.isEligible(\n threeDomainSecureParameters,\n );\n\n if (\n this.threeDSVerificationMethod === TDSecureVerificationMethod.Always &&\n !isThreeDomainSecureEligible\n ) {\n throw new PaymentMethodInvalidError();\n }\n\n if (isThreeDomainSecureEligible) {\n const {\n liabilityShift,\n authenticationState,\n nonce: threeDSNonce,\n } = await threeDomainSecureComponent.show();\n\n if (\n liabilityShift === LiabilityShiftEnum.No ||\n liabilityShift === LiabilityShiftEnum.Unknown ||\n authenticationState === TDSecureAuthenticationState.Errored ||\n authenticationState === TDSecureAuthenticationState.Cancelled\n ) {\n throw new PaymentMethodInvalidError();\n }\n\n if (\n authenticationState === TDSecureAuthenticationState.Succeeded &&\n [LiabilityShiftEnum.Yes, LiabilityShiftEnum.Possible].includes(liabilityShift)\n ) {\n return threeDSNonce;\n }\n\n throw new PaymentMethodInvalidError();\n }\n\n return nonce;\n }\n\n /**\n *\n * PayPal Fastlane instrument change\n *\n */\n private async handlePayPalStoredInstrumentChange(\n methodId: string,\n ): Promise {\n const paypalAxoSdk = this.paypalFastlaneUtils.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.paypalFastlaneUtils.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 private handleError(error: unknown): void {\n if (\n this.paypalcommercefastlane?.onError &&\n typeof this.paypalcommercefastlane.onError === 'function'\n ) {\n this.paypalcommercefastlane.onError(error);\n }\n }\n}\n","export interface PaypalFastlaneRequestError {\n name: string;\n message: string;\n response: {\n body: {\n name: string;\n };\n };\n}\n\nexport default function isPaypalFastlaneRequestError(\n error: unknown,\n): error is PaypalFastlaneRequestError {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'message' in error &&\n 'response' in error &&\n 'body' in (error as PaypalFastlaneRequestError).response &&\n 'name' in (error as PaypalFastlaneRequestError).response.body\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 createPayPalFastlaneUtils,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-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 createPayPalSdkScriptLoader(),\n createPayPalFastlaneUtils(),\n );\n};\n\nexport default toResolvableModule(createPayPalCommerceFastlanePaymentStrategy, [\n { id: 'paypalcommerceacceleratedcheckout' }, // PayPal Fastlane relates to 'paypalcommerceacceleratedcheckout' method id\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 enum PaymentStatusTypes {\n ACKNOWLEDGE = 'ACKNOWLEDGE',\n FINALIZE = 'FINALIZE',\n INITIALIZE = 'INITIALIZE',\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 { noop } from 'lodash';\n\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithPaypalExpressPaymentInitializeOptions } from './paypal-express-payment-initialize-options';\nimport PaypalScriptLoader from './paypal-express-script-loader';\nimport { PaymentStatusTypes, PaypalHostWindow, PaypalSDK } from './paypal-express-types';\n\nexport default class PaypalExpressPaymentStrategy implements PaymentStrategy {\n private paypalSdk?: PaypalSDK;\n private paymentMethod?: PaymentMethod;\n private useRedirectFlow = false;\n private window: PaypalHostWindow;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: PaypalScriptLoader,\n ) {\n this.window = window;\n }\n\n async initialize(\n options: PaymentInitializeOptions & WithPaypalExpressPaymentInitializeOptions,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n\n this.paymentMethod = state.getPaymentMethodOrThrow(options.methodId);\n this.useRedirectFlow =\n (options.paypalexpress && options.paypalexpress.useRedirectFlow) === true;\n\n const merchantId = this.paymentMethod.config.merchantId;\n\n if (!this.isInContextEnabled() || !merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const paypalSdk = await this.scriptLoader.loadPaypalSDK();\n\n this.paypalSdk = paypalSdk;\n\n this.paypalSdk.checkout.setup(merchantId, {\n button: 'paypal-button',\n environment: this.paymentMethod.config.testMode ? 'sandbox' : 'production',\n });\n }\n\n deinitialize() {\n if (this.isInContextEnabled() && this.paypalSdk) {\n this.paypalSdk.checkout.closeFlow();\n this.paypalSdk = undefined;\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions) {\n let state: PaymentIntegrationSelectors;\n let redirectUrl: string | undefined;\n const paypal = this.paypalSdk;\n\n if (this.isAcknowledgedOrFinalized()) {\n await this.paymentIntegrationService.submitOrder(payload, options);\n\n return;\n }\n\n if (!this.isInContextEnabled() || this.useRedirectFlow) {\n state = await this.paymentIntegrationService.submitOrder(payload, options);\n redirectUrl = state.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 if (!paypal) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n paypal.checkout.initXO();\n\n try {\n state = await this.paymentIntegrationService.submitOrder(payload, options);\n } catch (error) {\n paypal.checkout.closeFlow();\n\n return Promise.reject(error);\n }\n\n redirectUrl = state.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\n async finalize(options?: PaymentRequestOptions) {\n const state = this.paymentIntegrationService.getState();\n const order = state.getOrder();\n\n if (order && this.isAcknowledgedOrFinalized()) {\n await this.paymentIntegrationService.finalizeOrder(options);\n\n return Promise.resolve();\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private isAcknowledgedOrFinalized(): boolean {\n const state = this.paymentIntegrationService.getState();\n\n return (\n state.getPaymentStatus() === PaymentStatusTypes.ACKNOWLEDGE ||\n state.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 '@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 { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PaypalExpressPaymentStrategy from './paypal-express-payment-strategy';\nimport PaypalExpressScriptLoader from './paypal-express-script-loader';\n\nconst createPaypalExpressPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new PaypalExpressPaymentStrategy(\n paymentIntegrationService,\n new PaypalExpressScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createPaypalExpressPaymentStrategy, [\n { id: 'paypalexpress', type: 'PAYMENT_TYPE_HOSTED' },\n { id: 'paypalexpresscredit', type: 'PAYMENT_TYPE_HOSTED' },\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 { 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 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new Promise(() => {\n this.redirectUrl(redirect_url);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }) as any;\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 { 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 ('errors' in result && 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(methodId, 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(methodId: string, shouldSaveInstrument?: boolean) {\n const { getPaymentMethodOrThrow } = this._paymentIntegrationService.getState();\n const { initializationData } = getPaymentMethodOrThrow(methodId);\n\n const cardTokenizationResult = await this._squareV2PaymentProcessor.tokenize();\n\n if (\n initializationData && 'isSquareV2ApiV2Enabled' in initializationData\n ? !initializationData.isSquareV2ApiV2Enabled\n : !this.shouldVerify()\n ) {\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 { getPaymentMethodOrThrow } = this._paymentIntegrationService.getState();\n const { initializationData } = getPaymentMethodOrThrow(methodId);\n\n const { instrumentId } = paymentData;\n const shouldVerify =\n initializationData && 'isSquareV2ApiV2Enabled' in initializationData\n ? initializationData.isSquareV2ApiV2Enabled\n : this.shouldVerify();\n const verificationToken = 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 PaymentStrategy,\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 allow_redisplay?: 'always' | 'limited' | 'unspecified';\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 allowRedisplayForStoredInstruments?: 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 private _allowRedisplayForStoredInstruments?: 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 allowRedisplayForStoredInstruments,\n },\n } = paymentMethod as StripeV3PaymentMethod;\n\n this._allowRedisplayForStoredInstruments = allowRedisplayForStoredInstruments;\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 const shouldAllowRedisplay = this._allowRedisplayForStoredInstruments;\n\n return this.getStripeJs().createPaymentMethod({\n type: StripePaymentMethodType.CreditCard,\n card,\n billing_details: billingDetails,\n ...(shouldAllowRedisplay ? { allow_redisplay: 'always' } : {}),\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","export const supportedLocales: Record = {\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-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 { merge, 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 PaymentRequestOptions,\n PaymentStrategy,\n RequestError,\n StripeUPEIntent,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n formatStripeLocale,\n isStripePaymentMethodLike,\n STRIPE_UPE_CLIENT_API_VERSION,\n STRIPE_UPE_CLIENT_BETAS,\n StripeAdditionalActionRequired,\n StripeAppearanceOptions,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeElementUpdateOptions,\n StripeEventType,\n StripeFormattedPaymentPayload,\n StripeInitializationData,\n StripeIntegrationService,\n StripeJsVersion,\n StripePaymentMethodType,\n StripeResult,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport isStripeAcceleratedCheckoutCustomer from './is-stripe-accelerated-checkout-customer';\nimport StripeUPEPaymentInitializeOptions, {\n WithStripeUPEPaymentInitializeOptions,\n} from './stripe-upe-initialize-options';\n\nexport default class StripeUPEPaymentStrategy implements PaymentStrategy {\n private _stripeUPEClient?: StripeClient;\n private _stripeElements?: StripeElements;\n private _isStripeElementUpdateEnabled?: boolean;\n private _allowRedisplayForStoredInstruments?: boolean;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n private stripeIntegrationService: StripeIntegrationService,\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.stripeIntegrationService.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.stripeIntegrationService.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 await this.paymentIntegrationService.submitOrder(order, options);\n\n if (isVaultedInstrument(paymentData)) {\n const { instrumentId } = paymentData;\n\n await this._executeWithVaulted(\n payment.methodId,\n instrumentId,\n shouldSetAsDefaultInstrument,\n );\n\n return;\n }\n\n await this._executeWithStripeConfirmation(\n payment.methodId,\n payment.gatewayId,\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.stripeIntegrationService.deinitialize();\n this._stripeElements = undefined;\n this._stripeUPEClient = undefined;\n\n return Promise.resolve();\n }\n\n private async _executeWithStripeConfirmation(\n methodId: string,\n gatewayId?: 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 gatewayId,\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\n if (!isStripePaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { clientToken, initializationData } = paymentMethod;\n const {\n shopperLanguage,\n allowRedisplayForStoredInstruments = false,\n enableLink,\n } = initializationData;\n\n this._allowRedisplayForStoredInstruments = allowRedisplayForStoredInstruments;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._stripeUPEClient = await this._loadStripeJs(initializationData);\n this._isStripeElementUpdateEnabled = typeof initStripeElementUpdateTrigger === 'function';\n\n let appearance: StripeAppearanceOptions | undefined;\n\n if (style) {\n const styles = style;\n\n appearance = {\n variables: this.stripeIntegrationService.mapAppearanceVariables(style),\n rules: {\n '.Input': this.stripeIntegrationService.mapInputAppearanceRules(styles),\n },\n };\n }\n\n this._stripeElements = await this.scriptLoader.getElements(this._stripeUPEClient, {\n clientSecret: clientToken,\n locale: formatStripeLocale(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 link: enableLink ? StripeStringConstants.AUTO : StripeStringConstants.NEVER,\n },\n ...this._getStripeElementTerms(),\n });\n\n this.stripeIntegrationService.mountElement(stripeElement, containerId);\n\n stripeElement.on(StripeElementEvent.READY, () => {\n render();\n });\n\n stripeElement.on(StripeElementEvent.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 gatewayId?: string,\n shouldSaveInstrument = false,\n shouldSetAsDefaultInstrument = false,\n ): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.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, error: stripeError } = 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 if (stripeError || !paymentIntent) {\n const { initializationData } = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n const { sendSecondPaymentRequestOnStripeError } = initializationData || {};\n\n if (sendSecondPaymentRequestOnStripeError) {\n // INFO: even in case when stripe payment confirmation was declined\n // we need to send submitPayment request to update status of checkout session on BE side.\n try {\n const paymentPayloadWithError = merge({}, paymentPayload, {\n paymentData: {\n formattedPayload: {\n client_side_error: true,\n },\n },\n });\n\n await this.paymentIntegrationService.submitPayment(paymentPayloadWithError);\n } catch {\n // INFO: additional action should be ignored for this update status request.\n // will throw Stripe error message to the shopper.\n }\n }\n\n this.stripeIntegrationService.throwStripeError(stripeError);\n }\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n methodId: string,\n additionalActionData: StripeAdditionalActionRequired['data'],\n ): Promise {\n if (!this._stripeUPEClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeIntegrationService.mapStripePaymentData(\n this._stripeElements,\n redirect_url,\n !!this._allowRedisplayForStoredInstruments,\n );\n\n const isPaymentCompleted = await this.stripeIntegrationService.isPaymentCompleted(\n methodId,\n this._stripeUPEClient,\n );\n\n return !isPaymentCompleted\n ? this._stripeUPEClient.confirmPayment(stripePaymentData)\n : this._stripeUPEClient.retrievePaymentIntent(token || '');\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.stripeIntegrationService.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 initializationData: StripeInitializationData,\n ): Promise {\n if (this._stripeUPEClient) {\n return this._stripeUPEClient;\n }\n\n const state = this.paymentIntegrationService.getState();\n\n return this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n StripeJsVersion.V3,\n STRIPE_UPE_CLIENT_BETAS,\n STRIPE_UPE_CLIENT_API_VERSION,\n );\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';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeUPEPaymentStrategy from './stripe-upe-payment-strategy';\n\nconst createStripeUPEPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n\n return new StripeUPEPaymentStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n );\n};\n\nexport default toResolvableModule(createStripeUPEPaymentStrategy, [\n { gateway: 'stripeupe' },\n { gateway: 'stripeupe', id: 'klarna' },\n]);\n","import { StripePaymentEvent } from './stripe';\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 { merge } from 'lodash';\n\nimport {\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 PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n isStripePaymentEvent,\n isStripePaymentMethodLike,\n StripeAdditionalActionRequired,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElements,\n StripeElementType,\n StripeEventType,\n StripeFormattedPaymentPayload,\n StripeInitializationData,\n StripeInstrumentSetupFutureUsage,\n StripeIntegrationService,\n StripePIPaymentMethodOptions,\n StripePIPaymentMethodSavingOptions,\n StripeResult,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeOCSPaymentInitializeOptions, {\n WithStripeOCSPaymentInitializeOptions,\n} from './stripe-ocs-initialize-options';\n\nexport default class StripeOCSPaymentStrategy implements PaymentStrategy {\n private stripeClient?: StripeClient;\n private stripeElements?: StripeElements;\n private selectedMethodId?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n private stripeIntegrationService: StripeIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithStripeOCSPaymentInitializeOptions,\n ): Promise {\n const { stripeocs, methodId, gatewayId } = options;\n\n if (!stripeocs?.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(stripeocs, gatewayId, methodId);\n } catch (error) {\n if (error instanceof Error) {\n stripeocs.onError?.(error);\n }\n }\n\n this.stripeIntegrationService.initCheckoutEventsSubscription(\n gatewayId,\n methodId,\n stripeocs,\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.stripeClient) {\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 { isStoreCreditApplied } = this.paymentIntegrationService\n .getState()\n .getCheckoutOrThrow();\n\n if (isStoreCreditApplied) {\n await this.paymentIntegrationService.applyStoreCredit(isStoreCreditApplied);\n }\n\n await this.stripeIntegrationService.updateStripePaymentIntent(gatewayId, methodId);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n const { clientToken } = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n\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, gatewayId);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n const paymentElement = this.stripeElements?.getElement(StripeElementType.PAYMENT);\n\n paymentElement?.unmount();\n paymentElement?.destroy();\n this.stripeIntegrationService.deinitialize();\n this.stripeElements = undefined;\n this.stripeClient = undefined;\n\n return Promise.resolve();\n }\n\n private async _initializeStripeElement(\n stripe: StripeOCSPaymentInitializeOptions,\n gatewayId: string,\n methodId: string,\n ) {\n let paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n\n if (!paymentMethod?.clientToken) {\n const state = await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n\n paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n }\n\n if (!isStripePaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { clientToken, initializationData } = paymentMethod;\n const { customerSessionToken, enableLink } = initializationData;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.stripeClient = await this._loadStripeJs(initializationData);\n\n const {\n appearance,\n containerId,\n fonts,\n layout,\n render,\n paymentMethodSelect,\n handleClosePaymentMethod,\n togglePreloader,\n } = stripe;\n\n this.stripeElements = await this.scriptLoader.getElements(this.stripeClient, {\n clientSecret: clientToken,\n customerSessionClientSecret: customerSessionToken,\n appearance,\n fonts,\n });\n\n const { getBillingAddress, getShippingAddress } = this.paymentIntegrationService.getState();\n const billingAddress = getBillingAddress();\n const { postalCode } = getShippingAddress() || billingAddress || {};\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 link: enableLink ? StripeStringConstants.AUTO : StripeStringConstants.NEVER,\n },\n layout,\n savePaymentMethod: {\n maxVisiblePaymentMethods: 20,\n },\n defaultValues: {\n billingDetails: {\n email: billingAddress?.email || '',\n },\n },\n });\n\n this.stripeIntegrationService.mountElement(stripeElement, containerId);\n\n stripeElement.on(StripeElementEvent.LOADER_START, () => {\n togglePreloader?.(false);\n });\n\n stripeElement.on(StripeElementEvent.READY, () => {\n render();\n });\n\n stripeElement.on(StripeElementEvent.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 initializationData: StripeInitializationData,\n ): Promise {\n if (this.stripeClient) {\n return this.stripeClient;\n }\n\n const state = this.paymentIntegrationService.getState();\n const stripeJsVersion =\n this.stripeIntegrationService.getStripeJsVersion(initializationData);\n\n return this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n stripeJsVersion,\n );\n }\n\n private _collapseStripeElement() {\n const stripeElement = this.stripeElements?.getElement(StripeElementType.PAYMENT);\n\n stripeElement?.collapse();\n }\n\n private _getPaymentPayload(\n methodId: string,\n token: string,\n paymentMethodOptions?: StripePIPaymentMethodOptions,\n ): Payment {\n const cartId = this.paymentIntegrationService.getState().getCart()?.id || '';\n const { card, us_bank_account } = paymentMethodOptions || {};\n const shouldSaveInstrument =\n this._shouldSaveInstrument(card) || this._shouldSaveInstrument(us_bank_account);\n const tokenizedOptions = this._getTokenizedOptions(token, paymentMethodOptions);\n\n const formattedPayload = {\n cart_id: cartId,\n confirm: false,\n method: this.selectedMethodId,\n vault_payment_instrument: shouldSaveInstrument,\n ...tokenizedOptions,\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 gatewayId: string,\n ): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n if (!this.stripeClient || !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, error: stripeError } = await this._confirmStripePaymentOrThrow(\n methodId,\n additionalActionData,\n );\n const {\n client_secret: paymentIntentClientSecret,\n payment_method_options: paymentMethodOptions,\n } = paymentIntent || {};\n\n const paymentPayload = this._getPaymentPayload(\n methodId,\n paymentIntentClientSecret || token,\n paymentMethodOptions,\n );\n\n if (stripeError || !paymentIntent) {\n const { initializationData } = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n const { sendSecondPaymentRequestOnStripeError } = initializationData || {};\n\n if (sendSecondPaymentRequestOnStripeError) {\n // INFO: even in case when stripe payment confirmation was declined\n // we need to send submitPayment request to update status of checkout session on BE side.\n try {\n const paymentPayloadWithError = merge({}, paymentPayload, {\n paymentData: {\n formattedPayload: {\n client_side_error: true,\n },\n },\n });\n\n await this.paymentIntegrationService.submitPayment(paymentPayloadWithError);\n } catch {\n // INFO: additional action should be ignored for this update status request.\n // will throw Stripe error message to the shopper.\n }\n }\n\n this.stripeIntegrationService.throwStripeError(stripeError);\n }\n\n try {\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n methodId: string,\n additionalActionData: StripeAdditionalActionRequired['data'],\n ): Promise {\n if (!this.stripeClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeIntegrationService.mapStripePaymentData(\n this.stripeElements,\n redirect_url,\n );\n\n const isPaymentCompleted = await this.stripeIntegrationService.isPaymentCompleted(\n methodId,\n this.stripeClient,\n );\n\n return !isPaymentCompleted\n ? this.stripeClient.confirmPayment(stripePaymentData)\n : this.stripeClient.retrievePaymentIntent(token || '');\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 private _shouldSaveInstrument(paymentMethodOptions?: StripePIPaymentMethodSavingOptions) {\n const setupFutureUsage = paymentMethodOptions?.setup_future_usage;\n\n return (\n setupFutureUsage === StripeInstrumentSetupFutureUsage.ON_SESSION ||\n setupFutureUsage === StripeInstrumentSetupFutureUsage.OFF_SESSION\n );\n }\n\n private _getTokenizedOptions(\n token: string,\n paymentMethodOptions?: StripePIPaymentMethodOptions,\n ) {\n if (this._shouldSaveInstrument(paymentMethodOptions?.us_bank_account)) {\n return { tokenized_ach: { token } };\n }\n\n return { credit_card_token: { token } };\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeOCSPaymentStrategy from './stripe-ocs-payment-strategy';\n\nconst createStripeOCSPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n\n return new StripeOCSPaymentStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n );\n};\n\nexport default toResolvableModule(createStripeOCSPaymentStrategy, [\n { gateway: 'stripeocs', id: 'optimized_checkout' },\n]);\n","import { merge } from 'lodash';\n\nimport {\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 PaymentMethod,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n isStripePaymentEvent,\n StripeAdditionalActionRequired,\n StripeCheckoutInstance,\n StripeCheckoutSession,\n StripeCheckoutSessionActionResult,\n StripeCheckoutSessionActions,\n StripeCheckoutSessionPaymentStatus,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElementsCreateOptions,\n StripeEventType,\n StripeFormattedPaymentPayload,\n StripeInitializationData,\n StripeIntegrationService,\n StripeJsVersion,\n StripePaymentMethodType,\n StripeSavedPaymentMethod,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeOCSPaymentInitializeOptions, {\n WithStripeOCSPaymentInitializeOptions,\n} from '../stripe-ocs/stripe-ocs-initialize-options';\n\nexport default class StripeCSPaymentStrategy implements PaymentStrategy {\n private stripeClient?: StripeClient;\n private stripeCheckout?: StripeCheckoutInstance;\n private selectedMethodId?: string;\n\n constructor(\n private readonly paymentIntegrationService: PaymentIntegrationService,\n private readonly scriptLoader: StripeScriptLoader,\n private readonly stripeIntegrationService: StripeIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithStripeOCSPaymentInitializeOptions,\n ): Promise {\n const { stripeocs, methodId, gatewayId } = options;\n\n if (!stripeocs?.containerId || !gatewayId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n let paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n\n if (!paymentMethod?.clientToken) {\n await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n\n paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n }\n\n try {\n await this._initStripeCheckoutSession(stripeocs, paymentMethod);\n await this._updateStripeShopperData();\n this._initializePaymentElement(stripeocs, paymentMethod);\n this._initializeAdaptivePricingElement(stripeocs, paymentMethod);\n } catch (error) {\n if (error instanceof Error) {\n stripeocs.onError?.(error);\n }\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.stripeClient) {\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._updateCheckoutSessionData(gatewayId, methodId);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n const { clientToken } = state.getPaymentMethodOrThrow(methodId, gatewayId);\n const paymentPayload = this._getPaymentPayload(methodId, clientToken || '');\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._processAdditionalAction(error, gatewayId, methodId);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n const paymentElement = this.stripeCheckout?.getPaymentElement();\n const currencySelectorElement = this.stripeCheckout?.getCurrencySelectorElement();\n\n paymentElement?.unmount();\n paymentElement?.destroy();\n currencySelectorElement?.unmount();\n currencySelectorElement?.destroy();\n this.stripeCheckout = undefined;\n this.stripeClient = undefined;\n this.selectedMethodId = undefined;\n\n return Promise.resolve();\n }\n\n private async _initStripeCheckoutSession(\n stripe: StripeOCSPaymentInitializeOptions,\n paymentMethod: PaymentMethod,\n ): Promise {\n const { clientToken, initializationData } = paymentMethod;\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.stripeClient = await this._loadStripeJs(initializationData);\n\n const { appearance, fonts } = stripe;\n\n this.stripeCheckout = await this.scriptLoader.getStripeCheckout(this.stripeClient, {\n clientSecret: clientToken,\n elementsOptions: {\n appearance,\n fonts,\n },\n adaptivePricing: {\n allowed: !!initializationData?.adaptivePricingEnabled,\n },\n });\n }\n\n private _initializePaymentElement(\n stripe: StripeOCSPaymentInitializeOptions,\n paymentMethod: PaymentMethod,\n ) {\n const { initializationData, id: methodId, gateway } = paymentMethod;\n\n const { enableLink } = initializationData || {};\n const {\n containerId,\n layout,\n render,\n paymentMethodSelect,\n handleClosePaymentMethod,\n togglePreloader,\n } = stripe;\n\n const stripeElement = this._getStripeElement({\n fields: {\n billingDetails: {\n email: StripeStringConstants.NEVER,\n name: StripeStringConstants.NEVER,\n address: StripeStringConstants.NEVER,\n },\n },\n wallets: {\n applePay: StripeStringConstants.NEVER,\n googlePay: StripeStringConstants.NEVER,\n link: enableLink ? StripeStringConstants.AUTO : StripeStringConstants.NEVER,\n },\n layout,\n });\n\n if (!stripeElement || !gateway) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this.stripeIntegrationService.mountElement(stripeElement, containerId);\n\n stripeElement.on(StripeElementEvent.LOADER_START, () => {\n togglePreloader?.(false);\n });\n\n stripeElement.on(StripeElementEvent.READY, () => {\n render();\n });\n\n stripeElement.on(StripeElementEvent.CHANGE, (event: StripeEventType) => {\n this._onStripeElementChange(event, gateway, methodId, paymentMethodSelect);\n });\n\n handleClosePaymentMethod?.(this._collapseStripeElement.bind(this));\n }\n\n private async _loadStripeJs(\n initializationData: StripeInitializationData,\n ): Promise {\n if (this.stripeClient) {\n return this.stripeClient;\n }\n\n const state = this.paymentIntegrationService.getState();\n\n return this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n StripeJsVersion.CLOVER,\n );\n }\n\n private async _getStripeActionsOrThrow(): Promise {\n if (!this.stripeCheckout) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { actions, error } = await this.stripeCheckout.loadActions();\n\n if (!actions || error) {\n throw new PaymentMethodFailedError(error?.message);\n }\n\n return actions;\n }\n\n private _getStripeElement(options?: StripeElementsCreateOptions): StripeElement | undefined {\n return (\n this.stripeCheckout?.getPaymentElement() ||\n this.stripeCheckout?.createPaymentElement(options)\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 private _collapseStripeElement() {\n const stripeElement = this.stripeCheckout?.getPaymentElement();\n\n stripeElement?.collapse();\n }\n\n private async _updateCheckoutSessionData(gatewayId: string, methodId: string): Promise {\n await this._updateStripeShopperData();\n\n // INFO: to trigger checkout session data update on the BE side we need to make stripe config request\n await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n }\n\n private _getPaymentPayload(\n methodId: string,\n token: string,\n newVaultedStripeInstrument?: StripeSavedPaymentMethod,\n ): Payment {\n const cartId = this.paymentIntegrationService.getState().getCart()?.id || '';\n const tokenizedOptions = this._getTokenizedOptions(token, newVaultedStripeInstrument);\n\n const formattedPayload = {\n cart_id: cartId,\n confirm: false,\n method: this.selectedMethodId,\n vault_payment_instrument: !!newVaultedStripeInstrument,\n ...tokenizedOptions,\n };\n\n return {\n methodId,\n paymentData: {\n formattedPayload,\n },\n };\n }\n\n private async _processAdditionalAction(\n error: unknown,\n gatewayId: string,\n methodId: string,\n ): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n const { data: additionalActionData } = error.body?.additional_action_required || {};\n const { token } = additionalActionData || {};\n const existingStripeSavedPaymentMethods = await this._getStripeSavedPaymentMethodsOrThrow();\n const { session: stripeCheckoutSession, error: stripeError } =\n await this._confirmStripePayment(additionalActionData);\n const newStripeSavedPaymentMethods = await this._getStripeSavedPaymentMethodsOrThrow(\n stripeCheckoutSession,\n );\n const { id: checkoutSessionId, status: checkoutSessionStatus } =\n stripeCheckoutSession || {};\n const newVaultedStripeInstrument = this._getNewVaultedStripeInstrument(\n existingStripeSavedPaymentMethods,\n newStripeSavedPaymentMethods,\n );\n const paymentPayload = this._getPaymentPayload(\n methodId,\n checkoutSessionId || token,\n newVaultedStripeInstrument,\n );\n const { initializationData } = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n const { sendSecondPaymentRequestOnStripeError } = initializationData || {};\n\n if (stripeError || !stripeCheckoutSession) {\n if (sendSecondPaymentRequestOnStripeError) {\n // INFO: even in case when stripe payment confirmation was declined\n // we need to send submitPayment request to update status of checkout session on BE side.\n try {\n const paymentPayloadWithError = merge({}, paymentPayload, {\n paymentData: {\n formattedPayload: {\n client_side_error: true,\n },\n },\n });\n\n await this.paymentIntegrationService.submitPayment(paymentPayloadWithError);\n } catch {\n // INFO: additional action should be ignored for this update status request.\n // will throw Stripe error message to the shopper.\n }\n }\n\n throw new PaymentMethodFailedError(stripeError?.message);\n }\n\n try {\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n if (checkoutSessionStatus?.paymentStatus === StripeCheckoutSessionPaymentStatus.Paid) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n }\n\n throw error;\n }\n }\n\n private async _confirmStripePayment(\n additionalActionData: StripeAdditionalActionRequired['data'],\n ): Promise {\n const { redirect_url } = additionalActionData || {};\n\n if (!this.stripeCheckout) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const stripeActions = await this._getStripeActionsOrThrow();\n\n return stripeActions.confirm({\n redirect: StripeStringConstants.IF_REQUIRED,\n returnUrl: redirect_url,\n });\n }\n\n private async _updateStripeShopperData(): Promise {\n const stripeActions = await this._getStripeActionsOrThrow();\n\n await this._updateStripeEmail(stripeActions);\n await this._updateStripeShippingAddress(stripeActions);\n await this._updateStripeBillingAddress(stripeActions);\n }\n\n private async _updateStripeEmail(stripeActions: StripeCheckoutSessionActions): Promise {\n const stripeCheckoutSession = await stripeActions.getSession();\n\n if (stripeCheckoutSession.email) {\n return;\n }\n\n const { getBillingAddress } = this.paymentIntegrationService.getState();\n const billingAddress = getBillingAddress();\n\n await stripeActions.updateEmail(billingAddress?.email || '');\n }\n\n private async _updateStripeShippingAddress(\n stripeActions: StripeCheckoutSessionActions,\n ): Promise {\n const shippingAddress = this.paymentIntegrationService.getState().getShippingAddress();\n\n if (!shippingAddress) {\n return;\n }\n\n await stripeActions.updateShippingAddress({\n name: this.stripeIntegrationService.getShopperFullName(shippingAddress),\n address: this.stripeIntegrationService.mapStripeAddress(shippingAddress),\n });\n }\n\n private async _updateStripeBillingAddress(\n stripeActions: StripeCheckoutSessionActions,\n ): Promise {\n const billingAddress = this.paymentIntegrationService.getState().getBillingAddress();\n\n if (!billingAddress) {\n return;\n }\n\n await stripeActions.updateBillingAddress({\n name: this.stripeIntegrationService.getShopperFullName(billingAddress),\n address: this.stripeIntegrationService.mapStripeAddress(billingAddress),\n });\n }\n\n private async _getStripeSavedPaymentMethodsOrThrow(\n stripeCheckoutSession?: StripeCheckoutSession,\n ): Promise {\n if (stripeCheckoutSession?.savedPaymentMethods) {\n return stripeCheckoutSession.savedPaymentMethods;\n }\n\n const stripeActions = await this._getStripeActionsOrThrow();\n const { savedPaymentMethods } = await stripeActions.getSession();\n\n return savedPaymentMethods || [];\n }\n\n private _getNewVaultedStripeInstrument(\n existingStripeSavedPaymentMethods: StripeSavedPaymentMethod[],\n newStripeSavedPaymentMethods: StripeSavedPaymentMethod[],\n ): StripeSavedPaymentMethod | undefined {\n return newStripeSavedPaymentMethods.find(\n (method: StripeSavedPaymentMethod) =>\n !existingStripeSavedPaymentMethods.some(\n (existingMethod: StripeSavedPaymentMethod) => existingMethod.id === method.id,\n ),\n );\n }\n\n private _getTokenizedOptions(\n token: string,\n newVaultedStripeInstrument?: StripeSavedPaymentMethod,\n ) {\n if (newVaultedStripeInstrument?.type === StripePaymentMethodType.ACH) {\n return { tokenized_ach: { token } };\n }\n\n return { credit_card_token: { token } };\n }\n\n private _initializeAdaptivePricingElement(\n stripe: StripeOCSPaymentInitializeOptions,\n paymentMethod: PaymentMethod,\n ): void {\n const { initializationData } = paymentMethod;\n const { currencySelectorContainerId } = stripe;\n\n if (!initializationData?.adaptivePricingEnabled) {\n return;\n }\n\n if (!currencySelectorContainerId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const currencySelectorElement = this._getCurrencySelectorElement();\n\n if (!currencySelectorElement) {\n return;\n }\n\n currencySelectorElement.mount(`#${currencySelectorContainerId}`);\n\n this._initAdaptivePricingEvents(currencySelectorElement);\n }\n\n private _getCurrencySelectorElement(): StripeElement | undefined {\n return (\n this.stripeCheckout?.getCurrencySelectorElement() ||\n this.stripeCheckout?.createCurrencySelectorElement()\n );\n }\n\n private _initAdaptivePricingEvents(currencySelectorElement: StripeElement): void {\n currencySelectorElement.on(StripeElementEvent.CHANGE, async (event: StripeEventType) => {\n if (!event.value || !('currency' in event.value)) {\n return;\n }\n\n const { currency } = this.paymentIntegrationService.getState().getCartOrThrow();\n const currencyCode = currency.code.toLowerCase();\n const stripeCurrencyCode = event.value.currency.toLowerCase();\n\n await this.paymentIntegrationService.updatePaymentProviderCustomer({\n isCustomerCurrencySelected: currencyCode !== stripeCurrencyCode,\n customerCurrency: stripeCurrencyCode,\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';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeCSPaymentStrategy from './stripe-cs-payment-strategy';\n\nconst createStripeCSPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n\n return new StripeCSPaymentStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n );\n};\n\nexport default toResolvableModule(createStripeCSPaymentStrategy, [\n { gateway: 'stripeocs', id: 'checkout_session' },\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';\nimport { isBaseInstrument } from '@bigcommerce/checkout-sdk/utility';\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 findInstrument = instruments?.find(\n (instrument) => isBaseInstrument(instrument) && instrument.bigpayToken === instrumentId,\n );\n const trustedShippingAddress = isBaseInstrument(findInstrument)\n ? findInstrument.trustedShippingAddress\n : {};\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 messageEventListener = async (event: MessageEvent) => {\n if (event.origin.indexOf('cardinalcommerce.com') === -1) {\n return;\n }\n\n if (typeof event.data !== 'string' || !this._isValidJsonWithSessionId(event.data)) {\n return reject(new Error(PAYMENT_CANNOT_CONTINUE));\n }\n\n window.removeEventListener('message', messageEventListener);\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', messageEventListener);\n\n let iframeHidden: HTMLIFrameElement;\n\n try {\n iframeHidden = this._createHiddenIframe(error.body);\n } catch (e) {\n window.removeEventListener('message', messageEventListener);\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 && data.Status) {\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, [\n { gateway: 'worldpayaccess', id: 'credit_card' },\n { id: 'worldpayaccess' },\n]);\n","import {\n isHostedInstrumentLike,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WorldpayAccessRedirectResponse } from './worldpayaccess-payment-options';\n\nexport default class WorldpayAccessOpenBankingPaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute({ payment }: OrderRequestBody): Promise {\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n await this._paymentIntegrationService.submitOrder();\n\n try {\n await this._paymentIntegrationService.submitPayment(\n this._buildOpenBankingSubmitPayment(payment),\n );\n } catch (error) {\n if (this._isWorldpayAccessRedirectResponse(error)) {\n const redirectUrl = error.body.additional_action_required.data.redirect_url;\n\n return new Promise(() => window.location.replace(redirectUrl));\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 _buildOpenBankingSubmitPayment(payment: OrderPaymentRequestBody): Payment {\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = isHostedInstrumentLike(\n payment.paymentData,\n )\n ? payment.paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n return {\n ...payment,\n paymentData: {\n formattedPayload: {\n open_banking: {},\n vault_payment_instrument: shouldSaveInstrument || false,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || false,\n },\n },\n };\n }\n\n private _isWorldpayAccessRedirectResponse(\n response: unknown,\n ): response is WorldpayAccessRedirectResponse {\n if (typeof response !== 'object' || response === null) {\n return false;\n }\n\n const partialResponse = response as Partial;\n\n if (!partialResponse.body) {\n return false;\n }\n\n const partialBody = partialResponse.body as {\n status?: string;\n additional_action_required?: {\n data?: { redirect_url?: string };\n };\n };\n\n return (\n partialBody.status === 'additional_action_required' &&\n !!partialBody.additional_action_required?.data?.redirect_url\n );\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport WorldpayAccessOpenBankingPaymentStrategy from './worldpayaccess-open-banking-payment-strategy';\n\nconst createWorldpayAccessOpenBankingPaymentStrategy: PaymentStrategyFactory<\n WorldpayAccessOpenBankingPaymentStrategy\n> = (paymentIntegrationService) =>\n new WorldpayAccessOpenBankingPaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createWorldpayAccessOpenBankingPaymentStrategy, [\n { id: 'open_banking', gateway: 'worldpayaccess' },\n]);\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 } 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 { 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 { 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 * This error is thrown when at least one cart item changed stock position (e.g. moved to a different warehouse)\n * and the server returns type `cart_stock_positions_changed`.\n */\nexport default class CartStockPositionsChangedError extends StandardError {\n changedItemIds: string[];\n\n constructor(changedItemIds: string[], message?: string) {\n super(\n message ||\n 'At least one item changed stock position. Please review your cart and try again.',\n );\n\n this.name = 'CartStockPositionsChangedError';\n this.type = 'cart_stock_positions_changed';\n this.changedItemIds = changedItemIds;\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 { StandardError } from '../../common/error/errors';\n\nexport default class MissingShippingMethodError extends StandardError {\n constructor(message: string) {\n super(message);\n\n this.name = 'MissingShippingMethodError';\n this.type = 'missing_shipping_method';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport default class InvalidShippingAddressError extends StandardError {\n constructor(message: string) {\n super(message);\n\n this.name = 'InvalidShippingAddressError';\n this.type = 'invalid_shipping_address';\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\nimport { isNil, omitBy } from 'lodash';\n\nimport {\n CartConsistencyError,\n CartStockPositionsChangedError,\n EmptyCartError,\n} from '../cart/errors';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport { MissingShippingMethodError, OrderTaxProviderUnavailableError } from './errors';\nimport InvalidShippingAddressError from './errors/invalid-shipping-address-error';\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 if (error.body.type === 'cart_stock_positions_changed') {\n const changedItemIds =\n (error.body.errors as { changedItemIds?: string[] })?.changedItemIds ?? [];\n\n throw new CartStockPositionsChangedError(changedItemIds);\n }\n\n if (error.body.type === 'missing_shipping_method') {\n throw new MissingShippingMethodError(error.body.detail);\n }\n\n if (error.body.type === 'invalid_shipping_address') {\n throw new InvalidShippingAddressError(error.body.detail);\n }\n\n if (error.body.type === 'empty_cart') {\n throw new EmptyCartError();\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 { 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 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 { 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","// / \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 { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\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';\n\nimport { PaymentMethod } from '.';\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\n observer.next(\n createAction(\n PaymentMethodActionType.LoadPaymentMethodsSucceeded,\n methods,\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","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 { 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","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","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 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 CYBERSOURCEV2_GOOGLE_PAY = 'googlepaycybersourcev2',\n HUMM = 'humm',\n KLARNA = 'klarna',\n KLARNAV2 = 'klarnav2',\n LEGACY = 'legacy',\n MOLLIE = 'mollie',\n MONERIS = 'moneris',\n NO_PAYMENT_DATA_REQUIRED = 'nopaymentdatarequired',\n OFFLINE = 'offline',\n OFFSITE = 'offsite',\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 WORLDPAYACCESS = 'worldpayaccess',\n WORLDPAYACCESS_GOOGLE_PAY = 'googlepayworldpayaccess',\n STRIPE_GOOGLE_PAY = 'googlepaystripe',\n SEZZLE = 'sezzle',\n ZIP = 'zip',\n}\n\nexport default PaymentStrategyType;\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 { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, empty, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport {\n PaymentIntegrationService,\n PaymentStrategy as PaymentStrategyV2,\n} 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 { getDefaultLogger } from '../common/log';\nimport {\n LoadOrderPaymentsAction,\n OrderActionCreator,\n OrderPaymentRequestBody,\n OrderRequestBody,\n} from '../order';\nimport { OrderFinalizationNotRequiredError } from '../order/errors';\nimport { registerIntegrations } from '../payment-integration';\nimport { SpamProtectionAction, SpamProtectionActionCreator } from '../spam-protection';\n\nimport PaymentMethod from './payment-method';\nimport {\n OrderFinalizeOptions,\n PaymentInitializeOptions,\n PaymentRequestOptions,\n} 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 private _paymentIntegrationService: PaymentIntegrationService,\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?: OrderFinalizeOptions,\n ): ThunkAction {\n const { integrations } = options ?? {};\n\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 registerIntegrations(\n this._strategyRegistryV2,\n integrations ?? [],\n this._paymentIntegrationService,\n );\n\n let strategy: PaymentStrategy | PaymentStrategyV2;\n\n try {\n strategy = this._getStrategy(method);\n } catch {\n throw new OrderFinalizationNotRequiredError();\n }\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, integrations } = 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 registerIntegrations(\n this._strategyRegistryV2,\n integrations ?? [],\n this._paymentIntegrationService,\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 try {\n strategy = this._strategyRegistryV2.get({\n id: method.id,\n gateway: method.gateway,\n type: method.type,\n });\n } catch (error) {\n getDefaultLogger().error(\n `[PaymentStrategyActionCreator] Unable to resolve V2 strategy for id: ${method.id}, gateway: ${method.gateway}, type: ${method.type}`,\n );\n throw error;\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 { 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 { 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","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 { 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 { 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 { 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 { 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 _checkoutId?: string,\n private _cardInstrument?: CardInstrument,\n ) {\n this._iframe = document.createElement('iframe');\n\n const src = this._checkoutId\n ? `/checkout/payment/hosted-field?version=${LIBRARY_VERSION}&checkoutId=${this._checkoutId}`\n : `/checkout/payment/hosted-field?version=${LIBRARY_VERSION}`;\n\n this._iframe.src = src;\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 { 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 { 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 let paymentMethod = state.paymentMethods.getPaymentMethod(\n payload.methodId,\n payload.gatewayId,\n );\n\n if (paymentMethod?.gateway === 'worldpayaccess' && paymentMethod?.id === 'credit_card') {\n paymentMethod = { ...paymentMethod, id: 'worldpayaccess', method: 'credit-card' };\n }\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, checkoutId?: string): 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 checkoutId,\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 { 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","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","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","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 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 [],\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","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 PAYPALEXPRESS = \"paypalexpress\"\n}\nexport default CheckoutButtonMethodType;\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","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 }, {});\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 // Worldpay Access: sub-methods carry the provider name in `gateway` and the method\n // name in `id`. BigPay's mapToId uses `id` as the gateway field unless\n // `method === 'multi-option'`, so we align with hosted-form-order-data-transformer\n if (paymentMethod.gateway === 'worldpayaccess') {\n if (paymentMethod.id === 'credit_card') {\n return { ...paymentMethod, id: 'worldpayaccess', method: 'credit-card' };\n }\n\n if (paymentMethod.id === 'open_banking') {\n return { ...paymentMethod, id: 'worldpayaccess', method: 'open_banking' };\n }\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","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","export const ACKNOWLEDGE = 'ACKNOWLEDGE';\nexport const FINALIZE = 'FINALIZE';\nexport const INITIALIZE = 'INITIALIZE';\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 { 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 { 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 { 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 { 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 { 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 { 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","export enum SubStrategyType {\n CARD = 'card_ui',\n NONE = 'none',\n UNSUPPORTED = 'unsupported',\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, checkout } = this._store.getState();\n const { paymentSettings: { bigpayBaseUrl: host = '' } = {} } =\n config.getStoreConfig() || {};\n const checkoutId = checkout.getCheckoutOrThrow().id;\n\n if (!formOptions) {\n throw new InvalidArgumentError();\n }\n\n const form = formOptions && this._hostedFormFactory.create(host, formOptions, checkoutId);\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 { 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 { 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 { 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 { 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 { 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 { 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 { 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 { 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 const consignmentInMemory = store\n .getState()\n .consignments.getConsignmentById(consignment.id);\n\n const alreadySelectedOptionId = consignmentInMemory?.selectedShippingOption?.id;\n\n if (alreadySelectedOptionId === consignment.shippingOptionId) {\n observer.complete();\n\n return;\n }\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 { EmptyCartError } from '../cart/errors';\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.physicalItems.stockPosition',\n 'cart.lineItems.digitalItems.options',\n 'cart.lineItems.digitalItems.stockPosition',\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\n .post(url, {\n body: consignments,\n params: {\n include: joinOrMergeIncludes(DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .put(url, {\n body,\n params: {\n include: joinOrMergeIncludes(DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .delete(url, { params: { include }, headers, timeout })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\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 { 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, 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 { 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 { 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 { id } = checkout;\n const checkoutVersion = options?.version ?? checkout.version;\n\n const { body } = await (useStoreCredit\n ? this._storeCreditRequestSender.applyStoreCredit(id, {\n ...options,\n version: checkoutVersion,\n })\n : this._storeCreditRequestSender.removeStoreCredit(id, {\n ...options,\n version: checkoutVersion,\n }));\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, version }: 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 body: { version },\n });\n }\n\n removeStoreCredit(\n checkoutId: string,\n { timeout, version }: 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 body: { version },\n });\n }\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, getLocale: getCartLocale },\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 getCartLocale: clone(getCartLocale),\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 { 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 {\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 CouponActionCreator from '../coupon/coupon-action-creator';\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 _couponActionCreator: CouponActionCreator,\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 const checkoutId = this._storeProjection.getState().getCheckoutOrThrow().id;\n\n return this._hostedFormFactory.create(host, options, checkoutId);\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 applyCoupon(\n coupon: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(this._couponActionCreator.applyCoupon(coupon, options));\n\n return this._storeProjection.getState();\n }\n\n async removeCoupon(\n coupon: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(this._couponActionCreator.removeCoupon(coupon, options));\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, RequestSender } 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 CouponActionCreator from '../coupon/coupon-action-creator';\nimport CouponRequestSender from '../coupon/coupon-request-sender';\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 requestSender?: RequestSender,\n): PaymentIntegrationService {\n const {\n config: { getHost, getLocale },\n } = store.getState();\n\n if (!requestSender) {\n requestSender = createRequestSender({ host: getHost() });\n }\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 applyCouponActionCreator = new CouponActionCreator(\n new CouponRequestSender(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 applyCouponActionCreator,\n spamProtectionActionCreator,\n paymentProviderCustomerActionCreator,\n shippingCountryActionCreator,\n remoteCheckoutActionCreator,\n paymentStrategyWidgetActionCreator,\n );\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 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","export default function isFuture(date: Date): boolean {\n return date.valueOf() > Date.now();\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 { 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 { 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 {\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 { 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","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 { 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","import { isEqual, omit } from 'lodash';\n\nimport {\n BraintreeFastlaneAddress,\n BraintreeFastlaneAuthenticationState,\n BraintreeFastlaneProfileData,\n BraintreeFastlaneStylesOption,\n BraintreeFastlaneVaultedInstrument,\n BraintreeInitializationData,\n BraintreeIntegrationService,\n getFastlaneStyles,\n isBraintreeAcceleratedCheckoutCustomer,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { CookieStorage } 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 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 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\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, fastlane } = options || {};\n const fastlaneOptions = fastlane || braintreefastlane;\n const { onPayPalFastlaneAddressChange } = fastlaneOptions || {};\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 fastlaneOptions?.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 = CookieStorage.get('bc-fastlane-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 CookieStorage.remove('bc-fastlane-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?.authenticationState !==\n 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 PayPalFastlaneAuthenticationState,\n PayPalFastlaneStylesOption,\n PayPalFastlaneUtils,\n PayPalInitializationData,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-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 _paypalSdkScriptLoader: PayPalSdkScriptLoader,\n private _paypalCommerceFastlaneUtils: PayPalFastlaneUtils,\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, fastlane } = options || {};\n const fastlaneOptions = fastlane || paypalcommercefastlane;\n const { onPayPalFastlaneAddressChange, styles } = fastlaneOptions || {};\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._paypalSdkScriptLoader.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n cart.locale,\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 if (isAuthenticationFlowCanceled) {\n this._paypalCommerceFastlaneUtils.removeStorageSessionId();\n } else {\n this._paypalCommerceFastlaneUtils.updateStorageSessionId(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 {\n PaymentProviderCustomer,\n PayPalConnectCustomer,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isPaypalAcceleratedCheckoutCustomer(\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 { 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 {\n STRIPE_UPE_CLIENT_API_VERSION,\n STRIPE_UPE_CLIENT_BETAS,\n StripeAppearanceOptions,\n StripeClient,\n StripeDisplayName,\n StripeElementEvent,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeEventType,\n StripeFormMode,\n StripeJsVersion,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\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 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?: StripeClient;\n private _stripeElements?: StripeElements;\n private sendData?: ReturnType;\n\n constructor(\n private _store: CheckoutStore,\n private _stripeScriptLoader: 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 { initializationData } = 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._stripeScriptLoader.getStripeClient(\n initializationData,\n state.cart.getLocale(),\n StripeJsVersion.V3,\n STRIPE_UPE_CLIENT_BETAS,\n STRIPE_UPE_CLIENT_API_VERSION,\n );\n\n let appearance: StripeAppearanceOptions;\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 = await this._stripeScriptLoader.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: StripeDisplayName.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(StripeElementEvent.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 { 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 { B2BTokenActionCreator } from '../b2b-token';\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 ExtensionMessage,\n ExtensionMessenger,\n ExtensionQueryMap,\n ExtensionRegion,\n WorkerExtensionMessenger,\n} from '../extension';\nimport { FormFieldsActionCreator } from '../form';\nimport { CountryActionCreator } from '../geography';\nimport { OrderActionCreator, OrderRequestBody } from '../order';\nimport {\n OrderFinalizeOptions,\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 CheckoutInitialState from './checkout-initial-state';\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 _b2bTokenActionCreator: B2BTokenActionCreator,\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 private _workerExtensionMessenger: WorkerExtensionMessenger,\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 * Hydrates the checkout service with an initial state.\n *\n * The initial state can contain various checkout data such as cart items,\n * customer information, and other relevant state.\n *\n * ```js\n * const initialState = {\n * // ... initial checkout state data\n * };\n *\n * const state = await service.hydrateInitialState(initialState);\n *\n * console.log(state.data.getCheckout());\n * ```\n *\n * @alpha\n * @param state - The initial state data to hydrate the checkout service with.\n * @returns A promise that resolves to the current state after hydration.\n */\n hydrateInitialState(state: CheckoutInitialState): Promise {\n return this._dispatch(this._checkoutActionCreator.hydrateInitialState(state));\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?: OrderFinalizeOptions): 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 * Retrieves a B2B authentication token for the current customer.\n *\n * The token can be used to authenticate requests to B2B REST and GraphQL\n * endpoints. The customer must be signed in for this method to succeed.\n * The B2B base URL and client ID are read from the checkout settings config.\n *\n * ```js\n * const state = await service.getB2BToken();\n *\n * console.log(state.data.getB2BToken());\n * ```\n *\n * @param options - Options for the request.\n * @returns A promise that resolves to the current state.\n */\n getB2BToken(options?: RequestOptions): Promise {\n const action = this._b2bTokenActionCreator.loadB2BToken(options);\n\n return this._dispatch(action, { queueId: 'b2bToken' });\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(\n container,\n region,\n this._workerExtensionMessenger,\n );\n const state = await this._dispatch(action, { queueId: 'extensions' });\n\n this._extensionEventBroadcaster.listen();\n\n return state;\n }\n\n /**\n * Clear cache for a checkout extension when removing it from UI.\n * This function should be used whenver an extension is removed from the UI.\n *\n * @alpha\n * @param region - The name of an area where the extension should be presented.\n */\n clearExtensionCache(region: ExtensionRegion): void {\n this._extensionMessenger.clearCacheByRegion(region);\n }\n\n /**\n * Posts a message to a checkout extension.\n *\n * @alpha\n * @param extensionId - The ID of an extension to post the event to.\n * @param message - The message to post to an extension.\n */\n postMessageToExtension(extensionId: string, message: ExtensionMessage): void {\n this._extensionMessenger.post(extensionId, message);\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]) => Promise | void,\n ): () => void {\n return this._extensionMessenger.listenForCommand(extensionId, command, handler);\n }\n\n /**\n * Manages the query handler for an extension.\n *\n * @alpha\n * @param extensionId - The ID of the extension sending the query.\n * @param query - The query to be handled.\n * @param handler - The handler function for the extension query.\n * @returns A function that, when called, will deregister the query handler.\n */\n handleExtensionQuery(\n extensionId: string,\n query: T,\n handler: (command: ExtensionQueryMap[T]) => Promise | void,\n ): () => void {\n return this._extensionMessenger.listenForQuery(extensionId, query, 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","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","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 * 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","export interface B2BToken {\n token: string;\n}\n\nexport default interface B2BTokenState {\n data?: B2BToken;\n errors: B2BTokenErrorsState;\n statuses: B2BTokenStatusesState;\n}\n\nexport interface B2BTokenErrorsState {\n loadError?: Error;\n}\n\nexport interface B2BTokenStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: B2BTokenState = {\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';\n\nimport { B2BTokenActionType, LoadB2BTokenAction } from './b2b-token-actions';\nimport B2BTokenState, {\n B2BToken,\n B2BTokenErrorsState,\n B2BTokenStatusesState,\n DEFAULT_STATE,\n} from './b2b-token-state';\n\nexport default function b2bTokenReducer(\n state: B2BTokenState = DEFAULT_STATE,\n action: Action,\n): B2BTokenState {\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: B2BToken | undefined, action: LoadB2BTokenAction): B2BToken | undefined {\n switch (action.type) {\n case B2BTokenActionType.LoadB2BTokenSucceeded:\n return action.payload;\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: B2BTokenErrorsState = DEFAULT_STATE.errors,\n action: LoadB2BTokenAction,\n): B2BTokenErrorsState {\n switch (action.type) {\n case B2BTokenActionType.LoadB2BTokenRequested:\n case B2BTokenActionType.LoadB2BTokenSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case B2BTokenActionType.LoadB2BTokenFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: B2BTokenStatusesState = DEFAULT_STATE.statuses,\n action: LoadB2BTokenAction,\n): B2BTokenStatusesState {\n switch (action.type) {\n case B2BTokenActionType.LoadB2BTokenRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case B2BTokenActionType.LoadB2BTokenFailed:\n case B2BTokenActionType.LoadB2BTokenSucceeded:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\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 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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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 | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return replace(data, action.payload?.checkout?.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, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { BillingAddressAction, BillingAddressActionType } from '../billing';\nimport {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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 | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return objectMerge(data, action.payload?.checkout?.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 { 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 { 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 { CheckoutHydrateAction, CheckoutHydrateActionType } from '../checkout';\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(\n data: Config | undefined,\n action: LoadConfigAction | CheckoutHydrateAction,\n): Config | undefined {\n switch (action.type) {\n case ConfigActionType.LoadConfigSucceeded:\n return objectMerge(data, action.payload);\n\n case CheckoutHydrateActionType.HydrateInitialState: {\n const merged = objectMerge(data, action.payload?.config);\n\n // b2bApiSettings is a top-level field in CheckoutInitialState (separate from config),\n // so it must be merged into storeConfig manually after the config hydration.\n // Skip if config data is absent or this is a non-B2B store (no b2bApiSettings).\n if (!merged || !action.payload?.b2bApiSettings) {\n return merged;\n }\n\n return {\n ...merged,\n storeConfig: {\n ...merged.storeConfig,\n b2bApiSettings: action.payload.b2bApiSettings,\n },\n };\n }\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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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 | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return arrayReplace(data, action.payload?.checkout?.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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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:\n | CheckoutAction\n | GiftCertificateAction\n | ConsignmentAction\n | CouponAction\n | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return arrayReplace(data, action.payload?.checkout?.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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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 | CheckoutHydrateAction;\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 case CheckoutHydrateActionType.HydrateInitialState:\n return objectMerge(data, action.payload?.checkout?.customer);\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 {\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} from '../checkout/checkout-hydrate-actions';\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 | CheckoutHydrateAction,\n): Extension[] | undefined {\n if (action.type === ExtensionActionType.LoadExtensionsSucceeded) {\n return arrayReplace(data, action.payload);\n }\n\n if (action.type === CheckoutHydrateActionType.HydrateInitialState) {\n return arrayReplace(data, action.payload?.extensions);\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 { ExtraFields } from './extra-field';\nimport { FormFields } from './form-field';\n\nexport default interface FormFieldsState {\n data?: FormFields;\n extraFields?: ExtraFields;\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 { CheckoutHydrateAction, CheckoutHydrateActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { ExtraFields } from './extra-field';\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 extraFields: extraFieldsReducer,\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 | CheckoutHydrateAction,\n): FormFields | undefined {\n switch (action.type) {\n case FormFieldsActionType.LoadFormFieldsSucceeded:\n return objectMerge(data, action.payload);\n\n case CheckoutHydrateActionType.HydrateInitialState:\n return objectMerge(data, action.payload?.formFields);\n\n default:\n return data;\n }\n}\n\nfunction extraFieldsReducer(\n extraFields: ExtraFields | undefined,\n action: CheckoutHydrateAction,\n): ExtraFields | undefined {\n switch (action.type) {\n case CheckoutHydrateActionType.HydrateInitialState:\n return action.payload?.extraFields ?? extraFields;\n\n default:\n return extraFields;\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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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:\n | ConsignmentAction\n | CheckoutAction\n | CouponAction\n | CustomerAction\n | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return arrayReplace(data, action.payload?.checkout?.consignments);\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 { CheckoutHydrateAction, CheckoutHydrateActionType } from './checkout-hydrate-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 | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return objectMerge(\n data,\n omit(action.payload?.checkout, [\n 'billingAddress',\n 'cart',\n 'consignments',\n 'customer',\n 'coupons',\n 'giftCertificates',\n ]),\n ) as CheckoutDataState;\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\ntype FunctionProperties = {\n [K in keyof T]: T[K] extends (...args: unknown[]) => unknown ? T[K] : never;\n};\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<{ [key: string]: T }>((result, key) => {\n result[key] = createFreezeProxy(map[key]);\n\n return result;\n }, {}) 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 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 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 'worldpayaccess.credit_card': {\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 bigcommerce_payments_creditcards: {\n provider: 'bigcommerce_payments',\n method: 'credit_card',\n },\n bigcommerce_payments: {\n provider: 'bigcommerce_payments',\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 { createB2BTokenSelectorFactory } from '../b2b-token';\nimport { 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 createB2BTokenSelector = createB2BTokenSelectorFactory();\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 b2bToken = createB2BTokenSelector(state.b2bToken);\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 b2bToken,\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 { createSelector } from '../common/selector';\n\nimport B2BTokenState, { DEFAULT_STATE } from './b2b-token-state';\n\nexport default interface B2BTokenSelector {\n getToken(): string | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type B2BTokenSelectorFactory = (state: B2BTokenState) => B2BTokenSelector;\n\nexport function createB2BTokenSelectorFactory(): B2BTokenSelectorFactory {\n const getToken = createSelector(\n (state: B2BTokenState) => state.data?.token,\n (token) => () => token,\n );\n\n const getLoadError = createSelector(\n (state: B2BTokenState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: B2BTokenState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: B2BTokenState = DEFAULT_STATE): B2BTokenSelector => {\n return {\n getToken: getToken(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';\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 { 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 getLocale(): string | undefined;\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 const getLocale = createSelector(\n (state: CartState) => state.data?.locale,\n (data) => () => data,\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 getLocale: getLocale(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 { 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 = { customerAccount: [], shippingAddress: [], billingAddress: [] }) =>\n () =>\n data\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 { 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 { 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';\nimport mapExtraFieldToFormField from './map-extra-field-to-form-field';\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 getAddressExtraFields(): 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 getAddressExtraFields = createSelector(\n (state: FormFieldsState) => state.extraFields,\n (extraFields) => () => {\n if (!extraFields || !extraFields.address.length) {\n return [];\n }\n\n return extraFields.address.map(mapExtraFieldToFormField);\n },\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 getAddressExtraFields: getAddressExtraFields(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 { 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';\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 [],\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 { 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 { 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 { 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 { 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 initialStoreState: Partial = {},\n options?: CheckoutStoreOptions,\n): CheckoutStore {\n const actionTransformer = createActionTransformer(createRequestErrorFactory());\n const createInternalCheckoutSelectors = createInternalCheckoutSelectorsFactory();\n const stateTransformer = (state: CheckoutStoreState) => createInternalCheckoutSelectors(state);\n const reducer = createCheckoutStoreReducer();\n\n return createDataStore(reducer, initialStoreState, {\n actionTransformer,\n stateTransformer,\n ...options,\n });\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 { 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, combineReducers, Reducer } from '@bigcommerce/data-store';\n\nimport { b2bTokenReducer } from '../b2b-token';\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 b2bToken: b2bTokenReducer,\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, RequestSender } from '@bigcommerce/request-sender';\nimport { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport { B2BTokenActionCreator, B2BTokenRequestSender } from '../b2b-token';\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { createDataStoreProjection } from '../common/data-store';\nimport { ErrorActionCreator, ErrorLogger } from '../common/error';\nimport { ExperimentAwareRequestSender } from '../common/http-request';\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 WorkerExtensionMessenger,\n} from '../extension';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport * as customerStrategyFactories from '../generated/customer-strategies';\nimport * as paymentStrategyFactories 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 experimentRequestSender = new ExperimentAwareRequestSender(requestSender, {\n getBasePath: () => store.getState().config.getStoreConfig()?.links.baseUrl ?? undefined,\n getFeatures: () =>\n store.getState().config.getStoreConfig()?.checkoutSettings?.features ?? {},\n }) as unknown as RequestSender;\n const paymentClient = createPaymentClient(store);\n const orderRequestSender = new OrderRequestSender(experimentRequestSender);\n const checkoutRequestSender = new CheckoutRequestSender(experimentRequestSender);\n const configActionCreator = new ConfigActionCreator(new ConfigRequestSender(requestSender));\n const spamProtection = createSpamProtection(createScriptLoader());\n const spamProtectionRequestSender = new SpamProtectionRequestSender(experimentRequestSender);\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(experimentRequestSender),\n );\n const formFieldsActionCreator = new FormFieldsActionCreator(\n new FormFieldsRequestSender(experimentRequestSender),\n );\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n configActionCreator,\n formFieldsActionCreator,\n );\n const paymentIntegrationService = createPaymentIntegrationService(\n store,\n experimentRequestSender,\n );\n\n // NO_PAYMENT_DATA_REQUIRED must always be available regardless of build mode — it handles\n // free orders / full store credit checkouts and cannot be lazily loaded via integrations.\n const essentialPaymentStrategyFactories = {\n createNoPaymentStrategy: paymentStrategyFactories.createNoPaymentStrategy,\n };\n const registryV2 = createPaymentStrategyRegistryV2(\n paymentIntegrationService,\n process.env.ESSENTIAL_BUILD ? essentialPaymentStrategyFactories : paymentStrategyFactories,\n { useFallback: true },\n );\n const customerRegistryV2 = createCustomerStrategyRegistryV2(\n paymentIntegrationService,\n process.env.ESSENTIAL_BUILD ? {} : customerStrategyFactories,\n );\n const extensionActionCreator = new ExtensionActionCreator(\n new ExtensionRequestSender(experimentRequestSender),\n );\n const workerExtensionMessenger = new WorkerExtensionMessenger();\n const extensionMessenger = new ExtensionMessenger(store, workerExtensionMessenger);\n const storeProjection = createDataStoreProjection(store, createCheckoutSelectorsFactory());\n\n return new CheckoutService(\n store,\n storeProjection,\n extensionMessenger,\n createExtensionEventBroadcaster(storeProjection, extensionMessenger),\n new B2BTokenActionCreator(new B2BTokenRequestSender(requestSender)),\n new BillingAddressActionCreator(\n new BillingAddressRequestSender(experimentRequestSender),\n subscriptionsActionCreator,\n ),\n checkoutActionCreator,\n configActionCreator,\n new CustomerActionCreator(\n new CustomerRequestSender(experimentRequestSender),\n checkoutActionCreator,\n spamProtectionActionCreator,\n ),\n new ConsignmentActionCreator(\n new ConsignmentRequestSender(experimentRequestSender),\n checkoutRequestSender,\n ),\n new CountryActionCreator(new CountryRequestSender(experimentRequestSender, { locale })),\n new CouponActionCreator(new CouponRequestSender(experimentRequestSender)),\n new CustomerStrategyActionCreator(\n createCustomerStrategyRegistry(store, experimentRequestSender),\n customerRegistryV2,\n paymentIntegrationService,\n ),\n new ErrorActionCreator(),\n new GiftCertificateActionCreator(new GiftCertificateRequestSender(experimentRequestSender)),\n new InstrumentActionCreator(\n new InstrumentRequestSender(paymentClient, experimentRequestSender),\n ),\n orderActionCreator,\n new PaymentMethodActionCreator(new PaymentMethodRequestSender(experimentRequestSender)),\n new PaymentStrategyActionCreator(\n createPaymentStrategyRegistry(store, paymentClient, experimentRequestSender),\n registryV2,\n orderActionCreator,\n spamProtectionActionCreator,\n paymentIntegrationService,\n ),\n new PickupOptionActionCreator(new PickupOptionRequestSender(experimentRequestSender)),\n new ShippingCountryActionCreator(\n new ShippingCountryRequestSender(experimentRequestSender, { locale }),\n store,\n ),\n new ShippingStrategyActionCreator(\n createShippingStrategyRegistry(store, experimentRequestSender),\n ),\n new SignInEmailActionCreator(new SignInEmailRequestSender(experimentRequestSender)),\n spamProtectionActionCreator,\n new StoreCreditActionCreator(new StoreCreditRequestSender(experimentRequestSender)),\n subscriptionsActionCreator,\n formFieldsActionCreator,\n extensionActionCreator,\n workerExtensionMessenger,\n );\n}\n\nexport interface CheckoutServiceOptions {\n locale?: string;\n host?: string;\n shouldWarnMutation?: boolean;\n externalSource?: string;\n errorLogger?: ErrorLogger;\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';\n\nexport interface PaymentStrategyFactories {\n [key: string]: PaymentStrategyFactory;\n}\n\nexport default function createPaymentStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n paymentStrategyFactories: PaymentStrategyFactories,\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 {\n CustomerStrategy,\n CustomerStrategyFactory,\n CustomerStrategyResolveId,\n isResolvableModule,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\n\nexport interface CustomerStrategyFactories {\n [key: string]: CustomerStrategyFactory;\n}\n\nexport default function createCustomerStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n customerStrategyFactories: CustomerStrategyFactories,\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 {\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 { 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 B2B authentication token for the current customer.\n *\n * @returns The B2B token string if it has been loaded, otherwise undefined.\n */\n getB2BToken(): string | 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 address extra fields.\n *\n * @returns The list of extra fields if available, otherwise an empty array.\n */\n getAddressExtraFields(): 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 getB2BToken = createSelector(\n ({ b2bToken }: InternalCheckoutSelectors) => b2bToken.getToken,\n (getToken) => clone(getToken),\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 getAddressExtraFields = createSelector(\n ({ form }: InternalCheckoutSelectors) => form.getAddressExtraFields,\n (getAddressExtraFields) => clone(getAddressExtraFields),\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 getB2BToken: getB2BToken(state),\n getInstruments: getInstruments(state),\n getCustomerAccountFields: getCustomerAccountFields(state),\n getBillingAddressFields: getBillingAddressFields(state),\n getShippingAddressFields: getShippingAddressFields(state),\n getAddressExtraFields: getAddressExtraFields(state),\n getPickupOptions: getPickupOptions(state),\n getUserExperienceSettings: getUserExperienceSettings(state),\n getPaymentProviderCustomer: getPaymentProviderCustomer(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport {\n CartChangedError,\n CartConsistencyError,\n CartStockPositionsChangedError,\n} 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():\n | Error\n | CartChangedError\n | CartConsistencyError\n | CartStockPositionsChangedError\n | 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 load the B2B token.\n *\n * @returns The error object if unable to load the B2B token, otherwise undefined.\n */\n getLoadB2BTokenError(): 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 getLoadB2BTokenError: state.b2bToken.getLoadError,\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 a B2B token is being loaded.\n *\n * @returns True if a B2B token is being loaded, otherwise false.\n */\n isLoadingB2BToken(): 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 isLoadingB2BToken: state.b2bToken.isLoading,\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 { 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 { 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 {\n createSpamProtection,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\n\nimport CustomerActionCreator from './customer-action-creator';\nimport CustomerRequestSender from './customer-request-sender';\nimport { CustomerStrategy } from './strategies';\nimport { DefaultCustomerStrategy } from './strategies/default';\n\nexport default function createCustomerStrategyRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\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 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 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 } from '@bigcommerce/script-loader';\n\nimport { CheckoutRequestSender, CheckoutStore, CheckoutValidator } from '../checkout';\nimport { BrowserStorage } from '../common/storage';\nimport { HostedFormFactory } from '../hosted-form';\nimport { OrderActionCreator, OrderRequestSender } from '../order';\nimport { createSpamProtection, PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport PaymentActionCreator from './payment-action-creator';\nimport PaymentRequestSender from './payment-request-sender';\nimport PaymentRequestTransformer from './payment-request-transformer';\nimport PaymentStrategyRegistry from './payment-strategy-registry';\nimport PaymentStrategyType from './payment-strategy-type';\nimport { ConvergePaymentStrategy } from './strategies/converge';\nimport {\n createStepHandler,\n createSubStrategyRegistry,\n PaymentResumer,\n PPSDKStrategy,\n} from './strategies/ppsdk';\n\nexport default function createPaymentStrategyRegistry(\n store: CheckoutStore,\n paymentClient: any,\n requestSender: RequestSender,\n) {\n const registry = new PaymentStrategyRegistry({\n defaultToken: PaymentStrategyType.CREDIT_CARD,\n });\n\n const paymentRequestTransformer = new PaymentRequestTransformer();\n const paymentRequestSender = new PaymentRequestSender(paymentClient);\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const checkoutValidator = new CheckoutValidator(checkoutRequestSender);\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 formPoster = createFormPoster();\n const stepHandler = createStepHandler(formPoster, paymentHumanVerificationHandler);\n const hostedFormFactory = new HostedFormFactory(store);\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.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 return registry;\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';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { createAmazonPayV2PaymentProcessor } from '@bigcommerce/checkout-sdk/amazon-pay-utils';\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n createPayPalFastlaneUtils,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { createPaymentIntegrationService } from '../payment-integration';\nimport { PaymentProviderCustomerActionCreator } from '../payment-provider-customer';\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 paymentIntegrationService = createPaymentIntegrationService(store);\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 const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\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(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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 createPayPalSdkScriptLoader(),\n createPayPalFastlaneUtils(),\n ),\n );\n\n registry.register(\n 'default',\n () => new DefaultShippingStrategy(store, consignmentActionCreator),\n );\n\n return registry;\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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory 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 getButtonStyle = (buttonStyle?: ButtonStyleOption): string => {\n switch (buttonStyle) {\n case ButtonStyleOption.White:\n return 'white';\n\n case ButtonStyleOption.WhiteBorder:\n return 'white-outline';\n\n case ButtonStyleOption.Black:\n default:\n return 'black';\n }\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 private _applePayScriptLoader: ApplePayScriptLoader,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithApplePayButtonInitializeOptions,\n ): Promise {\n const { methodId, containerId, applepay } = options;\n\n if (!methodId || !applepay) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n await this._applePayScriptLoader.loadSdk();\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 (\n this._paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE &&\n this._paymentMethod.clientToken\n ) {\n this._braintreeSdk.initialize(this._paymentMethod.clientToken);\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 applePayButton = this._createApplePayButtonElement(styleOption);\n\n container.appendChild(applePayButton);\n\n return applePayButton;\n }\n\n private _createApplePayButtonElement(styleOption?: ButtonStyleOption): HTMLElement {\n const applePayButton = document.createElement('apple-pay-button');\n\n applePayButton.setAttribute('buttonstyle', getButtonStyle(styleOption));\n applePayButton.setAttribute('type', 'plain');\n applePayButton.setAttribute(\n 'style',\n '--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;',\n );\n\n return applePayButton;\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\n const state = this._paymentIntegrationService.getState();\n const { shouldExecuteSpamCheck } = state.getCheckoutOrThrow();\n\n if (shouldExecuteSpamCheck) {\n await this._paymentIntegrationService.verifyCheckoutSpamProtection();\n }\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","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\n} 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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayButtonStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n\n return new ApplePayButtonStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), window, braintreeSDKVersionManager),\n ),\n new ApplePayScriptLoader(new ScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createApplePayButtonStrategy, [{ id: 'applepay' }]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n PayPalBuyNowInitializeOptions,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsButtonInitializeOptions, {\n WithBigCommercePaymentsButtonInitializeOptions,\n} from './bigcommerce-payments-button-initialize-options';\n\nexport default class BigCommercePaymentsButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithBigCommercePaymentsButtonInitializeOptions,\n ): Promise {\n const { bigcommerce_payments, containerId, methodId } = options;\n\n const isBuyNowFlow = Boolean(bigcommerce_payments?.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 (!bigcommerce_payments) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !bigcommerce_payments.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof bigcommerce_payments.buyNowInitializeOptions?.getBuyNowCartRequestBody !==\n 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments.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 ? bigcommerce_payments.currencyCode\n : this.paymentIntegrationService.getState().getCartOrThrow().currency.code;\n\n await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(\n methodId,\n currencyCode,\n false,\n );\n\n this.renderButton(containerId, methodId, bigcommerce_payments, isBuyNowFlow);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n bigcommerce_payments: BigCommercePaymentsButtonInitializeOptions,\n isBuyNowFlow?: boolean,\n ): void {\n const { buyNowInitializeOptions, style, onComplete, onEligibilityFailure } =\n bigcommerce_payments;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, isAppSwitchEnabled } =\n paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n ...(!isBuyNowFlow &&\n this.isPaypalCommerceAppSwitchEnabled(methodId) && {\n appSwitchWhenAvailable: true,\n }),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder('bigcommerce_payments'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const hostedCheckoutCallbacks = {\n ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n }),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const buttonRenderOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n if (paypalButton.hasReturned?.() && this.isPaypalCommerceAppSwitchEnabled(methodId)) {\n paypalButton.resume?.();\n } else {\n paypalButton.render(`#${containerId}`);\n }\n } else if (onEligibilityFailure && typeof onEligibilityFailure === 'function') {\n onEligibilityFailure();\n } else {\n this.bigCommercePaymentsIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart =\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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 =\n this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n } catch (error) {\n if (typeof error === 'string') {\n throw new Error(error);\n }\n\n throw error;\n }\n }\n\n /**\n *\n * PayPal AppSwitch enabling handling\n *\n */\n private isPaypalCommerceAppSwitchEnabled(methodId: string): boolean {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n return paymentMethod.initializationData?.isAppSwitchEnabled ?? false;\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsButtonStrategy from './bigcommerce-payments-button-strategy';\n\nconst createBigCommercePaymentsButtonStrategy: CheckoutButtonStrategyFactory<\n BigCommercePaymentsButtonStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsButtonStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsButtonStrategy, [\n { id: 'bigcommerce_payments' },\n]);\n","import { BigCommercePaymentsInitializationData } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n PayPalBuyNowInitializeOptions,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsPayLaterButtonInitializeOptions, {\n WithBigCommercePaymentsPayLaterButtonInitializeOptions,\n} from './bigcommerce-payments-paylater-button-initialize-options';\n\nexport default class BigCommercePaymentsPayLaterButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions &\n WithBigCommercePaymentsPayLaterButtonInitializeOptions,\n ): Promise {\n const { bigcommerce_payments_paylater, containerId, methodId } = options;\n const { buyNowInitializeOptions, currencyCode: providedCurrencyCode } =\n bigcommerce_payments_paylater || {};\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 (!bigcommerce_payments_paylater) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_paylater\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_paylater.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.bigcommerce_payments_paylater.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.bigCommercePaymentsIntegrationService.loadPayPalSdk(\n methodId,\n currencyCode,\n false,\n );\n\n this.renderButton(containerId, methodId, bigcommerce_payments_paylater);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n bigcommerce_payments_paylater: BigCommercePaymentsPayLaterButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style, onComplete, onEligibilityFailure } =\n bigcommerce_payments_paylater;\n\n const bigCommercePaymentsSdk =\n this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_paylater',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.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 = [\n bigCommercePaymentsSdk.FUNDING.PAYLATER,\n bigCommercePaymentsSdk.FUNDING.CREDIT,\n ];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (!hasRenderedSmartButton) {\n const buttonRenderOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = bigCommercePaymentsSdk.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.bigCommercePaymentsIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart =\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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 =\n this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsPayLaterButtonStrategy from './bigcommerce-payments-paylater-button-strategy';\n\nconst createBigCommercePaymentsPayLaterButtonStrategy: CheckoutButtonStrategyFactory<\n BigCommercePaymentsPayLaterButtonStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsPayLaterButtonStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsPayLaterButtonStrategy, [\n { id: 'bigcommerce_payments_paylater' },\n]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n StyleButtonColor,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsVenmoButtonInitializeOptions, {\n WithBigCommercePaymentsVenmoButtonInitializeOptions,\n} from './bigcommerce-payments-venmo-button-initialize-options';\n\nexport default class BigCommercePaymentsVenmoButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions &\n WithBigCommercePaymentsVenmoButtonInitializeOptions,\n ): Promise {\n const { bigcommerce_payments_venmo, containerId, methodId } = options;\n const { buyNowInitializeOptions, currencyCode: providedCurrencyCode } =\n bigcommerce_payments_venmo || {};\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 (!bigcommerce_payments_venmo) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_venmo\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_venmo.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.bigcommerce_payments_venmo.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.bigCommercePaymentsIntegrationService.loadPayPalSdk(\n methodId,\n currencyCode,\n false,\n );\n\n this.renderButton(containerId, methodId, bigcommerce_payments_venmo);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n bigcommerce_payments_venmo: BigCommercePaymentsVenmoButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style, onEligibilityFailure } = bigcommerce_payments_venmo;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const fundingSource = paypalSdk.FUNDING.VENMO;\n\n const defaultCallbacks = {\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_venmo',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const buttonRenderOptions: BigCommercePaymentsButtonsOptions = {\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.bigCommercePaymentsIntegrationService.removeElement(containerId);\n }\n }\n\n private getValidVenmoButtonStyles(style: PayPalButtonStyleOptions | undefined) {\n const validButtonStyle =\n this.bigCommercePaymentsIntegrationService.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 =\n await this.bigCommercePaymentsIntegrationService.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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsVenmoButtonStrategy from './bigcommerce-payments-venmo-button-strategy';\n\nconst createBigCommercePaymentsVenmoButtonStrategy: CheckoutButtonStrategyFactory<\n BigCommercePaymentsVenmoButtonStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsVenmoButtonStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsVenmoButtonStrategy, [\n { id: 'bigcommerce_payments_venmo' },\n]);\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 { isNil, omitBy } from 'lodash';\n\nimport { PaypalStyleOptions } from '@bigcommerce/checkout-sdk/braintree-utils';\n\nexport default function getValidButtonStyle(style?: PaypalStyleOptions): PaypalStyleOptions {\n const { color, fundingicons, height = 40, 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 | string): number {\n const minHeight = 25;\n const defaultHeight = 40;\n const maxHeight = 55;\n\n const currentHeight = Number(height);\n\n if (!currentHeight || Number.isNaN(currentHeight)) {\n return defaultHeight;\n }\n\n if (currentHeight > maxHeight) {\n return maxHeight;\n }\n\n if (currentHeight < minHeight) {\n return minHeight;\n }\n\n return currentHeight;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n BraintreeError,\n BraintreeHostWindow,\n BraintreeInitializationData,\n BraintreeIntegrationService,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n isBraintreeError,\n PaypalAuthorizeData,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n BuyNowCartCreationError,\n BuyNowCartRequestBody,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport getValidButtonStyle from '../get-valid-button-style';\nimport mapToBraintreeShippingAddressOverride from '../map-to-braintree-shipping-address-override';\n\nimport BraintreePaypalButtonInitializeOptions, {\n WithBraintreePaypalButtonInitializeOptions,\n} from './braintree-paypal-button-initialize-options';\n\nexport default class BraintreePaypalButtonStrategy implements CheckoutButtonStrategy {\n private buyNowCartId: string | undefined;\n\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: CheckoutButtonInitializeOptions & WithBraintreePaypalButtonInitializeOptions,\n ): Promise {\n const { braintreepaypal, 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 (!braintreepaypal) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal\" argument is not provided.`,\n );\n }\n\n let state = this.paymentIntegrationService.getState();\n let currencyCode: string;\n\n if (braintreepaypal.buyNowInitializeOptions) {\n if (!braintreepaypal.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypalcredit.currencyCode\" argument is not provided.`,\n );\n }\n\n currencyCode = braintreepaypal.currencyCode;\n } else {\n await this.paymentIntegrationService.loadDefaultCheckout();\n\n state = this.paymentIntegrationService.getState();\n currencyCode = state.getCartOrThrow().currency.code;\n }\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { clientToken, config, 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 commit: false,\n };\n\n const paypalCheckoutSuccessCallback = (\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n this.renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypal,\n containerId,\n methodId,\n !!config.testMode,\n );\n };\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this.handleError(error, containerId, braintreepaypal.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 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.braintreeHostWindow;\n\n if (paypal) {\n const paypalButtonRender = paypal.Buttons({\n env: testMode ? 'sandbox' : 'production',\n fundingSource: paypal.FUNDING.PAYPAL,\n style: getValidButtonStyle(style),\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.braintreeIntegrationService.removeElement(containerId);\n }\n }\n\n private async setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalButtonInitializeOptions,\n methodId: string,\n ): Promise {\n const { onPaymentError, shippingAddress, buyNowInitializeOptions } = braintreepaypal;\n\n try {\n const buyNowCart =\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function'\n ? await this.createBuyNowCart(\n buyNowInitializeOptions.getBuyNowCartRequestBody(),\n )\n : undefined;\n\n this.buyNowCartId = buyNowCart?.id;\n\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomer();\n const paymentMethod: PaymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n const amount = buyNowCart ? buyNowCart.cartAmount : state.getCartOrThrow().cartAmount;\n const currencyCode = buyNowCart\n ? braintreepaypal.currencyCode\n : state.getCartOrThrow().currency.code;\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: unknown) {\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 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.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: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(billingAddress),\n shipping_address: JSON.stringify(shippingAddress),\n ...(this.buyNowCartId && { cart_id: this.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 async createBuyNowCart(buyNowCardRequestBody?: BuyNowCartRequestBody | void) {\n if (!buyNowCardRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n return await this.paymentIntegrationService.createBuyNowCart(buyNowCardRequestBody);\n } catch (error) {\n throw new BuyNowCartCreationError();\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 BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreePaypalButtonStrategy from './braintree-paypal-button-strategy';\n\nconst createBraintreePaypalButtonStrategy: CheckoutButtonStrategyFactory<\n BraintreePaypalButtonStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n );\n\n return new BraintreePaypalButtonStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeIntegrationService,\n braintreeHostWindow,\n );\n};\n\nexport default toResolvableModule(createBraintreePaypalButtonStrategy, [{ id: 'braintreepaypal' }]);\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n BraintreeError,\n BraintreeHostWindow,\n BraintreeInitializationData,\n BraintreeIntegrationService,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n isBraintreeError,\n PaypalAuthorizeData,\n PaypalButtonStyleLabelOption,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n BuyNowCartCreationError,\n BuyNowCartRequestBody,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport getValidButtonStyle from '../get-valid-button-style';\nimport mapToBraintreeShippingAddressOverride from '../map-to-braintree-shipping-address-override';\n\nimport BraintreePaypalCreditButtonInitializeOptions, {\n WithBraintreePaypalCreditButtonInitializeOptions,\n} from './braintree-paypal-credit-button-initialize-options';\n\nexport default class BraintreePaypalCreditButtonStrategy implements CheckoutButtonStrategy {\n private buyNowCartId: string | undefined;\n\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: CheckoutButtonInitializeOptions & WithBraintreePaypalCreditButtonInitializeOptions,\n ): 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 = this.paymentIntegrationService.getState();\n let currencyCode: string;\n\n if (braintreepaypalcredit.buyNowInitializeOptions) {\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 await this.paymentIntegrationService.loadDefaultCheckout();\n\n state = this.paymentIntegrationService.getState();\n currencyCode = state.getCartOrThrow().currency.code;\n }\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { clientToken, config, 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 commit: false,\n };\n\n const paypalCheckoutSuccessCallback = (\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n this.renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n containerId,\n methodId,\n !!config.testMode,\n );\n };\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this.handleError(error, containerId, braintreepaypalcredit.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 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.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 const buttonStyle =\n fundingSource === paypal.FUNDING.CREDIT\n ? {\n label: PaypalButtonStyleLabelOption.CREDIT,\n ...getValidButtonStyle(style),\n }\n : getValidButtonStyle(style);\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.braintreeIntegrationService.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\n try {\n const buyNowCart =\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function'\n ? await this.createBuyNowCart(\n buyNowInitializeOptions.getBuyNowCartRequestBody(),\n )\n : undefined;\n\n this.buyNowCartId = buyNowCart?.id;\n\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomer();\n const paymentMethod: PaymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n const amount = buyNowCart ? buyNowCart.cartAmount : state.getCartOrThrow().cartAmount; // state.getCheckoutOrThrow().outstandingBalance\n const currencyCode = buyNowCart\n ? braintreepaypalcredit.currencyCode\n : state.getCartOrThrow().currency.code;\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: true,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error: unknown) {\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 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.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: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(billingAddress),\n shipping_address: JSON.stringify(shippingAddress),\n ...(this.buyNowCartId && { cart_id: this.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 async createBuyNowCart(buyNowCardRequestBody?: BuyNowCartRequestBody | void) {\n if (!buyNowCardRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n return await this.paymentIntegrationService.createBuyNowCart(buyNowCardRequestBody);\n } catch (error) {\n throw new BuyNowCartCreationError();\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 BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreePaypalCreditButtonStrategy from './braintree-paypal-credit-button-strategy';\n\nconst createBraintreePaypalCreditButtonStrategy: CheckoutButtonStrategyFactory<\n BraintreePaypalCreditButtonStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n );\n return new BraintreePaypalCreditButtonStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeIntegrationService,\n braintreeHostWindow,\n );\n};\n\nexport default toResolvableModule(createBraintreePaypalCreditButtonStrategy, [\n { id: 'braintreepaypalcredit' },\n]);\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), hostWindow, braintreeSDKVersionManager),\n );\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 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 || 40}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 await this.paymentIntegrationService.loadDefaultCheckout();\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeScriptLoader = new BraintreeScriptLoader(\n scriptLoader,\n braintreeHostWindow,\n braintreeSDKVersionManager,\n );\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 GooglePayError,\n GooglePayInitializationData,\n GooglePayPaymentDataRequest,\n GooglePayPaymentOptions,\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 this._googlePayPaymentProcessor.setIsWebViewExperimentOn(\n !!paymentMethod.initializationData?.isWebViewExperimentOn,\n );\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) => Promise {\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 if (this._googlePayPaymentProcessor.isWebViewWithRestrictions()) {\n return {};\n }\n\n return {\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({\n callbackTrigger,\n shippingAddress,\n shippingOptionData,\n offerData,\n }) => {\n const {\n availableTriggers,\n addressChangeTriggers,\n shippingOptionsChangeTriggers,\n offerChangeTriggers,\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 const { newOfferInfo = undefined, error: couponsError = undefined } =\n offerChangeTriggers.includes(callbackTrigger)\n ? await this._googlePayPaymentProcessor.handleCoupons(offerData)\n : {};\n\n // We can add another errors if needed 'couponsError || shippingError || anotherError'\n const error: GooglePayError | undefined = couponsError;\n\n if (this._buyNowInitializeOptions) {\n return this._getBuyNowTransactionInfo(\n availableShippingOptions,\n newOfferInfo,\n error,\n );\n }\n\n return this._getTransactionInfo(availableShippingOptions, newOfferInfo, error);\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(\n availableShippingOptions?: ShippingOptionParameters,\n newOfferInfo?: GooglePayPaymentDataRequest['offerInfo'],\n error?: GooglePayError,\n ) {\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 ...(newOfferInfo && {\n newOfferInfo,\n }),\n ...(error && {\n error,\n }),\n };\n }\n\n private async _getTransactionInfo(\n availableShippingOptions?: ShippingOptionParameters,\n newOfferInfo?: GooglePayPaymentDataRequest['offerInfo'],\n error?: GooglePayError,\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 ...(this._countryCode && { countryCode: this._countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n ...(availableShippingOptions && {\n newShippingOptionParameters: availableShippingOptions,\n }),\n ...(newOfferInfo && {\n newOfferInfo,\n }),\n ...(error && {\n error,\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\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';\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 PayPalCommerceSdk(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';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PayPalSdkHelper } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\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 GooglePayBigCommercePaymentsGateway from './google-pay-bigcommerce-payments-gateway';\n\nconst createGooglePayBigCommercePaymentsButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayBigCommercePaymentsGateway(\n paymentIntegrationService,\n new PayPalSdkHelper(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayBigCommercePaymentsButtonStrategy, [\n { id: 'googlepay_bigcommerce_payments' },\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';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\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';\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 StripeScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayStripeButtonStrategy, [\n { id: 'googlepaystripe' },\n { id: 'googlepaystripeupe' },\n { id: 'googlepaystripeocs' },\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 PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n PaypalButtonCreationService,\n PayPalButtonOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\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 paypalIntegrationService: PayPalIntegrationService,\n private paypalButtonCreationService: PaypalButtonCreationService,\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.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, isAppSwitchEnabled } =\n paymentMethod.initializationData || {};\n\n const buyNowFlowCallbacks = {\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const buttonOptions: PayPalButtonOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalIntegrationService.getValidButtonStyle(style),\n isAppSwitchEnabled,\n isHostedCheckoutEnabled,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && onComplete && { onPaymentComplete: () => onComplete() }),\n };\n\n const paypalButton = this.paypalButtonCreationService.createPayPalButton(\n 'paypalcommerce',\n methodId,\n buttonOptions,\n buyNowInitializeOptions,\n );\n\n if (paypalButton.isEligible()) {\n if (paypalButton.hasReturned?.() && isAppSwitchEnabled) {\n paypalButton.resume?.();\n } else {\n paypalButton.render(`#${containerId}`);\n }\n } else if (onEligibilityFailure && typeof onEligibilityFailure === 'function') {\n onEligibilityFailure();\n } else {\n this.paypalIntegrationService.removeElement(containerId);\n }\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalIntegrationService,\n PaypalButtonCreationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceButtonStrategy from './paypal-commerce-button-strategy';\n\nconst createPayPalCommerceButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceButtonStrategy\n> = (paymentIntegrationService) => {\n const paypalIntegrationService = createPayPalIntegrationService(paymentIntegrationService);\n const paypalButtonCreationService = new PaypalButtonCreationService(\n paymentIntegrationService,\n paypalIntegrationService,\n );\n\n return new PayPalCommerceButtonStrategy(\n paymentIntegrationService,\n paypalIntegrationService,\n paypalButtonCreationService,\n );\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 ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalButtonsOptions,\n PayPalBuyNowInitializeOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\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 paypalIntegrationService: PayPalIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPayPalCommerceCreditButtonInitializeOptions,\n ): Promise {\n const { paypalcommercecredit, containerId, methodId } = options;\n const { buyNowInitializeOptions, currencyCode: providedCurrencyCode } =\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.paypalIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommercecredit);\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.paypalIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, isAppSwitchEnabled } =\n paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n createOrder: () => this.paypalIntegrationService.createOrder('paypalcommercecredit'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const hostedCheckoutCallbacks = {\n ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n }),\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: PayPalButtonsOptions = {\n fundingSource,\n style: this.paypalIntegrationService.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.paypalIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalIntegrationService.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.paypalIntegrationService.getBillingAddressFromOrderDetails(orderDetails);\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalIntegrationService.getShippingAddressFromOrderDetails(orderDetails);\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalIntegrationService.updateOrder('paypalcommerce');\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalIntegrationService.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.paypalIntegrationService.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.paypalIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalIntegrationService.updateOrder('paypalcommerce');\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.paypalIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalIntegrationService.updateOrder('paypalcommerce');\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';\nimport { createPayPalIntegrationService } from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceCreditButtonStrategy from './paypal-commerce-credit-button-strategy';\n\nconst createPayPalCommerceCreditButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceCreditButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditButtonStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\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 { 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 { 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 { round } from 'lodash';\n\nimport {\n AmountTransformer,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n Payment,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n ShippingOption,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n isStripePaymentMethodLike,\n StripeAdditionalActionRequired,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeError,\n StripeEventType,\n StripeInitializationData,\n StripeIntegrationService,\n StripeLinkV2Event,\n StripeLinkV2Options,\n StripeLinkV2ShippingRate,\n StripePaymentMethodType,\n StripeResult,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport {\n expressCheckoutAllowedCountryCodes,\n stripeAllowedShippingOptionsLength,\n} from './constants';\nimport { WithStripeOCSCustomerInitializeOptions } from './stripe-ocs-customer-initialize-options';\n\nexport default class StripeLinkV2ButtonStrategy implements CheckoutButtonStrategy {\n private _stripeClient?: StripeClient;\n private _stripeElements?: StripeElements;\n private _linkV2Element?: StripeElement;\n private _amountTransformer?: AmountTransformer;\n private _onComplete?: (orderId?: number) => Promise;\n private _loadingIndicatorContainer?: string;\n private _currencyCode?: string;\n private _captureMethod?: 'automatic' | 'manual';\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n private stripeIntegrationService: StripeIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithStripeOCSCustomerInitializeOptions,\n ): Promise {\n const { stripeocs, containerId } = options || {};\n\n if (!stripeocs || !containerId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { gatewayId } = stripeocs;\n\n if (!gatewayId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const methodId = this._getMethodId(gatewayId);\n const state = await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n const paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n const { loadingContainerId, buttonHeight, onComplete } = stripeocs;\n\n this._loadingIndicatorContainer = loadingContainerId;\n\n this._onComplete = onComplete;\n\n if (!isStripePaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { initializationData } = paymentMethod;\n const { captureMethod } = initializationData;\n const stripeJsVersion =\n this.stripeIntegrationService.getStripeJsVersion(initializationData);\n\n this._captureMethod = captureMethod;\n this._stripeClient = await this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n stripeJsVersion,\n );\n\n await this.paymentIntegrationService.loadDefaultCheckout();\n\n await this._mountExpressCheckoutElement(containerId, this._stripeClient, buttonHeight);\n\n this._initializeEvents(methodId);\n }\n\n signIn() {\n return Promise.resolve();\n }\n\n signOut() {\n return Promise.resolve();\n }\n\n executePaymentMethodCheckout() {\n return Promise.resolve();\n }\n\n deinitialize() {\n return Promise.resolve();\n }\n\n private async _mountExpressCheckoutElement(\n container: string,\n stripeExpressCheckoutClient: StripeClient,\n buttonHeight = 40,\n ) {\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n const expressCheckoutOptions: StripeElementsCreateOptions = {\n shippingAddressRequired: shouldRequireShippingAddress,\n ...(shouldRequireShippingAddress\n ? { allowedShippingCountries: await this._getAvailableCountries() }\n : {}),\n ...(shouldRequireShippingAddress\n ? { shippingRates: [{ id: '_', amount: 0, displayName: 'Pending rates' }] }\n : {}),\n billingAddressRequired: true,\n emailRequired: true,\n phoneNumberRequired: true,\n paymentMethods: {\n link: StripeStringConstants.AUTO,\n applePay: StripeStringConstants.NEVER,\n googlePay: StripeStringConstants.NEVER,\n amazonPay: StripeStringConstants.NEVER,\n paypal: StripeStringConstants.NEVER,\n klarna: StripeStringConstants.NEVER,\n },\n // Minimal buttonHeight value is 40\n buttonHeight,\n };\n\n const { cartAmount = 1 } = this.paymentIntegrationService.getState().getCart() || {};\n\n const elementsOptions: StripeLinkV2Options = {\n mode: 'payment',\n amount: this._toCents(cartAmount),\n currency: this._getCurrency(),\n ...(this._captureMethod ? { captureMethod: this._captureMethod } : {}),\n };\n\n this._stripeElements = stripeExpressCheckoutClient.elements(elementsOptions);\n\n this._linkV2Element = this._stripeElements.create(\n StripeElementType.EXPRESS_CHECKOUT,\n expressCheckoutOptions,\n );\n this._linkV2Element.mount(`#${container}`);\n }\n\n /** Events * */\n\n private _initializeEvents(methodId: string): void {\n if (!this._linkV2Element) {\n return;\n }\n\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n\n if (shouldRequireShippingAddress) {\n this._linkV2Element.on(StripeElementEvent.SHIPPING_ADDRESS_CHANGE, async (event) =>\n this._onShippingAddressChange(event),\n );\n this._linkV2Element.on(StripeElementEvent.SHIPPING_RATE_CHANGE, async (event) =>\n this._onShippingRateChange(event),\n );\n }\n\n this._linkV2Element.on(StripeElementEvent.CONFIRM, async (event) =>\n this._onConfirm(event, methodId),\n );\n\n this._linkV2Element.on(StripeElementEvent.CANCEL, this._onCancel);\n }\n\n private async _onShippingAddressChange(event: StripeEventType) {\n if (!('address' in event)) {\n return;\n }\n\n const shippingAddress = event.address;\n // Depending on the country, some fields can be missing or partially redacted.\n // For example, the shipping address in the US can only contain a city, state, and ZIP code.\n // The full shipping address appears in the confirm event object after the purchase is confirmed in the browser’s payment interface.\n const result = {\n firstName: '',\n lastName: '',\n phone: '',\n company: '',\n address1: '',\n address2: '',\n city: shippingAddress?.city || '',\n countryCode: shippingAddress?.country || '',\n postalCode: shippingAddress?.postal_code || '',\n stateOrProvince: shippingAddress?.state || '',\n stateOrProvinceCode: shippingAddress?.state || '',\n customFields: [],\n };\n\n await this.paymentIntegrationService.updateShippingAddress(result);\n\n const shippingRates = await this._getAvailableShippingOptions();\n\n await this._updateDisplayedPrice();\n\n if (!shippingRates?.length) {\n event.reject();\n } else {\n event.resolve({\n shippingRates,\n });\n }\n }\n\n private _onCancel() {\n throw new PaymentMethodCancelledError();\n }\n\n private async _onShippingRateChange(event: StripeEventType) {\n if ('shippingRate' in event) {\n const { shippingRate } = event;\n\n await this._handleShippingOptionChange(shippingRate?.id);\n\n await this._updateDisplayedPrice();\n\n event.resolve({});\n }\n }\n\n /** Confirm methods * */\n private async _onConfirm(event: StripeEventType, methodId: string) {\n if (\n 'billingDetails' in event &&\n 'shippingAddress' in event &&\n this._stripeClient &&\n this._stripeElements\n ) {\n await this._updateShippingAndBillingAddress(event);\n await this.paymentIntegrationService.submitOrder();\n\n const paymentPayload = this._getPaymentPayload(methodId);\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._processAdditionalAction(error, methodId);\n }\n }\n\n return Promise.resolve();\n }\n\n private async _updateShippingAndBillingAddress(event: StripeLinkV2Event) {\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n\n const firstName =\n event.shippingAddress?.name?.split(' ')[0] ||\n event.billingDetails?.name?.split(' ')[0] ||\n '';\n const lastName =\n event.shippingAddress?.name?.split(' ')[1] ||\n event.billingDetails?.name?.split(' ')[1] ||\n '';\n\n if (shouldRequireShippingAddress) {\n const shippingAddress = this._mapShippingAddress(\n event.shippingAddress,\n event.billingDetails,\n firstName,\n lastName,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n }\n\n const billingAddress = this._mapBillingAddress(\n event.shippingAddress,\n event.billingDetails,\n firstName,\n lastName,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n private _mapShippingAddress(\n shippingAddress: StripeLinkV2Event['shippingAddress'],\n billingDetails: StripeLinkV2Event['billingDetails'],\n firstName: string,\n lastName: string,\n ) {\n return {\n firstName,\n lastName,\n phone: billingDetails?.phone || '',\n company: '',\n address1: shippingAddress?.address?.line1 || '',\n address2: shippingAddress?.address?.line2 || '',\n city: shippingAddress?.address?.city || '',\n countryCode: shippingAddress?.address?.country || '',\n postalCode: shippingAddress?.address?.postal_code || '',\n stateOrProvince: shippingAddress?.address?.state || '',\n stateOrProvinceCode: shippingAddress?.address?.state || '',\n customFields: [],\n };\n }\n\n private _mapBillingAddress(\n shippingAddress: StripeLinkV2Event['shippingAddress'],\n billingDetails: StripeLinkV2Event['billingDetails'],\n firstName: string,\n lastName: string,\n ) {\n return {\n email: billingDetails?.email || '',\n firstName,\n lastName,\n phone: billingDetails?.phone || '',\n company: '',\n address1: billingDetails?.address?.line1 || '',\n address2: '',\n city: billingDetails?.address?.city || '',\n countryCode: billingDetails?.address?.country || '',\n postalCode: billingDetails?.address?.postal_code || '',\n stateOrProvince: billingDetails?.address?.state || '',\n stateOrProvinceCode: shippingAddress?.address?.state || '',\n customFields: [],\n };\n }\n\n private async _processAdditionalAction(error: unknown, methodId: string): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n if (!this._stripeClient || !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 additionalActionData,\n methodId,\n );\n\n const paymentPayload = this._getPaymentPayload(methodId, paymentIntent?.id || token);\n\n try {\n this._toggleLoadingIndicator(true);\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n await this._completeCheckoutFlow();\n } catch (error) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n } finally {\n this._toggleLoadingIndicator(false);\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n additionalActionData: StripeAdditionalActionRequired['data'],\n methodId: string,\n ): Promise {\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeIntegrationService.mapStripePaymentData(\n this._stripeElements,\n redirect_url,\n );\n let stripeError: StripeError | undefined;\n\n try {\n const isPaymentCompleted = await this.stripeIntegrationService.isPaymentCompleted(\n methodId,\n this._stripeClient,\n );\n\n const confirmationResult = !isPaymentCompleted\n ? await this._stripeClient?.confirmPayment({\n elements: stripePaymentData.elements,\n clientSecret: token,\n redirect: StripeStringConstants.IF_REQUIRED,\n confirmParams: {\n return_url: stripePaymentData.confirmParams?.return_url,\n },\n })\n : await this._stripeClient?.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 return this.stripeIntegrationService.throwStripeError(stripeError);\n }\n }\n\n private async _completeCheckoutFlow() {\n if (typeof this._onComplete === 'function') {\n return this._onComplete();\n }\n\n window.location.replace('/checkout/order-confirmation');\n\n return Promise.resolve();\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 ...(token ? { credit_card_token: { token } } : {}),\n confirm: false,\n method: StripePaymentMethodType.Link,\n };\n\n return {\n methodId,\n paymentData: {\n formattedPayload,\n },\n };\n }\n\n /** Utils * */\n\n private _shouldRequireShippingAddress() {\n const { getCart } = this.paymentIntegrationService.getState();\n\n const { lineItems } = getCart() || {};\n\n return !!lineItems?.physicalItems.length;\n }\n\n private async _updateDisplayedPrice() {\n if (this._stripeElements) {\n this._stripeElements.update({\n currency: this._getCurrency(),\n mode: 'payment',\n amount: await this._getTotalPrice(),\n });\n }\n }\n\n private _getCurrency() {\n if (!this._currencyCode) {\n const currencyCode = this.paymentIntegrationService.getState().getCart()?.currency;\n\n if (currencyCode) {\n this._currencyCode = currencyCode.code.toLowerCase();\n }\n }\n\n return this._currencyCode;\n }\n\n private async _getTotalPrice(): Promise {\n await this.paymentIntegrationService.loadCheckout();\n\n const { getCheckoutOrThrow, getCart } = this.paymentIntegrationService.getState();\n const { decimalPlaces } = getCart()?.currency || {};\n const totalPrice = round(getCheckoutOrThrow().outstandingBalance, decimalPlaces).toFixed(\n decimalPlaces,\n );\n\n return this._toCents(+totalPrice);\n }\n\n private async _getAvailableCountries(): Promise {\n const countries = await this.paymentIntegrationService.loadShippingCountries();\n const deliverableCountries =\n countries.getShippingCountries()?.map((country) => country.code) || [];\n\n return deliverableCountries.filter((code) => {\n return expressCheckoutAllowedCountryCodes.includes(code);\n });\n }\n\n private async _getAvailableShippingOptions(): Promise {\n const state = this.paymentIntegrationService.getState();\n const consignments = state.getConsignments();\n\n if (!consignments?.[0]) {\n return;\n }\n\n const consignment = consignments[0];\n const options = (consignment.availableShippingOptions || []).map(\n this._getStripeShippingOption.bind(this),\n );\n const recommendedShippingOption = consignment.availableShippingOptions?.find(\n (shippingOption) => shippingOption.isRecommended,\n );\n const selectedId = consignment.selectedShippingOption?.id;\n const recommendedId = recommendedShippingOption?.id;\n\n if (selectedId) {\n // Set selected shipping option first in the array, as it will be selected by default\n options.sort((option) => (option.id === selectedId ? -1 : 0));\n } else if (recommendedId) {\n // Set recommended shipping option first in the array, as it will be selected by default\n options.sort((option) => (option.id === recommendedId ? -1 : 0));\n await this._handleShippingOptionChange(recommendedId);\n } else {\n await this._handleShippingOptionChange(options[0]?.id);\n }\n\n // Stripe has restricted the number of shipping rates.\n return options.slice(0, stripeAllowedShippingOptionsLength);\n }\n\n private _getStripeShippingOption({ id, cost, description }: ShippingOption) {\n return {\n id,\n displayName: description,\n amount: this._toCents(cost),\n };\n }\n\n private async _handleShippingOptionChange(optionId?: string) {\n if (!optionId || optionId === 'shipping_option_unselected') {\n return;\n }\n\n return this.paymentIntegrationService.selectShippingOption(optionId);\n }\n\n private _getAmountTransformer() {\n if (this._amountTransformer) {\n return this._amountTransformer;\n }\n\n const { getCart } = this.paymentIntegrationService.getState();\n const { currency } = getCart() || {};\n\n if (currency) {\n const amountTransformer = new AmountTransformer(currency.decimalPlaces);\n\n return amountTransformer;\n }\n }\n\n private _toCents(amount: number) {\n const fallbackValue = Math.round(amount * 100);\n const amountTransformer = this._getAmountTransformer();\n\n if (amountTransformer) {\n return amountTransformer.toInteger(amount);\n }\n\n return fallbackValue;\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 _getMethodId(gatewayId: string): string {\n const { initializationData: { checkoutSessionEnabled } = {} } =\n this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(gatewayId);\n\n return checkoutSessionEnabled\n ? StripePaymentMethodType.CHECKOUT_SESSION\n : StripePaymentMethodType.OCS;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\nimport { DEFAULT_CONTAINER_STYLES, LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport StripeLinkV2ButtonStrategy from './stripe-link-v2-button-strategy';\n\nconst createLinkV2ButtonStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n const loadingIndicator = new LoadingIndicator({\n containerStyles: DEFAULT_CONTAINER_STYLES,\n });\n\n return new StripeLinkV2ButtonStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n loadingIndicator,\n );\n};\n\nexport default toResolvableModule(createLinkV2ButtonStrategy, [{ id: 'stripeocs' }]);\n","import { uniqueId } from 'lodash';\n\nimport { InvalidArgumentError } from '../error/errors';\n\nconst getUniqId = (idPrefix?: string): string => {\n const id = uniqueId(idPrefix);\n\n return document.getElementById(id) ? getUniqId(idPrefix) : id;\n};\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 = getUniqId(idPrefix);\n }\n\n return container.id;\n });\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 { 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 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","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 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 { 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 { 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","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 = '',\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 { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { createCheckoutStore } from '../checkout';\nimport { ConfigState } from '../config';\nimport * as defaultCheckoutButtonStrategyFactories from '../generated/checkout-button-strategies';\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 } = 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(\n paymentIntegrationService,\n process.env.ESSENTIAL_BUILD ? {} : defaultCheckoutButtonStrategyFactories,\n );\n\n return new CheckoutButtonInitializer(\n store,\n new CheckoutButtonStrategyActionCreator(\n createCheckoutButtonRegistry(store, requestSender, formPoster, 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';\n\nexport interface CheckoutButtonStrategyFactories {\n [key: string]: CheckoutButtonStrategyFactory;\n}\n\nexport default function createCheckoutButtonStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n checkoutButtonStrategyFactories: CheckoutButtonStrategyFactories,\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 { CheckoutActionCreator, CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { PaypalScriptLoader } from '../payment/strategies/paypal';\n\nimport { CheckoutButtonMethodType, CheckoutButtonStrategy } from './strategies';\nimport { PaypalButtonStrategy } from './strategies/paypal';\n\nexport default function createCheckoutButtonRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\n formPoster: FormPoster,\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 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 { 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 { 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","import { FormatError, IntlMessageFormat } from 'intl-messageformat';\nimport { isObject, union } from 'lodash';\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\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 }\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._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 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 }, {});\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","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 { 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","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":["y","x","module","exports","iframeResizer","__WEBPACK_EXTERNAL_MODULE_iframe_resizer_1512d797__","__webpack_require__","d","__WEBPACK_EXTERNAL_MODULE_iframe_resizer_js_iframeResizer_contentWindow_a6cfc03f__","__webpack_module_cache__","moduleId","cachedModule","undefined","__webpack_modules__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","r","Symbol","toStringTag","value","B2B_EXTRA_FIELD_PREFIX","isExtraField","field","name","startsWith","mapExtraFieldToFormField","extraField","fieldType","type","extraFieldType","getFieldTypeInfo","options","config","numberOfRows","rows","_a","length","assign","items","map","val","label","id","custom","hidden","visibleToStorefront","required","isRequired","default","defaultValue","String","maxLength","max","maxValue","throwErrorAction","error","meta","action","__WEBPACK_EXTERNAL_MODULE_rxjs_concat__","__WEBPACK_EXTERNAL_MODULE_rxjs_of__","__WEBPACK_EXTERNAL_MODULE_rxjs_throwError__","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_createErrorAction__","payload","B2BTokenActionType","B2BTokenActionCreator","constructor","_requestSender","this","loadB2BToken","store","state","getState","storeConfig","getStoreConfigOrThrow","storeHash","storeProfile","baseUrl","b2bBaseUrl","clientId","b2bClientId","b2bApiSettings","customerId","customer","getCustomerOrThrow","channelId","checkout","getCheckoutOrThrow","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_createAction__","LoadB2BTokenRequested","__WEBPACK_EXTERNAL_MODULE_rxjs_defer__","__awaiter","body","getB2BToken","LoadB2BTokenSucceeded","token","data","pipe","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_catchError__","LoadB2BTokenFailed","SDK_VERSION_HEADERS","MissingDataErrorType","BillingAddressActionType","B2BTokenRequestSender","appClientId","jwtBody","timeout","params","app_client_id","headers","post","credentials","bcToken","StandardError","Error","message","super","setPrototypeOf","__proto__","captureStackTrace","stack","MissingDataError","subtype","MissingBillingAddress","MissingCart","MissingConsignments","MissingCheckout","MissingCustomer","MissingCheckoutConfig","MissingOrderConfig","MissingOrder","MissingOrderId","MissingPayment","MissingPaymentToken","MissingPaymentMethod","MissingPaymentProviderCustomer","MissingShippingAddress","getErrorMessage","UnableToContinueAsGuestError","ContentType","BillingAddressActionCreator","_subscriptionActionCreator","continueAsGuest","getCheckout","getCustomer","isGuest","billingAddress","getBillingAddress","billingAddressRequestBody","country","existingBillingAddressRequestBody","__rest","hasBillingAddress","__WEBPACK_EXTERNAL_MODULE_lodash_isEmpty__","__WEBPACK_EXTERNAL_MODULE_rxjs_merge__","ContinueAsGuestRequested","billing_address_action_creator_awaiter","_createOrUpdateBillingAddress","ContinueAsGuestSucceeded","ContinueAsGuestFailed","_updateCustomerConsent","updateAddress","address","__WEBPACK_EXTERNAL_MODULE_rxjs_Observable__","create","observer","next","UpdateBillingAddressRequested","email","then","UpdateBillingAddressSucceeded","complete","catch","response","UpdateBillingAddressFailed","acceptsAbandonedCartEmails","acceptsMarketingNewsletter","__WEBPACK_EXTERNAL_MODULE_rxjs_empty__","updateSubscriptions","checkoutId","createAddress","EmptyCartError","content_type","DEFAULT_PARAMS","include","join","BillingAddressRequestSender","url","Accept","JsonV1","err","billing_address_request_sender_rest","put","ProjectionActionType","ErrorActionType","createDataStoreProjection","stateTransformer","projection","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_createDataStore__","Synchronize","subscribe","dispatch","initial","ErrorActionCreator","clearError","ClearError","ExperimentAwareRequestSender","_config","sendRequest","_prefixed","patch","delete","basePath","getBasePath","getFeatures","endsWith","test","getEnvironment","e","ConsoleLogger","_console","log","messages","_logToConsole","info","warn","debug","NoopLogger","logger","isEnabled","console","createLogger","getDefaultLogger","cachableActionDecorator","_","descriptor","memoizedMethods","WeakMap","decorateMethod","method","args","lastArg","useCache","param","instanceMethods","fn","set","__WEBPACK_EXTERNAL_MODULE__bigcommerce_memoize_bf7b411a_memoize__","__WEBPACK_EXTERNAL_MODULE_rxjs_from__","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_shareReplay__","isEqual","__WEBPACK_EXTERNAL_MODULE_lodash_isEqual__","ConfigActionType","ConfigActionCreator","_configRequestSender","loadConfig","LoadConfigRequested","LoadConfigSucceeded","LoadConfigFailed","__decorate","DEFAULT_RESPONSE","status","RequestError","errors","CheckoutNotAvailableError","title","INTERNAL_USE_ONLY","ConfigRequestSender","CouponActionType","CouponActionCreator","_couponRequestSender","applyCoupon","code","ApplyCouponRequested","ApplyCouponSucceeded","ApplyCouponFailed","removeCoupon","RemoveCouponRequested","RemoveCouponSucceeded","RemoveCouponFailed","checkout_default_includes","CheckoutIncludes","GiftCertificateActionType","CartSource","CustomerActionType","joinIncludes","includes","__WEBPACK_EXTERNAL_MODULE_lodash_uniq__","CouponRequestSender","couponCode","AvailableShippingOptions","GiftCertificateActionCreator","_giftCertificateRequestSender","applyGiftCertificate","giftCertificate","ApplyGiftCertificateRequested","ApplyGiftCertificateSucceeded","ApplyGiftCertificateFailed","removeGiftCertificate","RemoveGiftCertificateRequested","RemoveGiftCertificateSucceeded","RemoveGiftCertificateFailed","GiftCertificateRequestSender","giftCertificateCode","isResolvableModule","InvalidArgumentError","Registry","_factories","_instances","_defaultToken","defaultToken","_useFallback","_b","useFallback","_tokenResolver","_c","tokenResolver","cacheToken","_getInstance","getFactory","exactMatch","resolvedToken","keys","register","factory","_hasFactory","_hasInstance","ResolveIdRegistry","_registry","_resolveToken","bind","_encodeToken","resolveId","getUseFallback","btoa","JSON","stringify","_decodeToken","parse","atob","registeredTokens","query","results","forEach","registeredToken","resolverId","result","matches","totalKeys","entries","push","matchedResults","sort","a","b","filter","queryKeyCount","exactResult","find","matched","isSpamProtectionExecuteSucceededAction","succeededAction","CustomerStrategyActionType","CheckoutActionType","CheckoutHydrateActionType","CustomerActionCreator","_customerRequestSender","_checkoutActionCreator","_spamProtectionActionCreator","createCustomer","customerAccount","isStorefrontSpamProtectionEnabled","checkoutSettings","createAccount","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_switchMap__","loadCurrentCheckout","CreateCustomerSucceeded","CreateCustomerRequested","execute","CreateCustomerFailed","customerAddress","CreateCustomerAddressRequested","customer_action_creator_awaiter","CreateCustomerAddressSucceeded","CreateCustomerAddressFailed","signInCustomer","cartId","cart","source","BuyNow","SignInCustomerRequested","persistentCartRetrievalInformation","loadCheckout","SignInCustomerSucceeded","SignInCustomerFailed","signOutCustomer","SignOutCustomerRequested","SignOutCustomerSucceeded","SignOutCustomerFailed","CustomerRequestSender","registerIntegrations","registry","integrations","paymentIntegrationService","resolveIds","CustomerStrategyActionCreator","_strategyRegistry","_strategyRegistryV2","_paymentIntegrationService","signIn","methodId","SignInRequested","_getStrategy","SignInSucceeded","SignInFailed","signOut","SignOutRequested","SignOutSucceeded","SignOutFailed","executePaymentMethodCheckout","ExecutePaymentMethodCheckoutRequested","ExecutePaymentMethodCheckoutSucceeded","ExecutePaymentMethodCheckoutFailed","initialize","customerStrategies","isInitialized","InitializeRequested","InitializeSucceeded","InitializeFailed","deinitialize","DeinitializeRequested","DeinitializeSucceeded","DeinitializeFailed","widgetInteraction","WidgetInteractionStarted","WidgetInteractionFinished","WidgetInteractionFailed","strategy","joinOrMergeIncludes","baseIncludes","includeDictionaryOrList","Array","isArray","includesDictionary","deletions","__WEBPACK_EXTERNAL_MODULE_lodash_keys__","__WEBPACK_EXTERNAL_MODULE_lodash_pickBy__","on","additions","__WEBPACK_EXTERNAL_MODULE_lodash_filter__","__WEBPACK_EXTERNAL_MODULE_lodash_difference__","mergeIncludes","CheckoutRequestSender","updateCheckout","FormFieldsActionType","CheckoutActionCreator","_checkoutRequestSender","_configActionCreator","_formFieldsActionCreator","LoadCheckoutRequested","loadFormFields","LoadCheckoutSucceeded","_transformCustomerAddresses","LoadCheckoutFailed","loadDefaultCheckout","checkout_action_creator_awaiter","context","getContextConfig","UpdateCheckoutRequested","UpdateCheckoutSucceeded","UpdateCheckoutFailed","hydrateInitialState","HydrateInitialState","addresses","shouldSaveAddress","SpamProtectionActionType","FormFieldsActionCreator","_formFieldsRequestSender","LoadFormFieldsRequested","form_fields_action_creator_awaiter","loadFields","LoadFormFieldsSucceeded","LoadFormFieldsFailed","form_fields_action_creator_decorate","FormFieldsRequestSender","SpamProtectionChallengeNotCompletedError","SpamProtectionFailedError","NotInitializedErrorType","ExtensionActionType","ExtensionInternalEventType","SpamProtectionActionCreator","_googleRecaptcha","spam_protection_action_creator_awaiter","spamProtectionElementId","containerId","document","getElementById","reset","spamProtectionElement","createElement","setAttribute","appendChild","recaptchaSitekey","googleRecaptchaSitekey","load","verifyCheckoutSpamProtection","VerifyCheckoutRequested","validate","VerifyCheckoutSucceeded","VerifyCheckoutFailed","ExecuteRequested","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_take__","ExecuteSucceeded","ExecuteFailed","MutationObserverFactory","_window","window","callback","MutationObserver","NotInitializedError","CustomerNotInitialized","PaymentNotInitialized","ShippingNotInitialized","SpamProtectionNotInitialized","not_initialized_error_getErrorMessage","SpamProtectionNotLoadedError","GoogleRecaptcha","googleRecaptchaScriptLoader","mutationObserverFactory","_memoized","recaptcha","sitekey","container","event$","__WEBPACK_EXTERNAL_MODULE_rxjs_Subject__","_widgetId","render","size","getResponse","_event$","_recaptcha","element","remove","querySelector","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_retryWhen__","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_delay__","index","TIMEOUT","_watchRecaptchaChallengeWindow","event","iframeContainer","parentElement","style","visibility","observe","attributes","attributeFilter","GoogleRecaptchaScriptLoader","_scriptLoader","_loadPromise","_loadScript","callbackName","Promise","resolve","reject","grecaptcha","loadScript","createSpamProtection","scriptLoader","SpamProtectionRequestSender","DefaultCustomerStrategy","_store","_customerActionCreator","continueWithCheckoutCallback","parseUrl","anchor","href","port","indexOf","hostname","hash","origin","protocol","pathname","search","ExtensionNotFoundError","isIframeEvent","object","IframeEventPoster","targetOrigin","_targetWindow","_context","_targetOrigin","targetWindow","__WEBPACK_EXTERNAL_MODULE_rxjs_fromEvent__","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_filter__","successType","errorType","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_map__","toPromise","postMessage","setTarget","setContext","createExtensionEventPoster","extension","iframe","contentWindow","CancellablePromise","promise","cancellable","cancel","race","UnexpectedDetachmentError","ExtensionInternalCommandType","DetachmentObserver","_mutationObserver","ensurePresence","targets","mutationsList","mutation","from","removedNodes","node","some","target","contains","childList","subtree","output","disconnect","originalIframeResizer","ExtensionNotLoadedError","ResizableIframeCreator","_options","createFrame","src","initCallback","failedCallback","border","display","width","_toResizableFrame","removeChild","timeoutInterval","detachmentObserver","setTimeout","handleMessage","ResizeIframe","iframes","autoResize","scrolling","sizeWidth","heightCalculationMethod","teardown","removeEventListener","clearTimeout","addEventListener","ExtensionIframe","_containerId","_extension","parentOrigin","_url","URL","searchParams","attach","iframeCreator","iframeResizerCallback","_iframe","toString","ExtensionReady","ExtensionFailed","detach","ExtensionActionCreator","loadExtensions","LoadExtensionsRequested","extensions","LoadExtensionsSucceeded","LoadExtensionsFailed","renderExtension","region","workerExtensionMessenger","extension_action_creator_awaiter","getCartOrThrow","links","checkoutLink","getExtensionByRegion","RenderExtensionRequested","worker","Worker","blob","createObjectURL","Blob","createExtensionWebWorker","add","RenderExtensionSucceeded","RenderExtensionFailed","ExtensionRequestSender","bind_decorator","bindMethodDecorator","decoratedTarget","getOwnPropertyNames","getOwnPropertyDescriptor","bindClassDecorator","boundMethod","ExtensionCommandType","ExtensionQueryType","WorkerEventListener","_worker","_isListening","_listeners","listen","_handleMessage","stopListen","addListener","listener","listeners","removeListener","splice","trigger","messageEvent","worker_event_listener_rest","worker_event_listener_decorate","WorkerEventPoster","UnsupportedExtensionCommandError","UnsupportedExtensionQueryError","WorkerExtensionMessenger","_workers","_commandListeners","_queryListeners","extensionId","listenForCommand","command","commandHandler","_getWorkerById","validCommandType","_validateCommand","commandHandlerProxy","listenForQuery","queryHandler","validQueryType","_validateQuery","queryHandlerProxy","clearCacheById","values","appendWww","replace","ExtensionEventType","IframeEventListener","sourceOrigin","_sourceOrigins","iframe_event_listener_rest","iframe_event_listener_decorate","ExtensionMessenger","_workerExtensionMessenger","_posters","clearCacheByRegion","_getExtensionByRegion","_getExtensionById","_getExtensions","_extensions","getExtensions","ExtensionEventBroadcaster","_extensionMessenger","_subscribers","_subscribed","_unsubscribers","eventListener","Subscribe","_handleSubscribe","Unsubscribe","_handleUnsubscribe","broadcast","eventType","subscribeConsignmentsChange","broadcaster","getConsignments","getInitialConsignments","consignments","currentConsignments","ConsignmentsChanged","previousConsignments","standard_error_StandardError","missing_data_error_MissingDataErrorType","not_initialized_error_NotInitializedErrorType","missing_data_error_MissingDataError","missing_data_error_getErrorMessage","getShippableItemsCount","lineItems","physicalItems","item","addedByPromotion","__WEBPACK_EXTERNAL_MODULE_lodash_reduce__","total","quantity","guard","errorFactory","not_initialized_error_NotInitializedError","errors_not_initialized_error_getErrorMessage","amazonPayV2Regions","de","jp","uk","us","AmazonPayV2CheckoutLanguage","AmazonPayV2Placement","AmazonPayV2LedgerCurrency","AmazonPayV2PayOptions","AmazonPayV2ButtonColor","AmazonPayV2ButtonDesign","AmazonPayV2PaymentProcessor","amazonPayV2ScriptLoader","paymentMethod","amazonPayV2SDK","buttonParentContainer","createAmazonPayButtonParentContainer","amazonPayV2Button","bindButton","buttonId","sessionId","changeAction","getAmazonPayV2SDK","Pay","bindChangeAction","amazonCheckoutSessionId","createButton","renderButton","prepareCheckout","createCheckoutSessionConfig","requestConfig","prepareRequestConfig","getAmazonPayV2Button","onClick","initCheckout","prepareCheckoutWithCreationRequestConfig","createCheckoutConfig","amazon_pay_v2_payment_processor_awaiter","estimatedOrderAmount","productType","signout","renderAmazonPayButton","buttonColor","checkoutState","decoupleCheckoutInitiation","placement","isButtonMicroTextDisabled","parentContainerId","getButtonParentContainer","design","C0001","amazonPayV2ButtonOptions","getAmazonPayV2ButtonOptions","updateBuyNowFlowFlag","isBuyNowFlow","Boolean","isPh4Enabled","features","storeCountryCode","isPh4UsOnly","publicKeyId","signedPayload","amazon_pay_v2_payment_processor_rest","isEnvironmentSpecific","uid","Math","random","substr","parentContainer","Gold","getCart","getPaymentMethodOrThrow","getCheckoutState","merchantId","testMode","initializationData","checkoutLanguage","checkoutSessionMethod","extractAmazonCheckoutSessionId","ledgerCurrency","buttonBaseConfig","sandbox","PayOnly","PayAndShip","shopPath","amount","outstandingBalance","currencyCode","currency","buttonOptions","tmpConfig","createCheckoutSession","getOrThrow","checkoutSelectors","paymentMethods","PaymentMethodClientUnavailableError","AmazonPayV2ScriptLoader","windowWithAmazonPay","amazonPayV2Region","amazon","createAmazonPayV2PaymentProcessor","__WEBPACK_EXTERNAL_MODULE__bigcommerce_script_loader_875b3e8f_getScriptLoader__","toResolvableModule","invalid_argument_error_InvalidArgumentError","NotImplementedError","AmazonPayV2CustomerStrategy","amazonPayV2PaymentProcessor","amazonpay","_e","loadPaymentMethod","Checkout","payment","getPaymentId","remoteCheckoutSignOut","providerId","create_amazon_pay_v2_customer_strategy","isExperimentEnabled","experimentName","fallbackValue","BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION","BRAINTREE_SDK_DEFAULT_VERSION","BRAINTREE_SDK_STABLE_VERSION","BraintreeSDKVersionManager","braintreeWindow","getSDKVersion","getStoreConfig","getPreloadedSDKVersion","braintree","preloadedVersion","__WEBPACK_EXTERNAL_MODULE_lodash_find__","VERSION","UnsupportedBrowserError","TotalPriceStatusType","BraintreeOrderStatus","NonInstantLocalPaymentMethods","BraintreeFastlaneAuthenticationState","BraintreeErrorType","BraintreeErrorCode","BraintreeSupportedCardBrands","isBraintreeError","BraintreeEnv","BraintreeModuleName","BraintreeFormFieldType","BraintreeSdk","braintreeScriptLoader","clientToken","setClientToken","teardownModule","dataCollector","getClient","client","getClientTokenOrThrow","clientCreator","loadClient","authorization","getDataCollectorOrThrow","emptyDataCollector","deviceData","loadDataCollector","dataCollectorConfig","kount","KountNotEnabled","getBraintreeGooglePayment","googlePayment","braintreeGooglePayment","all","loadGooglePayment","getBraintreeThreeDS","threeDS","threeDSecure","load3DS","version","getBraintreeLocalPayment","merchantAccountId","braintreeLocalPayment","localPaymentCreator","loadLocalPayment","getUsBankAccount","usBankAccount","loadUsBankAccount","getBraintreeVisaCheckout","visaCheckout","loadVisaCheckout","paypal","getVisaCheckoutSdk","visaCheckoutSDK","loadVisaCheckoutSdk","getVenmoCheckoutOrThrow","braintreeVenmo","venmoCheckout","loadVenmoCheckout","venmoCheckoutConfig","allowDesktop","paymentMethodUsage","braintreeVenmoCheckout","isBrowserSupported","BRAINTREE_SDK_SCRIPTS_INTEGRITY","Client","PaypalCheckout","Paypal","LocalPayment","DataCollector","UsBankAccount","GooglePayment","ThreeDSecure","VisaCheckout","Venmo","HostedFields","Fastlane","ApplePayGatewayType","BraintreeScriptLoader","braintreeHostWindow","braintreeSDKVersionManager","loadBraintreeModuleOrThrow","loadFastlane","loadPaypalCheckout","loadPaypal","loadHostedFields","V","async","integrity","crossorigin","braintreeModuleName","fileName","getBraintreeModule","braintreeSdkVersion","scriptPath","getIntegrityValuesByModuleName","moduleName","PaymentMethodCancelledError","DefaultLabels","ApplePayCustomerStrategy","_sessionFactory","_braintreeSdk","_applePayScriptLoader","_onAuthorizeCallback","__WEBPACK_EXTERNAL_MODULE_lodash_noop__","_onError","_onClick","_subTotalLabel","Subtotal","_shippingLabel","Shipping","_hasApplePaySession","applepay","shippingLabel","subtotalLabel","onError","onPaymentAuthorize","loadSdk","_paymentMethod","_applePayButton","_createButton","_handleWalletButtonClick","gateway","BRAINTREE","applePayButton","_createApplePayButtonElement","preventDefault","request","_getBaseRequest","applePaySession","_handleApplePayEvents","begin","storeName","decimalPlaces","merchantCapabilities","supportedNetworks","requiresShipping","requiredBillingContactFields","requiredShippingContactFields","countryCode","grandTotal","toFixed","subtotal","taxes","tax","onvalidatemerchant","apple_pay_customer_strategy_awaiter","merchantSession","_onValidateMerchant","completeMerchantValidation","onshippingcontactselected","_handleShippingContactSelected","onshippingmethodselected","_handleShippingMethodSelected","oncancel","onpaymentauthorized","_onPaymentAuthorized","shippingAddress","_transformContactToAddress","shippingContact","updateShippingAddress","abort","selectionShippingOptionId","selectedShippingOption","availableOptions","availableShippingOptions","selectedOption","unselectedOptions","option","shippingOptions","description","cost","detail","additionalDescription","identifier","isRecommended","completeShippingContactSelection","ApplePaySession","STATUS_INVALID_SHIPPING_POSTAL_ADDRESS","recommendedOption","optionId","selectedOptionId","_updateShippingOption","newShippingMethods","newTotal","newLineItems","_getUpdatedLineItems","shippingMethod","completeShippingMethodSelection","shippingCostTotal","selectShippingOption","paymentData","validationURL","location","paymentsUrl","billingContact","deviceSessionId","_getBraintreeDeviceData","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","assertApplePayWindow","isApplePayWindow","ApplePaySessionFactory","ApplePayScriptLoader","sdkVersion","isApplePaySdkWindow","create_apple_pay_customer_strategy","getHost","__WEBPACK_EXTERNAL_MODULE__bigcommerce_request_sender_01d1f546_createRequestSender__","host","__WEBPACK_EXTERNAL_MODULE__bigcommerce_script_loader_875b3e8f_ScriptLoader__","BuyNowCartCreationError","request_error_DEFAULT_RESPONSE","request_error_RequestError","LiabilityShiftEnum","BigCommercePaymentsIntent","StyleButtonLabel","StyleButtonColor","StyleButtonShape","NonInstantAlternativePaymentMethods","PayPalOrderStatus","BigCommercePaymentsIntegrationService","formPoster","bigCommercePaymentsRequestSender","bigCommercePaymentsScriptLoader","loadPayPalSdk","providedCurrencyCode","initializesOnCheckoutPage","forceLoad","paypalSdk","getPayPalSDK","getPayPalSdkOrThrow","createBuyNowCartOrThrow","buyNowInitializeOptions","cartRequestBody","getBuyNowCartRequestBody","createBuyNowCart","createOrder","requestBody","orderId","createOrderCardFields","setupToken","updateOrder","consignment","getConsignmentsOrThrow","_error","getOrderStatus","tokenizePayment","postForm","payment_type","provider","order_id","cart_id","gatewayId","vault_payment_instrument","set_as_default_stored_instrument","device_info","method_id","paypal_account","getShippingOptionOrThrow","selectedShippingOptionId","recommendedShippingOption","shippingOptionToSelect","getAddress","getBillingAddressFromOrderDetails","payer","given_name","surname","email_address","address_line_1","address_line_2","admin_area_2","country_code","postal_code","admin_area_1","phone_number","national_number","getShippingAddressFromOrderDetails","orderDetails","purchase_units","full_name","shipping","split","getValidButtonStyle","color","height","shape","validStyles","getValidHeight","__WEBPACK_EXTERNAL_MODULE_lodash_omitBy__","__WEBPACK_EXTERNAL_MODULE_lodash_isNil__","removeElement","elementId","internal_api_headers_INTERNAL_USE_ONLY","content_type_ContentType","http_request_content_type","sdk_version_headers_SDK_VERSION_HEADERS","BigCommercePaymentsRequestSender","requestSender","Json","BigCommercePaymentsScriptLoader","paypalSdkScriptConfig","getPayPalSdkScriptConfigOrThrow","loadPayPalSDK","bigCommercePaymentsPayPalSDK","transformConfig","scriptSrc","URLSearchParams","intent","buyerCountry","attributionId","isVenmoEnabled","isHostedCheckoutEnabled","isPayPalCreditAvailable","isDeveloperModeApplicable","availableAlternativePaymentMethods","enabledAlternativePaymentMethods","isGooglePayEnabled","commit","shouldEnableCard","enableCardFunding","disableCardFunding","enableCreditFunding","disableCreditFunding","enableVenmoFunding","disableVenmoFunding","disableAPMsFunding","apm","googlePayComponent","cardFieldsComponent","disableFunding","filterFundingOptions","enableFunding","components","fundingOptions","fundingTypesToBeFiltered","fundingOption","transformedConfig","create_bigcommerce_payments_integration_service","__WEBPACK_EXTERNAL_MODULE__bigcommerce_form_poster_1cd9ef62_createFormPoster__","default_checkout_button_height","BigCommercePaymentsCustomerStrategy","bigCommercePaymentsIntegrationService","bigcommerce_payments","getPaymentMethod","Buttons","onComplete","paymentButtonStyles","isAppSwitchEnabled","checkoutTopButtonStyles","defaultCallbacks","appSwitchWhenAvailable","onApprove","orderID","hostedCheckoutCallbacks","onShippingAddressChange","onShippingOptionsChange","actions","onHostedCheckoutApprove","buttonRenderOptions","fundingSource","FUNDING","PAYPAL","paypalButton","isEligible","hasReturned","resume","order","handleError","shippingOption","create_bigcommerce_payments_customer_strategy","UntrustedShippingCardVerificationType","bigcommerce_payments_types_BigCommercePaymentsIntent","bigcommerce_payments_types_LiabilityShiftEnum","TDSecureVerificationMethod","TDSecureAuthenticationState","bigcommerce_payments_types_StyleButtonLabel","bigcommerce_payments_types_StyleButtonColor","bigcommerce_payments_types_StyleButtonShape","PayPalFastlaneAuthenticationState","PayPalSdkHelper","getPayPalFastlaneSdk","bigCommercePaymentsFastlaneSdk","getPayPalFastlaneSdkConfiguration","getPayPalGooglePaySdk","bigCommercePaymentsGooglePay","getPayPalGooglePaySdkScriptConfigOrThrow","getPayPalApmsSdk","bigCommercePaymentsApms","getPayPalApmSdkConfiguration","getPayPalMessages","bigCommercePaymentsMessages","paypalSdkMessagesConfig","getPayPalSdkMessagesConfiguration","scriptOptions","scriptAttributes","enableAPMsFunding","createBigCommercePaymentsSdk","__WEBPACK_EXTERNAL_MODULE__bigcommerce_script_loader_875b3e8f_createScriptLoader__","CookieStorage","cookieKey","encodeURIComponent","cookie","firstIndex","lastIndex","decodeURIComponent","substring","secure","cookieText","expires","path","domain","toUTCString","now","Date","minutes","setTime","getTime","BigCommercePaymentsFastlaneUtils","initializePayPalFastlane","paypalFastlaneSdk","isTestModeEnabled","styles","localStorage","setItem","bigCommercePaymentsFastlane","defaultStyles","root","backgroundColorPrimary","getPayPalFastlaneOrThrow","lookupCustomerOrThrow","identity","lookupCustomerByEmail","triggerAuthenticationFlowOrThrow","customerContextId","triggerAuthenticationFlow","updateStorageSessionId","setDate","getDate","cookiesOption","removeStorageSessionId","getStorageSessionId","mapPayPalFastlaneProfileToBcCustomerData","authenticationResult","authenticationState","profileData","paypalBillingAddress","card","paymentSource","paypalShippingAddress","paypalProfileName","paypalInstrument","mapPayPalToBcAddress","instruments","mapPayPalToBcInstrument","filterAddresses","UNRECOGNIZED","instrument","brand","expiry","lastDigits","expiryYear","expiryMonth","bigpayToken","defaultInstrument","iin","last4","trustedShippingAddress","untrustedShippingCardVerificationMode","PAN","mapBcToPayPalAddress","addressLine1","addressLine2","adminArea1","adminArea2","profileName","fullName","phoneData","nationalNumber","reduce","customerAddresses","currentAddress","isEqualAddresses","firstAddress","secondAddress","normalizeAddress","__WEBPACK_EXTERNAL_MODULE_lodash_omit__","createBigCommercePaymentsFastlaneUtils","isInvalidStyleOption","styleOption","getFastlaneStyles","styleSettings","uiStyles","fastlaneStyles","input","toggle","textBody","text","textCaption","caption","branding","cleanUpFastlaneStyles","fastlaneRootSettingsBackgroundColor","errorColor","fastlaneRootSettingsErrorColor","fontFamily","fastlaneRootSettingsFontFamily","fontSizeBase","fastlaneRootSettingsFontSize","_d","padding","fastlaneRootSettingsPadding","primaryColor","fastlaneRootSettingsPrimaryColor","_f","borderRadius","fastlaneInputSettingsBorderRadius","_g","borderColor","fastlaneInputSettingsBorderColor","_h","focusBorderColor","fastlaneInputSettingsFocusBorderBase","_j","backgroundColor","fastlaneInputSettingsBackgroundColor","_k","borderWidth","fastlaneInputSettingsBorderWidth","_l","textColorBase","fastlaneInputSettingsTextColorBase","_m","colorPrimary","fastlaneToggleSettingsColorPrimary","_o","colorSecondary","fastlaneToggleSettingsColorSecondary","_p","fastlaneTextBodySettingsColor","_r","_q","fontSize","fastlaneTextBodySettingsFontSize","_t","_s","fastlaneTextCaptionSettingsColor","_v","_u","fastlaneTextCaptionSettingsFontSize","_x","_w","fastlaneBrandingSettings","mergeFastlaneStyles","BigCommercePaymentsFastlaneCustomerStrategy","bigCommercePaymentsSdk","bigCommercePaymentsFastlaneUtils","bigcommerce_payments_fastlane","updatePaymentProviderCustomer","checkoutPaymentMethodExecuted","runPayPalAuthenticationFlowOrThrow","customerEmail","isAuthenticationFlowCanceled","CANCELED","updateCustomerDataState","updatedState","isFastlaneShippingOptionAutoSelectEnabled","firstShippingOption","shippingOptionId","isFastlaneStylingEnabled","create_bigcommerce_payments_fastlane_customer_strategy","BigCommercePaymentsPayLaterCustomerStrategy","bigcommerce_payments_paylater","bigCommercePaymentsPayLater","fundingSources","PAYLATER","CREDIT","hasRenderedSmartButton","create_bigcommerce_payments_paylater_customer_strategy","BigCommercePaymentsVenmoCustomerStrategy","bigcommerce_payments_venmo","VENMO","paypalButtonRender","create_bigcommerce_payments_venmo_customer_strategy","PaymentMethodFailedError","PaymentMethodInvalidError","BoltDeveloperMode","StyleButtonSize","bolt_StyleButtonShape","BoltCustomerStrategy","boltScriptLoader","boltHostWindow","bolt","onInit","publishableKey","developerConfig","loadBoltClient","getCustomerEmail","hasBoltAccount","__WEBPACK_EXTERNAL_MODULE_rxjs_noop__","openBoltCheckoutModalOrThrow","boltClient","getBoltClientOrThrow","embeddedOneClickEnabled","callbacks","close","openCheckout","isCustomError","BoltCheckout","BoltScriptLoader","developerModeParams","storefrontApiToken","getDomainURL","getScriptOptions","loadBoltEmbedded","Bolt","developerMode","StagingMode","DevelopmentMode","developerDomain","create_bolt_customer_strategy","PaymentArgumentInvalidError","invalidFields","PaymentInvalidFormError","details","paypalSdkPromise","PAYPAL_COMPONENTS","PaypalButtonStyleLayoutOption","PaypalButtonStyleSizeOption","PaypalButtonStyleColorOption","PaypalButtonStyleLabelOption","PaypalButtonStyleShapeOption","MessagingPlacements","BraintreeIntegrationService","overlay","dataCollectors","threeDSecureOptions","getBraintreeFastlane","cardId","braintreeFastlane","getSessionId","braintreeFastlaneCreator","getPaypal","braintreePaypal","shouldSaveInstrument","braintree_integration_service_rest","newWindowFlow","__WEBPACK_EXTERNAL_MODULE__braintree_browser_detection_e7ac357c_supportsPopups__","show","focusWindow","tokenize","enableShippingAddress","flow","useraction","getPaypalCheckout","onSuccess","paypalCheckout","paypalCheckoutConfig","braintreePaypalCheckout","paypalSdkLoadConfig","isCreditEnabled","loadPayPalSDKOnce","getDataCollector","cacheKey","cached","getBraintreeEnv","isTestMode","Sandbox","Production","mapToBraintreeShippingAddressOverride","recipientName","line1","line2","mapToLegacyShippingAddress","first_name","last_name","mapToLegacyBillingAddress","riskCorrelationId","get3DS","getVenmoCheckout","venmoConfig","verifyCard","tokenizationPayload","tokenizeCard","challenge3DSVerification","creditCardInstrument","ccExpiry","ccNumber","ccName","isCreditCardInstrumentLike","getErrorsRequiredFields","requestData","mapToCreditCard","creditCards","nonce","bin","present3DSChallenge","creditCard","cardholderName","number","cvv","ccCvv","expirationDate","month","year","countryCodeAlpha2","countryName","streetAddress","endpoint","addFrame","removeFrame","challengeRequested","additionalInformation","cancelVerifyCard","braintree_integration_service_awaiter","verification","roundedAmount","Number","onLookupComplete","_data","collectDeviceData","BraintreePaypalCustomerStrategy","braintreeIntegrationService","braintreepaypal","paypalCheckoutOptions","renderPayPalButton","buttonStyles","env","setupPayment","authorizeData","shippingAddressOverride","createPayment","shippingAddressEditable","offerCredit","tokenizePayload","device_data","billing_address","shipping_address","buttonContainerId","onErrorCallback","create_braintree_paypal_customer_strategy","BraintreePaypalCreditCustomerStrategy","braintreepaypalcredit","create_braintree_paypal_credit_customer_strategy","get_fastlane_styles_isInvalidStyleOption","get_fastlane_styles_getFastlaneStyles","get_fastlane_styles_cleanUpFastlaneStyles","get_fastlane_styles_mergeFastlaneStyles","BraintreeFastlaneCustomerStrategy","braintreeFastlaneUtils","isAcceleratedCheckoutEnabled","braintreefastlane","getValidPaymentMethodOrThrow","paypalFastlaneStylesSettings","initializeBraintreeFastlaneOrThrow","shouldRunAuthenticationFlow","primaryMethodId","shouldRunAcceleratedCheckout","validPaymentMethodId","BraintreeFastlaneUtils","getDeviceSessionId","getBraintreeFastlaneOrThrow","getBraintreeFastlaneComponentOrThrow","FastlaneCardComponent","shouldSetShippingOption","getMethodIdOrThrow","saveSessionIdToCookies","removeSessionIdFromCookies","shippingAddresses","getPayPalBillingAddresses","billingAddresses","mergeShippingAndBillingAddresses","digitalItems","digitalItemBilling","setShippingOption","getSessionIdFromCookies","binDetails","phones","countries","getCountries","getCountryNameByCountryCode","matchedCountry","extendedAddress","filteredBillingAddresses","create_braintree_fastlane_customer_strategy","BraintreeVisaCheckoutCustomerStrategy","braintreeSdk","buttonClassName","braintreevisacheckout","visaCheckoutOptions","braintreeVisaCheckout","visaCheckoutInstance","initOptions","createInitOptions","paymentRequest","settings","locale","storeLanguage","collectShipping","signInButton","createSignInButton","init","paymentSuccessPayload","getShippingAddress","billing","mapToVisaCheckoutAddress","userData","cardInformation","userEmail","card_information","cardType","lastTwo","buttonClass","insertVisaCheckoutButton","visaCheckoutButton","flexDirection","className","innerHTML","create_braintree_visa_checkout_customer_strategy","hostWindow","CurrencyFormatter","currencySettings","symbolLocation","symbol","thousandsSeparator","decimalSeparator","_decimalPlaces","parseInt","_symbolLocation","_symbol","_thousandsSeparator","_decimalSeparator","format","formattedNumber","_formatNumber","formattedCurrency","_formatCurrency","positiveAmount","abs","integerAmount","decimalAmount","_toFixed","parsedIntegerAmount","toLowerCase","precision","round","CurrencyService","_storeConfig","_customerFormatter","shopperCurrency","_storeFormatter","toCustomerCurrency","exchangeRate","toStoreCurrency","currency_service_decorate","items_require_shipping","lineItem","isShippingRequired","customItems","isWebView","isReactNativeWindow","userAgent","navigator","vendor","isOperaWindow","opera","isAndroidWebView","isIOSWebView","PayPalCommerceIntent","types_StyleButtonLabel","types_StyleButtonColor","types_StyleButtonShape","types_TotalPriceStatusType","GooglePayCardNetwork","CallbackIntentsType","ErrorReasonType","CallbackTriggerType","isGooglePayCardNetworkKey","GooglePayKey","GooglePayGateway","_gatewayIdentifier","_isBuyNowFlow","_shouldRequestShipping","_isWebViewExperimentOn","mapToShippingAddressRequestBody","_mapToAddressRequestBody","mapToBillingAddressRequestBody","paymentMethodData","mapToExternalCheckoutData","tokenizationData","cardNetwork","cardDetails","getRequiredData","emailRequired","_isShippingAddressRequired","loadShippingCountries","allowedCountryCodes","getShippingCountries","shippingAddressRequired","shippingAddressParameters","phoneNumberRequired","shippingOptionRequired","getCallbackIntents","OFFER","SHIPPING_ADDRESS","SHIPPING_OPTION","getCallbackTriggers","availableTriggers","INITIALIZE","initializationTrigger","addressChangeTriggers","shippingOptionsChangeTriggers","offerChangeTriggers","getNonce","extraPaymentData","getMerchantInfo","googleMerchantName","merchantName","googleMerchantId","platformToken","authJwt","getGooglePayInitializationData","getTransactionInfo","_getCurrencyCodeOrThrow","storeCountry","isWebViewWithRestrictions","totalPrice","getTotalPrice","totalPriceStatus","ESTIMATED","setIsWebViewExperimentOn","isWebViewExperimentOn","getPaymentGatewayParameters","gatewayMerchantId","getCardParameters","allowedAuthMethods","allowedCardNetworks","supportedCards","billingAddressRequired","billingAddressParameters","_getPaymentMethodFn","_currencyCode","handleShippingAddressChange","mappedShippingAddress","_currencyService","currency_service","_getGooglePayShippingOption","handleShippingOptionChange","defaultSelectedOptionId","maxDecimalPlaces","min","__WEBPACK_EXTERNAL_MODULE_lodash_round__","handleCoupons","offerData","redemptionCodes","newCouponsState","offers","appliedCoupons","getAppliedCoupons","google_pay_gateway_awaiter","redemptionCode","appliedCouponError","coupon","newOfferInfo","coupons","displayName","reason","OFFER_INVALID","setShouldRequestShipping","getGatewayIdentifier","setGatewayIdentifier","shippingContextRequiresCheck","address3","_getFirstAndLastName","trim","nameParts","slice","isGooglePayErrorObject","isGooglePayKey","GooglePayCustomerStrategy","_googlePayPaymentProcessor","_methodId","googlePayOptions","_getMethodId","_getGooglePayClientOptions","_addPaymentButton","_paymentButton","paymentDataCallbacks","onPaymentDataChanged","callbackTrigger","shippingOptionData","google_pay_customer_strategy_awaiter","couponsError","newTransactionInfo","FINAL","newShippingOptionParameters","buttonType","addPaymentButton","_handleClick","initializeWidget","_interactWithPaymentSheet","statusCode","showPaymentSheet","siteLink","setExternalCheckoutForm","GooglePayPaymentProcessor","_gateway","_formPoster","_baseRequest","apiVersion","apiVersionMinor","googlePayPaymentOptions","_paymentsClient","getGooglePaymentsClient","_buildButtonPayloads","_buildWidgetPayloads","_determineReadinessToPay","_prefetchGooglePaymentData","paymentButton","_getPaymentsClient","allowedPaymentMethods","_getBaseCardPaymentMethod","paymentDataRequest","_getPaymentDataRequest","loadPaymentData","setExternalCheckoutXhr","_setExternalCheckout","processAdditionalAction","useFormPoster","transactionInfo","prefetchPaymentData","isReadyToPay","_getIsReadyToPayRequest","_baseCardPaymentMethod","parameters","baseCardPaymentMethod","_cardPaymentMethod","tokenizationSpecification","isWebViewLogic","callbackIntents","offerInfo","_paymentDataRequest","merchantInfo","_isReadyToPayRequest","_getOrThrow","GooglePayScriptLoader","google","payments","api","PaymentsClient","environment","createGooglePayScriptLoader","create_google_pay_adyenv2_customer_strategy","create_google_pay_adyenv3_customer_strategy","GooglePayAuthorizeNetGateway","service","_super","isGooglePayAuthorizeNetInitializationData","assertsIsGooglePayAuthorizeNetInitializationData","paymentGatewayId","create_google_pay_authorizenet_customer_strategy","is_request_error","assertIsGooglePayCheckoutComInitializationData","isGooglePayCheckoutComInitializationData","GooglePayCheckoutComGateway","_resolve","threeDSBody","three_ds_result","acs_url","isGooglePayThreeDSecureResult","isGooglePayTokenObject","assertIsGooglePayTokenObject","_tokenize","checkoutcomkey","token_data","Authorization","create_google_pay_checkoutcom_customer_strategy","GooglePayCybersourceGateway","create_google_pay_cybersource_customer_strategy","create_google_pay_bnz_customer_strategy","GooglePayOrbitalGateway","create_google_pay_orbital_customer_strategy","StripeFormMode","StripeDisplayName","StripeCheckoutSessionStatusType","StripeCheckoutSessionPaymentStatus","StripeLoadActionsResultType","StripePaymentMethodType","StripeStringConstants","StripeJsVersion","StripeElementType","StripePaymentIntentStatus","StripeElementEvent","StripeInstrumentSetupFutureUsage","StripeScriptLoader","stripeWindow","getStripeClient","stripeJsVersion","betas","bcStripeClient","stripe","stripePublishableKey","stripeConnectedAccount","stripeClient","stripeAccount","getElements","stripeElements","bcStripeElements","updateStripeElements","elements","update","fetchUpdates","getStripeCheckout","stripeCheckout","getStoredStripeCheckout","bcStripeCheckout","Stripe","getScriptUrl","V3","loadActions","logErrorToConsole","stripeCheckoutSession","getSession","stripeSessionIdFromOptions","clientSecret","STRIPE_UPE_CLIENT_BETAS","STRIPE_UPE_CLIENT_API_VERSION","assertsIsGooglePayStripeInitializationData","isGooglePayStripeInitializationData","GooglePayStripeGateway","isGooglePayStripeTokenObject","assertIsGooglePayStripeTokenObject","stripeVersion","__WEBPACK_EXTERNAL_MODULE_lodash_some__","initialization","stripeUPEClient","loadStripeJs","catchedConfirmError","confirmCardPayment","retrievePaymentIntent","__","_throwDisplayableStripeError","_isCancellationError","paymentIntent","getCartLocale","useNewStripeJsVersion","CLOVER","stripeError","payment_intent","last_payment_error","__WEBPACK_EXTERNAL_MODULE_lodash_includes__","create_google_pay_stripe_customer_strategy","create_google_pay_stripeupe_customer_strategy","GooglePayWorldpayAccessGateway","create_google_pay_worldpayaccess_customer_strategy","GooglePayBraintreeGateway","_service","_braintreeGooglePayment","isThreeDSecureEnabled","isNetworkTokenized","orderAmount","getOrderOrThrow","_braintreePresent3DSChallenge","isGooglePayBraintreeTokenObject","assertIsGooglePayBraintreeTokenObject","androidPayCards","createPaymentDataRequest","cardRequirements","billingAddressFormat","paymentMethodTokenizationParameters","create_google_pay_braintree_customer_strategy","LOADING_INDICATOR_STYLES","PAYPAL_SDK_SUPPORTED_LOCALES","transformLocaleToPayPalFormat","language","toUpperCase","PayPalCommerceSdk","paypalGooglePay","paypalApms","paypalMessages","assertsIsGooglePayPayPalCommercePaymentMethod","isGooglePayPaypalCommercePaymentMethod","GooglePayPaypalCommerceGateway","payPalCommerceSdk","googlePaySdk","getLocale","googlepayConfig","Googlepay","create_google_pay_paypal_commerce_customer_strategy","GooglePayBigCommercePaymentsGateway","payPalSdkHelper","create_google_pay_bigcommerce_payments_customer_strategy","getBrowserInfo","userLanguage","color_depth","screen","colorDepth","java_enabled","javaEnabled","screen_height","screen_width","time_zone_offset","getTimezoneOffset","GooglePayTdOnlineMartGateway","browser_info","errorBody","__WEBPACK_EXTERNAL_MODULE_lodash_isObject__","__WEBPACK_EXTERNAL_MODULE_lodash_isArray__","isTdOnlineMartAdditionalAction","threeDSResult","formUrl","payer_auth_request","threeDSSessionData","merchant_data","creq","create_google_pay_tdonlinemart_customer_strategy","PayPalIntent","paypal_types_TDSecureVerificationMethod","paypal_types_TDSecureAuthenticationState","paypal_types_LiabilityShiftEnum","paypal_types_StyleButtonLabel","paypal_types_StyleButtonColor","paypal_types_StyleButtonShape","paypal_types_PayPalFastlaneAuthenticationState","paypal_types_NonInstantAlternativePaymentMethods","paypal_types_PayPalOrderStatus","PayPalSdkScriptLoader","createPayPalSdkScriptLoader","PayPalIntegrationService","paypalRequestSender","paypalSdkLoader","PayPalRequestSender","create_paypal_integration_service","paypal_button_creation_service","paypalIntegrationService","createPayPalButton","onCancel","onPaymentComplete","paypal_button_creation_service_awaiter","buyNowCart","PayPalCommerceCustomerStrategy","paypalButtonCreationService","paypalcommerce","create_paypal_commerce_customer_strategy","paypal_commerce_types_LiabilityShiftEnum","paypal_commerce_types_PayPalCommerceIntent","paypal_commerce_types_StyleButtonLabel","paypal_commerce_types_StyleButtonColor","paypal_commerce_types_StyleButtonShape","paypal_commerce_types_NonInstantAlternativePaymentMethods","paypal_commerce_types_PayPalOrderStatus","PayPalCommerceIntegrationService","paypalCommerceRequestSender","paypalCommerceScriptLoader","PayPalCommerceRequestSender","PayPalCommerceScriptLoader","create_paypal_commerce_integration_service","PayPalCommerceCreditCustomerStrategy","paypalCommerceIntegrationService","paypalcommercecredit","paypalCommerceCredit","create_paypal_commerce_credit_customer_strategy","PayPalCommerceVenmoCustomerStrategy","paypalcommercevenmo","create_paypal_commerce_venmo_customer_strategy","PaypalFastlaneUtils","paypalFastlane","createPaypalFastlaneUtils","utils_get_fastlane_styles_isInvalidStyleOption","utils_get_fastlane_styles_getFastlaneStyles","utils_get_fastlane_styles_cleanUpFastlaneStyles","utils_get_fastlane_styles_mergeFastlaneStyles","PayPalCommerceFastlaneCustomerStrategy","paypalSdkScriptLoader","paypalFastlaneUtils","paypalcommercefastlane","create_paypal_commerce_fastlane_customer_strategy","isStripePaymentMethodLike","shopperLanguage","isStripeAcceleratedCheckoutCustomer","StripeUPECustomerStrategy","stripeupe","onEmailChange","getStyles","isLoading","paymentProviderCustomer","getPaymentProviderCustomerOrThrow","stripeLinkAuthenticationState","appearance","variables","fieldInnerShadow","colorBackground","fieldBackground","colorText","labelText","colorDanger","fieldErrorText","colorTextSecondary","colorTextPlaceholder","fieldPlaceholderText","rules","fieldBorder","fieldText","boxShadow","_stripeElements","billingEmail","defaultValues","mode","SHIPPING","linkAuthenticationElement","getElement","AUTHENTICATION","CHANGE","authenticated","deleteConsignment","mount","unmount","create_stripe_upe_customer_strategy","StripeIntegrationService","isMounted","checkoutEventsUnsubscribe","initCheckoutEventsSubscription","stripeInitializationOptions","stripe_integration_service_awaiter","paymentElement","PAYMENT","updateStripePaymentIntent","mountElement","stripeElement","mapAppearanceVariables","colorIcon","mapInputAppearanceRules","throwStripeError","throwDisplayableStripeError","isCancellationError","errorMessage","throwPaymentConfirmationProceedMessage","isPaymentCompleted","SUCCEEDED","mapStripePaymentData","returnUrl","shouldAllowRedisplay","mapStripeAddress","redirect","IF_REQUIRED","confirmParams","payment_method_data","allow_redisplay","billing_details","getShopperFullName","return_url","isAdditionalActionError","isRedirectAction","additionalAction","redirect_url","isOnPageAdditionalAction","getStripeJsVersion","DEFAULT_STYLES","DEFAULT_CONTAINER_STYLES","position","ROTATION_ANIMATION","LoadingIndicator","containerStyles","defineAnimation","buildContainer","indicator","buildIndicator","parentId","parent","opacity","hide","handleTransitionEnd","bottom","left","right","top","transition","setStyleAttribute","margin","transform","transformStyle","animation","attrs","k","setProperty","head","sheet","CSSStyleSheet","insertRule","AmountTransformer","toInteger","pow","expressCheckoutAllowedCountryCodes","StripeLinkV2CustomerStrategy","stripeIntegrationService","loadingIndicator","stripeocs","loadingContainerId","buttonHeight","_loadingIndicatorContainer","_onComplete","captureMethod","_captureMethod","_stripeClient","_mountExpressCheckoutElement","_initializeEvents","stripeExpressCheckoutClient","shouldRequireShippingAddress","_shouldRequireShippingAddress","expressCheckoutOptions","allowedShippingCountries","_getAvailableCountries","shippingRates","link","AUTO","applePay","NEVER","googlePay","amazonPay","klarna","cartAmount","elementsOptions","_toCents","_getCurrency","_linkV2Element","EXPRESS_CHECKOUT","SHIPPING_ADDRESS_CHANGE","stripe_link_v2_customer_strategy_awaiter","_onShippingAddressChange","SHIPPING_RATE_CHANGE","_onShippingRateChange","CONFIRM","_onConfirm","CANCEL","_onCancel","_getAvailableShippingOptions","_updateDisplayedPrice","shippingRate","_handleShippingOptionChange","_updateShippingAndBillingAddress","paymentPayload","_getPaymentPayload","_processAdditionalAction","billingDetails","_mapShippingAddress","_mapBillingAddress","additionalActionData","additional_action_required","_confirmStripePaymentOrThrow","_toggleLoadingIndicator","_completeCheckoutFlow","stripePaymentData","confirmationResult","confirmPayment","credit_card_token","confirm","Link","_getTotalPrice","_getStripeShippingOption","selectedId","recommendedId","_getAmountTransformer","_amountTransformer","amountTransformer","checkoutSessionEnabled","CHECKOUT_SESSION","OCS","create_stripe_link_v2_customer_strategy","stripeScriptLoader","OrderFinalizationNotRequiredError","NoPaymentDataRequiredPaymentStrategy","finalize","create_no_payment_strategy","AdyenV3ActionType","AdyenV2ActionType","AdyenComponentType","AdyenPaymentMethodType","HTTPMethod","ResultCode","AdyenCardFields","AdyenV2ScriptLoader","_stylesheetLoader","configuration","loadStylesheet","prepend","AdyenCheckout","isCardState","encryptedSecurityCode","encryptedExpiryMonth","isVaultedInstrument","instrumentId","AdyenV2PaymentStrategy","adyenv2","_paymentInitializeOptions","originKey","clientKey","paymentMethodsResponse","clientSideAuthentication","_adyenClient","translations","es","_paymentComponent","_mountPaymentComponent","CreditCard","Bancontact","_cardVerificationComponent","_mountCardVerificationComponent","adyenv2_payment_strategy_rest","shouldSetAsDefaultInstrument","_validateCardData","componentState","_componentState","encryptedCardNumber","encryptedExpiryYear","credit_card_number_confirmation","expiry_month","expiry_year","verification_value","bigpay_token","_getAdyenClient","_getPaymentInitializeOptions","_getThreeDS2ChallengeWidgetSize","additionalActionOptions","threeDS2Options","widgetSize","_handleAction","threeDS2ContainerId","onBeforeLoad","onLoad","adyenAction","additionalActionComponent","createFromAction","onAdditionalDetails","additionalActionState","paymentMethodType","ThreeDS2Challenge","QRCode","_mapAdyenPlaceholderData","prefillCardHolderName","street","houseNumberOrName","holderName","adyenClient","cardVerificationComponent","cardVerificationContainerId","SecuredFields","placeholder","caretColor","onChange","_updateComponentState","validateState","validateCardFields","onFieldValid","paymentComponent","ACH","IDEAL","SEPA","hasVaultedInstruments","AliPay","GiroPay","Sofort","Klarna","KlarnaPayNow","KlarnaAccount","Vipps","WeChatPayQR","provider_data","paymentError","cardComponent","componentRef","showValidation","isValid","issuer","props","_mapCardErrors","cardStateErrors","create_adyenv2_payment_strategy","__WEBPACK_EXTERNAL_MODULE__bigcommerce_script_loader_875b3e8f_getStylesheetLoader__","AdyenV3ScriptLoader","isHostedInstrumentLike","Adyenv3PaymentStrategy","adyenv3","paymentInitializeOptions","installmentOptions","paymentMethodsConfiguration","useKlarnaWidget","klarna_account","klarna_paynow","showInstallmentAmounts","_getLocale","showPayButton","adyenv3_payment_strategy_rest","submit","paymentToken","socialSecurityNumber","shopperName","isBoletoState","installments","plan","onActionHandled","componentType","challengeWindowSize","ThreeDS2","Sdk","_mountElement","_isOneyPaymentMethod","personalDetails","deliveryAddress","showBrandsUnderCardNumber","showEmailAddress","onSubmit","basePaymentData","tokenData","adyenComponent","_waitForMountContainer","maxAttempts","ceil","mountContainerMaxWaitMs","mountContainerPollIntervalMs","pollIntervalMs","step","poll","adyenv3_payment_strategy_awaiter","create_adyenv3_payment_strategy","AFFIRM_SCRIPTS","AffirmPaymentStrategy","affirmScriptLoader","affirm","initializeAffirmCheckout","checkout_token","getCheckoutInformation","open","onFail","failObject","successObject","ui","getOrder","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","taxTotal","first","last","full","zipcode","display_name","sku","unit_price","salePrice","qty","item_image_url","imageUrl","item_url","categories","getCategories","giftCertificates","listPrice","line","discountedAmount","discount_amount","discount_display_name","discountAmount","DISCOUNTED_AMOUNT","categoryTree","category","AffirmScriptLoader","affirmWindow","apikey","scriptURI","SANDBOX","PROD","m","g","n","h","p","getElementsByTagName","l","c","arguments","f","a1","c1","a2","c2","parentNode","insertBefore","public_api_key","script","create_affirm_payment_strategy","OrderFinalizationNotCompletedError","AfterpayPaymentStrategy","_afterpayScriptLoader","_mapCurrencyToISO2","withHttps","_afterpaySdk","applyStoreCredit","_loadPaymentMethod","validateCheckout","_redirectToAfterpay","forgetCheckout","loadPaymentMethods","AUD","NZD","CAD","USD","SCRIPTS_DEFAULT","SCRIPTS_US","AfterpayScriptLoader","_getScriptURI","isAfterpayWindow","AfterPay","HTTPS_SANDBOX","HTTPS_PROD","create_afterpay_payment_strategy","AmazonPayV2PaymentStrategy","_isReadyToPay","editButtonId","_bindEditButton","_isModalFlow","_createContainer","_amazonPayButton","_isOneTimeTransaction","_getAmazonPayButton","click","onFocus","isModalFlow","button","clone","cloneNode","replaceChild","_showLoadingSpinner","create_amazon_pay_v2_payment_strategy","apple_pay_payment_strategy_DefaultLabels","ApplePayPaymentStrategy","_storeCreditLabel","StoreCredit","storeCreditLabel","isStoreCreditApplied","storeCredit","apple_pay_payment_strategy_awaiter","create_apple_pay_payment_strategy","bigcommerce_payments_constants_LOADING_INDICATOR_STYLES","get_paypal_messages_styles_from_bnpl_config","messagesStyles","layout","logo","ratio","isBaseInstrument","BigCommercePaymentsPaymentStrategy","paypalSdkHelper","bannerContainerId","paypalBNPLConfiguration","bannerConfiguration","Messages","renderMessages","loadingIndicatorContainer","shouldRenderPayPalButtonOnInitialization","bigcommerce_payments_payment_strategy_rest","isPayPalVaultedInstrumentPaymentData","prepareVaultedInstrumentPaymentPayload","preparePaymentPayload","isProviderError","paypalOrderId","shouldConfirmInstrument","isTrustedVaultingFlow","checkoutPaymentButtonStyles","onRenderButton","onValidate","submitForm","handleClick","handleApprove","toggleLoadingIndicator","fieldsValues","getFieldsValues","getInstruments","findInstrument","paypalMessagesOptions","isBigCommercePaymentsProviderError","provider_error","create_bigcommerce_payments_payment_strategy","isPayPalFastlaneCustomer","BigCommercePaymentsFastlanePaymentStrategy","threeDSVerificationMethod","initializePayPalPaymentComponent","renderPayPalPaymentComponent","handlePayPalStoredInstrumentChange","orderRequest","bigcommerce_payments_fastlane_payment_strategy_rest","isVaultedFlow","isBigcommerceFastlaneRequestError","invalidRequestError","translationKey","getPaymentProviderCustomer","paypalFastlaneCustomer","paypalFastlaneSessionId","getBillingAddressOrThrow","cardComponentOptions","fields","prefill","enabled","paypalComponentMethods","getPayPalComponentMethodsOrThrow","isBigcommercePaymentsFastlaneThreeDSAvailable","is3dsEnabled","get3DSNonce","paypal_fastlane_token","getPaymentToken","is3DSEnabled","fastlaneToken","checkoutUrl","threeDomainSecureComponent","ThreeDomainSecureClient","threeDomainSecureParameters","threeDSRequested","Always","transactionContext","experience_context","cancel_url","isThreeDomainSecureEligible","liabilityShift","threeDSNonce","No","Unknown","Errored","Cancelled","Succeeded","Yes","Possible","paypalAxoSdk","selectionChanged","selectedCard","profile","showCardSelector","selectedInstrument","create_bigcommerce_payments_fastlane_payment_strategy","BigCommercePaymentsPayLaterPaymentStrategy","bigcommerce_payments_paylater_payment_strategy_rest","bigCommercePaymentsButtons","bigCommerceSdk","create_bigcommerce_payments_paylater_payment_strategy","TimeoutError","BigCommercePaymentsRatePayPaymentStrategy","pollingInterval","maxPollingIntervalTime","pollingTimer","stopPolling","bigcommerce_payments_ratepay","legalTextContainer","createFraudNetScript","loadFraudnetConfig","renderLegalText","bigcommerce_payments_ratepay_payment_strategy_rest","metadataId","guid","ratepayBirthDate","ratepayPhoneNumber","ratepayPhoneCountryCode","rate_pay","birth_date","normalizeDate","initializePollingMechanism","fraudNetScript","querySelectorAll","fraudNetConfig","deinitializePollingMechanism","legalTextContainerElement","date","formattedDate","formatDate","formattedMonth","getMonth","getFullYear","legalTextContainerElementId","legalTextContainerId","buttonContainer","buttonContainerParent","marginBottom","ratePayButton","Legal","PAY_UPON_INVOICE","resetPollingMechanism","scriptElement","generateGUID","s","i","floor","characters","reinitializeStrategy","resolvePromise","rejectPromise","orderStatus","useMetadata","isOrderApproved","PollingStop","isPollingError","PollingError","create_bigcommerce_payments_ratepay_payment_strategy","HostedFieldType","hosted_field_type","isCreditCardFormFields","CardNumber","CardName","CardExpiry","isCreditCardVaultedFormFields","CardNumberVerification","CardCodeVerification","CardExpiryVerification","BigCommercePaymentsCreditCardsPaymentStrategy","bigcommerce_payments_creditcards","bigCommercePaymentsInitializationOptions","form","onCreditCardFieldsRenderingError","onLoadComplete","hostedFormOptions","isCreditCardForm","isCreditCardVaultedForm","hasUndefinedValues","initializeFields","shouldInitializePayPalFastlane","initializePayPalFastlaneOrThrow","bigcommerce_payments_credit_cards_payment_strategy_rest","executionPaymentData","validateHostedFormOrThrow","submitHostedForm","getInstrumentParams","returnedOrderId","submitPaymentPayload","returnedVaultedToken","cvvField","expiryField","numberField","nameField","verification_nonce","card_with_order","formOptions","executeCallback","getExecuteCallback","cardFieldsConfig","getInputStyles","vaultSetupToken","inputEvents","onChangeHandler","onFocusHandler","onBlur","onBlurHandler","onInputSubmitRequest","cardFields","CardFields","stylizeInputContainers","renderFields","renderVaultedFields","createVaultSetupTokenCallback","createOrderCallback","createVaultSetupToken","bigcommerce_payments_credit_cards_payment_strategy_awaiter","fieldsOptions","getCardFieldsOrThrow","cardCode","CVVField","cardExpiry","ExpiryField","cardName","NameField","cardNumber","NumberField","cardCodeVerification","cardExpiryVerification","cardNumberVerification","getFieldTypeByEmittedField","emittedBy","mapFieldType","submitConfig","cardFieldsState","validationData","getValidityData","mapValidationErrors","updatedFields","cardNameField","fieldsKeys","every","fieldsErrors","getInvalidErrorByFieldType","CardCode","validationErrors","commonStyles","fontWeight","outline","background","marginLeft","onEnter","bigCommercePaymentsPaymentProviderCustomer","isBigCommercePaymentsAnalyticsV2Enabled","connectClientToken","payPalFastlaneSdk","create_bigcommerce_payments_credit_cards_payment_strategy","BigCommercePaymentsAlternativeMethodsPaymentStrategy","bigCommercePaymentsSdkHelper","isPollingEnabled","bigcommerce_payments_apms","bigCommercePaymentsAlternativeMethods","shouldRenderFields","bigcommerce_payments_alternative_methods_payment_strategy_rest","isNonInstantPaymentMethod","bigCommercePaymentsButton","Approved","deInitializePollingMechanism","paypalAmpsSdk","getPaypalAmpsSdkOrThrow","buttonStyle","onInitButton","onCreateOrder","handleFailure","bigcommerce_payments_alternative_methods_payment_strategy_awaiter","apmFieldsContainer","apmFieldsStyles","fieldContainerElement","PaymentFields","create_bigcommerce_payments_alternative_methods_payment_strategy","BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy","bigcomemrce_payments_redirect_alternative_methods_payment_strategy_rest","isRedirectError","redirectUrl","create_bigcommerce_payments_redirect_alternative_methods_payment_strategy","BigCommercePaymentsVenmoPaymentStrategy","bigcommerce_payments_venmo_payment_strategy_rest","create_bigcommerce_payments_venmo_payment_strategy","BlueSnapDirect3ds","blueSnapSdk","_blueSnapSdk","initialize3ds","cardData","_getBlueSnapSdk","threeDsPaymentsSetup","sdkResponse","threeDSecureReferenceId","threeDsPaymentsSubmitData","isHostedCardFieldOptionsMap","isHostedStoredCardFieldOptionsMap","BlueSnapDirectCardType","BlueSnapDirectEventOrigin","BlueSnapDirectErrorDescription","BlueSnapDirectErrorCode","BlueSnapDirectHostedFieldTagId","BlueSnapDirectCreditCardPaymentStrategy","_blueSnapDirectHostedForm","_blueSnapDirect3ds","_paymentFieldsToken","_shouldUseHostedFields","_getPaymentFieldsToken","pfToken","bluesnapSubmitedForm","_getBlueSnapDirectThreeDSecureData","getCardInstrumentOrThrow","previouslyUsedCard","last4Digits","ccType","cardHolderName","billingFirstName","billingLastName","billingCountry","billingCity","billingZip","shippingFirstName","shippingLastName","shippingCountry","shippingCity","shippingZip","BlueSnapHostedFieldType","CREDIT_CARD_ERRORS","empty","invalid","BlueSnapDirectHostedForm","_nameOnCardInput","_hostedInputValidator","initializeValidationFields","paymentFieldsToken","enable3DS","callbacksAndStyles","bluesnap_direct_hosted_form_rest","_onValidate","_setCustomBlueSnapAttributes","_setCustomStoredCardsBlueSnapAttributes","_getHostedPaymentFieldsOptions","hostedPaymentFieldsCreate","accessibilityLabel","threeDSecureData","shouldSendName","hostedPaymentFieldsSubmitData","_isBlueSnapDirectCallbackError","THREE_DS_AUTH_FAILED","errorDescription","getValue","onCardTypeChange","onFieldEventHandler","setupComplete","_usetUiEventCallback","_handleError","onType","_tagId","onValid","tagId","ccnPlaceHolder","cvvPlaceHolder","expPlaceHolder","_mapStyles","focus","selector","declaration","declarationBlock","property","__WEBPACK_EXTERNAL_MODULE_lodash_kebabCase__","errorCode","eventOrigin","INVALID_OR_EMPTY","EMPTY","INVALID","isBlueSnapDirectInputValidationErrorDescription","cardNumberContainer","cardExpiryContainer","cardCodeContainer","cardNameContainer","dataset","bluesnap","BlueSnapHostedInputValidator","_errors","_updateErrors","errorData","BluesnapDirectNameOnCardInput","_style","_create","_getInput","_handleFocus","_handleBlur","_handleEnter","_input","_applyStyles","HTMLInputElement","ON_BLUR","allowedStyle","styleKeys","_configureInput","autocomplete","inputMode","BlueSnapDirectSdkEnv","BlueSnapDirectScriptLoader","PRODUCTION","create_bluesnap_direct_credit_card_payment_strategy","BlueSnapDirectAPMPaymentStrategy","_formatePaymentPayload","_isBlueSnapDirectRedirectResponse","providerData","frameUrl","partialValue","merchantid","isBlueSnapDirectRedirectResponseProviderData","providerDataQuery","ecp","account_number","accountNumber","account_type","accountType","shopper_permission","shopperPermission","routing_number","routingNumber","companyName","company_name","sepa_direct_debit","iban","isIdealInstrument","ideal","bic","isPayByBankInstrument","pay_by_bank","partialResponse","partialBody","create_bluesnap_direct_apm_payment_strategy","PaymentStatusTypes","payment_status_types","BlueSnapV2PaymentStrategy","_initializeOptions","frame","_createIframe","initializeOffsitePayment","getPaymentStatus","ACKNOWLEDGE","FINALIZE","finalizeOrder","bluesnapv2","create_bluesnapv2_payment_strategy","AnalyticsExtraItemsManager","storage","saveExtraItemsData","productId","categoryNames","getStorageKey","readExtraItemsData","getItem","itemsData","hasNotExtraItems","isExtraItemsData","clearExtraItemData","removeItem","isAnalyticsTrackerWindow","isWithAccountCreation","BoltError","getError","BoltPaymentStrategy","analyticsExtraItemsManager","useBoltClient","useBoltEmbedded","onPaymentSelect","useBigCommerceCheckout","boltEmbedded","mountBoltEmbeddedField","embeddedField","setExtraItemsForAnalytics","bolt_payment_strategy_rest","isBoltPaymentData","getBoltClientPaymentPayload","getBoltEmbeddedPaymentPayload","getBoltFullCheckoutPaymentPayload","orderToken","boltTransaction","success","transaction","reference","configure","tokenizeResult","validateTokenizeResultOrThrow","last_four_digits","expiration_month","expiration","expiration_year","create_account","shouldCreateAccount","embedded_checkout","setBoltOrderId","transactionReference","getTransactionReference","getBoltEmbeddedOrThrow","setOrderId","renderSeparateFields","lastFourDigits","expirationMonth","expirationYear","isNaN","isAnalyticsEnabled","create_bolt_payment_strategy","__WEBPACK_EXTERNAL_MODULE_local_storage_fallback_5dc95480_default__","isUsBankAccountInstrumentLike","BraintreeAchPaymentStrategy","braintreeach","getMandateText","handleBraintreeError","braintree_ach_payment_strategy_rest","isSubmittingWithVaultingInstrument","tokenizePaymentForVaultedInstrument","preparePaymentDataForVaultedInstrument","preparePaymentData","getUsBankAccountOrThrow","mandateText","bankDetails","getBankDetails","isVaultingEnabled","tokenized_bank_account","masked_account_number","ownershipType","businessName","create_braintree_ach_payment_strategy","create_braintree_sdk","BraintreeMessages","messagingContainer","bannedId","CART","removeAttribute","getPaypalMessagesStylesFromBNPLConfig","Overlay","closeElement","mainElement","_createElements","_element","_closeElement","_mainElement","_registerClick","_unregisterClick","_removeAfterTransition","transitionDuration","hasCloseButton","innerHtml","classLayout","classClose","classOverlayText","overlayText","addClassLayout","innerText","getOverlayStyle","_addEventListener","_removeEventListener","onClickClose","handleTransition","propertyName","braintree_paypal_constants_LOADING_INDICATOR_STYLES","is_braintree_error_isBraintreeError","BraintreePaypalPaymentStrategy","braintreeMessages","braintreeOptions","braintreeButtonOptions","loadPaypalCheckoutInstance","braintree_paypal_payment_strategy_rest","braintreeTokenizePayload","getOutstandingBalance","vaultPaymentInstrument","paymentMethodId","shouldShowPayPalCreditBanner","renderPayPalMessages","onPaymentError","getSmartButtonContainerId","braintree_paypal_payment_strategy_awaiter","tokenizePaymentOrThrow","isBraintreePaypalProviderError","create_braintree_paypal_payment_strategy","BraintreeRequestSender","BraintreeLocalMethodsPaymentStrategy","braintreeRequestSender","isLPMsUpdateExperimentEnabled","braintreelocalmethods","braintree_local_methods_payment_strategy_rest","executeWithNotInstantLPM","executeWithInstantLPM","basicPaymentData","getLPMsBasicPaymentData","isBraintreeRedirectError","startPayment","getInstantLPMConfig","getInstantLPMCallback","paymentType","fallback","buttonText","onPaymentStart","start","braintree_local_methods_payment_strategy_awaiter","paymentId","isBraintreeOrderSavedResponse","order_id_saved_successfully","startPaymentError","payloadData","isOrderPending","Pending","Completed","Failed","create_braintree_local_methods_payment_strategy","isBraintreeAcceleratedCheckoutCustomer","BraintreeFastlanePaymentStrategy","isThreeDSExperimentEnabled","initializeCardComponent","renderBraintreeCardComponent","handleBraintreeStoredInstrumentChange","braintree_fastlane_payment_strategy_rest","braintreeCardComponent","paypalPaymentComponent","getBraintreeCardComponentOrThrow","getPayPalInstruments","threeDSToken","mapToPayPalAddress","binGuest","verifyError","braintreePaymentProviderCustomer","braintreeFastlaneCustomer","selectedInstruments","create_braintree_fastlane_payment_strategy","BraintreeVisaCheckoutPaymentStrategy","visaCheckoutSdk","braintree_visa_checkout_payment_strategy_rest","create_braintree_visa_checkout_payment_strategy","BraintreeVenmoPaymentStrategy","venmoOptions","braintreevenmo","initializeBraintreeVenmo","braintree_venmo_payment_strategy_rest","isBraintreeVenmoWebFallbackSupport","mobileWebFallBack","braintreeVenmoTokenize","create_braintree_venmo_payment_strategy","BraintreeCreditCardPaymentStrategy","braintreeHostedForm","isHostedPaymentFormEnabled","unsupportedCardBrands","isHostedFormInitialized","shouldInitializeBraintreeFastlane","braintree_credit_card_payment_strategy_rest","prepareHostedPaymentData","isPaymentMethodInitialized","commonPaymentData","isSubmittingWithStoredCard","shouldPerform3DSVerification","tokenizeForStoredCardVerification","verifyCardWithHostedForm","prepareAdditionalActionPaymentData","storedCreditCardNonce","isBraintreePaymentRequest3DSError","newPaymentData","isHostedFormEnabled","braintreeCustomer","isBraintreeFormFieldsMap","isBraintreeHostedFormError","invalidFieldKeys","BraintreeHostedFormType","BraintreeHostedForm","isInitializedHostedForm","handleBlur","mapErrors","handleFocus","handleCardTypeChange","cards","handleInputSubmitRequest","handleValidityChange","isValidForm","StoredCardVerification","mapFieldOptions","createHostedFields","mapStyleOptions","mapBillingAddress","mapTokenizeError","hostedFields","hostedFieldsOptions","preventCursorJumps","supportedCardBrands","cardBrand","is_braintree_supported_card_brand","internalLabel","mapStyles","isValidParam","isEmpty","isPotentiallyValid","fieldKey","createInvalidError","isStoredCard","createRequiredError","formFields","create_braintree_credit_card_payment_strategy","CreditCardPaymentStrategy","_isHostedPaymentFormEnabled","_shouldRenderHostedForm","_executeWithHostedForm","_executeWithoutHostedForm","_isHostedFieldAvailable","paymentSettings","bigpayBaseUrl","createHostedForm","_hostedForm","credit_card_payment_strategy_rest","__WEBPACK_EXTERNAL_MODULE_lodash_values__","CBAMPGSPaymentStrategy","cbaMGPSScriptLoader","isTestModeFlagEnabled","isCBAMPGSPaymentMethodLike","threeDSjs","isConfigured","wsVersion","retryState","storeId","transactionId","initiateAuthentication","msg","gatewayRecommendation","restApiResponse","authenticationStatus","authenticatePayer","attempt","cba_mpgs_payment_strategy_awaiter","cause","fullScreenRedirect","CBAMPGSScriptLoader","ThreeDS","create_cba_mpgs_payment_strategy","AdditionalActionType","CheckoutComCustomPaymentStrategy","checkoutcom_custom_payment_strategy_rest","_processResponse","loadCurrentOrder","additionalActionRequired","OffsiteRedirect","_performRedirect","CheckoutComFawryPaymentStrategy","checkoutcom_fawry_payment_strategy_rest","_createFormattedPayload","fawryPaymentData","customerMobile","create_checkoutcom_fawry_payment_strategy","isThreeDSecureRequiredError","CheckoutComCreditCardPaymentStrategy","checkoutcom_credit_card_payment_strategy_rest","_handleThreeDSecure","callback_url","PaReq","TermUrl","MD","create_checkoutcom_credit_card_payment_strategy","CheckoutComSEPAPaymentStrategy","checkoutcom_sepa_payment_strategy_rest","create_checkoutcom_sepa_payment_strategy","CheckoutComiDealPaymentStrategy","checkoutcom_ideal_payment_strategy_rest","create_checkoutcom_ideal_payment_strategy","DOCUMENT_SUPPORTED_APMS","CheckoutComAPMPaymentStrategy","checkoutcom_apm_payment_strategy_rest","ccDocument","create_checkoutcom_apm_payment_strategy","ClearpayPaymentStrategy","_clearpayScriptLoader","_clearpaySdk","_isCountrySupported","_redirectToClearpay","ClearpayScriptLoader","_getScriptUrl","httpsEnabled","create_clearpay_payment_strategy","create_credit_card_payment_strategy","CardinalThreeDSecureFlow","_cardinalClient","prepare","_getClientToken","hostedForm","getCardInstrument","getBin","runBinProcess","__WEBPACK_EXTERNAL_MODULE_lodash_merge__","getThreeDSecureData","_getOrderData","CardinalSignatureValidationErrors","CardinalEventType","CardinalInitializationType","CardinalValidatedAction","CardinalPaymentType","CardinalTriggerEvents","CardinalPaymentBrand","CardinalSignatureVerification","CardinalClient","_provider","_testMode","_configurationToken","_sdk","_getClientSDK","SetupCompleted","off","Validated","ActionCode","ErrorNumber","ErrorDescription","setup","Init","jwt","binNumber","BinProcess","Status","orderData","Success","NoAction","Payment","ExtendedData","SignatureVerification","Failure","continueObject","AcsUrl","Payload","partialOrder","_mapToPartialOrder","continue","CCA","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","CardinalScriptLoader","Cardinal","CyberSourcePaymentStrategy","_threeDSecureFlow","create_cybersource_payment_strategy","CardinalThreeDSecureFlowV2","xid","_getBin","_submitPayment","threeDsResult","threeDsToken","isCreditCardInstrument","hostedFormBin","CyberSourceV2PaymentStrategy","create_cybersourcev2_payment_strategy","isAdditionalActionRequiredErrorResponse","GooglePayAdyenV2","googlePayToken","GooglePayPaymentStrategy","_isDeinitializationBlocked","_loadingIndicator","walletButton","google_pay_payment_strategy_rest","extraData","_clickListener","google_pay_payment_strategy_awaiter","_isDirectPayOnClickEnabled","_interactWithPaymentSheetAndPay","_toggleBlockDeinitialization","isGooglePayDontOverrideAddresssExperimentOn","freshPaymentMethod","_getIsSignedInOrThrow","_handleOfferTrigger","isSignedIn","isBlocked","create_google_pay_adyenv2_payment_strategy","GooglePayAdyenV3","create_google_pay_adyenv3_payment_strategy","create_google_pay_authorizenet_payment_strategy","create_google_pay_checkoutcom_payment_strategy","create_google_pay_cybersource_payment_strategy","create_google_pay_orbital_payment_strategy","create_google_pay_stripe_payment_strategy","create_google_pay_worldpayaccess_payment_strategy","create_google_pay_braintree_payment_strategy","ConfirmOrderStatus","types_PayPalCommerceIntent","GooglePayPaypalCommercePaymentStrategy","_payPalCommerceSdk","getOrderId","confirmOrderData","confirmOrder","payPalSDK","PayerActionRequired","initiatePayerAction","create_google_pay_paypal_commerce_payment_strategy","types_ConfirmOrderStatus","types_BigCommercePaymentsIntent","GooglePayBigCommercePaymentsPaymentStrategy","_payPalSdkHelper","create_google_pay_bigcommerce_payments_payment_strategy","create_google_pay_tdonlinemart_payment_strategy","PaymentExecuteError","HummPaymentStrategy","humm_payment_strategy_rest","processable","isOffsiteRedirectResponse","handleOffsiteRedirectResponse","create_humm_payment_strategy","supportedCountries","supportedCountriesRequiringStates","KlarnaPaymentStrategy","klarnaScriptLoader","klarnaCredit","unsubscribe","loadWidget","klarna_payment_strategy_rest","authorization_token","authorizationToken","authorize","initializePayment","client_token","getUpdateSessionData","mapToKlarnaAddress","needsStateCode","klarnaAddress","street_address","family_name","street_address2","updateSessionData","res","approved","show_form","KlarnaScriptLoader","klarnaWindow","Credit","create_klarna_payment_strategy","KlarnaV2PaymentStrategy","klarnav2ScriptLoader","klarnav2TokenUpdater","klarnaPayments","loadPaymentsWidget","klarnav2_payment_strategy_rest","klarnaMultipleRadioButton","klarnaOrderInitialization","isKlarnaMultipleRadioButtonEnabled","authorizeOrThrow","klarnav2","updateClientToken","payment_method_category","enableBillie","organization_name","KlarnaV2ScriptLoader","Payments","KlarnaV2TokenUpdater","create_klarnav2_payment_strategy","LegacyPaymentStrategy","create_legacy_payment_strategy","MolliePaymentMethodType","methodsNotAllowedWhenDigitalOrder","MolliePaymentStrategy","mollieScriptLoader","mollie","controllers","__WEBPACK_EXTERNAL_MODULE_lodash_each__","controller","initializeOptions","isCreditCard","shouldShowTSVHostedForm","mountCardVerificationfields","mollieClient","loadMollieJs","mountElements","disableButton","loadPaymentMethodsAllowed","mollie_payment_strategy_rest","executeWithVaulted","executeWithCC","executeWithAPM","cardHolderElement","cardNumberElement","verificationCodeElement","expiryDateElement","getMollieClient","createToken","shopper_locale","getShopperLocale","CREDIT_CARD","isHostedFieldAvailable","mollie_payment_strategy_awaiter","getInitializeOptions","testmode","cardNumberId","cardCvcId","cardExpiryId","cardHolderId","createComponent","cartDigitalItems","paragraph","unsupportedMethodMessage","MollieScriptLoader","mollieHostWindow","isMollieWindow","Mollie","create_mollie_payment_strategy","moneris_payment_strategy_IFRAME_NAME","MonerisPaymentStrategy","moneris","monerisOptions","profileId","createIframe","moneris_payment_strategy_rest","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","__WEBPACK_EXTERNAL_MODULE_lodash_map__","allow","monerisResponse","responseCode","dataKey","create_moneris_payment_strategy","OfflinePaymentStrategy","create_offline_payment_strategy","OffsitePaymentStrategy","offsite_payment_strategy_rest","orderPayload","_shouldSubmitFullPayload","create_offsite_payment_strategy","utils_get_paypal_messages_styles_from_bnpl_config","PayPalCommercePaymentStrategy","payPalSdkScriptLoader","paypal_commerce_payment_strategy_rest","isRedirectActionError","isPaypalCommerceAppSwitchEnabled","isPaypalProviderError","create_paypal_commerce_payment_strategy","PayPalCommerceCreditPaymentStrategy","paypalOptions","paypal_commerce_credit_payment_strategy_rest","create_paypal_commerce_credit_payment_strategy","PayPalCommerceVenmoPaymentStrategy","paypal_commerce_venmo_payment_strategy_rest","create_paypal_commerce_venmo_payment_strategy","paypal_commerce_constants_LOADING_INDICATOR_STYLES","PayPalCommerceAlternativeMethodsPaymentStrategy","isOrderApprovedProcessing","paypalcommercealternativemethods","paypal_commerce_alternative_methods_payment_strategy_rest","paypal_commerce_alternative_methods_payment_strategy_awaiter","OXXO","bcOrderId","create_paypal_commerce_alternative_methods_payment_strategy","PayPalCommerceCreditCardsPaymentStrategy","paypalcommercecreditcards","paypalCommerceInitializationOptions","paypal_commerce_credit_cards_payment_strategy_rest","paypal_commerce_credit_cards_payment_strategy_awaiter","paypalCommercePaymentProviderCustomer","isPayPalCommerceAnalyticsV2Enabled","create_paypal_commerce_credit_cards_payment_strategy","PaypalCommerceRatepayPaymentStrategy","paypalCommerceService","paypalcommerceratepay","paypal_commerce_ratepay_payment_strategy_rest","create_paypal_commerce_ratepay_payment_strategy","is_paypal_fastlane_customer_isPayPalFastlaneCustomer","PaypalCommerceFastlanePaymentStrategy","paypal_commerce_fastlane_payment_strategy_rest","isPaypalFastlaneRequestError","create_paypal_commerce_fastlane_payment_strategy","paypal_express_types_PaypalButtonStyleLayoutOption","paypal_express_types_PaypalButtonStyleSizeOption","paypal_express_types_PaypalButtonStyleColorOption","paypal_express_types_PaypalButtonStyleLabelOption","paypal_express_types_PaypalButtonStyleShapeOption","paypal_express_types_PaymentStatusTypes","PaypalExpressPaymentStrategy","useRedirectFlow","paypalexpress","isInContextEnabled","loadPaypalSDK","closeFlow","isAcknowledgedOrFinalized","getPaymentRedirectUrl","initXO","startFlow","PaypalScriptLoader","create_paypal_express_payment_strategy","PaypalProPaymentStrategy","threeDSecureFlow","create_paypal_pro_payment_strategy","SagePayPaymentStrategy","_isThreeDSTwoExperimentOn","create_sage_pay_payment_strategy","ExternalPaymentStrategy","external_payment_strategy_rest","_isAdditionalActionRequired","SezzlePaymentStrategy","create_sezzle_payment_strategy","SquareIntent","SquareV2PaymentProcessor","applicationId","locationId","square","_payments","_formValidationSubscription","_card","destroy","initializeCard","onValidationChange","_getPayments","_subscribeToFormValidation","_getCard","verifyBuyer","CHARGE","_chargeVerifyBuyer","_storeVerifyBuyer","blacklist","Set","eventObservables","currentState","isCompletelyValid","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_distinctUntilChanged__","_mapToSquareBillingContact","STORE","SquareV2PaymentStrategy","_squareV2PaymentProcessor","squarev2","_getVaultedInstrumentPayload","_getCardPayload","shouldVerify","cardTokenizationResult","isSquareV2ApiV2Enabled","tokenForSavingCard","store_card_nonce","store_card_token","verificationToken","_getSquareCardIdOrThrow","three_d_secure","SquareV2WebPaymentsSdkEnv","SquareV2ScriptLoader","LIVE","isSquareV2Window","assertSquareV2Window","Square","create_squarev2_payment_strategy","isIndividualCardElementOptions","individualCardElementOptions","cardNumberElementOptions","cardCvcElementOptions","cardExpiryElementOptions","IconStyle","stripev3_StripeElementType","stripev3_StripePaymentMethodType","StripeV3ErrorType","StripeV3Error","AuthFailure","APM_REDIRECT","Alipay","StripeV3PaymentStrategy","stripev3","isDeinitialize","useIndividualCardFields","allowRedisplayForStoredInstruments","_allowRedisplayForStoredInstruments","stripeV3Client","mountCardVerificationFields","mountCardFields","stripev3_payment_strategy_rest","shouldSubmitOrderBeforeLoadingAPM","confirmStripePayment","buildPaymentPayload","handleEmptyPaymentIntentError","unmountElement","isAuthError","getStripeJs","confirmAlipayPayment","handleActions","confirmIdealPayment","Sepa","confirmSepaDebitPayment","getStripeCardElements","getStripeElement","mapStripeBillingDetails","createPaymentMethod","stripeCardElements","zipCodeElementOptions","isBillingAddressLike","stripePaymentMethodType","cardExpiryElement","cardCvcElement","CardCvc","needsConfirm","StripeV3ScriptLoader","create_stripev3_payment_strategy","supportedLocales","ar","bg","cs","da","el","en","et","fi","fil","fr","he","hr","hu","it","ja","ko","lt","lv","ms","mt","nb","nl","pl","pt","ro","ru","sk","sl","sv","th","tr","vi","zh","formatLocale","localeLanguage","countryLocales","formattedLocale","StripeUPEPaymentStrategy","_loadStripeElement","stripe_upe_payment_strategy_rest","_stripeUPEClient","_executeWithVaulted","_executeWithStripeConfirmation","_processAdditionalActionWithStripeConfirmation","_processVaultedAdditionalAction","initStripeElementUpdateTrigger","enableLink","_loadStripeJs","_isStripeElementUpdateEnabled","wallets","_getStripeElementTerms","READY","_updateStripeLinkStateByElementType","_updateStripeElement","sendSecondPaymentRequestOnStripeError","paymentPayloadWithError","client_side_error","shouldShowTerms","terms","paymentElementType","isStripeLinkElementType","create_stripe_upe_payment_strategy","isStripePaymentEvent","StripeOCSPaymentStrategy","_initializeStripeElement","stripe_ocs_payment_strategy_rest","customerSessionToken","fonts","paymentMethodSelect","handleClosePaymentMethod","togglePreloader","customerSessionClientSecret","savePaymentMethod","maxVisiblePaymentMethods","LOADER_START","_onStripeElementChange","_collapseStripeElement","collapse","paymentMethodOptions","us_bank_account","_shouldSaveInstrument","tokenizedOptions","_getTokenizedOptions","selectedMethodId","client_secret","paymentIntentClientSecret","payment_method_options","collapsed","setupFutureUsage","setup_future_usage","ON_SESSION","OFF_SESSION","tokenized_ach","create_stripe_ocs_payment_strategy","StripeCSPaymentStrategy","_initStripeCheckoutSession","_updateStripeShopperData","_initializePaymentElement","_initializeAdaptivePricingElement","stripe_cs_payment_strategy_rest","_updateCheckoutSessionData","getPaymentElement","currencySelectorElement","getCurrencySelectorElement","adaptivePricing","allowed","adaptivePricingEnabled","_getStripeElement","_getStripeActionsOrThrow","createPaymentElement","newVaultedStripeInstrument","existingStripeSavedPaymentMethods","_getStripeSavedPaymentMethodsOrThrow","session","_confirmStripePayment","newStripeSavedPaymentMethods","checkoutSessionId","checkoutSessionStatus","_getNewVaultedStripeInstrument","paymentStatus","Paid","stripeActions","_updateStripeEmail","_updateStripeShippingAddress","_updateStripeBillingAddress","updateEmail","savedPaymentMethods","existingMethod","currencySelectorContainerId","_getCurrencySelectorElement","_initAdaptivePricingEvents","createCurrencySelectorElement","stripe_cs_payment_strategy_awaiter","stripeCurrencyCode","isCustomerCurrencySelected","customerCurrency","create_stripe_cs_payment_strategy","FieldType","TDOnlineMartPaymentStrategy","tdOnlineMartScriptLoader","tdInputs","CARD_NUMBER","CVV","EXPIRY","tdOnlineMartClient","loadTDOnlineMartJs","mountHostedFields","td_online_mart_payment_strategy_rest","getPaymentPayloadOrThrow","processWithAdditionalAction","inputElement","digitalItemsInCart","shouldAddVerificationToken","isTrustedVaultingInstrument","getTokenOrThrow","throwTokenizationError","getHostedFieldsOptions","getTDOnlineMartClientOrThrow","inputId","isTdOnlineMartAdditionalAction_isTdOnlineMartAdditionalAction","isCreateTokenError","classes","TDOnlineMartScriptLoader","tdOnlineMartWindow","customcheckout","create_td_online_mart_payment_strategy","PAYMENT_CANNOT_CONTINUE","worldpayaccess_payment_strategy_submit","WorldpayAccessPaymentStrategy","worldpay","_submitAdditionalAction","messageEventListener","worldpayaccess_payment_strategy_awaiter","_isValidJsonWithSessionId","iframeHidden","SessionId","submitError","onLoadError","_createHiddenIframe","formId","inputBin","source_id","inputJWT","match","srcdoc","outerHTML","str","create_worldpayaccess_payment_strategy","WorldpayAccessOpenBankingPaymentStrategy","_buildOpenBankingSubmitPayment","_isWorldpayAccessRedirectResponse","open_banking","create_worldpayaccess_open_banking_payment_strategy","StorefrontPaymentRequestSender","saveExternalId","externalId","ZipPaymentStrategy","storefrontPaymentRequestSender","zip_payment_strategy_rest","_prepareForReferredRegistration","create_zip_payment_strategy","CountryActionType","OrderActionType","CountryActionCreator","_countryRequestSender","loadCountries","LoadCountriesRequested","LoadCountriesSucceeded","LoadCountriesFailed","CountryRequestSender","CartConsistencyError","CartStockPositionsChangedError","changedItemIds","OrderTaxProviderUnavailableError","MissingShippingMethodError","InvalidShippingAddressError","OrderRequestSender","loadOrder","checkoutVariant","SpamProtectionNotCompletedError","PaymentMethodActionType","OrderActionCreator","_orderRequestSender","_checkoutValidator","LoadOrderRequested","LoadOrderSucceeded","LoadOrderFailed","loadOrderPayments","LoadOrderPaymentsRequested","LoadOrderPaymentsSucceeded","LoadOrderPaymentsFailed","_getCurrentOrderId","SubmitOrderRequested","externalSource","getExternalSource","variantIdentificationToken","getVariantIdentificationToken","shouldExecuteSpamCheck","_mapToOrderRequestBody","customerMessage","SubmitOrderSucceeded","SubmitOrderFailed","FinalizeOrderRequested","FinalizeOrderSucceeded","FinalizeOrderFailed","order_action_creator_rest","createPaymentClient","paymentClient","__WEBPACK_EXTERNAL_MODULE__bigcommerce_bigpay_client_fce6db19_createClient__","setHost","isPaymentMethod","PaymentMethodActionCreator","loadPaymentMethodsById","methodIds","LoadPaymentMethodsRequested","payment_method_action_creator_awaiter","LoadPaymentMethodsSucceeded","LoadPaymentMethodsFailed","sessionHash","methods","LoadPaymentMethodRequested","LoadPaymentMethodSucceeded","LoadPaymentMethodFailed","payment_method_action_creator_decorate","PaymentMethodRequestSender","order_finalization_not_required_error_OrderFinalizationNotRequiredError","PaymentStrategyActionType","PaymentStrategyType","payment_strategy_type","PaymentStrategyWidgetActionCreator","PaymentStrategyActionCreator","_orderActionCreator","_paymentStrategyWidgetActionCreator","isPaymentDataRequired","NO_PAYMENT_DATA_REQUIRED","FinalizeRequested","_loadOrderPaymentsIfNeeded","payment_strategy_action_creator_awaiter","FinalizeSucceeded","FinalizeFailed","paymentStrategies","getByMethod","CartComparator","cartA","cartB","_normalize","itemA","itemB","variantId","localeCompare","extendedSalePrice","recipient","giftWrapping","CartChangedError","previous","updated","CheckoutValidator","comparator","_compareCoupons","_compareGiftCertificates","_getComparableCheckout","couponsA","couponsB","giftCertificatesA","giftCertificatesB","BrowserStorage","_namespace","rawValue","withNamespace","getItemOnce","CardingProtectionChallengeNotCompletedError","CardingProtectionFailedError","HostedFieldEventType","HostedInputEventType","PaymentHumanVerificationHandler","handle","errorOrId","handleWithRecaptchaSitekey","handleWithPaymentHumanVerificationRequestError","_isPaymentHumanVerificationRequest","_initialize","_performRecaptcha","payment_human_verification_handler_awaiter","human_verification_token","cardingProtectionElementId","cardingProtectionElement","mapFromPaymentErrorResponse","joinErrors","InvalidHostedFormConfigError","InvalidHostedFormError","InvalidHostedFormValueError","__WEBPACK_EXTERNAL_MODULE_lodash_flatMap__","fieldErrors","HostedField","_type","_placeholder","_accessibilityLabel","_styles","_eventPoster","_eventListener","_detachmentObserver","_checkoutId","_cardInstrument","overflow","getType","hosted_field_awaiter","AttachRequested","cardInstrument","fontUrls","_getFontUrls","AttachSucceeded","AttachFailed","SubmitRequested","SubmitSucceeded","SubmitFailed","_isSubmitErrorEvent","submitStoredCardForm","StoredCardRequested","StoredCardSucceeded","StoredCardFailed","validateForm","ValidateRequested","family","PaymentActionType","HostedForm","_fields","_payloadTransformer","_eventCallbacks","_paymentHumanVerificationHandler","hosted_form_awaiter","Blurred","CardTypeChanged","Focused","Entered","_cardType","BinChanged","_bin","getCardType","_getFirstField","otherFields","__WEBPACK_EXTERNAL_MODULE_lodash_without__","otherField","submitStoredCard","is_vaulted_instrument_isVaultedInstrument","HostedFormOrderDataTransformer","getConfig","instrumentMeta","getInstrumentsMeta","orderMeta","getOrderMeta","paymentMethodMeta","getPaymentMethodsMeta","authToken","vaultAccessToken","HostedFormFactory","fieldOptions","_getCardInstrument","__WEBPACK_EXTERNAL_MODULE_lodash_pick__","MissingPaymentInstrument","PaymentActionCreator","_paymentRequestSender","_paymentRequestTransformer","InitializeOffsitePaymentRequested","InitializeOffsitePaymentSucceeded","InitializeOffsitePaymentFailed","SubmitPaymentRequested","payment_action_creator_awaiter","SubmitPaymentSucceeded","SubmitPaymentFailed","PaymentRequestSender","_client","_transformResponse","statusText","mapToInternalAddress","addressId","is_billing_address_like_isBillingAddressLike","province","provinceCode","postCode","couponTypes","mapToInternalCoupon","discount","discountType","couponType","mapToInternalGiftCertificate","used","remainingBalance","remaining","balance","purchaseDate","mapToDiscountNotifications","promotions","notifications","promotion","banners","banner","placeholders","messageHtml","mapToInternalLineItems","itemMap","idKey","amountAfterDiscount","integerAmountAfterDiscount","integerUnitPrice","integerUnitPriceAfterDiscount","integerDiscount","sender","mapGiftCertificateToInternalLineItem","extendedListPrice","downloadsPageUrl","downloadPageUrl","mapToInternalLineItem","mapToInternalLineItemType","mapToInternalCart","sum","discountNotifications","totalDiscountedAmount","certificate","appliedGiftCertificates","__WEBPACK_EXTERNAL_MODULE_lodash_keyBy__","amountBeforeDiscount","shippingCostBeforeDiscount","integerAmountBeforeDiscount","taxSubtotal","handling","handlingCostTotal","CheckoutButtonMethodType","checkout_button_method_type","mapToInternalCustomer","customerGroupName","customerGroup","CardExpiryFormatter","RegExp","trimmedMonth","trimmedYear","toObject","CardNumberFormatter","__WEBPACK_EXTERNAL_MODULE_card_validator_0e6920dd_number__","__WEBPACK_EXTERNAL_MODULE_lodash_max__","__WEBPACK_EXTERNAL_MODULE_card_validator_0e6920dd_creditCardType__","lengths","unformattedValue","unformat","gaps","gapIndex","mapToInternalOrder","customerCanBeCreated","mapToInternalOrderPayment","baseAmount","callbackUrl","mapToGiftCertificates","socialData","mapToInternalSocialDataList","hasDigitalItems","isDownloadable","isComplete","mapToStoreCredit","orderAmountAsInteger","isDefaultOrderPayment","helpText","instructions","socialDataObject","socialMedia","image","shareText","sharingLink","channelName","channel","channelCode","mapToInternalShippingOption","isSelected","price","selected","transitTime","PaymentRequestTransformer","_cardExpiryFormatter","_cardNumberFormatter","getShippingOption","contextConfig","paymentMeta","internalCustomer","formattedInstrument","is_vaulted_instrument_isFormattedVaultedInstrument","_transformPaymentMethod","quoteMeta","geoCountryCode","transformWithHostedFormData","_transformHostedInputValues","BRAINTREE_VENMO","BRAINTREE_PAYPAL","hostedFormNonce","isBopisEnabled","bopis","requiredAddress","isPickup","selectedPickupOption","isPPSDKPaymentMethod","initializationStrategy","PPSDK","PaymentStrategyRegistry","_getToken","KLARNAV2","_hasFactoryForMethod","OFFLINE","payment_argument_invalid_error_PaymentArgumentInvalidError","credit_card_payment_strategy_CreditCardPaymentStrategy","_paymentActionCreator","_hostedFormFactory","credit_card_credit_card_payment_strategy_rest","ConvergePaymentStrategy","orderActionCreator","paymentActionCreator","hostedFormFactory","payment_method_cancelled_error_PaymentMethodCancelledError","PENDING_REDIRECT_PARAM","RedirectionState","_isRedirecting","currentUrlHasRedirectingParam","isRedirecting","setRedirecting","setRedirectingParamOnUrl","removeRedirectingParamFromUrl","getCurrentUrl","__WEBPACK_EXTERNAL_MODULE_query_string_2dcf3be8_parseUrl__","replaceCurrentUrl","history","replaceState","currentUrl","updatedUrl","__WEBPACK_EXTERNAL_MODULE_query_string_2dcf3be8_stringifyUrl__","__WEBPACK_EXTERNAL_MODULE_query_string_2dcf3be8_exclude__","isAnyContinue","__WEBPACK_EXTERNAL_MODULE_lodash_overSome__","__WEBPACK_EXTERNAL_MODULE_lodash_get__","__WEBPACK_EXTERNAL_MODULE_lodash_isString__","__WEBPACK_EXTERNAL_MODULE_lodash_isUndefined__","redirect_isParameters","availableMethods","isParameters","ContinueHandler","_humanVerificationHandler","form_fields","redirectionState","handleRedirect","available_methods","humanVerificationHandler","human_verification_awaiter","handleHumanVerification","humanVerification","StepHandler","_continueHandler","isSuccess","isContinue","isFailure","failureResponse","isError","COMPLETED_PAYMENTS_KEY","PPSDKCompletedPayments","_browserStorage","isCompleted","getCompletedPayments","setCompleted","completedPayments","setCompletedPayments","SubStrategyType","PPSDKStrategy","_subStrategyRegistry","_paymentResumer","browserStorage","_completedPayments","ppsdk_strategy_rest","_subStrategy","subStrategy","getPPSDKMethod","getToken","__WEBPACK_EXTERNAL_MODULE_lodash_cond__","__WEBPACK_EXTERNAL_MODULE_lodash_constant__","CARD","NONE","__WEBPACK_EXTERNAL_MODULE_lodash_stubTrue__","UNSUPPORTED","SubStrategyRegistry","CardSubStrategy","_ppsdkStepHandler","card_sub_strategy_awaiter","NoneSubStrategy","_stepHandler","payment_method_id","PaymentProviderCustomerType","RemoteCheckoutActionType","PaymentResumer","auth_token","CartRequestSender","PaymentProviderCustomerActionCreator","providerCustomerData","UpdatePaymentProviderCustomer","ConsignmentActionType","RemoteCheckoutActionCreator","_remoteCheckoutRequestSender","initializeBilling","InitializeRemoteBillingRequested","InitializeRemoteBillingSucceeded","InitializeRemoteBillingFailed","initializeShipping","InitializeRemoteShippingRequested","InitializeRemoteShippingSucceeded","InitializeRemoteShippingFailed","InitializeRemotePaymentRequested","InitializeRemotePaymentSucceeded","InitializeRemotePaymentFailed","loadSettings","LoadRemoteSettingsRequested","LoadRemoteSettingsSucceeded","LoadRemoteSettingsFailed","SignOutRemoteCustomerRequested","SignOutRemoteCustomerSucceeded","SignOutRemoteCustomerFailed","ForgetCheckoutRemoteCustomerRequested","remote_checkout_action_creator_awaiter","ForgetCheckoutRemoteCustomerSucceeded","ForgetCheckoutRemoteCustomerFailed","UpdateRemoteCheckout","RemoteCheckoutRequestSender","methodName","generateToken","trackAuthorizationEvent","ConsignmentActionCreator","_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","consignmentInMemory","getConsignmentById","_isUpdateConsignmentRequest","itemId","_hydrateLineItems","lineItemIds","existingItem","sharedItem","concat","DEFAULT_INCLUDES","ConsignmentRequestSender","consignment_request_sender_rest","ShippingCountryActionType","StoreCreditActionType","ShippingCountryActionCreator","_shippingCountryRequestSender","checkoutData","LoadShippingCountriesRequested","LoadShippingCountriesSucceeded","LoadShippingCountriesFailed","ShippingCountryRequestSender","SubscriptionsActionType","StoreCreditActionCreator","_storeCreditRequestSender","ApplyStoreCreditRequested","store_credit_action_creator_awaiter","checkoutVersion","removeStoreCredit","ApplyStoreCreditSucceeded","ApplyStoreCreditFailed","StoreCreditRequestSender","UpdateSubscriptionsError","SubscriptionsActionCreator","_subscriptionsRequestSender","subscriptions","UpdateSubscriptionsRequested","subscriptions_action_creator_awaiter","UpdateSubscriptionsSucceeded","UpdateSubscriptionsFailed","SubscriptionsRequestSender","isPlainObject","__WEBPACK_EXTERNAL_MODULE_lodash_isPlainObject__","cloneDeep","__WEBPACK_EXTERNAL_MODULE_lodash_memoize__","cloneDeepSafe","cache","cloneResult","createPaymentIntegrationSelectors","getPaymentTokenOrThrow","getPaymentIdOrThrow","getPaymentStatusOrThrow","getPaymentRedirectUrlOrThrow","getShippingAddressOrThrow","getShippingAddresses","getShippingAddressesOrThrow","shippingCountries","InstrumentActionType","DefaultPaymentIntegrationService","_storeProjectionFactory","_billingAddressActionCreator","_consignmentActionCreator","_paymentMethodActionCreator","_cartRequestSender","_storeCreditActionCreator","_couponActionCreator","_paymentProviderCustomerActionCreator","_shippingCountryActionCreator","_remoteCheckoutActionCreator","_storeProjection","subscriber","filters","initializeOffsitePaymentConfig","buyNowCartRequestBody","handlePaymentHumanVerification","queueId","PaymentIntegrationStoreProjectionFactory","_transformSelectors","createPaymentIntegrationService","storeProjectionFactory","checkoutActionCreator","checkoutValidator","billingAddressActionCreator","consignmentActionCreator","paymentMethodActionCreator","paymentHumanVerificationHandler","customerActionCreator","storeCreditActionCreator","applyCouponActionCreator","spamProtection","spamProtectionRequestSender","spamProtectionActionCreator","cartRequestSender","paymentProviderCustomerActionCreator","shippingCountryActionCreator","remoteCheckoutActionCreator","paymentStrategyWidgetActionCreator","InstrumentActionCreator","_instrumentRequestSender","loadInstruments","LoadInstrumentsRequested","_getSessionContext","_getCurrentAccessToken","_getShippingAddress","_getValidAccessToken","currentToken","LoadInstrumentsSucceeded","LoadInstrumentsFailed","deleteInstrument","DeleteInstrumentRequested","DeleteInstrumentSucceeded","DeleteInstrumentFailed","_isValidVaultAccessToken","newDate","setMinutes","getMinutes","addMinutes","vaultAccessExpiry","valueOf","getVaultAccessToken","isTransactional","PickupOptionActionType","ShippingStrategyActionType","InstrumentResponseTransformer","transformResponse","instrument_response_transformer_rest","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","InstrumentRequestSender","_transformer","requestContext","_loadInstrumentsWithAddress","_loadInstruments","deleteShopperInstrument","errorResponse","loadInstrumentsWithAddress","PickupOptionActionCreator","_pickupOptionRequestSender","loadPickupOptions","apiQuery","_hydrateApiQuery","LoadPickupOptionsRequested","fetchPickupOptions","LoadPickupOptionsSucceeded","LoadPickupOptionsFailed","consignmentLineItems","cartItems","searchArea","PickupOptionRequestSender","ShippingStrategyActionCreator","UpdateAddressRequested","UpdateAddressSucceeded","UpdateAddressFailed","selectOption","SelectOptionRequested","SelectOptionSucceeded","SelectOptionFailed","mergedOptions","shippingStrategies","instrument_UntrustedShippingCardVerificationType","AmazonPayV2ShippingStrategy","_amazonPayV2PaymentProcessor","_shippingStrategyActionCreator","updateAddressRequestBody","editAddressButtonId","shouldShowLoadingSpinner","_shouldShowLoadingSpinner","BraintreeFastlaneShippingStrategy","_braintreeIntegrationService","fastlane","fastlaneOptions","onPayPalFastlaneAddressChange","_shouldRunAuthenticationFlow","_runAuthenticationFlowOrThrow","_shouldUseBraintreeFastlaneShippingComponent","_handleBraintreeFastlaneShippingAddressChange","_getPayPalBillingAddress","paypalPhoneNumber","_mapPayPalToBcAddress","_mergeShippingAndBillingAddresses","_mapPayPalToBcInstrument","_getCountryNameByCountryCode","_normalizeAddress","selectedAddress","showShippingAddressSelector","paymentProviderCustomerAddresses","_filterAddresses","_isEqualAddresses","_getBraintreePaymentMethodOrThrow","isFastlaneEnabled","DefaultShippingStrategy","PayPalCommerceFastlaneShippingStrategy","_paypalSdkScriptLoader","_paypalCommerceFastlaneUtils","_shouldAuthenticateUserWithFastlane","_initializePayPalSdk","_authenticateUserWithFastlaneOtp","_shouldUsePayPalFastlaneShippingComponent","_handlePayPalShippingAddressChange","_getPayPalPaymentMethodOrThrow","_getPayPalCustomerAuthenticationState","paypalConnectSessionId","customerAuthenticationState","billingAddressEmail","SignInEmailActionType","StripeUPEShippingStrategy","_stripeScriptLoader","onChangeShipping","availableCountries","getStripeState","getShippingAddressFields","shippingFields","spacingUnit","shippingPhoneField","allowedCountries","validation","SPLIT","stripeState","shippingAddressElement","isNewAddress","sendData","phoneFieldRequired","SignInEmailActionCreator","sendSignInEmail","emailRequest","SendSignInEmailRequested","signin_email_action_creator_awaiter","SendSignInEmailSucceeded","SendSignInEmailFailed","SignInEmailRequestSender","ErrorMessageTransformer","_messageCustomizer","CheckoutService","_extensionEventBroadcaster","_b2bTokenActionCreator","_countryActionCreator","_customerStrategyActionCreator","_errorActionCreator","_giftCertificateActionCreator","_instrumentActionCreator","_paymentStrategyActionCreator","_pickupOptionActionCreator","_signInEmailActionCreator","_subscriptionsActionCreator","_extensionActionCreator","_errorTransformer","isDevelopment","isCheckoutServiceError","createCheckoutServiceErrorTransformer","notifyState","_dispatch","loadCheckoutAction","formFieldsAction","loadConfigAction","finalizeOrderIfNeeded","loadPaymentMethodByIds","deinitializePayment","loadBillingCountries","loadBillingAddressFields","loadShippingAddressFields","initializeCustomer","deinitializeCustomer","signInEmailRequest","createCustomerAccount","createCustomerAddress","deinitializeShipping","assignItemsToAddress","unassignItemsToAddress","selectConsignmentShippingOption","initializeSpamProtection","executeSpamCheck","clearExtensionCache","postMessageToExtension","handleExtensionCommand","handler","handleExtensionQuery","checkout_service_decorate","withMemoizedCombiner","creator","combiner","pop","combinerArgs","create_selector","__WEBPACK_EXTERNAL_MODULE_reselect_createSelector__","create_shallow_equal_selector","__WEBPACK_EXTERNAL_MODULE_reselect_createSelectorCreator__","__WEBPACK_EXTERNAL_MODULE_reselect_defaultMemoize__","__WEBPACK_EXTERNAL_MODULE_shallowequal_default__","UnrecoverableError","map_from_internal_error_response_joinErrors","timeout_error_TimeoutError","RequestErrorFactory","_factoryMethods","mapFromInternalErrorResponse","mapFromStorefrontErrorResponse","factoryMethod","createError","_getType","_isStorefrontErrorResponseBody","_isInternalErrorResponseBody","internalType","__WEBPACK_EXTERNAL_MODULE_lodash_last__","storefrontErrorResponse","internalErrorResponse","omitDeep","predicate","__WEBPACK_EXTERNAL_MODULE_lodash_transform__","clearErrorReducer","isClearErrorAction","objectA","objectB","isArrayEqual","isDateEqual","isRegExpEqual","keyFilter","keysA","keysB","isObjectEqual","objectSet","DEFAULT_STATE","statuses","b2bTokenReducer","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_combineReducers__","dataReducer","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_composeReducers__","errorsReducer","statusesReducer","reducer","currentValue","newValue","billing_address_state_DEFAULT_STATE","billingAddressReducer","billing_address_reducer_dataReducer","billing_address_reducer_errorsReducer","billing_address_reducer_statusesReducer","array_replace","arrayReplace","currentArray","newArray","matchObject","sameAsCurrentCount","sameAsNewCount","countSameAsReplaced","replacedValue","newItem","currentItem","object_merge","objectMerge","currentObject","newObject","cart_state_DEFAULT_STATE","cartReducer","cart_reducer_dataReducer","cart_reducer_errorsReducer","cart_reducer_statusesReducer","CheckoutButtonActionType","checkout_button_state_DEFAULT_STATE","DEFAULT_DATA_STATE","initializedContainers","DEFAULT_ERROR_STATE","DEFAULT_STATUS_STATE","checkoutButtonReducer","checkout_button_reducer_dataReducer","checkout_button_reducer_errorsReducer","checkout_button_reducer_statusesReducer","InitializeButtonSucceeded","DeinitializeButtonSucceeded","InitializeButtonRequested","InitializeButtonFailed","DeinitializeButtonRequested","DeinitializeButtonFailed","config_state_DEFAULT_STATE","configReducer","config_reducer_dataReducer","config_reducer_errorsReducer","config_reducer_statusesReducer","merged","coupon_state_DEFAULT_STATE","couponReducer","coupon_reducer_dataReducer","coupon_reducer_errorsReducer","coupon_reducer_statusesReducer","gift_certificate_state_DEFAULT_STATE","giftCertificateReducer","gift_certificate_reducer_dataReducer","gift_certificate_reducer_errorsReducer","gift_certificate_reducer_statusesReducer","customer_state_DEFAULT_STATE","customerReducer","customer_reducer_dataReducer","customer_reducer_errorsReducer","customer_reducer_statusesReducer","customer_strategy_state_DEFAULT_STATE","customerStrategyReducer","customer_strategy_reducer_dataReducer","customer_strategy_reducer_errorsReducer","customer_strategy_reducer_statusesReducer","initializeErrors","initializeMethodId","deinitializeError","deinitializeMethodId","signInError","signInMethodId","signOutError","signOutMethodId","executePaymentMethodCheckoutError","executePaymentMethodCheckoutMethodId","widgetInteractionError","widgetInteractionMethodId","isInitializing","isDeinitializing","isSigningIn","isSigningOut","isExecutingPaymentMethodCheckout","isWidgetInteracting","extension_state_DEFAULT_STATE","extensionReducer","extension_reducer_dataReducer","extension_reducer_errorsReducer","extension_reducer_statusesReducer","form_fields_state_DEFAULT_STATE","formFieldsReducer","form_fields_reducer_dataReducer","extraFields","extraFieldsReducer","form_fields_reducer_errorsReducer","form_fields_reducer_statusesReducer","country_state_DEFAULT_STATE","countryReducer","country_reducer_dataReducer","country_reducer_errorsReducer","country_reducer_statusesReducer","order_state_DEFAULT_STATE","orderReducer","order_reducer_dataReducer","order_reducer_errorsReducer","metaReducer","order_reducer_statusesReducer","order_billing_address_state_DEFAULT_STATE","orderBillingAddressReducer","order_billing_address_reducer_dataReducer","paymentReducer","payment_reducer_dataReducer","payment_method_state_DEFAULT_STATE","paymentMethodReducer","payment_method_reducer_dataReducer","payment_method_reducer_errorsReducer","payment_method_reducer_metaReducer","payment_method_reducer_statusesReducer","array","defaultPredicate","derivedPredicate","__WEBPACK_EXTERNAL_MODULE_lodash_findIndex__","mergeOrPush","methodA","methodB","loadMethodId","loadMethodError","isLoadingMethod","payment_strategy_state_DEFAULT_STATE","paymentStrategyReducer","payment_strategy_reducer_dataReducer","payment_strategy_reducer_errorsReducer","payment_strategy_reducer_statusesReducer","initializeError","executeError","executeMethodId","finalizeError","finalizeMethodId","isExecuting","isFinalizing","payment_provider_customer_state_DEFAULT_STATE","paymentProviderCustomerReducer","payment_provider_customer_reducer_dataReducer","instrument_state_DEFAULT_STATE","instrumentReducer","instrument_reducer_dataReducer","instrument_reducer_errorsReducer","instrument_reducer_metaReducer","instrument_reducer_statusesReducer","deleteError","failedInstrument","isDeleting","deletingInstrument","remote_checkout_state_DEFAULT_STATE","remoteCheckoutReducer","remote_checkout_reducer_dataReducer","consignment_state_DEFAULT_STATE","updateShippingOptionError","updateError","isUpdating","isUpdatingShippingOption","consignmentReducer","consignment_reducer_dataReducer","consignment_reducer_errorsReducer","consignment_reducer_statusesReducer","objectFlatten","flattened","keyString","objectWithSortedKeys","current","pickup_option_state_DEFAULT_STATE","pickupOptionReducer","pickup_option_reducer_dataReducer","pickup_option_reducer_errorsReducer","pickup_option_reducer_statusesReducer","sortedflattenedMeta","shipping_country_state_DEFAULT_STATE","shippingCountryReducer","shipping_country_reducer_dataReducer","shipping_country_reducer_errorsReducer","shipping_country_reducer_statusesReducer","shipping_strategy_state_DEFAULT_STATE","shippingStrategyReducer","shipping_strategy_reducer_dataReducer","shipping_strategy_reducer_errorsReducer","shipping_strategy_reducer_statusesReducer","updateAddressError","updateAddressMethodId","selectOptionError","selectOptionMethodId","isUpdatingAddress","isSelectingOption","signin_email_state_DEFAULT_STATE","signInEmailReducer","signin_email_reducer_dataReducer","signin_email_reducer_errorsReducer","signin_email_reducer_statusesReducer","store_credit_reducer_DEFAULT_STATE","storeCreditReducer","store_credit_reducer_errorsReducer","store_credit_reducer_statusesReducer","subscriptions_state_DEFAULT_STATE","subscriptionsReducer","subscriptions_reducer_errorsReducer","subscriptions_reducer_statusesReducer","checkout_state_DEFAULT_STATE","checkoutReducer","checkout_reducer_dataReducer","checkout_reducer_errorsReducer","checkout_reducer_statusesReducer","guard_guard","createFreezeProxy","proxy","iteratee","getPrototypeOf","traversePrototypeOf","charAt","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_deepFreeze__","trap","createProxy","supported_payment_instruments","authorizenet","elavon","checkoutcom","sagepay","cybersource","cybersourcev2","bnz","converge","orbital","paymetric","cba_mpgs","worldpayaccess","tdonlinemart","normalize","__WEBPACK_EXTERNAL_MODULE_lodash_identity__","store_credit_state_DEFAULT_STATE","createInternalCheckoutSelectorsFactory","createB2BTokenSelector","getLoadError","loadError","__WEBPACK_EXTERNAL_MODULE__bigcommerce_memoize_bf7b411a_memoizeOne__","createB2BTokenSelectorFactory","createBillingAddressSelector","getUpdateError","getContinueAsGuestError","continueAsGuestError","isContinuingAsGuest","createBillingAddressSelectorFactory","createCartSelector","createCartSelectorFactory","createCheckoutButtonSelector","getInitializeError","getDeinitializeError","createCheckoutButtonSelectorFactory","createConfigSelector","getFlashMessages","filterType","flashMessages","formState","createConfigSelectorFactory","createCountrySelector","createCountrySelectorFactory","createCouponSelector","getCoupons","getRemoveError","removeCouponError","getApplyError","applyCouponError","isApplying","isApplyingCoupon","isRemoving","isRemovingCoupon","createCouponSelectorFactory","createCustomerSelector","getCreateAccountError","isCreatingCustomerAccount","isCreating","getCreateAddressError","createAddressError","isCreatingCustomerAddress","isCreatingAddress","createCustomerSelectorFactory","createCustomerStrategySelector","getSignInError","getSignOutError","getExecutePaymentMethodCheckoutError","getWidgetInteractionError","createCustomerStrategySelectorFactory","createGiftCertificateSelector","getGiftCertificates","removeGiftCertificateError","applyGiftCertificateError","isApplyingGiftCertificate","isRemovingGiftCertificate","createGiftCertificateSelectorFactory","createInstrumentSelector","getInstrumentsByPaymentMethod","paymentMethodKey","currentMethod","__WEBPACK_EXTERNAL_MODULE_lodash_isMatch__","supportedProvider","getDeleteError","createInstrumentSelectorFactory","createFormSelector","selectedCountry","processField","getBillingAddressFields","getCustomerAccountFields","getAddressExtraFields","itemtype","processCountry","subdivisions","requiresState","processProvince","hasPostalCodes","processsPostCode","createFormSelectorFactory","createPaymentMethodSelector","getPaymentMethods","getLoadMethodError","createPaymentMethodSelectorFactory","createPaymentStrategySelector","getExecuteError","getFinalizeError","getWidgetInteractingError","createPaymentStrategySelectorFactory","createPickupOptionSelector","getPickupOptions","pickupOptions","sortedFlattenedParams","createPickupOptionSelectorFactory","createPaymentProviderCustomerSelector","createPaymentProviderCustomerSelectorFactory","createRemoteCheckoutSelector","createRemoteCheckoutSelectorFactory","createShippingAddressSelector","shippingConsignment","shippingConsignments","createShippingAddressSelectorFactory","createShippingCountrySelector","createShippingCountrySelectorFactory","createShippingStrategySelector","getUpdateAddressError","getSelectOptionError","createShippingStrategySelectorFactory","createConsignmentSelector","isAddressEqual","addressA","addressB","getCreateError","getLoadShippingOptionsError","loadShippingOptionsError","getUnassignedItems","assignedLineItemIds","itemIds","getItemAssignmentError","getUpdateShippingOptionError","isLoadingShippingOptions","isAssigningItems","createConsignmentSelectorFactory","createCheckoutSelector","isExecutingSpamCheck","createCheckoutSelectorFactory","createOrderSelector","getOrderBillingAddress","currentPayment","createOrderSelectorFactory","createOrderBillingAddressSelector","createOrderBillingAddressSelectorFactory","createPaymentSelector","getInternalPayment","getGatewayPayment","getHostedPayment","providerType","internalPayment","MissingPaymentId","MissingPaymentStatus","MissingPaymentRedirectUrl","isPaymentDataSubmitted","createPaymentSelectorFactory","createStoreCreditSelector","applyError","createStoreCreditSelectorFactory","createSubscriptionsSelector","createSubscriptionsSelectorFactory","createSignInEmailSelector","getEmail","signInEmail","getSendError","sendError","isSending","createSignInEmailSelectorFactory","createExtensionSelector","createExtensionSelectorFactory","b2bToken","checkoutButton","orderBillingAddress","remoteCheckout","selectors","shouldWarnMutation","createCheckoutStore","initialStoreState","actionTransformer","requestErrorFactory","createRequestErrorFactory","action$","createInternalCheckoutSelectors","createCheckoutService","checkoutVariantIdentificationToken","experimentRequestSender","orderRequestSender","checkoutRequestSender","configActionCreator","subscriptionsActionCreator","formFieldsActionCreator","registryV2","paymentStrategyFactories","createPaymentStrategy","createPaymentStrategyRegistry","payment_strategies_namespaceObject","customerRegistryV2","customerStrategyFactories","createCustomerStrategy","createCustomerStrategyRegistry","customer_strategies_namespaceObject","extensionActionCreator","extensionMessenger","storeProjection","createCheckoutStoreSelector","getShippingOptions","getSelectedShippingOption","getBillingCountries","getSelectedPaymentMethod","getSignInEmail","getUserExperienceSettings","checkoutUserExperienceSettings","createCheckoutStoreSelectorFactory","createCheckoutStoreErrorSelector","getSelectShippingOptionError","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","getLoadB2BTokenError","getCreateCustomerAccountError","getCreateCustomerAddressError","getPickupOptionsError","getLoadExtensionsError","createCheckoutStoreErrorSelectorFactory","createCheckoutStoreStatusSelector","isPending","isSelectingShippingOption","isCustomerStepPending","isShippingStepPending","isPaymentStepPending","isSubmittingOrder","isLoadingCheckout","isUpdatingCheckout","isFinalizingOrder","isLoadingOrder","isLoadingCart","isLoadingBillingCountries","isLoadingShippingCountries","isLoadingPaymentMethods","isLoadingPaymentMethod","isInitializingPayment","isInitializingCustomer","isInitializedCustomer","isUpdatingBillingAddress","isUpdatingSubscriptions","isUpdatingShippingAddress","isUpdatingConsignment","isDeletingConsignment","isCreatingConsignments","isInitializingShipping","isApplyingStoreCredit","isLoadingInstruments","isDeletingInstrument","isLoadingConfig","isSendingSignInEmail","isLoadingB2BToken","isLoadingPickupOptions","createCheckoutStoreStatusSelectorFactory","createCheckoutSelectorsFactory","checkout_service","messenger","subscribers","createExtensionEventBroadcaster","create_customer_strategy_registry_createCustomerStrategyRegistry","paymentRequestTransformer","paymentRequestSender","stepHandler","createStepHandler","CONVERGE","createSubStrategyRegistry","create_payment_strategy_registry_createPaymentStrategyRegistry","consignmentRequestSender","createShippingStrategyRegistry","AmazonPayV2ConfigCreationError","isWithBuyNowFeatures","AmazonPayV2ButtonStrategy","amazonPayV2ConfigRequestSender","initializeAmazonButtonOptions","_buyNowInitializeOptions","Cart","_getCheckoutCreationRequestConfig","_createBuyNowCartOrThrow","_createCheckoutConfig","public_key","rest","amazon_pay_v2_button_strategy_rest","payloadJSON","AmazonPayV2RequestSender","create_amazon_pay_v2_button_strategy","amazonPayV2RequestSender","apple_pay_button_strategy_DefaultLabels","ButtonStyleOption","ApplePayButtonStrategy","_requiresShipping","White","WhiteBorder","Black","getButtonStyle","_getRequestWithEmptyTotal","apple_pay_button_strategy_awaiter","onpaymentmethodselected","_createBuyNowCart","_handlePaymentMethodSelected","completePaymentMethodSelection","create_apple_pay_button_strategy","BigCommercePaymentsButtonStrategy","onEligibilityFailure","buyNowFlowCallbacks","create_bigcommerce_payments_button_strategy","BigCommercePaymentsPayLaterButtonStrategy","create_bigcommerce_payments_paylater_button_strategy","BigCommercePaymentsVenmoButtonStrategy","getValidVenmoButtonStyles","validButtonStyle","gold","create_bigcommerce_payments_venmo_button_strategy","BoltButtonStrategy","BoltConnect","setupProductPageCheckout","addButtonContainer","boltButtonContainer","boltButtonObject","getBoltObjectData","append","domainUrl","getButtonHeight","buttonBorderRadius","getButtonBorderRadius","publishable_key","variant","border_radius","buttonSize","Small","Large","Medium","buttonShape","Pill","Rect","create_bolt_button_strategy","fundingicons","tagline","currentHeight","BraintreePaypalButtonStrategy","shouldProcessPayment","onAuthorizeError","buyNowCartId","buyNowCardRequestBody","create_braintree_paypal_button_strategy","BraintreePaypalCreditButtonStrategy","create_braintree_paypal_credit_button_strategy","BraintreeVisaCheckoutButtonStrategy","braintree_visa_checkout_button_strategy_awaiter","paymentSuccess","toVisaCheckoutAddress","alignItems","create_braintree_visa_checkout_button_strategy","getVenmoButtonStyle","WHITE","backgroundPosition","backgroundSize","backgroundImage","BLUE","backgroundRepeat","cursor","minHeight","minWidth","BraintreeVenmoButtonStrategy","cartButtonStyles","renderVenmoButton","isUnsupportedBrowserError","handleInitializationVenmoError","removeVenmoContainer","venmoButton","braintree_venmo_button_strategy_awaiter","buyBowCart","handlePostForm","create_braintree_venmo_button_strategy","GooglePayButtonStrategy","_getMethodOrThrow","_countryCode","google_pay_button_strategy_awaiter","_buyNowCart","_getBuyNowTransactionInfo","_getTransactionInfo","create_google_pay_braintree_button_strategy","create_google_pay_paypal_commerce_button_strategy","create_google_pay_bigcommerce_payments_button_strategy","create_google_pay_adyenv2_button_strategy","create_google_pay_adyenv3_button_strategy","create_google_pay_authorizenet_button_strategy","create_google_pay_checkoutcom_button_strategy","create_google_pay_cybersource_button_strategy","create_google_pay_orbital_button_strategy","create_google_pay_stripe_button_strategy","create_google_pay_worldpayaccess_button_strategy","create_google_pay_tdonlinemart_button_strategy","PayPalCommerceButtonStrategy","create_paypal_commerce_button_strategy","PayPalCommerceCreditButtonStrategy","create_paypal_commerce_credit_button_strategy","PayPalCommerceVenmoButtonStrategy","create_paypal_commerce_venmo_button_strategy","PaypalButtonStrategy","paypalExpressScriptLoader","paypalSDK","allowCredit","fundingCreditOption","allowedSources","disallowedSources","Button","funding","disallowed","getStyle","onAuthorize","RECT","RESPONSIVE","CheckoutButtonNotInitialized","paymentID","payerID","getPaymentData","payerId","payerInfo","payer_info","create_paypal_express_button_strategy","StripeLinkV2ButtonStrategy","stripe_link_v2_button_strategy_awaiter","create_stripe_link_v2_button_strategy","getUniqId","idPrefix","__WEBPACK_EXTERNAL_MODULE_lodash_uniqueId__","isTerminalCacheKeyMap","CacheKeyResolver","_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","CheckoutButtonErrorSelector","_checkoutButton","getInitializeButtonError","getDeinitializeButtonError","checkout_button_error_selector_decorate","CheckoutButtonStatusSelector","isInitializingButton","isDeinitializingButton","checkout_button_status_selector_decorate","createCheckoutButtonSelectors","checkout_button_error_selector","checkout_button_status_selector","CheckoutButtonInitializer","_buttonStrategyActionCreator","_state","initializeButton","containerIds","containers","setUniqueElementId","deinitializeButton","checkout_button_initializer_decorate","CheckoutButtonStrategyActionCreator","_registryV2","paymentMethodRequestParams","paymentMethodRequestOptions","payment_method_client_unavailable_error_PaymentMethodClientUnavailableError","paypal_sdk_PaypalButtonStyleLayoutOption","paypal_sdk_PaypalButtonStyleSizeOption","paypal_sdk_PaypalButtonStyleColorOption","paypal_sdk_PaypalButtonStyleLabelOption","paypal_sdk_PaypalButtonStyleShapeOption","EmbeddedCheckoutEventType","NotEmbeddableErrorType","EmbeddedContentEventType","paypal_script_loader_PaypalScriptLoader","paypal_button_strategy_PaypalButtonStrategy","_paypalScriptLoader","_host","_setupPayment","_tokenizePayment","createCheckoutButtonInitializer","checkoutButtonStrategyFactories","createCheckoutButtonStrategy","createCheckoutButtonStrategyRegistry","checkout_button_strategies_namespaceObject","checkout_button_initializer","PAYPALEXPRESS","createCheckoutButtonRegistry","InvalidLoginTokenError","NotEmbeddableError","UnknownError","IS_COOKIE_ALLOWED_KEY","LAST_ALLOW_COOKIE_ATTEMPT_KEY","EmbeddedCheckout","_iframeCreator","_messageListener","_messagePoster","_storage","_location","_isAttached","CheckoutComplete","CheckoutError","CheckoutLoaded","onFrameLoad","FrameLoaded","onSignOut","SignedOut","_configureStyles","_allowCookie","_attemptLogin","_retryAllowCookie","FrameError","iFrameResizer","StyleConfigured","lastAttempt","MissingContent","embedded_checkout_decorate","resizable_iframe_creator_ResizableIframeCreator","MissingContainer","allowPaymentRequest","contentId","embedCheckout","handleFrameLoadedEvent","hasAttribute","custom_error_isCustomError","IframeEmbeddedCheckoutMessenger","_untargetedMessagePoster","_messageHandlers","postComplete","_postMessage","postError","_transformError","postFrameError","untargeted","postFrameLoaded","postLoaded","postSignedOut","receiveStyles","_notifyMessageHandlers","iframe_embedded_checkout_messenger_decorate","NoopEmbeddedCheckoutMessenger","noop_embedded_checkout_messenger_decorate","createEmbeddedCheckoutMessenger","parentWindow","noop_embedded_checkout_messenger","iframe_embedded_checkout_messenger","DEFAULT_LOCALE","KEY_PREFIX","LanguageService","_logger","locales","_transformConfig","_locale","_locales","_translations","_formatters","mapKeys","_hasTranslations","translate","prefixedKey","__WEBPACK_EXTERNAL_MODULE_intl_messageformat_1c4020d9_IntlMessageFormat__","_escapeSpecialCharacters","ignoreTag","_transformData","_isFormatError","originalMessage","defaultLocale","defaultTranslations","_flattenObject","fallbackTranslations","__WEBPACK_EXTERNAL_MODULE_lodash_union__","fallbackLocale","parentKey","resultKey","language_service_decorate","createLanguageService","language_service","currency_service_CurrencyService","currency_currency_service_decorate","create_currency_service_createCurrencyService","currency_currency_service","isAnalyticsTrackerWindowGA","ga","sendGoogleAnalytics","nonInteraction","isPayloadSizeLimitReached","serializeAnalyticsEventPayload","acc","AnalyticStepId","ANALYTIC_STEPS","CUSTOMER","BILLING","AnalyticsStepTracker","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","getShopperCurrency","getPaymentMethodName","shipping_method","shippingMethodId","completedStepId","getStoreProfile","toShopperCurrency","getProducts","product_id","giftCertificateItems","itemAttributes","image_url","NoopStepTracker","createStepTracker","stepTrackerConfig","isBraintreeFastlaneWindow","BraintreeAnalyticTracker","_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","PayPalCommerceAnalyticTracker","_checkoutService","paypalHostWindow","_getPayPalEventsOrThrow","createPayPalCommerceAnalyticTracker","AnalyticStepType","StoredCardHostedFormService","createStoredCardHostedFormService","AnalyticStepOrder","BodlEmitterService","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","__WEBPACK_EXTERNAL_MODULE_lodash_flatten__","retail_price","retailPrice","NoopBodlService","createBodlService","isBodlEnabled"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"checkout-sdk.js","mappings":"k+DAAA,IAAAA,EACAC,EAGAC,EAAAC,SAJAH,EAIA,CAAqBI,cAAA,IAAAC,EAAA,eAHrBJ,EAAA,GAAaK,EAAAC,EAAAN,EAAAD,GAA6BC,WCD1CC,EAAAC,QAAAK,ICCAC,GAAA,GAGA,SAAAH,GAAAI,GAEA,IAAAC,EAAAF,GAAAC,GACA,QAAAE,IAAAD,EACA,OAAAA,EAAAR,QAGA,IAAAD,EAAAO,GAAAC,GAAA,CAGAP,QAAA,IAOA,OAHAU,GAAAH,GAAAR,EAAAA,EAAAC,QAAAG,IAGAJ,EAAAC,OACA,CCrBAG,GAAAC,EAAA,CAAAJ,EAAAW,KACA,QAAAC,KAAAD,EACAR,GAAAU,EAAAF,EAAAC,KAAAT,GAAAU,EAAAb,EAAAY,IACAE,OAAAC,eAAAf,EAAAY,EAAA,CAAyCI,YAAA,EAAAC,IAAAN,EAAAC,MCJzCT,GAAAU,EAAA,CAAAK,EAAAC,IAAAL,OAAAM,UAAAC,eAAAC,KAAAJ,EAAAC,GCCAhB,GAAAoB,EAAAvB,IACA,oBAAAwB,QAAAA,OAAAC,aACAX,OAAAC,eAAAf,EAAAwB,OAAAC,YAAA,CAAuDC,MAAA,WAEvDZ,OAAAC,eAAAf,EAAA,cAAgD0B,OAAA,+hMCFzC,MAAMC,GAAyB,iBAE/B,SAASC,GAAaC,GACzB,OAAOA,EAAMC,KAAKC,WAAWJ,GACjC,CAEe,SAASK,GAAyBC,SAC7C,MA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ACAyC,QAK+D,CACvE,CAAE1uC,GAAI,wBC/CG0iE,GAA2B,CACpC,mBAAoB,qBACpB,UAAW,QAOFC,GAA+B,CACxC,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,SC3mBW,SAASC,GACpBxX,GAEA,IAAKA,EACD,OAGJ,IAAID,EAEJ,GAAIC,EAAcj8C,SAAS,KAAM,CAC7B,MAAO0zD,EAAUj7C,GAAUwjC,EAAcngB,MAAM,KAE/CkgB,EAAS,GAAG0X,KAAYj7C,EAAOk7C,qBAE/B3X,EAAS,GAAGC,KAAiBA,EAAc0X,gBAG/C,OAAOH,GAA6BxzD,SAASg8C,GAAUA,OAAS3tD,CACpE,wSCPe,MAAMulE,GAGjB,WAAAxhE,CAAoBsf,GAAApf,KAAAof,aAAAA,EAChBpf,KAAKgc,OAASA,MAClB,CAEM,oBAAA2zB,CACFphB,EACA0E,EACAnE,EACA66B,4CAEA,IAAK3pD,KAAKgc,OAAOk2B,kBAAmB,CAChC,MAAMr0C,EAASmC,KAAK6vC,kCAChBthB,EACA0E,EACAnE,EACA66B,GAKJ,SAFM3pD,KAAK+lC,cAAcloC,IAEpBmC,KAAKgc,OAAOk2B,kBACb,MAAM,IAAIze,GAIlB,OAAOz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B,CAAU77C,GACN,OAAOpB,KAAKg7B,MAAM55B,EAASpB,KAAAk9C,IAAA,GAAM7uE,KAAKwrD,gBAC1C,ECLG,MAAMsjB,GAAqC,CAC9C,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KAC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Y3lK,EAAKi4G,UACjBqI,SAAUtgH,EAAKuzD,eACfqyG,cAAe5lK,EAAK6lK,aACpBC,WAAY9lK,EAAKunB,MACjBthB,SAAUD,EACV+/J,gBA9BsB1lI,EA8BWrgC,EA7B7B5V,MAAMC,QAAQg2C,EAASw0C,eAChBx0C,EAASw0C,cACTzqF,MAAMC,QAAQg2C,EAAS0yB,YACvBizG,EAAQ3lI,EAAS0yB,YAAY5hF,IAAI,EAAGhB,UAAWA,GAGnD,IAwBP81L,aAAcjmK,EAAKkmK,aA/BE,IAAC7lI,OAmCyBg/H,GAAsBluL,IACxE6uB,GAAS7wB,OAAA8B,OAAA9B,OAAA8B,OAAA,GACH+uB,GAAI,CACPo/J,WAAYttL,OAAOkuB,EAAKo/J,cAGpC,CAEQ,iBAAAgF,CAAkBn0G,GACtB,OAAOl9E,KAAKuqL,gBAAgBrtG,EAChC,EChSW,MAAMk2G,GACjB,aAAA7C,GAAuB,CAEvB,cAAAG,GAAwB,CAExB,aAAAS,GAAuB,CAEvB,kBAAAI,GAA4B,CAE5B,sBAAAE,GAAgC,CAEhC,yBAAAC,GAAmC,CAEnC,6BAAA3E,GAAuC,CAEvC,mBAAA4E,GAA6B,CAE7B,qBAAAvE,GAA+B,CAE/B,cAAA2E,GAAwB,CAExB,eAAAC,GAAyB,CAEzB,eAAA9E,GAAyB,CAEzB,YAAA+E,GAAsB,ECNX,SAASoB,GACpBjrL,GAEA,OCtBG,SAAuB4T,GAC1B,MAAO,eAAgBA,CAC3B,CDoBQs3K,CAAct3K,QACP,IAAIk0K,GAAmB9nL,EAAW4T,OAAOm0K,WAAWjvL,UAGxD,IAAIkyL,EACf","sources":["webpack://@bigcommerce/checkout-sdk/external module \"iframe-resizer\"","webpack://@bigcommerce/checkout-sdk/external module \"iframe-resizer/js/iframeResizer.contentWindow\"","webpack://@bigcommerce/checkout-sdk/webpack/bootstrap","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/./packages/core/src/form/map-extra-field-to-form-field.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/throw-error-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/b2b-token/b2b-token-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/b2b-token/b2b-token-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/sdk-version-headers.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/b2b-token/b2b-token-request-sender.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/billing/errors/unable-to-continue-as-guest-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/content-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/empty-cart-error.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/http-request/experiment-aware-request-sender.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/./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-actions.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/coupon/gift-certificate-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/cart/cart-source.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-actions.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-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/core/src/spam-protection/is-spam-protection-succeeded-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-hydrate-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/payment-integration/register-integrations.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/form/form-fields-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/spam-protection-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/spam-protection/errors/spam-protection-challenge-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-failed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/not-initialized-error.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/spam-protection/spam-protection-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/mutation-observer.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/spam-protection/spam-protection-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/default/default-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/parse-url.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/extension-not-found-error.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/extension/create-extension-event-poster.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/cancellable-promise/cancellable-promise.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/errors/unexpected-detachment-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-internal-commands.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/detachment-observer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-resizer.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-iframe.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/create-extension-web-worker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/bind-decorator/bind-decorator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-commands.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-queries.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/worker/worker-event-listener.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/worker/worker-event-poster.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/unsupported-extension-command-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/unsupported-extension-query-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/worker-extension-messenger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/append-www.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-listener.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-messenger.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/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/missing-data-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/not-initialized-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/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/invalid-argument-error.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/utility/src/is-experiment-enabled/is-experiment-enabled.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk-verison.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk-version-manager.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.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk-scripts-integrity.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/isManageableBraintreeSDKVersion.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-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-session-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/is-apple-pay-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/is-apple-pay-sdk-window.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/buy-now-cart-creation-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/internal-api-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/content-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/sdk-version-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/create-bigcommerce-payments-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/checkout-buttons/default-checkout-button-height.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/bigcommerce-payments-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/create-bigcommerce-payments-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/bigcommerce-payments-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/paypal-sdk-helper.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/create-bigcommerce-payments-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/storage/src/cookie-storage.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/bigcommerce-payments-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/create-bigcommerce-payments-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/get-fastlane-styles.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-fastlane/bigcommerce-payments-fastlane-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-fastlane/create-bigcommerce-payments-fastlane-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/bigcommerce-payments-paylater-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/create-bigcommerce-payments-paylater-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/bigcommerce-payments-venmo-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/create-bigcommerce-payments-venmo-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/payment-method-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt.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-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/create-bolt-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-argument-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-invalid-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/load-paypal-sdk-once.ts","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/braintree-utils/src/utils/is-credit-card-instrument-like.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/./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/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/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/utility/src/is-web-view/is-web-view.ts","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/is-react-native-window/is-react-native-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/is-opera-window/is-opera-window.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/google-pay-payment-initialize-options.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/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/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/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/stripe-utils/src/stripe.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/stripe-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/stripe-upe/stripe-upe-constants.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/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/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/paypal-utils/src/paypal-commerce-constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/utils/transform-locale-to-paypal-format.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/paypal-commerce-sdk.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-gateway.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/google-pay-integration/src/google-pay-bigcommerce-payments/google-pay-bigcommerce-payments-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-bigcommerce-payments/create-google-pay-bigcommerce-payments-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/paypal-utils/src/paypal-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/paypal-sdk-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/create-paypal-sdk-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/paypal-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/paypal-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/create-paypal-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/paypal-button-creation-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-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-integration-service.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-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-utils/src/paypal-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/create-paypal-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-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-utils/src/is-stripe-payment-method-like.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/stripe-upe-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/create-stripe-upe-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/stripe-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/is-stripe-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/ui/src/loading-indicator/loading-indicator.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/utility/amount-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/stripe-link-v2-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/create-stripe-link-v2-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/order-finalization-not-required-error.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/adyen-utils/src/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-utils/src/adyenv2/adyenv2-script-loader.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/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.ts","webpack://@bigcommerce/checkout-sdk/./packages/affirm-integration/src/affirm-payment-strategy.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/bigcommerce-payments-integration/src/bigcommerce-payments-constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/get-paypal-messages-styles-from-bnpl-config.ts","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/is-base-instrument/is-base-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/bigcommerce-payments-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-bigcommerce-payments-provider-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/create-bigcommerce-payments-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-paypal-fastlane-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-fastlane/bigcommerce-payments-fastlane-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-bigcommerce-fastlane-request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-fastlane/create-bigcommerce-payments-fastlane-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/bigcommerce-payments-paylater-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/create-bigcommerce-payments-paylater-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/timeout-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-ratepay/bigcommerce-payments-ratepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-ratepay/create-bigcommerce-payments-ratepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/hosted-form/hosted-field-type.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/bigcommerce-payments-integration/src/bigcommerce-payments-credit-cards/bigcommerce-payments-credit-cards-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-bigcommerce-payments-fastlane-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-credit-cards/create-bigcommerce-payments-credit-cards-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-alternative-methods/bigcommerce-payments-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-alternative-methods/create-bigcommerce-payments-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-redirect-alternative-methods/bigcomemrce-payments-redirect-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-utils/src/utils/is-redirect-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-redirect-alternative-methods/create-bigcommerce-payments-redirect-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/bigcommerce-payments-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/create-bigcommerce-payments-venmo-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/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/types.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/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/braintree-utils/src/braintree-messages.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/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-request-sender.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/braintree-integration/src/braintree-visa-checkout/braintree-visa-checkout-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-visa-checkout/create-braintree-visa-checkout-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-venmo/braintree-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-venmo/create-braintree-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-credit-card/braintree-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-payment-request-3ds-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-form-fields-map.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-hosted-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-hosted-form/braintree-hosted-form.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-supported-card-brand.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-credit-card/create-braintree-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/credit-card-integration/src/credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/cba-mpgs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/is-cba-mpgs-payment-method-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/cba-mpgs.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/cba-mpgs-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/cba-mpgs-integration/src/create-cba-mpgs-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/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/google-pay-bigcommerce-payments/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-bigcommerce-payments/google-pay-bigcommerce-payments-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-bigcommerce-payments/create-google-pay-bigcommerce-payments-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/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-utils/src/utils/get-paypal-messages-styles-from-bnpl-config.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/paypal-commerce-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/utils/is-redirect-action-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-utils/src/utils/is-paypal-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-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-constants.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/paypal-commerce-integration/src/paypal-commerce-credit-card/paypal-commerce-credit-cards-payment-strategy.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/create-paypal-commerce-credit-cards-payment-strategy.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-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-utils/src/utils/is-paypal-fastlane-request-error.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-express-integration/src/paypal-express-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/paypal-express-payment-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-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/external-integration/src/external-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/external-integration/src/is-additional-action.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-utils/src/stripe-supported-locales.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-utils/src/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-utils/src/is-stripe-payment-event.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/stripe-ocs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/create-stripe-ocs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-cs/stripe-cs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-cs/create-stripe-cs-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/worldpayaccess-integration/src/worldpayaccess-open-banking-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/worldpayaccess-integration/src/create-worldpayaccess-open-banking-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/order/order-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/cart/errors/cart-consistency-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/cart-stock-positions-changed-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/errors/missing-shipping-method-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/errors/invalid-shipping-address-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/create-payment-client.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-request-sender.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-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-widget-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-action-creator.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/storage/browser-storage.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/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/spam-protection/payment-human-verification-handler.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.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-actions.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/payment/payment-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-request-sender.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/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/promotion/map-to-discount-notifications.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/generated/checkout-button-method-type.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/./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/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/payment-status-types.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/converge/converge-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-method-cancelled-error.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/redirect/redirect.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/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-sub-strategy-type.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-provider-customer/payment-provider-customer-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-payment-resumer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-provider-customer/payment-provider-customer-actions-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-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-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/store-credit/store-credit-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/subscription/subscriptions-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/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/instrument/instrument-actions.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/payment/instrument/instrument-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/date-time/add-minutes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/date-time/is-future.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-actions.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-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-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument.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/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/paypal-utils/src/utils/is-paypal-accelerated-checkout-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-actions.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-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/./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/./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/object-set.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/b2b-token/b2b-token-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/b2b-token/b2b-token-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/replace.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/cart/cart-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-actions.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/b2b-token/b2b-token-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-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/coupon/coupon-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-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/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/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/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/store-credit/store-credit-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-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/checkout/create-action-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/create-request-error-factory.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/payment/create-payment-strategy-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/create-customer-strategy-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-selectors.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/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/ppsdk/create-ppsdk-sub-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/create-shipping-strategy-registry.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/bigcommerce-payments-integration/src/bigcommerce-payments/bigcommerce-payments-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments/create-bigcommerce-payments-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/bigcommerce-payments-paylater-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-paylater/create-bigcommerce-payments-paylater-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/bigcommerce-payments-venmo-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bigcommerce-payments-integration/src/bigcommerce-payments-venmo/create-bigcommerce-payments-venmo-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/get-valid-button-style.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/braintree-paypal-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/create-braintree-paypal-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal-credit/braintree-paypal-credit-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal-credit/create-braintree-paypal-credit-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/google-pay-bigcommerce-payments/create-google-pay-bigcommerce-payments-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-express-integration/src/paypal-express-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/create-paypal-express-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/stripe-link-v2-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-ocs/create-stripe-link-v2-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/set-unique-element-id.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/checkout-buttons/checkout-button-strategy-action-creator.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/paypal/paypal-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/embedded-checkout-events.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/payment/strategies/paypal/paypal-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/paypal/paypal-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/errors/invalid-login-token-error.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/./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/bodl/analytics-steps.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/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":["var x = (y) => {\n\tvar x = {}; __webpack_require__.d(x, y); return x\n} \nvar y = (x) => (() => (x))\nmodule.exports = x({ [\"iframeResizer\"]: () => (__WEBPACK_EXTERNAL_MODULE_iframe_resizer_1512d797__.iframeResizer) });","module.exports = __WEBPACK_EXTERNAL_MODULE_iframe_resizer_js_iframeResizer_contentWindow_a6cfc03f__;","// 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","// 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};","import { ExtraField, ExtraFieldType } from './extra-field';\nimport FormField, { FormFieldFieldType, FormFieldType } from './form-field';\n\nexport const B2B_EXTRA_FIELD_PREFIX = 'b2bExtraField_';\n\nexport function isExtraField(field: FormField): boolean {\n return field.name.startsWith(B2B_EXTRA_FIELD_PREFIX);\n}\n\nexport default function mapExtraFieldToFormField(extraField: ExtraField): FormField {\n const { fieldType, type } = getFieldTypeInfo(extraField.type);\n\n let options: FormField['options'];\n\n if (extraField.config.numberOfRows) {\n options = { rows: extraField.config.numberOfRows };\n }\n\n if (extraField.config.options?.length) {\n options = {\n ...options,\n items: extraField.config.options.map((val) => ({\n value: val,\n label: val,\n })),\n };\n }\n\n return {\n id: `${B2B_EXTRA_FIELD_PREFIX}${extraField.id}`,\n name: `${B2B_EXTRA_FIELD_PREFIX}${extraField.id}`,\n custom: false,\n label: extraField.name,\n hidden: !extraField.visibleToStorefront,\n required: extraField.isRequired,\n default:\n extraField.config.defaultValue != null\n ? String(extraField.config.defaultValue)\n : undefined,\n fieldType,\n type,\n maxLength: extraField.config.maxLength,\n max: extraField.config.maxValue,\n options,\n };\n}\n\nfunction getFieldTypeInfo(extraFieldType: ExtraFieldType): {\n fieldType: FormFieldFieldType;\n type: FormFieldType;\n} {\n switch (extraFieldType) {\n case 'multiline_text':\n return { fieldType: 'multiline', type: 'string' };\n\n case 'number':\n return { fieldType: 'text', type: 'integer' };\n\n case 'dropdown':\n return { fieldType: 'dropdown', type: 'array' };\n\n case 'text':\n default:\n return { fieldType: 'text', type: 'string' };\n }\n}\n","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 { Action } from '@bigcommerce/data-store';\n\nimport { B2BToken } from './b2b-token-state';\n\nexport enum B2BTokenActionType {\n LoadB2BTokenRequested = 'LOAD_B2B_TOKEN_REQUESTED',\n LoadB2BTokenSucceeded = 'LOAD_B2B_TOKEN_SUCCEEDED',\n LoadB2BTokenFailed = 'LOAD_B2B_TOKEN_FAILED',\n}\n\nexport type LoadB2BTokenAction =\n | LoadB2BTokenRequestedAction\n | LoadB2BTokenSucceededAction\n | LoadB2BTokenFailedAction;\n\nexport interface LoadB2BTokenRequestedAction extends Action {\n type: B2BTokenActionType.LoadB2BTokenRequested;\n}\n\nexport interface LoadB2BTokenSucceededAction extends Action {\n type: B2BTokenActionType.LoadB2BTokenSucceeded;\n}\n\nexport interface LoadB2BTokenFailedAction extends Action {\n type: B2BTokenActionType.LoadB2BTokenFailed;\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 { RequestOptions } from '../common/http-request';\n\nimport { B2BTokenActionType, LoadB2BTokenAction } from './b2b-token-actions';\nimport B2BTokenRequestSender from './b2b-token-request-sender';\n\nexport default class B2BTokenActionCreator {\n constructor(private _requestSender: B2BTokenRequestSender) {}\n\n loadB2BToken(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const storeConfig = state.config.getStoreConfigOrThrow();\n const { storeHash } = storeConfig.storeProfile;\n const { baseUrl: b2bBaseUrl = '', clientId: b2bClientId = '' } =\n storeConfig.b2bApiSettings ?? {};\n const { id: customerId } = state.customer.getCustomerOrThrow();\n const { channelId } = state.checkout.getCheckoutOrThrow();\n\n return concat(\n of(createAction(B2BTokenActionType.LoadB2BTokenRequested)),\n defer(async () => {\n const { body } = await this._requestSender.getB2BToken(\n b2bClientId,\n customerId,\n storeHash,\n channelId,\n b2bBaseUrl,\n options,\n );\n\n return createAction(B2BTokenActionType.LoadB2BTokenSucceeded, {\n token: body.data.token,\n });\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(B2BTokenActionType.LoadB2BTokenFailed, error),\n ),\n );\n };\n }\n}\n","export const SDK_VERSION_HEADERS = { 'X-Checkout-SDK-Version': LIBRARY_VERSION };\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 { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nexport interface B2BTokenResponseBody {\n code: number;\n data: {\n token: string;\n };\n}\n\nexport default class B2BTokenRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n async getB2BToken(\n appClientId: string,\n customerId: number,\n storeHash: string,\n channelId: number,\n b2bBaseUrl: string,\n options?: RequestOptions,\n ): Promise> {\n const { body: jwtBody } = await this._requestSender.get<{ token: string }>(\n '/customer/current.jwt',\n {\n timeout: options?.timeout,\n params: { app_client_id: appClientId },\n headers: SDK_VERSION_HEADERS,\n },\n );\n\n return this._requestSender.post(`${b2bBaseUrl}/api/v2/login`, {\n timeout: options?.timeout,\n credentials: false,\n headers: { 'Content-Type': 'application/json' },\n body: {\n bcToken: jwtBody.token,\n customerId,\n storeHash,\n channelId,\n },\n });\n }\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 '../../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","enum ContentType {\n Json = 'application/json',\n JsonV1 = 'application/vnd.bc.v1+json',\n}\n\nexport default ContentType;\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\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 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\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 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 hasBillingAddress: boolean,\n options?: RequestOptions,\n ): Promise> {\n if (!hasBillingAddress) {\n return this._requestSender.createAddress(checkoutId, address, options);\n }\n\n return this._requestSender.updateAddress(checkoutId, address, options);\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error is thrown when cart is removed or empty.\n */\nexport default class EmptyCartError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Your checkout could not be processed because your cart is empty. Please add items to your cart and try again.',\n );\n\n this.name = 'EmptyCartError';\n this.type = 'empty_cart';\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { AddressRequestBody } from '../address';\nimport { EmptyCartError } from '../cart/errors';\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.physicalItems.stockPosition',\n 'cart.lineItems.digitalItems.options',\n 'cart.lineItems.digitalItems.stockPosition',\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\n .post(url, {\n body: address,\n params: DEFAULT_PARAMS,\n headers,\n timeout,\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .put(url, { params: DEFAULT_PARAMS, body, headers, timeout })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\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","import { RequestOptions, RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { StoreConfig } from '../../config';\n\nexport interface ExperimentConfig {\n getBasePath: () => string | undefined;\n getFeatures: () => StoreConfig['checkoutSettings']['features'];\n}\n\nexport default class ExperimentAwareRequestSender {\n constructor(private _requestSender: RequestSender, private _config: ExperimentConfig) {}\n\n sendRequest(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.sendRequest(url, options);\n }\n\n get(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.get(url, options);\n }\n\n post(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.post(this._prefixed(url), options);\n }\n\n put(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.put(this._prefixed(url), options);\n }\n\n patch(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.patch(this._prefixed(url), options);\n }\n\n delete(url: string, options?: RequestOptions): Promise> {\n return this._requestSender.delete(this._prefixed(url), options);\n }\n\n private _prefixed(url: string): string {\n const basePath = this._config.getBasePath();\n\n const isExperimentEnabled =\n this._config.getFeatures()['CHECKOUT-9950.update_sf_checkout_url_for_subfolder'];\n\n if (\n !isExperimentEnabled ||\n !basePath ||\n basePath.endsWith('/checkout') ||\n /^https?:\\/\\//.test(url)\n ) {\n return url;\n }\n\n return `${basePath}${url}`;\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","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 { 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 { 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 | object;\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.physicalItems.stockPosition',\n 'cart.lineItems.digitalItems.options',\n 'cart.lineItems.digitalItems.stockPosition',\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 { 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","export enum CartSource {\n BuyNow = 'BUY_NOW',\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 { 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 { EmptyCartError } from '../cart/errors';\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\n .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 .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes([\n ...CHECKOUT_DEFAULT_INCLUDES,\n CheckoutIncludes.AvailableShippingOptions,\n ]),\n },\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\n }\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 { EmptyCartError } from '../cart/errors';\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\n .post(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n body: { giftCertificateCode },\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\n }\n}\n","import ResolvableModule from './resolvable-module';\n\nexport default function isResolvableModule(\n module: TModule,\n): module is ResolvableModule {\n return module && '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: (\n token: string,\n registeredTokens: string[],\n exactMatch?: boolean,\n ) => 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 getFactory(token: string, exactMatch?: boolean): Factory | undefined {\n const resolvedToken = this._tokenResolver(token, Object.keys(this._factories), exactMatch);\n const factory = resolvedToken ? this._factories[resolvedToken] : undefined;\n\n return factory;\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 factory = this.getFactory(token);\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 defaultToken: this._encodeToken({ default: true } as unknown as TToken),\n useFallback: this._useFallback,\n });\n }\n\n get(resolveId: TToken): TType {\n return this._registry.get(this._encodeToken(resolveId));\n }\n\n getFactory(resolveId: TToken, exactMatch?: boolean): Factory | undefined {\n try {\n return this._registry.getFactory(this._encodeToken(resolveId), exactMatch);\n } catch (error) {\n return undefined;\n }\n }\n\n getUseFallback(): boolean {\n return this._useFallback;\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(\n token: string,\n registeredTokens: string[],\n exactMatch?: boolean,\n ): string | undefined {\n const query = this._decodeToken(token);\n\n const results: Array<{\n token: string;\n matches: number;\n default: boolean;\n totalKeys: number;\n }> = [];\n\n registeredTokens.forEach((registeredToken) => {\n const resolverId = this._decodeToken(registeredToken);\n\n const result = {\n token: registeredToken,\n matches: 0,\n default: false,\n totalKeys: Object.keys(resolverId).length,\n };\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 queryKeyCount = Object.keys(query).length;\n\n if (exactMatch) {\n const exactResult = matchedResults.find(\n (result) => result.matches === queryKeyCount && result.matches === result.totalKeys,\n );\n\n if (!exactResult) {\n throw new Error(\n `Unable to resolve to a registered token with the provided token for ${JSON.stringify(\n query,\n )} with exact match.`,\n );\n }\n\n return exactResult.token;\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(\n `Unable to resolve to a registered token with the provided token for ${JSON.stringify(\n query,\n )}.`,\n );\n }\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\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 { 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 { Action } from '@bigcommerce/data-store';\n\nimport CheckoutInitialState from './checkout-initial-state';\n\nexport enum CheckoutHydrateActionType {\n HydrateInitialState = 'HYDRATE_INITIAL_STATE',\n}\n\nexport interface CheckoutHydrateAction extends Action {\n type: CheckoutHydrateActionType.HydrateInitialState;\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 { CartSource } from '@bigcommerce/checkout-sdk/payment-integration-api';\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 const checkout = store.getState().checkout.getCheckoutOrThrow();\n const cartId = checkout.cart.source === CartSource.BuyNow ? checkout.id : undefined;\n\n return concat(\n of(createAction(CustomerActionType.SignInCustomerRequested)),\n from(\n this._customerRequestSender.signInCustomer({ ...credentials, cartId }, options),\n ).pipe(\n switchMap(({ body }) => {\n if (body.data.persistentCartRetrievalInformation) {\n return concat(\n this._checkoutActionCreator.loadCheckout(\n body.data.persistentCartRetrievalInformation.id,\n options,\n )(store),\n of(\n createAction(\n CustomerActionType.SignInCustomerSucceeded,\n body.data,\n ),\n ),\n );\n }\n\n return 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\n signOutCustomer(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const checkout = store.getState().checkout.getCheckoutOrThrow();\n const cartId = checkout.cart.source === CartSource.BuyNow ? checkout.id : undefined;\n\n return concat(\n of(createAction(CustomerActionType.SignOutCustomerRequested)),\n from(this._customerRequestSender.signOutCustomer(options, cartId)).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}\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(\n { timeout }: RequestOptions = {},\n cartId?: string,\n ): Promise> {\n const url = '/internalapi/v1/checkout/customer';\n\n return this._requestSender.delete(url, {\n timeout,\n headers: SDK_VERSION_HEADERS,\n ...(cartId && { body: { cartId } }),\n });\n }\n}\n","import {\n isResolvableModule,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\n\nexport type StrategyFactory = (\n paymentIntegrationService: PaymentIntegrationService,\n) => TStrategy;\n\nexport function registerIntegrations(\n registry: ResolveIdRegistry,\n integrations: Array>,\n paymentIntegrationService: PaymentIntegrationService,\n): void {\n integrations.forEach((factory) => {\n if (!isResolvableModule, TResolveId>(factory)) {\n return;\n }\n\n factory.resolveIds.forEach((resolveId) => {\n if (registry.getFactory(resolveId, true)) {\n return;\n }\n\n registry.register(resolveId, () => factory(paymentIntegrationService));\n });\n });\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport {\n CustomerStrategy as CustomerStrategyV2,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { registerIntegrations } from '../payment-integration';\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 private _paymentIntegrationService: PaymentIntegrationService,\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 registerIntegrations(\n this._strategyRegistryV2,\n options?.integrations ?? [],\n this._paymentIntegrationService,\n );\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 { EmptyCartError } from '../cart/errors';\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\n .put(url, {\n params: {\n include: joinOrMergeIncludes(CHECKOUT_DEFAULT_INCLUDES, include),\n },\n body,\n headers,\n timeout,\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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 { Action, 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 } from '../config';\nimport { FormFieldsActionCreator } from '../form';\n\nimport Checkout, { CheckoutRequestBody } from './checkout';\nimport { CheckoutActionType, LoadCheckoutAction, UpdateCheckoutAction } from './checkout-actions';\nimport { CheckoutHydrateActionType } from './checkout-hydrate-actions';\nimport CheckoutInitialState from './checkout-initial-state';\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 () => {\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._transformCustomerAddresses(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._transformCustomerAddresses(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 hydrateInitialState(state: CheckoutInitialState): Action {\n return {\n type: CheckoutHydrateActionType.HydrateInitialState,\n payload: state,\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 { 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 } 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 { 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 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 './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 { 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 { 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 return concat(\n of(createAction(SpamProtectionActionType.InitializeRequested, undefined)),\n defer(async () => {\n const spamProtectionElementId = options\n ? options.containerId\n : 'spamProtectionContainer';\n\n const element = document.getElementById(spamProtectionElementId);\n\n if (element) {\n this._googleRecaptcha.reset(spamProtectionElementId);\n }\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\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","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 { 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\n .load()\n .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 .catch((err) => {\n throw err;\n });\n }\n\n reset(containerId: string): void {\n const element = document.getElementById(containerId);\n\n element?.remove();\n this._recaptcha?.reset(this._widgetId);\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 { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { EmptyCartError } from '../cart/errors';\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\n .post(url, { body: { token }, headers, timeout })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\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","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 { 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 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 { 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","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 { 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 { 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 { 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","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 { 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","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 { createExtensionWebWorker } from './create-extension-web-worker';\nimport { ExtensionNotFoundError } from './errors';\nimport { ExtensionRegion, ExtensionType } from './extension';\nimport { ExtensionAction, ExtensionActionType } from './extension-actions';\nimport { ExtensionIframe } from './extension-iframe';\nimport { ExtensionRequestSender } from './extension-request-sender';\nimport { WorkerExtensionMessenger } from './worker-extension-messenger';\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 workerExtensionMessenger: WorkerExtensionMessenger,\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 } = state.config.getStoreConfigOrThrow();\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 if (extension.type === ExtensionType.Worker) {\n const worker = createExtensionWebWorker(extension.url);\n\n workerExtensionMessenger.add(extension.id, worker);\n } else {\n const iframe = new ExtensionIframe(container, extension, {\n cartId,\n parentOrigin: parseUrl(checkoutLink).origin,\n });\n\n await iframe.attach();\n }\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","export function createExtensionWebWorker(url: string): Worker {\n if (!window.Worker) {\n throw new Error(\n `Unable to load the extension's web worker: your browser does not support Web Workers.`,\n );\n }\n\n try {\n const blob = URL.createObjectURL(\n new Blob(\n [\n `importScripts=((i)=>(...a)=>i(...a.map((u)=>''+new URL(u,\"${url}\"))))(importScripts);importScripts(\"${url}\")`,\n ],\n { type: 'text/javascript' },\n ),\n );\n\n return new Worker(blob);\n } catch (error) {\n throw new Error(`Unable to load the extension's web worker`);\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","/**\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","export type ExtensionCommand =\n | ReloadCheckoutCommand\n | ShowLoadingIndicatorCommand\n | SetIframeStyleCommand\n | ReRenderShippingForm\n | ReRenderShippingStep;\n\nexport enum ExtensionCommandType {\n ReloadCheckout = 'EXTENSION:RELOAD_CHECKOUT',\n ShowLoadingIndicator = 'EXTENSION:SHOW_LOADING_INDICATOR',\n SetIframeStyle = 'EXTENSION:SET_IFRAME_STYLE',\n ReRenderShippingForm = 'EXTENSION:RE_RENDER_SHIPPING_FORM',\n ReRenderShippingStep = 'EXTENSION:RE_RENDER_SHIPPING_STEP',\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 ReRenderShippingForm {\n type: ExtensionCommandType.ReRenderShippingForm;\n}\n\nexport interface ReRenderShippingStep {\n type: ExtensionCommandType.ReRenderShippingStep;\n}\nexport interface ExtensionCommandMap {\n [ExtensionCommandType.ReloadCheckout]: ReloadCheckoutCommand;\n [ExtensionCommandType.ShowLoadingIndicator]: ShowLoadingIndicatorCommand;\n [ExtensionCommandType.SetIframeStyle]: SetIframeStyleCommand;\n [ExtensionCommandType.ReRenderShippingForm]: ReRenderShippingForm;\n [ExtensionCommandType.ReRenderShippingStep]: ReRenderShippingStep;\n}\n","export type ExtensionQuery = GetConsignmentsQuery;\n\nexport enum ExtensionQueryType {\n GetConsignments = 'EXTENSION:GET_CONSIGNMENTS',\n}\n\nexport interface GetConsignmentsQuery {\n type: ExtensionQueryType.GetConsignments;\n payload?: {\n useCache?: boolean;\n };\n}\n\nexport interface ExtensionQueryMap {\n [ExtensionQueryType.GetConsignments]: GetConsignmentsQuery;\n}\n","import { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { WorkerEventListeners, WorkerEventMap } from './WorkerEvent';\n\nexport class WorkerEventListener<\n TEventMap extends WorkerEventMap,\n TContext = undefined,\n> {\n private _isListening: boolean;\n private _listeners: WorkerEventListeners;\n\n constructor(private _worker: Worker) {\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 this._worker.addEventListener('message', this._handleMessage);\n }\n\n stopListen(): void {\n if (!this._isListening) {\n return;\n }\n\n this._isListening = false;\n this._worker.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 const { context, ...event } = messageEvent.data;\n\n this.trigger(event, context);\n }\n}\n","export class WorkerEventPoster {\n constructor(private _worker: Worker, private _context: TContext) {}\n\n post(event: TEvent): void {\n if (!this._worker) {\n throw new Error(\n 'WorkerPoster: Worker is not initialized or creation failed. Cannot post message.',\n );\n }\n\n this._worker.postMessage({ ...event, context: this._context });\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 { StandardError } from '../../common/error/errors';\n\nexport class UnsupportedExtensionQueryError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unable to proceed due to unsupported extension query.');\n\n this.name = 'UnsupportedExtensionQueryError';\n this.type = 'unsupported_extension_query_error';\n }\n}\n","import { WorkerEventListener, WorkerEventPoster } from '../common/worker';\n\nimport {\n ExtensionNotFoundError,\n UnsupportedExtensionCommandError,\n UnsupportedExtensionQueryError,\n} from './errors';\nimport { ExtensionCommandMap, ExtensionCommandType } from './extension-commands';\nimport { ExtensionCommandOrQueryContext, ExtensionMessage } from './extension-message';\nimport { ExtensionQueryMap, ExtensionQueryType } from './extension-queries';\n\nexport class WorkerExtensionMessenger {\n constructor(\n private _workers: { [extensionId: string]: Worker } = {},\n private _commandListeners: {\n [extensionId: string]: WorkerEventListener;\n } = {},\n private _queryListeners: {\n [extensionId: string]: WorkerEventListener;\n } = {},\n ) {}\n\n add(extensionId: string, worker: Worker): void {\n this._workers[extensionId] = worker;\n }\n\n listenForCommand(\n extensionId: string,\n command: T,\n commandHandler: (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => Promise | void,\n ): () => void {\n const worker = this._getWorkerById(extensionId);\n\n if (!this._commandListeners[extensionId]) {\n this._commandListeners[extensionId] = new WorkerEventListener(worker);\n }\n\n const listener = this._commandListeners[extensionId];\n\n listener.listen();\n\n const validCommandType = this._validateCommand(command);\n\n const commandHandlerProxy = (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandOrQueryContext,\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 listenForQuery(\n extensionId: string,\n query: T,\n queryHandler: (\n query: ExtensionQueryMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => Promise | void,\n ): () => void {\n const worker = this._getWorkerById(extensionId);\n\n if (!this._queryListeners[extensionId]) {\n this._queryListeners[extensionId] = new WorkerEventListener(worker);\n }\n\n const listener = this._queryListeners[extensionId];\n\n listener.listen();\n\n const validQueryType = this._validateQuery(query);\n\n const queryHandlerProxy = (\n query: ExtensionQueryMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => {\n if (context?.extensionId === extensionId) {\n queryHandler(query, context);\n }\n };\n\n listener.addListener(validQueryType, queryHandlerProxy);\n\n return () => {\n listener.removeListener(validQueryType, queryHandlerProxy);\n };\n }\n\n stopListen(extensionId: string): void {\n if (this._commandListeners[extensionId]) {\n this._commandListeners[extensionId].stopListen();\n }\n\n if (this._queryListeners[extensionId]) {\n this._queryListeners[extensionId].stopListen();\n }\n }\n\n post(extensionId: string, message: ExtensionMessage): void {\n if (!this._workers[extensionId]) {\n throw new Error(`Worker with extensionId ${extensionId} not found`);\n }\n\n const workerPoster = new WorkerEventPoster(this._workers[extensionId], extensionId);\n\n workerPoster.post(message);\n }\n\n clearCacheById(extensionId: string): void {\n delete this._workers[extensionId];\n }\n\n private _getWorkerById(extensionId: string): Worker {\n const worker = this._workers[extensionId];\n\n if (!worker) {\n throw new ExtensionNotFoundError(`Worker with extensionId ${extensionId} not found`);\n }\n\n return worker;\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 private _validateQuery(query: T): T {\n if (Object.values(ExtensionQueryType).includes(query)) {\n return query;\n }\n\n throw new UnsupportedExtensionQueryError();\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 { 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 { 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\nexport type EventListeners = {\n [key in keyof TEventMap]?: Array<(event: TEventMap[key], context?: TContext) => void>;\n};\n","import { ReadableCheckoutStore } from '../checkout';\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\n\nimport { createExtensionEventPoster } from './create-extension-event-poster';\nimport {\n ExtensionNotFoundError,\n UnsupportedExtensionCommandError,\n UnsupportedExtensionQueryError,\n} from './errors';\nimport { Extension, ExtensionType } from './extension';\nimport { ExtensionCommandMap, ExtensionCommandType } from './extension-commands';\nimport { ExtensionCommandOrQueryContext, ExtensionMessage } from './extension-message';\nimport { ExtensionQueryMap, ExtensionQueryType } from './extension-queries';\nimport { WorkerExtensionMessenger } from './worker-extension-messenger';\n\nexport class ExtensionMessenger {\n private _extensions: Extension[] | undefined;\n\n constructor(\n private _store: ReadableCheckoutStore,\n private _workerExtensionMessenger: WorkerExtensionMessenger,\n private _commandListeners: {\n [extensionId: string]: IframeEventListener;\n } = {},\n private _queryListeners: {\n [extensionId: string]: IframeEventListener;\n } = {},\n private _posters: { [extensionId: string]: IframeEventPoster } = {},\n ) {}\n\n clearCacheByRegion(region: string): void {\n const extension = this._getExtensionByRegion(region);\n\n if (extension.type === ExtensionType.Worker) {\n this._workerExtensionMessenger.clearCacheById(extension.id);\n\n return;\n }\n\n this.clearCacheById(extension.id);\n }\n\n clearCacheById(extensionId: string): void {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n this._workerExtensionMessenger.clearCacheById(extension.id);\n\n return;\n }\n\n if (this._commandListeners[extensionId]) {\n delete this._commandListeners[extensionId];\n }\n\n if (this._queryListeners[extensionId]) {\n delete this._queryListeners[extensionId];\n }\n\n if (this._posters[extensionId]) {\n delete this._posters[extensionId];\n }\n }\n\n listenForCommand(\n extensionId: string,\n command: T,\n commandHandler: (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => Promise | void,\n ): () => void {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n return this._workerExtensionMessenger.listenForCommand(\n extensionId,\n command,\n commandHandler,\n );\n }\n\n if (!this._commandListeners[extensionId]) {\n this._commandListeners[extensionId] = new IframeEventListener(extension.url);\n }\n\n const listener = this._commandListeners[extensionId];\n\n listener.listen();\n\n const validCommandType = this._validateCommand(command);\n\n const commandHandlerProxy = (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandOrQueryContext,\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 listenForQuery(\n extensionId: string,\n query: T,\n queryHandler: (\n query: ExtensionQueryMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => Promise | void,\n ): () => void {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n return this._workerExtensionMessenger.listenForQuery(extensionId, query, queryHandler);\n }\n\n if (!this._queryListeners[extensionId]) {\n this._queryListeners[extensionId] = new IframeEventListener(extension.url);\n }\n\n const listener = this._queryListeners[extensionId];\n\n listener.listen();\n\n const validQueryType = this._validateQuery(query);\n\n const queryHandlerProxy = (\n query: ExtensionQueryMap[T],\n context?: ExtensionCommandOrQueryContext,\n ) => {\n if (context?.extensionId === extensionId) {\n queryHandler(query, context);\n }\n };\n\n listener.addListener(validQueryType, queryHandlerProxy);\n\n return () => {\n listener.removeListener(validQueryType, queryHandlerProxy);\n };\n }\n\n stopListen(extensionId: string): void {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n this._workerExtensionMessenger.stopListen(extensionId);\n\n return;\n }\n\n if (this._commandListeners[extensionId]) {\n this._commandListeners[extensionId].stopListen();\n }\n\n if (this._queryListeners[extensionId]) {\n this._queryListeners[extensionId].stopListen();\n }\n }\n\n post(extensionId: string, message: ExtensionMessage): void {\n try {\n const extension = this._getExtensionById(extensionId);\n\n if (extension.type === ExtensionType.Worker) {\n this._workerExtensionMessenger.post(extensionId, message);\n\n return;\n }\n\n if (!this._posters[extensionId]) {\n this._posters[extensionId] =\n createExtensionEventPoster(extension);\n }\n\n this._posters[extensionId].post(message);\n } catch (error) {\n this.clearCacheById(extensionId);\n // eslint-disable-next-line no-console\n console.log(\n `Unable to post event to extension(${extensionId}) because extension iframe is not mounted.\\nThe event that could not be delivered:`,\n message,\n );\n }\n }\n\n private _getExtensionById(extensionId: string): Extension {\n this._getExtensions();\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 _getExtensionByRegion(region: string): Extension {\n this._getExtensions();\n\n const extension = this._extensions?.find((e) => e.region === region);\n\n if (!extension) {\n throw new ExtensionNotFoundError(\n `Unable to proceed due to no extension found for region: ${region}.`,\n );\n }\n\n return extension;\n }\n\n private _getExtensions(): void {\n if (this._extensions) {\n return;\n }\n\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\n private _validateCommand(command: T): T {\n if (Object.values(ExtensionCommandType).includes(command)) {\n return command;\n }\n\n throw new UnsupportedExtensionCommandError();\n }\n private _validateQuery(query: T): T {\n if (Object.values(ExtensionQueryType).includes(query)) {\n return query;\n }\n\n throw new UnsupportedExtensionQueryError();\n }\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 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\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 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 { 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: number, 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 {\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 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 | undefined {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n return;\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) {\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 if (!createCheckoutSessionConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\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: `${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 * 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\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 let paymentMethod: PaymentMethod;\n\n try {\n paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n } catch (_e) {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n paymentMethod = this.paymentIntegrationService\n .getState()\n .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","export interface Features {\n [featureName: string]: boolean | undefined;\n}\n\nexport default function isExperimentEnabled(\n features: Features,\n experimentName: string,\n fallbackValue = true,\n): boolean {\n return features[experimentName] ?? fallbackValue;\n}\n","export const BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION = '3.128.0';\nexport const BRAINTREE_SDK_DEFAULT_VERSION = '3.123.2';\nexport const BRAINTREE_SDK_STABLE_VERSION = '3.106.0';\n","import { find } from 'lodash';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport { BraintreeHostWindow } from './braintree';\nimport {\n BRAINTREE_SDK_DEFAULT_VERSION,\n BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION,\n BRAINTREE_SDK_STABLE_VERSION,\n} from './braintree-sdk-verison';\n\nexport default class BraintreeSDKVersionManager {\n private braintreeWindow: BraintreeHostWindow = window;\n\n constructor(private paymentIntegrationService: PaymentIntegrationService) {}\n\n getSDKVersion() {\n const state = this.paymentIntegrationService.getState();\n const storeConfig = state.getStoreConfig();\n const features = storeConfig?.checkoutSettings.features || {};\n\n const preloadedVersion = this.getPreloadedSDKVersion();\n\n if (preloadedVersion) {\n return preloadedVersion;\n }\n\n if (isExperimentEnabled(features, 'PAYPAL-5809.braintree_hosted_fields_fix_version')) {\n return BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION;\n }\n\n if (isExperimentEnabled(features, 'PAYPAL-5636.update_braintree_sdk_version')) {\n return BRAINTREE_SDK_DEFAULT_VERSION;\n }\n\n return BRAINTREE_SDK_STABLE_VERSION;\n }\n\n private getPreloadedSDKVersion(): void | string {\n const braintree = this.braintreeWindow.braintree;\n\n if (braintree) {\n const preloadedVersion = find<{ VERSION?: string }>(\n Object.values(braintree),\n (module) => !!module.VERSION,\n );\n\n return preloadedVersion?.VERSION;\n }\n }\n}\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","import { Address } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport * 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(\n options: BraintreeThreeDSecureOptions,\n callback?: Braintree3DSVerifyCardCallback,\n ): Promise;\n cancelVerifyCard(): Promise;\n on(\n event: K,\n handler: BraintreeThreeDSecureEventMap[K],\n ): void;\n}\n\nexport type Braintree3DSVerifyCardCallback = (\n verifyError: Braintree3DSVerifyCardError,\n payload: Braintree3DSVerifyCardPayload,\n) => void;\n\nexport interface BraintreeThreeDSecureEventMap {\n 'customer-canceled': () => void;\n}\n\nexport interface Braintree3DSVerifyCardError {\n code: string;\n}\n\nexport interface Braintree3DSVerifyCardPayload {\n nonce: string;\n}\n\nexport interface BraintreeThreeDSecureCreatorConfig extends BraintreeModuleCreatorConfig {\n version?: number;\n}\n\nexport interface BraintreeThreeDSecureOptions {\n nonce: string;\n amount: number | string;\n challengeRequested?: boolean;\n showLoader?: boolean;\n bin?: string;\n additionalInformation?: {\n acsWindowSize?: '01' | '02' | '03' | '04' | '05';\n };\n collectDeviceData?: boolean;\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\nexport enum BraintreeOrderStatus {\n Completed = 'COMPLETED',\n Pending = 'PENDING',\n Failed = 'FAILED',\n}\n\nexport interface BraintreeOrderStatusData {\n status: BraintreeOrderStatus;\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 non-instant payment methods\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 BraintreeOrderSavedResponse {\n body: {\n additional_action_required: {\n data: {\n order_id_saved_successfully: string;\n };\n };\n };\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 binDetails?: {\n bin: string;\n };\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\nexport interface BraintreeRedirectError {\n body: {\n additional_action_required: {\n data: {\n redirect_url: string;\n };\n };\n };\n}\n\nexport default interface BillingAddress extends Address {\n id: string;\n email?: string;\n}\n\nexport enum BraintreeSupportedCardBrands {\n Visa = 'visa',\n Mastercard = 'mastercard',\n AmericanExpress = 'american-express',\n DinersClub = 'diners-club',\n Discover = 'discover',\n Jcb = 'jcb',\n UnionPay = 'union-pay',\n Maestro = 'maestro',\n Elo = 'elo',\n Mir = 'mir',\n Hiper = 'hiper',\n Hipercard = 'hipercard',\n}\n\nexport 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 interface BraintreeRequestData {\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","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 { 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 enableCheckoutPaywallBanner?: boolean;\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 paypalBNPLConfiguration?: PayPalBNPLConfigurationItem[] | null;\n nonce?: string;\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 preventCursorJumps?: boolean;\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: (err: null | undefined | BraintreeError) => 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 BNPL Configurator related types\n *\n */\nexport interface PayPalBNPLConfigurationItem {\n id: string;\n name: string;\n status: boolean;\n styles: Record;\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 {\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 { BraintreeModuleName } from './braintree';\nimport {\n BRAINTREE_SDK_DEFAULT_VERSION,\n BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION,\n BRAINTREE_SDK_STABLE_VERSION,\n} from './braintree-sdk-verison';\n\nexport const BRAINTREE_SDK_SCRIPTS_INTEGRITY = {\n [BRAINTREE_SDK_STABLE_VERSION]: {\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 [BRAINTREE_SDK_DEFAULT_VERSION]: {\n [BraintreeModuleName.Client]:\n 'sha384-o+nbQGcwNNxIBeXeu3+XmbSq+Cg8R3EN3N0l5hXCgMMU2RGY0t1z0LroSEIAbfAO',\n [BraintreeModuleName.PaypalCheckout]:\n 'sha384-WrfbWPBS4mH86GAoycPSgiH8hQ8KH7A67C93Hjhunv/xhNk2YpBn3wbFA4Fhg9U/',\n [BraintreeModuleName.Paypal]:\n 'sha384-VF389nvvrRUgDsTXMxTYORDtVegB9IQa3Cxr//DyJnLYnz8/X8VCzEvck2c+Megt',\n [BraintreeModuleName.LocalPayment]:\n 'sha384-tZKx2rEQbfmZpoPSY5VPmJEhaq4X75dLvwHMs3VE9U+C8lPyw+hWTIL1+GPvWCIH',\n [BraintreeModuleName.DataCollector]:\n 'sha384-E6k3wOpP7syCDDwaRDLF06942Y00NkbwJvWi2OQXwwKzGwG5fd3E7RFUvCCecfvO',\n [BraintreeModuleName.UsBankAccount]:\n 'sha384-258FON8LZGG0W9Qaz4Jij83pZHu30YnKjJA7gNulLBh6CclkucgF+tHDQuYFRYfW',\n [BraintreeModuleName.GooglePayment]:\n 'sha384-taJ2p/0+n0VH328POAoBiuEbL3tnHUTE9S42hK1V+Txs3X+QYjZOyKW35JgHRFfO',\n [BraintreeModuleName.ThreeDSecure]:\n 'sha384-+NSZH4Zj3sO5bdWvPKhU5N16QDxeueTVTnUVeleeESkhLSaz4Ob1hh/5myecc9Ym',\n [BraintreeModuleName.VisaCheckout]:\n 'sha384-66DiBjghxk1OmBj8aksN8gbQ+CwoQcx1vPfiXUN08g1iQVM+BwewF0p7toM3i7SS',\n [BraintreeModuleName.Venmo]:\n 'sha384-B5UwY42kE4RoLoWbQ7YpqosUlUad2/DlGWiw0HhoZbSPk30CQAaSA10ohyLDTkDU',\n [BraintreeModuleName.HostedFields]:\n 'sha384-Aw9EesSaUeWxe36PqEHiOyOyOq8M6CIb1gw7/yHNVPRzGtFXXcd2OQ8qXrIlOj2P',\n [BraintreeModuleName.Fastlane]:\n 'sha384-rhBL1hpZ71JqG+2TsT0Dih47mbjx8cjJCpeZjk9tw3df1gFMKfCTmMyZunhr7H4Y',\n },\n [BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION]: {\n [BraintreeModuleName.Client]:\n 'sha384-0WNxksIpRP+fYZiIdr12g6DBUQfLDzYCQJZtR/C8KkcwSGhPHfcFp3tTaGcMyFTq',\n [BraintreeModuleName.PaypalCheckout]:\n 'sha384-lWM1jk4BOxoDNV6Kop7tVNvQgINlmEVz0c/OwM+HNHK3QC8xqwd54Ovrt2QRDTjh',\n [BraintreeModuleName.Paypal]:\n 'sha384-fXUmVxC2EMZBDXZ7eTHSTL/LFBrHej/MSXT/vTBXvra4lzgLNGvREAp+x0GYObuH',\n [BraintreeModuleName.LocalPayment]:\n 'sha384-pha1xGuGSkmZH5x9aqHvRaO4xLea7rmQ/79PFj9zxNzxuFcOWZg7gOP7FibygOEC',\n [BraintreeModuleName.DataCollector]:\n 'sha384-Q6PI2F9eekWbAxhroybl+aEcvqhdowN/EQlGwBUyJOzPFn9982u9xl6SU6XfGKzc',\n [BraintreeModuleName.UsBankAccount]:\n 'sha384-W3RLQSKJL1tQ3+Y7mP6tmkamtZ8bV4Yw/XxL9Jj5JtXHraD8loMF8hAIG5m2zK7F',\n [BraintreeModuleName.GooglePayment]:\n 'sha384-TITQMsFWA3elDNGP2mWz2oKBo4qjt+TlqzovcaPoeBiAh/wPBi6nae50ADdgU1/i',\n [BraintreeModuleName.ThreeDSecure]:\n 'sha384-YiycYN89ZlL/Evcaq4y1ajW1mhd7JYfZBDuOwHtIn4/Jnm20GL+/XCM+zYAwWD8D',\n [BraintreeModuleName.VisaCheckout]:\n 'sha384-/OdaTv9qrkKzjObtUe6yzfDhHozFW/+uXlrSl736sOZRJpjGQETvpYXqMFFg69xv',\n [BraintreeModuleName.Venmo]:\n 'sha384-dA+ojdW9vbJS4JavcXyOs9d5uZHJg5dNtYupoPSH2zsXIiYDVS5amLb/u8qmQ6oz',\n [BraintreeModuleName.HostedFields]:\n 'sha384-31ZkS58+iaWsW06ftW52zzVZFp43WPd7pNYRiddYynSNg6Oh7WGbSFGorAUH6T1z',\n [BraintreeModuleName.Fastlane]:\n 'sha384-jlbrwNvL3HvLAUCtLSmrnQ2GH1udCUrRS/bVmReAS5fuIVvcW8Pko/Gkg82tlgtr',\n },\n};\n","export enum ApplePayGatewayType {\n BRAINTREE = 'braintree',\n BRAINTREE_FASTLANE = 'braintreeacceleratedcheckout',\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 BraintreeSDKVersionManager from './braintree-sdk-version-manager';\nimport isManageableBraintreeSDKVersion from './isManageableBraintreeSDKVersion';\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 constructor(\n private scriptLoader: ScriptLoader,\n private braintreeHostWindow: BraintreeHostWindow,\n private braintreeSDKVersionManager: BraintreeSDKVersionManager,\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 braintreeSdkVersion = this.braintreeSDKVersionManager.getSDKVersion();\n\n const scriptPath = `//js.braintreegateway.com/web/${braintreeSdkVersion}/js/${fileName}`;\n\n const integrity = isManageableBraintreeSDKVersion(braintreeSdkVersion)\n ? this.getIntegrityValuesByModuleName(braintreeModuleName, braintreeSdkVersion)\n : undefined;\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(\n moduleName: BraintreeModuleName,\n version: keyof typeof BRAINTREE_SDK_SCRIPTS_INTEGRITY,\n ): string {\n const integrity = BRAINTREE_SDK_SCRIPTS_INTEGRITY[version][moduleName];\n\n if (!integrity) {\n throw new Error('Unexpected fileName value');\n }\n\n return integrity;\n }\n}\n","import { BRAINTREE_SDK_SCRIPTS_INTEGRITY } from './braintree-sdk-scripts-integrity';\n\nfunction isManageableBraintreeSDKVersion(\n version: string,\n): version is keyof typeof BRAINTREE_SDK_SCRIPTS_INTEGRITY {\n return version in BRAINTREE_SDK_SCRIPTS_INTEGRITY;\n}\n\nexport default isManageableBraintreeSDKVersion;\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","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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory 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 private _applePayScriptLoader: ApplePayScriptLoader,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithApplePayCustomerInitializeOptions,\n ): Promise {\n const { methodId, applepay } = options;\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 await this._applePayScriptLoader.loadSdk();\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 (\n this._paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE &&\n this._paymentMethod.clientToken\n ) {\n this._braintreeSdk.initialize(this._paymentMethod.clientToken);\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 applePayButton = this._createApplePayButtonElement();\n\n container.appendChild(applePayButton);\n\n return applePayButton;\n }\n\n private _createApplePayButtonElement(): HTMLElement {\n const applePayButton = document.createElement('apple-pay-button');\n\n applePayButton.setAttribute('buttonstyle', 'black');\n applePayButton.setAttribute('type', 'plain');\n applePayButton.setAttribute(\n 'style',\n '--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;',\n );\n\n return applePayButton;\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","import ApplePayWindow from './apple-pay-window';\nimport isApplePayWindow from './is-apple-pay-window';\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 ApplePayWindow from './apple-pay-window';\n\nexport default function isApplePayWindow(window: Window): window is ApplePayWindow {\n return 'ApplePaySession' in window;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { assertApplePayWindow } from './apple-pay-session-factory';\nimport isApplePaySdkWindow from './is-apple-pay-sdk-window';\n\nexport default class ApplePayScriptLoader {\n private sdkVersion = '1.latest';\n\n constructor(private scriptLoader: ScriptLoader) {}\n\n async loadSdk() {\n if (isApplePaySdkWindow(window)) {\n return;\n }\n\n await this.scriptLoader.loadScript(\n `https://applepay.cdn-apple.com/jsapi/${this.sdkVersion}/apple-pay-sdk.js`,\n );\n\n assertApplePayWindow(window);\n }\n}\n","interface ApplePaySdkWindow extends Window {\n ApplePaySDK?: {\n origin: string;\n publicPath: string;\n token: string | undefined;\n };\n}\n\nexport default function isApplePaySdkWindow(window: Window): window is ApplePaySdkWindow {\n return 'ApplePaySDK' in window;\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\n} 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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayCustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n\n return new ApplePayCustomerStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), window, braintreeSDKVersionManager),\n ),\n new ApplePayScriptLoader(new ScriptLoader()),\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 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 { 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 | object;\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 { PayPalBNPLConfigurationItem } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n BuyNowCartRequestBody,\n HostedInstrument,\n ShippingOption,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n/**\n *\n * BigCommerce Payments Funding sources\n *\n */\nexport type FundingType = string;\n// TODO: rename BigCommercePaymentsSDKFunding to PayPalSDKFunding\nexport interface BigCommercePaymentsSDKFunding {\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 * BigCommerce Payments SDK\n *\n */\n\nexport interface BigCommercePaymentsCardFieldsConfig {\n inputEvents: {\n onChange(data: BigCommercePaymentsCardFieldsState): void;\n onFocus(data: BigCommercePaymentsCardFieldsState): void;\n onBlur(data: BigCommercePaymentsCardFieldsState): void;\n onInputSubmitRequest(data: BigCommercePaymentsCardFieldsState): void;\n };\n createVaultSetupToken?: (data: BigCommercePaymentsCardFieldsState) => void;\n createOrder?: () => Promise;\n style: BigCommercePaymentsHostedFieldsRenderOptions['styles'];\n onApprove(data: BigCommercePaymentsCardFieldsOnApproveData): void;\n onError(): void;\n}\n\nexport interface BigCommercePaymentsCardFieldsOnApproveData {\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 BigCommercePaymentsCardFieldsFieldData {\n isFocused: boolean;\n isEmpty: boolean;\n isValid: boolean;\n isPotentiallyValid: boolean;\n}\n\ntype BigCommercePaymentsCardFieldsCard = BigCommercePaymentsHostedFieldsCard;\n\nexport interface BigCommercePaymentsCardFieldsState {\n cards: BigCommercePaymentsCardFieldsCard[];\n emittedBy: string;\n isFormValid: boolean;\n errors: string[];\n fields: {\n cardCvvField: BigCommercePaymentsCardFieldsFieldData;\n cardNumberField: BigCommercePaymentsCardFieldsFieldData;\n cardNameField?: BigCommercePaymentsCardFieldsFieldData;\n cardExpiryField: BigCommercePaymentsCardFieldsFieldData;\n };\n}\n\nexport interface BigCommercePaymentsFields {\n render(container: HTMLElement | string): Promise;\n clear(): void;\n removeClass(className: string): Promise;\n close(): Promise;\n}\n\ninterface BigCommercePaymentsFieldsInitializationData {\n placeholder?: string;\n}\n\nexport interface BigCommercePaymentsCardFields {\n isEligible(): boolean;\n CVVField(config?: BigCommercePaymentsFieldsInitializationData): BigCommercePaymentsFields;\n ExpiryField(config?: BigCommercePaymentsFieldsInitializationData): BigCommercePaymentsFields;\n NameField(config?: BigCommercePaymentsFieldsInitializationData): BigCommercePaymentsFields;\n NumberField(config?: BigCommercePaymentsFieldsInitializationData): BigCommercePaymentsFields;\n submit(config?: BigCommercePaymentsCardFieldsSubmitConfig): Promise;\n getState(): Promise;\n}\n\nexport interface BigCommercePaymentsCardFieldsSubmitConfig {\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: (\n data: BigCommercePaymentsCardFieldsConfig,\n ) => 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: BigCommercePaymentsSDKFunding;\n HostedFields: {\n isEligible(): boolean;\n render(\n data: BigCommercePaymentsHostedFieldsRenderOptions,\n ): Promise;\n };\n Legal: PayPalLegal & LegalFunding;\n Buttons(options: BigCommercePaymentsButtonsOptions): BigCommercePaymentsButtons;\n PaymentFields(\n options: BigCommercePaymentsPaymentFieldsOptions,\n ): BigCommercePaymentsPaymentFields;\n Messages(options: BigCommercePaymentsMessagesOptions): BigCommercePaymentsMessages;\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 BigCommercePaymentsScriptParams {\n options: {\n 'client-id'?: string;\n 'merchant-id'?: string;\n 'buyer-country'?: string;\n 'disable-funding'?: FundingType[];\n 'enable-funding'?: FundingType[];\n currency?: string;\n commit?: boolean;\n intent?: BigCommercePaymentsIntent;\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 'data-namespace'?: string;\n };\n}\n\nexport enum BigCommercePaymentsIntent {\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 BigCommercePaymentsHostWindow extends Window {\n bigCommercePaymentsPayPalSDK?: PayPalSDK;\n}\n\n/**\n *\n * BigCommerce Payments Initialization Data\n *\n */\nexport interface BigCommercePaymentsInitializationData {\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?: BigCommercePaymentsIntent;\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 isAppSwitchEnabled?: boolean;\n paypalBNPLConfiguration?: PayPalBNPLConfigurationItem[];\n}\n\n/**\n *\n * BigCommerce Payments BuyNow\n *\n */\nexport interface PayPalBuyNowInitializeOptions {\n getBuyNowCartRequestBody(): BuyNowCartRequestBody;\n}\n\n/**\n *\n * BigCommerce Payments Hosted Fields\n *\n */\nexport interface BigCommercePaymentsHostedFieldsRenderOptions {\n fields?: {\n number?: BigCommercePaymentsHostedFieldOption;\n cvv?: BigCommercePaymentsHostedFieldOption;\n expirationDate?: BigCommercePaymentsHostedFieldOption;\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 BigCommercePaymentsHostedFieldOption {\n selector: string;\n placeholder?: string;\n}\n\nexport interface BigCommercePaymentsHostedFields {\n submit(\n options?: BigCommercePaymentsHostedFieldsSubmitOptions,\n ): Promise;\n getState(): BigCommercePaymentsHostedFieldsState;\n on(eventName: string, callback: (event: BigCommercePaymentsHostedFieldsState) => void): void;\n}\n\nexport interface BigCommercePaymentsHostedFieldsSubmitOptions {\n contingencies?: Array<'3D_SECURE'>;\n cardholderName?: string;\n}\n\nexport interface BigCommercePaymentsHostedFieldsApprove {\n orderId: string;\n liabilityShift?: 'POSSIBLE' | 'NO' | 'UNKNOWN';\n}\n\nexport interface BigCommercePaymentsHostedFieldsState {\n cards: BigCommercePaymentsHostedFieldsCard[];\n emittedBy: string;\n fields: {\n number?: BigCommercePaymentsHostedFieldsFieldData;\n expirationDate?: BigCommercePaymentsHostedFieldsFieldData;\n expirationMonth?: BigCommercePaymentsHostedFieldsFieldData;\n expirationYear?: BigCommercePaymentsHostedFieldsFieldData;\n cvv?: BigCommercePaymentsHostedFieldsFieldData;\n postalCode?: BigCommercePaymentsHostedFieldsFieldData;\n };\n}\n\nexport interface BigCommercePaymentsHostedFieldsCard {\n type: string;\n niceType: string;\n code: {\n name: string;\n size: number;\n };\n}\n\nexport interface BigCommercePaymentsHostedFieldsFieldData {\n container: HTMLElement;\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\n/**\n *\n * BigCommerce Payments Buttons\n *\n */\nexport interface BigCommercePaymentsButtons {\n render(id: string): void;\n close(): void;\n isEligible(): boolean;\n hasReturned?(): boolean;\n resume?(): void;\n}\n\nexport interface BigCommercePaymentsButtonsOptions {\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 phone?: {\n phone_number: {\n national_number: string;\n };\n };\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 * BigCommerce Payments Payment fields\n *\n */\nexport interface BigCommercePaymentsPaymentFields {\n render(id: string): void;\n}\n\nexport interface BigCommercePaymentsPaymentFieldsOptions {\n style?: BigCommercePaymentsFieldsStyleOptions;\n fundingSource: string;\n fields: {\n name?: {\n value?: string;\n };\n email?: {\n value?: string;\n };\n };\n}\n\nexport interface BigCommercePaymentsFieldsStyleOptions {\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 * BigCommercePayments Messages\n */\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface BigCommercePaymentsMessages {\n render(id: string): void;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface BigCommercePaymentsMessagesOptions {\n amount: number;\n placement: string;\n style?: BigCommercePaymentsMessagesStyleOptions;\n fundingSource?: string;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface BigCommercePaymentsMessagesStyleOptions {\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 fastlaneToken?: string;\n methodId?: string;\n gatewayId?: string;\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 BigCommercePaymentsRequestSender from './bigcommerce-payments-request-sender';\nimport BigCommercePaymentsScriptLoader from './bigcommerce-payments-script-loader';\nimport {\n BigCommercePaymentsInitializationData,\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n PayPalCreateOrderCardFieldsResponse,\n PayPalCreateOrderRequestBody,\n PayPalOrderDetails,\n PayPalOrderStatus,\n PayPalSDK,\n StyleButtonColor,\n StyleButtonLabel,\n StyleButtonShape,\n} from './bigcommerce-payments-types';\n\nexport default class BigCommercePaymentsIntegrationService {\n private paypalSdk?: PayPalSDK;\n\n constructor(\n private formPoster: FormPoster,\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsRequestSender: BigCommercePaymentsRequestSender,\n private bigCommercePaymentsScriptLoader: BigCommercePaymentsScriptLoader,\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.bigCommercePaymentsScriptLoader.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.bigCommercePaymentsRequestSender.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.bigCommercePaymentsRequestSender.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.bigCommercePaymentsRequestSender.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.bigCommercePaymentsRequestSender.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: address?.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 phone: payer.phone?.phone_number?.national_number,\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","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 } 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 './bigcommerce-payments-types';\n\nexport default class BigCommercePaymentsRequestSender {\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/bigcommerce_payments`;\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 = 'bigcommerce_payments',\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 BigCommercePaymentsHostWindow,\n BigCommercePaymentsInitializationData,\n BigCommercePaymentsScriptParams,\n ComponentsScriptType,\n FundingType,\n PayPalSDK,\n} from './bigcommerce-payments-types';\n\nexport default class BigCommercePaymentsScriptLoader {\n private window: BigCommercePaymentsHostWindow;\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: BigCommercePaymentsScriptParams,\n forceLoad = false,\n ): Promise {\n if (!this.window.bigCommercePaymentsPayPalSDK || 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.bigCommercePaymentsPayPalSDK) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.bigCommercePaymentsPayPalSDK;\n }\n\n private getPayPalSdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage = true,\n ): BigCommercePaymentsScriptParams {\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 === 'bigcommerce_payments_creditcards';\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 enableVenmoFunding = isVenmoEnabled ? ['venmo'] : [];\n const disableVenmoFunding = !isVenmoEnabled ? ['venmo'] : [];\n const disableAPMsFunding = availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n );\n const googlePayComponent: ComponentsScriptType = isGooglePayEnabled ? ['googlepay'] : [];\n const cardFieldsComponent: ComponentsScriptType = initializesOnCheckoutPage\n ? ['card-fields']\n : [];\n const disableFunding: FundingType[] = this.filterFundingOptions([\n ...disableCardFunding,\n ...disableCreditFunding,\n ...disableVenmoFunding,\n ...disableAPMsFunding,\n ]);\n const enableFunding: FundingType[] = this.filterFundingOptions([\n ...enableCardFunding,\n ...enableCreditFunding,\n ...enableVenmoFunding,\n ...enabledAlternativePaymentMethods,\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 'data-namespace': 'bigCommercePaymentsPayPalSDK',\n },\n };\n }\n\n private filterFundingOptions(fundingOptions: FundingType[] | undefined): FundingType[] {\n const fundingTypesToBeFiltered = ['klarna', 'afterpay'];\n\n if (!fundingOptions) {\n return [];\n }\n\n return fundingOptions.filter(\n (fundingOption: FundingType) => !fundingTypesToBeFiltered.includes(fundingOption),\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 BigCommercePaymentsIntegrationService,\n BigCommercePaymentsRequestSender,\n BigCommercePaymentsScriptLoader,\n} from './index';\n\nconst createBigCommercePaymentsIntegrationService = (\n paymentIntegrationService: PaymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new BigCommercePaymentsIntegrationService(\n createFormPoster(),\n paymentIntegrationService,\n new BigCommercePaymentsRequestSender(createRequestSender({ host: getHost() })),\n new BigCommercePaymentsScriptLoader(getScriptLoader()),\n );\n};\n\nexport default createBigCommercePaymentsIntegrationService;\n","const DefaultCheckoutButtonHeight = 40;\n\nexport default DefaultCheckoutButtonHeight;\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsCustomerInitializeOptions, {\n WithBigCommercePaymentsCustomerInitializeOptions,\n} from './bigcommerce-payments-customer-initialize-options';\n\nexport default class BigCommercePaymentsCustomerStrategy implements CustomerStrategy {\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBigCommercePaymentsCustomerInitializeOptions,\n ): Promise {\n const { bigcommerce_payments, 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 (!bigcommerce_payments) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments\" argument is not provided.',\n );\n }\n\n if (!bigcommerce_payments.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments.container\" argument is not provided.',\n );\n }\n\n if (bigcommerce_payments.onClick && typeof bigcommerce_payments.onClick !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments.onClick\" argument is not a function.',\n );\n }\n\n this.onError = bigcommerce_payments.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 const paypalSdk = await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n // eslint-disable-next-line no-console\n console.error(\n '[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n this.renderButton(methodId, bigcommerce_payments);\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 bigcommerce_payments: BigCommercePaymentsCustomerInitializeOptions,\n ): void {\n const { container, onClick, onComplete } = bigcommerce_payments;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const {\n isHostedCheckoutEnabled,\n paymentButtonStyles,\n isAppSwitchEnabled = false,\n } = paymentMethod.initializationData || {};\n const { checkoutTopButtonStyles } = paymentButtonStyles || {};\n\n const defaultCallbacks = {\n ...(isAppSwitchEnabled && {\n appSwitchWhenAvailable: true,\n }),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder('bigcommerce_payments'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.tokenizePayment(methodId, orderID),\n ...(onClick && { onClick: () => onClick() }),\n };\n\n const hostedCheckoutCallbacks = {\n ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n }),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const buttonRenderOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.bigCommercePaymentsIntegrationService.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 if (paypalButton.hasReturned?.() && isAppSwitchEnabled) {\n paypalButton.resume?.();\n } else {\n paypalButton.render(`#${container}`);\n }\n } else {\n this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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 =\n this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsCustomerStrategy from './bigcommerce-payments-customer-strategy';\n\nconst createBigCommercePaymentsCustomerStrategy: CustomerStrategyFactory<\n BigCommercePaymentsCustomerStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsCustomerStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsCustomerStrategy, [\n { id: 'bigcommerce_payments' },\n]);\n","import { HostedInstrument, NonceInstrument } from './payment';\n\ntype PaymentInstrument = CardInstrument | AccountInstrument | HostedInstrument | NonceInstrument;\n\nexport default PaymentInstrument;\n\nexport interface 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 { CardInstrument, CustomerAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n/**\n *\n * BigCommerce Payments Funding sources\n *\n */\nexport type FundingType = string;\n\n/**\n *\n * BigCommerce Payments Initialization Data\n *\n */\nexport interface BigCommercePaymentsInitializationData {\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 BCP Fastlane A/B test will be finished\n enabledAlternativePaymentMethods: FundingType[];\n isDeveloperModeApplicable?: boolean;\n intent?: BigCommercePaymentsIntent;\n isAcceleratedCheckoutEnabled?: boolean; // PayPal Fastlane related\n isFastlaneShippingOptionAutoSelectEnabled?: boolean; // PayPal Fastlane related\n isFastlaneStylingEnabled?: boolean;\n isHostedCheckoutEnabled?: boolean;\n isBigCommercePaymentsAnalyticsV2Enabled?: 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 BCP Fastlane A/B test will be finished\n paymentButtonStyles?: Record;\n paypalBNPLConfiguration?: PayPalBNPLConfigurationItem[];\n threeDSVerificationMethod?: string;\n}\n\n/**\n *\n * PayPalHostWindow contains different\n * PayPal Sdk instances for different purposes\n *\n */\nexport interface PayPalHostWindow extends Window {\n bigCommercePaymentsFastlane?: PayPalFastlane;\n bigCommercePaymentsFastlaneSdk?: PayPalFastlaneSdk;\n bigCommercePaymentsMessages?: PayPalMessagesSdk;\n bigCommercePaymentsApms?: PayPalApmSdk;\n bigCommercePaymentsGooglePay?: PayPalGooglePaySdk;\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'?: FundingType[];\n 'disable-funding'?: FundingType[];\n currency?: string;\n commit?: boolean;\n intent?: BigCommercePaymentsIntent;\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 'data-sdk-client-token'?: string;\n };\n}\n\nexport enum BigCommercePaymentsIntent {\n AUTHORIZE = 'authorize',\n CAPTURE = 'capture',\n}\n\nexport type PayPalSdkComponents = Array<\n 'fastlane' | 'messages' | 'buttons' | 'payment-fields' | 'googlepay' | 'three-domain-secure'\n>;\n\n/**\n *\n * PayPal Sdk instances\n *\n */\nexport enum LiabilityShiftEnum {\n Possible = 'POSSIBLE',\n No = 'NO',\n Unknown = 'UNKNOWN',\n Yes = 'YES',\n}\n\nexport interface threeDSecureParameters {\n amount: string;\n currency: string;\n nonce: string;\n threeDSRequested: boolean;\n transactionContext: {\n experience_context: {\n brand_name?: string;\n locale: string;\n return_url: string;\n cancel_url: string;\n };\n };\n}\n\nexport interface PayPalFastlaneSdk {\n ThreeDomainSecureClient: {\n isEligible(params: threeDSecureParameters): Promise;\n show(): Promise;\n };\n Fastlane(options?: PayPalFastlaneOptions): Promise;\n}\n\ninterface ThreeDomainSecureClientShowResponse {\n liabilityShift: LiabilityShiftEnum;\n authenticationState: TDSecureAuthenticationState;\n nonce: string; // Enriched nonce or the original nonce\n}\n\nexport interface PayPalMessagesSdk {\n Messages(options: MessagingOptions): MessagingRender;\n}\n\nexport interface PayPalApmSdk {\n Buttons(options: BigCommercePaymentsButtonsOptions): BigCommercePaymentsButtons;\n PaymentFields(\n options: BigCommercePaymentsPaymentFieldsOptions,\n ): BigCommercePaymentsPaymentFields;\n}\n\nexport interface PayPalGooglePaySdk {\n Googlepay(): GooglePay;\n}\n\nexport enum TDSecureVerificationMethod {\n Always = 'SCA_ALWAYS',\n}\n\nexport enum TDSecureAuthenticationState {\n Succeeded = 'succeeded',\n Cancelled = 'cancelled',\n Errored = 'errored',\n}\n\n/**\n *\n * Google Pay related types\n *\n */\n\ninterface GooglePay {\n config: () => Promise;\n confirmOrder: (confirmOrderConfig: ConfirmOrderConfig) => Promise<{ status: string }>;\n initiatePayerAction: (payerActionConfig: PayerActionConfig) => Promise;\n}\n\ninterface ConfirmOrderConfig {\n orderId: string;\n paymentMethodData: ConfirmOrderData;\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\ninterface PayerActionConfig {\n orderId: 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\n/**\n *\n * BigCommerce Payments Buttons\n *\n */\nexport interface BigCommercePaymentsButtons {\n render(id: string): void;\n close(): void;\n isEligible(): boolean;\n}\n\nexport interface BigCommercePaymentsButtonsOptions {\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 * BigCommerce Payments PaymentFields fields\n *\n */\nexport interface BigCommercePaymentsPaymentFields {\n render(id: string): void;\n}\n\nexport interface BigCommercePaymentsPaymentFieldsOptions {\n style?: BigCommercePaymentsFieldsStyleOptions;\n fundingSource: string;\n fields: {\n name?: {\n value?: string;\n };\n email?: {\n value?: string;\n };\n };\n}\n\nexport interface BigCommercePaymentsFieldsStyleOptions {\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 = 'canceled',\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\nexport interface RedirectError {\n body: {\n additional_action_required: {\n data: {\n redirect_url: string;\n };\n };\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 BigCommercePaymentsInitializationData,\n FundingType,\n PayPalFastlaneSdk,\n PayPalGooglePaySdk,\n PayPalHostWindow,\n PayPalMessagesSdk,\n PayPalSdkConfig,\n} from './bigcommerce-payments-types';\n\nexport default class PayPalSdkHelper {\n private window: PayPalHostWindow;\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.bigCommercePaymentsFastlaneSdk) {\n const config = this.getPayPalFastlaneSdkConfiguration(\n paymentMethod,\n currencyCode,\n sessionId,\n );\n\n await this.loadPayPalSdk(config);\n\n if (!this.window.bigCommercePaymentsFastlaneSdk) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.window.bigCommercePaymentsFastlaneSdk;\n }\n\n async getPayPalGooglePaySdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n if (!this.window.bigCommercePaymentsGooglePay || forceLoad) {\n const paypalSdkScriptConfig = this.getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n initializesOnCheckoutPage,\n );\n\n await this.loadPayPalSdk(paypalSdkScriptConfig);\n }\n\n if (!this.window.bigCommercePaymentsGooglePay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.bigCommercePaymentsGooglePay;\n }\n\n async getPayPalApmsSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n ) {\n if (!this.window.bigCommercePaymentsApms) {\n const config = this.getPayPalApmSdkConfiguration(paymentMethod, currencyCode);\n\n await this.loadPayPalSdk(config);\n\n if (!this.window.bigCommercePaymentsApms) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.window.bigCommercePaymentsApms;\n }\n\n async getPayPalMessages(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n ): Promise {\n if (!this.window.bigCommercePaymentsMessages) {\n const paypalSdkMessagesConfig = this.getPayPalSdkMessagesConfiguration(\n paymentMethod,\n currencyCode,\n );\n\n await this.loadPayPalSdk(paypalSdkMessagesConfig);\n }\n\n if (!this.window.bigCommercePaymentsMessages) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.bigCommercePaymentsMessages;\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 { intent, clientId, merchantId, attributionId } = initializationData;\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit: true,\n components: ['fastlane', 'three-domain-secure'],\n currency: currencyCode,\n intent,\n },\n attributes: {\n 'data-client-metadata-id': sessionId.replace(/-/g, ''),\n 'data-namespace': 'bigCommercePaymentsFastlaneSdk',\n 'data-partner-attribution-id': attributionId,\n 'data-sdk-client-token': clientToken,\n },\n };\n }\n\n private getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage = true,\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 buyerCountry,\n attributionId,\n isHostedCheckoutEnabled,\n isDeveloperModeApplicable,\n } = initializationData;\n\n const commit = isHostedCheckoutEnabled || initializesOnCheckoutPage;\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit,\n components: ['googlepay'],\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 'data-namespace': 'bigCommercePaymentsGooglePay',\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 = this.filterFundingOptions(enabledAlternativePaymentMethods);\n const disableAPMsFunding = this.filterFundingOptions(\n availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n ),\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': 'bigCommercePaymentsApms',\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': 'bigCommercePaymentsMessages',\n 'data-partner-attribution-id': attributionId,\n },\n };\n }\n\n /**\n *\n * Utils methods\n *\n */\n private filterFundingOptions(fundingOptions: FundingType[] | undefined): FundingType[] {\n const fundingTypesToBeFiltered = ['klarna', 'afterpay'];\n\n if (!fundingOptions) {\n return [];\n }\n\n return fundingOptions.filter(\n (fundingOption: FundingType) => !fundingTypesToBeFiltered.includes(fundingOption),\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 { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport PayPalSdkHelper from './paypal-sdk-helper';\n\nexport default function createBigCommercePaymentsSdk(): PayPalSdkHelper {\n return new PayPalSdkHelper(createScriptLoader());\n}\n","interface CookieOptions {\n expires?: Date;\n path?: string;\n domain?: string;\n secure?: boolean;\n}\n\nexport default class CookieStorage {\n static get(name: string): string | null {\n const cookieKey = `${encodeURIComponent(`${name}`)}=`;\n const cookie = document.cookie;\n\n let value = null;\n\n const firstIndex = cookie.indexOf(cookieKey);\n\n if (firstIndex > -1) {\n let lastIndex = cookie.indexOf(';', firstIndex);\n\n if (lastIndex === -1) {\n lastIndex = cookie.length;\n }\n\n value = decodeURIComponent(cookie.substring(firstIndex + cookieKey.length, lastIndex));\n }\n\n return value;\n }\n\n static set(name: string, value: string, options: CookieOptions = { secure: true }) {\n let cookieText = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;\n\n const { expires, path, domain, secure } = options;\n\n if (expires) {\n cookieText += `; expires=${expires.toUTCString()}`;\n } else {\n const now = new Date();\n // info: default cookie expiration time after setup\n const minutes = 60;\n\n now.setTime(now.getTime() + minutes * 60 * 1000);\n\n cookieText += `; expires=${now.toUTCString()}`;\n }\n\n if (path) {\n cookieText += `; path=${path}`;\n }\n\n if (domain) {\n cookieText += `; domain=${domain}`;\n }\n\n if (secure) {\n cookieText += '; secure';\n }\n\n document.cookie = cookieText;\n }\n\n static remove(name: string, options?: CookieOptions) {\n CookieStorage.set(name, '', { expires: new Date(0), ...options });\n }\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 { CookieStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport {\n PayPalFastlane,\n PayPalFastlaneAddress,\n PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneLookupCustomerByEmailResult,\n PayPalFastlaneProfileCard,\n PayPalFastlaneProfileName,\n PayPalFastlaneProfilePhone,\n PayPalFastlaneProfileToBcCustomerDataMappingResult,\n PayPalFastlaneSdk,\n PayPalFastlaneStylesOption,\n PayPalHostWindow,\n} from './bigcommerce-payments-types';\n\nexport default class BigCommercePaymentsFastlaneUtils {\n private window: PayPalHostWindow;\n\n constructor() {\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.bigCommercePaymentsFastlane) {\n const defaultStyles = {\n root: {\n backgroundColorPrimary: 'transparent',\n },\n };\n\n this.window.bigCommercePaymentsFastlane = await paypalFastlaneSdk.Fastlane({\n styles: styles || defaultStyles,\n });\n }\n\n return this.window.bigCommercePaymentsFastlane;\n }\n\n getPayPalFastlaneOrThrow(): PayPalFastlane {\n if (!this.window.bigCommercePaymentsFastlane) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.bigCommercePaymentsFastlane;\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 *\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(sessionId: string): void {\n const expires = new Date();\n\n expires.setDate(expires.getDate() + 14); // 2 weeks expiry\n\n const cookiesOption = {\n expires,\n secure: true,\n };\n\n CookieStorage.set('bc-fastlane-sessionId', sessionId, cookiesOption);\n }\n\n removeStorageSessionId(): void {\n CookieStorage.remove('bc-fastlane-sessionId');\n }\n\n getStorageSessionId(): string {\n return CookieStorage.get('bc-fastlane-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 BigCommercePaymentsFastlaneUtils from './bigcommerce-payments-fastlane-utils';\n\nexport default function createBigCommercePaymentsFastlaneUtils(): BigCommercePaymentsFastlaneUtils {\n return new BigCommercePaymentsFastlaneUtils();\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 BigCommercePaymentsFastlaneUtils,\n BigCommercePaymentsInitializationData,\n getFastlaneStyles,\n PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneStylesOption,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsFastlaneCustomerInitializeOptions, {\n WithBigCommercePaymentsFastlaneCustomerInitializeOptions,\n} from './bigcommerce-payments-fastlane-customer-initialize-options';\n\nexport default class BigCommercePaymentsFastlaneCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsSdk: PayPalSdkHelper,\n private bigCommercePaymentsFastlaneUtils: BigCommercePaymentsFastlaneUtils,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions &\n WithBigCommercePaymentsFastlaneCustomerInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_fastlane } = 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.bigCommercePaymentsSdk.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n );\n\n await this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(\n paypalFastlaneSdk,\n isTestModeEnabled,\n this.getFastlaneStyles(methodId, bigcommerce_payments_fastlane),\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 await this.paymentIntegrationService.updatePaymentProviderCustomer({\n authenticationState: undefined,\n addresses: undefined,\n instruments: undefined,\n });\n\n this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId();\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 } =\n await this.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(customerEmail);\n\n const authenticationResult =\n await this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(\n customerContextId,\n );\n\n const isAuthenticationFlowCanceled =\n authenticationResult.authenticationState === PayPalFastlaneAuthenticationState.CANCELED;\n\n await this.updateCustomerDataState(methodId, authenticationResult);\n\n if (isAuthenticationFlowCanceled) {\n this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId();\n } else {\n this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(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.bigCommercePaymentsFastlaneUtils.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(\n methodId,\n );\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 bigcommerce_payments_fastlane:\n | BigCommercePaymentsFastlaneCustomerInitializeOptions\n | 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 bigcommerce_payments_fastlane?.styles,\n );\n }\n}\n","import {\n createBigCommercePaymentsFastlaneUtils,\n createBigCommercePaymentsSdk,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsFastlaneCustomerStrategy from './bigcommerce-payments-fastlane-customer-strategy';\n\nconst createBigCommercePaymentsFastlaneCustomerStrategy: CustomerStrategyFactory<\n BigCommercePaymentsFastlaneCustomerStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsFastlaneCustomerStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsSdk(),\n createBigCommercePaymentsFastlaneUtils(),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsFastlaneCustomerStrategy, [\n { id: 'bigcommerce_payments_fastlane' }, // this method id will be provided for users from test group\n { id: 'bigcommerce_payments_creditcards' }, // this method id will be provided for users from control group\n]);\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsPayLaterCustomerInitializeOptions, {\n WithBigCommercePaymentsPayLaterCustomerInitializeOptions,\n} from './bigcommerce-payments-paylater-customer-initialize-options';\n\nexport default class BigCommercePaymentsPayLaterCustomerStrategy implements CustomerStrategy {\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions &\n WithBigCommercePaymentsPayLaterCustomerInitializeOptions,\n ): Promise {\n const { bigcommerce_payments_paylater, 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 (!bigcommerce_payments_paylater) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_paylater\" argument is not provided.',\n );\n }\n\n if (!bigcommerce_payments_paylater.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_paylater.container\" argument is not provided.',\n );\n }\n\n if (\n bigcommerce_payments_paylater.onClick &&\n typeof bigcommerce_payments_paylater.onClick !== 'function'\n ) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_paylater.onClick\" argument is not a function.',\n );\n }\n\n this.onError = bigcommerce_payments_paylater.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 const paypalSdk = await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n // eslint-disable-next-line no-console\n console.error(\n '[BC BigCommercePayments PayLater]: button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n this.renderButton(methodId, bigcommerce_payments_paylater);\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 bigCommercePaymentsPayLater: BigCommercePaymentsPayLaterCustomerInitializeOptions,\n ): void {\n const { container, onComplete, onClick } = bigCommercePaymentsPayLater;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_paylater',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.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: BigCommercePaymentsButtonsOptions = {\n fundingSource,\n style: this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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 =\n this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsPayLaterCustomerStrategy from './bigcommerce-payments-paylater-customer-strategy';\n\nconst createBigCommercePaymentsPayLaterCustomerStrategy: CustomerStrategyFactory<\n BigCommercePaymentsPayLaterCustomerStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsPayLaterCustomerStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsPayLaterCustomerStrategy, [\n { id: 'bigcommerce_payments_paylater' },\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsVenmoCustomerInitializeOptions, {\n WithBigCommercePaymentsVenmoCustomerInitializeOptions,\n} from './bigcommerce-payments-venmo-customer-initialize-options';\n\nexport default class BigCommercePaymentsVenmoCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBigCommercePaymentsVenmoCustomerInitializeOptions,\n ): Promise {\n const { bigcommerce_payments_venmo, 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 (!bigcommerce_payments_venmo) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_venmo\" argument is not provided.',\n );\n }\n\n if (!bigcommerce_payments_venmo.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_venmo.container\" argument is not provided.',\n );\n }\n\n if (\n bigcommerce_payments_venmo.onClick &&\n typeof bigcommerce_payments_venmo.onClick !== 'function'\n ) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_venmo.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 const paypalSdk = await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n // eslint-disable-next-line no-console\n console.error(\n '[BC Payments Venmo]: Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n this.renderButton(methodId, bigcommerce_payments_venmo);\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 bigcommerce_payments_venmo: BigCommercePaymentsVenmoCustomerInitializeOptions,\n ): void {\n const { container, onClick } = bigcommerce_payments_venmo;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.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: BigCommercePaymentsButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle({\n ...checkoutTopButtonStyles,\n height: DefaultCheckoutButtonHeight,\n }),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_venmo',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.removeElement(container);\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsVenmoCustomerStrategy from './bigcommerce-payments-venmo-customer-strategy';\n\nconst createBigCommercePaymentsVenmoCustomerStrategy: CustomerStrategyFactory<\n BigCommercePaymentsVenmoCustomerStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsVenmoCustomerStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsVenmoCustomerStrategy, [\n { id: 'bigcommerce_payments_venmo' },\n]);\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 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 {\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 { 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 { 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","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 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 { BraintreePaypalCheckout, BraintreePaypalSdkCreatorConfig } from './braintree';\nimport { BraintreeError } from './types';\n\nlet paypalSdkPromise: Promise | null = null;\n\nexport default function loadPayPalSDKOnce(\n paypalCheckout: BraintreePaypalCheckout,\n config: BraintreePaypalSdkCreatorConfig,\n): Promise {\n if (!paypalSdkPromise) {\n paypalSdkPromise = new Promise((resolve, reject) => {\n paypalCheckout.loadPayPalSDK(config, (err: null | undefined | BraintreeError) => {\n if (err) {\n paypalSdkPromise = null;\n\n reject(err);\n } else {\n resolve(paypalCheckout);\n }\n });\n });\n }\n\n return paypalSdkPromise;\n}\n\n// for testing purposes\nexport function resetLoadPayPalSDKOncePromise() {\n paypalSdkPromise = null;\n}\n","// 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 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 enum MessagingPlacements {\n CART = 'cart',\n HOME = 'homepage',\n PAYMENT = 'payment',\n PRODUCT = 'product',\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 | string;\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';\nimport { isEmpty } from 'lodash';\n\nimport {\n Address,\n CancellablePromise,\n CreditCardInstrument,\n LegacyAddress,\n NonceInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethodCancelledError,\n UnsupportedBrowserError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { Overlay } from '@bigcommerce/checkout-sdk/ui';\n\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport loadPayPalSDKOnce from './load-paypal-sdk-once';\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 BraintreeRequestData,\n BraintreeShippingAddressOverride,\n BraintreeThreeDSecure,\n BraintreeThreeDSecureOptions,\n BraintreeTokenizationDetails,\n BraintreeTokenizePayload,\n BraintreeVenmoCheckout,\n BraintreeVenmoCreatorConfig,\n BraintreeVerifyPayload,\n PAYPAL_COMPONENTS,\n TokenizationPayload,\n} from './types';\nimport isBraintreeError from './utils/is-braintree-error';\nimport isCreditCardInstrumentLike from './utils/is-credit-card-instrument-like';\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 private threeDSecureOptions?: BraintreeThreeDSecureOptions;\n private threeDS?: Promise;\n private venmoCheckout?: BraintreeVenmoCheckout;\n\n constructor(\n private braintreeScriptLoader: BraintreeScriptLoader,\n private braintreeHostWindow: BraintreeHostWindow,\n private overlay?: Overlay,\n ) {}\n\n initialize(clientToken: string, threeDSecureOptions?: BraintreeThreeDSecureOptions) {\n this.clientToken = clientToken;\n this.threeDSecureOptions = threeDSecureOptions;\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 void loadPayPalSDKOnce(braintreePaypalCheckout, paypalSdkLoadConfig).then(\n paypalSdkLoadCallback,\n );\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 async get3DS(): Promise {\n if (!this.threeDS) {\n this.threeDS = Promise.all([\n this.getClient(),\n this.braintreeScriptLoader.load3DS(),\n ]).then(([client, threeDSecure]) => threeDSecure.create({ client, version: 2 }));\n }\n\n return this.threeDS;\n }\n\n async getVenmoCheckout(\n venmoConfig?: BraintreeVenmoCreatorConfig,\n ): Promise {\n if (!this.venmoCheckout) {\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 ...(venmoConfig || {}),\n };\n\n this.venmoCheckout = await new Promise((resolve, reject) => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n venmoCheckout.create(\n venmoCheckoutConfig,\n (error: BraintreeError, braintreeVenmoCheckout: BraintreeVenmoCheckout) => {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (error) {\n return reject(error);\n }\n\n if (!braintreeVenmoCheckout.isBrowserSupported()) {\n return reject(new UnsupportedBrowserError());\n }\n\n resolve(braintreeVenmoCheckout);\n },\n );\n });\n }\n\n return this.venmoCheckout;\n }\n\n /*\n Braintree Credit Card and Braintree Hosted Form\n */\n async verifyCard(\n payment: Payment,\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 async tokenizeCard(payment: Payment, billingAddress: Address): 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.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 challenge3DSVerification(\n tokenizationPayload: TokenizationPayload,\n amount: number,\n ): Promise {\n const threeDSecure = await this.get3DS();\n\n return this.present3DSChallenge(threeDSecure, amount, tokenizationPayload);\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 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 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\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 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 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 // eslint-disable-next-line @typescript-eslint/no-use-before-define\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 if (addFrame) {\n addFrame(error, iframe, cancelVerifyCard);\n }\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","import { CreditCardInstrument } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isCreditCardInstrumentLike(\n instrument: unknown,\n): instrument is CreditCardInstrument {\n if (typeof instrument !== 'object' || instrument === null) {\n return false;\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const creditCardInstrument = instrument as Partial>;\n\n return (\n typeof creditCardInstrument.ccExpiry === 'object' &&\n creditCardInstrument.ccExpiry !== null &&\n typeof creditCardInstrument.ccNumber === 'string' &&\n typeof creditCardInstrument.ccName === 'string'\n );\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 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\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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-initialize-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\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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","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","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 { CookieStorage } 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 ) {}\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.saveSessionIdToCookies(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.removeSessionIdFromCookies();\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.saveSessionIdToCookies(cart.id);\n\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 * Session id management\n *\n */\n getSessionIdFromCookies(): string {\n return CookieStorage.get('bc-fastlane-sessionId') || '';\n }\n\n saveSessionIdToCookies(sessionId: string): void {\n const expires = new Date();\n\n expires.setDate(expires.getDate() + 14); // 2 weeks expiry\n\n CookieStorage.set('bc-fastlane-sessionId', sessionId, {\n expires,\n secure: true,\n });\n }\n\n removeSessionIdFromCookies(): void {\n CookieStorage.remove('bc-fastlane-sessionId');\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, binDetails } = 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: binDetails?.bin || '',\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 BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n );\n const braintreeFastlaneUtils = new BraintreeFastlaneUtils(\n paymentIntegrationService,\n braintreeIntegrationService,\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), hostWindow, braintreeSDKVersionManager),\n );\n\n return new BraintreeVisaCheckoutCustomerStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeSdk,\n );\n};\n\nexport default toResolvableModule(createBraintreeVisaCheckoutCustomerStrategy, [\n { id: 'braintreevisacheckout' },\n]);\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 { isOperaWindow } from '../is-opera-window';\nimport { isReactNativeWindow } from '../is-react-native-window';\n\nexport function isWebView(): boolean {\n if (typeof window === 'undefined') {\n return false;\n }\n\n if (isReactNativeWindow(window)) {\n return true;\n }\n\n const userAgent =\n navigator.userAgent || navigator.vendor || (isOperaWindow(window) ? window.opera : '');\n\n const isAndroidWebView = /android.+; wv/i.test(userAgent);\n const isIOSWebView =\n /iPhone|iPod|iPad/i.test(userAgent) &&\n /AppleWebKit/i.test(userAgent) &&\n !/Safari/i.test(userAgent);\n\n return isAndroidWebView || isIOSWebView;\n}\n","interface ReactNativeWindow extends Window {\n ReactNativeWebView: {\n postMessage(msg: string): void;\n };\n}\n\nexport function isReactNativeWindow(window: Window): window is ReactNativeWindow {\n return 'ReactNativeWebView' in window;\n}\n","interface OperaWindow extends Window {\n opera: string;\n}\n\nexport function isOperaWindow(window: Window): window is OperaWindow {\n return 'opera' in window;\n}\n","import { BigCommercePaymentsIntent } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 offerInfo?: Offers;\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 NewOfferInfo {\n newOfferInfo?: Offers;\n}\n\nexport interface Offers {\n offers: OfferInfoItem[];\n}\n\nexport interface GooglePayError {\n message: string;\n reason: ErrorReasonType;\n intent: CallbackTriggerType;\n}\n\nexport enum ErrorReasonType {\n OFFER_INVALID = 'OFFER_INVALID',\n PAYMENT_DATA_INVALID = 'PAYMENT_DATA_INVALID',\n SHIPPING_ADDRESS_INVALID = 'SHIPPING_ADDRESS_INVALID',\n SHIPPING_ADDRESS_UNSERVICEABLE = 'SHIPPING_ADDRESS_UNSERVICEABLE',\n SHIPPING_OPTION_INVALID = 'SHIPPING_OPTION_INVALID',\n OTHER_ERROR = 'OTHER_ERROR',\n}\n\nexport interface OfferInfoItem {\n redemptionCode: string;\n description: string;\n}\n\nexport interface HandleCouponsOut {\n newOfferInfo: GooglePayPaymentDataRequest['offerInfo'];\n error?: GooglePayError;\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 offerData: {\n redemptionCodes: string[];\n };\n}\n\nexport interface GooglePayPaymentOptions {\n paymentDataCallbacks?: {\n onPaymentDataChanged(\n intermediatePaymentData: IntermediatePaymentData,\n ): onPaymentDataChangedOut;\n };\n}\n\nexport type onPaymentDataChangedOut = Promise<\n | (NewTransactionInfo & NewShippingOptionParameters & NewOfferInfo & { error?: GooglePayError })\n | void\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) => Promise;\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 isWebViewExperimentOn?: boolean;\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 GooglePayBigCommercePaymentsInitializationData\n 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?: BigCommercePaymentsIntent;\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 shopperLanguage: string;\n useNewStripeJsVersion?: boolean;\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 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 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 | GooglePayBigCommercePaymentsInitializationData;\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","/**\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 * A container for loading spinner.\n */\n loadingContainerId?: string;\n\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 BIGCOMMERCE_PAYMENTS = 'googlepay_bigcommerce_payments',\n CHECKOUT_COM = 'googlepaycheckoutcom',\n CYBERSOURCE_V2 = 'googlepaycybersourcev2',\n ORBITAL = 'googlepayorbital',\n STRIPE = 'googlepaystripe',\n STRIPE_UPE = 'googlepaystripeupe',\n STRIPE_OCS = 'googlepaystripeocs',\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 { 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';\nimport { isExperimentEnabled, isWebView } from '@bigcommerce/checkout-sdk/utility';\n\nimport isGooglePayCardNetworkKey from '../guards/is-google-pay-card-network-key';\nimport {\n CallbackIntentsType,\n CallbackTriggerType,\n ErrorReasonType,\n ExtraPaymentData,\n GooglePayCardDataResponse,\n GooglePayCardNetwork,\n GooglePayCardParameters,\n GooglePayError,\n GooglePayFullBillingAddress,\n GooglePayGatewayParameters,\n GooglePayInitializationData,\n GooglePayMerchantInfo,\n GooglePayPaymentDataRequest,\n GooglePayRequiredPaymentData,\n GooglePaySetExternalCheckoutData,\n GooglePayTransactionInfo,\n HandleCouponsOut,\n IntermediatePaymentData,\n ShippingOptionParameters,\n TotalPriceStatusType,\n} from '../types';\n\nexport default class GooglePayGateway {\n private _getPaymentMethodFn?: () => PaymentMethod;\n private _isBuyNowFlow = false;\n private _shouldRequestShipping = true;\n private _currencyCode?: string;\n private _currencyService?: CurrencyService;\n private _isWebViewExperimentOn: null | boolean = null;\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 customFields = [],\n } = this._paymentIntegrationService.getState().getBillingAddress() || {};\n\n return {\n ...this._mapToAddressRequestBody(billingAddress, company, phone, customFields),\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 if (!nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\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 CallbackTriggerType.OFFER,\n ];\n\n const initializationTrigger = [CallbackTriggerType.INITIALIZE];\n const addressChangeTriggers = [\n CallbackTriggerType.INITIALIZE,\n CallbackTriggerType.SHIPPING_ADDRESS,\n ];\n const shippingOptionsChangeTriggers = [CallbackTriggerType.SHIPPING_OPTION];\n const offerChangeTriggers = [CallbackTriggerType.OFFER];\n\n return {\n availableTriggers,\n initializationTrigger,\n addressChangeTriggers,\n shippingOptionsChangeTriggers,\n offerChangeTriggers,\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 const { getCartOrThrow } = this._paymentIntegrationService.getState();\n\n if (this._isBuyNowFlow) {\n currencyCode = this._getCurrencyCodeOrThrow();\n } else {\n currencyCode = getCartOrThrow().currency.code;\n }\n\n const countryCode = this.getGooglePayInitializationData().storeCountry;\n\n if (this.isWebViewWithRestrictions()) {\n const totalPrice = this.getTotalPrice();\n\n return {\n ...(countryCode && { countryCode }),\n currencyCode,\n totalPrice,\n totalPriceStatus: TotalPriceStatusType.ESTIMATED,\n };\n }\n\n return {\n ...(countryCode && { countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.ESTIMATED,\n totalPrice: '0',\n };\n }\n\n isWebViewWithRestrictions(): boolean {\n if (this._isWebViewExperimentOn !== null) {\n return this._isWebViewExperimentOn && isWebView();\n }\n\n return isWebView();\n }\n\n setIsWebViewExperimentOn(isWebViewExperimentOn: boolean): void {\n this._isWebViewExperimentOn = isWebViewExperimentOn;\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, getStoreConfigOrThrow } =\n this._paymentIntegrationService.getState();\n const { decimalPlaces } = getCartOrThrow().currency;\n const isRoundingExperimentOn = isExperimentEnabled(\n getStoreConfigOrThrow().checkoutSettings.features,\n 'PI-5075.google_pay_round_total_price_to_max_2_decimal_places',\n );\n const maxDecimalPlaces = isRoundingExperimentOn\n ? Math.min(decimalPlaces, 2)\n : decimalPlaces;\n const totalPrice = round(getCheckoutOrThrow().outstandingBalance, maxDecimalPlaces).toFixed(\n maxDecimalPlaces,\n );\n\n return totalPrice;\n }\n\n async handleCoupons(\n offerData: IntermediatePaymentData['offerData'],\n ): Promise {\n const { redemptionCodes: newCouponsState = [] } = offerData;\n const { offers: appliedCoupons } = this.getAppliedCoupons() || {};\n let error;\n\n await newCouponsState.reduce(async (promise, code) => {\n await promise;\n\n const exists = (appliedCoupons || []).some(\n ({ redemptionCode }) => redemptionCode === code,\n );\n\n if (exists) {\n return;\n }\n\n const appliedCouponError = await this.applyCoupon(code);\n\n if (appliedCouponError) {\n error = appliedCouponError;\n }\n }, Promise.resolve());\n\n await (appliedCoupons || []).reduce(async (promise, coupon) => {\n await promise;\n\n const stillExists = newCouponsState.includes(coupon.redemptionCode);\n\n if (!stillExists) {\n await this._paymentIntegrationService.removeCoupon(coupon.redemptionCode);\n }\n }, Promise.resolve());\n\n return {\n newOfferInfo: this.getAppliedCoupons(),\n error,\n };\n }\n\n getAppliedCoupons(): GooglePayPaymentDataRequest['offerInfo'] {\n const state = this._paymentIntegrationService.getState();\n const { coupons } = state.getCheckout() || {};\n\n const offers = (coupons || []).map((coupon) => {\n const { displayName, code } = coupon;\n\n return {\n redemptionCode: code,\n description: displayName,\n };\n });\n\n return {\n offers,\n };\n }\n\n async applyCoupon(code: string): Promise {\n let error: GooglePayError | undefined;\n\n try {\n await this._paymentIntegrationService.applyCoupon(code);\n } catch (e) {\n if (e instanceof Error) {\n error = {\n reason: ErrorReasonType.OFFER_INVALID,\n message: e.message,\n intent: CallbackTriggerType.OFFER,\n };\n }\n\n return error;\n }\n }\n\n setShouldRequestShipping(isRequired: boolean): void {\n this._shouldRequestShipping = isRequired;\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, getStoreConfigOrThrow, getShippingAddress } =\n this._paymentIntegrationService.getState();\n const storeConfig = getStoreConfigOrThrow();\n const features = storeConfig.checkoutSettings.features;\n const checkWithExperiment = isExperimentEnabled(\n features,\n 'PI-4290.google_pay_require_shipping_address',\n );\n\n let shippingContextRequiresCheck: boolean;\n\n if (checkWithExperiment) {\n shippingContextRequiresCheck = this._shouldRequestShipping;\n } else {\n shippingContextRequiresCheck = getShippingAddress() === undefined;\n }\n\n return shippingContextRequiresCheck && itemsRequireShipping(getCartOrThrow(), storeConfig);\n }\n\n private _mapToAddressRequestBody(\n address: GooglePayFullBillingAddress,\n company: string,\n phone: string,\n customFields?: AddressRequestBody['customFields'],\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: 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({\n id,\n cost,\n description,\n additionalDescription,\n }: ShippingOption) {\n const formattedCost = this._currencyService?.toCustomerCurrency(cost);\n\n return {\n id,\n label: `${formattedCost || cost} ${description}`,\n description: additionalDescription,\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","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 GooglePayError,\n GooglePayInitializationData,\n GooglePayPaymentOptions,\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 this._googlePayPaymentProcessor.setIsWebViewExperimentOn(\n !!paymentMethod.initializationData?.isWebViewExperimentOn,\n );\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 if (this._googlePayPaymentProcessor.isWebViewWithRestrictions()) {\n return {};\n }\n\n return {\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({\n callbackTrigger,\n shippingAddress,\n shippingOptionData,\n offerData,\n }) => {\n const {\n availableTriggers,\n addressChangeTriggers,\n shippingOptionsChangeTriggers,\n offerChangeTriggers,\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 const { newOfferInfo = undefined, error: couponsError = undefined } =\n offerChangeTriggers.includes(callbackTrigger)\n ? await this._googlePayPaymentProcessor.handleCoupons(offerData)\n : {};\n\n // We can add another errors if needed 'couponsError || shippingError || anotherError'\n const error: GooglePayError | undefined = couponsError;\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 ...(newOfferInfo && {\n newOfferInfo,\n }),\n ...(error && {\n error,\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) => Promise {\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\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","import { FormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\n\nimport {\n AddressRequestBody,\n BillingAddressRequestBody,\n guard,\n NotInitializedError,\n NotInitializedErrorType,\n Omit,\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 HandleCouponsOut,\n IntermediatePaymentData,\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 | undefined {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n return;\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 setShouldRequestShipping(isRequired: boolean): void {\n return this._gateway.setShouldRequestShipping(isRequired);\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 async handleCoupons(\n offerData: IntermediatePaymentData['offerData'],\n ): Promise {\n return this._gateway.handleCoupons(offerData);\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 isWebViewWithRestrictions(): boolean {\n return this._gateway.isWebViewWithRestrictions();\n }\n\n setIsWebViewExperimentOn(isWebViewExperimentOn: boolean): void {\n return this._gateway.setIsWebViewExperimentOn(isWebViewExperimentOn);\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\n const isWebViewLogic = this._gateway.isWebViewWithRestrictions()\n ? {\n shippingOptionRequired: false,\n }\n : {\n callbackIntents: this._gateway.getCallbackIntents(),\n offerInfo: this._gateway.getAppliedCoupons(),\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 ...isWebViewLogic,\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","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 { PaymentMethod } from '@bigcommerce/checkout-sdk/payment-integration-api';\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\n/**\n * The PaymentIntent object.\n */\nexport interface PaymentIntent {\n /**\n * Unique identifier for the object.\n */\n id: string;\n\n /**\n * The client secret of the PaymentIntent. Used for client-side retrieval using a publishable key.\n */\n client_secret?: 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 payment_method_options?: StripePIPaymentMethodOptions;\n}\n\nexport interface StripePIPaymentMethodSavingOptions {\n setup_future_usage?: StripeInstrumentSetupFutureUsage;\n verification_method?: string;\n}\n\nexport interface StripePIPaymentMethodOptions {\n card?: StripePIPaymentMethodSavingOptions;\n us_bank_account?: StripePIPaymentMethodSavingOptions;\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 * 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 StripeCustomFont = CssFontSource | CustomFontSource;\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 StripeCheckoutSessionConfirmationError {\n code?: string;\n message: string;\n paymentFailed?: {\n declineCode?: string;\n };\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: StripeElementEvent, 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\nexport interface StripeCurrencyEvent extends StripeEvent {\n value: {\n currency: string;\n };\n}\n\nexport interface 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 =\n | StripeCurrencyEvent\n | StripeShippingEvent\n | StripeCustomerEvent\n | StripePaymentEvent\n | StripeLinkV2Event;\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
& { country: string };\n\nexport interface StripeAddressValues {\n name?: string;\n address?: AddressOptions;\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 allow_redisplay?: 'always' | 'limited' | 'unspecified';\n}\n\n/**\n * Parameters that will be passed on to the Stripe API to confirm the PaymentIntent.\n */\nexport interface StripeConfirmParams {\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?: StripeConfirmParams;\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 clientSecret?: string;\n}\n\nexport interface StripeCheckoutSessionConfirmPaymentData {\n redirect?: StripeStringConstants.ALWAYS | StripeStringConstants.IF_REQUIRED;\n returnUrl?: string;\n}\n\nexport interface FieldsOptions {\n billingDetails?: AutoOrNever | BillingDetailsProperties;\n phone?: string;\n}\n\nexport interface WalletOptions {\n applePay?: AutoOrNever;\n googlePay?: AutoOrNever;\n link?: AutoOrNever;\n}\n\nexport interface TermOptions {\n card?: AutoOrNever;\n}\n\nexport interface StripeLayoutOptions {\n type?: 'accordion' | 'tabs';\n linkInAccordion?: boolean;\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 | PaymentDefaultValues;\n validation?: validationElement;\n display?: { name: StripeDisplayName };\n terms?: TermOptions;\n layout?: StripeLayoutOptions;\n paymentMethodOrder?: string[];\n // Link v2 options\n lineItems?: LineItem[];\n allowedShippingCountries?: string[];\n shippingAddressRequired?: boolean;\n shippingRates?: StripeLinkV2ShippingRate[];\n billingAddressRequired?: boolean;\n emailRequired?: boolean;\n phoneNumberRequired?: boolean;\n paymentMethods?: {\n link: StripeStringConstants.AUTO;\n applePay: StripeStringConstants.NEVER;\n googlePay: StripeStringConstants.NEVER;\n amazonPay: StripeStringConstants.NEVER;\n paypal: StripeStringConstants.NEVER;\n klarna: StripeStringConstants.NEVER;\n };\n buttonHeight?: number;\n savePaymentMethod?: StripeSavePaymentMethod;\n}\n\ninterface validationElement {\n phone?: validationRequiredElement;\n}\n\ninterface validationRequiredElement {\n required?: string;\n}\n\ninterface PaymentDefaultValues {\n savePaymentMethod?: boolean;\n billingDetails?: BillingDetailsOptions;\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 StripeDisplayName {\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: StripeDisplayName;\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\nexport enum StripeCheckoutSessionStatusType {\n Open = 'open',\n Expired = 'expired',\n Complete = 'complete',\n}\n\nexport enum StripeCheckoutSessionPaymentStatus {\n Paid = 'paid',\n UnPaid = 'unpaid',\n NoPaymentRequired = 'no_payment_required',\n}\n\nexport interface StripeCheckoutSessionStatus {\n type: StripeCheckoutSessionStatusType;\n paymentStatus: StripeCheckoutSessionPaymentStatus;\n}\n\nexport interface StripeCheckoutSessionAmount {\n minorUnitsAmount: number;\n amount: string;\n}\n\nexport interface StripeCheckoutSessionTotal {\n appliedBalance: StripeCheckoutSessionAmount;\n balanceAppliedToNextInvoice: boolean;\n discount: StripeCheckoutSessionAmount;\n shippingRate: StripeCheckoutSessionAmount;\n subtotal: StripeCheckoutSessionAmount;\n taxExclusive: StripeCheckoutSessionAmount;\n taxInclusive: StripeCheckoutSessionAmount;\n total: StripeCheckoutSessionAmount;\n}\n\nexport interface StripeCheckoutSession {\n id: string;\n savedPaymentMethods?: StripeSavedPaymentMethod[];\n billingAddress: StripeAddressValues;\n businessName: string;\n canConfirm: boolean;\n currency: string;\n email: string;\n phoneNumber: string;\n shipping: unknown;\n shippingAddress: StripeAddressValues;\n shippingOptions: unknown;\n status: StripeCheckoutSessionStatus;\n tax: unknown;\n taxAmounts: unknown;\n total: StripeCheckoutSessionTotal;\n}\n\nexport interface StripeCheckoutInstance {\n loadActions(): Promise;\n createPaymentElement(options?: StripeElementsCreateOptions): StripeElement;\n getPaymentElement(): StripeElement | null;\n getCurrencySelectorElement(): StripeElement | null;\n createCurrencySelectorElement(): StripeElement;\n}\n\nexport enum StripeLoadActionsResultType {\n SUCCESS = 'success',\n ERROR = 'error',\n}\n\nexport interface StripeLoadActionsResult {\n type: StripeLoadActionsResultType;\n error?: { message: string };\n actions?: StripeCheckoutSessionActions;\n}\n\nexport interface StripeCheckoutSessionActionResult {\n type: StripeLoadActionsResultType;\n error?: StripeCheckoutSessionConfirmationError;\n session?: StripeCheckoutSession;\n}\n\nexport interface StripeCheckoutSessionActions {\n updateEmail(email: string): Promise;\n updateShippingAddress(\n shippingAddress: StripeAddressValues,\n ): Promise;\n updateBillingAddress(\n billingAddress: StripeAddressValues,\n ): Promise;\n getSession(): Promise;\n confirm(\n options: StripeCheckoutSessionConfirmPaymentData,\n ): Promise;\n}\n\nexport interface StripeSavedPaymentMethod {\n id: string;\n type: string;\n billingDetails: BillingDetailsOptions;\n card?: StripeCardDetails;\n usBankAccount?: StripeUsBankAccountDetails;\n}\n\nexport interface StripeCardDetails {\n brand: string;\n last4: string;\n expMonth: number;\n expYear: number;\n}\n\nexport interface StripeUsBankAccountDetails {\n accountHolderType: string;\n accountType: string;\n bankName: string;\n last4: string;\n}\n\n/**\n * All available options are here https://stripe.com/docs/stripe-js/appearance-api#supported-css-properties\n */\nexport interface StripeAppearanceOptions {\n variables?: Record;\n\n rules?: Record>;\n}\n\nexport type StripeAppearanceValues = string | string[] | number | undefined;\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?: StripeCustomFont[];\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 * A token that represents the Stripe customer session.\n * Stripe documentation: https://docs.stripe.com/api/checkout/sessions\n */\n customerSessionClientSecret?: 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?: StripeAppearanceOptions;\n\n mode?: string;\n amount?: number;\n currency?: string;\n paymentMethodTypes?: string[];\n}\n\nexport interface StripeInitCheckoutOptions {\n clientSecret: string;\n elementsOptions?: StripeCheckoutSessionElementOptions;\n adaptivePricing?: {\n allowed: boolean;\n };\n defaultValues?: StripeCheckoutSessionDefaultValues;\n wallets?: any;\n}\n\nexport interface StripeCheckoutSessionElementOptions {\n appearance?: StripeAppearanceOptions;\n loader?: StripeStringConstants;\n fonts?: StripeCustomFont[];\n savedPaymentMethod?: {\n enableRedisplay?: StripeStringConstants;\n enableSave?: StripeStringConstants;\n };\n}\n\nexport interface StripeCheckoutSessionDefaultValues {\n billingAddress?: StripeAddressValues;\n shippingAddress?: StripeAddressValues;\n email?: string;\n phoneNumber?: 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?: StripeAppearanceOptions;\n mode?: string;\n amount?: number;\n currency?: string;\n}\n\nexport interface StripeClient {\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 initCheckout(options: StripeInitCheckoutOptions): Promise;\n}\n\nexport interface StripeResult {\n paymentIntent?: PaymentIntent;\n error?: StripeError;\n}\n\nexport interface StripeHostWindow extends Window {\n bcStripeClient?: StripeClient;\n bcStripeElements?: StripeElements;\n bcStripeCheckout?: StripeCheckoutInstance;\n Stripe?(\n stripePublishableKey: string,\n options?: StripeConfigurationOptions,\n ): T;\n}\n\nexport enum StripePaymentMethodType {\n CreditCard = 'card',\n ACH = 'us_bank_account',\n Link = 'link',\n EPS = 'eps',\n GRABPAY = 'grabpay',\n BANCONTACT = 'bancontact',\n IDEAL = 'ideal',\n ALIPAY = 'alipay',\n KLARNA = 'klarna',\n OCS = 'optimized_checkout',\n CHECKOUT_SESSION = 'checkout_session',\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 StripeJsVersion {\n V3 = 'v3',\n ACACIA = 'acacia',\n BASIL = 'basil',\n CLOVER = 'clover',\n}\n\nexport enum StripeElementType {\n PAYMENT = 'payment',\n AUTHENTICATION = 'linkAuthentication',\n SHIPPING = 'address',\n EXPRESS_CHECKOUT = 'expressCheckout',\n}\n\nexport enum StripePaymentIntentStatus {\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 StripePaymentMethod extends PaymentMethod {\n initializationData: StripeInitializationData;\n}\n\nexport interface StripeInitializationData {\n stripePublishableKey: string;\n stripeConnectedAccount: string;\n shopperLanguage: string;\n customerSessionToken?: string;\n enableLink?: boolean;\n allowRedisplayForStoredInstruments?: boolean;\n captureMethod?: 'automatic' | 'manual';\n useNewStripeJsVersion?: boolean;\n checkoutSessionEnabled?: boolean;\n sendSecondPaymentRequestOnStripeError?: boolean;\n adaptivePricingEnabled?: boolean;\n hasSectionOnTopOfPaymentsList?: 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\nexport enum StripeElementEvent {\n CLICK = 'click',\n CHANGE = 'change',\n READY = 'ready',\n SHIPPING_ADDRESS_CHANGE = 'shippingaddresschange',\n SHIPPING_RATE_CHANGE = 'shippingratechange',\n CONFIRM = 'confirm',\n CANCEL = 'cancel',\n LOADER_START = 'loaderstart',\n}\n\nexport interface LineItem {\n name: string;\n amount: number;\n}\n\nexport interface StripeSavePaymentMethod {\n maxVisiblePaymentMethods?: number;\n}\n\nexport enum StripeInstrumentSetupFutureUsage {\n ON_SESSION = 'on_session',\n OFF_SESSION = 'off_session',\n}\n\nexport interface StripeLinkV2Event {\n value?: null;\n billingDetails?: {\n name?: string;\n email?: string;\n phone?: string;\n address?: {\n line1?: string;\n city?: string;\n country?: string;\n postal_code?: string;\n state?: string;\n };\n };\n shippingAddress?: {\n name?: string;\n address?: {\n line1?: string;\n line2?: string;\n city?: string;\n country?: string;\n postal_code?: string;\n state?: string;\n };\n };\n address?: {\n line1?: string;\n city?: string;\n country?: string;\n postal_code?: string;\n state?: string;\n };\n shippingRate?: StripeLinkV2ShippingRate;\n elementType: string;\n expressPaymentType: string;\n resolve(data: StripeLinkV2EventResolveData): void;\n reject(): void;\n}\n\nexport interface StripeLinkV2EventResolveData {\n lineItems?: LineItem[];\n allowedShippingCountries?: string[];\n shippingAddressRequired?: boolean;\n shippingRates?: StripeLinkV2ShippingRate[];\n billingAddressRequired?: boolean;\n emailRequired?: boolean;\n phoneNumberRequired?: boolean;\n}\n\nexport interface StripeLinkV2ShippingRate {\n id: string;\n amount: number;\n displayName: string;\n}\n\nexport interface StripeLinkV2Options {\n clientSecret?: string;\n mode?: string;\n currency?: string;\n captureMethod?: 'automatic' | 'manual';\n amount?: number;\n}\n\nexport interface StripeFormattedPaymentPayload {\n cart_id: string;\n confirm: boolean;\n method?: string;\n credit_card_token?: { token: string };\n tokenized_ach?: { token: string };\n vault_payment_instrument?: boolean;\n set_as_default_stored_instrument?: boolean;\n client_side_error?: boolean;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n StripeCheckoutInstance,\n StripeClient,\n StripeElements,\n StripeElementsOptions,\n StripeHostWindow,\n StripeInitCheckoutOptions,\n StripeInitializationData,\n StripeJsVersion,\n} from './stripe';\n\nexport default class StripeScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private stripeWindow: StripeHostWindow = window,\n ) {}\n\n async getStripeClient(\n initializationData: StripeInitializationData,\n locale?: string,\n stripeJsVersion?: string,\n betas?: string[],\n apiVersion?: string,\n ): Promise {\n if (this.stripeWindow.bcStripeClient) {\n return this.stripeWindow.bcStripeClient;\n }\n\n const stripe = await this.load(stripeJsVersion);\n const { stripePublishableKey, stripeConnectedAccount } = initializationData;\n const options = {\n ...(stripeConnectedAccount ? { stripeAccount: stripeConnectedAccount } : {}),\n ...(locale ? { locale } : {}),\n ...(betas ? { betas } : {}),\n ...(apiVersion ? { apiVersion } : {}),\n };\n\n const stripeClient = stripe(stripePublishableKey, options);\n\n Object.assign(this.stripeWindow, { bcStripeClient: stripeClient });\n\n return stripeClient;\n }\n\n async getElements(\n stripeClient: StripeClient,\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 async getStripeCheckout(\n stripeClient: StripeClient,\n options: StripeInitCheckoutOptions,\n ): Promise {\n let stripeCheckout = await this.getStoredStripeCheckout(options);\n\n if (!stripeCheckout) {\n stripeCheckout = await stripeClient.initCheckout(options);\n\n Object.assign(this.stripeWindow, { bcStripeCheckout: stripeCheckout });\n }\n\n return stripeCheckout;\n }\n\n private async load(stripeJsVersion?: string) {\n if (!this.stripeWindow.Stripe) {\n await this.scriptLoader.loadScript(this.getScriptUrl(stripeJsVersion));\n\n if (!this.stripeWindow.Stripe) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.stripeWindow.Stripe;\n }\n\n private getScriptUrl(stripeJsVersion?: string) {\n if (!stripeJsVersion || stripeJsVersion === StripeJsVersion.V3) {\n return 'https://js.stripe.com/v3/';\n }\n\n return `https://js.stripe.com/${stripeJsVersion}/stripe.js`;\n }\n\n private async getStoredStripeCheckout(\n options: StripeInitCheckoutOptions,\n ): Promise {\n const stripeCheckout = this.stripeWindow.bcStripeCheckout;\n\n if (!stripeCheckout) {\n return undefined;\n }\n\n try {\n const { actions, error } = await stripeCheckout.loadActions();\n\n if (error || !actions) {\n this.logErrorToConsole(error);\n\n return undefined;\n }\n\n const stripeCheckoutSession = await actions.getSession();\n const stripeSessionIdFromOptions = options.clientSecret.split('_secret_')[0];\n\n if (stripeCheckoutSession.id === stripeSessionIdFromOptions) {\n return stripeCheckout;\n }\n } catch (error) {\n this.logErrorToConsole(error);\n\n return undefined;\n }\n\n return undefined;\n }\n\n private logErrorToConsole(error?: unknown) {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n error\n ? console.error(error)\n : console.error('No stripe checkout actions available on loadActions().');\n }\n}\n","export const STRIPE_UPE_CLIENT_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\nexport const STRIPE_UPE_CLIENT_API_VERSION = '2020-03-02;alipay_beta=v1;link_beta=v1';\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';\nimport {\n STRIPE_UPE_CLIENT_API_VERSION,\n STRIPE_UPE_CLIENT_BETAS,\n StripeJsVersion,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\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 GooglePayStripeInitializationData,\n} from '../types';\n\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: StripeScriptLoader,\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 shouldTrigger3DS = some(error.body.errors, { code: 'three_d_secure_required' });\n\n if (shouldTrigger3DS) {\n const initialization = this.getGooglePayInitializationData();\n\n assertsIsGooglePayStripeInitializationData(initialization);\n\n this.stripeUPEClient = await this.loadStripeJs(initialization, methodId);\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 initializationData: GooglePayStripeInitializationData,\n methodId: string,\n ): Promise {\n if (this.stripeUPEClient) {\n return this.stripeUPEClient;\n }\n\n const locale = this.paymentIntegrationService.getState().getCartLocale();\n\n if (methodId === 'googlepaystripeocs' && !!initializationData.useNewStripeJsVersion) {\n return this.scriptLoader.getStripeClient(\n initializationData,\n locale,\n StripeJsVersion.CLOVER,\n );\n }\n\n return this.scriptLoader.getStripeClient(\n initializationData,\n locale,\n StripeJsVersion.V3,\n STRIPE_UPE_CLIENT_BETAS,\n STRIPE_UPE_CLIENT_API_VERSION,\n );\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 { 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';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\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';\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 StripeScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayStripeCustomerStrategy, [\n { id: 'googlepaystripe' },\n { id: 'googlepaystripeocs' },\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';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\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';\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 StripeScriptLoader(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","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 { GooglePayKey } from '../google-pay-payment-initialize-options';\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 private _methodId = GooglePayKey.BRAINTREE;\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 let paymentMethod = super.getPaymentMethod();\n\n if (!paymentMethod.clientToken) {\n const state = await this._service.loadPaymentMethod(this._methodId);\n\n paymentMethod = state.getPaymentMethodOrThrow(this._methodId);\n }\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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","export const LOADING_INDICATOR_STYLES = {\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\n};\n\n/**\n * PayPal SDK supported locales\n * https://developer.paypal.com/sdk/js/configuration/#link-locale\n */\nexport const PAYPAL_SDK_SUPPORTED_LOCALES = [\n 'ar_BH',\n 'ar_DZ',\n 'ar_EG',\n 'ar_JO',\n 'ar_KW',\n 'ar_MA',\n 'ar_OM',\n 'ar_QA',\n 'ar_SA',\n 'ar_TN',\n 'ar_YE',\n 'ar_AE',\n 'bg_BG',\n 'cs_CZ',\n 'da_DK',\n 'da_FO',\n 'da_GL',\n 'de_AT',\n 'de_CH',\n 'de_DE',\n 'de_LU',\n 'el_GR',\n 'en_AD',\n 'en_AE',\n 'en_AG',\n 'en_AI',\n 'en_AL',\n 'en_AM',\n 'en_AN',\n 'en_AO',\n 'en_AT',\n 'en_AU',\n 'en_AW',\n 'en_AZ',\n 'en_BB',\n 'en_BE',\n 'en_BH',\n 'en_BJ',\n 'en_BM',\n 'en_BN',\n 'en_BS',\n 'en_BT',\n 'en_BW',\n 'en_BY',\n 'en_BZ',\n 'en_C2',\n 'en_CA',\n 'en_CD',\n 'en_CG',\n 'en_CH',\n 'en_CI',\n 'en_CK',\n 'en_CL',\n 'en_CM',\n 'en_CN',\n 'en_CO',\n 'en_CR',\n 'en_CV',\n 'en_CY',\n 'en_CZ',\n 'en_DE',\n 'en_DJ',\n 'en_DK',\n 'en_DM',\n 'en_DO',\n 'en_DZ',\n 'en_EC',\n 'en_EE',\n 'en_EG',\n 'en_ER',\n 'en_ES',\n 'en_ET',\n 'en_FI',\n 'en_FJ',\n 'en_FK',\n 'en_FM',\n 'en_FO',\n 'en_FR',\n 'en_GA',\n 'en_GB',\n 'en_GD',\n 'en_GE',\n 'en_GF',\n 'en_GI',\n 'en_GL',\n 'en_GM',\n 'en_GN',\n 'en_GP',\n 'en_GR',\n 'en_GT',\n 'en_GW',\n 'en_GY',\n 'en_HK',\n 'en_HN',\n 'en_HR',\n 'en_HU',\n 'en_ID',\n 'en_IE',\n 'en_IL',\n 'en_IN',\n 'en_IS',\n 'en_IT',\n 'en_JM',\n 'en_JO',\n 'en_JP',\n 'en_KE',\n 'en_KG',\n 'en_KH',\n 'en_KI',\n 'en_KM',\n 'en_KN',\n 'en_KR',\n 'en_KW',\n 'en_KY',\n 'en_KZ',\n 'en_LA',\n 'en_LC',\n 'en_LI',\n 'en_LK',\n 'en_LS',\n 'en_LT',\n 'en_LU',\n 'en_LV',\n 'en_MA',\n 'en_MC',\n 'en_MD',\n 'en_ME',\n 'en_MG',\n 'en_MH',\n 'en_MK',\n 'en_ML',\n 'en_MN',\n 'en_MQ',\n 'en_MR',\n 'en_MS',\n 'en_MT',\n 'en_MU',\n 'en_MV',\n 'en_MW',\n 'en_MY',\n 'en_MZ',\n 'en_NA',\n 'en_NC',\n 'en_NE',\n 'en_NF',\n 'en_NG',\n 'en_NI',\n 'en_NL',\n 'en_NO',\n 'en_NP',\n 'en_NR',\n 'en_NU',\n 'en_NZ',\n 'en_OM',\n 'en_PA',\n 'en_PE',\n 'en_PF',\n 'en_PG',\n 'en_PH',\n 'en_PL',\n 'en_PM',\n 'en_PN',\n 'en_PT',\n 'en_PW',\n 'en_PY',\n 'en_QA',\n 'en_RE',\n 'en_RO',\n 'en_RS',\n 'en_RU',\n 'en_RW',\n 'en_SA',\n 'en_SB',\n 'en_SC',\n 'en_SE',\n 'en_SG',\n 'en_SH',\n 'en_SI',\n 'en_SJ',\n 'en_SK',\n 'en_SL',\n 'en_SM',\n 'en_SN',\n 'en_SO',\n 'en_SR',\n 'en_ST',\n 'en_SV',\n 'en_SZ',\n 'en_TC',\n 'en_TD',\n 'en_TG',\n 'en_TH',\n 'en_TJ',\n 'en_TM',\n 'en_TN',\n 'en_TO',\n 'en_TR',\n 'en_TT',\n 'en_TV',\n 'en_TW',\n 'en_TZ',\n 'en_UA',\n 'en_UG',\n 'en_US',\n 'en_UY',\n 'en_VA',\n 'en_VC',\n 'en_VE',\n 'en_VG',\n 'en_VN',\n 'en_VU',\n 'en_WF',\n 'en_WS',\n 'en_YE',\n 'en_YT',\n 'en_ZA',\n 'en_ZM',\n 'en_ZW',\n 'es_AD',\n 'es_AI',\n 'es_AO',\n 'es_AR',\n 'es_AW',\n 'es_BB',\n 'es_BJ',\n 'es_BM',\n 'es_BO',\n 'es_BS',\n 'es_BZ',\n 'es_CD',\n 'es_CG',\n 'es_CK',\n 'es_CL',\n 'es_CO',\n 'es_CR',\n 'es_CV',\n 'es_DJ',\n 'es_DM',\n 'es_DO',\n 'es_DZ',\n 'es_EC',\n 'es_EG',\n 'es_ER',\n 'es_ES',\n 'es_ET',\n 'es_FJ',\n 'es_FK',\n 'es_FO',\n 'es_GA',\n 'es_GD',\n 'es_GE',\n 'es_GI',\n 'es_GL',\n 'es_GM',\n 'es_GN',\n 'es_GT',\n 'es_GW',\n 'es_GY',\n 'es_HN',\n 'es_IE',\n 'es_JM',\n 'es_JO',\n 'es_KE',\n 'es_KG',\n 'es_KI',\n 'es_KM',\n 'es_KN',\n 'es_KW',\n 'es_KY',\n 'es_KZ',\n 'es_LC',\n 'es_LI',\n 'es_LS',\n 'es_LU',\n 'es_MA',\n 'es_MG',\n 'es_MH',\n 'es_ML',\n 'es_MR',\n 'es_MS',\n 'es_MU',\n 'es_MW',\n 'es_MX',\n 'es_MZ',\n 'es_NA',\n 'es_NC',\n 'es_NE',\n 'es_NF',\n 'es_NI',\n 'es_NR',\n 'es_NU',\n 'es_NZ',\n 'es_OM',\n 'es_PA',\n 'es_PE',\n 'es_PF',\n 'es_PG',\n 'es_PM',\n 'es_PN',\n 'es_PW',\n 'es_PY',\n 'es_QA',\n 'es_RS',\n 'es_RW',\n 'es_SA',\n 'es_SB',\n 'es_SC',\n 'es_SH',\n 'es_SJ',\n 'es_SL',\n 'es_SM',\n 'es_SN',\n 'es_SO',\n 'es_SR',\n 'es_ST',\n 'es_SV',\n 'es_SZ',\n 'es_TC',\n 'es_TD',\n 'es_TG',\n 'es_TJ',\n 'es_TM',\n 'es_TN',\n 'es_TT',\n 'es_TV',\n 'es_UA',\n 'es_UG',\n 'es_US',\n 'es_UY',\n 'es_VA',\n 'es_VC',\n 'es_VE',\n 'es_VG',\n 'es_VU',\n 'es_WF',\n 'es_YE',\n 'es_ZM',\n 'et_EE',\n 'fi_FI',\n 'fr_AD',\n 'fr_AE',\n 'fr_AI',\n 'fr_AM',\n 'fr_AO',\n 'fr_AW',\n 'fr_AZ',\n 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Y',\n 'zh_KZ',\n 'zh_LC',\n 'zh_LI',\n 'zh_LS',\n 'zh_LT',\n 'zh_LU',\n 'zh_MA',\n 'zh_MG',\n 'zh_MH',\n 'zh_ML',\n 'zh_MR',\n 'zh_MS',\n 'zh_MU',\n 'zh_MW',\n 'zh_MZ',\n 'zh_NA',\n 'zh_NC',\n 'zh_NE',\n 'zh_NF',\n 'zh_NI',\n 'zh_NR',\n 'zh_NU',\n 'zh_NZ',\n 'zh_OM',\n 'zh_PA',\n 'zh_PE',\n 'zh_PF',\n 'zh_PG',\n 'zh_PM',\n 'zh_PN',\n 'zh_PW',\n 'zh_QA',\n 'zh_RS',\n 'zh_RW',\n 'zh_SA',\n 'zh_SB',\n 'zh_SC',\n 'zh_SH',\n 'zh_SJ',\n 'zh_SL',\n 'zh_SM',\n 'zh_SN',\n 'zh_SO',\n 'zh_SR',\n 'zh_ST',\n 'zh_SV',\n 'zh_SZ',\n 'zh_TC',\n 'zh_TD',\n 'zh_TG',\n 'zh_TJ',\n 'zh_TM',\n 'zh_TN',\n 'zh_TT',\n 'zh_TV',\n 'zh_UA',\n 'zh_UG',\n 'zh_US',\n 'zh_UY',\n 'zh_VA',\n 'zh_VC',\n 'zh_VE',\n 'zh_VG',\n 'zh_VU',\n 'zh_WF',\n 'zh_YE',\n 'zh_ZA',\n 'zh_ZM',\n];\n","import { PAYPAL_SDK_SUPPORTED_LOCALES } from '../paypal-commerce-constants';\n\n/**\n * Transforms store language to PayPal SDK locale format.\n * PayPal SDK expects locale in format 'en_US' (underscore separator).\n * Returns undefined if the locale is not supported by PayPal SDK.\n * Examples: 'fr-CA' -> 'fr_CA', 'fr' -> 'fr_FR'\n */\nexport default function transformLocaleToPayPalFormat(\n storeLanguage: string | undefined,\n): string | undefined {\n if (!storeLanguage) {\n return undefined;\n }\n\n let locale: string;\n\n if (storeLanguage.includes('-')) {\n const [language, region] = storeLanguage.split('-');\n\n locale = `${language}_${region.toUpperCase()}`;\n } else {\n locale = `${storeLanguage}_${storeLanguage.toUpperCase()}`;\n }\n\n return PAYPAL_SDK_SUPPORTED_LOCALES.includes(locale) ? locale : undefined;\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';\nimport { transformLocaleToPayPalFormat } from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport {\n PayPalCommerceHostWindow,\n PayPalCommerceInitializationData,\n PayPalFastlaneSdk,\n PayPalGooglePaySdk,\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 storeLanguage: string | undefined,\n ): Promise {\n if (!this.window.paypalFastlaneSdk) {\n const config = this.getPayPalFastlaneSdkConfiguration(\n paymentMethod,\n currencyCode,\n sessionId,\n storeLanguage,\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 getPayPalGooglePaySdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n if (!this.window.paypalGooglePay || forceLoad) {\n const paypalSdkScriptConfig = this.getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n storeLanguage,\n initializesOnCheckoutPage,\n );\n\n await this.loadPayPalSdk(paypalSdkScriptConfig);\n }\n\n if (!this.window.paypalGooglePay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypalGooglePay;\n }\n\n async getPayPalApmsSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n ) {\n if (!this.window.paypalApms) {\n const config = this.getPayPalApmSdkConfiguration(\n paymentMethod,\n currencyCode,\n storeLanguage,\n );\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 storeLanguage: string | undefined,\n ): Promise {\n if (!this.window.paypalMessages) {\n const paypalSdkMessagesConfig = this.getPayPalSdkMessagesConfiguration(\n paymentMethod,\n currencyCode,\n storeLanguage,\n );\n\n await this.loadPayPalSdk(paypalSdkMessagesConfig);\n }\n\n if (!this.window.paypalMessages) {\n throw new PaymentMethodClientUnavailableError();\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 storeLanguage: string | undefined,\n ): PayPalSdkConfig {\n const { clientToken, initializationData } = paymentMethod;\n\n if (!initializationData || !initializationData.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { intent, clientId, merchantId, attributionId } = initializationData;\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit: true,\n components: [\n 'fastlane',\n 'buttons',\n 'payment-fields',\n 'hosted-fields',\n 'three-domain-secure',\n ],\n currency: currencyCode,\n intent,\n ...(locale && { locale }),\n },\n attributes: {\n 'data-client-metadata-id': sessionId.replace(/-/g, ''),\n 'data-namespace': 'paypalFastlaneSdk',\n 'data-partner-attribution-id': attributionId,\n 'data-sdk-client-token': clientToken,\n },\n };\n }\n\n private getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage = true,\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 buyerCountry,\n attributionId,\n isHostedCheckoutEnabled,\n isDeveloperModeApplicable,\n } = initializationData;\n\n const commit = isHostedCheckoutEnabled || initializesOnCheckoutPage;\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit,\n components: ['googlepay'],\n currency: currencyCode,\n intent,\n ...(isDeveloperModeApplicable && { 'buyer-country': buyerCountry }),\n ...(locale && { locale }),\n },\n attributes: {\n 'data-partner-attribution-id': attributionId,\n 'data-client-token': clientToken,\n 'data-namespace': 'paypalGooglePay',\n },\n };\n }\n\n private getPayPalApmSdkConfiguration(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\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 const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 storeLanguage: string | undefined,\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 const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 {\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 {\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\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 { GooglePayConfig } from './types';\n\nexport default class GooglePayPaypalCommerceGateway extends GooglePayGateway {\n private googlepayConfig?: GooglePayConfig;\n private service: PaymentIntegrationService;\n\n constructor(service: PaymentIntegrationService, private payPalCommerceSdk: PayPalCommerceSdk) {\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 state = this.service.getState();\n const currency = state.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 const googlePaySdk = await this.payPalCommerceSdk.getPayPalGooglePaySdk(\n paymentMethod,\n currency,\n state.getLocale(),\n );\n\n this.googlepayConfig = await googlePaySdk.Googlepay().config();\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 { 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';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\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';\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 PayPalCommerceSdk(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayPayPalCommerceCustomerStrategy, [\n { id: 'googlepaypaypalcommerce' },\n]);\n","import {\n BigCommercePaymentsInitializationData,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 GooglePayConfig,\n GooglePayPayPalCommerceGatewayParameters,\n GooglePayPayPalCommerceInitializationData,\n GooglePaySetExternalCheckoutData,\n} from '../types';\n\nexport default class GooglePayBigCommercePaymentsGateway extends GooglePayGateway {\n private googlepayConfig?: GooglePayConfig;\n private service: PaymentIntegrationService;\n\n constructor(service: PaymentIntegrationService, private payPalSdkHelper: PayPalSdkHelper) {\n super('googlepay_bigcommerce_payments', 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 const googlePaySdk = await this.payPalSdkHelper.getPayPalGooglePaySdk(\n paymentMethod as PaymentMethod,\n currency,\n );\n\n this.googlepayConfig = await googlePaySdk.Googlepay().config();\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 { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PayPalSdkHelper } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\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 GooglePayBigCommercePaymentsGateway from './google-pay-bigcommerce-payments-gateway';\n\nconst createGooglePayBigCommercePaymentsCustomerStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayBigCommercePaymentsGateway(\n paymentIntegrationService,\n new PayPalSdkHelper(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayBigCommercePaymentsCustomerStrategy, [\n { id: 'googlepay_bigcommerce_payments' },\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 {\n BuyNowCartRequestBody,\n CardInstrument,\n CustomerAddress,\n HostedInstrument,\n ShippingOption,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n/**\n *\n * PayPal 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 BuyNow\n *\n */\nexport interface PayPalBuyNowInitializeOptions {\n getBuyNowCartRequestBody(): BuyNowCartRequestBody;\n}\n\n/**\n *\n * PayPal Initialization Data\n *\n */\nexport interface PayPalInitializationData {\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?: PayPalIntent;\n isAcceleratedCheckoutEnabled?: boolean; // PayPal Fastlane related\n isFastlaneShippingOptionAutoSelectEnabled?: boolean; // PayPal Fastlane related\n isFastlaneStylingEnabled?: boolean;\n isHostedCheckoutEnabled?: boolean;\n isPayPalAnalyticsV2Enabled?: boolean; // PayPal Fastlane related\n isPayPalCreditAvailable?: boolean;\n isPayPalCommerceAnalyticsV2Enabled?: boolean; // PayPal Fastlane related\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 threeDSVerificationMethod?: string;\n isAppSwitchEnabled?: boolean;\n}\n\n/**\n *\n * PayPalHostWindow contains different\n * PayPal Sdk instances for different purposes\n *\n */\nexport interface PayPalHostWindow extends Window {\n paypal?: PayPalSDK;\n paypalFastlane?: PayPalFastlane;\n paypalFastlaneSdk?: PayPalFastlaneSdk;\n paypalMessages?: PayPalMessagesSdk;\n paypalApms?: PayPalApmSdk;\n paypalGooglePay?: PayPalGooglePaySdk;\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?: PayPalIntent;\n components?: PayPalSdkComponents;\n locale?: string;\n };\n attributes: {\n 'data-client-metadata-id'?: string;\n 'data-partner-attribution-id'?: string;\n 'data-sdk-client-token'?: string;\n 'data-namespace'?: string;\n 'data-client-token'?: string;\n };\n}\n\nexport enum PayPalIntent {\n AUTHORIZE = 'authorize',\n CAPTURE = 'capture',\n}\n\nexport type PayPalSdkComponents = Array<\n | 'fastlane'\n | 'three-domain-secure'\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 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\n/**\n *\n * PayPal Sdk instances\n *\n */\nexport interface PayPalSDK {\n CardFields: (data: PaypalCardFieldsConfig) => 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: PayPalHostedFieldsRenderOptions): Promise;\n };\n Legal: PayPalLegal & LegalFunding;\n Buttons(options: PayPalButtonsOptions): PayPalButtons;\n PaymentFields(options: PayPalPaymentFieldsOptions): PayPalPaymentFields;\n Messages(options: PayPalMessagesOptions): PayPalMessages;\n}\n\nexport interface PaypalCardFieldsConfig {\n inputEvents: {\n onChange(data: PayPalCardFieldsState): void;\n onFocus(data: PayPalCardFieldsState): void;\n onBlur(data: PayPalCardFieldsState): void;\n onInputSubmitRequest(data: PayPalCardFieldsState): void;\n };\n createVaultSetupToken?: (data: PayPalCardFieldsState) => void;\n createOrder?: () => Promise;\n style: PayPalHostedFieldsRenderOptions['styles'];\n onApprove(data: PayPalCardFieldsOnApproveData): void;\n onError(): void;\n}\n\ninterface PayPalFieldsInitializationData {\n placeholder?: string;\n}\n\nexport interface PayPalCardFields {\n isEligible(): boolean;\n CVVField(config?: PayPalFieldsInitializationData): PayPalFields;\n ExpiryField(config?: PayPalFieldsInitializationData): PayPalFields;\n NameField(config?: PayPalFieldsInitializationData): PayPalFields;\n NumberField(config?: PayPalFieldsInitializationData): PayPalFields;\n submit(config?: PayPalCardFieldsSubmitConfig): Promise;\n getState(): Promise;\n}\n\nexport interface PayPalCardFieldsSubmitConfig {\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 PayPalCardFieldsOnApproveData {\n vaultSetupToken?: string;\n orderID: string;\n liabilityShift?: LiabilityShiftEnum;\n}\n\ninterface PayPalCardFieldsFieldData {\n isFocused: boolean;\n isEmpty: boolean;\n isValid: boolean;\n isPotentiallyValid: boolean;\n}\n\ntype PayPalCardFieldsCard = PayPalHostedFieldsCard;\n\nexport interface PayPalCardFieldsState {\n cards: PayPalCardFieldsCard[];\n emittedBy: string;\n isFormValid: boolean;\n errors: string[];\n fields: {\n cardCvvField: PayPalCardFieldsFieldData;\n cardNumberField: PayPalCardFieldsFieldData;\n cardNameField?: PayPalCardFieldsFieldData;\n cardExpiryField: PayPalCardFieldsFieldData;\n };\n}\n\nexport interface PayPalFields {\n render(container: HTMLElement | string): Promise;\n clear(): void;\n removeClass(className: string): Promise;\n close(): Promise;\n}\n\nexport interface PayPalFastlaneSdk {\n ThreeDomainSecureClient: {\n isEligible(params: threeDSecureParameters): Promise;\n show(): Promise;\n };\n Fastlane(options?: PayPalFastlaneOptions): Promise;\n}\n\ninterface ThreeDomainSecureClientShowResponse {\n liabilityShift: LiabilityShiftEnum;\n authenticationState: TDSecureAuthenticationState;\n nonce: string; // Enriched nonce or the original nonce\n}\n\nexport enum TDSecureVerificationMethod {\n Always = 'SCA_ALWAYS',\n}\n\nexport enum TDSecureAuthenticationState {\n Succeeded = 'succeeded',\n Cancelled = 'cancelled',\n Errored = 'errored',\n}\n\nexport enum LiabilityShiftEnum {\n Possible = 'POSSIBLE',\n No = 'NO',\n Unknown = 'UNKNOWN',\n Yes = 'YES',\n}\n\nexport interface threeDSecureParameters {\n amount: string;\n currency: string;\n nonce: string;\n threeDSRequested: boolean;\n transactionContext: {\n experience_context: {\n brand_name?: string;\n locale: string;\n return_url: string;\n cancel_url: string;\n };\n };\n}\n\nexport interface PayPalMessagesSdk {\n Messages(options: MessagingOptions): MessagingRender;\n}\n\nexport interface PayPalApmSdk {\n Buttons(options: PayPalButtonsOptions): PayPalButtons;\n PaymentFields(options: PayPalPaymentFieldsOptions): PayPalPaymentFields;\n}\n\nexport interface PayPalGooglePaySdk {\n Googlepay(): GooglePay;\n}\n\n/**\n *\n * PayPal Payments Hosted Fields\n *\n */\nexport interface PayPalHostedFieldsRenderOptions {\n fields?: {\n number?: PayPalHostedFieldOption;\n cvv?: PayPalHostedFieldOption;\n expirationDate?: PayPalHostedFieldOption;\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 PayPalHostedFieldOption {\n selector: string;\n placeholder?: string;\n}\n\nexport interface PayPalHostedFields {\n submit(options?: PayPalHostedFieldsSubmitOptions): Promise;\n getState(): PayPalHostedFieldsState;\n on(eventName: string, callback: (event: PayPalHostedFieldsState) => void): void;\n}\n\nexport interface PayPalHostedFieldsSubmitOptions {\n contingencies?: Array<'3D_SECURE'>;\n cardholderName?: string;\n}\n\nexport interface PayPalHostedFieldsApprove {\n orderId: string;\n liabilityShift?: 'POSSIBLE' | 'NO' | 'UNKNOWN';\n}\n\nexport interface PayPalHostedFieldsState {\n cards: PayPalHostedFieldsCard[];\n emittedBy: string;\n fields: {\n number?: PayPalHostedFieldsFieldData;\n expirationDate?: PayPalHostedFieldsFieldData;\n expirationMonth?: PayPalHostedFieldsFieldData;\n expirationYear?: PayPalHostedFieldsFieldData;\n cvv?: PayPalHostedFieldsFieldData;\n postalCode?: PayPalHostedFieldsFieldData;\n };\n}\n\nexport interface PayPalHostedFieldsCard {\n type: string;\n niceType: string;\n code: {\n name: string;\n size: number;\n };\n}\n\nexport interface PayPalHostedFieldsFieldData {\n container: HTMLElement;\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\n/**\n *\n * PayPal Buttons\n *\n */\nexport interface PayPalButtons {\n render(id: string): void;\n close(): void;\n isEligible(): boolean;\n hasReturned?(): boolean;\n resume?(): void;\n}\n\nexport interface PayPalButtonsOptions {\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 phone?: {\n phone_number: {\n national_number: string;\n };\n };\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\nexport interface PayPalButtonOptions {\n fundingSource: string;\n style?: PayPalButtonStyleOptions;\n isAppSwitchEnabled?: boolean;\n isHostedCheckoutEnabled?: boolean;\n onClick?: () => void;\n onCancel?: () => void;\n onPaymentComplete?: () => void;\n onError?(error?: Error | unknown): void;\n}\n\n/**\n *\n * PayPal Messages\n */\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface PayPalMessages {\n render(id: string): void;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface PayPalMessagesOptions {\n amount: number;\n placement: string;\n style?: PayPalMessagesStyleOptions;\n fundingSource?: string;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface PayPalMessagesStyleOptions {\n layout?: string;\n}\n\n/**\n *\n * Google Pay related types\n *\n */\n\ninterface GooglePay {\n config: () => Promise;\n confirmOrder: (confirmOrderConfig: ConfirmOrderConfig) => Promise<{ status: string }>;\n initiatePayerAction: (payerActionConfig: PayerActionConfig) => Promise;\n}\n\ninterface ConfirmOrderConfig {\n orderId: string;\n paymentMethodData: ConfirmOrderData;\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\ninterface PayerActionConfig {\n orderId: 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\n/**\n *\n * PayPal Payment fields\n *\n */\nexport interface PayPalPaymentFields {\n render(id: string): void;\n}\n\nexport interface PayPalPaymentFieldsOptions {\n style?: PayPalFieldsStyleOptions;\n fundingSource: string;\n fields: {\n name?: {\n value?: string;\n };\n email?: {\n value?: string;\n };\n };\n}\n\nexport interface PayPalFieldsStyleOptions {\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 = 'canceled',\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\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 methodId?: string;\n orderId?: number;\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 fastlaneToken?: string;\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 { 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 FundingType,\n PayPalFastlaneSdk,\n PayPalGooglePaySdk,\n PayPalHostWindow,\n PayPalInitializationData,\n PayPalMessagesSdk,\n PayPalSDK,\n PayPalSdkComponents,\n PayPalSdkConfig,\n} from './paypal-types';\nimport { transformLocaleToPayPalFormat } from './utils';\n\nexport default class PayPalSdkScriptLoader {\n private window: PayPalHostWindow;\n\n constructor(private scriptLoader: ScriptLoader) {\n this.window = window;\n }\n\n async getPayPalSDK(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n if (!this.window.paypal || forceLoad) {\n const paypalSdkScriptConfig = this.getPayPalSdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n storeLanguage,\n initializesOnCheckoutPage,\n );\n\n await this.loadPayPalSdk(paypalSdkScriptConfig);\n\n if (!this.window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.window.paypal;\n }\n\n async getPayPalFastlaneSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n sessionId: string,\n storeLanguage: string | undefined,\n ): Promise {\n if (!this.window.paypalFastlaneSdk) {\n const config = this.getPayPalFastlaneSdkConfiguration(\n paymentMethod,\n currencyCode,\n sessionId,\n storeLanguage,\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 getPayPalGooglePaySdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n if (!this.window.paypalGooglePay || forceLoad) {\n const paypalSdkScriptConfig = this.getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n storeLanguage,\n initializesOnCheckoutPage,\n );\n\n await this.loadPayPalSdk(paypalSdkScriptConfig);\n }\n\n if (!this.window.paypalGooglePay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypalGooglePay;\n }\n\n async getPayPalApmsSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n ) {\n if (!this.window.paypalApms) {\n const config = this.getPayPalApmSdkConfiguration(\n paymentMethod,\n currencyCode,\n storeLanguage,\n );\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 storeLanguage: string | undefined,\n ): Promise {\n if (!this.window.paypalMessages) {\n const paypalSdkMessagesConfig = this.getPayPalSdkMessagesConfiguration(\n paymentMethod,\n currencyCode,\n storeLanguage,\n );\n\n await this.loadPayPalSdk(paypalSdkMessagesConfig);\n }\n\n if (!this.window.paypalMessages) {\n throw new PaymentMethodClientUnavailableError();\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 getPayPalSdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage = true,\n ): PayPalSdkConfig {\n const { id, 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 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 =\n id === 'paypalcommercecreditcards' || id === 'bigcommerce_payments_creditcards';\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 enableVenmoFunding = isVenmoEnabled ? ['venmo'] : [];\n const disableVenmoFunding = !isVenmoEnabled ? ['venmo'] : [];\n const disableAPMsFunding = availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n );\n const googlePayComponent: PayPalSdkComponents = isGooglePayEnabled ? ['googlepay'] : [];\n const cardFieldsComponent: PayPalSdkComponents = 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 ...enabledAlternativePaymentMethods,\n ];\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\n },\n attributes: {\n 'data-partner-attribution-id': attributionId,\n 'data-client-token': clientToken,\n },\n };\n }\n\n private getPayPalFastlaneSdkConfiguration(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n sessionId: string,\n storeLanguage: string | undefined,\n ): PayPalSdkConfig {\n const { clientToken, initializationData } = paymentMethod;\n\n if (!initializationData || !initializationData.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { intent, clientId, merchantId, attributionId } = initializationData;\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit: true,\n components: [\n 'fastlane',\n 'buttons',\n 'payment-fields',\n 'hosted-fields',\n 'three-domain-secure',\n ],\n currency: currencyCode,\n ...(locale && { locale }),\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-sdk-client-token': clientToken,\n },\n };\n }\n\n private getPayPalGooglePaySdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\n initializesOnCheckoutPage = true,\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 buyerCountry,\n attributionId,\n isHostedCheckoutEnabled,\n isDeveloperModeApplicable,\n } = initializationData;\n\n const commit = isHostedCheckoutEnabled || initializesOnCheckoutPage;\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit,\n components: ['googlepay'],\n currency: currencyCode,\n intent,\n ...(isDeveloperModeApplicable && { 'buyer-country': buyerCountry }),\n ...(locale && { locale }),\n },\n attributes: {\n 'data-partner-attribution-id': attributionId,\n 'data-client-token': clientToken,\n 'data-namespace': 'paypalGooglePay',\n },\n };\n }\n\n private getPayPalApmSdkConfiguration(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n storeLanguage: string | undefined,\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 const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 storeLanguage: string | undefined,\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 const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport PayPalSdkScriptLoader from './paypal-sdk-script-loader';\n\nexport default function createPayPalSdkScriptLoader(): PayPalSdkScriptLoader {\n return new PayPalSdkScriptLoader(getScriptLoader());\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 PayPalRequestSender from './paypal-request-sender';\nimport PayPalSdkScriptLoader from './paypal-sdk-script-loader';\nimport {\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n PayPalCreateOrderCardFieldsResponse,\n PayPalCreateOrderRequestBody,\n PayPalInitializationData,\n PayPalOrderDetails,\n PayPalOrderStatus,\n PayPalSDK,\n StyleButtonColor,\n StyleButtonLabel,\n StyleButtonShape,\n} from './paypal-types';\n\nexport default class PayPalIntegrationService {\n private paypalSdk?: PayPalSDK;\n\n constructor(\n private formPoster: FormPoster,\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalRequestSender: PayPalRequestSender,\n private paypalSdkLoader: PayPalSdkScriptLoader,\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 = state.getPaymentMethodOrThrow(methodId);\n const storeLanguage = state.getLocale();\n\n this.paypalSdk = await this.paypalSdkLoader.getPayPalSDK(\n paymentMethod,\n currencyCode,\n storeLanguage,\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.paypalRequestSender.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.paypalRequestSender.createOrder(providerId, {\n cartId,\n ...requestBody,\n });\n\n return { orderId, ...(setupToken ? { setupToken } : {}) };\n }\n\n async updateOrder(providerId: string, methodId?: string, orderId?: number): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const consignment = state.getConsignmentsOrThrow()[0];\n\n try {\n await this.paypalRequestSender.updateOrder(providerId, {\n availableShippingOptions: consignment.availableShippingOptions,\n cartId: cart.id,\n selectedShippingOption: consignment.selectedShippingOption,\n ...(methodId ? { methodId } : {}),\n ...(orderId ? { orderId } : {}),\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.paypalRequestSender.getOrderStatus(methodId, options);\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((option) => {\n if (consignment.selectedShippingOption) {\n const shippingOptionId = consignment.selectedShippingOption.id;\n\n return option.id === shippingOptionId;\n }\n\n return false;\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: address?.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 phone: payer.phone?.phone_number?.national_number,\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","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-types';\n\nexport default class PayPalRequestSender {\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 methodId: string,\n requestBody: PayPalUpdateOrderRequestBody,\n ): Promise {\n const url = `/api/storefront/initialization/${methodId}`;\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: string,\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 { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalSdkScriptLoader from './create-paypal-sdk-script-loader';\nimport PaypalIntegrationService from './paypal-integration-service';\nimport PaypalRequestSender from './paypal-request-sender';\n\nconst createPayPalIntegrationService = (paymentIntegrationService: PaymentIntegrationService) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new PaypalIntegrationService(\n createFormPoster(),\n paymentIntegrationService,\n new PaypalRequestSender(createRequestSender({ host: getHost() })),\n createPayPalSdkScriptLoader(),\n );\n};\n\nexport default createPayPalIntegrationService;\n","import {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalIntegrationService from './paypal-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalButtonOptions,\n PayPalButtons,\n PayPalBuyNowInitializeOptions,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from './paypal-types';\n\nclass PaypalButtonCreationService {\n private onError?: PayPalButtonOptions['onError'];\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\n ) {}\n\n createPayPalButton(\n providerId: string,\n methodId: string,\n buttonOptions: PayPalButtonOptions,\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): PayPalButtons {\n const {\n style,\n fundingSource,\n isAppSwitchEnabled,\n isHostedCheckoutEnabled,\n onClick,\n onCancel,\n onPaymentComplete,\n onError,\n } = buttonOptions;\n\n this.onError = onError;\n\n const paypalSdk = this.paypalIntegrationService.getPayPalSdkOrThrow();\n const isAvailableFundingSource = Object.values(paypalSdk.FUNDING).includes(fundingSource);\n\n if (!isAvailableFundingSource) {\n throw new InvalidArgumentError(\n `Unable to initialize PayPal button because \"fundingSource\" argument is not valid funding source.`,\n );\n }\n\n const hostedCheckoutCallbacks = {\n ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data, providerId),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data, providerId),\n }),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(\n data,\n actions,\n methodId,\n providerId,\n onPaymentComplete,\n ),\n };\n\n return paypalSdk.Buttons({\n fundingSource,\n style: this.paypalIntegrationService.getValidButtonStyle(style),\n ...(isAppSwitchEnabled && {\n appSwitchWhenAvailable: true,\n }),\n createOrder: async () => {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n\n return this.paypalIntegrationService.createOrder(providerId);\n },\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalIntegrationService.tokenizePayment(methodId, orderID),\n ...(onClick ? { onClick } : {}),\n ...(onCancel ? { onCancel } : {}),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n });\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n providerId: 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.paypalIntegrationService.getBillingAddressFromOrderDetails(orderDetails);\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalIntegrationService.getShippingAddressFromOrderDetails(orderDetails);\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalIntegrationService.updateOrder(providerId);\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalIntegrationService.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 providerId: string,\n ): Promise {\n const address = this.paypalIntegrationService.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.paypalIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalIntegrationService.updateOrder(providerId);\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n providerId: string,\n ): Promise {\n const shippingOption = this.paypalIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalIntegrationService.updateOrder(providerId);\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\nexport default PaypalButtonCreationService;\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';\nimport {\n PaypalButtonCreationService,\n PayPalButtonOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceCustomerInitializeOptions, {\n WithPayPalCommerceCustomerInitializeOptions,\n} from './paypal-commerce-customer-initialize-options';\n\nexport default class PayPalCommerceCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\n private paypalButtonCreationService: PaypalButtonCreationService,\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 const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethod(methodId);\n\n if (!paymentMethod) {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n }\n\n const paypalSdk = await this.paypalIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n console.error(\n '[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\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, onError } = paypalcommerce;\n\n const paypalSdk = this.paypalIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, paymentButtonStyles, isAppSwitchEnabled } =\n paymentMethod.initializationData || {};\n const { checkoutTopButtonStyles } = paymentButtonStyles || {};\n\n const buttonOptions: PayPalButtonOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n isAppSwitchEnabled,\n isHostedCheckoutEnabled,\n style: {\n ...checkoutTopButtonStyles,\n height: DefaultCheckoutButtonHeight,\n },\n ...(onClick && { onClick: () => onClick() }),\n ...(isHostedCheckoutEnabled && onComplete && { onPaymentComplete: () => onComplete() }),\n onError,\n };\n\n const paypalButton = this.paypalButtonCreationService.createPayPalButton(\n 'paypalcommerce',\n methodId,\n buttonOptions,\n );\n\n if (paypalButton.isEligible()) {\n if (paypalButton.hasReturned?.() && isAppSwitchEnabled) {\n paypalButton.resume?.();\n } else {\n paypalButton.render(`#${container}`);\n }\n } else {\n this.paypalIntegrationService.removeElement(container);\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalIntegrationService,\n PaypalButtonCreationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceCustomerStrategy from './paypal-commerce-customer-strategy';\n\nconst createPayPalCommerceCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceCustomerStrategy\n> = (paymentIntegrationService) => {\n const paypalIntegrationService = createPayPalIntegrationService(paymentIntegrationService);\n const paypalButtonCreationService = new PaypalButtonCreationService(\n paymentIntegrationService,\n paypalIntegrationService,\n );\n\n return new PayPalCommerceCustomerStrategy(\n paymentIntegrationService,\n paypalIntegrationService,\n paypalButtonCreationService,\n );\n};\n\nexport default toResolvableModule(createPayPalCommerceCustomerStrategy, [{ id: 'paypalcommerce' }]);\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 locale?: string;\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}\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 paypalBNPLConfiguration?: PayPalBNPLConfigurationItem[];\n isAppSwitchEnabled?: boolean;\n}\n\nexport interface PayPalBNPLConfigurationItem {\n id: string;\n name: string;\n status: boolean;\n styles: 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 hasReturned?(): boolean;\n resume?(): void;\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 phone?: {\n phone_number: {\n national_number: string;\n };\n };\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 IDEAL = 'ideal',\n}\n\nexport interface PayPalOrderData {\n orderId: string;\n setupToken?: string;\n approveUrl: string;\n fastlaneToken?: 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 fastlaneToken?: string;\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 state.getLocale(),\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: address?.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 phone: payer.phone?.phone_number?.national_number,\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","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';\nimport { transformLocaleToPayPalFormat } from '@bigcommerce/checkout-sdk/paypal-utils';\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 storeLanguage: string | undefined,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n const paypalSdkScriptConfig = this.getPayPalSdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n storeLanguage,\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 storeLanguage: string | undefined,\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 enableVenmoFunding = isVenmoEnabled ? ['venmo'] : [];\n const disableVenmoFunding = !isVenmoEnabled ? ['venmo'] : [];\n const disableAPMsFunding = availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n );\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 ...enabledAlternativePaymentMethods,\n ];\n\n const locale = transformLocaleToPayPalFormat(storeLanguage);\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 ...(locale && { locale }),\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 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 const paypalSdk = await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n console.error(\n '[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\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, isAppSwitchEnabled } =\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 ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n }),\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 const paypalSdk = await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n if (!paypalSdk || !paypalSdk.Buttons || typeof paypalSdk.Buttons !== 'function') {\n console.error(\n '[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\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 { 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 { CookieStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport {\n PayPalFastlane,\n PayPalFastlaneAddress,\n PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneLookupCustomerByEmailResult,\n PayPalFastlaneProfileCard,\n PayPalFastlaneProfileName,\n PayPalFastlaneProfilePhone,\n PayPalFastlaneProfileToBcCustomerDataMappingResult,\n PayPalFastlaneSdk,\n PayPalFastlaneStylesOption,\n PayPalHostWindow,\n} from './paypal-types';\n\nexport default class PaypalFastlaneUtils {\n private window: PayPalHostWindow;\n\n constructor() {\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 *\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(sessionId: string): void {\n const expires = new Date();\n\n expires.setDate(expires.getDate() + 14); // 2 weeks expiry\n\n const cookiesOption = {\n expires,\n secure: true,\n };\n\n CookieStorage.set('bc-fastlane-sessionId', sessionId, cookiesOption);\n }\n\n removeStorageSessionId(): void {\n CookieStorage.remove('bc-fastlane-sessionId');\n }\n\n getStorageSessionId(): string {\n return CookieStorage.get('bc-fastlane-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 PaypalFastlaneUtils from './paypal-fastlane-utils';\n\nexport default function createPaypalFastlaneUtils(): PaypalFastlaneUtils {\n return new PaypalFastlaneUtils();\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 PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneStylesOption,\n PayPalFastlaneUtils,\n PayPalInitializationData,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-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 paypalSdkScriptLoader: PayPalSdkScriptLoader,\n private paypalFastlaneUtils: PayPalFastlaneUtils,\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 = state.getPaymentMethodOrThrow(methodId);\n\n const isTestModeEnabled = !!paymentMethod.initializationData?.isDeveloperModeApplicable;\n\n const paypalFastlaneSdk = await this.paypalSdkScriptLoader.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n state.getLocale(),\n );\n\n await this.paypalFastlaneUtils.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 await this.paymentIntegrationService.updatePaymentProviderCustomer({\n authenticationState: undefined,\n addresses: undefined,\n instruments: undefined,\n });\n\n this.paypalFastlaneUtils.removeStorageSessionId();\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.paypalFastlaneUtils.lookupCustomerOrThrow(\n customerEmail,\n );\n\n const authenticationResult =\n await this.paypalFastlaneUtils.triggerAuthenticationFlowOrThrow(customerContextId);\n\n const isAuthenticationFlowCanceled =\n authenticationResult.authenticationState === PayPalFastlaneAuthenticationState.CANCELED;\n\n await this.updateCustomerDataState(methodId, authenticationResult);\n\n if (isAuthenticationFlowCanceled) {\n this.paypalFastlaneUtils.removeStorageSessionId();\n } else {\n this.paypalFastlaneUtils.updateStorageSessionId(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.paypalFastlaneUtils.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 = 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 createPayPalFastlaneUtils,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceFastlaneCustomerStrategy from './paypal-commerce-fastlane-customer-strategy';\n\nconst createPayPalCommerceFastlaneCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceFastlaneCustomerStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceFastlaneCustomerStrategy(\n paymentIntegrationService,\n createPayPalSdkScriptLoader(),\n createPayPalFastlaneUtils(),\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 { PaymentMethod } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { StripePaymentMethod } from './stripe';\n\nexport function isStripePaymentMethodLike(\n paymentMethod: PaymentMethod,\n): paymentMethod is StripePaymentMethod {\n return (\n typeof paymentMethod === 'object' &&\n paymentMethod !== null &&\n 'initializationData' in paymentMethod &&\n (paymentMethod as StripePaymentMethod).initializationData !== undefined &&\n (paymentMethod as StripePaymentMethod).initializationData !== null &&\n typeof (paymentMethod as StripePaymentMethod).initializationData === 'object' &&\n 'stripePublishableKey' in (paymentMethod as StripePaymentMethod).initializationData &&\n 'stripeConnectedAccount' in (paymentMethod as StripePaymentMethod).initializationData &&\n 'shopperLanguage' in (paymentMethod as StripePaymentMethod).initializationData &&\n typeof (paymentMethod as StripePaymentMethod).initializationData.stripePublishableKey !==\n 'undefined' &&\n typeof (paymentMethod as StripePaymentMethod).initializationData.stripeConnectedAccount !==\n 'undefined' &&\n typeof (paymentMethod as StripePaymentMethod).initializationData.shopperLanguage !==\n 'undefined'\n );\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 {\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';\nimport {\n isStripePaymentMethodLike,\n STRIPE_UPE_CLIENT_API_VERSION,\n STRIPE_UPE_CLIENT_BETAS,\n StripeAppearanceOptions,\n StripeClient,\n StripeElementEvent,\n StripeElements,\n StripeElementType,\n StripeEventType,\n StripeFormMode,\n StripeJsVersion,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport isStripeAcceleratedCheckoutCustomer from './is-stripe-accelerated-checkout-customer';\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: StripeScriptLoader,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithStripeUPECustomerInitializeOptions,\n ): Promise {\n let stripeUPEClient: StripeClient;\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 (!isStripePaymentMethodLike(paymentMethod) || !clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\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: StripeAppearanceOptions | 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 paymentMethod.initializationData,\n state.getCartLocale(),\n StripeJsVersion.V3,\n STRIPE_UPE_CLIENT_BETAS,\n STRIPE_UPE_CLIENT_API_VERSION,\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(StripeElementEvent.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 { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeUPECustomerStrategy from './stripe-upe-customer-strategy';\n\nconst createStripeUPECustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new StripeUPECustomerStrategy(\n paymentIntegrationService,\n new StripeScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createStripeUPECustomerStrategy, [{ id: 'stripeupe' }]);\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 StripeClient,\n StripeConfirmPaymentData,\n StripeElement,\n StripeElements,\n StripeElementType,\n StripeError,\n StripeInitializationData,\n StripeJsVersion,\n StripePaymentIntentStatus,\n StripeStringConstants,\n} from './stripe';\nimport StripePaymentInitializeOptions from './stripe-initialize-options';\nimport StripeScriptLoader from './stripe-script-loader';\n\nexport default class StripeIntegrationService {\n private isMounted = false;\n private checkoutEventsUnsubscribe?: () => void;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n ) {}\n\n deinitialize(): void {\n this.checkoutEventsUnsubscribe?.();\n this.isMounted = false;\n }\n\n initCheckoutEventsSubscription(\n gatewayId: string,\n methodId: string,\n stripeInitializationOptions: StripePaymentInitializeOptions,\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 stripeInitializationOptions.onError?.(error);\n }\n\n return;\n }\n\n if (!this.isMounted) {\n await stripeElements?.fetchUpdates();\n this.mountElement(paymentElement, stripeInitializationOptions.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(methodId: string, stripeUPEClient?: StripeClient): 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 === StripePaymentIntentStatus.SUCCEEDED;\n }\n\n mapStripePaymentData(\n stripeElements?: StripeElements,\n returnUrl?: string,\n shouldAllowRedisplay = false,\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 ...(shouldAllowRedisplay ? { allow_redisplay: 'always' } : {}),\n billing_details: {\n email,\n address,\n name: this.getShopperFullName(billingAddress),\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 // INFO: no need to update Stripe Element if client token is not present\n return;\n }\n\n this.scriptLoader.updateStripeElements({ clientSecret: clientToken });\n }\n\n getStripeJsVersion(initializationData: StripeInitializationData): StripeJsVersion {\n return initializationData.useNewStripeJsVersion\n ? StripeJsVersion.CLOVER\n : StripeJsVersion.V3;\n }\n\n mapStripeAddress(address?: Address): AddressOptions {\n if (address) {\n const {\n city,\n address1,\n address2,\n countryCode: country,\n postalCode,\n stateOrProvinceCode,\n } = address;\n\n return {\n city,\n country,\n postal_code: postalCode,\n line1: address1,\n line2: address2,\n ...(stateOrProvinceCode ? { state: stateOrProvinceCode } : {}),\n };\n }\n\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n getShopperFullName(address?: Address): string {\n const { firstName = '', lastName = '' } = address || {};\n\n return `${firstName} ${lastName}`.trim();\n }\n}\n","import { StripeError } from './stripe';\n\nexport function isStripeError(error: unknown): error is StripeError {\n return typeof error === 'object' && error !== null && 'type' in error;\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\nexport const DEFAULT_CONTAINER_STYLES = {\n position: 'fixed',\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\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 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","export const expressCheckoutAllowedCountryCodes = [\n 'AC',\n 'AD',\n 'AE',\n 'AF',\n 'AG',\n 'AI',\n 'AL',\n 'AM',\n 'AO',\n 'AQ',\n 'AR',\n 'AT',\n 'AU',\n 'AW',\n 'AX',\n 'AZ',\n 'BA',\n 'BB',\n 'BD',\n 'BE',\n 'BF',\n 'BG',\n 'BH',\n 'BI',\n 'BJ',\n 'BL',\n 'BM',\n 'BN',\n 'BO',\n 'BQ',\n 'BR',\n 'BS',\n 'BT',\n 'BV',\n 'BW',\n 'BY',\n 'BZ',\n 'CA',\n 'CD',\n 'CF',\n 'CG',\n 'CH',\n 'CI',\n 'CK',\n 'CL',\n 'CM',\n 'CN',\n 'CO',\n 'CR',\n 'CV',\n 'CW',\n 'CY',\n 'CZ',\n 'DE',\n 'DJ',\n 'DK',\n 'DM',\n 'DO',\n 'DZ',\n 'EC',\n 'EE',\n 'EG',\n 'EH',\n 'ER',\n 'ES',\n 'ET',\n 'FI',\n 'FJ',\n 'FK',\n 'FO',\n 'FR',\n 'GA',\n 'GB',\n 'GD',\n 'GE',\n 'GF',\n 'GG',\n 'GH',\n 'GI',\n 'GL',\n 'GM',\n 'GN',\n 'GP',\n 'GQ',\n 'GR',\n 'GS',\n 'GT',\n 'GU',\n 'GW',\n 'GY',\n 'HK',\n 'HN',\n 'HR',\n 'HT',\n 'HU',\n 'ID',\n 'IE',\n 'IL',\n 'IM',\n 'IN',\n 'IO',\n 'IQ',\n 'IS',\n 'IT',\n 'JE',\n 'JM',\n 'JO',\n 'JP',\n 'KE',\n 'KG',\n 'KH',\n 'KI',\n 'KM',\n 'KN',\n 'KR',\n 'KW',\n 'KY',\n 'KZ',\n 'LA',\n 'LB',\n 'LC',\n 'LI',\n 'LK',\n 'LR',\n 'LS',\n 'LT',\n 'LU',\n 'LV',\n 'LY',\n 'MA',\n 'MC',\n 'MD',\n 'ME',\n 'MF',\n 'MG',\n 'MK',\n 'ML',\n 'MM',\n 'MN',\n 'MO',\n 'MQ',\n 'MR',\n 'MS',\n 'MT',\n 'MU',\n 'MV',\n 'MW',\n 'MX',\n 'MY',\n 'MZ',\n 'NA',\n 'NC',\n 'NE',\n 'NG',\n 'NI',\n 'NL',\n 'NO',\n 'NP',\n 'NR',\n 'NU',\n 'NZ',\n 'OM',\n 'PA',\n 'PE',\n 'PF',\n 'PG',\n 'PH',\n 'PK',\n 'PL',\n 'PM',\n 'PN',\n 'PR',\n 'PS',\n 'PT',\n 'PY',\n 'QA',\n 'RE',\n 'RO',\n 'RS',\n 'RU',\n 'RW',\n 'SA',\n 'SB',\n 'SC',\n 'SD',\n 'SE',\n 'SG',\n 'SH',\n 'SI',\n 'SJ',\n 'SK',\n 'SL',\n 'SM',\n 'SN',\n 'SO',\n 'SR',\n 'SS',\n 'ST',\n 'SV',\n 'SX',\n 'SZ',\n 'TA',\n 'TC',\n 'TD',\n 'TF',\n 'TG',\n 'TH',\n 'TJ',\n 'TK',\n 'TL',\n 'TM',\n 'TN',\n 'TO',\n 'TR',\n 'TT',\n 'TV',\n 'TW',\n 'TZ',\n 'UA',\n 'UG',\n 'US',\n 'UY',\n 'UZ',\n 'VA',\n 'VC',\n 'VE',\n 'VG',\n 'VN',\n 'VU',\n 'WF',\n 'WS',\n 'XK',\n 'YE',\n 'YT',\n 'ZA',\n 'ZM',\n 'ZW',\n 'ZZ',\n];\n\n// Stripe has restricted the number of shipping rates to 9.\nexport const stripeAllowedShippingOptionsLength = 9;\n","import { round } from 'lodash';\n\nimport {\n AmountTransformer,\n CustomerInitializeOptions,\n CustomerStrategy,\n InvalidArgumentError,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n Payment,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n ShippingOption,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n isStripePaymentMethodLike,\n StripeAdditionalActionRequired,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeError,\n StripeEventType,\n StripeInitializationData,\n StripeIntegrationService,\n StripeLinkV2Event,\n StripeLinkV2Options,\n StripeLinkV2ShippingRate,\n StripePaymentMethodType,\n StripeResult,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport {\n expressCheckoutAllowedCountryCodes,\n stripeAllowedShippingOptionsLength,\n} from './constants';\nimport { WithStripeOCSCustomerInitializeOptions } from './stripe-ocs-customer-initialize-options';\n\nexport default class StripeLinkV2CustomerStrategy implements CustomerStrategy {\n private _stripeClient?: StripeClient;\n private _stripeElements?: StripeElements;\n private _linkV2Element?: StripeElement;\n private _amountTransformer?: AmountTransformer;\n private _onComplete?: (orderId?: number) => Promise;\n private _loadingIndicatorContainer?: string;\n private _captureMethod?: 'automatic' | 'manual';\n private _currencyCode?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n private stripeIntegrationService: StripeIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithStripeOCSCustomerInitializeOptions,\n ): Promise {\n const { stripeocs } = options || {};\n\n if (!stripeocs) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"options\" argument is not provided.`,\n );\n }\n\n const { gatewayId, container } = stripeocs;\n\n if (!container || !gatewayId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const methodId = this._getMethodId(gatewayId);\n const state = await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n const paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n const { loadingContainerId, buttonHeight, onComplete } = stripeocs;\n\n this._loadingIndicatorContainer = loadingContainerId;\n\n this._onComplete = onComplete;\n\n if (!isStripePaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { initializationData } = paymentMethod;\n const { captureMethod } = initializationData;\n const stripeJsVersion =\n this.stripeIntegrationService.getStripeJsVersion(initializationData);\n\n this._captureMethod = captureMethod;\n this._stripeClient = await this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n stripeJsVersion,\n );\n\n await this._mountExpressCheckoutElement(container, this._stripeClient, buttonHeight);\n\n this._initializeEvents(methodId);\n }\n\n signIn() {\n return Promise.resolve();\n }\n\n signOut() {\n return Promise.resolve();\n }\n\n executePaymentMethodCheckout() {\n return Promise.resolve();\n }\n\n deinitialize() {\n return Promise.resolve();\n }\n\n private async _mountExpressCheckoutElement(\n container: string,\n stripeExpressCheckoutClient: StripeClient,\n buttonHeight = 40,\n ) {\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n const expressCheckoutOptions: StripeElementsCreateOptions = {\n shippingAddressRequired: shouldRequireShippingAddress,\n ...(shouldRequireShippingAddress\n ? { allowedShippingCountries: await this._getAvailableCountries() }\n : {}),\n ...(shouldRequireShippingAddress\n ? { shippingRates: [{ id: '_', amount: 0, displayName: 'Pending rates' }] }\n : {}),\n billingAddressRequired: true,\n emailRequired: true,\n phoneNumberRequired: true,\n paymentMethods: {\n link: StripeStringConstants.AUTO,\n applePay: StripeStringConstants.NEVER,\n googlePay: StripeStringConstants.NEVER,\n amazonPay: StripeStringConstants.NEVER,\n paypal: StripeStringConstants.NEVER,\n klarna: StripeStringConstants.NEVER,\n },\n // Minimal buttonHeight value is 40\n buttonHeight,\n };\n\n const { cartAmount } = this.paymentIntegrationService.getState().getCartOrThrow();\n\n const elementsOptions: StripeLinkV2Options = {\n mode: 'payment',\n amount: this._toCents(cartAmount),\n currency: this._getCurrency(),\n ...(this._captureMethod ? { captureMethod: this._captureMethod } : {}),\n };\n\n this._stripeElements = stripeExpressCheckoutClient.elements(elementsOptions);\n\n this._linkV2Element = this._stripeElements.create(\n StripeElementType.EXPRESS_CHECKOUT,\n expressCheckoutOptions,\n );\n this._linkV2Element.mount(`#${container}`);\n\n return this._linkV2Element;\n }\n\n /** Events * */\n\n private _initializeEvents(methodId: string): void {\n if (!this._linkV2Element) {\n return;\n }\n\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n\n if (shouldRequireShippingAddress) {\n this._linkV2Element.on(StripeElementEvent.SHIPPING_ADDRESS_CHANGE, async (event) =>\n this._onShippingAddressChange(event),\n );\n this._linkV2Element.on(StripeElementEvent.SHIPPING_RATE_CHANGE, async (event) =>\n this._onShippingRateChange(event),\n );\n }\n\n this._linkV2Element.on(StripeElementEvent.CONFIRM, async (event) =>\n this._onConfirm(event, methodId),\n );\n\n this._linkV2Element.on(StripeElementEvent.CANCEL, this._onCancel);\n }\n\n private async _onShippingAddressChange(event: StripeEventType): Promise {\n if (!('address' in event)) {\n return;\n }\n\n const shippingAddress = event.address;\n // Depending on the country, some fields can be missing or partially redacted.\n // For example, the shipping address in the US can only contain a city, state, and ZIP code.\n // The full shipping address appears in the confirm event object after the purchase is confirmed in the browser’s payment interface.\n const result = {\n firstName: '',\n lastName: '',\n phone: '',\n company: '',\n address1: '',\n address2: '',\n city: shippingAddress?.city || '',\n countryCode: shippingAddress?.country || '',\n postalCode: shippingAddress?.postal_code || '',\n stateOrProvince: shippingAddress?.state || '',\n stateOrProvinceCode: shippingAddress?.state || '',\n customFields: [],\n };\n\n await this.paymentIntegrationService.updateShippingAddress(result);\n\n const shippingRates = await this._getAvailableShippingOptions();\n\n await this._updateDisplayedPrice();\n\n if (!shippingRates?.length) {\n event.reject();\n } else {\n event.resolve({\n shippingRates,\n });\n }\n }\n\n private _onCancel() {\n throw new PaymentMethodCancelledError();\n }\n\n private async _onShippingRateChange(event: StripeEventType) {\n if ('shippingRate' in event) {\n const { shippingRate } = event;\n\n await this._handleShippingOptionChange(shippingRate?.id);\n\n await this._updateDisplayedPrice();\n\n event.resolve({});\n }\n }\n\n /** Confirm methods * */\n private async _onConfirm(event: StripeEventType, methodId: string) {\n if (\n 'billingDetails' in event &&\n 'shippingAddress' in event &&\n this._stripeClient &&\n this._stripeElements\n ) {\n await this._updateShippingAndBillingAddress(event);\n await this.paymentIntegrationService.submitOrder();\n\n const paymentPayload = this._getPaymentPayload(methodId);\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._processAdditionalAction(error, methodId);\n }\n }\n\n return Promise.resolve();\n }\n\n private async _updateShippingAndBillingAddress(event: StripeLinkV2Event) {\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n\n const firstName =\n event.shippingAddress?.name?.split(' ')[0] ||\n event.billingDetails?.name?.split(' ')[0] ||\n '';\n const lastName =\n event.shippingAddress?.name?.split(' ')[1] ||\n event.billingDetails?.name?.split(' ')[1] ||\n '';\n\n if (shouldRequireShippingAddress) {\n const shippingAddress = this._mapShippingAddress(\n event.shippingAddress,\n event.billingDetails,\n firstName,\n lastName,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n }\n\n const billingAddress = this._mapBillingAddress(\n event.shippingAddress,\n event.billingDetails,\n firstName,\n lastName,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n private _mapShippingAddress(\n shippingAddress: StripeLinkV2Event['shippingAddress'],\n billingDetails: StripeLinkV2Event['billingDetails'],\n firstName: string,\n lastName: string,\n ) {\n return {\n firstName,\n lastName,\n phone: billingDetails?.phone || '',\n company: '',\n address1: shippingAddress?.address?.line1 || '',\n address2: shippingAddress?.address?.line2 || '',\n city: shippingAddress?.address?.city || '',\n countryCode: shippingAddress?.address?.country || '',\n postalCode: shippingAddress?.address?.postal_code || '',\n stateOrProvince: shippingAddress?.address?.state || '',\n stateOrProvinceCode: shippingAddress?.address?.state || '',\n customFields: [],\n };\n }\n\n private _mapBillingAddress(\n shippingAddress: StripeLinkV2Event['shippingAddress'],\n billingDetails: StripeLinkV2Event['billingDetails'],\n firstName: string,\n lastName: string,\n ) {\n return {\n email: billingDetails?.email || '',\n firstName,\n lastName,\n phone: billingDetails?.phone || '',\n company: '',\n address1: billingDetails?.address?.line1 || '',\n address2: '',\n city: billingDetails?.address?.city || '',\n countryCode: billingDetails?.address?.country || '',\n postalCode: billingDetails?.address?.postal_code || '',\n stateOrProvince: billingDetails?.address?.state || '',\n stateOrProvinceCode: shippingAddress?.address?.state || '',\n customFields: [],\n };\n }\n\n private async _processAdditionalAction(error: unknown, methodId: string): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n if (!this._stripeClient || !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 additionalActionData,\n methodId,\n );\n\n const paymentPayload = this._getPaymentPayload(methodId, paymentIntent?.id || token);\n\n try {\n this._toggleLoadingIndicator(true);\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n await this._completeCheckoutFlow();\n } catch (error) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n } finally {\n this._toggleLoadingIndicator(false);\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n additionalActionData: StripeAdditionalActionRequired['data'],\n methodId: string,\n ): Promise {\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeIntegrationService.mapStripePaymentData(\n this._stripeElements,\n redirect_url,\n );\n let stripeError: StripeError | undefined;\n\n try {\n const isPaymentCompleted = await this.stripeIntegrationService.isPaymentCompleted(\n methodId,\n this._stripeClient,\n );\n\n const confirmationResult = !isPaymentCompleted\n ? await this._stripeClient?.confirmPayment({\n elements: stripePaymentData.elements,\n clientSecret: token,\n redirect: StripeStringConstants.IF_REQUIRED,\n confirmParams: {\n return_url: stripePaymentData.confirmParams?.return_url,\n },\n })\n : await this._stripeClient?.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 return this.stripeIntegrationService.throwStripeError(stripeError);\n }\n }\n\n private async _completeCheckoutFlow() {\n if (typeof this._onComplete === 'function') {\n return this._onComplete();\n }\n\n window.location.replace('/order-confirmation');\n\n return Promise.resolve();\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 ...(token ? { credit_card_token: { token } } : {}),\n confirm: false,\n method: StripePaymentMethodType.Link,\n };\n\n return {\n methodId,\n paymentData: {\n formattedPayload,\n },\n };\n }\n\n /** Utils * */\n\n private _shouldRequireShippingAddress() {\n const { getCartOrThrow } = this.paymentIntegrationService.getState();\n const { lineItems } = getCartOrThrow();\n\n return !!lineItems.physicalItems.length;\n }\n\n private async _updateDisplayedPrice() {\n if (this._stripeElements) {\n this._stripeElements.update({\n currency: this._getCurrency(),\n mode: 'payment',\n amount: await this._getTotalPrice(),\n });\n }\n }\n\n private _getCurrency() {\n if (!this._currencyCode) {\n const { code: currencyCode } = this.paymentIntegrationService\n .getState()\n .getCartOrThrow().currency;\n\n this._currencyCode = currencyCode.toLowerCase();\n }\n\n return this._currencyCode;\n }\n\n private async _getTotalPrice(): Promise {\n await this.paymentIntegrationService.loadCheckout();\n\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 this._toCents(+totalPrice);\n }\n\n private async _getAvailableCountries(): Promise {\n const countries = await this.paymentIntegrationService.loadShippingCountries();\n const deliverableCountries =\n countries.getShippingCountries()?.map((country) => country.code) || [];\n\n return deliverableCountries.filter((code) => {\n return expressCheckoutAllowedCountryCodes.includes(code);\n });\n }\n\n private async _getAvailableShippingOptions(): Promise {\n const state = this.paymentIntegrationService.getState();\n const consignments = state.getConsignments();\n\n if (!consignments?.[0]) {\n return;\n }\n\n const consignment = consignments[0];\n const options = (consignment.availableShippingOptions || []).map(\n this._getStripeShippingOption.bind(this),\n );\n const recommendedShippingOption = consignment.availableShippingOptions?.find(\n (shippingOption) => shippingOption.isRecommended,\n );\n const selectedId = consignment.selectedShippingOption?.id;\n const recommendedId = recommendedShippingOption?.id;\n\n if (selectedId) {\n // Set selected shipping option first in the array, as it will be selected by default\n options.sort((option) => (option.id === selectedId ? -1 : 0));\n } else if (recommendedId) {\n // Set recommended shipping option first in the array, as it will be selected by default\n options.sort((option) => (option.id === recommendedId ? -1 : 0));\n await this._handleShippingOptionChange(recommendedId);\n } else {\n await this._handleShippingOptionChange(options[0]?.id);\n }\n\n // Stripe has restricted the number of shipping rates.\n return options.slice(0, stripeAllowedShippingOptionsLength);\n }\n\n private _getStripeShippingOption({ id, cost, description }: ShippingOption) {\n return {\n id,\n displayName: description,\n amount: this._toCents(cost),\n };\n }\n\n private async _handleShippingOptionChange(optionId?: string) {\n if (!optionId || optionId === 'shipping_option_unselected') {\n return;\n }\n\n return this.paymentIntegrationService.selectShippingOption(optionId);\n }\n\n private _getAmountTransformer() {\n if (this._amountTransformer) {\n return this._amountTransformer;\n }\n\n const { getCart } = this.paymentIntegrationService.getState();\n const { currency } = getCart() || {};\n\n if (currency) {\n const amountTransformer = new AmountTransformer(currency.decimalPlaces);\n\n return amountTransformer;\n }\n }\n\n private _toCents(amount: number) {\n const fallbackValue = Math.round(amount * 100);\n const amountTransformer = this._getAmountTransformer();\n\n if (amountTransformer) {\n return amountTransformer.toInteger(amount);\n }\n\n return fallbackValue;\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 _getMethodId(gatewayId: string): string {\n const { initializationData: { checkoutSessionEnabled } = {} } =\n this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(gatewayId);\n\n return checkoutSessionEnabled\n ? StripePaymentMethodType.CHECKOUT_SESSION\n : StripePaymentMethodType.OCS;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\nimport { DEFAULT_CONTAINER_STYLES, LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport StripeLinkV2CustomerStrategy from './stripe-link-v2-customer-strategy';\n\nconst createStripeLinkV2CustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n const loadingIndicator = new LoadingIndicator({\n containerStyles: DEFAULT_CONTAINER_STYLES,\n });\n\n return new StripeLinkV2CustomerStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n loadingIndicator,\n );\n};\n\nexport default toResolvableModule(createStripeLinkV2CustomerStrategy, [{ id: 'stripeocs' }]);\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 { 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","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: [{ code: string }];\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 type AdyenComponentFieldVisibility = 'hidden' | 'readOnly' | 'editable';\n\nexport interface AdyenOpenInvoiceComponentVisibility {\n personalDetails?: AdyenComponentFieldVisibility;\n billingAddress?: AdyenComponentFieldVisibility;\n deliveryAddress?: AdyenComponentFieldVisibility;\n}\n\nexport interface AdyenBoletoComponentOptions extends AdyenComponentEvents {\n personalDetailsRequired?: boolean;\n billingAddressRequired?: boolean;\n showEmailAddress?: boolean;\n visibility?: AdyenOpenInvoiceComponentVisibility;\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 { 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","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 { 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.71.1/adyen.css`,\n {\n prepend: false,\n attributes: {\n integrity:\n 'sha384-5MvB4RnzvviA3VBT4KYABZ4HXNZG5LRqREEgd41xt/pf/QvKmsj2O9GuNuywRXx9',\n crossorigin: 'anonymous',\n },\n },\n ),\n this._scriptLoader.loadScript(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/5.71.1/adyen.js`,\n {\n async: true,\n attributes: {\n integrity:\n 'sha384-yvY2yFNR4WqIjPqP9MzjI+gJimmaJnAvj4rLHKvgJbgFD5fMuf8zIJrFJOW8Lhhf',\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 static readonly mountContainerMaxWaitMs = 5000;\n private static readonly mountContainerPollIntervalMs = 50;\n\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._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 paymentData.instrumentId,\n bigpayToken,\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 _getLocale(): string | undefined {\n const locale = this.paymentIntegrationService.getState().getLocale();\n\n if (locale && locale.substring(0, 2) === 'es') {\n return 'es';\n }\n\n return locale;\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 void this._mountElement(additionalActionComponent, containerId)\n .then(() => {\n if (onLoad && typeof onLoad === 'function') {\n onLoad(() => {\n reject(new PaymentMethodCancelledError());\n additionalActionComponent.unmount();\n });\n }\n })\n .catch(reject);\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 async _mountCardVerificationComponent(): Promise {\n const adyenv3 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n\n if (!adyenv3.cardVerificationContainerId) {\n return undefined;\n }\n\n const 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 await this._mountElement(\n cardVerificationComponent,\n adyenv3.cardVerificationContainerId,\n );\n } catch {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return cardVerificationComponent;\n }\n\n private async _mountPaymentComponent(paymentMethod: PaymentMethod): Promise {\n const adyenv3 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n const billingAddress = this.paymentIntegrationService.getState().getBillingAddress();\n const { prefillCardHolderName } = paymentMethod.initializationData;\n\n const paymentComponent = adyenClient.create(paymentMethod.method, {\n ...(this._isOneyPaymentMethod(paymentMethod.method)\n ? {\n visibility: {\n personalDetails: 'hidden',\n billingAddress: 'hidden',\n deliveryAddress: 'hidden',\n },\n }\n : {}),\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 await this._mountElement(paymentComponent, adyenv3.containerId);\n } catch {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return paymentComponent;\n }\n\n private _isOneyPaymentMethod(method: string): boolean {\n return method.startsWith('facilypay');\n }\n\n private async _processAdditionalAction(\n error: unknown,\n shouldSaveInstrument?: boolean,\n shouldSetAsDefaultInstrument?: boolean,\n paymentToken?: string,\n bigpayToken?: Record,\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 const basePaymentData = {\n ...payment.paymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n };\n\n const tokenData =\n shouldSetAsDefaultInstrument && !shouldSaveInstrument\n ? {\n instrumentId: paymentToken,\n formattedPayload: {\n bigpay_token: {\n ...bigpayToken,\n token: paymentToken,\n },\n },\n }\n : {};\n\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...basePaymentData,\n ...tokenData,\n },\n });\n } catch (paymentError) {\n return this._processAdditionalAction(\n paymentError,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n paymentToken,\n bigpayToken,\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 async _mountElement(\n adyenComponent: AdyenComponent,\n containerId: string,\n ): Promise {\n await this._waitForMountContainer(containerId);\n\n try {\n adyenComponent.mount(`#${containerId}`);\n } catch {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n }\n\n private async _waitForMountContainer(containerId: string): Promise {\n const maxAttempts = Math.ceil(\n Adyenv3PaymentStrategy.mountContainerMaxWaitMs /\n Adyenv3PaymentStrategy.mountContainerPollIntervalMs,\n );\n const pollIntervalMs = Adyenv3PaymentStrategy.mountContainerPollIntervalMs;\n\n let step = 0;\n\n const poll = async (): Promise => {\n if (step === maxAttempts) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (document.getElementById(containerId)) {\n return;\n }\n\n await new Promise((resolve) => {\n setTimeout(resolve, pollIntervalMs);\n });\n\n step += 1;\n await poll();\n };\n\n await poll();\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","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 {\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","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';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const withHttpsExperimentName = 'PI-4789.afterpay_script_use_https';\n const withHttps = isExperimentEnabled(features, withHttpsExperimentName, false);\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._afterpaySdk = await this._afterpayScriptLoader.load(\n paymentMethod,\n countryCode,\n withHttps,\n );\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.js',\n HTTPS_PROD = 'https://portal.afterpay.com/afterpay-async.js',\n HTTPS_SANDBOX = 'https://portal.sandbox.afterpay.com/afterpay.js',\n}\n\nenum SCRIPTS_US {\n PROD = '//portal.afterpay.com/afterpay-async.js',\n SANDBOX = '//portal.sandbox.afterpay.com/afterpay.js',\n HTTPS_PROD = 'https://portal.afterpay.com/afterpay-async.js',\n HTTPS_SANDBOX = 'https://portal.sandbox.afterpay.com/afterpay.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(\n method: PaymentMethod,\n countryCode: string,\n withHttps = false,\n ): Promise {\n const testMode = method.config.testMode || false;\n const scriptURI = this._getScriptURI(countryCode, testMode, withHttps);\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, withHttps = false): string {\n if (countryCode === 'US') {\n if (withHttps) {\n return testMode ? SCRIPTS_US.HTTPS_SANDBOX : SCRIPTS_US.HTTPS_PROD;\n }\n\n return testMode ? SCRIPTS_US.SANDBOX : SCRIPTS_US.PROD;\n }\n\n if (withHttps) {\n return testMode ? SCRIPTS_DEFAULT.HTTPS_SANDBOX : SCRIPTS_DEFAULT.HTTPS_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 if (!this._amazonPayButton) {\n throw new InvalidArgumentError(\n 'Unable to render the Amazon Pay button to an invalid HTML container element.',\n );\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 ApplePayScriptLoader from './apple-pay-script-loader';\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 private _applePayScriptLoader: ApplePayScriptLoader,\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 await this._applePayScriptLoader.loadSdk();\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 (\n paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE &&\n paymentMethod.clientToken\n ) {\n this._braintreeSdk.initialize(paymentMethod.clientToken);\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","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\n} 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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n\n return new ApplePayPaymentStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), window, braintreeSDKVersionManager),\n ),\n new ApplePayScriptLoader(new ScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createApplePayPaymentStrategy, [{ id: 'applepay' }]);\n","export const LOADING_INDICATOR_STYLES = {\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\n};\n","import { MessagesStyleOptions, PayPalBNPLConfigurationItem } from '../bigcommerce-payments-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","export interface BaseInstrument {\n bigpayToken: string;\n defaultInstrument: boolean;\n provider: string;\n trustedShippingAddress: boolean;\n method: string;\n type: string;\n}\n\nexport function isBaseInstrument(instrument: unknown): instrument is BaseInstrument {\n if (typeof instrument !== 'object' || instrument === null) {\n return false;\n }\n\n return (\n 'bigpayToken' in instrument &&\n 'defaultInstrument' in instrument &&\n 'provider' in instrument &&\n 'trustedShippingAddress' in instrument &&\n 'method' in instrument &&\n 'type' in instrument\n );\n}\n","import {\n getPaypalMessagesStylesFromBNPLConfig,\n isBigCommercePaymentsProviderError,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalMessagesSdk,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isBaseInstrument } from '@bigcommerce/checkout-sdk/utility';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtons,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n ClickCallbackActions,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsPaymentInitializeOptions, {\n WithBigCommercePaymentsPaymentInitializeOptions,\n} from './bigcommerce-payments-payment-initialize-options';\n\nexport default class BigCommercePaymentsPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: BigCommercePaymentsButtons;\n private bigcommerce_payments?: BigCommercePaymentsPaymentInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private paypalSdkHelper: PayPalSdkHelper,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithBigCommercePaymentsPaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments } = options || {};\n\n this.bigcommerce_payments = bigcommerce_payments;\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 (!bigcommerce_payments) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments\" 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 const { container, bannerContainerId } = bigcommerce_payments;\n\n const {\n orderId,\n paypalBNPLConfiguration = [],\n isPayPalCreditAvailable,\n } = paymentMethod.initializationData || {};\n\n if (bannerContainerId !== undefined) {\n if (!document.getElementById(bannerContainerId)) {\n // eslint-disable-next-line no-console\n console.error('Unable to create banner without valid banner container ID.');\n\n return;\n }\n\n const bannerConfiguration = paypalBNPLConfiguration?.find(\n ({ id }) => id === 'checkout',\n );\n\n if (isPayPalCreditAvailable || !bannerConfiguration?.status) {\n return;\n }\n\n const paypalMessages = await this.paypalSdkHelper.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n );\n\n if (!paypalMessages || typeof paypalMessages?.Messages !== 'function') {\n console.error(\n '[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n return this.renderMessages(paypalMessages, bannerContainerId, bannerConfiguration);\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 this.loadingIndicatorContainer = container?.split('#')[1];\n\n await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n if (bigcommerce_payments.onInit && typeof bigcommerce_payments.onInit === 'function') {\n bigcommerce_payments.onInit(() => this.renderButton(methodId, bigcommerce_payments));\n }\n\n if (\n bigcommerce_payments.shouldRenderPayPalButtonOnInitialization === undefined ||\n bigcommerce_payments.shouldRenderPayPalButtonOnInitialization\n ) {\n this.renderButton(methodId, bigcommerce_payments);\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const { onError } = this.bigcommerce_payments || {};\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)) {\n await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(payment.methodId);\n\n await new Promise((_resolve, reject) => {\n if (this.bigcommerce_payments) {\n this.paypalButton?.close();\n this.renderButton(payment.methodId, this.bigcommerce_payments);\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 bigcommerce_payments: BigCommercePaymentsPaymentInitializeOptions,\n ): void {\n const paypalSdk = this.bigCommercePaymentsIntegrationService.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 } = bigcommerce_payments;\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"container\" argument is not provided.',\n );\n }\n\n const buttonOptions: BigCommercePaymentsButtonsOptions = {\n ...(this.isAppSwitchEnabled(methodId) && {\n appSwitchWhenAvailable: true,\n }),\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.bigCommercePaymentsIntegrationService.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 if (this.paypalButton.hasReturned?.() && this.isAppSwitchEnabled(methodId)) {\n this.paypalButton.resume?.();\n } else {\n this.paypalButton.render(container);\n }\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: BigCommercePaymentsPaymentInitializeOptions['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: BigCommercePaymentsPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm?.();\n }\n\n private handleError(\n error: unknown,\n onError: BigCommercePaymentsPaymentInitializeOptions['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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_paymentscheckout',\n {\n shouldSaveInstrument: fieldsValues?.shouldSaveInstrument || false,\n },\n );\n }\n\n /**\n *\n * Vaulting flow methods\n *\n * */\n private getFieldsValues(): HostedInstrument | undefined {\n const { getFieldsValues } = this.bigcommerce_payments || {};\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 findInstrument = instruments?.find(\n (instrument) =>\n isBaseInstrument(instrument) &&\n instrument.bigpayToken === paymentData.instrumentId,\n );\n const trustedShippingAddress = isBaseInstrument(findInstrument)\n ? findInstrument.trustedShippingAddress\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 /**\n *\n * Render Pay Later Messages\n *\n * */\n private renderMessages(\n paypalMessages: PayPalMessagesSdk,\n bannerContainerId: string,\n bannerConfiguration: PayPalBNPLConfigurationItem,\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: checkout.outstandingBalance,\n placement: 'payment',\n style: getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\n };\n\n paypalMessages.Messages(paypalMessagesOptions).render(`#${bannerContainerId}`);\n }\n\n private isProviderError(error: unknown): boolean {\n if (isBigCommercePaymentsProviderError(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 /**\n *\n * AppSwitch enabling handling\n *\n */\n private isAppSwitchEnabled(methodId: string): boolean {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n return paymentMethod.initializationData?.isAppSwitchEnabled ?? 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 isBigCommercePaymentsProviderError(error: unknown): error is ProviderError {\n return typeof error === 'object' && error !== null && 'errors' in error;\n}\n","import { createBigCommercePaymentsSdk } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport { LOADING_INDICATOR_STYLES } from '../bigcommerce-payments-constants';\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsPaymentStrategy from './bigcommerce-payments-payment-strategy';\n\nconst createBigCommercePaymentsPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n createBigCommercePaymentsSdk(),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsPaymentStrategy, [\n { id: 'bigcommerce_payments' },\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 BigCommercePaymentsFastlaneUtils,\n BigCommercePaymentsInitializationData,\n getFastlaneStyles,\n isBigcommerceFastlaneRequestError,\n isPayPalFastlaneCustomer,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneCardComponentMethods,\n PayPalFastlaneCardComponentOptions,\n PayPalFastlanePaymentFormattedPayload,\n PayPalFastlaneSdk,\n PayPalSdkHelper,\n TDSecureAuthenticationState,\n TDSecureVerificationMethod,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport BigCommercePaymentsRequestSender from '../bigcommerce-payments-request-sender';\nimport { LiabilityShiftEnum } from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsFastlanePaymentInitializeOptions, {\n WithBigCommercePaymentsFastlanePaymentInitializeOptions,\n} from './bigcommerce-payments-fastlane-payment-initialize-options';\n\nexport default class BigCommercePaymentsFastlanePaymentStrategy implements PaymentStrategy {\n private paypalComponentMethods?: PayPalFastlaneCardComponentMethods;\n private threeDSVerificationMethod?: string;\n private paypalFastlaneSdk?: PayPalFastlaneSdk;\n private bigcommerce_payments_fastlane?: BigCommercePaymentsFastlanePaymentInitializeOptions;\n private methodId?: string;\n private orderId?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsRequestSender: BigCommercePaymentsRequestSender,\n private bigCommercePaymentsSdk: PayPalSdkHelper,\n private bigCommercePaymentsFastlaneUtils: BigCommercePaymentsFastlaneUtils,\n ) {}\n\n /**\n *\n * Default methods\n *\n * */\n async initialize(\n options: PaymentInitializeOptions & WithBigCommercePaymentsFastlanePaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_fastlane } = 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.methodId = methodId;\n\n if (!bigcommerce_payments_fastlane) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_fastlane\" argument is not provided.',\n );\n }\n\n this.bigcommerce_payments_fastlane = bigcommerce_payments_fastlane;\n\n if (\n !bigcommerce_payments_fastlane.onInit ||\n typeof bigcommerce_payments_fastlane.onInit !== 'function'\n ) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_fastlane.onInit\" argument is not provided or it is not a function.',\n );\n }\n\n if (\n !bigcommerce_payments_fastlane.onChange ||\n typeof bigcommerce_payments_fastlane.onChange !== 'function'\n ) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_fastlane.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 this.threeDSVerificationMethod =\n paymentMethod.initializationData?.threeDSVerificationMethod;\n\n this.paypalFastlaneSdk = await this.bigCommercePaymentsSdk.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 bigcommerce_payments_fastlane?.styles,\n );\n\n await this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(\n this.paypalFastlaneSdk,\n !!isDeveloperModeApplicable,\n fastlaneStyles,\n );\n\n if (this.shouldRunAuthenticationFlow()) {\n await this.runPayPalAuthenticationFlowOrThrow(methodId);\n }\n\n await this.initializePayPalPaymentComponent();\n\n bigcommerce_payments_fastlane.onInit((container: string) =>\n this.renderPayPalPaymentComponent(container),\n );\n bigcommerce_payments_fastlane.onChange(() =>\n this.handlePayPalStoredInstrumentChange(methodId),\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 { paymentData, methodId } = payment;\n\n const isVaultedFlow = paymentData && isVaultedInstrument(paymentData);\n\n try {\n await this.paymentIntegrationService.submitOrder(order, options);\n\n const paymentPayload = isVaultedFlow\n ? await this.prepareVaultedInstrumentPaymentPayload(methodId, paymentData)\n : await this.preparePaymentPayload(methodId, paymentData);\n\n await this.paymentIntegrationService.submitPayment(\n paymentPayload,\n );\n\n this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId();\n } catch (error) {\n if (\n isBigcommerceFastlaneRequestError(error) &&\n error.response.name === 'INVALID_REQUEST'\n ) {\n const invalidRequestError = {\n translationKey: 'payment.errors.invalid_request_error',\n };\n\n this.handleError(invalidRequestError);\n\n return Promise.reject();\n }\n\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.bigCommercePaymentsFastlaneUtils.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.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(customerEmail);\n\n const authenticationResult =\n await this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(\n customerContextId,\n );\n\n const { authenticationState, addresses, instruments } =\n this.bigCommercePaymentsFastlaneUtils.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 if (isAuthenticationFlowCanceled) {\n this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId();\n } else {\n this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(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 * BigCommercePayments 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.bigCommercePaymentsFastlaneUtils.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 paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n const is3DSEnabled =\n this.isBigcommercePaymentsFastlaneThreeDSAvailable() &&\n paymentMethod.config.is3dsEnabled;\n\n const nonce = is3DSEnabled ? await this.get3DSNonce(instrumentId) : instrumentId;\n\n await this.createOrder(nonce);\n\n return {\n methodId,\n paymentData: {\n formattedPayload: {\n paypal_fastlane_token: {\n order_id: this.orderId,\n token: nonce,\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 billingAddress = state.getBillingAddressOrThrow();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\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:\n this.bigCommercePaymentsFastlaneUtils.mapBcToPayPalAddress(billingAddress),\n });\n\n const is3DSEnabled =\n this.isBigcommercePaymentsFastlaneThreeDSAvailable() &&\n paymentMethod.config.is3dsEnabled;\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n const nonce = is3DSEnabled ? await this.get3DSNonce(id) : id;\n\n await this.createOrder(nonce);\n\n return {\n methodId,\n paymentData: {\n ...paymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n formattedPayload: {\n paypal_fastlane_token: {\n order_id: this.orderId,\n token: nonce,\n },\n },\n },\n };\n }\n\n private async createOrder(id: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cartId = state.getCartOrThrow().id;\n\n if (this.methodId) {\n const { orderId } = await this.bigCommercePaymentsRequestSender.createOrder(\n this.methodId,\n {\n cartId,\n fastlaneToken: id,\n },\n );\n\n this.orderId = orderId;\n }\n }\n\n /**\n *\n * 3DSecure methods\n *\n * */\n private async get3DSNonce(nonce: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const order = state.getOrderOrThrow();\n const checkoutUrl = state.getStoreConfigOrThrow().links.checkoutLink;\n\n const threeDomainSecureComponent = this.paypalFastlaneSdk?.ThreeDomainSecureClient;\n\n if (!threeDomainSecureComponent) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n const threeDomainSecureParameters = {\n amount: order.orderAmount.toFixed(2),\n currency: cart.currency.code,\n nonce,\n threeDSRequested: this.threeDSVerificationMethod === TDSecureVerificationMethod.Always,\n transactionContext: {\n experience_context: {\n locale: 'en-US',\n return_url: checkoutUrl,\n cancel_url: checkoutUrl,\n },\n },\n };\n\n const isThreeDomainSecureEligible = await threeDomainSecureComponent.isEligible(\n threeDomainSecureParameters,\n );\n\n if (\n this.threeDSVerificationMethod === TDSecureVerificationMethod.Always &&\n !isThreeDomainSecureEligible\n ) {\n throw new PaymentMethodInvalidError();\n }\n\n if (isThreeDomainSecureEligible) {\n const {\n liabilityShift,\n authenticationState,\n nonce: threeDSNonce,\n } = await threeDomainSecureComponent.show();\n\n if (\n liabilityShift === LiabilityShiftEnum.No ||\n liabilityShift === LiabilityShiftEnum.Unknown ||\n authenticationState === TDSecureAuthenticationState.Errored ||\n authenticationState === TDSecureAuthenticationState.Cancelled\n ) {\n throw new PaymentMethodInvalidError();\n }\n\n if (\n authenticationState === TDSecureAuthenticationState.Succeeded &&\n [LiabilityShiftEnum.Yes, LiabilityShiftEnum.Possible].includes(liabilityShift)\n ) {\n return threeDSNonce;\n }\n }\n\n return nonce;\n }\n\n /**\n *\n * BigCommercePayments Fastlane instrument change\n *\n */\n private async handlePayPalStoredInstrumentChange(\n methodId: string,\n ): Promise {\n const paypalAxoSdk = this.bigCommercePaymentsFastlaneUtils.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 =\n this.bigCommercePaymentsFastlaneUtils.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 /**\n *\n * Bigcommerce Payments Fastlane experiments handling\n *\n */\n private isBigcommercePaymentsFastlaneThreeDSAvailable(): boolean {\n const state = this.paymentIntegrationService.getState();\n const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n\n return isExperimentEnabled(features, 'PROJECT-7080.bcp_fastlane_three_ds');\n }\n\n private handleError(error: unknown): void {\n if (\n this.bigcommerce_payments_fastlane?.onError &&\n typeof this.bigcommerce_payments_fastlane.onError === 'function'\n ) {\n this.bigcommerce_payments_fastlane.onError(error);\n }\n }\n}\n","export interface BigcommerceFastlaneRequestError {\n name: string;\n message: string;\n response: {\n name: string;\n };\n}\n\nexport default function isBigcommerceFastlaneRequestError(\n error: unknown,\n): error is BigcommerceFastlaneRequestError {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'message' in error &&\n 'response' in error &&\n 'name' in (error as BigcommerceFastlaneRequestError).response\n );\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n createBigCommercePaymentsFastlaneUtils,\n createBigCommercePaymentsSdk,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsRequestSender from '../bigcommerce-payments-request-sender';\n\nimport BigCommercePaymentsFastlanePaymentStrategy from './bigcommerce-payments-fastlane-payment-strategy';\n\nconst createBigCommercePaymentsFastlanePaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsFastlanePaymentStrategy\n> = (paymentIntegrationService) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new BigCommercePaymentsFastlanePaymentStrategy(\n paymentIntegrationService,\n new BigCommercePaymentsRequestSender(createRequestSender({ host: getHost() })),\n createBigCommercePaymentsSdk(),\n createBigCommercePaymentsFastlaneUtils(),\n );\n};\n\nexport default toResolvableModule(createBigCommercePaymentsFastlanePaymentStrategy, [\n { id: 'bigcommerce_payments_fastlane' }, // BigCommercePayments Fastlane relates to 'bigcommerce_payments_fastlane' method id\n]);\n","import {\n BigCommercePaymentsInitializationData,\n getPaypalMessagesStylesFromBNPLConfig,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalMessagesSdk,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtons,\n BigCommercePaymentsButtonsOptions,\n ClickCallbackActions,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsPayLaterPaymentInitializeOptions, {\n WithBigCommercePaymentsPayLaterPaymentInitializeOptions,\n} from './bigcommerce-payments-paylater-payment-initialize-options';\n\nexport default class BigCommercePaymentsPayLaterPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private bigCommercePaymentsButtons?: BigCommercePaymentsButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private loadingIndicator: LoadingIndicator,\n private paypalSdkHelper: PayPalSdkHelper,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions &\n WithBigCommercePaymentsPayLaterPaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_paylater } = 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 (!bigcommerce_payments_paylater) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_paylater\" 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 const { paypalBNPLConfiguration = [], orderId } = paymentMethod.initializationData || {};\n const { bannerContainerId, container } = bigcommerce_payments_paylater;\n\n if (bannerContainerId !== undefined) {\n if (!document.getElementById(bannerContainerId)) {\n // eslint-disable-next-line no-console\n console.error('Unable to create banner without valid banner container ID.');\n\n return;\n }\n\n const bannerConfiguration =\n paypalBNPLConfiguration &&\n paypalBNPLConfiguration.find(({ id }) => id === 'checkout');\n\n if (!bannerConfiguration?.status) {\n return;\n }\n\n const paypalMessages = await this.paypalSdkHelper.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n );\n\n return this.renderMessages(paypalMessages, bannerContainerId, bannerConfiguration);\n }\n\n // Info:\n // The BigCommercePayments 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 BigCommercePayments button.\n if (orderId) {\n this.orderId = orderId;\n\n return;\n }\n\n await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = container?.split('#')[1];\n\n this.renderButton(methodId, bigcommerce_payments_paylater);\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.bigCommercePaymentsIntegrationService.submitPayment(\n payment.methodId,\n this.orderId,\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.orderId = undefined;\n\n this.bigCommercePaymentsButtons?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n bigcommerce_payments_paylater: BigCommercePaymentsPayLaterPaymentInitializeOptions,\n ): void {\n if (!bigcommerce_payments_paylater?.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"container\" argument is not provided.',\n );\n }\n\n const bigCommerceSdk = this.bigCommercePaymentsIntegrationService.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 } =\n bigcommerce_payments_paylater;\n\n const fundingSources = [bigCommerceSdk.FUNDING.PAYLATER, bigCommerceSdk.FUNDING.CREDIT];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (hasRenderedSmartButton) {\n return;\n }\n\n const buttonOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(\n checkoutPaymentButtonStyles,\n ),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_paylater',\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.bigCommercePaymentsButtons = bigCommerceSdk.Buttons(buttonOptions);\n\n if (\n !this.bigCommercePaymentsButtons.isEligible() &&\n fundingSource === bigCommerceSdk.FUNDING.PAYLATER\n ) {\n return;\n }\n\n if (\n !this.bigCommercePaymentsButtons.isEligible() &&\n fundingSource === bigCommerceSdk.FUNDING.CREDIT\n ) {\n throw new NotImplementedError(\n `BigCommercePayments ${fundingSource} is not available for your region. Please use BigCommercePayments Checkout instead.`,\n );\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.bigCommercePaymentsButtons.render(container);\n hasRenderedSmartButton = true;\n });\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: BigCommercePaymentsPayLaterPaymentInitializeOptions['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: BigCommercePaymentsPayLaterPaymentInitializeOptions['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: BigCommercePaymentsPayLaterPaymentInitializeOptions['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,\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: checkout.outstandingBalance,\n placement: 'payment',\n style: getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\n };\n\n paypalMessages.Messages(paypalMessagesOptions).render(`#${bannerContainerId}`);\n }\n}\n","import { createBigCommercePaymentsSdk } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport { LOADING_INDICATOR_STYLES } from '../bigcommerce-payments-constants';\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsPayLaterPaymentStrategy from './bigcommerce-payments-paylater-payment-strategy';\n\nconst createBigCommercePaymentsPayLaterPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsPayLaterPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsPayLaterPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n createBigCommercePaymentsSdk(),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsPayLaterPaymentStrategy, [\n { id: 'bigcommerce_payments_paylater' },\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n BigCommercePaymentsInitializationData,\n BirthDate,\n PayPalOrderStatus,\n} from '../bigcommerce-payments-types';\n\nimport {\n BigCommercePaymentsRatePayPaymentInitializeOptions,\n WithBigCommercePaymentsRatePayPaymentInitializeOptions,\n} from './bigcommerce-payments-ratepay-initialize-options';\n\nconst POLLING_INTERVAL = 3000;\nconst MAX_POLLING_TIME = 300000;\n\nexport default class BigCommercePaymentsRatePayPaymentStrategy implements PaymentStrategy {\n private guid?: string;\n private bigcommerce_payments_ratepay?: BigCommercePaymentsRatePayPaymentInitializeOptions;\n private loadingIndicatorContainer?: string;\n private pollingTimer = 0;\n private stopPolling = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\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 & WithBigCommercePaymentsRatePayPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, bigcommerce_payments_ratepay } = 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 (!bigcommerce_payments_ratepay) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_ratepay\" argument is not provided.`,\n );\n }\n\n const { legalTextContainer, container, loadingContainerId } = bigcommerce_payments_ratepay;\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.bigcommerce_payments_ratepay = bigcommerce_payments_ratepay;\n\n await this.bigCommercePaymentsIntegrationService.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.bigcommerce_payments_ratepay || {};\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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_apmscheckout',\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.bigcommerce_payments_ratepay || {};\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 bigCommercePaymentsSdk =\n this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const ratePayButton = bigCommercePaymentsSdk.Legal({\n fundingSource: bigCommercePaymentsSdk.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.bigcommerce_payments_ratepay || {};\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 & WithBigCommercePaymentsRatePayPaymentInitializeOptions,\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.bigCommercePaymentsIntegrationService.getOrderStatus(\n 'bigcommerce_payments_apms',\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 bigcommerce_payments_ratepay: this.bigcommerce_payments_ratepay,\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 { LOADING_INDICATOR_STYLES } from '../bigcommerce-payments-constants';\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsRatePayPaymentStrategy from './bigcommerce-payments-ratepay-payment-strategy';\n\nconst createBigCommercePaymentsRatePayPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsRatePayPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsRatePayPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n new LoadingIndicator({\n containerStyles: { ...LOADING_INDICATOR_STYLES, position: 'fixed' },\n }),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsRatePayPaymentStrategy, [\n { gateway: 'bigcommerce_payments_apms', id: 'ratepay' },\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 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 { isNil, omitBy } from 'lodash';\n\nimport {\n BigCommercePaymentsFastlaneUtils,\n BigCommercePaymentsInitializationData,\n isBigCommercePaymentsFastlaneCustomer,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\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';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n BigCommercePaymentsCardFields,\n BigCommercePaymentsCardFieldsConfig,\n BigCommercePaymentsCardFieldsOnApproveData,\n BigCommercePaymentsCardFieldsState,\n BigCommercePaymentsFields,\n BigCommercePaymentsHostedFieldsRenderOptions,\n LiabilityShiftEnum,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsCreditCardsPaymentInitializeOptions, {\n WithBigCommercePaymentsCreditCardsPaymentInitializeOptions,\n} from './bigcommerce-payments-credit-cards-payment-initialize-options';\n\nexport default class BigCommercePaymentsCreditCardsPaymentStrategy implements PaymentStrategy {\n private executionPaymentData?: OrderPaymentRequestBody['paymentData'];\n private isCreditCardForm?: boolean;\n private isCreditCardVaultedForm?: boolean;\n\n private cardFields?: BigCommercePaymentsCardFields;\n private cvvField?: BigCommercePaymentsFields;\n private expiryField?: BigCommercePaymentsFields;\n private numberField?: BigCommercePaymentsFields;\n private nameField?: BigCommercePaymentsFields;\n\n private hostedFormOptions?: HostedFormOptions;\n private returnedOrderId?: string;\n private returnedVaultedToken?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private bigCommercePaymentsSdk: PayPalSdkHelper,\n private bigCommercePaymentsFastlaneUtils: BigCommercePaymentsFastlaneUtils,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions &\n WithBigCommercePaymentsCreditCardsPaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_creditcards } = options;\n const bigCommercePaymentsInitializationOptions = bigcommerce_payments_creditcards;\n\n const { form, onCreditCardFieldsRenderingError, onLoadComplete } =\n bigCommercePaymentsInitializationOptions || {};\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.bigcommerce_payments_creditcards.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.bigCommercePaymentsIntegrationService.loadPayPalSdk(\n methodId,\n undefined,\n true,\n true,\n );\n\n if (this.isCreditCardForm || this.isCreditCardVaultedForm) {\n await this.initializeFields(form, onCreditCardFieldsRenderingError);\n }\n\n onLoadComplete?.();\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 // The condition gets triggered when customer pays with vaulted instrument and shipping address is trusted\n const { orderId } =\n await this.bigCommercePaymentsIntegrationService.createOrderCardFields(\n 'bigcommerce_payments_creditcardscheckout',\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?: BigCommercePaymentsCreditCardsPaymentInitializeOptions['onCreditCardFieldsRenderingError'],\n ): Promise {\n const { fields, styles } = formOptions;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const executeCallback = this.getExecuteCallback(fields);\n\n const cardFieldsConfig: BigCommercePaymentsCardFieldsConfig = {\n style: this.getInputStyles(styles),\n onApprove: ({\n orderID,\n vaultSetupToken,\n liabilityShift,\n }: BigCommercePaymentsCardFieldsOnApproveData) => {\n if (\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.bigCommercePaymentsIntegrationService.createOrderCardFields(\n 'bigcommerce_payments_creditcardscheckout',\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.bigCommercePaymentsIntegrationService.createOrderCardFields(\n 'bigcommerce_payments_creditcardscheckout',\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({\n orderID,\n vaultSetupToken,\n }: BigCommercePaymentsCardFieldsOnApproveData) {\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 }: BigCommercePaymentsCardFieldsState):\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 * */\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 }: BigCommercePaymentsCardFieldsState): HostedFieldValidateEventData {\n const updatedFields = { ...fields };\n\n delete updatedFields.cardNameField;\n\n const fieldsKeys = Object.keys(updatedFields) as Array<\n keyof BigCommercePaymentsCardFieldsState['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(): BigCommercePaymentsCardFields {\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 ): BigCommercePaymentsHostedFieldsRenderOptions['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: BigCommercePaymentsCardFieldsState,\n ): void {\n formOptions?.onValidate?.(this.getValidityData(event));\n }\n\n private onFocusHandler(\n formOptions: HostedFormOptions,\n event: BigCommercePaymentsCardFieldsState,\n ): void {\n formOptions?.onFocus?.(this.getFieldTypeByEmittedField(event));\n }\n\n private onBlurHandler(\n formOptions: HostedFormOptions,\n event: BigCommercePaymentsCardFieldsState,\n ): void {\n formOptions?.onBlur?.(this.getFieldTypeByEmittedField(event));\n }\n\n private onInputSubmitRequest(\n formOptions: HostedFormOptions,\n event: BigCommercePaymentsCardFieldsState,\n ): void {\n formOptions?.onEnter?.(this.getFieldTypeByEmittedField(event));\n }\n\n /**\n *\n * BigCommercePayments Accelerated checkout related methods\n *\n */\n // TODO: remove this part when BCP Fastlane 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 bigCommercePaymentsPaymentProviderCustomer = isBigCommercePaymentsFastlaneCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n return (\n paymentMethod?.initializationData?.isAcceleratedCheckoutEnabled &&\n paymentMethod?.initializationData?.isBigCommercePaymentsAnalyticsV2Enabled &&\n !bigCommercePaymentsPaymentProviderCustomer?.authenticationState\n );\n }\n\n // TODO: remove this part when BCP Fastlane 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.bigCommercePaymentsSdk.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n );\n\n await this.bigCommercePaymentsFastlaneUtils.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 PaymentProviderCustomer,\n PayPalConnectCustomer,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isBigCommercePaymentsFastlaneCustomer(\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 createBigCommercePaymentsFastlaneUtils,\n createBigCommercePaymentsSdk,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsCreditCardsPaymentStrategy from './bigcommerce-payments-credit-cards-payment-strategy';\n\nconst createBigCommercePaymentsCreditCardsPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsCreditCardsPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsCreditCardsPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n createBigCommercePaymentsSdk(),\n createBigCommercePaymentsFastlaneUtils(),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsCreditCardsPaymentStrategy, [\n { id: 'bigcommerce_payments_creditcards' },\n]);\n","import { noop } from 'lodash';\n\nimport {\n PayPalApmSdk,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodClientUnavailableError,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n TimeoutError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtons,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n NonInstantAlternativePaymentMethods,\n PayPalOrderStatus,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions, {\n WithBigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\n} from './bigcommerce-payments-alternative-methods-payment-initialize-options';\n\nconst POLLING_INTERVAL = 3000;\nconst MAX_POLLING_TIME = 300000;\n\nexport default class BigCommercePaymentsAlternativeMethodsPaymentStrategy\n implements PaymentStrategy\n{\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private bigCommercePaymentsButton?: BigCommercePaymentsButtons;\n private paypalApms?: PayPalApmSdk;\n private pollingTimer = 0;\n private stopPolling = noop;\n private isPollingEnabled = false;\n private bigCommercePaymentsAlternativeMethods?: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private bigCommercePaymentsSdkHelper: PayPalSdkHelper,\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 &\n WithBigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, bigcommerce_payments_apms } = options;\n\n this.bigCommercePaymentsAlternativeMethods = bigcommerce_payments_apms;\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 (!bigcommerce_payments_apms) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_apms\" 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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n\n this.isPollingEnabled = isExperimentEnabled(features, 'PAYPAL-5624.bcp_ideal_polling');\n\n // Info:\n // The APM 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 the button.\n if (orderId) {\n this.orderId = orderId;\n\n return;\n }\n\n this.paypalApms = await this.bigCommercePaymentsSdkHelper.getPayPalApmsSdk(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n );\n\n this.loadingIndicatorContainer = bigcommerce_payments_apms.container.split('#')[1];\n\n this.renderButton(methodId, gatewayId, bigcommerce_payments_apms);\n\n if (shouldRenderFields) {\n this.renderFields(methodId, bigcommerce_payments_apms);\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.isPollingEnabled && methodId === 'ideal') {\n await new Promise((resolve, reject) => {\n void this.initializePollingMechanism(methodId, resolve, reject, gatewayId);\n });\n }\n\n if (!this.isNonInstantPaymentMethod(methodId)) {\n await this.paymentIntegrationService.submitOrder(order, options);\n }\n\n await this.bigCommercePaymentsIntegrationService.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 if (this.isPollingEnabled) {\n this.resetPollingMechanism();\n }\n\n this.bigCommercePaymentsButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Polling mechanism\n *\n *\n * */\n private async initializePollingMechanism(\n methodId: string,\n resolvePromise: (value?: unknown) => void,\n rejectPromise: (value?: unknown) => 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.bigCommercePaymentsIntegrationService.getOrderStatus(\n gatewayId,\n );\n\n const isOrderApproved = orderStatus === PayPalOrderStatus.Approved;\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 bigCommercePaymentsAlternativeMethods: this.bigCommercePaymentsAlternativeMethods,\n });\n\n this.handleError(new TimeoutError());\n } catch (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 private async reinitializeStrategy(\n options: PaymentInitializeOptions &\n WithBigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\n ) {\n await this.deinitialize();\n await this.initialize(options);\n }\n\n private handleError(error: unknown) {\n const { onError } = this.bigCommercePaymentsAlternativeMethods || {};\n\n if (this.isPollingEnabled) {\n this.resetPollingMechanism();\n }\n\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n gatewayId: string,\n bigcommerce_payments_apms: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\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 } = bigcommerce_payments_apms;\n\n const buttonOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource: methodId,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(buttonStyle),\n onInit: (_, actions) => bigcommerce_payments_apms.onInitButton(actions),\n createOrder: () => this.onCreateOrder(methodId, gatewayId, bigcommerce_payments_apms),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onCancel: () => {\n this.toggleLoadingIndicator(false);\n this.deInitializePollingMechanism();\n },\n onError: (error) => {\n this.deInitializePollingMechanism();\n this.handleFailure(error, onError);\n },\n onClick: async (_, actions) =>\n bigcommerce_payments_apms.onValidate(actions.resolve, actions.reject),\n };\n\n this.bigCommercePaymentsButton = paypalAmpsSdk.Buttons(buttonOptions);\n\n if (!this.bigCommercePaymentsButton.isEligible()) {\n return;\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.bigCommercePaymentsButton.render(container);\n }\n\n private async onCreateOrder(\n methodId: string,\n gatewayId: string,\n bigcommerce_payments_apms: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\n ): Promise {\n const { onValidate } = bigcommerce_payments_apms;\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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_apms',\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.bigCommercePaymentsIntegrationService.submitPayment(\n methodId,\n orderId,\n gatewayId,\n );\n }\n\n return orderId;\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n }\n\n private handleFailure(\n error: Error,\n onError: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions['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 bigcommerce_payments_apms: BigCommercePaymentsAlternativeMethodsPaymentInitializeOptions,\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 } = bigcommerce_payments_apms;\n\n if (!apmFieldsContainer) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bigcommerce_payments_apms\" 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 { createBigCommercePaymentsSdk } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport { LOADING_INDICATOR_STYLES } from '../bigcommerce-payments-constants';\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsAlternativeMethodsPaymentStrategy from './bigcommerce-payments-alternative-methods-payment-strategy';\n\nconst createBigCommercePaymentsAlternativeMethodsPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsAlternativeMethodsPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsAlternativeMethodsPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n createBigCommercePaymentsSdk(),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsAlternativeMethodsPaymentStrategy, [\n { gateway: 'bigcommerce_payments_apms' },\n]);\n","import { isRedirectError } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsRedirectAlternativeMethodsPaymentInitializeOptions, {\n WithBigCommercePaymentsRedirectAlternativeMethodsPaymentInitializeOptions,\n} from './bigcomemrce-payments-redirect-alternative-methods-payment-initialize-options';\n\nexport default class BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy\n implements PaymentStrategy\n{\n private bigCommercePaymentsAlternativeMethods?: BigCommercePaymentsRedirectAlternativeMethodsPaymentInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n initialize(\n options: PaymentInitializeOptions &\n WithBigCommercePaymentsRedirectAlternativeMethodsPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, bigcommerce_payments_apms } = options;\n\n this.bigCommercePaymentsAlternativeMethods = bigcommerce_payments_apms;\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 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, gatewayId } = payment;\n\n try {\n const orderId = await this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_apms',\n {\n gatewayId: 'bigcommerce_payments_apms',\n methodId,\n },\n );\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: methodId,\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,\n gatewayId,\n paymentData,\n });\n } catch (error: unknown) {\n if (isRedirectError(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 reject();\n });\n }\n\n this.handleError(error);\n\n return Promise.reject(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 handleError(error: unknown) {\n const { onError } = this.bigCommercePaymentsAlternativeMethods || {};\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n}\n","import { isRequestError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RedirectError } from '../bigcommerce-payments-types';\n\nexport default function isRedirectError(error: unknown): error is RedirectError {\n return isRequestError(error) && error.body?.additional_action_required?.data.redirect_url;\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy from './bigcomemrce-payments-redirect-alternative-methods-payment-strategy';\n\nconst createBigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(\n createBigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy,\n [\n { gateway: 'bigcommerce_payments_apms', id: 'klarna' },\n { gateway: 'bigcommerce_payments_apms', id: 'afterpay' },\n ],\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 BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtons,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n ClickCallbackActions,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsVenmoPaymentInitializeOptions, {\n WithBigCommercePaymentsVenmoPaymentInitializeOptions,\n} from './bigcommerce-payments-venmo-payment-initialize-options';\n\nexport default class BigCommercePaymentsVenmoPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: BigCommercePaymentsButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithBigCommercePaymentsVenmoPaymentInitializeOptions,\n ): Promise {\n const { methodId, bigcommerce_payments_venmo } = 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 (!bigcommerce_payments_venmo) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_venmo\" 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.bigCommercePaymentsIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = bigcommerce_payments_venmo.container.split('#')[1];\n\n this.renderButton(methodId, bigcommerce_payments_venmo);\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.bigCommercePaymentsIntegrationService.submitPayment(\n payment.methodId,\n this.orderId,\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 bigcommerce_payments_venmo: BigCommercePaymentsVenmoPaymentInitializeOptions,\n ): void {\n const paypalSdk = this.bigCommercePaymentsIntegrationService.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 } =\n bigcommerce_payments_venmo;\n\n const buttonOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(\n checkoutPaymentButtonStyles,\n ),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_venmocheckout',\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()) {\n throw new NotImplementedError(\n `Venmo is not available for your region. Please another payment method 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: BigCommercePaymentsVenmoPaymentInitializeOptions['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: BigCommercePaymentsVenmoPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n this.toggleLoadingIndicator(false);\n }\n\n private handleError(\n error: Error,\n onError: BigCommercePaymentsVenmoPaymentInitializeOptions['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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsVenmoPaymentStrategy from './bigcommerce-payments-venmo-payment-strategy';\n\nconst createBigCommercePaymentsVenmoPaymentStrategy: PaymentStrategyFactory<\n BigCommercePaymentsVenmoPaymentStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsVenmoPaymentStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsVenmoPaymentStrategy, [\n { id: 'bigcommerce_payments_venmo' },\n]);\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","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","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 { 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 try {\n await this._blueSnapDirectHostedForm.attach(\n this._getPaymentFieldsToken(),\n creditCard,\n is3dsEnabled,\n );\n } catch (error) {\n if (error instanceof InvalidArgumentError) {\n return;\n }\n throw error;\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","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 ...(payment.paymentData.companyName\n ? { company_name: payment.paymentData.companyName }\n : {}),\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(\n paymentIntegrationService,\n createBraintreeSdk(paymentIntegrationService),\n );\n};\n\nexport default toResolvableModule(createBraintreeAchPaymentStrategy, [{ id: 'braintreeach' }]);\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport BraintreeSdk from './braintree-sdk';\nimport BraintreeSDKVersionManager from './braintree-sdk-version-manager';\n\nconst createBraintreeSdk = (paymentIntegrationService: PaymentIntegrationService) => {\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeScriptLoader = new BraintreeScriptLoader(\n getScriptLoader(),\n window,\n braintreeSDKVersionManager,\n );\n\n return new BraintreeSdk(braintreeScriptLoader);\n};\n\nexport default createBraintreeSdk;\n","import { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BraintreeHostWindow,\n BraintreeInitializationData,\n PayPalBNPLConfigurationItem,\n} from './braintree';\nimport { MessagesStyleOptions, MessagingPlacements } from './paypal';\n\nexport default class BraintreeMessages {\n private braintreeHostWindow: BraintreeHostWindow = window;\n\n constructor(private paymentIntegrationService: PaymentIntegrationService) {}\n\n render(methodId: string, containerId: string, placement: MessagingPlacements): void {\n const messagingContainer = containerId && document.getElementById(containerId);\n\n if (this.braintreeHostWindow.paypal && messagingContainer) {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const billingAddress = state.getBillingAddressOrThrow();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n if (!paymentMethod.initializationData) {\n return;\n }\n\n const { paypalBNPLConfiguration = [] } = paymentMethod.initializationData;\n\n const bannedId = placement === MessagingPlacements.PAYMENT ? 'checkout' : placement;\n const bannerConfiguration =\n paypalBNPLConfiguration &&\n paypalBNPLConfiguration.find(({ id }) => id === bannedId);\n\n if (!bannerConfiguration || !bannerConfiguration.status) {\n return;\n }\n\n // TODO: remove this code when this data attributes will be removed from banner div container in content service\n if (placement === MessagingPlacements.CART) {\n messagingContainer.removeAttribute('data-pp-style-logo-type');\n messagingContainer.removeAttribute('data-pp-style-logo-position');\n messagingContainer.removeAttribute('data-pp-style-text-color');\n messagingContainer.removeAttribute('data-pp-style-text-size');\n }\n\n this.braintreeHostWindow.paypal\n .Messages({\n amount: cart.cartAmount,\n buyerCountry: billingAddress.countryCode,\n placement,\n style: this.getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\n })\n .render(`#${containerId}`);\n }\n }\n\n private 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}\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","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 BraintreeInitializationData,\n BraintreeIntegrationService,\n BraintreeMessages,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n MessagingPlacements,\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 braintreeButtonOptions?: 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 braintreeMessages: BraintreeMessages,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreePaypalPaymentInitializeOptions,\n ) {\n const { braintree: braintreeOptions, methodId } = options;\n\n if (braintreeOptions?.containerId) {\n this.braintreeButtonOptions = braintreeOptions;\n }\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(braintreeOptions);\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(braintreeOptions);\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 if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { onError } = this.braintreeButtonOptions || {};\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)) {\n await this.loadPaypal();\n\n this.paypalButtonRender?.close();\n\n await this.loadPaypalCheckoutInstance(this.braintreeButtonOptions);\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(options?: BraintreePaypalPaymentInitializeOptions) {\n const { clientToken, initializationData, id: paymentMethodId } = 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 const isBraintreePaypalCredit = paymentMethodId === 'braintreepaypalcredit';\n const shouldShowPayPalCreditBanner =\n isBraintreePaypalCredit || !initializationData?.isCreditEnabled;\n\n await this.braintreeIntegrationService.getPaypalCheckout(\n paypalCheckoutConfig,\n (braintreePaypalCheckout) => {\n if (\n shouldShowPayPalCreditBanner &&\n paymentMethodId &&\n options?.bannerContainerId\n ) {\n this.renderPayPalMessages(paymentMethodId, options.bannerContainerId);\n }\n\n this.renderPayPalButton(braintreePaypalCheckout, options);\n },\n this.handleError,\n );\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private renderPayPalMessages(methodId: string, containerId: string) {\n this.braintreeMessages.render(methodId, containerId, MessagingPlacements.PAYMENT);\n }\n\n private renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n options?: BraintreePaypalPaymentInitializeOptions,\n ) {\n const { onPaymentError, submitForm, onRenderButton, containerId, onError } = options || {};\n\n if (!containerId) {\n return;\n }\n\n const container = this.getSmartButtonContainerId(containerId);\n const smartButtonContainer = document.getElementById(container);\n\n if (!smartButtonContainer) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because element with id ${containerId} does not exist.`,\n );\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 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 private getSmartButtonContainerId(container: string) {\n return container.split('#')[1] ?? container;\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 BraintreeMessages,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n overlay,\n );\n const braintreeMessages = new BraintreeMessages(paymentIntegrationService);\n\n return new BraintreePaypalPaymentStrategy(\n paymentIntegrationService,\n braintreeIntegrationService,\n braintreeMessages,\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 { RequestSender } from '@bigcommerce/request-sender';\n\nimport { BraintreeOrderStatusData } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class BraintreeRequestSender {\n constructor(private requestSender: RequestSender) {}\n\n async getOrderStatus(\n methodId = 'braintreelocalmethods',\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 { noop } from 'lodash';\n\nimport {\n BraintreeInitializationData,\n BraintreeLocalPayment,\n BraintreeLocalPaymentConfig,\n BraintreeLocalPaymentMethodRedirectAction,\n BraintreeLocalPaymentsPayload,\n BraintreeLPMPaymentStartData,\n BraintreeLPMStartPaymentError,\n BraintreeOrderSavedResponse,\n BraintreeOrderStatus,\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 TimeoutError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport BraintreeRequestSender from '../braintree-request-sender';\n\nimport {\n BraintreeLocalMethodsPaymentInitializeOptions,\n WithBraintreeLocalMethodsPaymentInitializeOptions,\n} from './braintree-local-methods-payment-initialize-options';\n\nconst POLLING_INTERVAL = 3000;\nconst MAX_POLLING_TIME = 300000;\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 gatewayId?: string;\n private isLPMsUpdateExperimentEnabled = false;\n private pollingTimer = 0;\n private stopPolling = noop;\n private isPollingEnabled = false;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeSdk: BraintreeSdk,\n private braintreeRequestSender: BraintreeRequestSender,\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 & WithBraintreeLocalMethodsPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, braintreelocalmethods } = options;\n\n this.gatewayId = gatewayId;\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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n\n this.isPollingEnabled = isExperimentEnabled(\n features,\n 'PAYPAL-5258.braintree_local_methods_polling',\n );\n\n this.isLPMsUpdateExperimentEnabled = isExperimentEnabled(\n features,\n 'PAYPAL-4853.add_new_payment_flow_for_braintree_lpms',\n );\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 const checkoutUrl = state.getStoreConfigOrThrow().links.checkoutLink;\n\n return {\n paymentType: methodId,\n amount: grandTotal,\n fallback: {\n url: checkoutUrl,\n buttonText: 'Complete Payment',\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 if (this.isPollingEnabled) {\n return new Promise((resolve, reject) => {\n void this.initializePollingMechanism(\n methodId,\n resolve,\n reject,\n this.gatewayId,\n );\n });\n }\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 this.resetPollingMechanism();\n\n return reject();\n }\n\n if (this.isPollingEnabled) {\n this.resetPollingMechanism();\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 if (this.isPollingEnabled) {\n this.resetPollingMechanism();\n }\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 /**\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.braintreeRequestSender.getOrderStatus(gatewayId, {\n params: {\n useMetadata: false,\n },\n });\n\n const isOrderPending = orderStatus.status === BraintreeOrderStatus.Pending;\n const isOrderApproved = orderStatus.status === BraintreeOrderStatus.Completed;\n const isPollingError = orderStatus.status === BraintreeOrderStatus.Failed;\n\n if (isOrderApproved) {\n this.deinitializePollingMechanism();\n\n return resolvePromise();\n }\n\n if (isPollingError) {\n return rejectPromise();\n }\n\n if (\n !isOrderApproved &&\n isOrderPending &&\n this.pollingTimer < this.maxPollingIntervalTime\n ) {\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 braintreelocalmethods: this.braintreelocalmethods,\n });\n\n this.handleError(new TimeoutError());\n } catch (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 private async reinitializeStrategy(\n options: PaymentInitializeOptions & WithBraintreeLocalMethodsPaymentInitializeOptions,\n ) {\n await this.deinitialize();\n await this.initialize(options);\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\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 BraintreeRequestSender from '../braintree-request-sender';\n\nimport BraintreeLocalMethodsPaymentStrategy from './braintree-local-methods-payment-strategy';\n\nconst createBraintreeLocalMethodsPaymentStrategy: PaymentStrategyFactory<\n BraintreeLocalMethodsPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n );\n const requestSender = createRequestSender();\n const braintreeRequestSender = new BraintreeRequestSender(requestSender);\n\n return new BraintreeLocalMethodsPaymentStrategy(\n paymentIntegrationService,\n braintreeSdk,\n braintreeRequestSender,\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 Braintree3DSVerifyCardError,\n Braintree3DSVerifyCardPayload,\n BraintreeFastlaneAddress,\n BraintreeFastlaneAuthenticationState,\n BraintreeFastlaneCardComponent,\n BraintreeFastlaneCardComponentOptions,\n BraintreeInitializationData,\n BraintreeSdk,\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 PaymentMethodCancelledError,\n PaymentMethodClientUnavailableError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\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 private is3DSEnabled?: boolean;\n private onError?: (error: Error) => void;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeFastlaneUtils: BraintreeFastlaneUtils,\n private braintreeSdk: BraintreeSdk,\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 await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { initializationData, clientToken } = paymentMethod || {};\n const { isFastlaneStylingEnabled } = initializationData || {};\n const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const isThreeDSExperimentEnabled = isExperimentEnabled(\n features,\n 'PROJECT-7080.braintree_fastlane_three_ds',\n );\n\n this.is3DSEnabled = paymentMethod.config.is3dsEnabled;\n\n if (clientToken && isThreeDSExperimentEnabled) {\n this.braintreeSdk.initialize(clientToken);\n }\n\n const paypalFastlaneStyleSettings = isFastlaneStylingEnabled\n ? paymentMethod.initializationData?.fastlaneStyles\n : undefined;\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 this.onError = braintreefastlane.onError;\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 await this.paymentIntegrationService.submitOrder(order, options);\n\n const paymentPayload = await this.preparePaymentPayload(payment.methodId);\n\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n\n this.braintreeFastlaneUtils.removeSessionIdFromCookies();\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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const isThreeDSExperimentEnabled = isExperimentEnabled(\n features,\n 'PROJECT-7080.braintree_fastlane_three_ds',\n );\n\n if (paypalInstrument) {\n const threeDSToken =\n this.is3DSEnabled && isThreeDSExperimentEnabled\n ? await this.get3DS(paypalInstrument.bigpayToken, paypalInstrument?.iin || '')\n : undefined;\n\n return {\n methodId,\n paymentData: {\n deviceSessionId,\n formattedPayload: {\n paypal_fastlane_token: {\n token: threeDSToken || paypalInstrument.bigpayToken,\n },\n },\n },\n };\n }\n\n const { getPaymentToken } = this.getBraintreeCardComponentOrThrow();\n\n const paymentToken = await getPaymentToken({\n name: { fullName },\n billingAddress: this.mapToPayPalAddress(billingAddress),\n });\n\n const binGuest = paymentToken.paymentSource.card?.binDetails?.bin || '';\n const threeDSToken =\n this.is3DSEnabled && isThreeDSExperimentEnabled\n ? await this.get3DS(paymentToken.id, binGuest)\n : undefined;\n\n return {\n methodId,\n paymentData: {\n deviceSessionId,\n nonce: threeDSToken || paymentToken.id,\n },\n };\n }\n\n /**\n * 3DS\n */\n private async get3DS(nonce: string, bin: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const threeDSecure = await this.braintreeSdk.getBraintreeThreeDS();\n const order = state.getOrderOrThrow();\n\n return new Promise((resolve, reject) => {\n void threeDSecure.verifyCard(\n {\n amount: order?.orderAmount,\n nonce,\n bin,\n onLookupComplete: (_data, next) => {\n threeDSecure.on('customer-canceled', () => {\n if (typeof this.onError === 'function') {\n this.onError(new PaymentMethodCancelledError());\n }\n\n reject(new PaymentMethodCancelledError());\n });\n\n next();\n },\n },\n (\n verifyError: Braintree3DSVerifyCardError,\n payload: Braintree3DSVerifyCardPayload,\n ) => {\n if (\n verifyError &&\n verifyError.code === 'THREEDS_VERIFY_CARD_CANCELED_BY_MERCHANT'\n ) {\n if (typeof this.onError === 'function') {\n this.onError(new PaymentMethodCancelledError());\n }\n\n reject(new PaymentMethodCancelledError());\n }\n\n return resolve(payload.nonce);\n },\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.braintreeFastlaneUtils.getSessionIdFromCookies();\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 BraintreeSdk,\n BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n );\n\n const braintreeFastlaneUtils = new BraintreeFastlaneUtils(\n paymentIntegrationService,\n braintreeIntegrationService,\n );\n\n const braintreeScriptLoader = new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n );\n\n const braintreeSdk = new BraintreeSdk(braintreeScriptLoader);\n\n return new BraintreeFastlanePaymentStrategy(\n paymentIntegrationService,\n braintreeFastlaneUtils,\n braintreeSdk,\n );\n};\n\nexport default toResolvableModule(createBraintreeFastlanePaymentStrategy, [\n { id: 'braintreeacceleratedcheckout' },\n]);\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { noop } from 'lodash';\n\nimport {\n BraintreeDataCollector,\n BraintreeInitializationData,\n BraintreeSdk,\n BraintreeVisaCheckout,\n VisaCheckoutAddress,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutTokenizedPayload,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n Address,\n InvalidArgumentError,\n LegacyAddress,\n MissingDataError,\n MissingDataErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithBraintreeVisaCheckoutPaymentInitializeOptions } from './braintree-visa-checkout-payment-options';\n\nexport default class BraintreeVisaCheckoutPaymentStrategy implements PaymentStrategy {\n private paymentMethod?: PaymentMethod;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private formPoster: FormPoster,\n private braintreeSdk: BraintreeSdk,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeVisaCheckoutPaymentInitializeOptions,\n ): 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 await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n\n this.paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n const checkout = state.getCheckoutOrThrow();\n const storeConfig = state.getStoreConfigOrThrow();\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 this.braintreeSdk.initialize(clientToken);\n\n const braintreeVisaCheckout = await this.braintreeSdk.getBraintreeVisaCheckout();\n\n const visaCheckoutSdk = await this.braintreeSdk.getVisaCheckoutSdk(config?.testMode);\n\n const initOptions = braintreeVisaCheckout.createInitOptions({\n settings: {\n locale: storeConfig.storeProfile.storeLanguage,\n shipping: {\n collectShipping: false,\n },\n },\n paymentRequest: {\n currencyCode: storeConfig.currency.code,\n subtotal: String(checkout.subtotal),\n },\n });\n\n await visaCheckoutSdk.init(initOptions);\n\n visaCheckoutSdk.on(\n 'payment.success',\n (paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) =>\n this.tokenizePayment(braintreeVisaCheckout, paymentSuccessPayload)\n .then(() =>\n Promise.all([\n this.paymentIntegrationService.loadCheckout(),\n this.paymentIntegrationService.loadPaymentMethod(methodId),\n ]),\n )\n .then(() => onPaymentSelect())\n .catch((error) => onError(error)),\n );\n visaCheckoutSdk.on('payment.error', (_, error) => onError(error));\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\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 (!this.paymentMethod?.initializationData?.nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { nonce } = this.paymentMethod.initializationData;\n\n try {\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: { nonce },\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.braintreeSdk.deinitialize();\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 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 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 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 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","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\n VisaCheckoutHostWindow,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeVisaCheckoutPaymentStrategy from './braintree-visa-checkout-payment-strategy';\n\nconst createBraintreeVisaCheckoutPaymentStrategy: PaymentStrategyFactory<\n BraintreeVisaCheckoutPaymentStrategy\n> = (paymentIntegrationService) => {\n const hostWindow: VisaCheckoutHostWindow & BraintreeHostWindow = window;\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), hostWindow, braintreeSDKVersionManager),\n );\n\n return new BraintreeVisaCheckoutPaymentStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeSdk,\n );\n};\n\nexport default toResolvableModule(createBraintreeVisaCheckoutPaymentStrategy, [\n { id: 'braintreevisacheckout' },\n]);\n","import {\n BraintreeError,\n BraintreeIntegrationService,\n BraintreeTokenizePayload,\n BraintreeVenmoCheckout,\n isBraintreeError,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n FormattedPayload,\n MissingDataError,\n MissingDataErrorType,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n PaymentStrategy,\n PaypalInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\nimport BraintreeVenmoPaymentStrategyInitializeOptions, {\n WithBraintreeVenmoInitializeOptions,\n} from './braintree-venmo-payment-strategy-initialize-options';\n\nexport default class BraintreeVenmoPaymentStrategy implements PaymentStrategy {\n private braintreeVenmoCheckout?: BraintreeVenmoCheckout;\n private venmoOptions?: BraintreeVenmoPaymentStrategyInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeIntegrationService: BraintreeIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeVenmoInitializeOptions,\n ): Promise {\n const { methodId } = options;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n const state = this.paymentIntegrationService.getState();\n\n this.venmoOptions = options.braintreevenmo;\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n await this.initializeBraintreeVenmo(paymentMethod);\n }\n\n async execute(orderRequest: OrderRequestBody): 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 await this.paymentIntegrationService.submitOrder(order);\n await this.paymentIntegrationService.submitPayment(paymentData);\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.braintreeIntegrationService.teardown();\n\n return Promise.resolve();\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 const state = this.paymentIntegrationService.getState();\n const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const isBraintreeVenmoWebFallbackSupport = isExperimentEnabled(\n features,\n 'PAYPAL-5406.braintree_venmo_web_fallback_support',\n );\n\n try {\n this.braintreeIntegrationService.initialize(clientToken);\n this.braintreeVenmoCheckout = await this.braintreeIntegrationService.getVenmoCheckout({\n ...(this.venmoOptions?.allowDesktop !== undefined\n ? { allowDesktop: this.venmoOptions.allowDesktop }\n : {}),\n ...(isBraintreeVenmoWebFallbackSupport\n ? {\n mobileWebFallBack: isBraintreeVenmoWebFallbackSupport,\n }\n : {}),\n });\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async preparePaymentData(payment: OrderPaymentRequestBody): Promise {\n const state = this.paymentIntegrationService.getState();\n const { nonce } = state.getPaymentMethodOrThrow(payment.methodId);\n\n if (nonce) {\n return { ...payment, paymentData: this.formattedPayload(nonce) };\n }\n const tokenizeResult = await this.braintreeVenmoTokenize();\n const sessionId = await this.braintreeIntegrationService.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 {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport BraintreeVenmoPaymentStrategy from './braintree-venmo-payment-strategy';\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nconst createBraintreeVenmoPaymentStrategy: CheckoutButtonStrategyFactory<\n BraintreeVenmoPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const scriptLoader = getScriptLoader();\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeScriptLoader = new BraintreeScriptLoader(\n scriptLoader,\n braintreeHostWindow,\n braintreeSDKVersionManager,\n );\n const braintreeIntegrationService = new BraintreeIntegrationService(\n braintreeScriptLoader,\n braintreeHostWindow,\n );\n\n return new BraintreeVenmoPaymentStrategy(\n paymentIntegrationService,\n braintreeIntegrationService,\n );\n};\n\nexport default toResolvableModule(createBraintreeVenmoPaymentStrategy, [{ id: 'braintreevenmo' }]);\n","import { some } from 'lodash';\n\nimport {\n BraintreeIntegrationService,\n BraintreeThreeDSecureOptions,\n isBraintreeAcceleratedCheckoutCustomer,\n isBraintreePaymentRequest3DSError,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n Address,\n isHostedInstrumentLike,\n isRequestError,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NonceInstrument,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentInstrument,\n PaymentInstrumentMeta,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodFailedError,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeHostedForm from '../braintree-hosted-form/braintree-hosted-form';\nimport isBraintreeError from '../is-braintree-error';\n\nimport {\n BraintreeCreditCardPaymentInitializeOptions,\n WithBraintreeCreditCardPaymentInitializeOptions,\n} from './braintree-credit-card-payment-initialize-options';\n\nexport default class BraintreeCreditCardPaymentStrategy implements PaymentStrategy {\n private is3dsEnabled?: boolean;\n private isHostedFormInitialized?: boolean;\n private deviceSessionId?: string;\n private paymentMethod?: PaymentMethod;\n private threeDSecure?: BraintreeThreeDSecureOptions;\n private onPaymentError?: BraintreeCreditCardPaymentInitializeOptions['onPaymentError'];\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeIntegrationService: BraintreeIntegrationService,\n private braintreeHostedForm: BraintreeHostedForm,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeCreditCardPaymentInitializeOptions,\n ): Promise {\n const { methodId, gatewayId, braintree } = options;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n\n this.paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n const { clientToken } = this.paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.threeDSecure = braintree?.threeDSecure;\n this.onPaymentError = braintree?.onPaymentError;\n\n try {\n this.braintreeIntegrationService.initialize(clientToken, this.threeDSecure);\n\n if (this.isHostedPaymentFormEnabled(methodId, gatewayId) && braintree?.form) {\n await this.braintreeHostedForm.initialize(\n braintree.form,\n braintree.unsupportedCardBrands,\n clientToken,\n );\n\n this.isHostedFormInitialized = this.braintreeHostedForm.isInitialized();\n }\n\n this.is3dsEnabled = this.paymentMethod.config.is3dsEnabled;\n this.deviceSessionId = await this.braintreeIntegrationService.getSessionId();\n\n // TODO: Remove when BT AXO A/B testing is finished\n if (this.shouldInitializeBraintreeFastlane()) {\n await this.initializeBraintreeFastlaneOrThrow(methodId);\n }\n } catch (error) {\n return this.handleError(error, methodId);\n }\n }\n\n async execute(orderRequest: OrderRequestBody): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (this.isHostedFormInitialized) {\n this.braintreeHostedForm.validate();\n }\n\n await this.paymentIntegrationService.submitOrder(order);\n\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddressOrThrow();\n const orderAmount = state.getOrderOrThrow().orderAmount;\n\n try {\n const paymentData = this.isHostedFormInitialized\n ? await this.prepareHostedPaymentData(payment, billingAddress, orderAmount)\n : await this.preparePaymentData(payment, billingAddress, orderAmount);\n\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData,\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.braintreeIntegrationService.teardown(),\n this.braintreeHostedForm.deinitialize(),\n ]);\n\n return Promise.resolve();\n }\n\n private handleError(error: unknown, methodId?: string): void | Promise {\n if (isBraintreeError(error)) {\n const isPaymentMethodInitialized = !!(\n methodId &&\n this.paymentIntegrationService.getState().isPaymentMethodInitialized({ methodId })\n );\n\n if (\n !isPaymentMethodInitialized &&\n error.code === 'HOSTED_FIELDS_INVALID_FIELD_SELECTOR'\n ) {\n return;\n }\n\n if (error.code.startsWith('THREEDS_')) {\n this.onPaymentError?.(new PaymentMethodFailedError('THREEDS_VERIFICATION_FAILED'));\n\n return Promise.reject();\n }\n\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.braintreeIntegrationService.verifyCard(\n payment,\n billingAddress,\n orderAmount,\n )\n : await this.braintreeIntegrationService.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 } = await this.braintreeHostedForm.tokenizeForStoredCardVerification();\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.verifyCardWithHostedForm(billingAddress, orderAmount)\n : await this.braintreeHostedForm.tokenize(billingAddress);\n\n return {\n ...commonPaymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n nonce,\n };\n }\n\n private prepareAdditionalActionPaymentData(\n payment: OrderPaymentRequestBody,\n nonce: string,\n ): PaymentInstrument & PaymentInstrumentMeta {\n const { paymentData } = payment;\n const commonPaymentData = { deviceSessionId: this.deviceSessionId, nonce };\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n if (\n this.isSubmittingWithStoredCard(payment) &&\n (shouldSaveInstrument || shouldSetAsDefaultInstrument)\n ) {\n return {\n ...paymentData,\n ...commonPaymentData,\n };\n }\n\n return {\n ...commonPaymentData,\n };\n }\n\n private async verifyCardWithHostedForm(\n billingAddress: Address,\n orderAmount: number,\n ): Promise {\n const tokenizationPayload = await this.braintreeHostedForm.tokenize(billingAddress);\n\n return this.braintreeIntegrationService.challenge3DSVerification(\n tokenizationPayload,\n orderAmount,\n );\n }\n\n private async processAdditionalAction(\n error: unknown,\n payment: OrderPaymentRequestBody,\n orderAmount: number,\n ): Promise {\n if (\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return this.handleError(error);\n }\n\n try {\n const { payer_auth_request: storedCreditCardNonce } =\n (isBraintreePaymentRequest3DSError(error) && error.body.three_ds_result) || {};\n const { paymentData } = payment;\n const state = this.paymentIntegrationService.getState();\n\n if (!paymentData || !isVaultedInstrument(paymentData)) {\n throw new PaymentArgumentInvalidError(['instrumentId']);\n }\n\n const instrument = state.getCardInstrumentOrThrow(paymentData.instrumentId);\n const { nonce } = await this.braintreeIntegrationService.challenge3DSVerification(\n {\n nonce: storedCreditCardNonce || '',\n bin: instrument.iin,\n },\n orderAmount,\n );\n\n const newPaymentData = this.prepareAdditionalActionPaymentData(payment, nonce);\n\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: newPaymentData,\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 state = this.paymentIntegrationService.getState();\n const paymentMethod = state.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 when BT AXO A/B testing is finished\n private shouldInitializeBraintreeFastlane(): boolean {\n const state = this.paymentIntegrationService.getState();\n const paymentProviderCustomer = state.getPaymentProviderCustomerOrThrow();\n const braintreeCustomer = isBraintreeAcceleratedCheckoutCustomer(paymentProviderCustomer)\n ? paymentProviderCustomer\n : {};\n const isFastlaneEnabled: boolean =\n this.paymentMethod?.initializationData.isAcceleratedCheckoutEnabled;\n\n return isFastlaneEnabled && !braintreeCustomer?.authenticationState;\n }\n\n // TODO: Remove when BT AXO A/B testing is finished\n private async initializeBraintreeFastlaneOrThrow(methodId: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { clientToken, config } = paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.braintreeIntegrationService.initialize(clientToken, this.threeDSecure);\n\n await this.braintreeIntegrationService.getBraintreeFastlane(cart.id, config.testMode);\n }\n}\n","export interface BraintreePayment3DSRequestErrors {\n code: string;\n}\n\nexport interface BraintreePaymentRequest3DSError {\n name: string;\n body: {\n status: string;\n three_ds_result: {\n payer_auth_request: string;\n };\n errors: BraintreePayment3DSRequestErrors[];\n };\n}\n\nexport default function isBraintreePaymentRequest3DSError(\n error: unknown,\n): error is BraintreePaymentRequest3DSError {\n if (typeof error !== 'object' || error === null) {\n return false;\n }\n /* eslint-disable @typescript-eslint/consistent-type-assertions */\n return (\n 'name' in error &&\n 'body' in error &&\n 'status' in (error as BraintreePaymentRequest3DSError).body &&\n 'three_ds_result' in (error as BraintreePaymentRequest3DSError).body &&\n 'payer_auth_request' in (error as BraintreePaymentRequest3DSError).body.three_ds_result &&\n 'errors' in (error as BraintreePaymentRequest3DSError).body\n );\n}\n","import { BraintreeFormFieldsMap, BraintreeStoredCardFieldsMap } from '../index';\n\nexport function isBraintreeFormFieldsMap(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n): fields is BraintreeFormFieldsMap {\n return 'cardNumber' in fields;\n}\n\nexport function isBraintreeStoredCardFieldsMap(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n): fields is BraintreeStoredCardFieldsMap {\n return !!(\n Object.keys(fields).length > 0 &&\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n ((fields as BraintreeStoredCardFieldsMap).cardCodeVerification ||\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n (fields as BraintreeStoredCardFieldsMap).cardNumberVerification)\n );\n}\n","import isBraintreeError from './is-braintree-error';\nimport { BraintreeHostedFormError } from '../types';\n\nfunction isValidInvalidFieldKeys(invalidFieldKeys: unknown): invalidFieldKeys is string[] {\n return (\n Array.isArray(invalidFieldKeys) && invalidFieldKeys.every((key) => typeof key === 'string')\n );\n}\n\nexport default function isBraintreeHostedFormError(\n error: unknown,\n): 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 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n (details as { invalidFieldKeys?: unknown }).invalidFieldKeys === undefined) ||\n isValidInvalidFieldKeys(details)\n );\n}\n","import { Dictionary, isEmpty, isNil, omitBy } from 'lodash';\n\nimport {\n BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION,\n BraintreeBillingAddressRequestData,\n BraintreeClient,\n BraintreeFormErrorDataKeys,\n BraintreeFormErrorsData,\n BraintreeFormFieldsMap,\n BraintreeFormFieldStyles,\n BraintreeFormFieldStylesMap,\n BraintreeFormFieldType,\n BraintreeFormFieldValidateErrorData,\n BraintreeFormFieldValidateEventData,\n BraintreeFormOptions,\n BraintreeHostedFields,\n BraintreeHostedFieldsCreatorConfig,\n BraintreeHostedFieldsState,\n BraintreeHostedFormError,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\n BraintreeStoredCardFieldsMap,\n isBraintreeFormFieldsMap,\n isBraintreeHostedFormError,\n isBraintreeSupportedCardBrand,\n TokenizationPayload,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n Address,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\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 client?: Promise;\n private clientToken?: string;\n private isInitializedHostedForm = false;\n\n constructor(\n private braintreeScriptLoader: BraintreeScriptLoader,\n private braintreeSDKVersionManager: BraintreeSDKVersionManager,\n ) {}\n\n async initialize(\n options: BraintreeFormOptions,\n unsupportedCardBrands?: string[],\n clientToken?: string,\n ): Promise {\n this.clientToken = clientToken;\n this.formOptions = options;\n this.type = isBraintreeFormFieldsMap(options.fields)\n ? BraintreeHostedFormType.CreditCard\n : BraintreeHostedFormType.StoredCardVerification;\n\n const fields = this.mapFieldOptions(options.fields, unsupportedCardBrands);\n\n if (isEmpty(fields)) {\n this.isInitializedHostedForm = false;\n\n return;\n }\n\n this.cardFields = await this.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 await this.cardFields?.teardown();\n }\n }\n\n validate(): void {\n if (!this.cardFields) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const state = this.cardFields.getState();\n\n if (!this.isValidForm(state)) {\n this.handleValidityChange(state);\n\n const errors = this.mapValidationErrors(state.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 payload = await this.cardFields.tokenize(\n omitBy(\n {\n billingAddress: billingAddress && this.mapBillingAddress(billingAddress),\n },\n isNil,\n ),\n );\n\n this.formOptions?.onValidate?.({ isValid: true, errors: {} });\n\n return {\n nonce: payload.nonce,\n bin: payload.details?.bin,\n };\n } catch (error) {\n if (isBraintreeHostedFormError(error)) {\n const errors = this.mapTokenizeError(error);\n\n if (errors) {\n this.formOptions?.onValidate?.({ isValid: false, errors });\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 payload = await this.cardFields.tokenize();\n\n this.formOptions?.onValidate?.({ isValid: true, errors: {} });\n\n return {\n nonce: payload.nonce,\n bin: payload.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?.({ isValid: false, errors });\n throw new PaymentInvalidFormError(errors as PaymentInvalidFormErrorDetails);\n }\n }\n\n throw error;\n }\n }\n\n async createHostedFields(\n options: Pick,\n ): Promise {\n const client = await this.getClient();\n const hostedFields = await this.braintreeScriptLoader.loadHostedFields();\n\n const currentSdkVersion = this.braintreeSDKVersionManager.getSDKVersion();\n const hostedFieldsOptions =\n currentSdkVersion === BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION\n ? { ...options, preventCursorJumps: true }\n : options;\n\n return hostedFields.create({ ...hostedFieldsOptions, client });\n }\n\n async getClient(): Promise {\n if (!this.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!this.client) {\n const client = await this.braintreeScriptLoader.loadClient();\n\n this.client = client.create({ authorization: this.clientToken });\n }\n\n return this.client;\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 unsupportedCardBrands?: string[],\n ): BraintreeHostedFieldsCreatorConfig['fields'] {\n if (isBraintreeFormFieldsMap(fields)) {\n const supportedCardBrands: Partial> = {};\n\n unsupportedCardBrands?.forEach((cardBrand) => {\n if (isBraintreeSupportedCardBrand(cardBrand)) {\n supportedCardBrands[cardBrand] = false;\n }\n });\n\n return omitBy(\n {\n number: {\n container: `#${fields.cardNumber.containerId}`,\n placeholder: fields.cardNumber.placeholder,\n internalLabel: fields.cardNumber.accessibilityLabel,\n ...(Object.keys(supportedCardBrands).length > 0\n ? { supportedCardBrands }\n : {}),\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 // eslint-disable-next-line no-restricted-syntax\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 cvv = [this.createRequiredError(this.mapFieldType('cvv'))];\n\n if (isStoredCard) {\n return { [this.mapFieldType('cvv')]: cvv };\n }\n\n return {\n [this.mapFieldType('cvv')]: cvv,\n [this.mapFieldType('expirationDate')]: [\n this.createRequiredError(this.mapFieldType('expirationDate')),\n ],\n [this.mapFieldType('number')]: [\n this.createRequiredError(this.mapFieldType('number')),\n ],\n [this.mapFieldType('cardholderName')]: [\n this.createRequiredError(this.mapFieldType('cardholderName')),\n ],\n };\n }\n\n return error.details?.invalidFieldKeys?.reduce((result, key) => {\n const type = this.mapFieldType(key);\n\n return {\n ...result,\n [type]: [this.createInvalidError(type)],\n };\n }, {});\n }\n\n private createRequiredError(\n fieldType: BraintreeFormFieldType,\n ): BraintreeFormFieldValidateErrorData {\n const messages = {\n [BraintreeFormFieldType.CardCode]: 'CVV is required',\n [BraintreeFormFieldType.CardCodeVerification]: 'CVV is required',\n [BraintreeFormFieldType.CardNumber]: 'Credit card number is required',\n [BraintreeFormFieldType.CardNumberVerification]: 'Credit card number is required',\n [BraintreeFormFieldType.CardExpiry]: 'Expiration date is required',\n [BraintreeFormFieldType.CardName]: 'Full name is required',\n };\n\n return {\n fieldType,\n message: messages[fieldType] ?? 'Field is required',\n type: 'required',\n };\n }\n\n private createInvalidError(\n fieldType: BraintreeFormFieldType,\n ): BraintreeFormFieldValidateErrorData {\n const formFields = {\n [BraintreeFormFieldType.CardCode]: {\n message: 'Invalid card code',\n type: 'invalid_card_code',\n },\n [BraintreeFormFieldType.CardCodeVerification]: {\n message: 'Invalid card code',\n type: 'invalid_card_code',\n },\n [BraintreeFormFieldType.CardNumber]: {\n message: 'Invalid card number',\n type: 'invalid_card_number',\n },\n [BraintreeFormFieldType.CardNumberVerification]: {\n message: 'Invalid card number',\n type: 'invalid_card_number',\n },\n [BraintreeFormFieldType.CardExpiry]: {\n message: 'Invalid card expiry',\n type: 'invalid_card_expiry',\n },\n [BraintreeFormFieldType.CardName]: {\n message: 'Invalid card name',\n type: 'invalid_card_name',\n },\n };\n\n return {\n fieldType,\n message: formFields[fieldType]?.message ?? 'Invalid field',\n type: formFields[fieldType]?.type ?? 'invalid',\n };\n }\n\n private handleBlur = (event: BraintreeHostedFieldsState): void => {\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 => {\n this.formOptions?.onFocus?.({\n fieldType: this.mapFieldType(event.emittedBy),\n });\n };\n\n private handleCardTypeChange = (event: BraintreeHostedFieldsState): void => {\n const cardType =\n event.cards.length === 1\n ? event.cards[0].type.replace(/^master-card$/, 'mastercard')\n : undefined;\n\n this.formOptions?.onCardTypeChange?.({ cardType });\n };\n\n private handleInputSubmitRequest = (event: BraintreeHostedFieldsState): void => {\n this.formOptions?.onEnter?.({\n fieldType: this.mapFieldType(event.emittedBy),\n });\n };\n\n private handleValidityChange = (event: BraintreeHostedFieldsState): void => {\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(key: string): key is BraintreeFormErrorDataKeys {\n return [\n 'number',\n 'cvv',\n 'expirationDate',\n 'postalCode',\n 'cardholderName',\n 'cardType',\n ].includes(key);\n }\n}\n","import { BraintreeSupportedCardBrands } from '../types';\n\nexport const isBraintreeSupportedCardBrand = (\n cardBrand: string,\n): cardBrand is BraintreeSupportedCardBrands => {\n const supportedCardBrands = Object.values(BraintreeSupportedCardBrands);\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return supportedCardBrands.includes(cardBrand as BraintreeSupportedCardBrands);\n};\n\nexport default isBraintreeSupportedCardBrand;\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeCreditCardPaymentStrategy from './braintree-credit-card-payment-strategy';\nimport BraintreeHostedForm from '../braintree-hosted-form/braintree-hosted-form';\n\nconst createBraintreeCreditCardPaymentStrategy: PaymentStrategyFactory<\n BraintreeCreditCardPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n\n const braintreeScriptLoader = new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n );\n\n const braintreeIntegrationService = new BraintreeIntegrationService(\n braintreeScriptLoader,\n braintreeHostWindow,\n );\n\n const braintreeHostedForm = new BraintreeHostedForm(\n braintreeScriptLoader,\n braintreeSDKVersionManager,\n );\n\n return new BraintreeCreditCardPaymentStrategy(\n paymentIntegrationService,\n braintreeIntegrationService,\n braintreeHostedForm,\n );\n};\n\nexport default toResolvableModule(createBraintreeCreditCardPaymentStrategy, [{ id: 'braintree' }]);\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 { noop, some } from 'lodash';\n\nimport { CreditCardPaymentStrategy } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStatusTypes,\n RequestError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\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';\nimport { isCBAMPGSPaymentMethodLike, isThreeDSErrorBody } from './is-cba-mpgs-payment-method-like';\n\nexport default class CBAMPGSPaymentStrategy extends CreditCardPaymentStrategy {\n private threeDSjs?: ThreeDSjs;\n\n private sessionId = '';\n private locale?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private cbaMGPSScriptLoader: CBAMPGSScriptLoader,\n ) {\n super(paymentIntegrationService);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const { methodId } = options;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n if (!isCBAMPGSPaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\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 this.locale = state.getLocale();\n\n if (!this.locale) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n await this.threeDSjs.configure({\n merchantId,\n sessionId: this.sessionId,\n callback: () => {\n if (this.threeDSjs?.isConfigured()) {\n return this.paymentIntegrationService.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();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): 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 state = this.paymentIntegrationService.getState();\n const paymentMethod = state.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 !isRequestError(error) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n const retryState = this.paymentIntegrationService.getState();\n const order = retryState.getOrder();\n\n const {\n storeProfile: { storeId },\n } = retryState.getStoreConfigOrThrow();\n\n if (!order || !this.sessionId) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const orderId = `${storeId}_${order.orderId}`;\n\n if (!isThreeDSErrorBody(error.body)) {\n throw new RequestError();\n }\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 async finalize(options?: PaymentRequestOptions): Promise {\n const state = this.paymentIntegrationService.getState();\n const order = state.getOrder();\n\n if (order && state.getPaymentStatus() === PaymentStatusTypes.FINALIZE) {\n await this.paymentIntegrationService.finalizeOrder(options);\n\n return Promise.resolve();\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(orderId: string, transactionId: string): 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 PaymentMethodFailedError(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 PaymentMethodFailedError());\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 PaymentMethodFailedError();\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 // eslint-disable-next-line @typescript-eslint/no-misused-promises\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 // eslint-disable-next-line no-plusplus, no-param-reassign\n return this.authenticatePayer(orderId, transactionId, ++attempt);\n }\n\n return reject(new PaymentMethodFailedError());\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","/* eslint-disable @typescript-eslint/consistent-type-assertions */\nimport { PaymentMethod } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CBAMPGSPaymentMethod, ThreeDSErrorBody } from './cba-mpgs';\n\nexport function isCBAMPGSPaymentMethodLike(\n paymentMethod: PaymentMethod,\n): paymentMethod is CBAMPGSPaymentMethod {\n return (\n typeof paymentMethod === 'object' &&\n paymentMethod !== null &&\n 'initializationData' in paymentMethod &&\n typeof (paymentMethod as CBAMPGSPaymentMethod).initializationData === 'object' &&\n (paymentMethod as CBAMPGSPaymentMethod).initializationData !== null &&\n 'merchantId' in (paymentMethod as CBAMPGSPaymentMethod).initializationData &&\n typeof (paymentMethod as CBAMPGSPaymentMethod).initializationData.merchantId === 'string' &&\n (typeof (paymentMethod as CBAMPGSPaymentMethod).initializationData.isTestModeFlagEnabled ===\n 'boolean' ||\n typeof (paymentMethod as CBAMPGSPaymentMethod).initializationData\n .isTestModeFlagEnabled === 'undefined')\n );\n}\n\nexport function isThreeDSErrorBody(body: unknown): body is ThreeDSErrorBody {\n return (\n typeof body === 'object' &&\n body !== null &&\n 'three_ds_result' in body &&\n typeof (body as ThreeDSErrorBody).three_ds_result === 'object' &&\n (body as ThreeDSErrorBody).three_ds_result !== null &&\n 'token' in (body as ThreeDSErrorBody).three_ds_result &&\n typeof (body as ThreeDSErrorBody).three_ds_result.token === 'string'\n );\n}\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport { PaymentMethod } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport 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\nexport interface CBAMPGSPaymentMethod extends PaymentMethod {\n initializationData: CBAMPGSInitializationData;\n}\n\nexport interface CBAMPGSInitializationData {\n isTestModeFlagEnabled?: boolean;\n merchantId: string;\n}\n\nexport interface ThreeDSErrorBody {\n three_ds_result: {\n token: string;\n };\n}\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\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 { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CBAMPGSPaymentStrategy from './cba-mpgs-payment-strategy';\nimport CBAMPGSScriptLoader from './cba-mpgs-script-loader';\n\nconst createCBAMPGSPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new CBAMPGSPaymentStrategy(\n paymentIntegrationService,\n new CBAMPGSScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createCBAMPGSPaymentStrategy, [{ id: 'cba_mpgs' }]);\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 skipRedirectConfirmationAlert: true,\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\n if (\n methodId === CHECKOUTCOM_SEPA_PAYMENT_METHOD &&\n document &&\n 'iban' in paymentData &&\n 'bic' in paymentData\n ) {\n const { iban, bic } = paymentData as unknown as WithCheckoutcomSEPAInstrument;\n\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 const features = this._paymentIntegrationService.getState().getStoreConfigOrThrow()\n .checkoutSettings.features;\n\n this._clearpaySdk = await this._clearpayScriptLoader.load(paymentMethod, features);\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';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\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 HTTPS_SANDBOX: 'https://portal.sandbox.clearpay.co.uk/afterpay-async.js',\n HTTPS_PROD: 'https://portal.clearpay.co.uk/afterpay-async.js',\n};\n\nconst CLEARPAY_HTTPS_PROD_SCRIPT_EXPERIMENT = 'PI-4555.clearpay_add_https_to_prod_script';\n\nexport default class ClearpayScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, public _window: ClearpayWindow = window) {}\n\n async load(method: PaymentMethod, features = {}): Promise {\n await this._scriptLoader.loadScript(this._getScriptUrl(method.config.testMode, features));\n\n if (!this._window.AfterPay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.AfterPay;\n }\n\n private _getScriptUrl(testMode?: boolean, features = {}): string {\n const httpsEnabled = isExperimentEnabled(\n features,\n CLEARPAY_HTTPS_PROD_SCRIPT_EXPERIMENT,\n false,\n );\n\n if (testMode) {\n return httpsEnabled ? SCRIPTS_DEFAULT.HTTPS_SANDBOX : SCRIPTS_DEFAULT.SANDBOX;\n }\n\n return httpsEnabled ? SCRIPTS_DEFAULT.HTTPS_PROD : 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';\n\nconst SDK_PROD_URL = 'https://static.client.cardinaltrusted.com/songbird/v2.0.0/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, [\n { id: 'cybersourcev2' },\n { id: 'bnz' },\n]);\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 {\n guard,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n Omit,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { DEFAULT_CONTAINER_STYLES, LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\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 ErrorReasonType,\n GooglePayError,\n GooglePayInitializationData,\n GooglePayPaymentOptions,\n HandleCouponsOut,\n IntermediatePaymentData,\n TotalPriceStatusType,\n} from './types';\n\nexport default class GooglePayPaymentStrategy implements PaymentStrategy {\n private _loadingIndicator: LoadingIndicator;\n private _loadingIndicatorContainer?: string;\n private _paymentButton?: HTMLElement;\n private _clickListener?: (event: MouseEvent) => unknown;\n private _methodId?: keyof WithGooglePayPaymentInitializeOptions;\n private _isDeinitializationBlocked = false;\n\n constructor(\n protected _paymentIntegrationService: PaymentIntegrationService,\n protected _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n ) {\n this._loadingIndicator = new LoadingIndicator({\n containerStyles: DEFAULT_CONTAINER_STYLES,\n });\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, loadingContainerId, ...callbacks } = googlePayOptions;\n\n this._loadingIndicatorContainer = loadingContainerId;\n\n await this._paymentIntegrationService.loadPaymentMethod(this._getMethodId());\n\n const paymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(this._getMethodId());\n\n this._googlePayPaymentProcessor.setIsWebViewExperimentOn(\n !!paymentMethod.initializationData?.isWebViewExperimentOn,\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._isDeinitializationBlocked) {\n return Promise.resolve();\n }\n\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 this._googlePayPaymentProcessor.setShouldRequestShipping(false);\n await this._googlePayPaymentProcessor.initializeWidget();\n\n if (this._isDirectPayOnClickEnabled()) {\n await this._interactWithPaymentSheetAndPay();\n } else {\n await this._interactWithPaymentSheet();\n }\n } catch (error) {\n let err: unknown = error;\n\n this._toggleLoadingIndicator(false);\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 } finally {\n this._toggleBlockDeinitialization(false);\n }\n\n onPaymentSelect?.();\n };\n }\n\n protected async _interactWithPaymentSheetAndPay(): Promise {\n const response = await this._googlePayPaymentProcessor.showPaymentSheet();\n\n this._toggleBlockDeinitialization(true);\n this._toggleLoadingIndicator(true);\n\n const methodId = this._getMethodId();\n\n const state = this._paymentIntegrationService.getState();\n const { features } = state.getStoreConfigOrThrow().checkoutSettings;\n const isGooglePayDontOverrideAddresssExperimentOn = isExperimentEnabled(\n features,\n 'PI-5031.google_pay_dont_override_address',\n );\n\n const billingAddress =\n this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(response);\n\n if (billingAddress && !isGooglePayDontOverrideAddresssExperimentOn) {\n await this._paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n await this._googlePayPaymentProcessor.setExternalCheckoutXhr(methodId, response);\n\n await this._paymentIntegrationService.loadCheckout();\n await this._paymentIntegrationService.loadPaymentMethod(methodId);\n\n const freshPaymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n\n await this._googlePayPaymentProcessor.initialize(() => freshPaymentMethod);\n\n await this.execute({ useStoreCredit: false, payment: { methodId } });\n\n this._completeCheckoutFlow();\n }\n\n protected _completeCheckoutFlow(): void {\n window.location.replace('/checkout/order-confirmation');\n this._toggleLoadingIndicator(false);\n this._toggleBlockDeinitialization(false);\n }\n\n protected async _interactWithPaymentSheet(): Promise {\n const response = await this._googlePayPaymentProcessor.showPaymentSheet();\n const state = this._paymentIntegrationService.getState();\n const { features } = state.getStoreConfigOrThrow().checkoutSettings;\n const isGooglePayDontOverrideAddresssExperimentOn = isExperimentEnabled(\n features,\n 'PI-5031.google_pay_dont_override_address',\n );\n\n this._toggleBlockDeinitialization(true);\n this._toggleLoadingIndicator(true);\n\n const billingAddress =\n this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(response);\n\n if (billingAddress && !isGooglePayDontOverrideAddresssExperimentOn) {\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 this._toggleLoadingIndicator(false);\n this._toggleBlockDeinitialization(false);\n }\n\n protected _getMethodId(): keyof WithGooglePayPaymentInitializeOptions {\n return guard(\n this._methodId,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n protected async _getIsSignedInOrThrow(): Promise {\n try {\n return !!(await this._googlePayPaymentProcessor.getNonce(this._getMethodId()));\n } catch (e) {\n if (\n e instanceof MissingDataError &&\n e.subtype === MissingDataErrorType.MissingPaymentToken\n ) {\n return false;\n }\n\n throw e;\n }\n }\n\n protected async _handleOfferTrigger(\n offerData: IntermediatePaymentData['offerData'],\n ): Promise> {\n let isSignedIn = false;\n let errorMessage = 'Sign in to Google Pay first to apply or remove promo codes.';\n\n try {\n isSignedIn = await this._getIsSignedInOrThrow();\n } catch (error) {\n if (error instanceof MissingDataError) {\n errorMessage = error.message;\n }\n }\n\n // We can only apply/remove coupons on the payment step only if we are logged into Google Pay, otherwise we will get an error\n if (isSignedIn) {\n const { newOfferInfo, error } = await this._googlePayPaymentProcessor.handleCoupons(\n offerData,\n );\n\n return {\n newOfferInfo,\n error,\n };\n }\n\n return {\n error: {\n reason: ErrorReasonType.OFFER_INVALID,\n message: errorMessage,\n intent: CallbackTriggerType.OFFER,\n },\n };\n }\n\n protected _getGooglePayClientOptions(countryCode?: string): GooglePayPaymentOptions {\n if (this._googlePayPaymentProcessor.isWebViewWithRestrictions()) {\n return {};\n }\n\n return {\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({ callbackTrigger, offerData }) => {\n if (\n callbackTrigger !== CallbackTriggerType.INITIALIZE &&\n callbackTrigger !== CallbackTriggerType.OFFER\n ) {\n return;\n }\n\n const { offerChangeTriggers } =\n this._googlePayPaymentProcessor.getCallbackTriggers();\n\n const { newOfferInfo = undefined, error: couponsError = undefined } =\n offerChangeTriggers.includes(callbackTrigger)\n ? await this._handleOfferTrigger(offerData)\n : {};\n\n // We can add another errors if needed 'couponsError || shippingError || anotherError'\n const error: GooglePayError | undefined = couponsError;\n\n await this._paymentIntegrationService.loadCheckout();\n\n const { code: currencyCode } = this._paymentIntegrationService\n .getState()\n .getCartOrThrow().currency;\n const totalPrice = this._googlePayPaymentProcessor.getTotalPrice();\n\n return {\n newTransactionInfo: {\n ...(countryCode && { countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n ...(newOfferInfo && {\n newOfferInfo,\n }),\n ...(error && {\n error,\n }),\n };\n },\n },\n };\n }\n\n private _isDirectPayOnClickEnabled(): boolean {\n const { features } = this._paymentIntegrationService\n .getState()\n .getStoreConfigOrThrow().checkoutSettings;\n\n return isExperimentEnabled(features, 'PI-5111.google_pay_direct_pay_on_click');\n }\n\n private _toggleBlockDeinitialization(isBlocked: boolean) {\n this._isDeinitializationBlocked = isBlocked;\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 { 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';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\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';\n\nconst createGooglePayStripePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayStripeGateway(\n paymentIntegrationService,\n new StripeScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayStripePaymentStrategy, [\n { id: 'googlepaystripe' },\n { id: 'googlepaystripeupe' },\n { id: 'googlepaystripeocs' },\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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 MissingDataError,\n MissingDataErrorType,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../google-pay-payment-strategy';\nimport { GooglePayInitializationData, GooglePayPayPalCommerceInitializationData } from '../types';\n\nimport { ConfirmOrderData, ConfirmOrderStatus } from './types';\n\nexport default class GooglePayPaypalCommercePaymentStrategy extends GooglePayPaymentStrategy {\n constructor(\n _paymentIntegrationService: PaymentIntegrationService,\n _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n private _payPalCommerceSdk: PayPalCommerceSdk,\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 if (!paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const currencyCode = state.getCartOrThrow().currency.code;\n\n const payPalSDK = await this._payPalCommerceSdk.getPayPalGooglePaySdk(\n paymentMethod,\n currencyCode,\n state.getLocale(),\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';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\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';\n\nconst createGooglePayPayPalCommercePaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) => {\n const payPalCommerceSdk = new PayPalCommerceSdk(getScriptLoader());\n\n return new GooglePayPaypalCommercePaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayPaypalCommerceGateway(paymentIntegrationService, payPalCommerceSdk),\n createRequestSender(),\n createFormPoster(),\n ),\n payPalCommerceSdk,\n createRequestSender(),\n );\n};\n\nexport default toResolvableModule(createGooglePayPayPalCommercePaymentStrategy, [\n { id: 'googlepaypaypalcommerce' },\n]);\n","import { GooglePayConfig } from '../types';\n\nexport type FundingType = string;\n\n/**\n *\n * BigCommercePayments 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 BigCommercePaymentsHostWindow extends Window {\n paypal?: PayPalSDK;\n}\n\nexport interface BigCommercePaymentsScriptParams {\n options: {\n 'client-id'?: string;\n 'merchant-id'?: string;\n 'buyer-country'?: string;\n 'disable-funding'?: FundingType[];\n 'enable-funding'?: FundingType[];\n currency?: string;\n commit?: boolean;\n intent?: BigCommercePaymentsIntent;\n components?: ComponentsScriptType;\n };\n attributes: {\n 'data-client-token'?: string;\n 'data-partner-attribution-id'?: string;\n };\n}\n\nexport enum BigCommercePaymentsIntent {\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 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 BigCommercePaymentsInitializationData,\n PayPalSdkHelper,\n} from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentMethod,\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 {\n GooglePayBigCommercePaymentsInitializationData,\n GooglePayInitializationData,\n} from '../types';\n\nimport { ConfirmOrderData, ConfirmOrderStatus } from './types';\n\nexport default class GooglePayBigCommercePaymentsPaymentStrategy extends GooglePayPaymentStrategy {\n constructor(\n _paymentIntegrationService: PaymentIntegrationService,\n _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n private _payPalSdkHelper: PayPalSdkHelper,\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 if (!paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const currencyCode = state.getCartOrThrow().currency.code;\n\n const payPalSDK = await this._payPalSdkHelper.getPayPalGooglePaySdk(\n paymentMethod as 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/googlepay_bigcommerce_paymentscheckout';\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 { PayPalSdkHelper } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\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 GooglePayBigCommercePaymentsGateway from './google-pay-bigcommerce-payments-gateway';\nimport GooglePayBigCommercePaymentsPaymentStrategy from './google-pay-bigcommerce-payments-payment-strategy';\n\nconst createGooglePayBigCommercePaymentsPaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) => {\n const payPalSdkHelper = new PayPalSdkHelper(getScriptLoader());\n\n return new GooglePayBigCommercePaymentsPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayBigCommercePaymentsGateway(paymentIntegrationService, payPalSdkHelper),\n createRequestSender(),\n createFormPoster(),\n ),\n payPalSdkHelper,\n createRequestSender(),\n );\n};\n\nexport default toResolvableModule(createGooglePayBigCommercePaymentsPaymentStrategy, [\n { id: 'googlepay_bigcommerce_payments' },\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","import { 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';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport KlarnaPayments, {\n KlarnaAddress,\n KlarnaAuthorizationResponse,\n KlarnaInitializationData,\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, initializationData } =\n state.getPaymentMethodOrThrow(methodId);\n const { klarnaMultipleRadioButton } = initializationData || {};\n\n await this.klarnav2TokenUpdater.klarnaOrderInitialization(cartId, clientToken);\n\n const paymentMethodСategory = this.isKlarnaMultipleRadioButtonEnabled(\n klarnaMultipleRadioButton,\n gatewayId,\n methodId,\n );\n const { authorization_token: authorizationToken } = await this.authorizeOrThrow(\n paymentMethodСategory,\n methodId,\n );\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 const { klarnaMultipleRadioButton } = paymentMethod.initializationData || {};\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 {\n container,\n payment_method_category: this.isKlarnaMultipleRadioButtonEnabled(\n klarnaMultipleRadioButton,\n gatewayId,\n methodId,\n ),\n },\n (response) => {\n if (onLoad) {\n onLoad(response);\n }\n\n resolve(response);\n },\n );\n });\n }\n\n private getUpdateSessionData(\n methodId: string,\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(\n methodId,\n billingAddress,\n billingAddress.email,\n ),\n };\n\n if (shippingAddress) {\n data.shipping_address = this.mapToKlarnaAddress(\n methodId,\n shippingAddress,\n billingAddress.email,\n );\n }\n\n return data;\n }\n\n private needsStateCode(countryCode: string) {\n return includes(supportedCountriesRequiringStates, countryCode);\n }\n\n private isKlarnaMultipleRadioButtonEnabled(\n klarnaMultipleRadioButton: boolean | undefined,\n gatewayId: string,\n methodId: string,\n ): string {\n return klarnaMultipleRadioButton ? methodId : gatewayId;\n }\n\n private mapToKlarnaAddress(methodId: string, address: Address, email?: string): KlarnaAddress {\n const state = this.paymentIntegrationService.getState();\n const { checkoutSettings } = state.getStoreConfigOrThrow();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { enableBillie } = paymentMethod.initializationData || {};\n\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 if (\n address.company &&\n enableBillie &&\n isExperimentEnabled(checkoutSettings.features, 'PI-3915.b2b_payment_session_for_klarna')\n ) {\n klarnaAddress.organization_name = address.company;\n }\n\n return klarnaAddress;\n }\n\n private async authorizeOrThrow(\n paymentMethodСategory: string,\n methodId: string,\n ): 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(\n methodId,\n billingAddress,\n shippingAddress,\n );\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 {\n payment_method_category: paymentMethodСategory,\n },\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 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 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\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 (\n typeof response.data !== 'string' ||\n response.origin !== `https://${testMode ? 'esqa' : 'www3'}.moneris.com`\n ) {\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 iframe.allow = 'payment';\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 {\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 payment.gatewayId === 'adyen' || payment.gatewayId === 'barclaycard';\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","import { MessagesStyleOptions, PayPalBNPLConfigurationItem } from '../paypal-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 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 {\n ApproveCallbackPayload,\n ClickCallbackActions,\n getPaypalMessagesStylesFromBNPLConfig,\n isPaypalProviderError,\n isRedirectActionError,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalButtons,\n PayPalButtonsOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalMessagesSdk,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isBaseInstrument } from '@bigcommerce/checkout-sdk/utility';\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?: PayPalButtons;\n private paypalcommerce?: PayPalCommercePaymentInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\n private payPalSdkScriptLoader: PayPalSdkScriptLoader,\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 = state.getPaymentMethodOrThrow(methodId);\n\n const { container, bannerContainerId } = paypalcommerce;\n\n const {\n orderId,\n paypalBNPLConfiguration = [],\n isPayPalCreditAvailable,\n } = paymentMethod.initializationData || {};\n\n if (bannerContainerId !== undefined) {\n if (!document.getElementById(bannerContainerId)) {\n // eslint-disable-next-line no-console\n console.error('Unable to create banner without valid banner container ID.');\n\n return;\n }\n\n const bannerConfiguration = paypalBNPLConfiguration?.find(\n ({ id }) => id === 'checkout',\n );\n\n if (isPayPalCreditAvailable || !bannerConfiguration?.status) {\n return;\n }\n\n const paypalMessages = await this.payPalSdkScriptLoader.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n state.getLocale(),\n );\n\n if (!paypalMessages || typeof paypalMessages?.Messages !== 'function') {\n console.error(\n '[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK',\n );\n\n return;\n }\n\n return this.renderMessages(paypalMessages, bannerContainerId, bannerConfiguration);\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 = paymentMethod.initializationData?.orderId;\n\n return;\n }\n\n this.loadingIndicatorContainer = container?.split('#')[1];\n\n await this.paypalIntegrationService.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\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 (isRedirectActionError(error)) {\n const redirectUrl = error.body.additional_action_required?.data?.redirect_url;\n\n return new Promise(() => window.location.replace(redirectUrl));\n }\n\n if (this.isProviderError(error)) {\n await this.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { paymentButtonStyles } = paymentMethod.initializationData || {};\n const { checkoutPaymentButtonStyles } = paymentButtonStyles || {};\n const { container, onError, onRenderButton, onValidate, submitForm } = paypalcommerce;\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"container\" argument is not provided.',\n );\n }\n\n const containerId = this.getSmartButtonContainerId(container);\n const smartButtonContainer = document.getElementById(containerId);\n\n if (!smartButtonContainer) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because element with id ${containerId} does not exist.`,\n );\n }\n\n const buttonOptions: PayPalButtonsOptions = {\n ...(this.isPaypalCommerceAppSwitchEnabled(methodId) && {\n appSwitchWhenAvailable: true,\n }),\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalIntegrationService.getValidButtonStyle(checkoutPaymentButtonStyles),\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 if (this.paypalButton.hasReturned?.() && this.isPaypalCommerceAppSwitchEnabled(methodId)) {\n this.paypalButton.resume?.();\n } else {\n this.paypalButton.render(container);\n }\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 return 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.paypalIntegrationService.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 const findInstrument = instruments?.find(\n (instrument) =>\n isBaseInstrument(instrument) &&\n instrument.bigpayToken === paymentData.instrumentId,\n );\n const trustedShippingAddress = isBaseInstrument(findInstrument)\n ? findInstrument.trustedShippingAddress\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 /**\n *\n * Render Pay Later Messages\n *\n * */\n private renderMessages(\n paypalMessages: PayPalMessagesSdk,\n bannerContainerId: string,\n bannerConfiguration: PayPalBNPLConfigurationItem,\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: checkout.outstandingBalance,\n placement: 'payment',\n style: getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\n };\n\n paypalMessages.Messages(paypalMessagesOptions).render(`#${bannerContainerId}`);\n }\n\n /**\n *\n * Error handling\n *\n */\n private isProviderError(error: unknown): boolean {\n if (isPaypalProviderError(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 /**\n *\n * PayPal AppSwitch enabling handling\n *\n */\n private isPaypalCommerceAppSwitchEnabled(methodId: string): boolean {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n return paymentMethod.initializationData?.isAppSwitchEnabled || false;\n }\n\n private getSmartButtonContainerId(container: string) {\n return container.split('#')[1] ?? container;\n }\n}\n","import { isRequestError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ProviderError } from './is-paypal-provider-error';\n\nexport interface RedirectActionError extends ProviderError {\n body: {\n additional_action_required: {\n type: 'offsite_redirect';\n data: {\n redirect_url: string;\n };\n };\n };\n}\n\nexport default function isRedirectActionError(error: unknown): error is RedirectActionError {\n return (\n isRequestError(error) && error.body.additional_action_required?.type === 'offsite_redirect'\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 isPaypalProviderError(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 PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalIntegrationService,\n LOADING_INDICATOR_STYLES,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommercePaymentStrategy from './paypal-commerce-payment-strategy';\n\nconst createPayPalCommercePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new PayPalCommercePaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\n new PayPalSdkScriptLoader(getScriptLoader()),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createPayPalCommercePaymentStrategy, [{ id: 'paypalcommerce' }]);\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 ApproveCallbackPayload,\n ClickCallbackActions,\n getPaypalMessagesStylesFromBNPLConfig,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalButtons,\n PayPalButtonsOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalMessagesSdk,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\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?: PayPalButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\n private loadingIndicator: LoadingIndicator,\n private payPalSdkScriptLoader: PayPalSdkScriptLoader,\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 = state.getPaymentMethodOrThrow(methodId);\n\n const { paypalBNPLConfiguration = [], orderId } = paymentMethod.initializationData || {};\n const { bannerContainerId, container } = paypalOptions;\n\n if (bannerContainerId !== undefined) {\n if (!document.getElementById(bannerContainerId)) {\n // eslint-disable-next-line no-console\n console.error('Unable to create banner without valid banner container ID.');\n\n return;\n }\n\n const bannerConfiguration =\n paypalBNPLConfiguration &&\n paypalBNPLConfiguration.find(({ id }) => id === 'checkout');\n\n if (!bannerConfiguration?.status) {\n return;\n }\n\n const paypalMessages = await this.payPalSdkScriptLoader.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n state.getLocale(),\n );\n\n return this.renderMessages(paypalMessages, bannerContainerId, bannerConfiguration);\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.paypalIntegrationService.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.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = 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: PayPalButtonsOptions = {\n fundingSource,\n style: this.paypalIntegrationService.getValidButtonStyle(\n checkoutPaymentButtonStyles,\n ),\n createOrder: () =>\n this.paypalIntegrationService.createOrder('paypalcommercecreditcheckout'),\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 return 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,\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: checkout.outstandingBalance,\n placement: 'payment',\n style: getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration),\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 {\n createPayPalIntegrationService,\n createPayPalSdkScriptLoader,\n LOADING_INDICATOR_STYLES,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceCreditPaymentStrategy from './paypal-commerce-credit-payment-strategy';\n\nconst createPayPalCommerceCreditPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceCreditPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditPaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n createPayPalSdkScriptLoader(),\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 {\n ApproveCallbackPayload,\n ClickCallbackActions,\n PayPalButtons,\n PayPalButtonsOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\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?: PayPalButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalIntegrationService: PayPalIntegrationService,\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 = 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.paypalIntegrationService.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.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = 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: PayPalButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.paypalIntegrationService.getValidButtonStyle(checkoutPaymentButtonStyles),\n createOrder: () =>\n this.paypalIntegrationService.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 return 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 { createPayPalIntegrationService } from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceVenmoPaymentStrategy from './paypal-commerce-venmo-payment-strategy';\n\nconst createPayPalCommerceVenmoPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceVenmoPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceVenmoPaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n\nexport default toResolvableModule(createPayPalCommerceVenmoPaymentStrategy, [\n { id: 'paypalcommercevenmo' },\n]);\n","export const LOADING_INDICATOR_STYLES = {\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\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 TimeoutError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n PayPalApmSdk,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { isExperimentEnabled } from '@bigcommerce/checkout-sdk/utility';\n\nimport {\n ApproveCallbackPayload,\n NonInstantAlternativePaymentMethods,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n PayPalOrderStatus,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceAlternativeMethodsPaymentOptions, {\n WithPayPalCommerceAlternativeMethodsPaymentInitializeOptions,\n} from './paypal-commerce-alternative-methods-payment-initialize-options';\n\nconst POLLING_INTERVAL = 3000;\nconst MAX_POLLING_TIME = 300000;\n\nexport default class PayPalCommerceAlternativeMethodsPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n private paypalApms?: PayPalApmSdk;\n private pollingTimer = 0;\n private stopPolling = noop;\n private isOrderApprovedProcessing = false;\n private paypalcommercealternativemethods?: PayPalCommerceAlternativeMethodsPaymentOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalIntegrationService,\n private paypalSdkScriptLoader: PayPalSdkScriptLoader,\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 &\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 this.paypalcommercealternativemethods = paypalcommercealternativemethods;\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 const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n\n this.isOrderApprovedProcessing = isExperimentEnabled(\n features,\n 'PAYPAL-5431.order_approved_processing',\n false,\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 this.paypalApms = await this.paypalSdkScriptLoader.getPayPalApmsSdk(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n state.getLocale(),\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.isOrderApprovedProcessing && methodId === 'ideal') {\n await new Promise((resolve, reject) => {\n void this.initializePollingMechanism(methodId, resolve, reject, gatewayId);\n });\n }\n\n if (\n !this.isNonInstantPaymentMethod(methodId) ||\n (methodId === NonInstantAlternativePaymentMethods.IDEAL &&\n !this.isOrderApprovedProcessing)\n ) {\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 if (!this.isOrderApprovedProcessing) {\n this.resetPollingMechanism();\n }\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Polling mechanism\n *\n *\n * */\n private async initializePollingMechanism(\n methodId: string,\n resolvePromise: (value?: unknown) => void,\n rejectPromise: (value?: unknown) => 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 gatewayId ?? 'paypalcommerce',\n );\n\n const isOrderApproved = orderStatus === PayPalOrderStatus.Approved;\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 paypalcommercealternativemethods: this.paypalcommercealternativemethods,\n });\n\n this.handleError(new TimeoutError());\n } catch (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 private async reinitializeStrategy(\n options: PaymentInitializeOptions &\n WithPayPalCommerceAlternativeMethodsPaymentInitializeOptions,\n ) {\n await this.deinitialize();\n await this.initialize(options);\n }\n\n private handleError(error: unknown) {\n const { onError } = this.paypalcommercealternativemethods || {};\n\n if (!this.isOrderApprovedProcessing) {\n this.resetPollingMechanism();\n }\n\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\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: () => {\n this.toggleLoadingIndicator(false);\n this.deinitializePollingMechanism();\n },\n onError: (error) => {\n this.deinitializePollingMechanism();\n this.handleFailure(error, onError);\n },\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 (\n this.isNonInstantPaymentMethod(methodId) &&\n ((methodId === NonInstantAlternativePaymentMethods.IDEAL &&\n this.isOrderApprovedProcessing) ||\n methodId === NonInstantAlternativePaymentMethods.OXXO)\n ) {\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\n if (methodId === NonInstantAlternativePaymentMethods.IDEAL) {\n const state = this.paymentIntegrationService.getState();\n const bcOrderId = state.getOrder()?.orderId;\n\n await this.paypalCommerceIntegrationService.updateOrder(\n 'paypalcommercealternativemethods',\n methodId,\n bcOrderId,\n );\n }\n\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 {\n createPayPalIntegrationService,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\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 createPayPalIntegrationService(paymentIntegrationService),\n createPayPalSdkScriptLoader(),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createPayPalCommerceAlternativeMethodsPaymentStrategy, [\n { gateway: 'paypalcommercealternativemethods' },\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 { isPayPalCommerceAcceleratedCheckoutCustomer } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\nimport {\n PayPalFastlaneUtils,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\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 paypalIntegrationService: PayPalIntegrationService,\n private paypalSdkScriptLoader: PayPalSdkScriptLoader,\n private paypalFastlaneUtils: PayPalFastlaneUtils,\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, onLoadComplete } =\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.paypalIntegrationService.loadPayPalSdk(methodId, undefined, true, true);\n\n if (this.isCreditCardForm || this.isCreditCardVaultedForm) {\n await this.initializeFields(form, onCreditCardFieldsRenderingError);\n }\n\n onLoadComplete?.();\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.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n const executeCallback = this.getExecuteCallback(fields);\n\n const cardFieldsConfig: PayPalCommerceCardFieldsConfig = {\n style: this.getInputStyles(styles),\n onApprove: ({\n orderID,\n vaultSetupToken,\n liabilityShift,\n }: PayPalCommerceCardFieldsOnApproveData) => {\n if (\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.paypalIntegrationService.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.paypalIntegrationService.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 = 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 = state.getPaymentMethodOrThrow(methodId);\n const { initializationData } = paymentMethod;\n\n if (!initializationData?.connectClientToken) {\n return;\n }\n\n const payPalFastlaneSdk = await this.paypalSdkScriptLoader.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n state.getLocale(),\n );\n\n await this.paypalFastlaneUtils.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 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 {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalFastlaneUtils,\n createPayPalIntegrationService,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceCreditCardsPaymentStrategy from './paypal-commerce-credit-cards-payment-strategy';\n\nconst createPaypalCommerceCreditCardsPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceCreditCardsPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditCardsPaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\n createPayPalSdkScriptLoader(),\n createPayPalFastlaneUtils(),\n );\n\nexport default toResolvableModule(createPaypalCommerceCreditCardsPaymentStrategy, [\n { id: 'paypalcommercecreditcards' },\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 {\n BirthDate,\n PayPalInitializationData,\n PayPalIntegrationService,\n PayPalOrderStatus,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\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 paypalCommerceService: PayPalIntegrationService,\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.paypalCommerceService.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.paypalCommerceService.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.paypalCommerceService.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.paypalCommerceService.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 {\n createPayPalIntegrationService,\n LOADING_INDICATOR_STYLES,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PaypalCommerceRatepayPaymentStrategy from './paypal-commerce-ratepay-payment-strategy';\n\nconst createPaypalCommerceRatepayPaymentStrategy: PaymentStrategyFactory<\n PaypalCommerceRatepayPaymentStrategy\n> = (paymentIntegrationService) =>\n new PaypalCommerceRatepayPaymentStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(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 PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n getFastlaneStyles,\n isPayPalFastlaneCustomer,\n isPaypalFastlaneRequestError,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneCardComponentMethods,\n PayPalFastlaneCardComponentOptions,\n PayPalFastlanePaymentFormattedPayload,\n PayPalFastlaneSdk,\n PayPalFastlaneUtils,\n PayPalInitializationData,\n PayPalSdkScriptLoader,\n TDSecureAuthenticationState,\n TDSecureVerificationMethod,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceRequestSender from '../paypal-commerce-request-sender';\nimport { LiabilityShiftEnum } from '../paypal-commerce-types';\n\nimport PayPalCommerceFastlanePaymentInitializeOptions, {\n WithPayPalCommerceFastlanePaymentInitializeOptions,\n} from './paypal-commerce-fastlane-payment-initialize-options';\n\nexport default class PaypalCommerceFastlanePaymentStrategy implements PaymentStrategy {\n private paypalComponentMethods?: PayPalFastlaneCardComponentMethods;\n private paypalFastlaneSdk?: PayPalFastlaneSdk;\n private threeDSVerificationMethod?: string;\n private paypalcommercefastlane?: PayPalCommerceFastlanePaymentInitializeOptions;\n private orderId?: string;\n private methodId?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceRequestSender: PayPalCommerceRequestSender,\n private paypalSdkScriptLoader: PayPalSdkScriptLoader,\n private paypalFastlaneUtils: PayPalFastlaneUtils,\n ) {}\n\n /**\n *\n * Default methods\n *\n * */\n async initialize(\n options: PaymentInitializeOptions & WithPayPalCommerceFastlanePaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommercefastlane } = options;\n\n this.methodId = methodId;\n\n this.paypalcommercefastlane = paypalcommercefastlane;\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 = state.getPaymentMethodOrThrow(methodId);\n const { isDeveloperModeApplicable, isFastlaneStylingEnabled } =\n paymentMethod.initializationData || {};\n\n this.threeDSVerificationMethod =\n paymentMethod.initializationData?.threeDSVerificationMethod;\n\n this.paypalFastlaneSdk = await this.paypalSdkScriptLoader.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n state.getLocale(),\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.paypalFastlaneUtils.initializePayPalFastlane(\n this.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 await this.paymentIntegrationService.submitOrder(order, options);\n\n const paymentPayload = isVaultedFlow\n ? await this.prepareVaultedInstrumentPaymentPayload(methodId, paymentData)\n : await this.preparePaymentPayload(methodId, paymentData);\n\n await this.paymentIntegrationService.submitPayment(\n paymentPayload,\n );\n\n this.paypalFastlaneUtils.removeStorageSessionId();\n } catch (error) {\n if (\n isPaypalFastlaneRequestError(error) &&\n error.response.body.name === 'INVALID_REQUEST'\n ) {\n const invalidRequestError = {\n translationKey: 'payment.errors.invalid_request_error',\n };\n\n this.handleError(invalidRequestError);\n\n return Promise.reject();\n }\n\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.paypalFastlaneUtils.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 } = await this.paypalFastlaneUtils.lookupCustomerOrThrow(\n customerEmail,\n );\n\n const authenticationResult =\n await this.paypalFastlaneUtils.triggerAuthenticationFlowOrThrow(customerContextId);\n\n const { authenticationState, addresses, instruments } =\n this.paypalFastlaneUtils.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 if (isAuthenticationFlowCanceled) {\n this.paypalFastlaneUtils.removeStorageSessionId();\n } else {\n this.paypalFastlaneUtils.updateStorageSessionId(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.paypalFastlaneUtils.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 paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const is3DSEnabled = paymentMethod.config.is3dsEnabled;\n\n const nonce = is3DSEnabled ? await this.get3DSNonce(instrumentId) : instrumentId;\n\n await this.createOrder(nonce);\n\n return {\n methodId,\n paymentData: {\n formattedPayload: {\n paypal_fastlane_token: {\n order_id: this.orderId,\n token: nonce,\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 billingAddress = state.getBillingAddressOrThrow();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\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.paypalFastlaneUtils.mapBcToPayPalAddress(billingAddress),\n });\n\n const is3DSEnabled = paymentMethod.config.is3dsEnabled;\n\n const nonce = is3DSEnabled ? await this.get3DSNonce(id) : id;\n\n await this.createOrder(nonce);\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: this.orderId,\n token: nonce,\n },\n },\n },\n };\n }\n\n private async createOrder(id: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cartId = state.getCartOrThrow().id;\n\n if (this.methodId) {\n const { orderId } = await this.paypalCommerceRequestSender.createOrder(this.methodId, {\n cartId,\n fastlaneToken: id,\n });\n\n this.orderId = orderId;\n }\n }\n\n /**\n *\n * 3DSecure methods\n *\n * */\n private async get3DSNonce(nonce: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const order = state.getOrderOrThrow();\n const checkoutUrl = state.getStoreConfigOrThrow().links.checkoutLink;\n\n const threeDomainSecureComponent = this.paypalFastlaneSdk?.ThreeDomainSecureClient;\n\n if (!threeDomainSecureComponent) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n const threeDomainSecureParameters = {\n amount: order.orderAmount.toFixed(2),\n currency: cart.currency.code,\n nonce,\n threeDSRequested: this.threeDSVerificationMethod === TDSecureVerificationMethod.Always,\n transactionContext: {\n experience_context: {\n locale: 'en-US',\n return_url: checkoutUrl,\n cancel_url: checkoutUrl,\n },\n },\n };\n\n const isThreeDomainSecureEligible = await threeDomainSecureComponent.isEligible(\n threeDomainSecureParameters,\n );\n\n if (\n this.threeDSVerificationMethod === TDSecureVerificationMethod.Always &&\n !isThreeDomainSecureEligible\n ) {\n throw new PaymentMethodInvalidError();\n }\n\n if (isThreeDomainSecureEligible) {\n const {\n liabilityShift,\n authenticationState,\n nonce: threeDSNonce,\n } = await threeDomainSecureComponent.show();\n\n if (\n liabilityShift === LiabilityShiftEnum.No ||\n liabilityShift === LiabilityShiftEnum.Unknown ||\n authenticationState === TDSecureAuthenticationState.Errored ||\n authenticationState === TDSecureAuthenticationState.Cancelled\n ) {\n throw new PaymentMethodInvalidError();\n }\n\n if (\n authenticationState === TDSecureAuthenticationState.Succeeded &&\n [LiabilityShiftEnum.Yes, LiabilityShiftEnum.Possible].includes(liabilityShift)\n ) {\n return threeDSNonce;\n }\n\n throw new PaymentMethodInvalidError();\n }\n\n return nonce;\n }\n\n /**\n *\n * PayPal Fastlane instrument change\n *\n */\n private async handlePayPalStoredInstrumentChange(\n methodId: string,\n ): Promise {\n const paypalAxoSdk = this.paypalFastlaneUtils.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.paypalFastlaneUtils.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 private handleError(error: unknown): void {\n if (\n this.paypalcommercefastlane?.onError &&\n typeof this.paypalcommercefastlane.onError === 'function'\n ) {\n this.paypalcommercefastlane.onError(error);\n }\n }\n}\n","export interface PaypalFastlaneRequestError {\n name: string;\n message: string;\n response: {\n body: {\n name: string;\n };\n };\n}\n\nexport default function isPaypalFastlaneRequestError(\n error: unknown,\n): error is PaypalFastlaneRequestError {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'message' in error &&\n 'response' in error &&\n 'body' in (error as PaypalFastlaneRequestError).response &&\n 'name' in (error as PaypalFastlaneRequestError).response.body\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 createPayPalFastlaneUtils,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-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 createPayPalSdkScriptLoader(),\n createPayPalFastlaneUtils(),\n );\n};\n\nexport default toResolvableModule(createPayPalCommerceFastlanePaymentStrategy, [\n { id: 'paypalcommerceacceleratedcheckout' }, // PayPal Fastlane relates to 'paypalcommerceacceleratedcheckout' method id\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 enum PaymentStatusTypes {\n ACKNOWLEDGE = 'ACKNOWLEDGE',\n FINALIZE = 'FINALIZE',\n INITIALIZE = 'INITIALIZE',\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 { noop } from 'lodash';\n\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithPaypalExpressPaymentInitializeOptions } from './paypal-express-payment-initialize-options';\nimport PaypalScriptLoader from './paypal-express-script-loader';\nimport { PaymentStatusTypes, PaypalHostWindow, PaypalSDK } from './paypal-express-types';\n\nexport default class PaypalExpressPaymentStrategy implements PaymentStrategy {\n private paypalSdk?: PaypalSDK;\n private paymentMethod?: PaymentMethod;\n private useRedirectFlow = false;\n private window: PaypalHostWindow;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: PaypalScriptLoader,\n ) {\n this.window = window;\n }\n\n async initialize(\n options: PaymentInitializeOptions & WithPaypalExpressPaymentInitializeOptions,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n\n this.paymentMethod = state.getPaymentMethodOrThrow(options.methodId);\n this.useRedirectFlow =\n (options.paypalexpress && options.paypalexpress.useRedirectFlow) === true;\n\n const merchantId = this.paymentMethod.config.merchantId;\n\n if (!this.isInContextEnabled() || !merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const paypalSdk = await this.scriptLoader.loadPaypalSDK();\n\n this.paypalSdk = paypalSdk;\n\n this.paypalSdk.checkout.setup(merchantId, {\n button: 'paypal-button',\n environment: this.paymentMethod.config.testMode ? 'sandbox' : 'production',\n });\n }\n\n deinitialize() {\n if (this.isInContextEnabled() && this.paypalSdk) {\n this.paypalSdk.checkout.closeFlow();\n this.paypalSdk = undefined;\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions) {\n let state: PaymentIntegrationSelectors;\n let redirectUrl: string | undefined;\n const paypal = this.paypalSdk;\n\n if (this.isAcknowledgedOrFinalized()) {\n await this.paymentIntegrationService.submitOrder(payload, options);\n\n return;\n }\n\n if (!this.isInContextEnabled() || this.useRedirectFlow) {\n state = await this.paymentIntegrationService.submitOrder(payload, options);\n redirectUrl = state.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 if (!paypal) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n paypal.checkout.initXO();\n\n try {\n state = await this.paymentIntegrationService.submitOrder(payload, options);\n } catch (error) {\n paypal.checkout.closeFlow();\n\n return Promise.reject(error);\n }\n\n redirectUrl = state.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\n async finalize(options?: PaymentRequestOptions) {\n const state = this.paymentIntegrationService.getState();\n const order = state.getOrder();\n\n if (order && this.isAcknowledgedOrFinalized()) {\n await this.paymentIntegrationService.finalizeOrder(options);\n\n return Promise.resolve();\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private isAcknowledgedOrFinalized(): boolean {\n const state = this.paymentIntegrationService.getState();\n\n return (\n state.getPaymentStatus() === PaymentStatusTypes.ACKNOWLEDGE ||\n state.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 '@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 { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PaypalExpressPaymentStrategy from './paypal-express-payment-strategy';\nimport PaypalExpressScriptLoader from './paypal-express-script-loader';\n\nconst createPaypalExpressPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new PaypalExpressPaymentStrategy(\n paymentIntegrationService,\n new PaypalExpressScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createPaypalExpressPaymentStrategy, [\n { id: 'paypalexpress', type: 'PAYMENT_TYPE_HOSTED' },\n { id: 'paypalexpresscredit', type: 'PAYMENT_TYPE_HOSTED' },\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 { 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 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new Promise(() => {\n this.redirectUrl(redirect_url);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }) as any;\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 { 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 ('errors' in result && 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(methodId, 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(methodId: string, shouldSaveInstrument?: boolean) {\n const { getPaymentMethodOrThrow } = this._paymentIntegrationService.getState();\n const { initializationData } = getPaymentMethodOrThrow(methodId);\n\n const cardTokenizationResult = await this._squareV2PaymentProcessor.tokenize();\n\n if (\n initializationData && 'isSquareV2ApiV2Enabled' in initializationData\n ? !initializationData.isSquareV2ApiV2Enabled\n : !this.shouldVerify()\n ) {\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 { getPaymentMethodOrThrow } = this._paymentIntegrationService.getState();\n const { initializationData } = getPaymentMethodOrThrow(methodId);\n\n const { instrumentId } = paymentData;\n const shouldVerify =\n initializationData && 'isSquareV2ApiV2Enabled' in initializationData\n ? initializationData.isSquareV2ApiV2Enabled\n : this.shouldVerify();\n const verificationToken = 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 PaymentStrategy,\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 allow_redisplay?: 'always' | 'limited' | 'unspecified';\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 allowRedisplayForStoredInstruments?: 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 private _allowRedisplayForStoredInstruments?: 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 allowRedisplayForStoredInstruments,\n },\n } = paymentMethod as StripeV3PaymentMethod;\n\n this._allowRedisplayForStoredInstruments = allowRedisplayForStoredInstruments;\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 const shouldAllowRedisplay = this._allowRedisplayForStoredInstruments;\n\n return this.getStripeJs().createPaymentMethod({\n type: StripePaymentMethodType.CreditCard,\n card,\n billing_details: billingDetails,\n ...(shouldAllowRedisplay ? { allow_redisplay: 'always' } : {}),\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","export const supportedLocales: Record = {\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-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 { merge, 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 PaymentRequestOptions,\n PaymentStrategy,\n RequestError,\n StripeUPEIntent,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n formatStripeLocale,\n isStripePaymentMethodLike,\n STRIPE_UPE_CLIENT_API_VERSION,\n STRIPE_UPE_CLIENT_BETAS,\n StripeAdditionalActionRequired,\n StripeAppearanceOptions,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeElementUpdateOptions,\n StripeEventType,\n StripeFormattedPaymentPayload,\n StripeInitializationData,\n StripeIntegrationService,\n StripeJsVersion,\n StripePaymentMethodType,\n StripeResult,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport isStripeAcceleratedCheckoutCustomer from './is-stripe-accelerated-checkout-customer';\nimport StripeUPEPaymentInitializeOptions, {\n WithStripeUPEPaymentInitializeOptions,\n} from './stripe-upe-initialize-options';\n\nexport default class StripeUPEPaymentStrategy implements PaymentStrategy {\n private _stripeUPEClient?: StripeClient;\n private _stripeElements?: StripeElements;\n private _isStripeElementUpdateEnabled?: boolean;\n private _allowRedisplayForStoredInstruments?: boolean;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n private stripeIntegrationService: StripeIntegrationService,\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.stripeIntegrationService.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.stripeIntegrationService.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 await this.paymentIntegrationService.submitOrder(order, options);\n\n if (isVaultedInstrument(paymentData)) {\n const { instrumentId } = paymentData;\n\n await this._executeWithVaulted(\n payment.methodId,\n instrumentId,\n shouldSetAsDefaultInstrument,\n );\n\n return;\n }\n\n await this._executeWithStripeConfirmation(\n payment.methodId,\n payment.gatewayId,\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.stripeIntegrationService.deinitialize();\n this._stripeElements = undefined;\n this._stripeUPEClient = undefined;\n\n return Promise.resolve();\n }\n\n private async _executeWithStripeConfirmation(\n methodId: string,\n gatewayId?: 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 gatewayId,\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\n if (!isStripePaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { clientToken, initializationData } = paymentMethod;\n const {\n shopperLanguage,\n allowRedisplayForStoredInstruments = false,\n enableLink,\n } = initializationData;\n\n this._allowRedisplayForStoredInstruments = allowRedisplayForStoredInstruments;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._stripeUPEClient = await this._loadStripeJs(initializationData);\n this._isStripeElementUpdateEnabled = typeof initStripeElementUpdateTrigger === 'function';\n\n let appearance: StripeAppearanceOptions | undefined;\n\n if (style) {\n const styles = style;\n\n appearance = {\n variables: this.stripeIntegrationService.mapAppearanceVariables(style),\n rules: {\n '.Input': this.stripeIntegrationService.mapInputAppearanceRules(styles),\n },\n };\n }\n\n this._stripeElements = await this.scriptLoader.getElements(this._stripeUPEClient, {\n clientSecret: clientToken,\n locale: formatStripeLocale(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 link: enableLink ? StripeStringConstants.AUTO : StripeStringConstants.NEVER,\n },\n ...this._getStripeElementTerms(),\n });\n\n this.stripeIntegrationService.mountElement(stripeElement, containerId);\n\n stripeElement.on(StripeElementEvent.READY, () => {\n render();\n });\n\n stripeElement.on(StripeElementEvent.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 gatewayId?: string,\n shouldSaveInstrument = false,\n shouldSetAsDefaultInstrument = false,\n ): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.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, error: stripeError } = 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 if (stripeError || !paymentIntent) {\n const { initializationData } = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n const { sendSecondPaymentRequestOnStripeError } = initializationData || {};\n\n if (sendSecondPaymentRequestOnStripeError) {\n // INFO: even in case when stripe payment confirmation was declined\n // we need to send submitPayment request to update status of checkout session on BE side.\n try {\n const paymentPayloadWithError = merge({}, paymentPayload, {\n paymentData: {\n formattedPayload: {\n client_side_error: true,\n },\n },\n });\n\n await this.paymentIntegrationService.submitPayment(paymentPayloadWithError);\n } catch {\n // INFO: additional action should be ignored for this update status request.\n // will throw Stripe error message to the shopper.\n }\n }\n\n this.stripeIntegrationService.throwStripeError(stripeError);\n }\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n methodId: string,\n additionalActionData: StripeAdditionalActionRequired['data'],\n ): Promise {\n if (!this._stripeUPEClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeIntegrationService.mapStripePaymentData(\n this._stripeElements,\n redirect_url,\n !!this._allowRedisplayForStoredInstruments,\n );\n\n const isPaymentCompleted = await this.stripeIntegrationService.isPaymentCompleted(\n methodId,\n this._stripeUPEClient,\n );\n\n return !isPaymentCompleted\n ? this._stripeUPEClient.confirmPayment(stripePaymentData)\n : this._stripeUPEClient.retrievePaymentIntent(token || '');\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.stripeIntegrationService.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 initializationData: StripeInitializationData,\n ): Promise {\n if (this._stripeUPEClient) {\n return this._stripeUPEClient;\n }\n\n const state = this.paymentIntegrationService.getState();\n\n return this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n StripeJsVersion.V3,\n STRIPE_UPE_CLIENT_BETAS,\n STRIPE_UPE_CLIENT_API_VERSION,\n );\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';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeUPEPaymentStrategy from './stripe-upe-payment-strategy';\n\nconst createStripeUPEPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n\n return new StripeUPEPaymentStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n );\n};\n\nexport default toResolvableModule(createStripeUPEPaymentStrategy, [\n { gateway: 'stripeupe' },\n { gateway: 'stripeupe', id: 'klarna' },\n]);\n","import { StripePaymentEvent } from './stripe';\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 { merge } from 'lodash';\n\nimport {\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 PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n isStripePaymentEvent,\n isStripePaymentMethodLike,\n StripeAdditionalActionRequired,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElements,\n StripeElementType,\n StripeEventType,\n StripeFormattedPaymentPayload,\n StripeInitializationData,\n StripeInstrumentSetupFutureUsage,\n StripeIntegrationService,\n StripePIPaymentMethodOptions,\n StripePIPaymentMethodSavingOptions,\n StripeResult,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeOCSPaymentInitializeOptions, {\n WithStripeOCSPaymentInitializeOptions,\n} from './stripe-ocs-initialize-options';\n\nexport default class StripeOCSPaymentStrategy implements PaymentStrategy {\n private stripeClient?: StripeClient;\n private stripeElements?: StripeElements;\n private selectedMethodId?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n private stripeIntegrationService: StripeIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithStripeOCSPaymentInitializeOptions,\n ): Promise {\n const { stripeocs, methodId, gatewayId } = options;\n\n if (!stripeocs?.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(stripeocs, gatewayId, methodId);\n } catch (error) {\n if (error instanceof Error) {\n stripeocs.onError?.(error);\n }\n }\n\n this.stripeIntegrationService.initCheckoutEventsSubscription(\n gatewayId,\n methodId,\n stripeocs,\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.stripeClient) {\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 { isStoreCreditApplied } = this.paymentIntegrationService\n .getState()\n .getCheckoutOrThrow();\n\n if (isStoreCreditApplied) {\n await this.paymentIntegrationService.applyStoreCredit(isStoreCreditApplied);\n }\n\n await this.stripeIntegrationService.updateStripePaymentIntent(gatewayId, methodId);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n const { clientToken } = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n\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, gatewayId);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n const paymentElement = this.stripeElements?.getElement(StripeElementType.PAYMENT);\n\n paymentElement?.unmount();\n paymentElement?.destroy();\n this.stripeIntegrationService.deinitialize();\n this.stripeElements = undefined;\n this.stripeClient = undefined;\n\n return Promise.resolve();\n }\n\n private async _initializeStripeElement(\n stripe: StripeOCSPaymentInitializeOptions,\n gatewayId: string,\n methodId: string,\n ) {\n let paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n\n if (!paymentMethod?.clientToken) {\n const state = await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n\n paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n }\n\n if (!isStripePaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { clientToken, initializationData } = paymentMethod;\n const { customerSessionToken, enableLink } = initializationData;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.stripeClient = await this._loadStripeJs(initializationData);\n\n const {\n appearance,\n containerId,\n fonts,\n layout,\n render,\n paymentMethodSelect,\n handleClosePaymentMethod,\n togglePreloader,\n } = stripe;\n\n this.stripeElements = await this.scriptLoader.getElements(this.stripeClient, {\n clientSecret: clientToken,\n customerSessionClientSecret: customerSessionToken,\n appearance,\n fonts,\n });\n\n const { getBillingAddress, getShippingAddress } = this.paymentIntegrationService.getState();\n const billingAddress = getBillingAddress();\n const { postalCode } = getShippingAddress() || billingAddress || {};\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 link: enableLink ? StripeStringConstants.AUTO : StripeStringConstants.NEVER,\n },\n layout,\n savePaymentMethod: {\n maxVisiblePaymentMethods: 20,\n },\n defaultValues: {\n billingDetails: {\n email: billingAddress?.email || '',\n },\n },\n });\n\n this.stripeIntegrationService.mountElement(stripeElement, containerId);\n\n stripeElement.on(StripeElementEvent.LOADER_START, () => {\n togglePreloader?.(false);\n });\n\n stripeElement.on(StripeElementEvent.READY, () => {\n render();\n });\n\n stripeElement.on(StripeElementEvent.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 initializationData: StripeInitializationData,\n ): Promise {\n if (this.stripeClient) {\n return this.stripeClient;\n }\n\n const state = this.paymentIntegrationService.getState();\n const stripeJsVersion =\n this.stripeIntegrationService.getStripeJsVersion(initializationData);\n\n return this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n stripeJsVersion,\n );\n }\n\n private _collapseStripeElement() {\n const stripeElement = this.stripeElements?.getElement(StripeElementType.PAYMENT);\n\n stripeElement?.collapse();\n }\n\n private _getPaymentPayload(\n methodId: string,\n token: string,\n paymentMethodOptions?: StripePIPaymentMethodOptions,\n ): Payment {\n const cartId = this.paymentIntegrationService.getState().getCart()?.id || '';\n const { card, us_bank_account } = paymentMethodOptions || {};\n const shouldSaveInstrument =\n this._shouldSaveInstrument(card) || this._shouldSaveInstrument(us_bank_account);\n const tokenizedOptions = this._getTokenizedOptions(token, paymentMethodOptions);\n\n const formattedPayload = {\n cart_id: cartId,\n confirm: false,\n method: this.selectedMethodId,\n vault_payment_instrument: shouldSaveInstrument,\n ...tokenizedOptions,\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 gatewayId: string,\n ): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n if (!this.stripeClient || !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, error: stripeError } = await this._confirmStripePaymentOrThrow(\n methodId,\n additionalActionData,\n );\n const {\n client_secret: paymentIntentClientSecret,\n payment_method_options: paymentMethodOptions,\n } = paymentIntent || {};\n\n const paymentPayload = this._getPaymentPayload(\n methodId,\n paymentIntentClientSecret || token,\n paymentMethodOptions,\n );\n\n if (stripeError || !paymentIntent) {\n const { initializationData } = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n const { sendSecondPaymentRequestOnStripeError } = initializationData || {};\n\n if (sendSecondPaymentRequestOnStripeError) {\n // INFO: even in case when stripe payment confirmation was declined\n // we need to send submitPayment request to update status of checkout session on BE side.\n try {\n const paymentPayloadWithError = merge({}, paymentPayload, {\n paymentData: {\n formattedPayload: {\n client_side_error: true,\n },\n },\n });\n\n await this.paymentIntegrationService.submitPayment(paymentPayloadWithError);\n } catch {\n // INFO: additional action should be ignored for this update status request.\n // will throw Stripe error message to the shopper.\n }\n }\n\n this.stripeIntegrationService.throwStripeError(stripeError);\n }\n\n try {\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n methodId: string,\n additionalActionData: StripeAdditionalActionRequired['data'],\n ): Promise {\n if (!this.stripeClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeIntegrationService.mapStripePaymentData(\n this.stripeElements,\n redirect_url,\n );\n\n const isPaymentCompleted = await this.stripeIntegrationService.isPaymentCompleted(\n methodId,\n this.stripeClient,\n );\n\n return !isPaymentCompleted\n ? this.stripeClient.confirmPayment(stripePaymentData)\n : this.stripeClient.retrievePaymentIntent(token || '');\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 private _shouldSaveInstrument(paymentMethodOptions?: StripePIPaymentMethodSavingOptions) {\n const setupFutureUsage = paymentMethodOptions?.setup_future_usage;\n\n return (\n setupFutureUsage === StripeInstrumentSetupFutureUsage.ON_SESSION ||\n setupFutureUsage === StripeInstrumentSetupFutureUsage.OFF_SESSION\n );\n }\n\n private _getTokenizedOptions(\n token: string,\n paymentMethodOptions?: StripePIPaymentMethodOptions,\n ) {\n if (this._shouldSaveInstrument(paymentMethodOptions?.us_bank_account)) {\n return { tokenized_ach: { token } };\n }\n\n return { credit_card_token: { token } };\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeOCSPaymentStrategy from './stripe-ocs-payment-strategy';\n\nconst createStripeOCSPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n\n return new StripeOCSPaymentStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n );\n};\n\nexport default toResolvableModule(createStripeOCSPaymentStrategy, [\n { gateway: 'stripeocs', id: 'optimized_checkout' },\n]);\n","import { merge } from 'lodash';\n\nimport {\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 PaymentMethod,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n isStripePaymentEvent,\n StripeAdditionalActionRequired,\n StripeCheckoutInstance,\n StripeCheckoutSession,\n StripeCheckoutSessionActionResult,\n StripeCheckoutSessionActions,\n StripeCheckoutSessionPaymentStatus,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElementsCreateOptions,\n StripeEventType,\n StripeFormattedPaymentPayload,\n StripeInitializationData,\n StripeIntegrationService,\n StripeJsVersion,\n StripePaymentMethodType,\n StripeSavedPaymentMethod,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeOCSPaymentInitializeOptions, {\n WithStripeOCSPaymentInitializeOptions,\n} from '../stripe-ocs/stripe-ocs-initialize-options';\n\nexport default class StripeCSPaymentStrategy implements PaymentStrategy {\n private stripeClient?: StripeClient;\n private stripeCheckout?: StripeCheckoutInstance;\n private selectedMethodId?: string;\n\n constructor(\n private readonly paymentIntegrationService: PaymentIntegrationService,\n private readonly scriptLoader: StripeScriptLoader,\n private readonly stripeIntegrationService: StripeIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithStripeOCSPaymentInitializeOptions,\n ): Promise {\n const { stripeocs, methodId, gatewayId } = options;\n\n if (!stripeocs?.containerId || !gatewayId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n let paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n\n if (!paymentMethod?.clientToken) {\n await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n\n paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n }\n\n try {\n await this._initStripeCheckoutSession(stripeocs, paymentMethod);\n await this._updateStripeShopperData();\n this._initializePaymentElement(stripeocs, paymentMethod);\n this._initializeAdaptivePricingElement(stripeocs, paymentMethod);\n } catch (error) {\n if (error instanceof Error) {\n stripeocs.onError?.(error);\n }\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.stripeClient) {\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._updateCheckoutSessionData(gatewayId, methodId);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n const { clientToken } = state.getPaymentMethodOrThrow(methodId, gatewayId);\n const paymentPayload = this._getPaymentPayload(methodId, clientToken || '');\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._processAdditionalAction(error, gatewayId, methodId);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n const paymentElement = this.stripeCheckout?.getPaymentElement();\n const currencySelectorElement = this.stripeCheckout?.getCurrencySelectorElement();\n\n paymentElement?.unmount();\n paymentElement?.destroy();\n currencySelectorElement?.unmount();\n currencySelectorElement?.destroy();\n this.stripeCheckout = undefined;\n this.stripeClient = undefined;\n this.selectedMethodId = undefined;\n\n return Promise.resolve();\n }\n\n private async _initStripeCheckoutSession(\n stripe: StripeOCSPaymentInitializeOptions,\n paymentMethod: PaymentMethod,\n ): Promise {\n const { clientToken, initializationData } = paymentMethod;\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.stripeClient = await this._loadStripeJs(initializationData);\n\n const { appearance, fonts } = stripe;\n\n this.stripeCheckout = await this.scriptLoader.getStripeCheckout(this.stripeClient, {\n clientSecret: clientToken,\n elementsOptions: {\n appearance,\n fonts,\n },\n adaptivePricing: {\n allowed: !!initializationData?.adaptivePricingEnabled,\n },\n });\n }\n\n private _initializePaymentElement(\n stripe: StripeOCSPaymentInitializeOptions,\n paymentMethod: PaymentMethod,\n ) {\n const { initializationData, id: methodId, gateway } = paymentMethod;\n\n const { enableLink } = initializationData || {};\n const {\n containerId,\n layout,\n render,\n paymentMethodSelect,\n handleClosePaymentMethod,\n togglePreloader,\n } = stripe;\n\n const stripeElement = this._getStripeElement({\n fields: {\n billingDetails: {\n email: StripeStringConstants.NEVER,\n name: StripeStringConstants.NEVER,\n address: StripeStringConstants.NEVER,\n },\n },\n wallets: {\n applePay: StripeStringConstants.NEVER,\n googlePay: StripeStringConstants.NEVER,\n link: enableLink ? StripeStringConstants.AUTO : StripeStringConstants.NEVER,\n },\n layout,\n });\n\n if (!stripeElement || !gateway) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this.stripeIntegrationService.mountElement(stripeElement, containerId);\n\n stripeElement.on(StripeElementEvent.LOADER_START, () => {\n togglePreloader?.(false);\n });\n\n stripeElement.on(StripeElementEvent.READY, () => {\n render();\n });\n\n stripeElement.on(StripeElementEvent.CHANGE, (event: StripeEventType) => {\n this._onStripeElementChange(event, gateway, methodId, paymentMethodSelect);\n });\n\n handleClosePaymentMethod?.(this._collapseStripeElement.bind(this));\n }\n\n private async _loadStripeJs(\n initializationData: StripeInitializationData,\n ): Promise {\n if (this.stripeClient) {\n return this.stripeClient;\n }\n\n const state = this.paymentIntegrationService.getState();\n\n return this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n StripeJsVersion.CLOVER,\n );\n }\n\n private async _getStripeActionsOrThrow(): Promise {\n if (!this.stripeCheckout) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { actions, error } = await this.stripeCheckout.loadActions();\n\n if (!actions || error) {\n throw new PaymentMethodFailedError(error?.message);\n }\n\n return actions;\n }\n\n private _getStripeElement(options?: StripeElementsCreateOptions): StripeElement | undefined {\n return (\n this.stripeCheckout?.getPaymentElement() ||\n this.stripeCheckout?.createPaymentElement(options)\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 private _collapseStripeElement() {\n const stripeElement = this.stripeCheckout?.getPaymentElement();\n\n stripeElement?.collapse();\n }\n\n private async _updateCheckoutSessionData(gatewayId: string, methodId: string): Promise {\n await this._updateStripeShopperData();\n\n // INFO: to trigger checkout session data update on the BE side we need to make stripe config request\n await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n }\n\n private _getPaymentPayload(\n methodId: string,\n token: string,\n newVaultedStripeInstrument?: StripeSavedPaymentMethod,\n ): Payment {\n const cartId = this.paymentIntegrationService.getState().getCart()?.id || '';\n const tokenizedOptions = this._getTokenizedOptions(token, newVaultedStripeInstrument);\n\n const formattedPayload = {\n cart_id: cartId,\n confirm: false,\n method: this.selectedMethodId,\n vault_payment_instrument: !!newVaultedStripeInstrument,\n ...tokenizedOptions,\n };\n\n return {\n methodId,\n paymentData: {\n formattedPayload,\n },\n };\n }\n\n private async _processAdditionalAction(\n error: unknown,\n gatewayId: string,\n methodId: string,\n ): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n const { data: additionalActionData } = error.body?.additional_action_required || {};\n const { token } = additionalActionData || {};\n const existingStripeSavedPaymentMethods = await this._getStripeSavedPaymentMethodsOrThrow();\n const { session: stripeCheckoutSession, error: stripeError } =\n await this._confirmStripePayment(additionalActionData);\n const newStripeSavedPaymentMethods = await this._getStripeSavedPaymentMethodsOrThrow(\n stripeCheckoutSession,\n );\n const { id: checkoutSessionId, status: checkoutSessionStatus } =\n stripeCheckoutSession || {};\n const newVaultedStripeInstrument = this._getNewVaultedStripeInstrument(\n existingStripeSavedPaymentMethods,\n newStripeSavedPaymentMethods,\n );\n const paymentPayload = this._getPaymentPayload(\n methodId,\n checkoutSessionId || token,\n newVaultedStripeInstrument,\n );\n const { initializationData } = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId, gatewayId);\n const { sendSecondPaymentRequestOnStripeError } = initializationData || {};\n\n if (stripeError || !stripeCheckoutSession) {\n if (sendSecondPaymentRequestOnStripeError) {\n // INFO: even in case when stripe payment confirmation was declined\n // we need to send submitPayment request to update status of checkout session on BE side.\n try {\n const paymentPayloadWithError = merge({}, paymentPayload, {\n paymentData: {\n formattedPayload: {\n client_side_error: true,\n },\n },\n });\n\n await this.paymentIntegrationService.submitPayment(paymentPayloadWithError);\n } catch {\n // INFO: additional action should be ignored for this update status request.\n // will throw Stripe error message to the shopper.\n }\n }\n\n throw new PaymentMethodFailedError(stripeError?.message);\n }\n\n try {\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n if (checkoutSessionStatus?.paymentStatus === StripeCheckoutSessionPaymentStatus.Paid) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n }\n\n throw error;\n }\n }\n\n private async _confirmStripePayment(\n additionalActionData: StripeAdditionalActionRequired['data'],\n ): Promise {\n const { redirect_url } = additionalActionData || {};\n\n if (!this.stripeCheckout) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const stripeActions = await this._getStripeActionsOrThrow();\n\n return stripeActions.confirm({\n redirect: StripeStringConstants.IF_REQUIRED,\n returnUrl: redirect_url,\n });\n }\n\n private async _updateStripeShopperData(): Promise {\n const stripeActions = await this._getStripeActionsOrThrow();\n\n await this._updateStripeEmail(stripeActions);\n await this._updateStripeShippingAddress(stripeActions);\n await this._updateStripeBillingAddress(stripeActions);\n }\n\n private async _updateStripeEmail(stripeActions: StripeCheckoutSessionActions): Promise {\n const stripeCheckoutSession = await stripeActions.getSession();\n\n if (stripeCheckoutSession.email) {\n return;\n }\n\n const { getBillingAddress } = this.paymentIntegrationService.getState();\n const billingAddress = getBillingAddress();\n\n await stripeActions.updateEmail(billingAddress?.email || '');\n }\n\n private async _updateStripeShippingAddress(\n stripeActions: StripeCheckoutSessionActions,\n ): Promise {\n const shippingAddress = this.paymentIntegrationService.getState().getShippingAddress();\n\n if (!shippingAddress) {\n return;\n }\n\n await stripeActions.updateShippingAddress({\n name: this.stripeIntegrationService.getShopperFullName(shippingAddress),\n address: this.stripeIntegrationService.mapStripeAddress(shippingAddress),\n });\n }\n\n private async _updateStripeBillingAddress(\n stripeActions: StripeCheckoutSessionActions,\n ): Promise {\n const billingAddress = this.paymentIntegrationService.getState().getBillingAddress();\n\n if (!billingAddress) {\n return;\n }\n\n await stripeActions.updateBillingAddress({\n name: this.stripeIntegrationService.getShopperFullName(billingAddress),\n address: this.stripeIntegrationService.mapStripeAddress(billingAddress),\n });\n }\n\n private async _getStripeSavedPaymentMethodsOrThrow(\n stripeCheckoutSession?: StripeCheckoutSession,\n ): Promise {\n if (stripeCheckoutSession?.savedPaymentMethods) {\n return stripeCheckoutSession.savedPaymentMethods;\n }\n\n const stripeActions = await this._getStripeActionsOrThrow();\n const { savedPaymentMethods } = await stripeActions.getSession();\n\n return savedPaymentMethods || [];\n }\n\n private _getNewVaultedStripeInstrument(\n existingStripeSavedPaymentMethods: StripeSavedPaymentMethod[],\n newStripeSavedPaymentMethods: StripeSavedPaymentMethod[],\n ): StripeSavedPaymentMethod | undefined {\n return newStripeSavedPaymentMethods.find(\n (method: StripeSavedPaymentMethod) =>\n !existingStripeSavedPaymentMethods.some(\n (existingMethod: StripeSavedPaymentMethod) => existingMethod.id === method.id,\n ),\n );\n }\n\n private _getTokenizedOptions(\n token: string,\n newVaultedStripeInstrument?: StripeSavedPaymentMethod,\n ) {\n if (newVaultedStripeInstrument?.type === StripePaymentMethodType.ACH) {\n return { tokenized_ach: { token } };\n }\n\n return { credit_card_token: { token } };\n }\n\n private _initializeAdaptivePricingElement(\n stripe: StripeOCSPaymentInitializeOptions,\n paymentMethod: PaymentMethod,\n ): void {\n const { initializationData } = paymentMethod;\n const { currencySelectorContainerId } = stripe;\n\n if (!initializationData?.adaptivePricingEnabled) {\n return;\n }\n\n if (!currencySelectorContainerId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const currencySelectorElement = this._getCurrencySelectorElement();\n\n if (!currencySelectorElement) {\n return;\n }\n\n currencySelectorElement.mount(`#${currencySelectorContainerId}`);\n\n this._initAdaptivePricingEvents(currencySelectorElement);\n }\n\n private _getCurrencySelectorElement(): StripeElement | undefined {\n return (\n this.stripeCheckout?.getCurrencySelectorElement() ||\n this.stripeCheckout?.createCurrencySelectorElement()\n );\n }\n\n private _initAdaptivePricingEvents(currencySelectorElement: StripeElement): void {\n currencySelectorElement.on(StripeElementEvent.CHANGE, async (event: StripeEventType) => {\n if (!event.value || !('currency' in event.value)) {\n return;\n }\n\n const { currency } = this.paymentIntegrationService.getState().getCartOrThrow();\n const currencyCode = currency.code.toLowerCase();\n const stripeCurrencyCode = event.value.currency.toLowerCase();\n\n await this.paymentIntegrationService.updatePaymentProviderCustomer({\n isCustomerCurrencySelected: currencyCode !== stripeCurrencyCode,\n customerCurrency: stripeCurrencyCode,\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';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport StripeCSPaymentStrategy from './stripe-cs-payment-strategy';\n\nconst createStripeCSPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n\n return new StripeCSPaymentStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n );\n};\n\nexport default toResolvableModule(createStripeCSPaymentStrategy, [\n { gateway: 'stripeocs', id: 'checkout_session' },\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';\nimport { isBaseInstrument } from '@bigcommerce/checkout-sdk/utility';\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 findInstrument = instruments?.find(\n (instrument) => isBaseInstrument(instrument) && instrument.bigpayToken === instrumentId,\n );\n const trustedShippingAddress = isBaseInstrument(findInstrument)\n ? findInstrument.trustedShippingAddress\n : {};\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 messageEventListener = async (event: MessageEvent) => {\n if (event.origin.indexOf('cardinalcommerce.com') === -1) {\n return;\n }\n\n if (typeof event.data !== 'string' || !this._isValidJsonWithSessionId(event.data)) {\n return reject(new Error(PAYMENT_CANNOT_CONTINUE));\n }\n\n window.removeEventListener('message', messageEventListener);\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', messageEventListener);\n\n let iframeHidden: HTMLIFrameElement;\n\n try {\n iframeHidden = this._createHiddenIframe(error.body);\n } catch (e) {\n window.removeEventListener('message', messageEventListener);\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 && data.Status) {\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, [\n { gateway: 'worldpayaccess', id: 'credit_card' },\n { id: 'worldpayaccess' },\n]);\n","import {\n isHostedInstrumentLike,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WorldpayAccessRedirectResponse } from './worldpayaccess-payment-options';\n\nexport default class WorldpayAccessOpenBankingPaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute({ payment }: OrderRequestBody): Promise {\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n await this._paymentIntegrationService.submitOrder();\n\n try {\n await this._paymentIntegrationService.submitPayment(\n this._buildOpenBankingSubmitPayment(payment),\n );\n } catch (error) {\n if (this._isWorldpayAccessRedirectResponse(error)) {\n const redirectUrl = error.body.additional_action_required.data.redirect_url;\n\n return new Promise(() => window.location.replace(redirectUrl));\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 _buildOpenBankingSubmitPayment(payment: OrderPaymentRequestBody): Payment {\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = isHostedInstrumentLike(\n payment.paymentData,\n )\n ? payment.paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n return {\n ...payment,\n paymentData: {\n formattedPayload: {\n open_banking: {},\n vault_payment_instrument: shouldSaveInstrument || false,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || false,\n },\n },\n };\n }\n\n private _isWorldpayAccessRedirectResponse(\n response: unknown,\n ): response is WorldpayAccessRedirectResponse {\n if (typeof response !== 'object' || response === null) {\n return false;\n }\n\n const partialResponse = response as Partial;\n\n if (!partialResponse.body) {\n return false;\n }\n\n const partialBody = partialResponse.body as {\n status?: string;\n additional_action_required?: {\n data?: { redirect_url?: string };\n };\n };\n\n return (\n partialBody.status === 'additional_action_required' &&\n !!partialBody.additional_action_required?.data?.redirect_url\n );\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport WorldpayAccessOpenBankingPaymentStrategy from './worldpayaccess-open-banking-payment-strategy';\n\nconst createWorldpayAccessOpenBankingPaymentStrategy: PaymentStrategyFactory<\n WorldpayAccessOpenBankingPaymentStrategy\n> = (paymentIntegrationService) =>\n new WorldpayAccessOpenBankingPaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createWorldpayAccessOpenBankingPaymentStrategy, [\n { id: 'open_banking', gateway: 'worldpayaccess' },\n]);\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 } 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 { 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 { 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 * This error is thrown when at least one cart item changed stock position (e.g. moved to a different warehouse)\n * and the server returns type `cart_stock_positions_changed`.\n */\nexport default class CartStockPositionsChangedError extends StandardError {\n changedItemIds: string[];\n\n constructor(changedItemIds: string[], message?: string) {\n super(\n message ||\n 'At least one item changed stock position. Please review your cart and try again.',\n );\n\n this.name = 'CartStockPositionsChangedError';\n this.type = 'cart_stock_positions_changed';\n this.changedItemIds = changedItemIds;\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 { StandardError } from '../../common/error/errors';\n\nexport default class MissingShippingMethodError extends StandardError {\n constructor(message: string) {\n super(message);\n\n this.name = 'MissingShippingMethodError';\n this.type = 'missing_shipping_method';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport default class InvalidShippingAddressError extends StandardError {\n constructor(message: string) {\n super(message);\n\n this.name = 'InvalidShippingAddressError';\n this.type = 'invalid_shipping_address';\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\nimport { isNil, omitBy } from 'lodash';\n\nimport {\n CartConsistencyError,\n CartStockPositionsChangedError,\n EmptyCartError,\n} from '../cart/errors';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport { MissingShippingMethodError, OrderTaxProviderUnavailableError } from './errors';\nimport InvalidShippingAddressError from './errors/invalid-shipping-address-error';\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 if (error.body.type === 'cart_stock_positions_changed') {\n const changedItemIds =\n (error.body.errors as { changedItemIds?: string[] })?.changedItemIds ?? [];\n\n throw new CartStockPositionsChangedError(changedItemIds);\n }\n\n if (error.body.type === 'missing_shipping_method') {\n throw new MissingShippingMethodError(error.body.detail);\n }\n\n if (error.body.type === 'invalid_shipping_address') {\n throw new InvalidShippingAddressError(error.body.detail);\n }\n\n if (error.body.type === 'empty_cart') {\n throw new EmptyCartError();\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 { 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 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 { 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","// / \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 { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\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';\n\nimport { PaymentMethod } from '.';\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\n observer.next(\n createAction(\n PaymentMethodActionType.LoadPaymentMethodsSucceeded,\n methods,\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","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 { 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","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","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 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 CYBERSOURCEV2_GOOGLE_PAY = 'googlepaycybersourcev2',\n HUMM = 'humm',\n KLARNA = 'klarna',\n KLARNAV2 = 'klarnav2',\n LEGACY = 'legacy',\n MOLLIE = 'mollie',\n MONERIS = 'moneris',\n NO_PAYMENT_DATA_REQUIRED = 'nopaymentdatarequired',\n OFFLINE = 'offline',\n OFFSITE = 'offsite',\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 WORLDPAYACCESS = 'worldpayaccess',\n WORLDPAYACCESS_GOOGLE_PAY = 'googlepayworldpayaccess',\n STRIPE_GOOGLE_PAY = 'googlepaystripe',\n SEZZLE = 'sezzle',\n ZIP = 'zip',\n}\n\nexport default PaymentStrategyType;\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 { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, empty, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport {\n PaymentIntegrationService,\n PaymentStrategy as PaymentStrategyV2,\n} 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 { getDefaultLogger } from '../common/log';\nimport {\n LoadOrderPaymentsAction,\n OrderActionCreator,\n OrderPaymentRequestBody,\n OrderRequestBody,\n} from '../order';\nimport { OrderFinalizationNotRequiredError } from '../order/errors';\nimport { registerIntegrations } from '../payment-integration';\nimport { SpamProtectionAction, SpamProtectionActionCreator } from '../spam-protection';\n\nimport PaymentMethod from './payment-method';\nimport {\n OrderFinalizeOptions,\n PaymentInitializeOptions,\n PaymentRequestOptions,\n} 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 private _paymentIntegrationService: PaymentIntegrationService,\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?: OrderFinalizeOptions,\n ): ThunkAction {\n const { integrations } = options ?? {};\n\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 registerIntegrations(\n this._strategyRegistryV2,\n integrations ?? [],\n this._paymentIntegrationService,\n );\n\n let strategy: PaymentStrategy | PaymentStrategyV2;\n\n try {\n strategy = this._getStrategy(method);\n } catch {\n throw new OrderFinalizationNotRequiredError();\n }\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, integrations } = 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 registerIntegrations(\n this._strategyRegistryV2,\n integrations ?? [],\n this._paymentIntegrationService,\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 try {\n strategy = this._strategyRegistryV2.get({\n id: method.id,\n gateway: method.gateway,\n type: method.type,\n });\n } catch (error) {\n getDefaultLogger().error(\n `[PaymentStrategyActionCreator] Unable to resolve V2 strategy for id: ${method.id}, gateway: ${method.gateway}, type: ${method.type}`,\n );\n throw error;\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 { 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 { 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","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 { 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 { 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 { 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 { 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 _checkoutId?: string,\n private _cardInstrument?: CardInstrument,\n ) {\n this._iframe = document.createElement('iframe');\n\n const src = this._checkoutId\n ? `/checkout/payment/hosted-field?version=${LIBRARY_VERSION}&checkoutId=${this._checkoutId}`\n : `/checkout/payment/hosted-field?version=${LIBRARY_VERSION}`;\n\n this._iframe.src = src;\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 { 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 { 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 let paymentMethod = state.paymentMethods.getPaymentMethod(\n payload.methodId,\n payload.gatewayId,\n );\n\n if (paymentMethod?.gateway === 'worldpayaccess' && paymentMethod?.id === 'credit_card') {\n paymentMethod = { ...paymentMethod, id: 'worldpayaccess', method: 'credit-card' };\n }\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, checkoutId?: string): 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 checkoutId,\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 { 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","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","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","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 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 [],\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","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 PAYPALEXPRESS = \"paypalexpress\"\n}\nexport default CheckoutButtonMethodType;\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","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 }, {});\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 // Worldpay Access: sub-methods carry the provider name in `gateway` and the method\n // name in `id`. BigPay's mapToId uses `id` as the gateway field unless\n // `method === 'multi-option'`, so we align with hosted-form-order-data-transformer\n if (paymentMethod.gateway === 'worldpayaccess') {\n if (paymentMethod.id === 'credit_card') {\n return { ...paymentMethod, id: 'worldpayaccess', method: 'credit-card' };\n }\n\n if (paymentMethod.id === 'open_banking') {\n return { ...paymentMethod, id: 'worldpayaccess', method: 'open_banking' };\n }\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","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","export const ACKNOWLEDGE = 'ACKNOWLEDGE';\nexport const FINALIZE = 'FINALIZE';\nexport const INITIALIZE = 'INITIALIZE';\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 { 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 { 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 { 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 { 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 { 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 { 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","export enum SubStrategyType {\n CARD = 'card_ui',\n NONE = 'none',\n UNSUPPORTED = 'unsupported',\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, checkout } = this._store.getState();\n const { paymentSettings: { bigpayBaseUrl: host = '' } = {} } =\n config.getStoreConfig() || {};\n const checkoutId = checkout.getCheckoutOrThrow().id;\n\n if (!formOptions) {\n throw new InvalidArgumentError();\n }\n\n const form = formOptions && this._hostedFormFactory.create(host, formOptions, checkoutId);\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 { 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 { 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 { 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 { 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 { 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 { 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 { 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 { 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 const consignmentInMemory = store\n .getState()\n .consignments.getConsignmentById(consignment.id);\n\n const alreadySelectedOptionId = consignmentInMemory?.selectedShippingOption?.id;\n\n if (alreadySelectedOptionId === consignment.shippingOptionId) {\n observer.complete();\n\n return;\n }\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 { EmptyCartError } from '../cart/errors';\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.physicalItems.stockPosition',\n 'cart.lineItems.digitalItems.options',\n 'cart.lineItems.digitalItems.stockPosition',\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\n .post(url, {\n body: consignments,\n params: {\n include: joinOrMergeIncludes(DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .put(url, {\n body,\n params: {\n include: joinOrMergeIncludes(DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\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\n .delete(url, { params: { include }, headers, timeout })\n .catch((err) => {\n if (err.body.type === 'empty_cart') {\n throw new EmptyCartError();\n }\n\n throw err;\n });\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 { 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, 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 { 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 { 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 { id } = checkout;\n const checkoutVersion = options?.version ?? checkout.version;\n\n const { body } = await (useStoreCredit\n ? this._storeCreditRequestSender.applyStoreCredit(id, {\n ...options,\n version: checkoutVersion,\n })\n : this._storeCreditRequestSender.removeStoreCredit(id, {\n ...options,\n version: checkoutVersion,\n }));\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, version }: 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 body: { version },\n });\n }\n\n removeStoreCredit(\n checkoutId: string,\n { timeout, version }: 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 body: { version },\n });\n }\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, getLocale: getCartLocale },\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 getCartLocale: clone(getCartLocale),\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 { 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 {\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 CouponActionCreator from '../coupon/coupon-action-creator';\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 _couponActionCreator: CouponActionCreator,\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 const checkoutId = this._storeProjection.getState().getCheckoutOrThrow().id;\n\n return this._hostedFormFactory.create(host, options, checkoutId);\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 applyCoupon(\n coupon: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(this._couponActionCreator.applyCoupon(coupon, options));\n\n return this._storeProjection.getState();\n }\n\n async removeCoupon(\n coupon: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(this._couponActionCreator.removeCoupon(coupon, options));\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, RequestSender } 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 CouponActionCreator from '../coupon/coupon-action-creator';\nimport CouponRequestSender from '../coupon/coupon-request-sender';\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 requestSender?: RequestSender,\n): PaymentIntegrationService {\n const {\n config: { getHost, getLocale },\n } = store.getState();\n\n if (!requestSender) {\n requestSender = createRequestSender({ host: getHost() });\n }\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 applyCouponActionCreator = new CouponActionCreator(\n new CouponRequestSender(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 applyCouponActionCreator,\n spamProtectionActionCreator,\n paymentProviderCustomerActionCreator,\n shippingCountryActionCreator,\n remoteCheckoutActionCreator,\n paymentStrategyWidgetActionCreator,\n );\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 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","export default function isFuture(date: Date): boolean {\n return date.valueOf() > Date.now();\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 { 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 { 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 {\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 { 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","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 { 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","import { isEqual, omit } from 'lodash';\n\nimport {\n BraintreeFastlaneAddress,\n BraintreeFastlaneAuthenticationState,\n BraintreeFastlaneProfileData,\n BraintreeFastlaneStylesOption,\n BraintreeFastlaneVaultedInstrument,\n BraintreeInitializationData,\n BraintreeIntegrationService,\n getFastlaneStyles,\n isBraintreeAcceleratedCheckoutCustomer,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { CookieStorage } 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 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 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\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, fastlane } = options || {};\n const fastlaneOptions = fastlane || braintreefastlane;\n const { onPayPalFastlaneAddressChange } = fastlaneOptions || {};\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 fastlaneOptions?.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 = CookieStorage.get('bc-fastlane-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 CookieStorage.remove('bc-fastlane-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?.authenticationState !==\n 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 PayPalFastlaneAuthenticationState,\n PayPalFastlaneStylesOption,\n PayPalFastlaneUtils,\n PayPalInitializationData,\n PayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-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 _paypalSdkScriptLoader: PayPalSdkScriptLoader,\n private _paypalCommerceFastlaneUtils: PayPalFastlaneUtils,\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, fastlane } = options || {};\n const fastlaneOptions = fastlane || paypalcommercefastlane;\n const { onPayPalFastlaneAddressChange, styles } = fastlaneOptions || {};\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._paypalSdkScriptLoader.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n cart.locale,\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 if (isAuthenticationFlowCanceled) {\n this._paypalCommerceFastlaneUtils.removeStorageSessionId();\n } else {\n this._paypalCommerceFastlaneUtils.updateStorageSessionId(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 {\n PaymentProviderCustomer,\n PayPalConnectCustomer,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isPaypalAcceleratedCheckoutCustomer(\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 { 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 {\n STRIPE_UPE_CLIENT_API_VERSION,\n STRIPE_UPE_CLIENT_BETAS,\n StripeAppearanceOptions,\n StripeClient,\n StripeDisplayName,\n StripeElementEvent,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeEventType,\n StripeFormMode,\n StripeJsVersion,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\n\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 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?: StripeClient;\n private _stripeElements?: StripeElements;\n private sendData?: ReturnType;\n\n constructor(\n private _store: CheckoutStore,\n private _stripeScriptLoader: 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 { initializationData } = 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._stripeScriptLoader.getStripeClient(\n initializationData,\n state.cart.getLocale(),\n StripeJsVersion.V3,\n STRIPE_UPE_CLIENT_BETAS,\n STRIPE_UPE_CLIENT_API_VERSION,\n );\n\n let appearance: StripeAppearanceOptions;\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 = await this._stripeScriptLoader.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: StripeDisplayName.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(StripeElementEvent.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 { 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 { B2BTokenActionCreator } from '../b2b-token';\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 ExtensionMessage,\n ExtensionMessenger,\n ExtensionQueryMap,\n ExtensionRegion,\n WorkerExtensionMessenger,\n} from '../extension';\nimport { FormFieldsActionCreator } from '../form';\nimport { CountryActionCreator } from '../geography';\nimport { OrderActionCreator, OrderRequestBody } from '../order';\nimport {\n OrderFinalizeOptions,\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 CheckoutInitialState from './checkout-initial-state';\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 _b2bTokenActionCreator: B2BTokenActionCreator,\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 private _workerExtensionMessenger: WorkerExtensionMessenger,\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 * Hydrates the checkout service with an initial state.\n *\n * The initial state can contain various checkout data such as cart items,\n * customer information, and other relevant state.\n *\n * ```js\n * const initialState = {\n * // ... initial checkout state data\n * };\n *\n * const state = await service.hydrateInitialState(initialState);\n *\n * console.log(state.data.getCheckout());\n * ```\n *\n * @alpha\n * @param state - The initial state data to hydrate the checkout service with.\n * @returns A promise that resolves to the current state after hydration.\n */\n hydrateInitialState(state: CheckoutInitialState): Promise {\n return this._dispatch(this._checkoutActionCreator.hydrateInitialState(state));\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?: OrderFinalizeOptions): 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 * Retrieves a B2B authentication token for the current customer.\n *\n * The token can be used to authenticate requests to B2B REST and GraphQL\n * endpoints. The customer must be signed in for this method to succeed.\n * The B2B base URL and client ID are read from the checkout settings config.\n *\n * ```js\n * const state = await service.getB2BToken();\n *\n * console.log(state.data.getB2BToken());\n * ```\n *\n * @param options - Options for the request.\n * @returns A promise that resolves to the current state.\n */\n getB2BToken(options?: RequestOptions): Promise {\n const action = this._b2bTokenActionCreator.loadB2BToken(options);\n\n return this._dispatch(action, { queueId: 'b2bToken' });\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(\n container,\n region,\n this._workerExtensionMessenger,\n );\n const state = await this._dispatch(action, { queueId: 'extensions' });\n\n this._extensionEventBroadcaster.listen();\n\n return state;\n }\n\n /**\n * Clear cache for a checkout extension when removing it from UI.\n * This function should be used whenver an extension is removed from the UI.\n *\n * @alpha\n * @param region - The name of an area where the extension should be presented.\n */\n clearExtensionCache(region: ExtensionRegion): void {\n this._extensionMessenger.clearCacheByRegion(region);\n }\n\n /**\n * Posts a message to a checkout extension.\n *\n * @alpha\n * @param extensionId - The ID of an extension to post the event to.\n * @param message - The message to post to an extension.\n */\n postMessageToExtension(extensionId: string, message: ExtensionMessage): void {\n this._extensionMessenger.post(extensionId, message);\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]) => Promise | void,\n ): () => void {\n return this._extensionMessenger.listenForCommand(extensionId, command, handler);\n }\n\n /**\n * Manages the query handler for an extension.\n *\n * @alpha\n * @param extensionId - The ID of the extension sending the query.\n * @param query - The query to be handled.\n * @param handler - The handler function for the extension query.\n * @returns A function that, when called, will deregister the query handler.\n */\n handleExtensionQuery(\n extensionId: string,\n query: T,\n handler: (command: ExtensionQueryMap[T]) => Promise | void,\n ): () => void {\n return this._extensionMessenger.listenForQuery(extensionId, query, 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","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","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 * 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","export interface B2BToken {\n token: string;\n}\n\nexport default interface B2BTokenState {\n data?: B2BToken;\n errors: B2BTokenErrorsState;\n statuses: B2BTokenStatusesState;\n}\n\nexport interface B2BTokenErrorsState {\n loadError?: Error;\n}\n\nexport interface B2BTokenStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: B2BTokenState = {\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';\n\nimport { B2BTokenActionType, LoadB2BTokenAction } from './b2b-token-actions';\nimport B2BTokenState, {\n B2BToken,\n B2BTokenErrorsState,\n B2BTokenStatusesState,\n DEFAULT_STATE,\n} from './b2b-token-state';\n\nexport default function b2bTokenReducer(\n state: B2BTokenState = DEFAULT_STATE,\n action: Action,\n): B2BTokenState {\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: B2BToken | undefined, action: LoadB2BTokenAction): B2BToken | undefined {\n switch (action.type) {\n case B2BTokenActionType.LoadB2BTokenSucceeded:\n return action.payload;\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: B2BTokenErrorsState = DEFAULT_STATE.errors,\n action: LoadB2BTokenAction,\n): B2BTokenErrorsState {\n switch (action.type) {\n case B2BTokenActionType.LoadB2BTokenRequested:\n case B2BTokenActionType.LoadB2BTokenSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case B2BTokenActionType.LoadB2BTokenFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: B2BTokenStatusesState = DEFAULT_STATE.statuses,\n action: LoadB2BTokenAction,\n): B2BTokenStatusesState {\n switch (action.type) {\n case B2BTokenActionType.LoadB2BTokenRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case B2BTokenActionType.LoadB2BTokenFailed:\n case B2BTokenActionType.LoadB2BTokenSucceeded:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\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 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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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 | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return replace(data, action.payload?.checkout?.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, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { BillingAddressAction, BillingAddressActionType } from '../billing';\nimport {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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 | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return objectMerge(data, action.payload?.checkout?.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 { 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 { 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 { CheckoutHydrateAction, CheckoutHydrateActionType } from '../checkout';\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(\n data: Config | undefined,\n action: LoadConfigAction | CheckoutHydrateAction,\n): Config | undefined {\n switch (action.type) {\n case ConfigActionType.LoadConfigSucceeded:\n return objectMerge(data, action.payload);\n\n case CheckoutHydrateActionType.HydrateInitialState: {\n const merged = objectMerge(data, action.payload?.config);\n\n // b2bApiSettings is a top-level field in CheckoutInitialState (separate from config),\n // so it must be merged into storeConfig manually after the config hydration.\n // Skip if config data is absent or this is a non-B2B store (no b2bApiSettings).\n if (!merged || !action.payload?.b2bApiSettings) {\n return merged;\n }\n\n return {\n ...merged,\n storeConfig: {\n ...merged.storeConfig,\n b2bApiSettings: action.payload.b2bApiSettings,\n },\n };\n }\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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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 | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return arrayReplace(data, action.payload?.checkout?.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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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:\n | CheckoutAction\n | GiftCertificateAction\n | ConsignmentAction\n | CouponAction\n | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return arrayReplace(data, action.payload?.checkout?.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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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 | CheckoutHydrateAction;\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 case CheckoutHydrateActionType.HydrateInitialState:\n return objectMerge(data, action.payload?.checkout?.customer);\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 {\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} from '../checkout/checkout-hydrate-actions';\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 | CheckoutHydrateAction,\n): Extension[] | undefined {\n if (action.type === ExtensionActionType.LoadExtensionsSucceeded) {\n return arrayReplace(data, action.payload);\n }\n\n if (action.type === CheckoutHydrateActionType.HydrateInitialState) {\n return arrayReplace(data, action.payload?.extensions);\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 { ExtraFields } from './extra-field';\nimport { FormFields } from './form-field';\n\nexport default interface FormFieldsState {\n data?: FormFields;\n extraFields?: ExtraFields;\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 { CheckoutHydrateAction, CheckoutHydrateActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { ExtraFields } from './extra-field';\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 extraFields: extraFieldsReducer,\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 | CheckoutHydrateAction,\n): FormFields | undefined {\n switch (action.type) {\n case FormFieldsActionType.LoadFormFieldsSucceeded:\n return objectMerge(data, action.payload);\n\n case CheckoutHydrateActionType.HydrateInitialState:\n return objectMerge(data, action.payload?.formFields);\n\n default:\n return data;\n }\n}\n\nfunction extraFieldsReducer(\n extraFields: ExtraFields | undefined,\n action: CheckoutHydrateAction,\n): ExtraFields | undefined {\n switch (action.type) {\n case CheckoutHydrateActionType.HydrateInitialState:\n return action.payload?.extraFields ?? extraFields;\n\n default:\n return extraFields;\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 {\n CheckoutAction,\n CheckoutActionType,\n CheckoutHydrateAction,\n CheckoutHydrateActionType,\n} 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:\n | ConsignmentAction\n | CheckoutAction\n | CouponAction\n | CustomerAction\n | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return arrayReplace(data, action.payload?.checkout?.consignments);\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 { CheckoutHydrateAction, CheckoutHydrateActionType } from './checkout-hydrate-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 | CheckoutHydrateAction,\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 case CheckoutHydrateActionType.HydrateInitialState:\n return objectMerge(\n data,\n omit(action.payload?.checkout, [\n 'billingAddress',\n 'cart',\n 'consignments',\n 'customer',\n 'coupons',\n 'giftCertificates',\n ]),\n ) as CheckoutDataState;\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\ntype FunctionProperties = {\n [K in keyof T]: T[K] extends (...args: unknown[]) => unknown ? T[K] : never;\n};\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<{ [key: string]: T }>((result, key) => {\n result[key] = createFreezeProxy(map[key]);\n\n return result;\n }, {}) 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 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 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 'worldpayaccess.credit_card': {\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 bigcommerce_payments_creditcards: {\n provider: 'bigcommerce_payments',\n method: 'credit_card',\n },\n bigcommerce_payments: {\n provider: 'bigcommerce_payments',\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 { createB2BTokenSelectorFactory } from '../b2b-token';\nimport { 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 createB2BTokenSelector = createB2BTokenSelectorFactory();\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 b2bToken = createB2BTokenSelector(state.b2bToken);\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 b2bToken,\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 { createSelector } from '../common/selector';\n\nimport B2BTokenState, { DEFAULT_STATE } from './b2b-token-state';\n\nexport default interface B2BTokenSelector {\n getToken(): string | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type B2BTokenSelectorFactory = (state: B2BTokenState) => B2BTokenSelector;\n\nexport function createB2BTokenSelectorFactory(): B2BTokenSelectorFactory {\n const getToken = createSelector(\n (state: B2BTokenState) => state.data?.token,\n (token) => () => token,\n );\n\n const getLoadError = createSelector(\n (state: B2BTokenState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: B2BTokenState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: B2BTokenState = DEFAULT_STATE): B2BTokenSelector => {\n return {\n getToken: getToken(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';\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 { 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 getLocale(): string | undefined;\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 const getLocale = createSelector(\n (state: CartState) => state.data?.locale,\n (data) => () => data,\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 getLocale: getLocale(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 { 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 = { customerAccount: [], shippingAddress: [], billingAddress: [] }) =>\n () =>\n data\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 { 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 { 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';\nimport mapExtraFieldToFormField from './map-extra-field-to-form-field';\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 getAddressExtraFields(): 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 getAddressExtraFields = createSelector(\n (state: FormFieldsState) => state.extraFields,\n (extraFields) => () => {\n if (!extraFields || !extraFields.address.length) {\n return [];\n }\n\n return extraFields.address.map(mapExtraFieldToFormField);\n },\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 getAddressExtraFields: getAddressExtraFields(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 { 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';\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 [],\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 { 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 { 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 { 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 { 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 initialStoreState: Partial = {},\n options?: CheckoutStoreOptions,\n): CheckoutStore {\n const actionTransformer = createActionTransformer(createRequestErrorFactory());\n const createInternalCheckoutSelectors = createInternalCheckoutSelectorsFactory();\n const stateTransformer = (state: CheckoutStoreState) => createInternalCheckoutSelectors(state);\n const reducer = createCheckoutStoreReducer();\n\n return createDataStore(reducer, initialStoreState, {\n actionTransformer,\n stateTransformer,\n ...options,\n });\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 { 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, combineReducers, Reducer } from '@bigcommerce/data-store';\n\nimport { b2bTokenReducer } from '../b2b-token';\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 b2bToken: b2bTokenReducer,\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, RequestSender } from '@bigcommerce/request-sender';\nimport { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport { B2BTokenActionCreator, B2BTokenRequestSender } from '../b2b-token';\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { createDataStoreProjection } from '../common/data-store';\nimport { ErrorActionCreator, ErrorLogger } from '../common/error';\nimport { ExperimentAwareRequestSender } from '../common/http-request';\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 WorkerExtensionMessenger,\n} from '../extension';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport * as customerStrategyFactories from '../generated/customer-strategies';\nimport * as paymentStrategyFactories 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 experimentRequestSender = new ExperimentAwareRequestSender(requestSender, {\n getBasePath: () => store.getState().config.getStoreConfig()?.links.baseUrl ?? undefined,\n getFeatures: () =>\n store.getState().config.getStoreConfig()?.checkoutSettings?.features ?? {},\n }) as unknown as RequestSender;\n const paymentClient = createPaymentClient(store);\n const orderRequestSender = new OrderRequestSender(experimentRequestSender);\n const checkoutRequestSender = new CheckoutRequestSender(experimentRequestSender);\n const configActionCreator = new ConfigActionCreator(new ConfigRequestSender(requestSender));\n const spamProtection = createSpamProtection(createScriptLoader());\n const spamProtectionRequestSender = new SpamProtectionRequestSender(experimentRequestSender);\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(experimentRequestSender),\n );\n const formFieldsActionCreator = new FormFieldsActionCreator(\n new FormFieldsRequestSender(experimentRequestSender),\n );\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n configActionCreator,\n formFieldsActionCreator,\n );\n const paymentIntegrationService = createPaymentIntegrationService(\n store,\n experimentRequestSender,\n );\n\n // NO_PAYMENT_DATA_REQUIRED must always be available regardless of build mode — it handles\n // free orders / full store credit checkouts and cannot be lazily loaded via integrations.\n const essentialPaymentStrategyFactories = {\n createNoPaymentStrategy: paymentStrategyFactories.createNoPaymentStrategy,\n };\n const registryV2 = createPaymentStrategyRegistryV2(\n paymentIntegrationService,\n process.env.ESSENTIAL_BUILD ? essentialPaymentStrategyFactories : paymentStrategyFactories,\n { useFallback: true },\n );\n const customerRegistryV2 = createCustomerStrategyRegistryV2(\n paymentIntegrationService,\n process.env.ESSENTIAL_BUILD ? {} : customerStrategyFactories,\n );\n const extensionActionCreator = new ExtensionActionCreator(\n new ExtensionRequestSender(experimentRequestSender),\n );\n const workerExtensionMessenger = new WorkerExtensionMessenger();\n const extensionMessenger = new ExtensionMessenger(store, workerExtensionMessenger);\n const storeProjection = createDataStoreProjection(store, createCheckoutSelectorsFactory());\n\n return new CheckoutService(\n store,\n storeProjection,\n extensionMessenger,\n createExtensionEventBroadcaster(storeProjection, extensionMessenger),\n new B2BTokenActionCreator(new B2BTokenRequestSender(requestSender)),\n new BillingAddressActionCreator(\n new BillingAddressRequestSender(experimentRequestSender),\n subscriptionsActionCreator,\n ),\n checkoutActionCreator,\n configActionCreator,\n new CustomerActionCreator(\n new CustomerRequestSender(experimentRequestSender),\n checkoutActionCreator,\n spamProtectionActionCreator,\n ),\n new ConsignmentActionCreator(\n new ConsignmentRequestSender(experimentRequestSender),\n checkoutRequestSender,\n ),\n new CountryActionCreator(new CountryRequestSender(experimentRequestSender, { locale })),\n new CouponActionCreator(new CouponRequestSender(experimentRequestSender)),\n new CustomerStrategyActionCreator(\n createCustomerStrategyRegistry(store, experimentRequestSender),\n customerRegistryV2,\n paymentIntegrationService,\n ),\n new ErrorActionCreator(),\n new GiftCertificateActionCreator(new GiftCertificateRequestSender(experimentRequestSender)),\n new InstrumentActionCreator(\n new InstrumentRequestSender(paymentClient, experimentRequestSender),\n ),\n orderActionCreator,\n new PaymentMethodActionCreator(new PaymentMethodRequestSender(experimentRequestSender)),\n new PaymentStrategyActionCreator(\n createPaymentStrategyRegistry(store, paymentClient, experimentRequestSender),\n registryV2,\n orderActionCreator,\n spamProtectionActionCreator,\n paymentIntegrationService,\n ),\n new PickupOptionActionCreator(new PickupOptionRequestSender(experimentRequestSender)),\n new ShippingCountryActionCreator(\n new ShippingCountryRequestSender(experimentRequestSender, { locale }),\n store,\n ),\n new ShippingStrategyActionCreator(\n createShippingStrategyRegistry(store, experimentRequestSender),\n ),\n new SignInEmailActionCreator(new SignInEmailRequestSender(experimentRequestSender)),\n spamProtectionActionCreator,\n new StoreCreditActionCreator(new StoreCreditRequestSender(experimentRequestSender)),\n subscriptionsActionCreator,\n formFieldsActionCreator,\n extensionActionCreator,\n workerExtensionMessenger,\n );\n}\n\nexport interface CheckoutServiceOptions {\n locale?: string;\n host?: string;\n shouldWarnMutation?: boolean;\n externalSource?: string;\n errorLogger?: ErrorLogger;\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';\n\nexport interface PaymentStrategyFactories {\n [key: string]: PaymentStrategyFactory;\n}\n\nexport default function createPaymentStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n paymentStrategyFactories: PaymentStrategyFactories,\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 {\n CustomerStrategy,\n CustomerStrategyFactory,\n CustomerStrategyResolveId,\n isResolvableModule,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\n\nexport interface CustomerStrategyFactories {\n [key: string]: CustomerStrategyFactory;\n}\n\nexport default function createCustomerStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n customerStrategyFactories: CustomerStrategyFactories,\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 {\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 { 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 B2B authentication token for the current customer.\n *\n * @returns The B2B token string if it has been loaded, otherwise undefined.\n */\n getB2BToken(): string | 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 address extra fields.\n *\n * @returns The list of extra fields if available, otherwise an empty array.\n */\n getAddressExtraFields(): 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 getB2BToken = createSelector(\n ({ b2bToken }: InternalCheckoutSelectors) => b2bToken.getToken,\n (getToken) => clone(getToken),\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 getAddressExtraFields = createSelector(\n ({ form }: InternalCheckoutSelectors) => form.getAddressExtraFields,\n (getAddressExtraFields) => clone(getAddressExtraFields),\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 getB2BToken: getB2BToken(state),\n getInstruments: getInstruments(state),\n getCustomerAccountFields: getCustomerAccountFields(state),\n getBillingAddressFields: getBillingAddressFields(state),\n getShippingAddressFields: getShippingAddressFields(state),\n getAddressExtraFields: getAddressExtraFields(state),\n getPickupOptions: getPickupOptions(state),\n getUserExperienceSettings: getUserExperienceSettings(state),\n getPaymentProviderCustomer: getPaymentProviderCustomer(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport {\n CartChangedError,\n CartConsistencyError,\n CartStockPositionsChangedError,\n} 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():\n | Error\n | CartChangedError\n | CartConsistencyError\n | CartStockPositionsChangedError\n | 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 load the B2B token.\n *\n * @returns The error object if unable to load the B2B token, otherwise undefined.\n */\n getLoadB2BTokenError(): 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 getLoadB2BTokenError: state.b2bToken.getLoadError,\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 a B2B token is being loaded.\n *\n * @returns True if a B2B token is being loaded, otherwise false.\n */\n isLoadingB2BToken(): 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 isLoadingB2BToken: state.b2bToken.isLoading,\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 { 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 { 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 {\n createSpamProtection,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\n\nimport CustomerActionCreator from './customer-action-creator';\nimport CustomerRequestSender from './customer-request-sender';\nimport { CustomerStrategy } from './strategies';\nimport { DefaultCustomerStrategy } from './strategies/default';\n\nexport default function createCustomerStrategyRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\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 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 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 } from '@bigcommerce/script-loader';\n\nimport { CheckoutRequestSender, CheckoutStore, CheckoutValidator } from '../checkout';\nimport { BrowserStorage } from '../common/storage';\nimport { HostedFormFactory } from '../hosted-form';\nimport { OrderActionCreator, OrderRequestSender } from '../order';\nimport { createSpamProtection, PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport PaymentActionCreator from './payment-action-creator';\nimport PaymentRequestSender from './payment-request-sender';\nimport PaymentRequestTransformer from './payment-request-transformer';\nimport PaymentStrategyRegistry from './payment-strategy-registry';\nimport PaymentStrategyType from './payment-strategy-type';\nimport { ConvergePaymentStrategy } from './strategies/converge';\nimport {\n createStepHandler,\n createSubStrategyRegistry,\n PaymentResumer,\n PPSDKStrategy,\n} from './strategies/ppsdk';\n\nexport default function createPaymentStrategyRegistry(\n store: CheckoutStore,\n paymentClient: any,\n requestSender: RequestSender,\n) {\n const registry = new PaymentStrategyRegistry({\n defaultToken: PaymentStrategyType.CREDIT_CARD,\n });\n\n const paymentRequestTransformer = new PaymentRequestTransformer();\n const paymentRequestSender = new PaymentRequestSender(paymentClient);\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const checkoutValidator = new CheckoutValidator(checkoutRequestSender);\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 formPoster = createFormPoster();\n const stepHandler = createStepHandler(formPoster, paymentHumanVerificationHandler);\n const hostedFormFactory = new HostedFormFactory(store);\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.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 return registry;\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';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { createAmazonPayV2PaymentProcessor } from '@bigcommerce/checkout-sdk/amazon-pay-utils';\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n createPayPalFastlaneUtils,\n createPayPalSdkScriptLoader,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { createPaymentIntegrationService } from '../payment-integration';\nimport { PaymentProviderCustomerActionCreator } from '../payment-provider-customer';\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 paymentIntegrationService = createPaymentIntegrationService(store);\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 const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\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(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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 createPayPalSdkScriptLoader(),\n createPayPalFastlaneUtils(),\n ),\n );\n\n registry.register(\n 'default',\n () => new DefaultShippingStrategy(store, consignmentActionCreator),\n );\n\n return registry;\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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory 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 getButtonStyle = (buttonStyle?: ButtonStyleOption): string => {\n switch (buttonStyle) {\n case ButtonStyleOption.White:\n return 'white';\n\n case ButtonStyleOption.WhiteBorder:\n return 'white-outline';\n\n case ButtonStyleOption.Black:\n default:\n return 'black';\n }\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 private _applePayScriptLoader: ApplePayScriptLoader,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithApplePayButtonInitializeOptions,\n ): Promise {\n const { methodId, containerId, applepay } = options;\n\n if (!methodId || !applepay) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n await this._applePayScriptLoader.loadSdk();\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 (\n this._paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE &&\n this._paymentMethod.clientToken\n ) {\n this._braintreeSdk.initialize(this._paymentMethod.clientToken);\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 applePayButton = this._createApplePayButtonElement(styleOption);\n\n container.appendChild(applePayButton);\n\n return applePayButton;\n }\n\n private _createApplePayButtonElement(styleOption?: ButtonStyleOption): HTMLElement {\n const applePayButton = document.createElement('apple-pay-button');\n\n applePayButton.setAttribute('buttonstyle', getButtonStyle(styleOption));\n applePayButton.setAttribute('type', 'plain');\n applePayButton.setAttribute(\n 'style',\n '--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;',\n );\n\n return applePayButton;\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\n const state = this._paymentIntegrationService.getState();\n const { shouldExecuteSpamCheck } = state.getCheckoutOrThrow();\n\n if (shouldExecuteSpamCheck) {\n await this._paymentIntegrationService.verifyCheckoutSpamProtection();\n }\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","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeScriptLoader,\n BraintreeSdk,\n BraintreeSDKVersionManager,\n} 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 ApplePayScriptLoader from './apple-pay-script-loader';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayButtonStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n\n return new ApplePayButtonStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), window, braintreeSDKVersionManager),\n ),\n new ApplePayScriptLoader(new ScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createApplePayButtonStrategy, [{ id: 'applepay' }]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n BigCommercePaymentsInitializationData,\n PayPalBuyNowInitializeOptions,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsButtonInitializeOptions, {\n WithBigCommercePaymentsButtonInitializeOptions,\n} from './bigcommerce-payments-button-initialize-options';\n\nexport default class BigCommercePaymentsButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithBigCommercePaymentsButtonInitializeOptions,\n ): Promise {\n const { bigcommerce_payments, containerId, methodId } = options;\n\n const isBuyNowFlow = Boolean(bigcommerce_payments?.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 (!bigcommerce_payments) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !bigcommerce_payments.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof bigcommerce_payments.buyNowInitializeOptions?.getBuyNowCartRequestBody !==\n 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments.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 ? bigcommerce_payments.currencyCode\n : this.paymentIntegrationService.getState().getCartOrThrow().currency.code;\n\n await this.bigCommercePaymentsIntegrationService.loadPayPalSdk(\n methodId,\n currencyCode,\n false,\n );\n\n this.renderButton(containerId, methodId, bigcommerce_payments, isBuyNowFlow);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n bigcommerce_payments: BigCommercePaymentsButtonInitializeOptions,\n isBuyNowFlow?: boolean,\n ): void {\n const { buyNowInitializeOptions, style, onComplete, onEligibilityFailure } =\n bigcommerce_payments;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, isAppSwitchEnabled } =\n paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n ...(!isBuyNowFlow &&\n this.isPaypalCommerceAppSwitchEnabled(methodId) && {\n appSwitchWhenAvailable: true,\n }),\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder('bigcommerce_payments'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const hostedCheckoutCallbacks = {\n ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n }),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const buttonRenderOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n if (paypalButton.hasReturned?.() && this.isPaypalCommerceAppSwitchEnabled(methodId)) {\n paypalButton.resume?.();\n } else {\n paypalButton.render(`#${containerId}`);\n }\n } else if (onEligibilityFailure && typeof onEligibilityFailure === 'function') {\n onEligibilityFailure();\n } else {\n this.bigCommercePaymentsIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart =\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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 =\n this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n } catch (error) {\n if (typeof error === 'string') {\n throw new Error(error);\n }\n\n throw error;\n }\n }\n\n /**\n *\n * PayPal AppSwitch enabling handling\n *\n */\n private isPaypalCommerceAppSwitchEnabled(methodId: string): boolean {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n return paymentMethod.initializationData?.isAppSwitchEnabled ?? false;\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsButtonStrategy from './bigcommerce-payments-button-strategy';\n\nconst createBigCommercePaymentsButtonStrategy: CheckoutButtonStrategyFactory<\n BigCommercePaymentsButtonStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsButtonStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsButtonStrategy, [\n { id: 'bigcommerce_payments' },\n]);\n","import { BigCommercePaymentsInitializationData } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\nimport {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n PayPalBuyNowInitializeOptions,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsPayLaterButtonInitializeOptions, {\n WithBigCommercePaymentsPayLaterButtonInitializeOptions,\n} from './bigcommerce-payments-paylater-button-initialize-options';\n\nexport default class BigCommercePaymentsPayLaterButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions &\n WithBigCommercePaymentsPayLaterButtonInitializeOptions,\n ): Promise {\n const { bigcommerce_payments_paylater, containerId, methodId } = options;\n const { buyNowInitializeOptions, currencyCode: providedCurrencyCode } =\n bigcommerce_payments_paylater || {};\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 (!bigcommerce_payments_paylater) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_paylater\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_paylater.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.bigcommerce_payments_paylater.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.bigCommercePaymentsIntegrationService.loadPayPalSdk(\n methodId,\n currencyCode,\n false,\n );\n\n this.renderButton(containerId, methodId, bigcommerce_payments_paylater);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n bigcommerce_payments_paylater: BigCommercePaymentsPayLaterButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style, onComplete, onEligibilityFailure } =\n bigcommerce_payments_paylater;\n\n const bigCommercePaymentsSdk =\n this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_paylater',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.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 = [\n bigCommercePaymentsSdk.FUNDING.PAYLATER,\n bigCommercePaymentsSdk.FUNDING.CREDIT,\n ];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (!hasRenderedSmartButton) {\n const buttonRenderOptions: BigCommercePaymentsButtonsOptions = {\n fundingSource,\n style: this.bigCommercePaymentsIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = bigCommercePaymentsSdk.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.bigCommercePaymentsIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart =\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.bigCommercePaymentsIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.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 =\n this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.bigCommercePaymentsIntegrationService.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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsPayLaterButtonStrategy from './bigcommerce-payments-paylater-button-strategy';\n\nconst createBigCommercePaymentsPayLaterButtonStrategy: CheckoutButtonStrategyFactory<\n BigCommercePaymentsPayLaterButtonStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsPayLaterButtonStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsPayLaterButtonStrategy, [\n { id: 'bigcommerce_payments_paylater' },\n]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BigCommercePaymentsIntegrationService from '../bigcommerce-payments-integration-service';\nimport {\n ApproveCallbackPayload,\n BigCommercePaymentsButtonsOptions,\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n StyleButtonColor,\n} from '../bigcommerce-payments-types';\n\nimport BigCommercePaymentsVenmoButtonInitializeOptions, {\n WithBigCommercePaymentsVenmoButtonInitializeOptions,\n} from './bigcommerce-payments-venmo-button-initialize-options';\n\nexport default class BigCommercePaymentsVenmoButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private bigCommercePaymentsIntegrationService: BigCommercePaymentsIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions &\n WithBigCommercePaymentsVenmoButtonInitializeOptions,\n ): Promise {\n const { bigcommerce_payments_venmo, containerId, methodId } = options;\n const { buyNowInitializeOptions, currencyCode: providedCurrencyCode } =\n bigcommerce_payments_venmo || {};\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 (!bigcommerce_payments_venmo) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_venmo\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bigcommerce_payments_venmo.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.bigcommerce_payments_venmo.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.bigCommercePaymentsIntegrationService.loadPayPalSdk(\n methodId,\n currencyCode,\n false,\n );\n\n this.renderButton(containerId, methodId, bigcommerce_payments_venmo);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n bigcommerce_payments_venmo: BigCommercePaymentsVenmoButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style, onEligibilityFailure } = bigcommerce_payments_venmo;\n\n const paypalSdk = this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();\n const fundingSource = paypalSdk.FUNDING.VENMO;\n\n const defaultCallbacks = {\n createOrder: () =>\n this.bigCommercePaymentsIntegrationService.createOrder(\n 'bigcommerce_payments_venmo',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.bigCommercePaymentsIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const buttonRenderOptions: BigCommercePaymentsButtonsOptions = {\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.bigCommercePaymentsIntegrationService.removeElement(containerId);\n }\n }\n\n private getValidVenmoButtonStyles(style: PayPalButtonStyleOptions | undefined) {\n const validButtonStyle =\n this.bigCommercePaymentsIntegrationService.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 =\n await this.bigCommercePaymentsIntegrationService.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 createBigCommercePaymentsIntegrationService from '../create-bigcommerce-payments-integration-service';\n\nimport BigCommercePaymentsVenmoButtonStrategy from './bigcommerce-payments-venmo-button-strategy';\n\nconst createBigCommercePaymentsVenmoButtonStrategy: CheckoutButtonStrategyFactory<\n BigCommercePaymentsVenmoButtonStrategy\n> = (paymentIntegrationService) =>\n new BigCommercePaymentsVenmoButtonStrategy(\n paymentIntegrationService,\n createBigCommercePaymentsIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createBigCommercePaymentsVenmoButtonStrategy, [\n { id: 'bigcommerce_payments_venmo' },\n]);\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 { isNil, omitBy } from 'lodash';\n\nimport { PaypalStyleOptions } from '@bigcommerce/checkout-sdk/braintree-utils';\n\nexport default function getValidButtonStyle(style?: PaypalStyleOptions): PaypalStyleOptions {\n const { color, fundingicons, height = 40, 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 | string): number {\n const minHeight = 25;\n const defaultHeight = 40;\n const maxHeight = 55;\n\n const currentHeight = Number(height);\n\n if (!currentHeight || Number.isNaN(currentHeight)) {\n return defaultHeight;\n }\n\n if (currentHeight > maxHeight) {\n return maxHeight;\n }\n\n if (currentHeight < minHeight) {\n return minHeight;\n }\n\n return currentHeight;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n BraintreeError,\n BraintreeHostWindow,\n BraintreeInitializationData,\n BraintreeIntegrationService,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n isBraintreeError,\n PaypalAuthorizeData,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n BuyNowCartCreationError,\n BuyNowCartRequestBody,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport getValidButtonStyle from '../get-valid-button-style';\nimport mapToBraintreeShippingAddressOverride from '../map-to-braintree-shipping-address-override';\n\nimport BraintreePaypalButtonInitializeOptions, {\n WithBraintreePaypalButtonInitializeOptions,\n} from './braintree-paypal-button-initialize-options';\n\nexport default class BraintreePaypalButtonStrategy implements CheckoutButtonStrategy {\n private buyNowCartId: string | undefined;\n\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: CheckoutButtonInitializeOptions & WithBraintreePaypalButtonInitializeOptions,\n ): Promise {\n const { braintreepaypal, 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 (!braintreepaypal) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal\" argument is not provided.`,\n );\n }\n\n let state = this.paymentIntegrationService.getState();\n let currencyCode: string;\n\n if (braintreepaypal.buyNowInitializeOptions) {\n if (!braintreepaypal.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypalcredit.currencyCode\" argument is not provided.`,\n );\n }\n\n currencyCode = braintreepaypal.currencyCode;\n } else {\n await this.paymentIntegrationService.loadDefaultCheckout();\n\n state = this.paymentIntegrationService.getState();\n currencyCode = state.getCartOrThrow().currency.code;\n }\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { clientToken, config, 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 commit: false,\n };\n\n const paypalCheckoutSuccessCallback = (\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n this.renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypal,\n containerId,\n methodId,\n !!config.testMode,\n );\n };\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this.handleError(error, containerId, braintreepaypal.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 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.braintreeHostWindow;\n\n if (paypal) {\n const paypalButtonRender = paypal.Buttons({\n env: testMode ? 'sandbox' : 'production',\n fundingSource: paypal.FUNDING.PAYPAL,\n style: getValidButtonStyle(style),\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.braintreeIntegrationService.removeElement(containerId);\n }\n }\n\n private async setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalButtonInitializeOptions,\n methodId: string,\n ): Promise {\n const { onPaymentError, shippingAddress, buyNowInitializeOptions } = braintreepaypal;\n\n try {\n const buyNowCart =\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function'\n ? await this.createBuyNowCart(\n buyNowInitializeOptions.getBuyNowCartRequestBody(),\n )\n : undefined;\n\n this.buyNowCartId = buyNowCart?.id;\n\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomer();\n const paymentMethod: PaymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n const amount = buyNowCart ? buyNowCart.cartAmount : state.getCartOrThrow().cartAmount;\n const currencyCode = buyNowCart\n ? braintreepaypal.currencyCode\n : state.getCartOrThrow().currency.code;\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: unknown) {\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 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.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: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(billingAddress),\n shipping_address: JSON.stringify(shippingAddress),\n ...(this.buyNowCartId && { cart_id: this.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 async createBuyNowCart(buyNowCardRequestBody?: BuyNowCartRequestBody | void) {\n if (!buyNowCardRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n return await this.paymentIntegrationService.createBuyNowCart(buyNowCardRequestBody);\n } catch (error) {\n throw new BuyNowCartCreationError();\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 BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreePaypalButtonStrategy from './braintree-paypal-button-strategy';\n\nconst createBraintreePaypalButtonStrategy: CheckoutButtonStrategyFactory<\n BraintreePaypalButtonStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n );\n\n return new BraintreePaypalButtonStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeIntegrationService,\n braintreeHostWindow,\n );\n};\n\nexport default toResolvableModule(createBraintreePaypalButtonStrategy, [{ id: 'braintreepaypal' }]);\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n BraintreeError,\n BraintreeHostWindow,\n BraintreeInitializationData,\n BraintreeIntegrationService,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n isBraintreeError,\n PaypalAuthorizeData,\n PaypalButtonStyleLabelOption,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n BuyNowCartCreationError,\n BuyNowCartRequestBody,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport getValidButtonStyle from '../get-valid-button-style';\nimport mapToBraintreeShippingAddressOverride from '../map-to-braintree-shipping-address-override';\n\nimport BraintreePaypalCreditButtonInitializeOptions, {\n WithBraintreePaypalCreditButtonInitializeOptions,\n} from './braintree-paypal-credit-button-initialize-options';\n\nexport default class BraintreePaypalCreditButtonStrategy implements CheckoutButtonStrategy {\n private buyNowCartId: string | undefined;\n\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: CheckoutButtonInitializeOptions & WithBraintreePaypalCreditButtonInitializeOptions,\n ): 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 = this.paymentIntegrationService.getState();\n let currencyCode: string;\n\n if (braintreepaypalcredit.buyNowInitializeOptions) {\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 await this.paymentIntegrationService.loadDefaultCheckout();\n\n state = this.paymentIntegrationService.getState();\n currencyCode = state.getCartOrThrow().currency.code;\n }\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { clientToken, config, 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 commit: false,\n };\n\n const paypalCheckoutSuccessCallback = (\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n this.renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n containerId,\n methodId,\n !!config.testMode,\n );\n };\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this.handleError(error, containerId, braintreepaypalcredit.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 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.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 const buttonStyle =\n fundingSource === paypal.FUNDING.CREDIT\n ? {\n label: PaypalButtonStyleLabelOption.CREDIT,\n ...getValidButtonStyle(style),\n }\n : getValidButtonStyle(style);\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.braintreeIntegrationService.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\n try {\n const buyNowCart =\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function'\n ? await this.createBuyNowCart(\n buyNowInitializeOptions.getBuyNowCartRequestBody(),\n )\n : undefined;\n\n this.buyNowCartId = buyNowCart?.id;\n\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomer();\n const paymentMethod: PaymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n const amount = buyNowCart ? buyNowCart.cartAmount : state.getCartOrThrow().cartAmount; // state.getCheckoutOrThrow().outstandingBalance\n const currencyCode = buyNowCart\n ? braintreepaypalcredit.currencyCode\n : state.getCartOrThrow().currency.code;\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: true,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error: unknown) {\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 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.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: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(billingAddress),\n shipping_address: JSON.stringify(shippingAddress),\n ...(this.buyNowCartId && { cart_id: this.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 async createBuyNowCart(buyNowCardRequestBody?: BuyNowCartRequestBody | void) {\n if (!buyNowCardRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n return await this.paymentIntegrationService.createBuyNowCart(buyNowCardRequestBody);\n } catch (error) {\n throw new BuyNowCartCreationError();\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 BraintreeSDKVersionManager,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreePaypalCreditButtonStrategy from './braintree-paypal-credit-button-strategy';\n\nconst createBraintreePaypalCreditButtonStrategy: CheckoutButtonStrategyFactory<\n BraintreePaypalCreditButtonStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\n braintreeHostWindow,\n );\n return new BraintreePaypalCreditButtonStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeIntegrationService,\n braintreeHostWindow,\n );\n};\n\nexport default toResolvableModule(createBraintreePaypalCreditButtonStrategy, [\n { id: 'braintreepaypalcredit' },\n]);\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), hostWindow, braintreeSDKVersionManager),\n );\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 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 || 40}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 await this.paymentIntegrationService.loadDefaultCheckout();\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeScriptLoader = new BraintreeScriptLoader(\n scriptLoader,\n braintreeHostWindow,\n braintreeSDKVersionManager,\n );\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 GooglePayError,\n GooglePayInitializationData,\n GooglePayPaymentDataRequest,\n GooglePayPaymentOptions,\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 this._googlePayPaymentProcessor.setIsWebViewExperimentOn(\n !!paymentMethod.initializationData?.isWebViewExperimentOn,\n );\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) => Promise {\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 if (this._googlePayPaymentProcessor.isWebViewWithRestrictions()) {\n return {};\n }\n\n return {\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({\n callbackTrigger,\n shippingAddress,\n shippingOptionData,\n offerData,\n }) => {\n const {\n availableTriggers,\n addressChangeTriggers,\n shippingOptionsChangeTriggers,\n offerChangeTriggers,\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 const { newOfferInfo = undefined, error: couponsError = undefined } =\n offerChangeTriggers.includes(callbackTrigger)\n ? await this._googlePayPaymentProcessor.handleCoupons(offerData)\n : {};\n\n // We can add another errors if needed 'couponsError || shippingError || anotherError'\n const error: GooglePayError | undefined = couponsError;\n\n if (this._buyNowInitializeOptions) {\n return this._getBuyNowTransactionInfo(\n availableShippingOptions,\n newOfferInfo,\n error,\n );\n }\n\n return this._getTransactionInfo(availableShippingOptions, newOfferInfo, error);\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(\n availableShippingOptions?: ShippingOptionParameters,\n newOfferInfo?: GooglePayPaymentDataRequest['offerInfo'],\n error?: GooglePayError,\n ) {\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 ...(newOfferInfo && {\n newOfferInfo,\n }),\n ...(error && {\n error,\n }),\n };\n }\n\n private async _getTransactionInfo(\n availableShippingOptions?: ShippingOptionParameters,\n newOfferInfo?: GooglePayPaymentDataRequest['offerInfo'],\n error?: GooglePayError,\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 ...(this._countryCode && { countryCode: this._countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n ...(availableShippingOptions && {\n newShippingOptionParameters: availableShippingOptions,\n }),\n ...(newOfferInfo && {\n newOfferInfo,\n }),\n ...(error && {\n error,\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 BraintreeSDKVersionManager,\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 braintreeSDKVersionManager = new BraintreeSDKVersionManager(paymentIntegrationService);\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(\n getScriptLoader(),\n braintreeHostWindow,\n braintreeSDKVersionManager,\n ),\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';\nimport { PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\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';\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 PayPalCommerceSdk(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';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PayPalSdkHelper } from '@bigcommerce/checkout-sdk/bigcommerce-payments-utils';\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 GooglePayBigCommercePaymentsGateway from './google-pay-bigcommerce-payments-gateway';\n\nconst createGooglePayBigCommercePaymentsButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayBigCommercePaymentsGateway(\n paymentIntegrationService,\n new PayPalSdkHelper(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayBigCommercePaymentsButtonStrategy, [\n { id: 'googlepay_bigcommerce_payments' },\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';\nimport { StripeScriptLoader } from '@bigcommerce/checkout-sdk/stripe-utils';\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';\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 StripeScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayStripeButtonStrategy, [\n { id: 'googlepaystripe' },\n { id: 'googlepaystripeupe' },\n { id: 'googlepaystripeocs' },\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 PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n PaypalButtonCreationService,\n PayPalButtonOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\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 paypalIntegrationService: PayPalIntegrationService,\n private paypalButtonCreationService: PaypalButtonCreationService,\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.paypalIntegrationService.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.paypalIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, isAppSwitchEnabled } =\n paymentMethod.initializationData || {};\n\n const buyNowFlowCallbacks = {\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const buttonOptions: PayPalButtonOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalIntegrationService.getValidButtonStyle(style),\n isAppSwitchEnabled,\n isHostedCheckoutEnabled,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && onComplete && { onPaymentComplete: () => onComplete() }),\n };\n\n const paypalButton = this.paypalButtonCreationService.createPayPalButton(\n 'paypalcommerce',\n methodId,\n buttonOptions,\n buyNowInitializeOptions,\n );\n\n if (paypalButton.isEligible()) {\n if (paypalButton.hasReturned?.() && isAppSwitchEnabled) {\n paypalButton.resume?.();\n } else {\n paypalButton.render(`#${containerId}`);\n }\n } else if (onEligibilityFailure && typeof onEligibilityFailure === 'function') {\n onEligibilityFailure();\n } else {\n this.paypalIntegrationService.removeElement(containerId);\n }\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalIntegrationService,\n PaypalButtonCreationService,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceButtonStrategy from './paypal-commerce-button-strategy';\n\nconst createPayPalCommerceButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceButtonStrategy\n> = (paymentIntegrationService) => {\n const paypalIntegrationService = createPayPalIntegrationService(paymentIntegrationService);\n const paypalButtonCreationService = new PaypalButtonCreationService(\n paymentIntegrationService,\n paypalIntegrationService,\n );\n\n return new PayPalCommerceButtonStrategy(\n paymentIntegrationService,\n paypalIntegrationService,\n paypalButtonCreationService,\n );\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 ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalButtonsOptions,\n PayPalBuyNowInitializeOptions,\n PayPalInitializationData,\n PayPalIntegrationService,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '@bigcommerce/checkout-sdk/paypal-utils';\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 paypalIntegrationService: PayPalIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPayPalCommerceCreditButtonInitializeOptions,\n ): Promise {\n const { paypalcommercecredit, containerId, methodId } = options;\n const { buyNowInitializeOptions, currencyCode: providedCurrencyCode } =\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.paypalIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommercecredit);\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.paypalIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, isAppSwitchEnabled } =\n paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n createOrder: () => this.paypalIntegrationService.createOrder('paypalcommercecredit'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const hostedCheckoutCallbacks = {\n ...(!isAppSwitchEnabled && {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n }),\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: PayPalButtonsOptions = {\n fundingSource,\n style: this.paypalIntegrationService.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.paypalIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalIntegrationService.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.paypalIntegrationService.getBillingAddressFromOrderDetails(orderDetails);\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalIntegrationService.getShippingAddressFromOrderDetails(orderDetails);\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalIntegrationService.updateOrder('paypalcommerce');\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalIntegrationService.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.paypalIntegrationService.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.paypalIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalIntegrationService.updateOrder('paypalcommerce');\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.paypalIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalIntegrationService.updateOrder('paypalcommerce');\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';\nimport { createPayPalIntegrationService } from '@bigcommerce/checkout-sdk/paypal-utils';\n\nimport PayPalCommerceCreditButtonStrategy from './paypal-commerce-credit-button-strategy';\n\nconst createPayPalCommerceCreditButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceCreditButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditButtonStrategy(\n paymentIntegrationService,\n createPayPalIntegrationService(paymentIntegrationService),\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 { 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 { 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 { round } from 'lodash';\n\nimport {\n AmountTransformer,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n Payment,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n ShippingOption,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n isStripePaymentMethodLike,\n StripeAdditionalActionRequired,\n StripeClient,\n StripeElement,\n StripeElementEvent,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeError,\n StripeEventType,\n StripeInitializationData,\n StripeIntegrationService,\n StripeLinkV2Event,\n StripeLinkV2Options,\n StripeLinkV2ShippingRate,\n StripePaymentMethodType,\n StripeResult,\n StripeScriptLoader,\n StripeStringConstants,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport {\n expressCheckoutAllowedCountryCodes,\n stripeAllowedShippingOptionsLength,\n} from './constants';\nimport { WithStripeOCSCustomerInitializeOptions } from './stripe-ocs-customer-initialize-options';\n\nexport default class StripeLinkV2ButtonStrategy implements CheckoutButtonStrategy {\n private _stripeClient?: StripeClient;\n private _stripeElements?: StripeElements;\n private _linkV2Element?: StripeElement;\n private _amountTransformer?: AmountTransformer;\n private _onComplete?: (orderId?: number) => Promise;\n private _loadingIndicatorContainer?: string;\n private _currencyCode?: string;\n private _captureMethod?: 'automatic' | 'manual';\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeScriptLoader,\n private stripeIntegrationService: StripeIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithStripeOCSCustomerInitializeOptions,\n ): Promise {\n const { stripeocs, containerId } = options || {};\n\n if (!stripeocs || !containerId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { gatewayId } = stripeocs;\n\n if (!gatewayId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const methodId = this._getMethodId(gatewayId);\n const state = await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n const paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n const { loadingContainerId, buttonHeight, onComplete } = stripeocs;\n\n this._loadingIndicatorContainer = loadingContainerId;\n\n this._onComplete = onComplete;\n\n if (!isStripePaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { initializationData } = paymentMethod;\n const { captureMethod } = initializationData;\n const stripeJsVersion =\n this.stripeIntegrationService.getStripeJsVersion(initializationData);\n\n this._captureMethod = captureMethod;\n this._stripeClient = await this.scriptLoader.getStripeClient(\n initializationData,\n state.getCartLocale(),\n stripeJsVersion,\n );\n\n await this.paymentIntegrationService.loadDefaultCheckout();\n\n await this._mountExpressCheckoutElement(containerId, this._stripeClient, buttonHeight);\n\n this._initializeEvents(methodId);\n }\n\n signIn() {\n return Promise.resolve();\n }\n\n signOut() {\n return Promise.resolve();\n }\n\n executePaymentMethodCheckout() {\n return Promise.resolve();\n }\n\n deinitialize() {\n return Promise.resolve();\n }\n\n private async _mountExpressCheckoutElement(\n container: string,\n stripeExpressCheckoutClient: StripeClient,\n buttonHeight = 40,\n ) {\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n const expressCheckoutOptions: StripeElementsCreateOptions = {\n shippingAddressRequired: shouldRequireShippingAddress,\n ...(shouldRequireShippingAddress\n ? { allowedShippingCountries: await this._getAvailableCountries() }\n : {}),\n ...(shouldRequireShippingAddress\n ? { shippingRates: [{ id: '_', amount: 0, displayName: 'Pending rates' }] }\n : {}),\n billingAddressRequired: true,\n emailRequired: true,\n phoneNumberRequired: true,\n paymentMethods: {\n link: StripeStringConstants.AUTO,\n applePay: StripeStringConstants.NEVER,\n googlePay: StripeStringConstants.NEVER,\n amazonPay: StripeStringConstants.NEVER,\n paypal: StripeStringConstants.NEVER,\n klarna: StripeStringConstants.NEVER,\n },\n // Minimal buttonHeight value is 40\n buttonHeight,\n };\n\n const { cartAmount = 1 } = this.paymentIntegrationService.getState().getCart() || {};\n\n const elementsOptions: StripeLinkV2Options = {\n mode: 'payment',\n amount: this._toCents(cartAmount),\n currency: this._getCurrency(),\n ...(this._captureMethod ? { captureMethod: this._captureMethod } : {}),\n };\n\n this._stripeElements = stripeExpressCheckoutClient.elements(elementsOptions);\n\n this._linkV2Element = this._stripeElements.create(\n StripeElementType.EXPRESS_CHECKOUT,\n expressCheckoutOptions,\n );\n this._linkV2Element.mount(`#${container}`);\n }\n\n /** Events * */\n\n private _initializeEvents(methodId: string): void {\n if (!this._linkV2Element) {\n return;\n }\n\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n\n if (shouldRequireShippingAddress) {\n this._linkV2Element.on(StripeElementEvent.SHIPPING_ADDRESS_CHANGE, async (event) =>\n this._onShippingAddressChange(event),\n );\n this._linkV2Element.on(StripeElementEvent.SHIPPING_RATE_CHANGE, async (event) =>\n this._onShippingRateChange(event),\n );\n }\n\n this._linkV2Element.on(StripeElementEvent.CONFIRM, async (event) =>\n this._onConfirm(event, methodId),\n );\n\n this._linkV2Element.on(StripeElementEvent.CANCEL, this._onCancel);\n }\n\n private async _onShippingAddressChange(event: StripeEventType) {\n if (!('address' in event)) {\n return;\n }\n\n const shippingAddress = event.address;\n // Depending on the country, some fields can be missing or partially redacted.\n // For example, the shipping address in the US can only contain a city, state, and ZIP code.\n // The full shipping address appears in the confirm event object after the purchase is confirmed in the browser’s payment interface.\n const result = {\n firstName: '',\n lastName: '',\n phone: '',\n company: '',\n address1: '',\n address2: '',\n city: shippingAddress?.city || '',\n countryCode: shippingAddress?.country || '',\n postalCode: shippingAddress?.postal_code || '',\n stateOrProvince: shippingAddress?.state || '',\n stateOrProvinceCode: shippingAddress?.state || '',\n customFields: [],\n };\n\n await this.paymentIntegrationService.updateShippingAddress(result);\n\n const shippingRates = await this._getAvailableShippingOptions();\n\n await this._updateDisplayedPrice();\n\n if (!shippingRates?.length) {\n event.reject();\n } else {\n event.resolve({\n shippingRates,\n });\n }\n }\n\n private _onCancel() {\n throw new PaymentMethodCancelledError();\n }\n\n private async _onShippingRateChange(event: StripeEventType) {\n if ('shippingRate' in event) {\n const { shippingRate } = event;\n\n await this._handleShippingOptionChange(shippingRate?.id);\n\n await this._updateDisplayedPrice();\n\n event.resolve({});\n }\n }\n\n /** Confirm methods * */\n private async _onConfirm(event: StripeEventType, methodId: string) {\n if (\n 'billingDetails' in event &&\n 'shippingAddress' in event &&\n this._stripeClient &&\n this._stripeElements\n ) {\n await this._updateShippingAndBillingAddress(event);\n await this.paymentIntegrationService.submitOrder();\n\n const paymentPayload = this._getPaymentPayload(methodId);\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._processAdditionalAction(error, methodId);\n }\n }\n\n return Promise.resolve();\n }\n\n private async _updateShippingAndBillingAddress(event: StripeLinkV2Event) {\n const shouldRequireShippingAddress = this._shouldRequireShippingAddress();\n\n const firstName =\n event.shippingAddress?.name?.split(' ')[0] ||\n event.billingDetails?.name?.split(' ')[0] ||\n '';\n const lastName =\n event.shippingAddress?.name?.split(' ')[1] ||\n event.billingDetails?.name?.split(' ')[1] ||\n '';\n\n if (shouldRequireShippingAddress) {\n const shippingAddress = this._mapShippingAddress(\n event.shippingAddress,\n event.billingDetails,\n firstName,\n lastName,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n }\n\n const billingAddress = this._mapBillingAddress(\n event.shippingAddress,\n event.billingDetails,\n firstName,\n lastName,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n private _mapShippingAddress(\n shippingAddress: StripeLinkV2Event['shippingAddress'],\n billingDetails: StripeLinkV2Event['billingDetails'],\n firstName: string,\n lastName: string,\n ) {\n return {\n firstName,\n lastName,\n phone: billingDetails?.phone || '',\n company: '',\n address1: shippingAddress?.address?.line1 || '',\n address2: shippingAddress?.address?.line2 || '',\n city: shippingAddress?.address?.city || '',\n countryCode: shippingAddress?.address?.country || '',\n postalCode: shippingAddress?.address?.postal_code || '',\n stateOrProvince: shippingAddress?.address?.state || '',\n stateOrProvinceCode: shippingAddress?.address?.state || '',\n customFields: [],\n };\n }\n\n private _mapBillingAddress(\n shippingAddress: StripeLinkV2Event['shippingAddress'],\n billingDetails: StripeLinkV2Event['billingDetails'],\n firstName: string,\n lastName: string,\n ) {\n return {\n email: billingDetails?.email || '',\n firstName,\n lastName,\n phone: billingDetails?.phone || '',\n company: '',\n address1: billingDetails?.address?.line1 || '',\n address2: '',\n city: billingDetails?.address?.city || '',\n countryCode: billingDetails?.address?.country || '',\n postalCode: billingDetails?.address?.postal_code || '',\n stateOrProvince: billingDetails?.address?.state || '',\n stateOrProvinceCode: shippingAddress?.address?.state || '',\n customFields: [],\n };\n }\n\n private async _processAdditionalAction(error: unknown, methodId: string): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n if (!this._stripeClient || !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 additionalActionData,\n methodId,\n );\n\n const paymentPayload = this._getPaymentPayload(methodId, paymentIntent?.id || token);\n\n try {\n this._toggleLoadingIndicator(true);\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n await this._completeCheckoutFlow();\n } catch (error) {\n this.stripeIntegrationService.throwPaymentConfirmationProceedMessage();\n } finally {\n this._toggleLoadingIndicator(false);\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n additionalActionData: StripeAdditionalActionRequired['data'],\n methodId: string,\n ): Promise {\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeIntegrationService.mapStripePaymentData(\n this._stripeElements,\n redirect_url,\n );\n let stripeError: StripeError | undefined;\n\n try {\n const isPaymentCompleted = await this.stripeIntegrationService.isPaymentCompleted(\n methodId,\n this._stripeClient,\n );\n\n const confirmationResult = !isPaymentCompleted\n ? await this._stripeClient?.confirmPayment({\n elements: stripePaymentData.elements,\n clientSecret: token,\n redirect: StripeStringConstants.IF_REQUIRED,\n confirmParams: {\n return_url: stripePaymentData.confirmParams?.return_url,\n },\n })\n : await this._stripeClient?.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 return this.stripeIntegrationService.throwStripeError(stripeError);\n }\n }\n\n private async _completeCheckoutFlow() {\n if (typeof this._onComplete === 'function') {\n return this._onComplete();\n }\n\n window.location.replace('/checkout/order-confirmation');\n\n return Promise.resolve();\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 ...(token ? { credit_card_token: { token } } : {}),\n confirm: false,\n method: StripePaymentMethodType.Link,\n };\n\n return {\n methodId,\n paymentData: {\n formattedPayload,\n },\n };\n }\n\n /** Utils * */\n\n private _shouldRequireShippingAddress() {\n const { getCart } = this.paymentIntegrationService.getState();\n\n const { lineItems } = getCart() || {};\n\n return !!lineItems?.physicalItems.length;\n }\n\n private async _updateDisplayedPrice() {\n if (this._stripeElements) {\n this._stripeElements.update({\n currency: this._getCurrency(),\n mode: 'payment',\n amount: await this._getTotalPrice(),\n });\n }\n }\n\n private _getCurrency() {\n if (!this._currencyCode) {\n const currencyCode = this.paymentIntegrationService.getState().getCart()?.currency;\n\n if (currencyCode) {\n this._currencyCode = currencyCode.code.toLowerCase();\n }\n }\n\n return this._currencyCode;\n }\n\n private async _getTotalPrice(): Promise {\n await this.paymentIntegrationService.loadCheckout();\n\n const { getCheckoutOrThrow, getCart } = this.paymentIntegrationService.getState();\n const { decimalPlaces } = getCart()?.currency || {};\n const totalPrice = round(getCheckoutOrThrow().outstandingBalance, decimalPlaces).toFixed(\n decimalPlaces,\n );\n\n return this._toCents(+totalPrice);\n }\n\n private async _getAvailableCountries(): Promise {\n const countries = await this.paymentIntegrationService.loadShippingCountries();\n const deliverableCountries =\n countries.getShippingCountries()?.map((country) => country.code) || [];\n\n return deliverableCountries.filter((code) => {\n return expressCheckoutAllowedCountryCodes.includes(code);\n });\n }\n\n private async _getAvailableShippingOptions(): Promise {\n const state = this.paymentIntegrationService.getState();\n const consignments = state.getConsignments();\n\n if (!consignments?.[0]) {\n return;\n }\n\n const consignment = consignments[0];\n const options = (consignment.availableShippingOptions || []).map(\n this._getStripeShippingOption.bind(this),\n );\n const recommendedShippingOption = consignment.availableShippingOptions?.find(\n (shippingOption) => shippingOption.isRecommended,\n );\n const selectedId = consignment.selectedShippingOption?.id;\n const recommendedId = recommendedShippingOption?.id;\n\n if (selectedId) {\n // Set selected shipping option first in the array, as it will be selected by default\n options.sort((option) => (option.id === selectedId ? -1 : 0));\n } else if (recommendedId) {\n // Set recommended shipping option first in the array, as it will be selected by default\n options.sort((option) => (option.id === recommendedId ? -1 : 0));\n await this._handleShippingOptionChange(recommendedId);\n } else {\n await this._handleShippingOptionChange(options[0]?.id);\n }\n\n // Stripe has restricted the number of shipping rates.\n return options.slice(0, stripeAllowedShippingOptionsLength);\n }\n\n private _getStripeShippingOption({ id, cost, description }: ShippingOption) {\n return {\n id,\n displayName: description,\n amount: this._toCents(cost),\n };\n }\n\n private async _handleShippingOptionChange(optionId?: string) {\n if (!optionId || optionId === 'shipping_option_unselected') {\n return;\n }\n\n return this.paymentIntegrationService.selectShippingOption(optionId);\n }\n\n private _getAmountTransformer() {\n if (this._amountTransformer) {\n return this._amountTransformer;\n }\n\n const { getCart } = this.paymentIntegrationService.getState();\n const { currency } = getCart() || {};\n\n if (currency) {\n const amountTransformer = new AmountTransformer(currency.decimalPlaces);\n\n return amountTransformer;\n }\n }\n\n private _toCents(amount: number) {\n const fallbackValue = Math.round(amount * 100);\n const amountTransformer = this._getAmountTransformer();\n\n if (amountTransformer) {\n return amountTransformer.toInteger(amount);\n }\n\n return fallbackValue;\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 _getMethodId(gatewayId: string): string {\n const { initializationData: { checkoutSessionEnabled } = {} } =\n this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(gatewayId);\n\n return checkoutSessionEnabled\n ? StripePaymentMethodType.CHECKOUT_SESSION\n : StripePaymentMethodType.OCS;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n StripeIntegrationService,\n StripeScriptLoader,\n} from '@bigcommerce/checkout-sdk/stripe-utils';\nimport { DEFAULT_CONTAINER_STYLES, LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport StripeLinkV2ButtonStrategy from './stripe-link-v2-button-strategy';\n\nconst createLinkV2ButtonStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeScriptLoader(getScriptLoader());\n const loadingIndicator = new LoadingIndicator({\n containerStyles: DEFAULT_CONTAINER_STYLES,\n });\n\n return new StripeLinkV2ButtonStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeIntegrationService(paymentIntegrationService, stripeScriptLoader),\n loadingIndicator,\n );\n};\n\nexport default toResolvableModule(createLinkV2ButtonStrategy, [{ id: 'stripeocs' }]);\n","import { uniqueId } from 'lodash';\n\nimport { InvalidArgumentError } from '../error/errors';\n\nconst getUniqId = (idPrefix?: string): string => {\n const id = uniqueId(idPrefix);\n\n return document.getElementById(id) ? getUniqId(idPrefix) : id;\n};\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 = getUniqId(idPrefix);\n }\n\n return container.id;\n });\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 { 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 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","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 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 { 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 { 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","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 = '',\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 { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { createCheckoutStore } from '../checkout';\nimport { ConfigState } from '../config';\nimport * as defaultCheckoutButtonStrategyFactories from '../generated/checkout-button-strategies';\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 } = 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(\n paymentIntegrationService,\n process.env.ESSENTIAL_BUILD ? {} : defaultCheckoutButtonStrategyFactories,\n );\n\n return new CheckoutButtonInitializer(\n store,\n new CheckoutButtonStrategyActionCreator(\n createCheckoutButtonRegistry(store, requestSender, formPoster, 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';\n\nexport interface CheckoutButtonStrategyFactories {\n [key: string]: CheckoutButtonStrategyFactory;\n}\n\nexport default function createCheckoutButtonStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n checkoutButtonStrategyFactories: CheckoutButtonStrategyFactories,\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 { CheckoutActionCreator, CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { PaypalScriptLoader } from '../payment/strategies/paypal';\n\nimport { CheckoutButtonMethodType, CheckoutButtonStrategy } from './strategies';\nimport { PaypalButtonStrategy } from './strategies/paypal';\n\nexport default function createCheckoutButtonRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\n formPoster: FormPoster,\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 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 { 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 { 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","import { FormatError, IntlMessageFormat } from 'intl-messageformat';\nimport { isObject, union } from 'lodash';\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\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 }\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._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 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 }, {});\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","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 { 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","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":["y","x","module","exports","iframeResizer","__WEBPACK_EXTERNAL_MODULE_iframe_resizer_1512d797__","__webpack_require__","d","__WEBPACK_EXTERNAL_MODULE_iframe_resizer_js_iframeResizer_contentWindow_a6cfc03f__","__webpack_module_cache__","moduleId","cachedModule","undefined","__webpack_modules__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","r","Symbol","toStringTag","value","B2B_EXTRA_FIELD_PREFIX","isExtraField","field","name","startsWith","mapExtraFieldToFormField","extraField","fieldType","type","extraFieldType","getFieldTypeInfo","options","config","numberOfRows","rows","_a","length","assign","items","map","val","label","id","custom","hidden","visibleToStorefront","required","isRequired","default","defaultValue","String","maxLength","max","maxValue","throwErrorAction","error","meta","action","__WEBPACK_EXTERNAL_MODULE_rxjs_concat__","__WEBPACK_EXTERNAL_MODULE_rxjs_of__","__WEBPACK_EXTERNAL_MODULE_rxjs_throwError__","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_createErrorAction__","payload","B2BTokenActionType","B2BTokenActionCreator","constructor","_requestSender","this","loadB2BToken","store","state","getState","storeConfig","getStoreConfigOrThrow","storeHash","storeProfile","baseUrl","b2bBaseUrl","clientId","b2bClientId","b2bApiSettings","customerId","customer","getCustomerOrThrow","channelId","checkout","getCheckoutOrThrow","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_createAction__","LoadB2BTokenRequested","__WEBPACK_EXTERNAL_MODULE_rxjs_defer__","__awaiter","body","getB2BToken","LoadB2BTokenSucceeded","token","data","pipe","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_catchError__","LoadB2BTokenFailed","SDK_VERSION_HEADERS","MissingDataErrorType","BillingAddressActionType","B2BTokenRequestSender","appClientId","jwtBody","timeout","params","app_client_id","headers","post","credentials","bcToken","StandardError","Error","message","super","setPrototypeOf","__proto__","captureStackTrace","stack","MissingDataError","subtype","MissingBillingAddress","MissingCart","MissingConsignments","MissingCheckout","MissingCustomer","MissingCheckoutConfig","MissingOrderConfig","MissingOrder","MissingOrderId","MissingPayment","MissingPaymentToken","MissingPaymentMethod","MissingPaymentProviderCustomer","MissingShippingAddress","getErrorMessage","UnableToContinueAsGuestError","ContentType","BillingAddressActionCreator","_subscriptionActionCreator","continueAsGuest","getCheckout","getCustomer","isGuest","billingAddress","getBillingAddress","billingAddressRequestBody","country","existingBillingAddressRequestBody","__rest","hasBillingAddress","__WEBPACK_EXTERNAL_MODULE_lodash_isEmpty__","__WEBPACK_EXTERNAL_MODULE_rxjs_merge__","ContinueAsGuestRequested","billing_address_action_creator_awaiter","_createOrUpdateBillingAddress","ContinueAsGuestSucceeded","ContinueAsGuestFailed","_updateCustomerConsent","updateAddress","address","__WEBPACK_EXTERNAL_MODULE_rxjs_Observable__","create","observer","next","UpdateBillingAddressRequested","email","then","UpdateBillingAddressSucceeded","complete","catch","response","UpdateBillingAddressFailed","acceptsAbandonedCartEmails","acceptsMarketingNewsletter","__WEBPACK_EXTERNAL_MODULE_rxjs_empty__","updateSubscriptions","checkoutId","createAddress","EmptyCartError","content_type","DEFAULT_PARAMS","include","join","BillingAddressRequestSender","url","Accept","JsonV1","err","billing_address_request_sender_rest","put","ProjectionActionType","ErrorActionType","createDataStoreProjection","stateTransformer","projection","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_createDataStore__","Synchronize","subscribe","dispatch","initial","ErrorActionCreator","clearError","ClearError","ExperimentAwareRequestSender","_config","sendRequest","_prefixed","patch","delete","basePath","getBasePath","getFeatures","endsWith","test","getEnvironment","e","ConsoleLogger","_console","log","messages","_logToConsole","info","warn","debug","NoopLogger","logger","isEnabled","console","createLogger","getDefaultLogger","cachableActionDecorator","_","descriptor","memoizedMethods","WeakMap","decorateMethod","method","args","lastArg","useCache","param","instanceMethods","fn","set","__WEBPACK_EXTERNAL_MODULE__bigcommerce_memoize_bf7b411a_memoize__","__WEBPACK_EXTERNAL_MODULE_rxjs_from__","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_shareReplay__","isEqual","__WEBPACK_EXTERNAL_MODULE_lodash_isEqual__","ConfigActionType","ConfigActionCreator","_configRequestSender","loadConfig","LoadConfigRequested","LoadConfigSucceeded","LoadConfigFailed","__decorate","DEFAULT_RESPONSE","status","RequestError","errors","CheckoutNotAvailableError","title","INTERNAL_USE_ONLY","ConfigRequestSender","CouponActionType","CouponActionCreator","_couponRequestSender","applyCoupon","code","ApplyCouponRequested","ApplyCouponSucceeded","ApplyCouponFailed","removeCoupon","RemoveCouponRequested","RemoveCouponSucceeded","RemoveCouponFailed","checkout_default_includes","CheckoutIncludes","GiftCertificateActionType","CartSource","CustomerActionType","joinIncludes","includes","__WEBPACK_EXTERNAL_MODULE_lodash_uniq__","CouponRequestSender","couponCode","AvailableShippingOptions","GiftCertificateActionCreator","_giftCertificateRequestSender","applyGiftCertificate","giftCertificate","ApplyGiftCertificateRequested","ApplyGiftCertificateSucceeded","ApplyGiftCertificateFailed","removeGiftCertificate","RemoveGiftCertificateRequested","RemoveGiftCertificateSucceeded","RemoveGiftCertificateFailed","GiftCertificateRequestSender","giftCertificateCode","isResolvableModule","InvalidArgumentError","Registry","_factories","_instances","_defaultToken","defaultToken","_useFallback","_b","useFallback","_tokenResolver","_c","tokenResolver","cacheToken","_getInstance","getFactory","exactMatch","resolvedToken","keys","register","factory","_hasFactory","_hasInstance","ResolveIdRegistry","_registry","_resolveToken","bind","_encodeToken","resolveId","getUseFallback","btoa","JSON","stringify","_decodeToken","parse","atob","registeredTokens","query","results","forEach","registeredToken","resolverId","result","matches","totalKeys","entries","push","matchedResults","sort","a","b","filter","queryKeyCount","exactResult","find","matched","isSpamProtectionExecuteSucceededAction","succeededAction","CustomerStrategyActionType","CheckoutActionType","CheckoutHydrateActionType","CustomerActionCreator","_customerRequestSender","_checkoutActionCreator","_spamProtectionActionCreator","createCustomer","customerAccount","isStorefrontSpamProtectionEnabled","checkoutSettings","createAccount","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_switchMap__","loadCurrentCheckout","CreateCustomerSucceeded","CreateCustomerRequested","execute","CreateCustomerFailed","customerAddress","CreateCustomerAddressRequested","customer_action_creator_awaiter","CreateCustomerAddressSucceeded","CreateCustomerAddressFailed","signInCustomer","cartId","cart","source","BuyNow","SignInCustomerRequested","persistentCartRetrievalInformation","loadCheckout","SignInCustomerSucceeded","SignInCustomerFailed","signOutCustomer","SignOutCustomerRequested","SignOutCustomerSucceeded","SignOutCustomerFailed","CustomerRequestSender","registerIntegrations","registry","integrations","paymentIntegrationService","resolveIds","CustomerStrategyActionCreator","_strategyRegistry","_strategyRegistryV2","_paymentIntegrationService","signIn","methodId","SignInRequested","_getStrategy","SignInSucceeded","SignInFailed","signOut","SignOutRequested","SignOutSucceeded","SignOutFailed","executePaymentMethodCheckout","ExecutePaymentMethodCheckoutRequested","ExecutePaymentMethodCheckoutSucceeded","ExecutePaymentMethodCheckoutFailed","initialize","customerStrategies","isInitialized","InitializeRequested","InitializeSucceeded","InitializeFailed","deinitialize","DeinitializeRequested","DeinitializeSucceeded","DeinitializeFailed","widgetInteraction","WidgetInteractionStarted","WidgetInteractionFinished","WidgetInteractionFailed","strategy","joinOrMergeIncludes","baseIncludes","includeDictionaryOrList","Array","isArray","includesDictionary","deletions","__WEBPACK_EXTERNAL_MODULE_lodash_keys__","__WEBPACK_EXTERNAL_MODULE_lodash_pickBy__","on","additions","__WEBPACK_EXTERNAL_MODULE_lodash_filter__","__WEBPACK_EXTERNAL_MODULE_lodash_difference__","mergeIncludes","CheckoutRequestSender","updateCheckout","FormFieldsActionType","CheckoutActionCreator","_checkoutRequestSender","_configActionCreator","_formFieldsActionCreator","LoadCheckoutRequested","loadFormFields","LoadCheckoutSucceeded","_transformCustomerAddresses","LoadCheckoutFailed","loadDefaultCheckout","checkout_action_creator_awaiter","context","getContextConfig","UpdateCheckoutRequested","UpdateCheckoutSucceeded","UpdateCheckoutFailed","hydrateInitialState","HydrateInitialState","addresses","shouldSaveAddress","SpamProtectionActionType","FormFieldsActionCreator","_formFieldsRequestSender","LoadFormFieldsRequested","form_fields_action_creator_awaiter","loadFields","LoadFormFieldsSucceeded","LoadFormFieldsFailed","form_fields_action_creator_decorate","FormFieldsRequestSender","SpamProtectionChallengeNotCompletedError","SpamProtectionFailedError","NotInitializedErrorType","ExtensionActionType","ExtensionInternalEventType","SpamProtectionActionCreator","_googleRecaptcha","spam_protection_action_creator_awaiter","spamProtectionElementId","containerId","document","getElementById","reset","spamProtectionElement","createElement","setAttribute","appendChild","recaptchaSitekey","googleRecaptchaSitekey","load","verifyCheckoutSpamProtection","VerifyCheckoutRequested","validate","VerifyCheckoutSucceeded","VerifyCheckoutFailed","ExecuteRequested","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_take__","ExecuteSucceeded","ExecuteFailed","MutationObserverFactory","_window","window","callback","MutationObserver","NotInitializedError","CustomerNotInitialized","PaymentNotInitialized","ShippingNotInitialized","SpamProtectionNotInitialized","not_initialized_error_getErrorMessage","SpamProtectionNotLoadedError","GoogleRecaptcha","googleRecaptchaScriptLoader","mutationObserverFactory","_memoized","recaptcha","sitekey","container","event$","__WEBPACK_EXTERNAL_MODULE_rxjs_Subject__","_widgetId","render","size","getResponse","_event$","_recaptcha","element","remove","querySelector","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_retryWhen__","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_delay__","index","TIMEOUT","_watchRecaptchaChallengeWindow","event","iframeContainer","parentElement","style","visibility","observe","attributes","attributeFilter","GoogleRecaptchaScriptLoader","_scriptLoader","_loadPromise","_loadScript","callbackName","Promise","resolve","reject","grecaptcha","loadScript","createSpamProtection","scriptLoader","SpamProtectionRequestSender","DefaultCustomerStrategy","_store","_customerActionCreator","continueWithCheckoutCallback","parseUrl","anchor","href","port","indexOf","hostname","hash","origin","protocol","pathname","search","ExtensionNotFoundError","isIframeEvent","object","IframeEventPoster","targetOrigin","_targetWindow","_context","_targetOrigin","targetWindow","__WEBPACK_EXTERNAL_MODULE_rxjs_fromEvent__","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_filter__","successType","errorType","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_map__","toPromise","postMessage","setTarget","setContext","createExtensionEventPoster","extension","iframe","contentWindow","CancellablePromise","promise","cancellable","cancel","race","UnexpectedDetachmentError","ExtensionInternalCommandType","DetachmentObserver","_mutationObserver","ensurePresence","targets","mutationsList","mutation","from","removedNodes","node","some","target","contains","childList","subtree","output","disconnect","originalIframeResizer","ExtensionNotLoadedError","ResizableIframeCreator","_options","createFrame","src","initCallback","failedCallback","border","display","width","_toResizableFrame","removeChild","timeoutInterval","detachmentObserver","setTimeout","handleMessage","ResizeIframe","iframes","autoResize","scrolling","sizeWidth","heightCalculationMethod","teardown","removeEventListener","clearTimeout","addEventListener","ExtensionIframe","_containerId","_extension","parentOrigin","_url","URL","searchParams","attach","iframeCreator","iframeResizerCallback","_iframe","toString","ExtensionReady","ExtensionFailed","detach","ExtensionActionCreator","loadExtensions","LoadExtensionsRequested","extensions","LoadExtensionsSucceeded","LoadExtensionsFailed","renderExtension","region","workerExtensionMessenger","extension_action_creator_awaiter","getCartOrThrow","links","checkoutLink","getExtensionByRegion","RenderExtensionRequested","worker","Worker","blob","createObjectURL","Blob","createExtensionWebWorker","add","RenderExtensionSucceeded","RenderExtensionFailed","ExtensionRequestSender","bind_decorator","bindMethodDecorator","decoratedTarget","getOwnPropertyNames","getOwnPropertyDescriptor","bindClassDecorator","boundMethod","ExtensionCommandType","ExtensionQueryType","WorkerEventListener","_worker","_isListening","_listeners","listen","_handleMessage","stopListen","addListener","listener","listeners","removeListener","splice","trigger","messageEvent","worker_event_listener_rest","worker_event_listener_decorate","WorkerEventPoster","UnsupportedExtensionCommandError","UnsupportedExtensionQueryError","WorkerExtensionMessenger","_workers","_commandListeners","_queryListeners","extensionId","listenForCommand","command","commandHandler","_getWorkerById","validCommandType","_validateCommand","commandHandlerProxy","listenForQuery","queryHandler","validQueryType","_validateQuery","queryHandlerProxy","clearCacheById","values","appendWww","replace","ExtensionEventType","IframeEventListener","sourceOrigin","_sourceOrigins","iframe_event_listener_rest","iframe_event_listener_decorate","ExtensionMessenger","_workerExtensionMessenger","_posters","clearCacheByRegion","_getExtensionByRegion","_getExtensionById","_getExtensions","_extensions","getExtensions","ExtensionEventBroadcaster","_extensionMessenger","_subscribers","_subscribed","_unsubscribers","eventListener","Subscribe","_handleSubscribe","Unsubscribe","_handleUnsubscribe","broadcast","eventType","subscribeConsignmentsChange","broadcaster","getConsignments","getInitialConsignments","consignments","currentConsignments","ConsignmentsChanged","previousConsignments","standard_error_StandardError","missing_data_error_MissingDataErrorType","not_initialized_error_NotInitializedErrorType","missing_data_error_MissingDataError","missing_data_error_getErrorMessage","getShippableItemsCount","lineItems","physicalItems","item","addedByPromotion","__WEBPACK_EXTERNAL_MODULE_lodash_reduce__","total","quantity","guard","errorFactory","not_initialized_error_NotInitializedError","errors_not_initialized_error_getErrorMessage","amazonPayV2Regions","de","jp","uk","us","AmazonPayV2CheckoutLanguage","AmazonPayV2Placement","AmazonPayV2LedgerCurrency","AmazonPayV2PayOptions","AmazonPayV2ButtonColor","AmazonPayV2ButtonDesign","AmazonPayV2PaymentProcessor","amazonPayV2ScriptLoader","paymentMethod","amazonPayV2SDK","buttonParentContainer","createAmazonPayButtonParentContainer","amazonPayV2Button","bindButton","buttonId","sessionId","changeAction","getAmazonPayV2SDK","Pay","bindChangeAction","amazonCheckoutSessionId","createButton","renderButton","prepareCheckout","createCheckoutSessionConfig","requestConfig","prepareRequestConfig","getAmazonPayV2Button","onClick","initCheckout","prepareCheckoutWithCreationRequestConfig","createCheckoutConfig","amazon_pay_v2_payment_processor_awaiter","estimatedOrderAmount","productType","signout","renderAmazonPayButton","buttonColor","checkoutState","decoupleCheckoutInitiation","placement","isButtonMicroTextDisabled","parentContainerId","getButtonParentContainer","design","C0001","amazonPayV2ButtonOptions","getAmazonPayV2ButtonOptions","updateBuyNowFlowFlag","isBuyNowFlow","Boolean","isPh4Enabled","features","storeCountryCode","isPh4UsOnly","publicKeyId","signedPayload","amazon_pay_v2_payment_processor_rest","isEnvironmentSpecific","uid","Math","random","substr","parentContainer","Gold","getCart","getPaymentMethodOrThrow","getCheckoutState","merchantId","testMode","initializationData","checkoutLanguage","checkoutSessionMethod","extractAmazonCheckoutSessionId","ledgerCurrency","buttonBaseConfig","sandbox","PayOnly","PayAndShip","shopPath","amount","outstandingBalance","currencyCode","currency","buttonOptions","tmpConfig","createCheckoutSession","getOrThrow","checkoutSelectors","paymentMethods","PaymentMethodClientUnavailableError","AmazonPayV2ScriptLoader","windowWithAmazonPay","amazonPayV2Region","amazon","createAmazonPayV2PaymentProcessor","__WEBPACK_EXTERNAL_MODULE__bigcommerce_script_loader_875b3e8f_getScriptLoader__","toResolvableModule","invalid_argument_error_InvalidArgumentError","NotImplementedError","AmazonPayV2CustomerStrategy","amazonPayV2PaymentProcessor","amazonpay","_e","loadPaymentMethod","Checkout","payment","getPaymentId","remoteCheckoutSignOut","providerId","create_amazon_pay_v2_customer_strategy","isExperimentEnabled","experimentName","fallbackValue","BRAINTREE_SDK_HOSTED_FIELDS_FIX_VERSION","BRAINTREE_SDK_DEFAULT_VERSION","BRAINTREE_SDK_STABLE_VERSION","BraintreeSDKVersionManager","braintreeWindow","getSDKVersion","getStoreConfig","getPreloadedSDKVersion","braintree","preloadedVersion","__WEBPACK_EXTERNAL_MODULE_lodash_find__","VERSION","UnsupportedBrowserError","TotalPriceStatusType","BraintreeOrderStatus","NonInstantLocalPaymentMethods","BraintreeFastlaneAuthenticationState","BraintreeErrorType","BraintreeErrorCode","BraintreeSupportedCardBrands","isBraintreeError","BraintreeEnv","BraintreeModuleName","BraintreeFormFieldType","BraintreeSdk","braintreeScriptLoader","clientToken","setClientToken","teardownModule","dataCollector","getClient","client","getClientTokenOrThrow","clientCreator","loadClient","authorization","getDataCollectorOrThrow","emptyDataCollector","deviceData","loadDataCollector","dataCollectorConfig","kount","KountNotEnabled","getBraintreeGooglePayment","googlePayment","braintreeGooglePayment","all","loadGooglePayment","getBraintreeThreeDS","threeDS","threeDSecure","load3DS","version","getBraintreeLocalPayment","merchantAccountId","braintreeLocalPayment","localPaymentCreator","loadLocalPayment","getUsBankAccount","usBankAccount","loadUsBankAccount","getBraintreeVisaCheckout","visaCheckout","loadVisaCheckout","paypal","getVisaCheckoutSdk","visaCheckoutSDK","loadVisaCheckoutSdk","getVenmoCheckoutOrThrow","braintreeVenmo","venmoCheckout","loadVenmoCheckout","venmoCheckoutConfig","allowDesktop","paymentMethodUsage","braintreeVenmoCheckout","isBrowserSupported","BRAINTREE_SDK_SCRIPTS_INTEGRITY","Client","PaypalCheckout","Paypal","LocalPayment","DataCollector","UsBankAccount","GooglePayment","ThreeDSecure","VisaCheckout","Venmo","HostedFields","Fastlane","ApplePayGatewayType","BraintreeScriptLoader","braintreeHostWindow","braintreeSDKVersionManager","loadBraintreeModuleOrThrow","loadFastlane","loadPaypalCheckout","loadPaypal","loadHostedFields","V","async","integrity","crossorigin","braintreeModuleName","fileName","getBraintreeModule","braintreeSdkVersion","scriptPath","getIntegrityValuesByModuleName","moduleName","PaymentMethodCancelledError","DefaultLabels","ApplePayCustomerStrategy","_sessionFactory","_braintreeSdk","_applePayScriptLoader","_onAuthorizeCallback","__WEBPACK_EXTERNAL_MODULE_lodash_noop__","_onError","_onClick","_subTotalLabel","Subtotal","_shippingLabel","Shipping","_hasApplePaySession","applepay","shippingLabel","subtotalLabel","onError","onPaymentAuthorize","loadSdk","_paymentMethod","_applePayButton","_createButton","_handleWalletButtonClick","gateway","BRAINTREE","applePayButton","_createApplePayButtonElement","preventDefault","request","_getBaseRequest","applePaySession","_handleApplePayEvents","begin","storeName","decimalPlaces","merchantCapabilities","supportedNetworks","requiresShipping","requiredBillingContactFields","requiredShippingContactFields","countryCode","grandTotal","toFixed","subtotal","taxes","tax","onvalidatemerchant","apple_pay_customer_strategy_awaiter","merchantSession","_onValidateMerchant","completeMerchantValidation","onshippingcontactselected","_handleShippingContactSelected","onshippingmethodselected","_handleShippingMethodSelected","oncancel","onpaymentauthorized","_onPaymentAuthorized","shippingAddress","_transformContactToAddress","shippingContact","updateShippingAddress","abort","selectionShippingOptionId","selectedShippingOption","availableOptions","availableShippingOptions","selectedOption","unselectedOptions","option","shippingOptions","description","cost","detail","additionalDescription","identifier","isRecommended","completeShippingContactSelection","ApplePaySession","STATUS_INVALID_SHIPPING_POSTAL_ADDRESS","recommendedOption","optionId","selectedOptionId","_updateShippingOption","newShippingMethods","newTotal","newLineItems","_getUpdatedLineItems","shippingMethod","completeShippingMethodSelection","shippingCostTotal","selectShippingOption","paymentData","validationURL","location","paymentsUrl","billingContact","deviceSessionId","_getBraintreeDeviceData","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","assertApplePayWindow","isApplePayWindow","ApplePaySessionFactory","ApplePayScriptLoader","sdkVersion","isApplePaySdkWindow","create_apple_pay_customer_strategy","getHost","__WEBPACK_EXTERNAL_MODULE__bigcommerce_request_sender_01d1f546_createRequestSender__","host","__WEBPACK_EXTERNAL_MODULE__bigcommerce_script_loader_875b3e8f_ScriptLoader__","BuyNowCartCreationError","request_error_DEFAULT_RESPONSE","request_error_RequestError","LiabilityShiftEnum","BigCommercePaymentsIntent","StyleButtonLabel","StyleButtonColor","StyleButtonShape","NonInstantAlternativePaymentMethods","PayPalOrderStatus","BigCommercePaymentsIntegrationService","formPoster","bigCommercePaymentsRequestSender","bigCommercePaymentsScriptLoader","loadPayPalSdk","providedCurrencyCode","initializesOnCheckoutPage","forceLoad","paypalSdk","getPayPalSDK","getPayPalSdkOrThrow","createBuyNowCartOrThrow","buyNowInitializeOptions","cartRequestBody","getBuyNowCartRequestBody","createBuyNowCart","createOrder","requestBody","orderId","createOrderCardFields","setupToken","updateOrder","consignment","getConsignmentsOrThrow","_error","getOrderStatus","tokenizePayment","postForm","payment_type","provider","order_id","cart_id","gatewayId","vault_payment_instrument","set_as_default_stored_instrument","device_info","method_id","paypal_account","getShippingOptionOrThrow","selectedShippingOptionId","recommendedShippingOption","shippingOptionToSelect","getAddress","getBillingAddressFromOrderDetails","payer","given_name","surname","email_address","address_line_1","address_line_2","admin_area_2","country_code","postal_code","admin_area_1","phone_number","national_number","getShippingAddressFromOrderDetails","orderDetails","purchase_units","full_name","shipping","split","getValidButtonStyle","color","height","shape","validStyles","getValidHeight","__WEBPACK_EXTERNAL_MODULE_lodash_omitBy__","__WEBPACK_EXTERNAL_MODULE_lodash_isNil__","removeElement","elementId","internal_api_headers_INTERNAL_USE_ONLY","content_type_ContentType","http_request_content_type","sdk_version_headers_SDK_VERSION_HEADERS","BigCommercePaymentsRequestSender","requestSender","Json","BigCommercePaymentsScriptLoader","paypalSdkScriptConfig","getPayPalSdkScriptConfigOrThrow","loadPayPalSDK","bigCommercePaymentsPayPalSDK","transformConfig","scriptSrc","URLSearchParams","intent","buyerCountry","attributionId","isVenmoEnabled","isHostedCheckoutEnabled","isPayPalCreditAvailable","isDeveloperModeApplicable","availableAlternativePaymentMethods","enabledAlternativePaymentMethods","isGooglePayEnabled","commit","shouldEnableCard","enableCardFunding","disableCardFunding","enableCreditFunding","disableCreditFunding","enableVenmoFunding","disableVenmoFunding","disableAPMsFunding","apm","googlePayComponent","cardFieldsComponent","disableFunding","filterFundingOptions","enableFunding","components","fundingOptions","fundingTypesToBeFiltered","fundingOption","transformedConfig","create_bigcommerce_payments_integration_service","__WEBPACK_EXTERNAL_MODULE__bigcommerce_form_poster_1cd9ef62_createFormPoster__","default_checkout_button_height","BigCommercePaymentsCustomerStrategy","bigCommercePaymentsIntegrationService","bigcommerce_payments","getPaymentMethod","Buttons","onComplete","paymentButtonStyles","isAppSwitchEnabled","checkoutTopButtonStyles","defaultCallbacks","appSwitchWhenAvailable","onApprove","orderID","hostedCheckoutCallbacks","onShippingAddressChange","onShippingOptionsChange","actions","onHostedCheckoutApprove","buttonRenderOptions","fundingSource","FUNDING","PAYPAL","paypalButton","isEligible","hasReturned","resume","order","handleError","shippingOption","create_bigcommerce_payments_customer_strategy","UntrustedShippingCardVerificationType","bigcommerce_payments_types_BigCommercePaymentsIntent","bigcommerce_payments_types_LiabilityShiftEnum","TDSecureVerificationMethod","TDSecureAuthenticationState","bigcommerce_payments_types_StyleButtonLabel","bigcommerce_payments_types_StyleButtonColor","bigcommerce_payments_types_StyleButtonShape","PayPalFastlaneAuthenticationState","PayPalSdkHelper","getPayPalFastlaneSdk","bigCommercePaymentsFastlaneSdk","getPayPalFastlaneSdkConfiguration","getPayPalGooglePaySdk","bigCommercePaymentsGooglePay","getPayPalGooglePaySdkScriptConfigOrThrow","getPayPalApmsSdk","bigCommercePaymentsApms","getPayPalApmSdkConfiguration","getPayPalMessages","bigCommercePaymentsMessages","paypalSdkMessagesConfig","getPayPalSdkMessagesConfiguration","scriptOptions","scriptAttributes","enableAPMsFunding","createBigCommercePaymentsSdk","__WEBPACK_EXTERNAL_MODULE__bigcommerce_script_loader_875b3e8f_createScriptLoader__","CookieStorage","cookieKey","encodeURIComponent","cookie","firstIndex","lastIndex","decodeURIComponent","substring","secure","cookieText","expires","path","domain","toUTCString","now","Date","minutes","setTime","getTime","BigCommercePaymentsFastlaneUtils","initializePayPalFastlane","paypalFastlaneSdk","isTestModeEnabled","styles","localStorage","setItem","bigCommercePaymentsFastlane","defaultStyles","root","backgroundColorPrimary","getPayPalFastlaneOrThrow","lookupCustomerOrThrow","identity","lookupCustomerByEmail","triggerAuthenticationFlowOrThrow","customerContextId","triggerAuthenticationFlow","updateStorageSessionId","setDate","getDate","cookiesOption","removeStorageSessionId","getStorageSessionId","mapPayPalFastlaneProfileToBcCustomerData","authenticationResult","authenticationState","profileData","paypalBillingAddress","card","paymentSource","paypalShippingAddress","paypalProfileName","paypalInstrument","mapPayPalToBcAddress","instruments","mapPayPalToBcInstrument","filterAddresses","UNRECOGNIZED","instrument","brand","expiry","lastDigits","expiryYear","expiryMonth","bigpayToken","defaultInstrument","iin","last4","trustedShippingAddress","untrustedShippingCardVerificationMode","PAN","mapBcToPayPalAddress","addressLine1","addressLine2","adminArea1","adminArea2","profileName","fullName","phoneData","nationalNumber","reduce","customerAddresses","currentAddress","isEqualAddresses","firstAddress","secondAddress","normalizeAddress","__WEBPACK_EXTERNAL_MODULE_lodash_omit__","createBigCommercePaymentsFastlaneUtils","isInvalidStyleOption","styleOption","getFastlaneStyles","styleSettings","uiStyles","fastlaneStyles","input","toggle","textBody","text","textCaption","caption","branding","cleanUpFastlaneStyles","fastlaneRootSettingsBackgroundColor","errorColor","fastlaneRootSettingsErrorColor","fontFamily","fastlaneRootSettingsFontFamily","fontSizeBase","fastlaneRootSettingsFontSize","_d","padding","fastlaneRootSettingsPadding","primaryColor","fastlaneRootSettingsPrimaryColor","_f","borderRadius","fastlaneInputSettingsBorderRadius","_g","borderColor","fastlaneInputSettingsBorderColor","_h","focusBorderColor","fastlaneInputSettingsFocusBorderBase","_j","backgroundColor","fastlaneInputSettingsBackgroundColor","_k","borderWidth","fastlaneInputSettingsBorderWidth","_l","textColorBase","fastlaneInputSettingsTextColorBase","_m","colorPrimary","fastlaneToggleSettingsColorPrimary","_o","colorSecondary","fastlaneToggleSettingsColorSecondary","_p","fastlaneTextBodySettingsColor","_r","_q","fontSize","fastlaneTextBodySettingsFontSize","_t","_s","fastlaneTextCaptionSettingsColor","_v","_u","fastlaneTextCaptionSettingsFontSize","_x","_w","fastlaneBrandingSettings","mergeFastlaneStyles","BigCommercePaymentsFastlaneCustomerStrategy","bigCommercePaymentsSdk","bigCommercePaymentsFastlaneUtils","bigcommerce_payments_fastlane","updatePaymentProviderCustomer","checkoutPaymentMethodExecuted","runPayPalAuthenticationFlowOrThrow","customerEmail","isAuthenticationFlowCanceled","CANCELED","updateCustomerDataState","updatedState","isFastlaneShippingOptionAutoSelectEnabled","firstShippingOption","shippingOptionId","isFastlaneStylingEnabled","create_bigcommerce_payments_fastlane_customer_strategy","BigCommercePaymentsPayLaterCustomerStrategy","bigcommerce_payments_paylater","bigCommercePaymentsPayLater","fundingSources","PAYLATER","CREDIT","hasRenderedSmartButton","create_bigcommerce_payments_paylater_customer_strategy","BigCommercePaymentsVenmoCustomerStrategy","bigcommerce_payments_venmo","VENMO","paypalButtonRender","create_bigcommerce_payments_venmo_customer_strategy","PaymentMethodFailedError","PaymentMethodInvalidError","BoltDeveloperMode","StyleButtonSize","bolt_StyleButtonShape","BoltCustomerStrategy","boltScriptLoader","boltHostWindow","bolt","onInit","publishableKey","developerConfig","loadBoltClient","getCustomerEmail","hasBoltAccount","__WEBPACK_EXTERNAL_MODULE_rxjs_noop__","openBoltCheckoutModalOrThrow","boltClient","getBoltClientOrThrow","embeddedOneClickEnabled","callbacks","close","openCheckout","isCustomError","BoltCheckout","BoltScriptLoader","developerModeParams","storefrontApiToken","getDomainURL","getScriptOptions","loadBoltEmbedded","Bolt","developerMode","StagingMode","DevelopmentMode","developerDomain","create_bolt_customer_strategy","PaymentArgumentInvalidError","invalidFields","PaymentInvalidFormError","details","paypalSdkPromise","PAYPAL_COMPONENTS","PaypalButtonStyleLayoutOption","PaypalButtonStyleSizeOption","PaypalButtonStyleColorOption","PaypalButtonStyleLabelOption","PaypalButtonStyleShapeOption","MessagingPlacements","BraintreeIntegrationService","overlay","dataCollectors","threeDSecureOptions","getBraintreeFastlane","cardId","braintreeFastlane","getSessionId","braintreeFastlaneCreator","getPaypal","braintreePaypal","shouldSaveInstrument","braintree_integration_service_rest","newWindowFlow","__WEBPACK_EXTERNAL_MODULE__braintree_browser_detection_e7ac357c_supportsPopups__","show","focusWindow","tokenize","enableShippingAddress","flow","useraction","getPaypalCheckout","onSuccess","paypalCheckout","paypalCheckoutConfig","braintreePaypalCheckout","paypalSdkLoadConfig","isCreditEnabled","loadPayPalSDKOnce","getDataCollector","cacheKey","cached","getBraintreeEnv","isTestMode","Sandbox","Production","mapToBraintreeShippingAddressOverride","recipientName","line1","line2","mapToLegacyShippingAddress","first_name","last_name","mapToLegacyBillingAddress","riskCorrelationId","get3DS","getVenmoCheckout","venmoConfig","verifyCard","tokenizationPayload","tokenizeCard","challenge3DSVerification","creditCardInstrument","ccExpiry","ccNumber","ccName","isCreditCardInstrumentLike","getErrorsRequiredFields","requestData","mapToCreditCard","creditCards","nonce","bin","present3DSChallenge","creditCard","cardholderName","number","cvv","ccCvv","expirationDate","month","year","countryCodeAlpha2","countryName","streetAddress","endpoint","addFrame","removeFrame","challengeRequested","additionalInformation","cancelVerifyCard","braintree_integration_service_awaiter","verification","roundedAmount","Number","onLookupComplete","_data","collectDeviceData","BraintreePaypalCustomerStrategy","braintreeIntegrationService","braintreepaypal","paypalCheckoutOptions","renderPayPalButton","buttonStyles","env","setupPayment","authorizeData","shippingAddressOverride","createPayment","shippingAddressEditable","offerCredit","tokenizePayload","device_data","billing_address","shipping_address","buttonContainerId","onErrorCallback","create_braintree_paypal_customer_strategy","BraintreePaypalCreditCustomerStrategy","braintreepaypalcredit","create_braintree_paypal_credit_customer_strategy","get_fastlane_styles_isInvalidStyleOption","get_fastlane_styles_getFastlaneStyles","get_fastlane_styles_cleanUpFastlaneStyles","get_fastlane_styles_mergeFastlaneStyles","BraintreeFastlaneCustomerStrategy","braintreeFastlaneUtils","isAcceleratedCheckoutEnabled","braintreefastlane","getValidPaymentMethodOrThrow","paypalFastlaneStylesSettings","initializeBraintreeFastlaneOrThrow","shouldRunAuthenticationFlow","primaryMethodId","shouldRunAcceleratedCheckout","validPaymentMethodId","BraintreeFastlaneUtils","getDeviceSessionId","getBraintreeFastlaneOrThrow","getBraintreeFastlaneComponentOrThrow","FastlaneCardComponent","shouldSetShippingOption","getMethodIdOrThrow","saveSessionIdToCookies","removeSessionIdFromCookies","shippingAddresses","getPayPalBillingAddresses","billingAddresses","mergeShippingAndBillingAddresses","digitalItems","digitalItemBilling","setShippingOption","getSessionIdFromCookies","binDetails","phones","countries","getCountries","getCountryNameByCountryCode","matchedCountry","extendedAddress","filteredBillingAddresses","create_braintree_fastlane_customer_strategy","BraintreeVisaCheckoutCustomerStrategy","braintreeSdk","buttonClassName","braintreevisacheckout","visaCheckoutOptions","braintreeVisaCheckout","visaCheckoutInstance","initOptions","createInitOptions","paymentRequest","settings","locale","storeLanguage","collectShipping","signInButton","createSignInButton","init","paymentSuccessPayload","getShippingAddress","billing","mapToVisaCheckoutAddress","userData","cardInformation","userEmail","card_information","cardType","lastTwo","buttonClass","insertVisaCheckoutButton","visaCheckoutButton","flexDirection","className","innerHTML","create_braintree_visa_checkout_customer_strategy","hostWindow","CurrencyFormatter","currencySettings","symbolLocation","symbol","thousandsSeparator","decimalSeparator","_decimalPlaces","parseInt","_symbolLocation","_symbol","_thousandsSeparator","_decimalSeparator","format","formattedNumber","_formatNumber","formattedCurrency","_formatCurrency","positiveAmount","abs","integerAmount","decimalAmount","_toFixed","parsedIntegerAmount","toLowerCase","precision","round","CurrencyService","_storeConfig","_customerFormatter","shopperCurrency","_storeFormatter","toCustomerCurrency","exchangeRate","toStoreCurrency","currency_service_decorate","items_require_shipping","lineItem","isShippingRequired","customItems","isWebView","isReactNativeWindow","userAgent","navigator","vendor","isOperaWindow","opera","isAndroidWebView","isIOSWebView","PayPalCommerceIntent","types_StyleButtonLabel","types_StyleButtonColor","types_StyleButtonShape","types_TotalPriceStatusType","GooglePayCardNetwork","CallbackIntentsType","ErrorReasonType","CallbackTriggerType","isGooglePayCardNetworkKey","GooglePayKey","GooglePayGateway","_gatewayIdentifier","_isBuyNowFlow","_shouldRequestShipping","_isWebViewExperimentOn","mapToShippingAddressRequestBody","_mapToAddressRequestBody","mapToBillingAddressRequestBody","paymentMethodData","mapToExternalCheckoutData","tokenizationData","cardNetwork","cardDetails","getRequiredData","emailRequired","_isShippingAddressRequired","loadShippingCountries","allowedCountryCodes","getShippingCountries","shippingAddressRequired","shippingAddressParameters","phoneNumberRequired","shippingOptionRequired","getCallbackIntents","OFFER","SHIPPING_ADDRESS","SHIPPING_OPTION","getCallbackTriggers","availableTriggers","INITIALIZE","initializationTrigger","addressChangeTriggers","shippingOptionsChangeTriggers","offerChangeTriggers","getNonce","extraPaymentData","getMerchantInfo","googleMerchantName","merchantName","googleMerchantId","platformToken","authJwt","getGooglePayInitializationData","getTransactionInfo","_getCurrencyCodeOrThrow","storeCountry","isWebViewWithRestrictions","totalPrice","getTotalPrice","totalPriceStatus","ESTIMATED","setIsWebViewExperimentOn","isWebViewExperimentOn","getPaymentGatewayParameters","gatewayMerchantId","getCardParameters","allowedAuthMethods","allowedCardNetworks","supportedCards","billingAddressRequired","billingAddressParameters","_getPaymentMethodFn","_currencyCode","handleShippingAddressChange","mappedShippingAddress","_currencyService","currency_service","_getGooglePayShippingOption","handleShippingOptionChange","defaultSelectedOptionId","maxDecimalPlaces","min","__WEBPACK_EXTERNAL_MODULE_lodash_round__","handleCoupons","offerData","redemptionCodes","newCouponsState","offers","appliedCoupons","getAppliedCoupons","google_pay_gateway_awaiter","redemptionCode","appliedCouponError","coupon","newOfferInfo","coupons","displayName","reason","OFFER_INVALID","setShouldRequestShipping","getGatewayIdentifier","setGatewayIdentifier","shippingContextRequiresCheck","address3","_getFirstAndLastName","trim","nameParts","slice","isGooglePayErrorObject","isGooglePayKey","GooglePayCustomerStrategy","_googlePayPaymentProcessor","_methodId","googlePayOptions","_getMethodId","_getGooglePayClientOptions","_addPaymentButton","_paymentButton","paymentDataCallbacks","onPaymentDataChanged","callbackTrigger","shippingOptionData","google_pay_customer_strategy_awaiter","couponsError","newTransactionInfo","FINAL","newShippingOptionParameters","buttonType","addPaymentButton","_handleClick","initializeWidget","_interactWithPaymentSheet","statusCode","showPaymentSheet","siteLink","setExternalCheckoutForm","GooglePayPaymentProcessor","_gateway","_formPoster","_baseRequest","apiVersion","apiVersionMinor","googlePayPaymentOptions","_paymentsClient","getGooglePaymentsClient","_buildButtonPayloads","_buildWidgetPayloads","_determineReadinessToPay","_prefetchGooglePaymentData","paymentButton","_getPaymentsClient","allowedPaymentMethods","_getBaseCardPaymentMethod","paymentDataRequest","_getPaymentDataRequest","loadPaymentData","setExternalCheckoutXhr","_setExternalCheckout","processAdditionalAction","useFormPoster","transactionInfo","prefetchPaymentData","isReadyToPay","_getIsReadyToPayRequest","_baseCardPaymentMethod","parameters","baseCardPaymentMethod","_cardPaymentMethod","tokenizationSpecification","isWebViewLogic","callbackIntents","offerInfo","_paymentDataRequest","merchantInfo","_isReadyToPayRequest","_getOrThrow","GooglePayScriptLoader","google","payments","api","PaymentsClient","environment","createGooglePayScriptLoader","create_google_pay_adyenv2_customer_strategy","create_google_pay_adyenv3_customer_strategy","GooglePayAuthorizeNetGateway","service","_super","isGooglePayAuthorizeNetInitializationData","assertsIsGooglePayAuthorizeNetInitializationData","paymentGatewayId","create_google_pay_authorizenet_customer_strategy","is_request_error","assertIsGooglePayCheckoutComInitializationData","isGooglePayCheckoutComInitializationData","GooglePayCheckoutComGateway","_resolve","threeDSBody","three_ds_result","acs_url","isGooglePayThreeDSecureResult","isGooglePayTokenObject","assertIsGooglePayTokenObject","_tokenize","checkoutcomkey","token_data","Authorization","create_google_pay_checkoutcom_customer_strategy","GooglePayCybersourceGateway","create_google_pay_cybersource_customer_strategy","create_google_pay_bnz_customer_strategy","GooglePayOrbitalGateway","create_google_pay_orbital_customer_strategy","StripeFormMode","StripeDisplayName","StripeCheckoutSessionStatusType","StripeCheckoutSessionPaymentStatus","StripeLoadActionsResultType","StripePaymentMethodType","StripeStringConstants","StripeJsVersion","StripeElementType","StripePaymentIntentStatus","StripeElementEvent","StripeInstrumentSetupFutureUsage","StripeScriptLoader","stripeWindow","getStripeClient","stripeJsVersion","betas","bcStripeClient","stripe","stripePublishableKey","stripeConnectedAccount","stripeClient","stripeAccount","getElements","stripeElements","bcStripeElements","updateStripeElements","elements","update","fetchUpdates","getStripeCheckout","stripeCheckout","getStoredStripeCheckout","bcStripeCheckout","Stripe","getScriptUrl","V3","loadActions","logErrorToConsole","stripeCheckoutSession","getSession","stripeSessionIdFromOptions","clientSecret","STRIPE_UPE_CLIENT_BETAS","STRIPE_UPE_CLIENT_API_VERSION","assertsIsGooglePayStripeInitializationData","isGooglePayStripeInitializationData","GooglePayStripeGateway","isGooglePayStripeTokenObject","assertIsGooglePayStripeTokenObject","stripeVersion","__WEBPACK_EXTERNAL_MODULE_lodash_some__","initialization","stripeUPEClient","loadStripeJs","catchedConfirmError","confirmCardPayment","retrievePaymentIntent","__","_throwDisplayableStripeError","_isCancellationError","paymentIntent","getCartLocale","useNewStripeJsVersion","CLOVER","stripeError","payment_intent","last_payment_error","__WEBPACK_EXTERNAL_MODULE_lodash_includes__","create_google_pay_stripe_customer_strategy","create_google_pay_stripeupe_customer_strategy","GooglePayWorldpayAccessGateway","create_google_pay_worldpayaccess_customer_strategy","GooglePayBraintreeGateway","_service","_braintreeGooglePayment","isThreeDSecureEnabled","isNetworkTokenized","orderAmount","getOrderOrThrow","_braintreePresent3DSChallenge","isGooglePayBraintreeTokenObject","assertIsGooglePayBraintreeTokenObject","androidPayCards","createPaymentDataRequest","cardRequirements","billingAddressFormat","paymentMethodTokenizationParameters","create_google_pay_braintree_customer_strategy","LOADING_INDICATOR_STYLES","PAYPAL_SDK_SUPPORTED_LOCALES","transformLocaleToPayPalFormat","language","toUpperCase","PayPalCommerceSdk","paypalGooglePay","paypalApms","paypalMessages","assertsIsGooglePayPayPalCommercePaymentMethod","isGooglePayPaypalCommercePaymentMethod","GooglePayPaypalCommerceGateway","payPalCommerceSdk","googlePaySdk","getLocale","googlepayConfig","Googlepay","create_google_pay_paypal_commerce_customer_strategy","GooglePayBigCommercePaymentsGateway","payPalSdkHelper","create_google_pay_bigcommerce_payments_customer_strategy","getBrowserInfo","userLanguage","color_depth","screen","colorDepth","java_enabled","javaEnabled","screen_height","screen_width","time_zone_offset","getTimezoneOffset","GooglePayTdOnlineMartGateway","browser_info","errorBody","__WEBPACK_EXTERNAL_MODULE_lodash_isObject__","__WEBPACK_EXTERNAL_MODULE_lodash_isArray__","isTdOnlineMartAdditionalAction","threeDSResult","formUrl","payer_auth_request","threeDSSessionData","merchant_data","creq","create_google_pay_tdonlinemart_customer_strategy","PayPalIntent","paypal_types_TDSecureVerificationMethod","paypal_types_TDSecureAuthenticationState","paypal_types_LiabilityShiftEnum","paypal_types_StyleButtonLabel","paypal_types_StyleButtonColor","paypal_types_StyleButtonShape","paypal_types_PayPalFastlaneAuthenticationState","paypal_types_NonInstantAlternativePaymentMethods","paypal_types_PayPalOrderStatus","PayPalSdkScriptLoader","createPayPalSdkScriptLoader","PayPalIntegrationService","paypalRequestSender","paypalSdkLoader","PayPalRequestSender","create_paypal_integration_service","paypal_button_creation_service","paypalIntegrationService","createPayPalButton","onCancel","onPaymentComplete","paypal_button_creation_service_awaiter","buyNowCart","PayPalCommerceCustomerStrategy","paypalButtonCreationService","paypalcommerce","create_paypal_commerce_customer_strategy","paypal_commerce_types_LiabilityShiftEnum","paypal_commerce_types_PayPalCommerceIntent","paypal_commerce_types_StyleButtonLabel","paypal_commerce_types_StyleButtonColor","paypal_commerce_types_StyleButtonShape","paypal_commerce_types_NonInstantAlternativePaymentMethods","paypal_commerce_types_PayPalOrderStatus","PayPalCommerceIntegrationService","paypalCommerceRequestSender","paypalCommerceScriptLoader","PayPalCommerceRequestSender","PayPalCommerceScriptLoader","create_paypal_commerce_integration_service","PayPalCommerceCreditCustomerStrategy","paypalCommerceIntegrationService","paypalcommercecredit","paypalCommerceCredit","create_paypal_commerce_credit_customer_strategy","PayPalCommerceVenmoCustomerStrategy","paypalcommercevenmo","create_paypal_commerce_venmo_customer_strategy","PaypalFastlaneUtils","paypalFastlane","createPaypalFastlaneUtils","utils_get_fastlane_styles_isInvalidStyleOption","utils_get_fastlane_styles_getFastlaneStyles","utils_get_fastlane_styles_cleanUpFastlaneStyles","utils_get_fastlane_styles_mergeFastlaneStyles","PayPalCommerceFastlaneCustomerStrategy","paypalSdkScriptLoader","paypalFastlaneUtils","paypalcommercefastlane","create_paypal_commerce_fastlane_customer_strategy","isStripePaymentMethodLike","shopperLanguage","isStripeAcceleratedCheckoutCustomer","StripeUPECustomerStrategy","stripeupe","onEmailChange","getStyles","isLoading","paymentProviderCustomer","getPaymentProviderCustomerOrThrow","stripeLinkAuthenticationState","appearance","variables","fieldInnerShadow","colorBackground","fieldBackground","colorText","labelText","colorDanger","fieldErrorText","colorTextSecondary","colorTextPlaceholder","fieldPlaceholderText","rules","fieldBorder","fieldText","boxShadow","_stripeElements","billingEmail","defaultValues","mode","SHIPPING","linkAuthenticationElement","getElement","AUTHENTICATION","CHANGE","authenticated","deleteConsignment","mount","unmount","create_stripe_upe_customer_strategy","StripeIntegrationService","isMounted","checkoutEventsUnsubscribe","initCheckoutEventsSubscription","stripeInitializationOptions","stripe_integration_service_awaiter","paymentElement","PAYMENT","updateStripePaymentIntent","mountElement","stripeElement","mapAppearanceVariables","colorIcon","mapInputAppearanceRules","throwStripeError","throwDisplayableStripeError","isCancellationError","errorMessage","throwPaymentConfirmationProceedMessage","isPaymentCompleted","SUCCEEDED","mapStripePaymentData","returnUrl","shouldAllowRedisplay","mapStripeAddress","redirect","IF_REQUIRED","confirmParams","payment_method_data","allow_redisplay","billing_details","getShopperFullName","return_url","isAdditionalActionError","isRedirectAction","additionalAction","redirect_url","isOnPageAdditionalAction","getStripeJsVersion","DEFAULT_STYLES","DEFAULT_CONTAINER_STYLES","position","ROTATION_ANIMATION","LoadingIndicator","containerStyles","defineAnimation","buildContainer","indicator","buildIndicator","parentId","parent","opacity","hide","handleTransitionEnd","bottom","left","right","top","transition","setStyleAttribute","margin","transform","transformStyle","animation","attrs","k","setProperty","head","sheet","CSSStyleSheet","insertRule","AmountTransformer","toInteger","pow","expressCheckoutAllowedCountryCodes","StripeLinkV2CustomerStrategy","stripeIntegrationService","loadingIndicator","stripeocs","loadingContainerId","buttonHeight","_loadingIndicatorContainer","_onComplete","captureMethod","_captureMethod","_stripeClient","_mountExpressCheckoutElement","_initializeEvents","stripeExpressCheckoutClient","shouldRequireShippingAddress","_shouldRequireShippingAddress","expressCheckoutOptions","allowedShippingCountries","_getAvailableCountries","shippingRates","link","AUTO","applePay","NEVER","googlePay","amazonPay","klarna","cartAmount","elementsOptions","_toCents","_getCurrency","_linkV2Element","EXPRESS_CHECKOUT","SHIPPING_ADDRESS_CHANGE","stripe_link_v2_customer_strategy_awaiter","_onShippingAddressChange","SHIPPING_RATE_CHANGE","_onShippingRateChange","CONFIRM","_onConfirm","CANCEL","_onCancel","_getAvailableShippingOptions","_updateDisplayedPrice","shippingRate","_handleShippingOptionChange","_updateShippingAndBillingAddress","paymentPayload","_getPaymentPayload","_processAdditionalAction","billingDetails","_mapShippingAddress","_mapBillingAddress","additionalActionData","additional_action_required","_confirmStripePaymentOrThrow","_toggleLoadingIndicator","_completeCheckoutFlow","stripePaymentData","confirmationResult","confirmPayment","credit_card_token","confirm","Link","_getTotalPrice","_getStripeShippingOption","selectedId","recommendedId","_getAmountTransformer","_amountTransformer","amountTransformer","checkoutSessionEnabled","CHECKOUT_SESSION","OCS","create_stripe_link_v2_customer_strategy","stripeScriptLoader","OrderFinalizationNotRequiredError","NoPaymentDataRequiredPaymentStrategy","finalize","create_no_payment_strategy","AdyenV3ActionType","AdyenV2ActionType","AdyenComponentType","AdyenPaymentMethodType","HTTPMethod","ResultCode","AdyenCardFields","AdyenV2ScriptLoader","_stylesheetLoader","configuration","loadStylesheet","prepend","AdyenCheckout","isCardState","encryptedSecurityCode","encryptedExpiryMonth","isVaultedInstrument","instrumentId","AdyenV2PaymentStrategy","adyenv2","_paymentInitializeOptions","originKey","clientKey","paymentMethodsResponse","clientSideAuthentication","_adyenClient","translations","es","_paymentComponent","_mountPaymentComponent","CreditCard","Bancontact","_cardVerificationComponent","_mountCardVerificationComponent","adyenv2_payment_strategy_rest","shouldSetAsDefaultInstrument","_validateCardData","componentState","_componentState","encryptedCardNumber","encryptedExpiryYear","credit_card_number_confirmation","expiry_month","expiry_year","verification_value","bigpay_token","_getAdyenClient","_getPaymentInitializeOptions","_getThreeDS2ChallengeWidgetSize","additionalActionOptions","threeDS2Options","widgetSize","_handleAction","threeDS2ContainerId","onBeforeLoad","onLoad","adyenAction","additionalActionComponent","createFromAction","onAdditionalDetails","additionalActionState","paymentMethodType","ThreeDS2Challenge","QRCode","_mapAdyenPlaceholderData","prefillCardHolderName","street","houseNumberOrName","holderName","adyenClient","cardVerificationComponent","cardVerificationContainerId","SecuredFields","placeholder","caretColor","onChange","_updateComponentState","validateState","validateCardFields","onFieldValid","paymentComponent","ACH","IDEAL","SEPA","hasVaultedInstruments","AliPay","GiroPay","Sofort","Klarna","KlarnaPayNow","KlarnaAccount","Vipps","WeChatPayQR","provider_data","paymentError","cardComponent","componentRef","showValidation","isValid","issuer","props","_mapCardErrors","cardStateErrors","create_adyenv2_payment_strategy","__WEBPACK_EXTERNAL_MODULE__bigcommerce_script_loader_875b3e8f_getStylesheetLoader__","AdyenV3ScriptLoader","isHostedInstrumentLike","Adyenv3PaymentStrategy","adyenv3","paymentInitializeOptions","installmentOptions","paymentMethodsConfiguration","useKlarnaWidget","klarna_account","klarna_paynow","showInstallmentAmounts","_getLocale","showPayButton","adyenv3_payment_strategy_rest","submit","paymentToken","socialSecurityNumber","shopperName","isBoletoState","installments","plan","onActionHandled","componentType","challengeWindowSize","ThreeDS2","Sdk","_mountElement","_isOneyPaymentMethod","personalDetails","deliveryAddress","showBrandsUnderCardNumber","showEmailAddress","onSubmit","basePaymentData","tokenData","adyenComponent","_waitForMountContainer","maxAttempts","ceil","mountContainerMaxWaitMs","mountContainerPollIntervalMs","pollIntervalMs","step","poll","adyenv3_payment_strategy_awaiter","create_adyenv3_payment_strategy","AFFIRM_SCRIPTS","AffirmPaymentStrategy","affirmScriptLoader","affirm","initializeAffirmCheckout","checkout_token","getCheckoutInformation","open","onFail","failObject","successObject","ui","getOrder","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","taxTotal","first","last","full","zipcode","display_name","sku","unit_price","salePrice","qty","item_image_url","imageUrl","item_url","categories","getCategories","giftCertificates","listPrice","line","discountedAmount","discount_amount","discount_display_name","discountAmount","DISCOUNTED_AMOUNT","categoryTree","category","AffirmScriptLoader","affirmWindow","apikey","scriptURI","SANDBOX","PROD","m","g","n","h","p","getElementsByTagName","l","c","arguments","f","a1","c1","a2","c2","parentNode","insertBefore","public_api_key","script","create_affirm_payment_strategy","OrderFinalizationNotCompletedError","AfterpayPaymentStrategy","_afterpayScriptLoader","_mapCurrencyToISO2","withHttps","_afterpaySdk","applyStoreCredit","_loadPaymentMethod","validateCheckout","_redirectToAfterpay","forgetCheckout","loadPaymentMethods","AUD","NZD","CAD","USD","SCRIPTS_DEFAULT","SCRIPTS_US","AfterpayScriptLoader","_getScriptURI","isAfterpayWindow","AfterPay","HTTPS_SANDBOX","HTTPS_PROD","create_afterpay_payment_strategy","AmazonPayV2PaymentStrategy","_isReadyToPay","editButtonId","_bindEditButton","_isModalFlow","_createContainer","_amazonPayButton","_isOneTimeTransaction","_getAmazonPayButton","click","onFocus","isModalFlow","button","clone","cloneNode","replaceChild","_showLoadingSpinner","create_amazon_pay_v2_payment_strategy","apple_pay_payment_strategy_DefaultLabels","ApplePayPaymentStrategy","_storeCreditLabel","StoreCredit","storeCreditLabel","isStoreCreditApplied","storeCredit","apple_pay_payment_strategy_awaiter","create_apple_pay_payment_strategy","bigcommerce_payments_constants_LOADING_INDICATOR_STYLES","get_paypal_messages_styles_from_bnpl_config","messagesStyles","layout","logo","ratio","isBaseInstrument","BigCommercePaymentsPaymentStrategy","paypalSdkHelper","bannerContainerId","paypalBNPLConfiguration","bannerConfiguration","Messages","renderMessages","loadingIndicatorContainer","shouldRenderPayPalButtonOnInitialization","bigcommerce_payments_payment_strategy_rest","isPayPalVaultedInstrumentPaymentData","prepareVaultedInstrumentPaymentPayload","preparePaymentPayload","isProviderError","paypalOrderId","shouldConfirmInstrument","isTrustedVaultingFlow","checkoutPaymentButtonStyles","onRenderButton","onValidate","submitForm","handleClick","handleApprove","toggleLoadingIndicator","fieldsValues","getFieldsValues","getInstruments","findInstrument","paypalMessagesOptions","isBigCommercePaymentsProviderError","provider_error","create_bigcommerce_payments_payment_strategy","isPayPalFastlaneCustomer","BigCommercePaymentsFastlanePaymentStrategy","threeDSVerificationMethod","initializePayPalPaymentComponent","renderPayPalPaymentComponent","handlePayPalStoredInstrumentChange","orderRequest","bigcommerce_payments_fastlane_payment_strategy_rest","isVaultedFlow","isBigcommerceFastlaneRequestError","invalidRequestError","translationKey","getPaymentProviderCustomer","paypalFastlaneCustomer","paypalFastlaneSessionId","getBillingAddressOrThrow","cardComponentOptions","fields","prefill","enabled","paypalComponentMethods","getPayPalComponentMethodsOrThrow","isBigcommercePaymentsFastlaneThreeDSAvailable","is3dsEnabled","get3DSNonce","paypal_fastlane_token","getPaymentToken","is3DSEnabled","fastlaneToken","checkoutUrl","threeDomainSecureComponent","ThreeDomainSecureClient","threeDomainSecureParameters","threeDSRequested","Always","transactionContext","experience_context","cancel_url","isThreeDomainSecureEligible","liabilityShift","threeDSNonce","No","Unknown","Errored","Cancelled","Succeeded","Yes","Possible","paypalAxoSdk","selectionChanged","selectedCard","profile","showCardSelector","selectedInstrument","create_bigcommerce_payments_fastlane_payment_strategy","BigCommercePaymentsPayLaterPaymentStrategy","bigcommerce_payments_paylater_payment_strategy_rest","bigCommercePaymentsButtons","bigCommerceSdk","create_bigcommerce_payments_paylater_payment_strategy","TimeoutError","BigCommercePaymentsRatePayPaymentStrategy","pollingInterval","maxPollingIntervalTime","pollingTimer","stopPolling","bigcommerce_payments_ratepay","legalTextContainer","createFraudNetScript","loadFraudnetConfig","renderLegalText","bigcommerce_payments_ratepay_payment_strategy_rest","metadataId","guid","ratepayBirthDate","ratepayPhoneNumber","ratepayPhoneCountryCode","rate_pay","birth_date","normalizeDate","initializePollingMechanism","fraudNetScript","querySelectorAll","fraudNetConfig","deinitializePollingMechanism","legalTextContainerElement","date","formattedDate","formatDate","formattedMonth","getMonth","getFullYear","legalTextContainerElementId","legalTextContainerId","buttonContainer","buttonContainerParent","marginBottom","ratePayButton","Legal","PAY_UPON_INVOICE","resetPollingMechanism","scriptElement","generateGUID","s","i","floor","characters","reinitializeStrategy","resolvePromise","rejectPromise","orderStatus","useMetadata","isOrderApproved","PollingStop","isPollingError","PollingError","create_bigcommerce_payments_ratepay_payment_strategy","HostedFieldType","hosted_field_type","isCreditCardFormFields","CardNumber","CardName","CardExpiry","isCreditCardVaultedFormFields","CardNumberVerification","CardCodeVerification","CardExpiryVerification","BigCommercePaymentsCreditCardsPaymentStrategy","bigcommerce_payments_creditcards","bigCommercePaymentsInitializationOptions","form","onCreditCardFieldsRenderingError","onLoadComplete","hostedFormOptions","isCreditCardForm","isCreditCardVaultedForm","hasUndefinedValues","initializeFields","shouldInitializePayPalFastlane","initializePayPalFastlaneOrThrow","bigcommerce_payments_credit_cards_payment_strategy_rest","executionPaymentData","validateHostedFormOrThrow","submitHostedForm","getInstrumentParams","returnedOrderId","submitPaymentPayload","returnedVaultedToken","cvvField","expiryField","numberField","nameField","verification_nonce","card_with_order","formOptions","executeCallback","getExecuteCallback","cardFieldsConfig","getInputStyles","vaultSetupToken","inputEvents","onChangeHandler","onFocusHandler","onBlur","onBlurHandler","onInputSubmitRequest","cardFields","CardFields","stylizeInputContainers","renderFields","renderVaultedFields","createVaultSetupTokenCallback","createOrderCallback","createVaultSetupToken","bigcommerce_payments_credit_cards_payment_strategy_awaiter","fieldsOptions","getCardFieldsOrThrow","cardCode","CVVField","cardExpiry","ExpiryField","cardName","NameField","cardNumber","NumberField","cardCodeVerification","cardExpiryVerification","cardNumberVerification","getFieldTypeByEmittedField","emittedBy","mapFieldType","submitConfig","cardFieldsState","validationData","getValidityData","mapValidationErrors","updatedFields","cardNameField","fieldsKeys","every","fieldsErrors","getInvalidErrorByFieldType","CardCode","validationErrors","commonStyles","fontWeight","outline","background","marginLeft","onEnter","bigCommercePaymentsPaymentProviderCustomer","isBigCommercePaymentsAnalyticsV2Enabled","connectClientToken","payPalFastlaneSdk","create_bigcommerce_payments_credit_cards_payment_strategy","BigCommercePaymentsAlternativeMethodsPaymentStrategy","bigCommercePaymentsSdkHelper","isPollingEnabled","bigcommerce_payments_apms","bigCommercePaymentsAlternativeMethods","shouldRenderFields","bigcommerce_payments_alternative_methods_payment_strategy_rest","isNonInstantPaymentMethod","bigCommercePaymentsButton","Approved","deInitializePollingMechanism","paypalAmpsSdk","getPaypalAmpsSdkOrThrow","buttonStyle","onInitButton","onCreateOrder","handleFailure","bigcommerce_payments_alternative_methods_payment_strategy_awaiter","apmFieldsContainer","apmFieldsStyles","fieldContainerElement","PaymentFields","create_bigcommerce_payments_alternative_methods_payment_strategy","BigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy","bigcomemrce_payments_redirect_alternative_methods_payment_strategy_rest","isRedirectError","redirectUrl","create_bigcommerce_payments_redirect_alternative_methods_payment_strategy","BigCommercePaymentsVenmoPaymentStrategy","bigcommerce_payments_venmo_payment_strategy_rest","create_bigcommerce_payments_venmo_payment_strategy","BlueSnapDirect3ds","blueSnapSdk","_blueSnapSdk","initialize3ds","cardData","_getBlueSnapSdk","threeDsPaymentsSetup","sdkResponse","threeDSecureReferenceId","threeDsPaymentsSubmitData","isHostedCardFieldOptionsMap","isHostedStoredCardFieldOptionsMap","BlueSnapDirectCardType","BlueSnapDirectEventOrigin","BlueSnapDirectErrorDescription","BlueSnapDirectErrorCode","BlueSnapDirectHostedFieldTagId","BlueSnapDirectCreditCardPaymentStrategy","_blueSnapDirectHostedForm","_blueSnapDirect3ds","_paymentFieldsToken","_shouldUseHostedFields","_getPaymentFieldsToken","pfToken","bluesnapSubmitedForm","_getBlueSnapDirectThreeDSecureData","getCardInstrumentOrThrow","previouslyUsedCard","last4Digits","ccType","cardHolderName","billingFirstName","billingLastName","billingCountry","billingCity","billingZip","shippingFirstName","shippingLastName","shippingCountry","shippingCity","shippingZip","BlueSnapHostedFieldType","CREDIT_CARD_ERRORS","empty","invalid","BlueSnapDirectHostedForm","_nameOnCardInput","_hostedInputValidator","initializeValidationFields","paymentFieldsToken","enable3DS","callbacksAndStyles","bluesnap_direct_hosted_form_rest","_onValidate","_setCustomBlueSnapAttributes","_setCustomStoredCardsBlueSnapAttributes","_getHostedPaymentFieldsOptions","hostedPaymentFieldsCreate","accessibilityLabel","threeDSecureData","shouldSendName","hostedPaymentFieldsSubmitData","_isBlueSnapDirectCallbackError","THREE_DS_AUTH_FAILED","errorDescription","getValue","onCardTypeChange","onFieldEventHandler","setupComplete","_usetUiEventCallback","_handleError","onType","_tagId","onValid","tagId","ccnPlaceHolder","cvvPlaceHolder","expPlaceHolder","_mapStyles","focus","selector","declaration","declarationBlock","property","__WEBPACK_EXTERNAL_MODULE_lodash_kebabCase__","errorCode","eventOrigin","INVALID_OR_EMPTY","EMPTY","INVALID","isBlueSnapDirectInputValidationErrorDescription","cardNumberContainer","cardExpiryContainer","cardCodeContainer","cardNameContainer","dataset","bluesnap","BlueSnapHostedInputValidator","_errors","_updateErrors","errorData","BluesnapDirectNameOnCardInput","_style","_create","_getInput","_handleFocus","_handleBlur","_handleEnter","_input","_applyStyles","HTMLInputElement","ON_BLUR","allowedStyle","styleKeys","_configureInput","autocomplete","inputMode","BlueSnapDirectSdkEnv","BlueSnapDirectScriptLoader","PRODUCTION","create_bluesnap_direct_credit_card_payment_strategy","BlueSnapDirectAPMPaymentStrategy","_formatePaymentPayload","_isBlueSnapDirectRedirectResponse","providerData","frameUrl","partialValue","merchantid","isBlueSnapDirectRedirectResponseProviderData","providerDataQuery","ecp","account_number","accountNumber","account_type","accountType","shopper_permission","shopperPermission","routing_number","routingNumber","companyName","company_name","sepa_direct_debit","iban","isIdealInstrument","ideal","bic","isPayByBankInstrument","pay_by_bank","partialResponse","partialBody","create_bluesnap_direct_apm_payment_strategy","PaymentStatusTypes","payment_status_types","BlueSnapV2PaymentStrategy","_initializeOptions","frame","_createIframe","initializeOffsitePayment","getPaymentStatus","ACKNOWLEDGE","FINALIZE","finalizeOrder","bluesnapv2","create_bluesnapv2_payment_strategy","AnalyticsExtraItemsManager","storage","saveExtraItemsData","productId","categoryNames","getStorageKey","readExtraItemsData","getItem","itemsData","hasNotExtraItems","isExtraItemsData","clearExtraItemData","removeItem","isAnalyticsTrackerWindow","isWithAccountCreation","BoltError","getError","BoltPaymentStrategy","analyticsExtraItemsManager","useBoltClient","useBoltEmbedded","onPaymentSelect","useBigCommerceCheckout","boltEmbedded","mountBoltEmbeddedField","embeddedField","setExtraItemsForAnalytics","bolt_payment_strategy_rest","isBoltPaymentData","getBoltClientPaymentPayload","getBoltEmbeddedPaymentPayload","getBoltFullCheckoutPaymentPayload","orderToken","boltTransaction","success","transaction","reference","configure","tokenizeResult","validateTokenizeResultOrThrow","last_four_digits","expiration_month","expiration","expiration_year","create_account","shouldCreateAccount","embedded_checkout","setBoltOrderId","transactionReference","getTransactionReference","getBoltEmbeddedOrThrow","setOrderId","renderSeparateFields","lastFourDigits","expirationMonth","expirationYear","isNaN","isAnalyticsEnabled","create_bolt_payment_strategy","__WEBPACK_EXTERNAL_MODULE_local_storage_fallback_5dc95480_default__","isUsBankAccountInstrumentLike","BraintreeAchPaymentStrategy","braintreeach","getMandateText","handleBraintreeError","braintree_ach_payment_strategy_rest","isSubmittingWithVaultingInstrument","tokenizePaymentForVaultedInstrument","preparePaymentDataForVaultedInstrument","preparePaymentData","getUsBankAccountOrThrow","mandateText","bankDetails","getBankDetails","isVaultingEnabled","tokenized_bank_account","masked_account_number","ownershipType","businessName","create_braintree_ach_payment_strategy","create_braintree_sdk","BraintreeMessages","messagingContainer","bannedId","CART","removeAttribute","getPaypalMessagesStylesFromBNPLConfig","Overlay","closeElement","mainElement","_createElements","_element","_closeElement","_mainElement","_registerClick","_unregisterClick","_removeAfterTransition","transitionDuration","hasCloseButton","innerHtml","classLayout","classClose","classOverlayText","overlayText","addClassLayout","innerText","getOverlayStyle","_addEventListener","_removeEventListener","onClickClose","handleTransition","propertyName","braintree_paypal_constants_LOADING_INDICATOR_STYLES","is_braintree_error_isBraintreeError","BraintreePaypalPaymentStrategy","braintreeMessages","braintreeOptions","braintreeButtonOptions","loadPaypalCheckoutInstance","braintree_paypal_payment_strategy_rest","braintreeTokenizePayload","getOutstandingBalance","vaultPaymentInstrument","paymentMethodId","shouldShowPayPalCreditBanner","renderPayPalMessages","onPaymentError","getSmartButtonContainerId","braintree_paypal_payment_strategy_awaiter","tokenizePaymentOrThrow","isBraintreePaypalProviderError","create_braintree_paypal_payment_strategy","BraintreeRequestSender","BraintreeLocalMethodsPaymentStrategy","braintreeRequestSender","isLPMsUpdateExperimentEnabled","braintreelocalmethods","braintree_local_methods_payment_strategy_rest","executeWithNotInstantLPM","executeWithInstantLPM","basicPaymentData","getLPMsBasicPaymentData","isBraintreeRedirectError","startPayment","getInstantLPMConfig","getInstantLPMCallback","paymentType","fallback","buttonText","onPaymentStart","start","braintree_local_methods_payment_strategy_awaiter","paymentId","isBraintreeOrderSavedResponse","order_id_saved_successfully","startPaymentError","payloadData","isOrderPending","Pending","Completed","Failed","create_braintree_local_methods_payment_strategy","isBraintreeAcceleratedCheckoutCustomer","BraintreeFastlanePaymentStrategy","isThreeDSExperimentEnabled","initializeCardComponent","renderBraintreeCardComponent","handleBraintreeStoredInstrumentChange","braintree_fastlane_payment_strategy_rest","braintreeCardComponent","paypalPaymentComponent","getBraintreeCardComponentOrThrow","getPayPalInstruments","threeDSToken","mapToPayPalAddress","binGuest","verifyError","braintreePaymentProviderCustomer","braintreeFastlaneCustomer","selectedInstruments","create_braintree_fastlane_payment_strategy","BraintreeVisaCheckoutPaymentStrategy","visaCheckoutSdk","braintree_visa_checkout_payment_strategy_rest","create_braintree_visa_checkout_payment_strategy","BraintreeVenmoPaymentStrategy","venmoOptions","braintreevenmo","initializeBraintreeVenmo","braintree_venmo_payment_strategy_rest","isBraintreeVenmoWebFallbackSupport","mobileWebFallBack","braintreeVenmoTokenize","create_braintree_venmo_payment_strategy","BraintreeCreditCardPaymentStrategy","braintreeHostedForm","isHostedPaymentFormEnabled","unsupportedCardBrands","isHostedFormInitialized","shouldInitializeBraintreeFastlane","braintree_credit_card_payment_strategy_rest","prepareHostedPaymentData","isPaymentMethodInitialized","commonPaymentData","isSubmittingWithStoredCard","shouldPerform3DSVerification","tokenizeForStoredCardVerification","verifyCardWithHostedForm","prepareAdditionalActionPaymentData","storedCreditCardNonce","isBraintreePaymentRequest3DSError","newPaymentData","isHostedFormEnabled","braintreeCustomer","isBraintreeFormFieldsMap","isBraintreeHostedFormError","invalidFieldKeys","BraintreeHostedFormType","BraintreeHostedForm","isInitializedHostedForm","handleBlur","mapErrors","handleFocus","handleCardTypeChange","cards","handleInputSubmitRequest","handleValidityChange","isValidForm","StoredCardVerification","mapFieldOptions","createHostedFields","mapStyleOptions","mapBillingAddress","mapTokenizeError","hostedFields","hostedFieldsOptions","preventCursorJumps","supportedCardBrands","cardBrand","is_braintree_supported_card_brand","internalLabel","mapStyles","isValidParam","isEmpty","isPotentiallyValid","fieldKey","createInvalidError","isStoredCard","createRequiredError","formFields","create_braintree_credit_card_payment_strategy","CreditCardPaymentStrategy","_isHostedPaymentFormEnabled","_shouldRenderHostedForm","_executeWithHostedForm","_executeWithoutHostedForm","_isHostedFieldAvailable","paymentSettings","bigpayBaseUrl","createHostedForm","_hostedForm","credit_card_payment_strategy_rest","__WEBPACK_EXTERNAL_MODULE_lodash_values__","CBAMPGSPaymentStrategy","cbaMGPSScriptLoader","isTestModeFlagEnabled","isCBAMPGSPaymentMethodLike","threeDSjs","isConfigured","wsVersion","retryState","storeId","transactionId","initiateAuthentication","msg","gatewayRecommendation","restApiResponse","authenticationStatus","authenticatePayer","attempt","cba_mpgs_payment_strategy_awaiter","cause","fullScreenRedirect","CBAMPGSScriptLoader","ThreeDS","create_cba_mpgs_payment_strategy","AdditionalActionType","CheckoutComCustomPaymentStrategy","checkoutcom_custom_payment_strategy_rest","_processResponse","loadCurrentOrder","additionalActionRequired","OffsiteRedirect","_performRedirect","CheckoutComFawryPaymentStrategy","checkoutcom_fawry_payment_strategy_rest","_createFormattedPayload","fawryPaymentData","customerMobile","create_checkoutcom_fawry_payment_strategy","isThreeDSecureRequiredError","CheckoutComCreditCardPaymentStrategy","checkoutcom_credit_card_payment_strategy_rest","_handleThreeDSecure","callback_url","PaReq","TermUrl","MD","create_checkoutcom_credit_card_payment_strategy","CheckoutComSEPAPaymentStrategy","checkoutcom_sepa_payment_strategy_rest","create_checkoutcom_sepa_payment_strategy","CheckoutComiDealPaymentStrategy","checkoutcom_ideal_payment_strategy_rest","create_checkoutcom_ideal_payment_strategy","DOCUMENT_SUPPORTED_APMS","CheckoutComAPMPaymentStrategy","checkoutcom_apm_payment_strategy_rest","ccDocument","create_checkoutcom_apm_payment_strategy","ClearpayPaymentStrategy","_clearpayScriptLoader","_clearpaySdk","_isCountrySupported","_redirectToClearpay","ClearpayScriptLoader","_getScriptUrl","httpsEnabled","create_clearpay_payment_strategy","create_credit_card_payment_strategy","CardinalThreeDSecureFlow","_cardinalClient","prepare","_getClientToken","hostedForm","getCardInstrument","getBin","runBinProcess","__WEBPACK_EXTERNAL_MODULE_lodash_merge__","getThreeDSecureData","_getOrderData","CardinalSignatureValidationErrors","CardinalEventType","CardinalInitializationType","CardinalValidatedAction","CardinalPaymentType","CardinalTriggerEvents","CardinalPaymentBrand","CardinalSignatureVerification","CardinalClient","_provider","_testMode","_configurationToken","_sdk","_getClientSDK","SetupCompleted","off","Validated","ActionCode","ErrorNumber","ErrorDescription","setup","Init","jwt","binNumber","BinProcess","Status","orderData","Success","NoAction","Payment","ExtendedData","SignatureVerification","Failure","continueObject","AcsUrl","Payload","partialOrder","_mapToPartialOrder","continue","CCA","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","CardinalScriptLoader","Cardinal","CyberSourcePaymentStrategy","_threeDSecureFlow","create_cybersource_payment_strategy","CardinalThreeDSecureFlowV2","xid","_getBin","_submitPayment","threeDsResult","threeDsToken","isCreditCardInstrument","hostedFormBin","CyberSourceV2PaymentStrategy","create_cybersourcev2_payment_strategy","isAdditionalActionRequiredErrorResponse","GooglePayAdyenV2","googlePayToken","GooglePayPaymentStrategy","_isDeinitializationBlocked","_loadingIndicator","walletButton","google_pay_payment_strategy_rest","extraData","_clickListener","google_pay_payment_strategy_awaiter","_isDirectPayOnClickEnabled","_interactWithPaymentSheetAndPay","_toggleBlockDeinitialization","isGooglePayDontOverrideAddresssExperimentOn","freshPaymentMethod","_getIsSignedInOrThrow","_handleOfferTrigger","isSignedIn","isBlocked","create_google_pay_adyenv2_payment_strategy","GooglePayAdyenV3","create_google_pay_adyenv3_payment_strategy","create_google_pay_authorizenet_payment_strategy","create_google_pay_checkoutcom_payment_strategy","create_google_pay_cybersource_payment_strategy","create_google_pay_orbital_payment_strategy","create_google_pay_stripe_payment_strategy","create_google_pay_worldpayaccess_payment_strategy","create_google_pay_braintree_payment_strategy","ConfirmOrderStatus","types_PayPalCommerceIntent","GooglePayPaypalCommercePaymentStrategy","_payPalCommerceSdk","getOrderId","confirmOrderData","confirmOrder","payPalSDK","PayerActionRequired","initiatePayerAction","create_google_pay_paypal_commerce_payment_strategy","types_ConfirmOrderStatus","types_BigCommercePaymentsIntent","GooglePayBigCommercePaymentsPaymentStrategy","_payPalSdkHelper","create_google_pay_bigcommerce_payments_payment_strategy","create_google_pay_tdonlinemart_payment_strategy","PaymentExecuteError","HummPaymentStrategy","humm_payment_strategy_rest","processable","isOffsiteRedirectResponse","handleOffsiteRedirectResponse","create_humm_payment_strategy","supportedCountries","supportedCountriesRequiringStates","KlarnaPaymentStrategy","klarnaScriptLoader","klarnaCredit","unsubscribe","loadWidget","klarna_payment_strategy_rest","authorization_token","authorizationToken","authorize","initializePayment","client_token","getUpdateSessionData","mapToKlarnaAddress","needsStateCode","klarnaAddress","street_address","family_name","street_address2","updateSessionData","res","approved","show_form","KlarnaScriptLoader","klarnaWindow","Credit","create_klarna_payment_strategy","KlarnaV2PaymentStrategy","klarnav2ScriptLoader","klarnav2TokenUpdater","klarnaPayments","loadPaymentsWidget","klarnav2_payment_strategy_rest","klarnaMultipleRadioButton","klarnaOrderInitialization","isKlarnaMultipleRadioButtonEnabled","authorizeOrThrow","klarnav2","updateClientToken","payment_method_category","enableBillie","organization_name","KlarnaV2ScriptLoader","Payments","KlarnaV2TokenUpdater","create_klarnav2_payment_strategy","LegacyPaymentStrategy","create_legacy_payment_strategy","MolliePaymentMethodType","methodsNotAllowedWhenDigitalOrder","MolliePaymentStrategy","mollieScriptLoader","mollie","controllers","__WEBPACK_EXTERNAL_MODULE_lodash_each__","controller","initializeOptions","isCreditCard","shouldShowTSVHostedForm","mountCardVerificationfields","mollieClient","loadMollieJs","mountElements","disableButton","loadPaymentMethodsAllowed","mollie_payment_strategy_rest","executeWithVaulted","executeWithCC","executeWithAPM","cardHolderElement","cardNumberElement","verificationCodeElement","expiryDateElement","getMollieClient","createToken","shopper_locale","getShopperLocale","CREDIT_CARD","isHostedFieldAvailable","mollie_payment_strategy_awaiter","getInitializeOptions","testmode","cardNumberId","cardCvcId","cardExpiryId","cardHolderId","createComponent","cartDigitalItems","paragraph","unsupportedMethodMessage","MollieScriptLoader","mollieHostWindow","isMollieWindow","Mollie","create_mollie_payment_strategy","moneris_payment_strategy_IFRAME_NAME","MonerisPaymentStrategy","moneris","monerisOptions","profileId","createIframe","moneris_payment_strategy_rest","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","__WEBPACK_EXTERNAL_MODULE_lodash_map__","allow","monerisResponse","responseCode","dataKey","create_moneris_payment_strategy","OfflinePaymentStrategy","create_offline_payment_strategy","OffsitePaymentStrategy","offsite_payment_strategy_rest","orderPayload","_shouldSubmitFullPayload","create_offsite_payment_strategy","utils_get_paypal_messages_styles_from_bnpl_config","PayPalCommercePaymentStrategy","payPalSdkScriptLoader","paypal_commerce_payment_strategy_rest","isRedirectActionError","isPaypalCommerceAppSwitchEnabled","isPaypalProviderError","create_paypal_commerce_payment_strategy","PayPalCommerceCreditPaymentStrategy","paypalOptions","paypal_commerce_credit_payment_strategy_rest","create_paypal_commerce_credit_payment_strategy","PayPalCommerceVenmoPaymentStrategy","paypal_commerce_venmo_payment_strategy_rest","create_paypal_commerce_venmo_payment_strategy","paypal_commerce_constants_LOADING_INDICATOR_STYLES","PayPalCommerceAlternativeMethodsPaymentStrategy","isOrderApprovedProcessing","paypalcommercealternativemethods","paypal_commerce_alternative_methods_payment_strategy_rest","paypal_commerce_alternative_methods_payment_strategy_awaiter","OXXO","bcOrderId","create_paypal_commerce_alternative_methods_payment_strategy","PayPalCommerceCreditCardsPaymentStrategy","paypalcommercecreditcards","paypalCommerceInitializationOptions","paypal_commerce_credit_cards_payment_strategy_rest","paypal_commerce_credit_cards_payment_strategy_awaiter","paypalCommercePaymentProviderCustomer","isPayPalCommerceAnalyticsV2Enabled","create_paypal_commerce_credit_cards_payment_strategy","PaypalCommerceRatepayPaymentStrategy","paypalCommerceService","paypalcommerceratepay","paypal_commerce_ratepay_payment_strategy_rest","create_paypal_commerce_ratepay_payment_strategy","is_paypal_fastlane_customer_isPayPalFastlaneCustomer","PaypalCommerceFastlanePaymentStrategy","paypal_commerce_fastlane_payment_strategy_rest","isPaypalFastlaneRequestError","create_paypal_commerce_fastlane_payment_strategy","paypal_express_types_PaypalButtonStyleLayoutOption","paypal_express_types_PaypalButtonStyleSizeOption","paypal_express_types_PaypalButtonStyleColorOption","paypal_express_types_PaypalButtonStyleLabelOption","paypal_express_types_PaypalButtonStyleShapeOption","paypal_express_types_PaymentStatusTypes","PaypalExpressPaymentStrategy","useRedirectFlow","paypalexpress","isInContextEnabled","loadPaypalSDK","closeFlow","isAcknowledgedOrFinalized","getPaymentRedirectUrl","initXO","startFlow","PaypalScriptLoader","create_paypal_express_payment_strategy","PaypalProPaymentStrategy","threeDSecureFlow","create_paypal_pro_payment_strategy","SagePayPaymentStrategy","_isThreeDSTwoExperimentOn","create_sage_pay_payment_strategy","ExternalPaymentStrategy","external_payment_strategy_rest","_isAdditionalActionRequired","SezzlePaymentStrategy","create_sezzle_payment_strategy","SquareIntent","SquareV2PaymentProcessor","applicationId","locationId","square","_payments","_formValidationSubscription","_card","destroy","initializeCard","onValidationChange","_getPayments","_subscribeToFormValidation","_getCard","verifyBuyer","CHARGE","_chargeVerifyBuyer","_storeVerifyBuyer","blacklist","Set","eventObservables","currentState","isCompletelyValid","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_distinctUntilChanged__","_mapToSquareBillingContact","STORE","SquareV2PaymentStrategy","_squareV2PaymentProcessor","squarev2","_getVaultedInstrumentPayload","_getCardPayload","shouldVerify","cardTokenizationResult","isSquareV2ApiV2Enabled","tokenForSavingCard","store_card_nonce","store_card_token","verificationToken","_getSquareCardIdOrThrow","three_d_secure","SquareV2WebPaymentsSdkEnv","SquareV2ScriptLoader","LIVE","isSquareV2Window","assertSquareV2Window","Square","create_squarev2_payment_strategy","isIndividualCardElementOptions","individualCardElementOptions","cardNumberElementOptions","cardCvcElementOptions","cardExpiryElementOptions","IconStyle","stripev3_StripeElementType","stripev3_StripePaymentMethodType","StripeV3ErrorType","StripeV3Error","AuthFailure","APM_REDIRECT","Alipay","StripeV3PaymentStrategy","stripev3","isDeinitialize","useIndividualCardFields","allowRedisplayForStoredInstruments","_allowRedisplayForStoredInstruments","stripeV3Client","mountCardVerificationFields","mountCardFields","stripev3_payment_strategy_rest","shouldSubmitOrderBeforeLoadingAPM","confirmStripePayment","buildPaymentPayload","handleEmptyPaymentIntentError","unmountElement","isAuthError","getStripeJs","confirmAlipayPayment","handleActions","confirmIdealPayment","Sepa","confirmSepaDebitPayment","getStripeCardElements","getStripeElement","mapStripeBillingDetails","createPaymentMethod","stripeCardElements","zipCodeElementOptions","isBillingAddressLike","stripePaymentMethodType","cardExpiryElement","cardCvcElement","CardCvc","needsConfirm","StripeV3ScriptLoader","create_stripev3_payment_strategy","supportedLocales","ar","bg","cs","da","el","en","et","fi","fil","fr","he","hr","hu","it","ja","ko","lt","lv","ms","mt","nb","nl","pl","pt","ro","ru","sk","sl","sv","th","tr","vi","zh","formatLocale","localeLanguage","countryLocales","formattedLocale","StripeUPEPaymentStrategy","_loadStripeElement","stripe_upe_payment_strategy_rest","_stripeUPEClient","_executeWithVaulted","_executeWithStripeConfirmation","_processAdditionalActionWithStripeConfirmation","_processVaultedAdditionalAction","initStripeElementUpdateTrigger","enableLink","_loadStripeJs","_isStripeElementUpdateEnabled","wallets","_getStripeElementTerms","READY","_updateStripeLinkStateByElementType","_updateStripeElement","sendSecondPaymentRequestOnStripeError","paymentPayloadWithError","client_side_error","shouldShowTerms","terms","paymentElementType","isStripeLinkElementType","create_stripe_upe_payment_strategy","isStripePaymentEvent","StripeOCSPaymentStrategy","_initializeStripeElement","stripe_ocs_payment_strategy_rest","customerSessionToken","fonts","paymentMethodSelect","handleClosePaymentMethod","togglePreloader","customerSessionClientSecret","savePaymentMethod","maxVisiblePaymentMethods","LOADER_START","_onStripeElementChange","_collapseStripeElement","collapse","paymentMethodOptions","us_bank_account","_shouldSaveInstrument","tokenizedOptions","_getTokenizedOptions","selectedMethodId","client_secret","paymentIntentClientSecret","payment_method_options","collapsed","setupFutureUsage","setup_future_usage","ON_SESSION","OFF_SESSION","tokenized_ach","create_stripe_ocs_payment_strategy","StripeCSPaymentStrategy","_initStripeCheckoutSession","_updateStripeShopperData","_initializePaymentElement","_initializeAdaptivePricingElement","stripe_cs_payment_strategy_rest","_updateCheckoutSessionData","getPaymentElement","currencySelectorElement","getCurrencySelectorElement","adaptivePricing","allowed","adaptivePricingEnabled","_getStripeElement","_getStripeActionsOrThrow","createPaymentElement","newVaultedStripeInstrument","existingStripeSavedPaymentMethods","_getStripeSavedPaymentMethodsOrThrow","session","_confirmStripePayment","newStripeSavedPaymentMethods","checkoutSessionId","checkoutSessionStatus","_getNewVaultedStripeInstrument","paymentStatus","Paid","stripeActions","_updateStripeEmail","_updateStripeShippingAddress","_updateStripeBillingAddress","updateEmail","savedPaymentMethods","existingMethod","currencySelectorContainerId","_getCurrencySelectorElement","_initAdaptivePricingEvents","createCurrencySelectorElement","stripe_cs_payment_strategy_awaiter","stripeCurrencyCode","isCustomerCurrencySelected","customerCurrency","create_stripe_cs_payment_strategy","FieldType","TDOnlineMartPaymentStrategy","tdOnlineMartScriptLoader","tdInputs","CARD_NUMBER","CVV","EXPIRY","tdOnlineMartClient","loadTDOnlineMartJs","mountHostedFields","td_online_mart_payment_strategy_rest","getPaymentPayloadOrThrow","processWithAdditionalAction","inputElement","digitalItemsInCart","shouldAddVerificationToken","isTrustedVaultingInstrument","getTokenOrThrow","throwTokenizationError","getHostedFieldsOptions","getTDOnlineMartClientOrThrow","inputId","isTdOnlineMartAdditionalAction_isTdOnlineMartAdditionalAction","isCreateTokenError","classes","TDOnlineMartScriptLoader","tdOnlineMartWindow","customcheckout","create_td_online_mart_payment_strategy","PAYMENT_CANNOT_CONTINUE","worldpayaccess_payment_strategy_submit","WorldpayAccessPaymentStrategy","worldpay","_submitAdditionalAction","messageEventListener","worldpayaccess_payment_strategy_awaiter","_isValidJsonWithSessionId","iframeHidden","SessionId","submitError","onLoadError","_createHiddenIframe","formId","inputBin","source_id","inputJWT","match","srcdoc","outerHTML","str","create_worldpayaccess_payment_strategy","WorldpayAccessOpenBankingPaymentStrategy","_buildOpenBankingSubmitPayment","_isWorldpayAccessRedirectResponse","open_banking","create_worldpayaccess_open_banking_payment_strategy","StorefrontPaymentRequestSender","saveExternalId","externalId","ZipPaymentStrategy","storefrontPaymentRequestSender","zip_payment_strategy_rest","_prepareForReferredRegistration","create_zip_payment_strategy","CountryActionType","OrderActionType","CountryActionCreator","_countryRequestSender","loadCountries","LoadCountriesRequested","LoadCountriesSucceeded","LoadCountriesFailed","CountryRequestSender","CartConsistencyError","CartStockPositionsChangedError","changedItemIds","OrderTaxProviderUnavailableError","MissingShippingMethodError","InvalidShippingAddressError","OrderRequestSender","loadOrder","checkoutVariant","SpamProtectionNotCompletedError","PaymentMethodActionType","OrderActionCreator","_orderRequestSender","_checkoutValidator","LoadOrderRequested","LoadOrderSucceeded","LoadOrderFailed","loadOrderPayments","LoadOrderPaymentsRequested","LoadOrderPaymentsSucceeded","LoadOrderPaymentsFailed","_getCurrentOrderId","SubmitOrderRequested","externalSource","getExternalSource","variantIdentificationToken","getVariantIdentificationToken","shouldExecuteSpamCheck","_mapToOrderRequestBody","customerMessage","SubmitOrderSucceeded","SubmitOrderFailed","FinalizeOrderRequested","FinalizeOrderSucceeded","FinalizeOrderFailed","order_action_creator_rest","createPaymentClient","paymentClient","__WEBPACK_EXTERNAL_MODULE__bigcommerce_bigpay_client_fce6db19_createClient__","setHost","isPaymentMethod","PaymentMethodActionCreator","loadPaymentMethodsById","methodIds","LoadPaymentMethodsRequested","payment_method_action_creator_awaiter","LoadPaymentMethodsSucceeded","LoadPaymentMethodsFailed","sessionHash","methods","LoadPaymentMethodRequested","LoadPaymentMethodSucceeded","LoadPaymentMethodFailed","payment_method_action_creator_decorate","PaymentMethodRequestSender","order_finalization_not_required_error_OrderFinalizationNotRequiredError","PaymentStrategyActionType","PaymentStrategyType","payment_strategy_type","PaymentStrategyWidgetActionCreator","PaymentStrategyActionCreator","_orderActionCreator","_paymentStrategyWidgetActionCreator","isPaymentDataRequired","NO_PAYMENT_DATA_REQUIRED","FinalizeRequested","_loadOrderPaymentsIfNeeded","payment_strategy_action_creator_awaiter","FinalizeSucceeded","FinalizeFailed","paymentStrategies","getByMethod","CartComparator","cartA","cartB","_normalize","itemA","itemB","variantId","localeCompare","extendedSalePrice","recipient","giftWrapping","CartChangedError","previous","updated","CheckoutValidator","comparator","_compareCoupons","_compareGiftCertificates","_getComparableCheckout","couponsA","couponsB","giftCertificatesA","giftCertificatesB","BrowserStorage","_namespace","rawValue","withNamespace","getItemOnce","CardingProtectionChallengeNotCompletedError","CardingProtectionFailedError","HostedFieldEventType","HostedInputEventType","PaymentHumanVerificationHandler","handle","errorOrId","handleWithRecaptchaSitekey","handleWithPaymentHumanVerificationRequestError","_isPaymentHumanVerificationRequest","_initialize","_performRecaptcha","payment_human_verification_handler_awaiter","human_verification_token","cardingProtectionElementId","cardingProtectionElement","mapFromPaymentErrorResponse","joinErrors","InvalidHostedFormConfigError","InvalidHostedFormError","InvalidHostedFormValueError","__WEBPACK_EXTERNAL_MODULE_lodash_flatMap__","fieldErrors","HostedField","_type","_placeholder","_accessibilityLabel","_styles","_eventPoster","_eventListener","_detachmentObserver","_checkoutId","_cardInstrument","overflow","getType","hosted_field_awaiter","AttachRequested","cardInstrument","fontUrls","_getFontUrls","AttachSucceeded","AttachFailed","SubmitRequested","SubmitSucceeded","SubmitFailed","_isSubmitErrorEvent","submitStoredCardForm","StoredCardRequested","StoredCardSucceeded","StoredCardFailed","validateForm","ValidateRequested","family","PaymentActionType","HostedForm","_fields","_payloadTransformer","_eventCallbacks","_paymentHumanVerificationHandler","hosted_form_awaiter","Blurred","CardTypeChanged","Focused","Entered","_cardType","BinChanged","_bin","getCardType","_getFirstField","otherFields","__WEBPACK_EXTERNAL_MODULE_lodash_without__","otherField","submitStoredCard","is_vaulted_instrument_isVaultedInstrument","HostedFormOrderDataTransformer","getConfig","instrumentMeta","getInstrumentsMeta","orderMeta","getOrderMeta","paymentMethodMeta","getPaymentMethodsMeta","authToken","vaultAccessToken","HostedFormFactory","fieldOptions","_getCardInstrument","__WEBPACK_EXTERNAL_MODULE_lodash_pick__","MissingPaymentInstrument","PaymentActionCreator","_paymentRequestSender","_paymentRequestTransformer","InitializeOffsitePaymentRequested","InitializeOffsitePaymentSucceeded","InitializeOffsitePaymentFailed","SubmitPaymentRequested","payment_action_creator_awaiter","SubmitPaymentSucceeded","SubmitPaymentFailed","PaymentRequestSender","_client","_transformResponse","statusText","mapToInternalAddress","addressId","is_billing_address_like_isBillingAddressLike","province","provinceCode","postCode","couponTypes","mapToInternalCoupon","discount","discountType","couponType","mapToInternalGiftCertificate","used","remainingBalance","remaining","balance","purchaseDate","mapToDiscountNotifications","promotions","notifications","promotion","banners","banner","placeholders","messageHtml","mapToInternalLineItems","itemMap","idKey","amountAfterDiscount","integerAmountAfterDiscount","integerUnitPrice","integerUnitPriceAfterDiscount","integerDiscount","sender","mapGiftCertificateToInternalLineItem","extendedListPrice","downloadsPageUrl","downloadPageUrl","mapToInternalLineItem","mapToInternalLineItemType","mapToInternalCart","sum","discountNotifications","totalDiscountedAmount","certificate","appliedGiftCertificates","__WEBPACK_EXTERNAL_MODULE_lodash_keyBy__","amountBeforeDiscount","shippingCostBeforeDiscount","integerAmountBeforeDiscount","taxSubtotal","handling","handlingCostTotal","CheckoutButtonMethodType","checkout_button_method_type","mapToInternalCustomer","customerGroupName","customerGroup","CardExpiryFormatter","RegExp","trimmedMonth","trimmedYear","toObject","CardNumberFormatter","__WEBPACK_EXTERNAL_MODULE_card_validator_0e6920dd_number__","__WEBPACK_EXTERNAL_MODULE_lodash_max__","__WEBPACK_EXTERNAL_MODULE_card_validator_0e6920dd_creditCardType__","lengths","unformattedValue","unformat","gaps","gapIndex","mapToInternalOrder","customerCanBeCreated","mapToInternalOrderPayment","baseAmount","callbackUrl","mapToGiftCertificates","socialData","mapToInternalSocialDataList","hasDigitalItems","isDownloadable","isComplete","mapToStoreCredit","orderAmountAsInteger","isDefaultOrderPayment","helpText","instructions","socialDataObject","socialMedia","image","shareText","sharingLink","channelName","channel","channelCode","mapToInternalShippingOption","isSelected","price","selected","transitTime","PaymentRequestTransformer","_cardExpiryFormatter","_cardNumberFormatter","getShippingOption","contextConfig","paymentMeta","internalCustomer","formattedInstrument","is_vaulted_instrument_isFormattedVaultedInstrument","_transformPaymentMethod","quoteMeta","geoCountryCode","transformWithHostedFormData","_transformHostedInputValues","BRAINTREE_VENMO","BRAINTREE_PAYPAL","hostedFormNonce","isBopisEnabled","bopis","requiredAddress","isPickup","selectedPickupOption","isPPSDKPaymentMethod","initializationStrategy","PPSDK","PaymentStrategyRegistry","_getToken","KLARNAV2","_hasFactoryForMethod","OFFLINE","payment_argument_invalid_error_PaymentArgumentInvalidError","credit_card_payment_strategy_CreditCardPaymentStrategy","_paymentActionCreator","_hostedFormFactory","credit_card_credit_card_payment_strategy_rest","ConvergePaymentStrategy","orderActionCreator","paymentActionCreator","hostedFormFactory","payment_method_cancelled_error_PaymentMethodCancelledError","PENDING_REDIRECT_PARAM","RedirectionState","_isRedirecting","currentUrlHasRedirectingParam","isRedirecting","setRedirecting","setRedirectingParamOnUrl","removeRedirectingParamFromUrl","getCurrentUrl","__WEBPACK_EXTERNAL_MODULE_query_string_2dcf3be8_parseUrl__","replaceCurrentUrl","history","replaceState","currentUrl","updatedUrl","__WEBPACK_EXTERNAL_MODULE_query_string_2dcf3be8_stringifyUrl__","__WEBPACK_EXTERNAL_MODULE_query_string_2dcf3be8_exclude__","isAnyContinue","__WEBPACK_EXTERNAL_MODULE_lodash_overSome__","__WEBPACK_EXTERNAL_MODULE_lodash_get__","__WEBPACK_EXTERNAL_MODULE_lodash_isString__","__WEBPACK_EXTERNAL_MODULE_lodash_isUndefined__","redirect_isParameters","availableMethods","isParameters","ContinueHandler","_humanVerificationHandler","form_fields","redirectionState","handleRedirect","available_methods","humanVerificationHandler","human_verification_awaiter","handleHumanVerification","humanVerification","StepHandler","_continueHandler","isSuccess","isContinue","isFailure","failureResponse","isError","COMPLETED_PAYMENTS_KEY","PPSDKCompletedPayments","_browserStorage","isCompleted","getCompletedPayments","setCompleted","completedPayments","setCompletedPayments","SubStrategyType","PPSDKStrategy","_subStrategyRegistry","_paymentResumer","browserStorage","_completedPayments","ppsdk_strategy_rest","_subStrategy","subStrategy","getPPSDKMethod","getToken","__WEBPACK_EXTERNAL_MODULE_lodash_cond__","__WEBPACK_EXTERNAL_MODULE_lodash_constant__","CARD","NONE","__WEBPACK_EXTERNAL_MODULE_lodash_stubTrue__","UNSUPPORTED","SubStrategyRegistry","CardSubStrategy","_ppsdkStepHandler","card_sub_strategy_awaiter","NoneSubStrategy","_stepHandler","payment_method_id","PaymentProviderCustomerType","RemoteCheckoutActionType","PaymentResumer","auth_token","CartRequestSender","PaymentProviderCustomerActionCreator","providerCustomerData","UpdatePaymentProviderCustomer","ConsignmentActionType","RemoteCheckoutActionCreator","_remoteCheckoutRequestSender","initializeBilling","InitializeRemoteBillingRequested","InitializeRemoteBillingSucceeded","InitializeRemoteBillingFailed","initializeShipping","InitializeRemoteShippingRequested","InitializeRemoteShippingSucceeded","InitializeRemoteShippingFailed","InitializeRemotePaymentRequested","InitializeRemotePaymentSucceeded","InitializeRemotePaymentFailed","loadSettings","LoadRemoteSettingsRequested","LoadRemoteSettingsSucceeded","LoadRemoteSettingsFailed","SignOutRemoteCustomerRequested","SignOutRemoteCustomerSucceeded","SignOutRemoteCustomerFailed","ForgetCheckoutRemoteCustomerRequested","remote_checkout_action_creator_awaiter","ForgetCheckoutRemoteCustomerSucceeded","ForgetCheckoutRemoteCustomerFailed","UpdateRemoteCheckout","RemoteCheckoutRequestSender","methodName","generateToken","trackAuthorizationEvent","ConsignmentActionCreator","_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","consignmentInMemory","getConsignmentById","_isUpdateConsignmentRequest","itemId","_hydrateLineItems","lineItemIds","existingItem","sharedItem","concat","DEFAULT_INCLUDES","ConsignmentRequestSender","consignment_request_sender_rest","ShippingCountryActionType","StoreCreditActionType","ShippingCountryActionCreator","_shippingCountryRequestSender","checkoutData","LoadShippingCountriesRequested","LoadShippingCountriesSucceeded","LoadShippingCountriesFailed","ShippingCountryRequestSender","SubscriptionsActionType","StoreCreditActionCreator","_storeCreditRequestSender","ApplyStoreCreditRequested","store_credit_action_creator_awaiter","checkoutVersion","removeStoreCredit","ApplyStoreCreditSucceeded","ApplyStoreCreditFailed","StoreCreditRequestSender","UpdateSubscriptionsError","SubscriptionsActionCreator","_subscriptionsRequestSender","subscriptions","UpdateSubscriptionsRequested","subscriptions_action_creator_awaiter","UpdateSubscriptionsSucceeded","UpdateSubscriptionsFailed","SubscriptionsRequestSender","isPlainObject","__WEBPACK_EXTERNAL_MODULE_lodash_isPlainObject__","cloneDeep","__WEBPACK_EXTERNAL_MODULE_lodash_memoize__","cloneDeepSafe","cache","cloneResult","createPaymentIntegrationSelectors","getPaymentTokenOrThrow","getPaymentIdOrThrow","getPaymentStatusOrThrow","getPaymentRedirectUrlOrThrow","getShippingAddressOrThrow","getShippingAddresses","getShippingAddressesOrThrow","shippingCountries","InstrumentActionType","DefaultPaymentIntegrationService","_storeProjectionFactory","_billingAddressActionCreator","_consignmentActionCreator","_paymentMethodActionCreator","_cartRequestSender","_storeCreditActionCreator","_couponActionCreator","_paymentProviderCustomerActionCreator","_shippingCountryActionCreator","_remoteCheckoutActionCreator","_storeProjection","subscriber","filters","initializeOffsitePaymentConfig","buyNowCartRequestBody","handlePaymentHumanVerification","queueId","PaymentIntegrationStoreProjectionFactory","_transformSelectors","createPaymentIntegrationService","storeProjectionFactory","checkoutActionCreator","checkoutValidator","billingAddressActionCreator","consignmentActionCreator","paymentMethodActionCreator","paymentHumanVerificationHandler","customerActionCreator","storeCreditActionCreator","applyCouponActionCreator","spamProtection","spamProtectionRequestSender","spamProtectionActionCreator","cartRequestSender","paymentProviderCustomerActionCreator","shippingCountryActionCreator","remoteCheckoutActionCreator","paymentStrategyWidgetActionCreator","InstrumentActionCreator","_instrumentRequestSender","loadInstruments","LoadInstrumentsRequested","_getSessionContext","_getCurrentAccessToken","_getShippingAddress","_getValidAccessToken","currentToken","LoadInstrumentsSucceeded","LoadInstrumentsFailed","deleteInstrument","DeleteInstrumentRequested","DeleteInstrumentSucceeded","DeleteInstrumentFailed","_isValidVaultAccessToken","newDate","setMinutes","getMinutes","addMinutes","vaultAccessExpiry","valueOf","getVaultAccessToken","isTransactional","PickupOptionActionType","ShippingStrategyActionType","InstrumentResponseTransformer","transformResponse","instrument_response_transformer_rest","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","InstrumentRequestSender","_transformer","requestContext","_loadInstrumentsWithAddress","_loadInstruments","deleteShopperInstrument","errorResponse","loadInstrumentsWithAddress","PickupOptionActionCreator","_pickupOptionRequestSender","loadPickupOptions","apiQuery","_hydrateApiQuery","LoadPickupOptionsRequested","fetchPickupOptions","LoadPickupOptionsSucceeded","LoadPickupOptionsFailed","consignmentLineItems","cartItems","searchArea","PickupOptionRequestSender","ShippingStrategyActionCreator","UpdateAddressRequested","UpdateAddressSucceeded","UpdateAddressFailed","selectOption","SelectOptionRequested","SelectOptionSucceeded","SelectOptionFailed","mergedOptions","shippingStrategies","instrument_UntrustedShippingCardVerificationType","AmazonPayV2ShippingStrategy","_amazonPayV2PaymentProcessor","_shippingStrategyActionCreator","updateAddressRequestBody","editAddressButtonId","shouldShowLoadingSpinner","_shouldShowLoadingSpinner","BraintreeFastlaneShippingStrategy","_braintreeIntegrationService","fastlane","fastlaneOptions","onPayPalFastlaneAddressChange","_shouldRunAuthenticationFlow","_runAuthenticationFlowOrThrow","_shouldUseBraintreeFastlaneShippingComponent","_handleBraintreeFastlaneShippingAddressChange","_getPayPalBillingAddress","paypalPhoneNumber","_mapPayPalToBcAddress","_mergeShippingAndBillingAddresses","_mapPayPalToBcInstrument","_getCountryNameByCountryCode","_normalizeAddress","selectedAddress","showShippingAddressSelector","paymentProviderCustomerAddresses","_filterAddresses","_isEqualAddresses","_getBraintreePaymentMethodOrThrow","isFastlaneEnabled","DefaultShippingStrategy","PayPalCommerceFastlaneShippingStrategy","_paypalSdkScriptLoader","_paypalCommerceFastlaneUtils","_shouldAuthenticateUserWithFastlane","_initializePayPalSdk","_authenticateUserWithFastlaneOtp","_shouldUsePayPalFastlaneShippingComponent","_handlePayPalShippingAddressChange","_getPayPalPaymentMethodOrThrow","_getPayPalCustomerAuthenticationState","paypalConnectSessionId","customerAuthenticationState","billingAddressEmail","SignInEmailActionType","StripeUPEShippingStrategy","_stripeScriptLoader","onChangeShipping","availableCountries","getStripeState","getShippingAddressFields","shippingFields","spacingUnit","shippingPhoneField","allowedCountries","validation","SPLIT","stripeState","shippingAddressElement","isNewAddress","sendData","phoneFieldRequired","SignInEmailActionCreator","sendSignInEmail","emailRequest","SendSignInEmailRequested","signin_email_action_creator_awaiter","SendSignInEmailSucceeded","SendSignInEmailFailed","SignInEmailRequestSender","ErrorMessageTransformer","_messageCustomizer","CheckoutService","_extensionEventBroadcaster","_b2bTokenActionCreator","_countryActionCreator","_customerStrategyActionCreator","_errorActionCreator","_giftCertificateActionCreator","_instrumentActionCreator","_paymentStrategyActionCreator","_pickupOptionActionCreator","_signInEmailActionCreator","_subscriptionsActionCreator","_extensionActionCreator","_errorTransformer","isDevelopment","isCheckoutServiceError","createCheckoutServiceErrorTransformer","notifyState","_dispatch","loadCheckoutAction","formFieldsAction","loadConfigAction","finalizeOrderIfNeeded","loadPaymentMethodByIds","deinitializePayment","loadBillingCountries","loadBillingAddressFields","loadShippingAddressFields","initializeCustomer","deinitializeCustomer","signInEmailRequest","createCustomerAccount","createCustomerAddress","deinitializeShipping","assignItemsToAddress","unassignItemsToAddress","selectConsignmentShippingOption","initializeSpamProtection","executeSpamCheck","clearExtensionCache","postMessageToExtension","handleExtensionCommand","handler","handleExtensionQuery","checkout_service_decorate","withMemoizedCombiner","creator","combiner","pop","combinerArgs","create_selector","__WEBPACK_EXTERNAL_MODULE_reselect_createSelector__","create_shallow_equal_selector","__WEBPACK_EXTERNAL_MODULE_reselect_createSelectorCreator__","__WEBPACK_EXTERNAL_MODULE_reselect_defaultMemoize__","__WEBPACK_EXTERNAL_MODULE_shallowequal_default__","UnrecoverableError","map_from_internal_error_response_joinErrors","timeout_error_TimeoutError","RequestErrorFactory","_factoryMethods","mapFromInternalErrorResponse","mapFromStorefrontErrorResponse","factoryMethod","createError","_getType","_isStorefrontErrorResponseBody","_isInternalErrorResponseBody","internalType","__WEBPACK_EXTERNAL_MODULE_lodash_last__","storefrontErrorResponse","internalErrorResponse","omitDeep","predicate","__WEBPACK_EXTERNAL_MODULE_lodash_transform__","clearErrorReducer","isClearErrorAction","objectA","objectB","isArrayEqual","isDateEqual","isRegExpEqual","keyFilter","keysA","keysB","isObjectEqual","objectSet","DEFAULT_STATE","statuses","b2bTokenReducer","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_combineReducers__","dataReducer","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_composeReducers__","errorsReducer","statusesReducer","reducer","currentValue","newValue","billing_address_state_DEFAULT_STATE","billingAddressReducer","billing_address_reducer_dataReducer","billing_address_reducer_errorsReducer","billing_address_reducer_statusesReducer","array_replace","arrayReplace","currentArray","newArray","matchObject","sameAsCurrentCount","sameAsNewCount","countSameAsReplaced","replacedValue","newItem","currentItem","object_merge","objectMerge","currentObject","newObject","cart_state_DEFAULT_STATE","cartReducer","cart_reducer_dataReducer","cart_reducer_errorsReducer","cart_reducer_statusesReducer","CheckoutButtonActionType","checkout_button_state_DEFAULT_STATE","DEFAULT_DATA_STATE","initializedContainers","DEFAULT_ERROR_STATE","DEFAULT_STATUS_STATE","checkoutButtonReducer","checkout_button_reducer_dataReducer","checkout_button_reducer_errorsReducer","checkout_button_reducer_statusesReducer","InitializeButtonSucceeded","DeinitializeButtonSucceeded","InitializeButtonRequested","InitializeButtonFailed","DeinitializeButtonRequested","DeinitializeButtonFailed","config_state_DEFAULT_STATE","configReducer","config_reducer_dataReducer","config_reducer_errorsReducer","config_reducer_statusesReducer","merged","coupon_state_DEFAULT_STATE","couponReducer","coupon_reducer_dataReducer","coupon_reducer_errorsReducer","coupon_reducer_statusesReducer","gift_certificate_state_DEFAULT_STATE","giftCertificateReducer","gift_certificate_reducer_dataReducer","gift_certificate_reducer_errorsReducer","gift_certificate_reducer_statusesReducer","customer_state_DEFAULT_STATE","customerReducer","customer_reducer_dataReducer","customer_reducer_errorsReducer","customer_reducer_statusesReducer","customer_strategy_state_DEFAULT_STATE","customerStrategyReducer","customer_strategy_reducer_dataReducer","customer_strategy_reducer_errorsReducer","customer_strategy_reducer_statusesReducer","initializeErrors","initializeMethodId","deinitializeError","deinitializeMethodId","signInError","signInMethodId","signOutError","signOutMethodId","executePaymentMethodCheckoutError","executePaymentMethodCheckoutMethodId","widgetInteractionError","widgetInteractionMethodId","isInitializing","isDeinitializing","isSigningIn","isSigningOut","isExecutingPaymentMethodCheckout","isWidgetInteracting","extension_state_DEFAULT_STATE","extensionReducer","extension_reducer_dataReducer","extension_reducer_errorsReducer","extension_reducer_statusesReducer","form_fields_state_DEFAULT_STATE","formFieldsReducer","form_fields_reducer_dataReducer","extraFields","extraFieldsReducer","form_fields_reducer_errorsReducer","form_fields_reducer_statusesReducer","country_state_DEFAULT_STATE","countryReducer","country_reducer_dataReducer","country_reducer_errorsReducer","country_reducer_statusesReducer","order_state_DEFAULT_STATE","orderReducer","order_reducer_dataReducer","order_reducer_errorsReducer","metaReducer","order_reducer_statusesReducer","order_billing_address_state_DEFAULT_STATE","orderBillingAddressReducer","order_billing_address_reducer_dataReducer","paymentReducer","payment_reducer_dataReducer","payment_method_state_DEFAULT_STATE","paymentMethodReducer","payment_method_reducer_dataReducer","payment_method_reducer_errorsReducer","payment_method_reducer_metaReducer","payment_method_reducer_statusesReducer","array","defaultPredicate","derivedPredicate","__WEBPACK_EXTERNAL_MODULE_lodash_findIndex__","mergeOrPush","methodA","methodB","loadMethodId","loadMethodError","isLoadingMethod","payment_strategy_state_DEFAULT_STATE","paymentStrategyReducer","payment_strategy_reducer_dataReducer","payment_strategy_reducer_errorsReducer","payment_strategy_reducer_statusesReducer","initializeError","executeError","executeMethodId","finalizeError","finalizeMethodId","isExecuting","isFinalizing","payment_provider_customer_state_DEFAULT_STATE","paymentProviderCustomerReducer","payment_provider_customer_reducer_dataReducer","instrument_state_DEFAULT_STATE","instrumentReducer","instrument_reducer_dataReducer","instrument_reducer_errorsReducer","instrument_reducer_metaReducer","instrument_reducer_statusesReducer","deleteError","failedInstrument","isDeleting","deletingInstrument","remote_checkout_state_DEFAULT_STATE","remoteCheckoutReducer","remote_checkout_reducer_dataReducer","consignment_state_DEFAULT_STATE","updateShippingOptionError","updateError","isUpdating","isUpdatingShippingOption","consignmentReducer","consignment_reducer_dataReducer","consignment_reducer_errorsReducer","consignment_reducer_statusesReducer","objectFlatten","flattened","keyString","objectWithSortedKeys","current","pickup_option_state_DEFAULT_STATE","pickupOptionReducer","pickup_option_reducer_dataReducer","pickup_option_reducer_errorsReducer","pickup_option_reducer_statusesReducer","sortedflattenedMeta","shipping_country_state_DEFAULT_STATE","shippingCountryReducer","shipping_country_reducer_dataReducer","shipping_country_reducer_errorsReducer","shipping_country_reducer_statusesReducer","shipping_strategy_state_DEFAULT_STATE","shippingStrategyReducer","shipping_strategy_reducer_dataReducer","shipping_strategy_reducer_errorsReducer","shipping_strategy_reducer_statusesReducer","updateAddressError","updateAddressMethodId","selectOptionError","selectOptionMethodId","isUpdatingAddress","isSelectingOption","signin_email_state_DEFAULT_STATE","signInEmailReducer","signin_email_reducer_dataReducer","signin_email_reducer_errorsReducer","signin_email_reducer_statusesReducer","store_credit_reducer_DEFAULT_STATE","storeCreditReducer","store_credit_reducer_errorsReducer","store_credit_reducer_statusesReducer","subscriptions_state_DEFAULT_STATE","subscriptionsReducer","subscriptions_reducer_errorsReducer","subscriptions_reducer_statusesReducer","checkout_state_DEFAULT_STATE","checkoutReducer","checkout_reducer_dataReducer","checkout_reducer_errorsReducer","checkout_reducer_statusesReducer","guard_guard","createFreezeProxy","proxy","iteratee","getPrototypeOf","traversePrototypeOf","charAt","__WEBPACK_EXTERNAL_MODULE__bigcommerce_data_store_76aed8d7_deepFreeze__","trap","createProxy","supported_payment_instruments","authorizenet","elavon","checkoutcom","sagepay","cybersource","cybersourcev2","bnz","converge","orbital","paymetric","cba_mpgs","worldpayaccess","tdonlinemart","normalize","__WEBPACK_EXTERNAL_MODULE_lodash_identity__","store_credit_state_DEFAULT_STATE","createInternalCheckoutSelectorsFactory","createB2BTokenSelector","getLoadError","loadError","__WEBPACK_EXTERNAL_MODULE__bigcommerce_memoize_bf7b411a_memoizeOne__","createB2BTokenSelectorFactory","createBillingAddressSelector","getUpdateError","getContinueAsGuestError","continueAsGuestError","isContinuingAsGuest","createBillingAddressSelectorFactory","createCartSelector","createCartSelectorFactory","createCheckoutButtonSelector","getInitializeError","getDeinitializeError","createCheckoutButtonSelectorFactory","createConfigSelector","getFlashMessages","filterType","flashMessages","formState","createConfigSelectorFactory","createCountrySelector","createCountrySelectorFactory","createCouponSelector","getCoupons","getRemoveError","removeCouponError","getApplyError","applyCouponError","isApplying","isApplyingCoupon","isRemoving","isRemovingCoupon","createCouponSelectorFactory","createCustomerSelector","getCreateAccountError","isCreatingCustomerAccount","isCreating","getCreateAddressError","createAddressError","isCreatingCustomerAddress","isCreatingAddress","createCustomerSelectorFactory","createCustomerStrategySelector","getSignInError","getSignOutError","getExecutePaymentMethodCheckoutError","getWidgetInteractionError","createCustomerStrategySelectorFactory","createGiftCertificateSelector","getGiftCertificates","removeGiftCertificateError","applyGiftCertificateError","isApplyingGiftCertificate","isRemovingGiftCertificate","createGiftCertificateSelectorFactory","createInstrumentSelector","getInstrumentsByPaymentMethod","paymentMethodKey","currentMethod","__WEBPACK_EXTERNAL_MODULE_lodash_isMatch__","supportedProvider","getDeleteError","createInstrumentSelectorFactory","createFormSelector","selectedCountry","processField","getBillingAddressFields","getCustomerAccountFields","getAddressExtraFields","itemtype","processCountry","subdivisions","requiresState","processProvince","hasPostalCodes","processsPostCode","createFormSelectorFactory","createPaymentMethodSelector","getPaymentMethods","getLoadMethodError","createPaymentMethodSelectorFactory","createPaymentStrategySelector","getExecuteError","getFinalizeError","getWidgetInteractingError","createPaymentStrategySelectorFactory","createPickupOptionSelector","getPickupOptions","pickupOptions","sortedFlattenedParams","createPickupOptionSelectorFactory","createPaymentProviderCustomerSelector","createPaymentProviderCustomerSelectorFactory","createRemoteCheckoutSelector","createRemoteCheckoutSelectorFactory","createShippingAddressSelector","shippingConsignment","shippingConsignments","createShippingAddressSelectorFactory","createShippingCountrySelector","createShippingCountrySelectorFactory","createShippingStrategySelector","getUpdateAddressError","getSelectOptionError","createShippingStrategySelectorFactory","createConsignmentSelector","isAddressEqual","addressA","addressB","getCreateError","getLoadShippingOptionsError","loadShippingOptionsError","getUnassignedItems","assignedLineItemIds","itemIds","getItemAssignmentError","getUpdateShippingOptionError","isLoadingShippingOptions","isAssigningItems","createConsignmentSelectorFactory","createCheckoutSelector","isExecutingSpamCheck","createCheckoutSelectorFactory","createOrderSelector","getOrderBillingAddress","currentPayment","createOrderSelectorFactory","createOrderBillingAddressSelector","createOrderBillingAddressSelectorFactory","createPaymentSelector","getInternalPayment","getGatewayPayment","getHostedPayment","providerType","internalPayment","MissingPaymentId","MissingPaymentStatus","MissingPaymentRedirectUrl","isPaymentDataSubmitted","createPaymentSelectorFactory","createStoreCreditSelector","applyError","createStoreCreditSelectorFactory","createSubscriptionsSelector","createSubscriptionsSelectorFactory","createSignInEmailSelector","getEmail","signInEmail","getSendError","sendError","isSending","createSignInEmailSelectorFactory","createExtensionSelector","createExtensionSelectorFactory","b2bToken","checkoutButton","orderBillingAddress","remoteCheckout","selectors","shouldWarnMutation","createCheckoutStore","initialStoreState","actionTransformer","requestErrorFactory","createRequestErrorFactory","action$","createInternalCheckoutSelectors","createCheckoutService","checkoutVariantIdentificationToken","experimentRequestSender","orderRequestSender","checkoutRequestSender","configActionCreator","subscriptionsActionCreator","formFieldsActionCreator","registryV2","paymentStrategyFactories","createPaymentStrategy","createPaymentStrategyRegistry","payment_strategies_namespaceObject","customerRegistryV2","customerStrategyFactories","createCustomerStrategy","createCustomerStrategyRegistry","customer_strategies_namespaceObject","extensionActionCreator","extensionMessenger","storeProjection","createCheckoutStoreSelector","getShippingOptions","getSelectedShippingOption","getBillingCountries","getSelectedPaymentMethod","getSignInEmail","getUserExperienceSettings","checkoutUserExperienceSettings","createCheckoutStoreSelectorFactory","createCheckoutStoreErrorSelector","getSelectShippingOptionError","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","getLoadB2BTokenError","getCreateCustomerAccountError","getCreateCustomerAddressError","getPickupOptionsError","getLoadExtensionsError","createCheckoutStoreErrorSelectorFactory","createCheckoutStoreStatusSelector","isPending","isSelectingShippingOption","isCustomerStepPending","isShippingStepPending","isPaymentStepPending","isSubmittingOrder","isLoadingCheckout","isUpdatingCheckout","isFinalizingOrder","isLoadingOrder","isLoadingCart","isLoadingBillingCountries","isLoadingShippingCountries","isLoadingPaymentMethods","isLoadingPaymentMethod","isInitializingPayment","isInitializingCustomer","isInitializedCustomer","isUpdatingBillingAddress","isUpdatingSubscriptions","isUpdatingShippingAddress","isUpdatingConsignment","isDeletingConsignment","isCreatingConsignments","isInitializingShipping","isApplyingStoreCredit","isLoadingInstruments","isDeletingInstrument","isLoadingConfig","isSendingSignInEmail","isLoadingB2BToken","isLoadingPickupOptions","createCheckoutStoreStatusSelectorFactory","createCheckoutSelectorsFactory","checkout_service","messenger","subscribers","createExtensionEventBroadcaster","create_customer_strategy_registry_createCustomerStrategyRegistry","paymentRequestTransformer","paymentRequestSender","stepHandler","createStepHandler","CONVERGE","createSubStrategyRegistry","create_payment_strategy_registry_createPaymentStrategyRegistry","consignmentRequestSender","createShippingStrategyRegistry","AmazonPayV2ConfigCreationError","isWithBuyNowFeatures","AmazonPayV2ButtonStrategy","amazonPayV2ConfigRequestSender","initializeAmazonButtonOptions","_buyNowInitializeOptions","Cart","_getCheckoutCreationRequestConfig","_createBuyNowCartOrThrow","_createCheckoutConfig","public_key","rest","amazon_pay_v2_button_strategy_rest","payloadJSON","AmazonPayV2RequestSender","create_amazon_pay_v2_button_strategy","amazonPayV2RequestSender","apple_pay_button_strategy_DefaultLabels","ButtonStyleOption","ApplePayButtonStrategy","_requiresShipping","White","WhiteBorder","Black","getButtonStyle","_getRequestWithEmptyTotal","apple_pay_button_strategy_awaiter","onpaymentmethodselected","_createBuyNowCart","_handlePaymentMethodSelected","completePaymentMethodSelection","create_apple_pay_button_strategy","BigCommercePaymentsButtonStrategy","onEligibilityFailure","buyNowFlowCallbacks","create_bigcommerce_payments_button_strategy","BigCommercePaymentsPayLaterButtonStrategy","create_bigcommerce_payments_paylater_button_strategy","BigCommercePaymentsVenmoButtonStrategy","getValidVenmoButtonStyles","validButtonStyle","gold","create_bigcommerce_payments_venmo_button_strategy","BoltButtonStrategy","BoltConnect","setupProductPageCheckout","addButtonContainer","boltButtonContainer","boltButtonObject","getBoltObjectData","append","domainUrl","getButtonHeight","buttonBorderRadius","getButtonBorderRadius","publishable_key","variant","border_radius","buttonSize","Small","Large","Medium","buttonShape","Pill","Rect","create_bolt_button_strategy","fundingicons","tagline","currentHeight","BraintreePaypalButtonStrategy","shouldProcessPayment","onAuthorizeError","buyNowCartId","buyNowCardRequestBody","create_braintree_paypal_button_strategy","BraintreePaypalCreditButtonStrategy","create_braintree_paypal_credit_button_strategy","BraintreeVisaCheckoutButtonStrategy","braintree_visa_checkout_button_strategy_awaiter","paymentSuccess","toVisaCheckoutAddress","alignItems","create_braintree_visa_checkout_button_strategy","getVenmoButtonStyle","WHITE","backgroundPosition","backgroundSize","backgroundImage","BLUE","backgroundRepeat","cursor","minHeight","minWidth","BraintreeVenmoButtonStrategy","cartButtonStyles","renderVenmoButton","isUnsupportedBrowserError","handleInitializationVenmoError","removeVenmoContainer","venmoButton","braintree_venmo_button_strategy_awaiter","buyBowCart","handlePostForm","create_braintree_venmo_button_strategy","GooglePayButtonStrategy","_getMethodOrThrow","_countryCode","google_pay_button_strategy_awaiter","_buyNowCart","_getBuyNowTransactionInfo","_getTransactionInfo","create_google_pay_braintree_button_strategy","create_google_pay_paypal_commerce_button_strategy","create_google_pay_bigcommerce_payments_button_strategy","create_google_pay_adyenv2_button_strategy","create_google_pay_adyenv3_button_strategy","create_google_pay_authorizenet_button_strategy","create_google_pay_checkoutcom_button_strategy","create_google_pay_cybersource_button_strategy","create_google_pay_orbital_button_strategy","create_google_pay_stripe_button_strategy","create_google_pay_worldpayaccess_button_strategy","create_google_pay_tdonlinemart_button_strategy","PayPalCommerceButtonStrategy","create_paypal_commerce_button_strategy","PayPalCommerceCreditButtonStrategy","create_paypal_commerce_credit_button_strategy","PayPalCommerceVenmoButtonStrategy","create_paypal_commerce_venmo_button_strategy","PaypalButtonStrategy","paypalExpressScriptLoader","paypalSDK","allowCredit","fundingCreditOption","allowedSources","disallowedSources","Button","funding","disallowed","getStyle","onAuthorize","RECT","RESPONSIVE","CheckoutButtonNotInitialized","paymentID","payerID","getPaymentData","payerId","payerInfo","payer_info","create_paypal_express_button_strategy","StripeLinkV2ButtonStrategy","stripe_link_v2_button_strategy_awaiter","create_stripe_link_v2_button_strategy","getUniqId","idPrefix","__WEBPACK_EXTERNAL_MODULE_lodash_uniqueId__","isTerminalCacheKeyMap","CacheKeyResolver","_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","CheckoutButtonErrorSelector","_checkoutButton","getInitializeButtonError","getDeinitializeButtonError","checkout_button_error_selector_decorate","CheckoutButtonStatusSelector","isInitializingButton","isDeinitializingButton","checkout_button_status_selector_decorate","createCheckoutButtonSelectors","checkout_button_error_selector","checkout_button_status_selector","CheckoutButtonInitializer","_buttonStrategyActionCreator","_state","initializeButton","containerIds","containers","setUniqueElementId","deinitializeButton","checkout_button_initializer_decorate","CheckoutButtonStrategyActionCreator","_registryV2","paymentMethodRequestParams","paymentMethodRequestOptions","payment_method_client_unavailable_error_PaymentMethodClientUnavailableError","paypal_sdk_PaypalButtonStyleLayoutOption","paypal_sdk_PaypalButtonStyleSizeOption","paypal_sdk_PaypalButtonStyleColorOption","paypal_sdk_PaypalButtonStyleLabelOption","paypal_sdk_PaypalButtonStyleShapeOption","EmbeddedCheckoutEventType","NotEmbeddableErrorType","EmbeddedContentEventType","paypal_script_loader_PaypalScriptLoader","paypal_button_strategy_PaypalButtonStrategy","_paypalScriptLoader","_host","_setupPayment","_tokenizePayment","createCheckoutButtonInitializer","checkoutButtonStrategyFactories","createCheckoutButtonStrategy","createCheckoutButtonStrategyRegistry","checkout_button_strategies_namespaceObject","checkout_button_initializer","PAYPALEXPRESS","createCheckoutButtonRegistry","InvalidLoginTokenError","NotEmbeddableError","UnknownError","IS_COOKIE_ALLOWED_KEY","LAST_ALLOW_COOKIE_ATTEMPT_KEY","EmbeddedCheckout","_iframeCreator","_messageListener","_messagePoster","_storage","_location","_isAttached","CheckoutComplete","CheckoutError","CheckoutLoaded","onFrameLoad","FrameLoaded","onSignOut","SignedOut","_configureStyles","_allowCookie","_attemptLogin","_retryAllowCookie","FrameError","iFrameResizer","StyleConfigured","lastAttempt","MissingContent","embedded_checkout_decorate","resizable_iframe_creator_ResizableIframeCreator","MissingContainer","allowPaymentRequest","contentId","embedCheckout","handleFrameLoadedEvent","hasAttribute","custom_error_isCustomError","IframeEmbeddedCheckoutMessenger","_untargetedMessagePoster","_messageHandlers","postComplete","_postMessage","postError","_transformError","postFrameError","untargeted","postFrameLoaded","postLoaded","postSignedOut","receiveStyles","_notifyMessageHandlers","iframe_embedded_checkout_messenger_decorate","NoopEmbeddedCheckoutMessenger","noop_embedded_checkout_messenger_decorate","createEmbeddedCheckoutMessenger","parentWindow","noop_embedded_checkout_messenger","iframe_embedded_checkout_messenger","DEFAULT_LOCALE","KEY_PREFIX","LanguageService","_logger","locales","_transformConfig","_locale","_locales","_translations","_formatters","mapKeys","_hasTranslations","translate","prefixedKey","__WEBPACK_EXTERNAL_MODULE_intl_messageformat_1c4020d9_IntlMessageFormat__","_escapeSpecialCharacters","ignoreTag","_transformData","_isFormatError","originalMessage","defaultLocale","defaultTranslations","_flattenObject","fallbackTranslations","__WEBPACK_EXTERNAL_MODULE_lodash_union__","fallbackLocale","parentKey","resultKey","language_service_decorate","createLanguageService","language_service","currency_service_CurrencyService","currency_currency_service_decorate","create_currency_service_createCurrencyService","currency_currency_service","isAnalyticsTrackerWindowGA","ga","sendGoogleAnalytics","nonInteraction","isPayloadSizeLimitReached","serializeAnalyticsEventPayload","acc","AnalyticStepId","ANALYTIC_STEPS","CUSTOMER","BILLING","AnalyticsStepTracker","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","getShopperCurrency","getPaymentMethodName","shipping_method","shippingMethodId","completedStepId","getStoreProfile","toShopperCurrency","getProducts","product_id","giftCertificateItems","itemAttributes","image_url","NoopStepTracker","createStepTracker","stepTrackerConfig","isBraintreeFastlaneWindow","BraintreeAnalyticTracker","_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","PayPalCommerceAnalyticTracker","_checkoutService","paypalHostWindow","_getPayPalEventsOrThrow","createPayPalCommerceAnalyticTracker","AnalyticStepType","StoredCardHostedFormService","createStoredCardHostedFormService","AnalyticStepOrder","BodlEmitterService","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","__WEBPACK_EXTERNAL_MODULE_lodash_flatten__","retail_price","retailPrice","NoopBodlService","createBodlService","isBodlEnabled"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/esm/extension.js b/dist/esm/extension.js index 42d9767b6c..6a92e18ae2 100644 --- a/dist/esm/extension.js +++ b/dist/esm/extension.js @@ -1,2 +1,2 @@ -import*as e from"iframe-resizer";import*as t from"iframe-resizer/js/iframeResizer.contentWindow";import{fromEvent as n}from"rxjs";import{filter as r,map as s,take as i}from"rxjs/operators";import{noop as o}from"lodash";var a,c,d={785(t,n,r){var s,i;t.exports=(s={iframeResizer:()=>e.iframeResizer},i={},r.d(i,s),i)},939(e){e.exports=t}},p={};function h(e){var t=p[e];if(void 0!==t)return t.exports;var n=p[e]={exports:{}};return d[e](n,n.exports,h),n.exports}h.d=(e,t)=>{for(var n in t)h.o(t,n)&&!h.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},h.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),function(e){e.ConsignmentsChanged="EXTENSION:CONSIGNMENTS_CHANGED"}(a||(a={})),function(e){e.ReloadCheckout="EXTENSION:RELOAD_CHECKOUT",e.ShowLoadingIndicator="EXTENSION:SHOW_LOADING_INDICATOR",e.SetIframeStyle="EXTENSION:SET_IFRAME_STYLE",e.ReRenderShippingForm="EXTENSION:RE_RENDER_SHIPPING_FORM",e.ReRenderShippingStep="EXTENSION:RE_RENDER_SHIPPING_STEP"}(c||(c={}));function u(e,t,n){if("function"!=typeof n.value)return n;let r=n.value;return{get(){const e=r.bind(this);return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e},set(e){r=e}}}class f extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}class l extends f{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}function m(e){if(!/^(https?:)?\/\//.test(e))throw new l("The provided URL must be absolute.");const t=document.createElement("a");t.href=e;const n=t.port&&-1!==e.indexOf(`${t.hostname}:${t.port}`)?t.port:"";return{hash:t.hash,hostname:t.hostname,href:t.href,origin:`${t.protocol}//${t.hostname}${n?`:${n}`:""}`,pathname:t.pathname,port:n,protocol:t.protocol,search:t.search}}function E(e,t){return e.type===t}var g,w,y;class _{constructor(e){var t;this._sourceOrigins=[m(e).origin,(t=m(e),m(0===t.hostname.indexOf("www")?t.href:t.href.replace(t.hostname,`www.${t.hostname}`))).origin],this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))}addListener(e,t){let n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)}removeListener(e,t){const n=this._listeners[e];if(!n)return;const r=n.indexOf(t);r>=0&&n.splice(r,1)}trigger(e,t){const n=this._listeners[e.type];n&&n.forEach(n=>t?n(e,t):n(e))}_handleMessage(e){if(-1===this._sourceOrigins.indexOf(e.origin)||!E(e.data,e.data.type))return;const t=e.data,{context:n}=t,r=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s=0;a--)(s=e[a])&&(o=(i<3?s(o):i>3?s(t,n,o):s(t,n))||o);i>3&&o&&Object.defineProperty(t,n,o)}([function(e,t,n){return t&&n?u(0,t,n):function(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(n=>{const r=Object.getOwnPropertyDescriptor(e.prototype,n);r&&"constructor"!==n&&Object.defineProperty(t.prototype,n,u(e.prototype,n,r))}),t}(e)}],_.prototype,"_handleMessage",null);class O{constructor(e,t,n){this._targetWindow=t,this._context=n,this._targetOrigin="*"===e?"*":m(e).origin}post(e,t){const o=this._targetWindow;if(window===o)return;if(!o)throw new Error("Unable to post message because target window is not set.");const a=t&&n(window,"message").pipe(r(e=>e.origin===this._targetOrigin&&E(e.data,e.data.type)&&-1!==[t.successType,t.errorType].indexOf(e.data.type)),s(e=>{if(t.errorType===e.data.type)throw e.data;return e.data}),i(1)).toPromise();return o.postMessage(Object.assign(Object.assign({},e),{context:this._context}),this._targetOrigin),a}setTarget(e){this._targetWindow=e}setContext(e){this._context=e}}!function(e){e.Subscribe="EXTENSION_INTERNAL:SUBSCRIBE",e.Unsubscribe="EXTENSION_INTERNAL:UNSUBSCRIBE",e.ResizeIframe="EXTENSION_INTERNAL:RESIZE_IFRAME"}(g||(g={})),function(e){e.ExtensionReady="EXTENSION:READY",e.ExtensionFailed="EXTENSION:FAILED"}(w||(w={})),function(e){e.GetConsignments="EXTENSION:GET_CONSIGNMENTS"}(y||(y={}));var I=function(e,t,n,r){return new(n||(n=Promise))(function(s,i){function o(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((r=r.apply(e,t||[])).next())})};class v{constructor(e,t,n,r){this._messageListener=e,this._eventListener=t,this._messagePoster=n,this._internalCommandPoster=r,this._messagePoster.setTarget(window.parent),this._internalCommandPoster.setTarget(window.parent)}initialize(e){return I(this,void 0,void 0,function*(){if(!e)throw new Error("Extension Id not found.");this._extensionId=e,this._messageListener.listen(),this._eventListener.listen(),this._messagePoster.setContext({extensionId:e});try{yield this._internalCommandPoster.post({type:g.ResizeIframe,payload:{extensionId:e}},{successType:w.ExtensionReady,errorType:w.ExtensionFailed})}catch(e){if(this._isExtensionFailedEvent(e))throw new Error("Extension failed to load within 60 seconds; please reload and try again.")}})}post(e){if(!this._isCommandOrQueryType(e.type))throw new Error(`${e.type} is not supported.`);this._messagePoster.post(e)}addListener(e,t=o){if(!this._extensionId)throw new Error("Extension is not initialized.");const n=this._extensionId;if(!Object.values(a).includes(e))throw new Error(`${e} is not supported.`);return this._internalCommandPoster.post({type:g.Subscribe,payload:{extensionId:n,eventType:e}}),this._eventListener.addListener(e,t),()=>{this._internalCommandPoster.post({type:g.Unsubscribe,payload:{extensionId:n,eventType:e}}),this._eventListener.removeListener(e,t)}}getConsignments(e=!0){return I(this,void 0,void 0,function*(){return new Promise(t=>{const n=e=>{this._messageListener.removeListener("EXTENSION:GET_CONSIGNMENTS",n),t(e.payload.consignments)};this._messageListener.addListener("EXTENSION:GET_CONSIGNMENTS",n),this.post({type:y.GetConsignments,payload:{useCache:e}})})})}_isExtensionFailedEvent(e){return e.type===w.ExtensionFailed}_isCommandOrQueryType(e){return Object.values(c).includes(e)||Object.values(y).includes(e)}}function N(e){return t=this,n=void 0,s=function*(){const{extensionId:t,parentOrigin:n,taggedElementId:r,fixedHeight:s}=e;h(939);const i=new v(new _(n),new _(n),new O(n),new O(n));return yield i.initialize(t),function(e,t){if(!function(e){return"parentIFrame"in e}(window))throw new Error("iFramerResizer window not found.");if(t)window.parentIFrame.size(t);else if(window.parentIFrame.autoResize(!0),e){const t=document.getElementById(e);if(!t)throw new Error("Element not found.");t.setAttribute("data-iframe-height",""),window.parentIFrame.setHeightCalculationMethod("taggedElement")}else window.parentIFrame.setHeightCalculationMethod("bodyOffset")}(r,s),i},new((r=void 0)||(r=Promise))(function(e,i){function o(e){try{c(s.next(e))}catch(e){i(e)}}function a(e){try{c(s.throw(e))}catch(e){i(e)}}function c(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(o,a)}c((s=s.apply(t,n||[])).next())});var t,n,r,s}export{c as ExtensionCommandType,a as ExtensionEventType,N as initializeExtensionService}; +import*as e from"iframe-resizer";import*as t from"iframe-resizer/js/iframeResizer.contentWindow";import{fromEvent as n}from"rxjs";import{filter as r,map as s,take as i}from"rxjs/operators";import{noop as o}from"lodash";var a={785(t,n,r){var s,i;t.exports=(s={iframeResizer:()=>e.iframeResizer},i={},r.d(i,s),i)},939(e){e.exports=t}},c={};function d(e){var t=c[e];if(void 0!==t)return t.exports;var n=c[e]={exports:{}};return a[e](n,n.exports,d),n.exports}d.d=(e,t)=>{for(var n in t)d.o(t,n)&&!d.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},d.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function p(e,t,n){if("function"!=typeof n.value)return n;let r=n.value;return{get(){const e=r.bind(this);return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e},set(e){r=e}}}class h extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}class u extends h{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}function f(e){if(!/^(https?:)?\/\//.test(e))throw new u("The provided URL must be absolute.");const t=document.createElement("a");t.href=e;const n=t.port&&-1!==e.indexOf(`${t.hostname}:${t.port}`)?t.port:"";return{hash:t.hash,hostname:t.hostname,href:t.href,origin:`${t.protocol}//${t.hostname}${n?`:${n}`:""}`,pathname:t.pathname,port:n,protocol:t.protocol,search:t.search}}function l(e,t){return e.type===t}var m,E,g,w,y;class _{constructor(e){var t;this._sourceOrigins=[f(e).origin,(t=f(e),f(0===t.hostname.indexOf("www")?t.href:t.href.replace(t.hostname,`www.${t.hostname}`))).origin],this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))}addListener(e,t){let n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)}removeListener(e,t){const n=this._listeners[e];if(!n)return;const r=n.indexOf(t);r>=0&&n.splice(r,1)}trigger(e,t){const n=this._listeners[e.type];n&&n.forEach(n=>t?n(e,t):n(e))}_handleMessage(e){if(-1===this._sourceOrigins.indexOf(e.origin)||!l(e.data,e.data.type))return;const t=e.data,{context:n}=t,r=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s=0;a--)(s=e[a])&&(o=(i<3?s(o):i>3?s(t,n,o):s(t,n))||o);i>3&&o&&Object.defineProperty(t,n,o)}([function(e,t,n){return t&&n?p(0,t,n):function(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(n=>{const r=Object.getOwnPropertyDescriptor(e.prototype,n);r&&"constructor"!==n&&Object.defineProperty(t.prototype,n,p(e.prototype,n,r))}),t}(e)}],_.prototype,"_handleMessage",null);class O{constructor(e,t,n){this._targetWindow=t,this._context=n,this._targetOrigin="*"===e?"*":f(e).origin}post(e,t){const o=this._targetWindow;if(window===o)return;if(!o)throw new Error("Unable to post message because target window is not set.");const a=t&&n(window,"message").pipe(r(e=>e.origin===this._targetOrigin&&l(e.data,e.data.type)&&-1!==[t.successType,t.errorType].indexOf(e.data.type)),s(e=>{if(t.errorType===e.data.type)throw e.data;return e.data}),i(1)).toPromise();return o.postMessage(Object.assign(Object.assign({},e),{context:this._context}),this._targetOrigin),a}setTarget(e){this._targetWindow=e}setContext(e){this._context=e}}!function(e){e.ReloadCheckout="EXTENSION:RELOAD_CHECKOUT",e.ShowLoadingIndicator="EXTENSION:SHOW_LOADING_INDICATOR",e.SetIframeStyle="EXTENSION:SET_IFRAME_STYLE",e.ReRenderShippingForm="EXTENSION:RE_RENDER_SHIPPING_FORM",e.ReRenderShippingStep="EXTENSION:RE_RENDER_SHIPPING_STEP"}(m||(m={})),function(e){e.ConsignmentsChanged="EXTENSION:CONSIGNMENTS_CHANGED"}(E||(E={})),function(e){e.Subscribe="EXTENSION_INTERNAL:SUBSCRIBE",e.Unsubscribe="EXTENSION_INTERNAL:UNSUBSCRIBE",e.ResizeIframe="EXTENSION_INTERNAL:RESIZE_IFRAME"}(g||(g={})),function(e){e.ExtensionReady="EXTENSION:READY",e.ExtensionFailed="EXTENSION:FAILED"}(w||(w={})),function(e){e.GetConsignments="EXTENSION:GET_CONSIGNMENTS"}(y||(y={}));var I=function(e,t,n,r){return new(n||(n=Promise))(function(s,i){function o(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((r=r.apply(e,t||[])).next())})};class v{constructor(e,t,n,r){this._messageListener=e,this._eventListener=t,this._messagePoster=n,this._internalCommandPoster=r,this._messagePoster.setTarget(window.parent),this._internalCommandPoster.setTarget(window.parent)}initialize(e){return I(this,void 0,void 0,function*(){if(!e)throw new Error("Extension Id not found.");this._extensionId=e,this._messageListener.listen(),this._eventListener.listen(),this._messagePoster.setContext({extensionId:e});try{yield this._internalCommandPoster.post({type:g.ResizeIframe,payload:{extensionId:e}},{successType:w.ExtensionReady,errorType:w.ExtensionFailed})}catch(e){if(this._isExtensionFailedEvent(e))throw new Error("Extension failed to load within 60 seconds; please reload and try again.")}})}post(e){if(!this._isCommandOrQueryType(e.type))throw new Error(`${e.type} is not supported.`);this._messagePoster.post(e)}addListener(e,t=o){if(!this._extensionId)throw new Error("Extension is not initialized.");const n=this._extensionId;if(!Object.values(E).includes(e))throw new Error(`${e} is not supported.`);return this._internalCommandPoster.post({type:g.Subscribe,payload:{extensionId:n,eventType:e}}),this._eventListener.addListener(e,t),()=>{this._internalCommandPoster.post({type:g.Unsubscribe,payload:{extensionId:n,eventType:e}}),this._eventListener.removeListener(e,t)}}getConsignments(e=!0){return I(this,void 0,void 0,function*(){return new Promise(t=>{const n=e=>{this._messageListener.removeListener("EXTENSION:GET_CONSIGNMENTS",n),t(e.payload.consignments)};this._messageListener.addListener("EXTENSION:GET_CONSIGNMENTS",n),this.post({type:y.GetConsignments,payload:{useCache:e}})})})}_isExtensionFailedEvent(e){return e.type===w.ExtensionFailed}_isCommandOrQueryType(e){return Object.values(m).includes(e)||Object.values(y).includes(e)}}function N(e){return t=this,n=void 0,s=function*(){const{extensionId:t,parentOrigin:n,taggedElementId:r,fixedHeight:s}=e;d(939);const i=new v(new _(n),new _(n),new O(n),new O(n));return yield i.initialize(t),function(e,t){if(!function(e){return"parentIFrame"in e}(window))throw new Error("iFramerResizer window not found.");if(t)window.parentIFrame.size(t);else if(window.parentIFrame.autoResize(!0),e){const t=document.getElementById(e);if(!t)throw new Error("Element not found.");t.setAttribute("data-iframe-height",""),window.parentIFrame.setHeightCalculationMethod("taggedElement")}else window.parentIFrame.setHeightCalculationMethod("bodyOffset")}(r,s),i},new((r=void 0)||(r=Promise))(function(e,i){function o(e){try{c(s.next(e))}catch(e){i(e)}}function a(e){try{c(s.throw(e))}catch(e){i(e)}}function c(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(o,a)}c((s=s.apply(t,n||[])).next())});var t,n,r,s}export{m as ExtensionCommandType,E as ExtensionEventType,N as initializeExtensionService}; //# sourceMappingURL=extension.js.map \ No newline at end of file diff --git a/dist/esm/extension.js.map b/dist/esm/extension.js.map index ab9d32be10..dee931bba4 100644 --- a/dist/esm/extension.js.map +++ b/dist/esm/extension.js.map @@ -1 +1 @@ -{"version":3,"file":"extension.js","mappings":"+NAEYA,ECKAC,gBCPZ,IAAAC,EACAC,EAGAC,EAAAC,SAJAH,EAIA,CAAqBI,cAAA,IAAAC,EAAA,eAHrBJ,EAAA,GAAaK,EAAAC,EAAAN,EAAAD,GAA6BC,WCD1CC,EAAAC,QAAAK,ICCAC,EAAA,GAGA,SAAAH,EAAAI,GAEA,IAAAC,EAAAF,EAAAC,GACA,QAAAE,IAAAD,EACA,OAAAA,EAAAR,QAGA,IAAAD,EAAAO,EAAA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AEQ,uBAAAX,CACJ9C,GAEA,OAAOA,EAAM9C,OAASwB,EAA2BmE,eACrD,CAEQ,qBAAAG,CAAsB9F,GAC1B,OACIzB,OAAO2H,OAAO7I,GAAsB8I,SAASnG,IAC7CzB,OAAO2H,OAAOzE,GAAoB0E,SAASnG,EAEnD,ECjHW,SAAe4G,EAC1B3C,wCAEA,MAAMqB,YAAEA,EAAWuB,aAAEA,EAAYC,gBAAEA,EAAeC,YAAEA,GAAgB9C,ECmBpErG,EAAQ,KDfR,MAAMoJ,EAAY,IAAIjC,EAClB,IAAIrD,EAAyCmF,GAC7C,IAAInF,EAAuCmF,GAC3C,IAAIlD,EAAoEkD,GACxE,IAAIlD,EAA4CkD,IAOpD,aAJMG,EAAU3B,WAAWC,GEtBxB,SACHwB,EACAC,GAEA,IARG,SAA+B9E,GAClC,MAAO,iBAAkBA,CAC7B,CAMSgF,CAAsBhF,QACvB,MAAM,IAAItC,MAAM,oCAGpB,GAAIoH,EACA9E,OAAOiF,aAAaC,KAAKJ,QAIzB,GAFA9E,OAAOiF,aAAaE,YAAW,GAE3BN,EAAiB,CACjB,MAAMO,EAAU3G,SAAS4G,eAAeR,GAExC,IAAKO,EACD,MAAM,IAAI1H,MAAM,sBAGpB0H,EAAQE,aAAa,qBAAsB,IAC3CtF,OAAOiF,aAAaM,2BAA2B,sBAE/CvF,OAAOiF,aAAaM,2BAA2B,aAG3D,CFFIC,CAAmBX,EAAiBC,GAE7BC,CACX","sources":["webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-commands.ts","webpack://@bigcommerce/checkout-sdk/external module \"iframe-resizer\"","webpack://@bigcommerce/checkout-sdk/external module \"iframe-resizer/js/iframeResizer.contentWindow\"","webpack://@bigcommerce/checkout-sdk/webpack/bootstrap","webpack://@bigcommerce/checkout-sdk/webpack/runtime/define property getters","webpack://@bigcommerce/checkout-sdk/webpack/runtime/hasOwnProperty shorthand","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/bind-decorator/bind-decorator.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/invalid-argument-error.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/extension/extension-internal-commands.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-internal-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-queries.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-listener.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/append-www.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-poster.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/initialize-extension-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-resizer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/iframe-resizer-setup.ts"],"sourcesContent":["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","export type ExtensionCommand =\n | ReloadCheckoutCommand\n | ShowLoadingIndicatorCommand\n | SetIframeStyleCommand\n | ReRenderShippingForm\n | ReRenderShippingStep;\n\nexport enum ExtensionCommandType {\n ReloadCheckout = 'EXTENSION:RELOAD_CHECKOUT',\n ShowLoadingIndicator = 'EXTENSION:SHOW_LOADING_INDICATOR',\n SetIframeStyle = 'EXTENSION:SET_IFRAME_STYLE',\n ReRenderShippingForm = 'EXTENSION:RE_RENDER_SHIPPING_FORM',\n ReRenderShippingStep = 'EXTENSION:RE_RENDER_SHIPPING_STEP',\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 ReRenderShippingForm {\n type: ExtensionCommandType.ReRenderShippingForm;\n}\n\nexport interface ReRenderShippingStep {\n type: ExtensionCommandType.ReRenderShippingStep;\n}\nexport interface ExtensionCommandMap {\n [ExtensionCommandType.ReloadCheckout]: ReloadCheckoutCommand;\n [ExtensionCommandType.ShowLoadingIndicator]: ShowLoadingIndicatorCommand;\n [ExtensionCommandType.SetIframeStyle]: SetIframeStyleCommand;\n [ExtensionCommandType.ReRenderShippingForm]: ReRenderShippingForm;\n [ExtensionCommandType.ReRenderShippingStep]: ReRenderShippingStep;\n}\n","var x = (y) => {\n\tvar x = {}; __webpack_require__.d(x, y); return x\n} \nvar y = (x) => (() => (x))\nmodule.exports = x({ [\"iframeResizer\"]: () => (__WEBPACK_EXTERNAL_MODULE_iframe_resizer_1512d797__.iframeResizer) });","module.exports = __WEBPACK_EXTERNAL_MODULE_iframe_resizer_js_iframeResizer_contentWindow_a6cfc03f__;","// 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","// 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))","/**\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 { 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\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 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 { 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","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","export type ExtensionQuery = GetConsignmentsQuery;\n\nexport enum ExtensionQueryType {\n GetConsignments = 'EXTENSION:GET_CONSIGNMENTS',\n}\n\nexport interface GetConsignmentsQuery {\n type: ExtensionQueryType.GetConsignments;\n payload?: {\n useCache?: boolean;\n };\n}\n\nexport interface ExtensionQueryMap {\n [ExtensionQueryType.GetConsignments]: GetConsignmentsQuery;\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\nexport type EventListeners = {\n [key in keyof TEventMap]?: Array<(event: TEventMap[key], context?: TContext) => void>;\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 { 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 { noop } from 'lodash';\n\nimport { Consignment } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\n\nimport { ExtensionCommandType } from './extension-commands';\nimport { ExtensionEventMap, ExtensionEventType } from './extension-events';\nimport {\n ExtensionInternalCommand,\n ExtensionInternalCommandType,\n} from './extension-internal-commands';\nimport { ExtensionInternalEventType } from './extension-internal-events';\nimport {\n ExtensionCommandOrQuery,\n ExtensionCommandOrQueryContext,\n ExtensionMessageMap,\n ExtensionMessageType,\n GetConsignmentsMessage,\n} from './extension-message';\nimport { ExtensionQueryType } from './extension-queries';\n\nexport default class ExtensionService {\n private _extensionId?: string;\n\n constructor(\n private _messageListener: IframeEventListener,\n private _eventListener: IframeEventListener,\n private _messagePoster: IframeEventPoster<\n ExtensionCommandOrQuery,\n ExtensionCommandOrQueryContext\n >,\n private _internalCommandPoster: IframeEventPoster,\n ) {\n this._messagePoster.setTarget(window.parent);\n this._internalCommandPoster.setTarget(window.parent);\n }\n\n async initialize(extensionId: string): Promise {\n if (!extensionId) {\n throw new Error('Extension Id not found.');\n }\n\n this._extensionId = extensionId;\n\n this._messageListener.listen();\n this._eventListener.listen();\n this._messagePoster.setContext({ extensionId });\n\n try {\n await this._internalCommandPoster.post(\n {\n type: ExtensionInternalCommandType.ResizeIframe,\n payload: { extensionId },\n },\n {\n successType: ExtensionInternalEventType.ExtensionReady,\n errorType: ExtensionInternalEventType.ExtensionFailed,\n },\n );\n } catch (event) {\n if (this._isExtensionFailedEvent(event)) {\n throw new Error(\n 'Extension failed to load within 60 seconds; please reload and try again.',\n );\n }\n }\n }\n\n post(command: ExtensionCommandOrQuery): void {\n if (!this._isCommandOrQueryType(command.type)) {\n throw new Error(`${command.type} is not supported.`);\n }\n\n this._messagePoster.post(command);\n }\n\n addListener(eventType: ExtensionEventType, callback: () => void = noop): () => void {\n if (!this._extensionId) {\n throw new Error('Extension is not initialized.');\n }\n\n const extensionId = this._extensionId;\n\n if (!Object.values(ExtensionEventType).includes(eventType)) {\n throw new Error(`${eventType} is not supported.`);\n }\n\n this._internalCommandPoster.post({\n type: ExtensionInternalCommandType.Subscribe,\n payload: { extensionId, eventType },\n });\n\n this._eventListener.addListener(eventType, callback);\n\n return () => {\n this._internalCommandPoster.post({\n type: ExtensionInternalCommandType.Unsubscribe,\n payload: { extensionId, eventType },\n });\n\n this._eventListener.removeListener(eventType, callback);\n };\n }\n\n async getConsignments(useCache = true): Promise {\n return new Promise((resolve) => {\n const callback = (event: GetConsignmentsMessage) => {\n this._messageListener.removeListener(\n ExtensionMessageType.GetConsignments,\n callback,\n );\n\n resolve(event.payload.consignments);\n };\n\n this._messageListener.addListener(ExtensionMessageType.GetConsignments, callback);\n\n this.post({ type: ExtensionQueryType.GetConsignments, payload: { useCache } });\n });\n }\n\n private _isExtensionFailedEvent(\n event: any,\n ): event is ExtensionInternalEventType.ExtensionFailed {\n return event.type === ExtensionInternalEventType.ExtensionFailed;\n }\n\n private _isCommandOrQueryType(type: any): type is ExtensionCommandOrQuery['type'] {\n return (\n Object.values(ExtensionCommandType).includes(type) ||\n Object.values(ExtensionQueryType).includes(type)\n );\n }\n}\n","import {\n IframeEventListener,\n IframeEventPoster,\n setupContentWindowForIframeResizer,\n} from '../common/iframe';\n\nimport { ExtensionCommand } from './extension-commands';\nimport { ExtensionEventMap } from './extension-events';\nimport { ExtensionInternalCommand } from './extension-internal-commands';\nimport { ExtensionCommandOrQueryContext, ExtensionMessageMap } from './extension-message';\nimport ExtensionService from './extension-service';\nimport { iframeResizerSetup } from './iframe-resizer-setup';\n\nexport interface InitializeExtensionServiceOptions {\n extensionId: string;\n parentOrigin: string;\n taggedElementId?: string;\n fixedHeight?: number;\n}\n\nexport default async function initializeExtensionService(\n options: InitializeExtensionServiceOptions,\n): Promise {\n const { extensionId, parentOrigin, taggedElementId, fixedHeight } = options;\n\n setupContentWindowForIframeResizer();\n\n const extension = new ExtensionService(\n new IframeEventListener(parentOrigin),\n new IframeEventListener(parentOrigin),\n new IframeEventPoster(parentOrigin),\n new IframeEventPoster(parentOrigin),\n );\n\n await extension.initialize(extensionId);\n\n iframeResizerSetup(taggedElementId, fixedHeight);\n\n return extension;\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","export interface IframeResizerWindow extends Window {\n parentIFrame: {\n autoResize: (isEnabled: boolean) => void;\n setHeightCalculationMethod: (id: string) => void;\n size: (height: number) => void;\n };\n}\n\nexport function isIframeResizerWindow(window: Window): window is IframeResizerWindow {\n return 'parentIFrame' in window;\n}\n\nexport function iframeResizerSetup(\n taggedElementId: string | undefined,\n fixedHeight: number | undefined,\n): void {\n if (!isIframeResizerWindow(window)) {\n throw new Error('iFramerResizer window not found.');\n }\n\n if (fixedHeight) {\n window.parentIFrame.size(fixedHeight);\n } else {\n window.parentIFrame.autoResize(true);\n\n if (taggedElementId) {\n const element = document.getElementById(taggedElementId);\n\n if (!element) {\n throw new Error(`Element not found.`);\n }\n\n element.setAttribute('data-iframe-height', '');\n window.parentIFrame.setHeightCalculationMethod('taggedElement');\n } else {\n window.parentIFrame.setHeightCalculationMethod('bodyOffset');\n }\n }\n}\n"],"names":["ExtensionEventType","ExtensionCommandType","y","x","module","exports","iframeResizer","__WEBPACK_EXTERNAL_MODULE_iframe_resizer_1512d797__","__webpack_require__","d","__WEBPACK_EXTERNAL_MODULE_iframe_resizer_js_iframeResizer_contentWindow_a6cfc03f__","__webpack_module_cache__","moduleId","cachedModule","undefined","__webpack_modules__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","bindMethodDecorator","_","descriptor","value","method","boundMethod","bind","this","assign","set","StandardError","Error","constructor","message","super","name","type","setPrototypeOf","__proto__","captureStackTrace","stack","InvalidArgumentError","parseUrl","url","test","anchor","document","createElement","href","port","indexOf","hostname","hash","origin","protocol","pathname","search","isIframeEvent","object","ExtensionInternalCommandType","ExtensionInternalEventType","ExtensionQueryType","IframeEventListener","sourceOrigin","_sourceOrigins","replace","_isListening","_listeners","listen","window","addEventListener","_handleMessage","stopListen","removeEventListener","addListener","listener","listeners","push","removeListener","index","splice","trigger","event","context","forEach","messageEvent","data","_a","__rest","__decorate","target","decoratedTarget","getOwnPropertyNames","getOwnPropertyDescriptor","bindClassDecorator","IframeEventPoster","targetOrigin","_targetWindow","_context","_targetOrigin","post","options","targetWindow","result","__WEBPACK_EXTERNAL_MODULE_rxjs_fromEvent__","pipe","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_filter__","successType","errorType","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_map__","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_take__","toPromise","postMessage","setTarget","setContext","ExtensionService","_messageListener","_eventListener","_messagePoster","_internalCommandPoster","parent","initialize","extensionId","_extensionId","ResizeIframe","payload","ExtensionReady","ExtensionFailed","_isExtensionFailedEvent","command","_isCommandOrQueryType","eventType","callback","__WEBPACK_EXTERNAL_MODULE_lodash_noop__","values","includes","Subscribe","Unsubscribe","getConsignments","useCache","Promise","resolve","consignments","GetConsignments","initializeExtensionService","parentOrigin","taggedElementId","fixedHeight","extension","isIframeResizerWindow","parentIFrame","size","autoResize","element","getElementById","setAttribute","setHeightCalculationMethod","iframeResizerSetup"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"extension.js","mappings":"6OAAA,IAAAA,EACAC,EAGAC,EAAAC,SAJAH,EAIA,CAAqBI,cAAA,IAAAC,EAAA,eAHrBJ,EAAA,GAAaK,EAAAC,EAAAN,EAAAD,GAA6BC,WCD1CC,EAAAC,QAAAK,ICCAC,EAAA,GAGA,SAAAH,EAAAI,GAEA,IAAAC,EAAAF,EAAAC,GACA,QAAAE,IAAAD,EACA,OAAAA,EAAAR,QAGA,IAAAD,EAAAO,EAAAC,GAAA,CAGAP,QAAA,IAOA,OAHAU,EAAAH,GAAAR,EAAAA,EAAAC,QAAAG,GAGAJ,EAAAC,OACA,CCrBAG,EAAAC,EAAA,CAAAJ,EAAAW,KACA,QAAAC,KAAAD,EACAR,EAAAU,EAAAF,EAAAC,KAAAT,EAAAU,EAAAb,EAAAY,IACAE,OAAAC,eAAAf,EAAAY,EAAA,CAAyCI,YAAA,EAAAC,IAAAN,EAAAC,MCJzCT,EAAAU,EAAA,CAAAK,EAAAC,IAAAL,OAAAM,UAAAC,eAAAC,KAAAJ,EAAAC,GCgDO,SAASI,EACZC,EACAZ,EACAa,GAEA,GAAgC,mBAArBA,EAAWC,MAClB,OAAOD,EAGX,IAAIE,EAAYF,EAAWC,MA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IAOpD,aAJMG,EAAU3B,WAAWC,GEtBxB,SACHwB,EACAC,GAEA,IARG,SAA+B9E,GAClC,MAAO,iBAAkBA,CAC7B,CAMSgF,CAAsBhF,QACvB,MAAM,IAAIxC,MAAM,oCAGpB,GAAIsH,EACA9E,OAAOiF,aAAaC,KAAKJ,QAIzB,GAFA9E,OAAOiF,aAAaE,YAAW,GAE3BN,EAAiB,CACjB,MAAMO,EAAU7G,SAAS8G,eAAeR,GAExC,IAAKO,EACD,MAAM,IAAI5H,MAAM,sBAGpB4H,EAAQE,aAAa,qBAAsB,IAC3CtF,OAAOiF,aAAaM,2BAA2B,sBAE/CvF,OAAOiF,aAAaM,2BAA2B,aAG3D,CFFIC,CAAmBX,EAAiBC,GAE7BC,CACX","sources":["webpack://@bigcommerce/checkout-sdk/external module \"iframe-resizer\"","webpack://@bigcommerce/checkout-sdk/external module \"iframe-resizer/js/iframeResizer.contentWindow\"","webpack://@bigcommerce/checkout-sdk/webpack/bootstrap","webpack://@bigcommerce/checkout-sdk/webpack/runtime/define property getters","webpack://@bigcommerce/checkout-sdk/webpack/runtime/hasOwnProperty shorthand","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/bind-decorator/bind-decorator.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/invalid-argument-error.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/extension/extension-commands.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-internal-commands.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-internal-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-queries.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-listener.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/append-www.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-poster.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/initialize-extension-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-resizer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/iframe-resizer-setup.ts"],"sourcesContent":["var x = (y) => {\n\tvar x = {}; __webpack_require__.d(x, y); return x\n} \nvar y = (x) => (() => (x))\nmodule.exports = x({ [\"iframeResizer\"]: () => (__WEBPACK_EXTERNAL_MODULE_iframe_resizer_1512d797__.iframeResizer) });","module.exports = __WEBPACK_EXTERNAL_MODULE_iframe_resizer_js_iframeResizer_contentWindow_a6cfc03f__;","// 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","// 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))","/**\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 { 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\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 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","export type ExtensionCommand =\n | ReloadCheckoutCommand\n | ShowLoadingIndicatorCommand\n | SetIframeStyleCommand\n | ReRenderShippingForm\n | ReRenderShippingStep;\n\nexport enum ExtensionCommandType {\n ReloadCheckout = 'EXTENSION:RELOAD_CHECKOUT',\n ShowLoadingIndicator = 'EXTENSION:SHOW_LOADING_INDICATOR',\n SetIframeStyle = 'EXTENSION:SET_IFRAME_STYLE',\n ReRenderShippingForm = 'EXTENSION:RE_RENDER_SHIPPING_FORM',\n ReRenderShippingStep = 'EXTENSION:RE_RENDER_SHIPPING_STEP',\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 ReRenderShippingForm {\n type: ExtensionCommandType.ReRenderShippingForm;\n}\n\nexport interface ReRenderShippingStep {\n type: ExtensionCommandType.ReRenderShippingStep;\n}\nexport interface ExtensionCommandMap {\n [ExtensionCommandType.ReloadCheckout]: ReloadCheckoutCommand;\n [ExtensionCommandType.ShowLoadingIndicator]: ShowLoadingIndicatorCommand;\n [ExtensionCommandType.SetIframeStyle]: SetIframeStyleCommand;\n [ExtensionCommandType.ReRenderShippingForm]: ReRenderShippingForm;\n [ExtensionCommandType.ReRenderShippingStep]: ReRenderShippingStep;\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 { 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","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","export type ExtensionQuery = GetConsignmentsQuery;\n\nexport enum ExtensionQueryType {\n GetConsignments = 'EXTENSION:GET_CONSIGNMENTS',\n}\n\nexport interface GetConsignmentsQuery {\n type: ExtensionQueryType.GetConsignments;\n payload?: {\n useCache?: boolean;\n };\n}\n\nexport interface ExtensionQueryMap {\n [ExtensionQueryType.GetConsignments]: GetConsignmentsQuery;\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\nexport type EventListeners = {\n [key in keyof TEventMap]?: Array<(event: TEventMap[key], context?: TContext) => void>;\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 { 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 { noop } from 'lodash';\n\nimport { Consignment } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\n\nimport { ExtensionCommandType } from './extension-commands';\nimport { ExtensionEventMap, ExtensionEventType } from './extension-events';\nimport {\n ExtensionInternalCommand,\n ExtensionInternalCommandType,\n} from './extension-internal-commands';\nimport { ExtensionInternalEventType } from './extension-internal-events';\nimport {\n ExtensionCommandOrQuery,\n ExtensionCommandOrQueryContext,\n ExtensionMessageMap,\n ExtensionMessageType,\n GetConsignmentsMessage,\n} from './extension-message';\nimport { ExtensionQueryType } from './extension-queries';\n\nexport default class ExtensionService {\n private _extensionId?: string;\n\n constructor(\n private _messageListener: IframeEventListener,\n private _eventListener: IframeEventListener,\n private _messagePoster: IframeEventPoster<\n ExtensionCommandOrQuery,\n ExtensionCommandOrQueryContext\n >,\n private _internalCommandPoster: IframeEventPoster,\n ) {\n this._messagePoster.setTarget(window.parent);\n this._internalCommandPoster.setTarget(window.parent);\n }\n\n async initialize(extensionId: string): Promise {\n if (!extensionId) {\n throw new Error('Extension Id not found.');\n }\n\n this._extensionId = extensionId;\n\n this._messageListener.listen();\n this._eventListener.listen();\n this._messagePoster.setContext({ extensionId });\n\n try {\n await this._internalCommandPoster.post(\n {\n type: ExtensionInternalCommandType.ResizeIframe,\n payload: { extensionId },\n },\n {\n successType: ExtensionInternalEventType.ExtensionReady,\n errorType: ExtensionInternalEventType.ExtensionFailed,\n },\n );\n } catch (event) {\n if (this._isExtensionFailedEvent(event)) {\n throw new Error(\n 'Extension failed to load within 60 seconds; please reload and try again.',\n );\n }\n }\n }\n\n post(command: ExtensionCommandOrQuery): void {\n if (!this._isCommandOrQueryType(command.type)) {\n throw new Error(`${command.type} is not supported.`);\n }\n\n this._messagePoster.post(command);\n }\n\n addListener(eventType: ExtensionEventType, callback: () => void = noop): () => void {\n if (!this._extensionId) {\n throw new Error('Extension is not initialized.');\n }\n\n const extensionId = this._extensionId;\n\n if (!Object.values(ExtensionEventType).includes(eventType)) {\n throw new Error(`${eventType} is not supported.`);\n }\n\n this._internalCommandPoster.post({\n type: ExtensionInternalCommandType.Subscribe,\n payload: { extensionId, eventType },\n });\n\n this._eventListener.addListener(eventType, callback);\n\n return () => {\n this._internalCommandPoster.post({\n type: ExtensionInternalCommandType.Unsubscribe,\n payload: { extensionId, eventType },\n });\n\n this._eventListener.removeListener(eventType, callback);\n };\n }\n\n async getConsignments(useCache = true): Promise {\n return new Promise((resolve) => {\n const callback = (event: GetConsignmentsMessage) => {\n this._messageListener.removeListener(\n ExtensionMessageType.GetConsignments,\n callback,\n );\n\n resolve(event.payload.consignments);\n };\n\n this._messageListener.addListener(ExtensionMessageType.GetConsignments, callback);\n\n this.post({ type: ExtensionQueryType.GetConsignments, payload: { useCache } });\n });\n }\n\n private _isExtensionFailedEvent(\n event: any,\n ): event is ExtensionInternalEventType.ExtensionFailed {\n return event.type === ExtensionInternalEventType.ExtensionFailed;\n }\n\n private _isCommandOrQueryType(type: any): type is ExtensionCommandOrQuery['type'] {\n return (\n Object.values(ExtensionCommandType).includes(type) ||\n Object.values(ExtensionQueryType).includes(type)\n );\n }\n}\n","import {\n IframeEventListener,\n IframeEventPoster,\n setupContentWindowForIframeResizer,\n} from '../common/iframe';\n\nimport { ExtensionCommand } from './extension-commands';\nimport { ExtensionEventMap } from './extension-events';\nimport { ExtensionInternalCommand } from './extension-internal-commands';\nimport { ExtensionCommandOrQueryContext, ExtensionMessageMap } from './extension-message';\nimport ExtensionService from './extension-service';\nimport { iframeResizerSetup } from './iframe-resizer-setup';\n\nexport interface InitializeExtensionServiceOptions {\n extensionId: string;\n parentOrigin: string;\n taggedElementId?: string;\n fixedHeight?: number;\n}\n\nexport default async function initializeExtensionService(\n options: InitializeExtensionServiceOptions,\n): Promise {\n const { extensionId, parentOrigin, taggedElementId, fixedHeight } = options;\n\n setupContentWindowForIframeResizer();\n\n const extension = new ExtensionService(\n new IframeEventListener(parentOrigin),\n new IframeEventListener(parentOrigin),\n new IframeEventPoster(parentOrigin),\n new IframeEventPoster(parentOrigin),\n );\n\n await extension.initialize(extensionId);\n\n iframeResizerSetup(taggedElementId, fixedHeight);\n\n return extension;\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","export interface IframeResizerWindow extends Window {\n parentIFrame: {\n autoResize: (isEnabled: boolean) => void;\n setHeightCalculationMethod: (id: string) => void;\n size: (height: number) => void;\n };\n}\n\nexport function isIframeResizerWindow(window: Window): window is IframeResizerWindow {\n return 'parentIFrame' in window;\n}\n\nexport function iframeResizerSetup(\n taggedElementId: string | undefined,\n fixedHeight: number | undefined,\n): void {\n if (!isIframeResizerWindow(window)) {\n throw new Error('iFramerResizer window not found.');\n }\n\n if (fixedHeight) {\n window.parentIFrame.size(fixedHeight);\n } else {\n window.parentIFrame.autoResize(true);\n\n if (taggedElementId) {\n const element = document.getElementById(taggedElementId);\n\n if (!element) {\n throw new Error(`Element not found.`);\n }\n\n element.setAttribute('data-iframe-height', '');\n window.parentIFrame.setHeightCalculationMethod('taggedElement');\n } else {\n window.parentIFrame.setHeightCalculationMethod('bodyOffset');\n }\n }\n}\n"],"names":["y","x","module","exports","iframeResizer","__WEBPACK_EXTERNAL_MODULE_iframe_resizer_1512d797__","__webpack_require__","d","__WEBPACK_EXTERNAL_MODULE_iframe_resizer_js_iframeResizer_contentWindow_a6cfc03f__","__webpack_module_cache__","moduleId","cachedModule","undefined","__webpack_modules__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","bindMethodDecorator","_","descriptor","value","method","boundMethod","bind","this","assign","set","StandardError","Error","constructor","message","super","name","type","setPrototypeOf","__proto__","captureStackTrace","stack","InvalidArgumentError","parseUrl","url","test","anchor","document","createElement","href","port","indexOf","hostname","hash","origin","protocol","pathname","search","isIframeEvent","object","ExtensionCommandType","ExtensionEventType","ExtensionInternalCommandType","ExtensionInternalEventType","ExtensionQueryType","IframeEventListener","sourceOrigin","_sourceOrigins","replace","_isListening","_listeners","listen","window","addEventListener","_handleMessage","stopListen","removeEventListener","addListener","listener","listeners","push","removeListener","index","splice","trigger","event","context","forEach","messageEvent","data","_a","__rest","__decorate","target","decoratedTarget","getOwnPropertyNames","getOwnPropertyDescriptor","bindClassDecorator","IframeEventPoster","targetOrigin","_targetWindow","_context","_targetOrigin","post","options","targetWindow","result","__WEBPACK_EXTERNAL_MODULE_rxjs_fromEvent__","pipe","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_filter__","successType","errorType","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_map__","__WEBPACK_EXTERNAL_MODULE_rxjs_operators_68fec7eb_take__","toPromise","postMessage","setTarget","setContext","ExtensionService","_messageListener","_eventListener","_messagePoster","_internalCommandPoster","parent","initialize","extensionId","_extensionId","ResizeIframe","payload","ExtensionReady","ExtensionFailed","_isExtensionFailedEvent","command","_isCommandOrQueryType","eventType","callback","__WEBPACK_EXTERNAL_MODULE_lodash_noop__","values","includes","Subscribe","Unsubscribe","getConsignments","useCache","Promise","resolve","consignments","GetConsignments","initializeExtensionService","parentOrigin","taggedElementId","fixedHeight","extension","isIframeResizerWindow","parentIFrame","size","autoResize","element","getElementById","setAttribute","setHeightCalculationMethod","iframeResizerSetup"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/esm/integrations/offline.js b/dist/esm/integrations/offline.js index e9d7f165da..51b9f3b5d3 100644 --- a/dist/esm/integrations/offline.js +++ b/dist/esm/integrations/offline.js @@ -1,2 +1,2 @@ -class e extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}class t extends e{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}class r{constructor(e){this._paymentIntegrationService=e}execute(e,t){return r=this,n=void 0,o=function*(){return console.log("payload =======1",e),yield this._paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:e.payment?Object.assign({methodId:e.payment.methodId},"purchaseorder"===e.payment.methodId&&{paymentData:e.payment.paymentData}):void 0}),t),Promise.resolve()},new((a=void 0)||(a=Promise))(function(e,t){function i(e){try{c(o.next(e))}catch(e){t(e)}}function s(e){try{c(o.throw(e))}catch(e){t(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a(function(e){e(r)})).then(i,s)}c((o=o.apply(r,n||[])).next())});var r,n,a,o}finalize(){return Promise.reject(new t)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const n=(a=e=>new r(e),o=[{type:"PAYMENT_TYPE_OFFLINE"}],Object.assign(a,{resolveIds:o}));var a,o;export{n as createOfflinePaymentStrategy}; +class e extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}class t extends e{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}class r{constructor(e){this._paymentIntegrationService=e}execute(e,t){return r=this,n=void 0,i=function*(){return yield this._paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:e.payment?{methodId:e.payment.methodId}:void 0}),t),Promise.resolve()},new((o=void 0)||(o=Promise))(function(e,t){function s(e){try{c(i.next(e))}catch(e){t(e)}}function a(e){try{c(i.throw(e))}catch(e){t(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof o?r:new o(function(e){e(r)})).then(s,a)}c((i=i.apply(r,n||[])).next())});var r,n,o,i}finalize(){return Promise.reject(new t)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const n=(o=e=>new r(e),i=[{type:"PAYMENT_TYPE_OFFLINE"}],Object.assign(o,{resolveIds:i}));var o,i;export{n as createOfflinePaymentStrategy}; //# sourceMappingURL=offline.js.map \ No newline at end of file diff --git a/dist/esm/integrations/offline.js.map b/dist/esm/integrations/offline.js.map index 46ae5560e9..7af172be03 100644 --- a/dist/esm/integrations/offline.js.map +++ b/dist/esm/integrations/offline.js.map @@ -1 +1 @@ -{"version":3,"file":"integrations/offline.js","mappings":"AAOe,MAAeA,UAAsBC,MAIhD,WAAAC,CAAYC,GCXD,IAAqCC,EDY5CC,MAAMF,GAAW,qCAJrBG,KAAAC,KAAO,gBACPD,KAAAE,KAAO,WCTyCJ,aDcZA,UCbhCK,OAAOC,eACPD,OAAOC,eDYQJ,KCZeF,GDYfE,KCVRK,UAAYP,EDYoB,mBAA5BH,MAAMW,kBACbX,MAAMW,kBAAkBN,iBAExBA,KAAKO,MAAQ,IAAIZ,MAAMK,KAAKH,SAASU,KAE7C,EEfW,MAAMC,UAA0Cd,EAC3D,WAAAE,GACIG,MAAM,kEAENC,KAAKC,KAAO,oCACZD,KAAKE,KAAO,iCAChB,ECJW,MAAMO,EACjB,WAAAb,CAAoBc,GAAAV,KAAAU,2BAAAA,CAAwD,CAEtE,OAAAC,CAAQC,EAA2BC,wCAmBrC,OAjBAC,QAAQC,IAAI,mBAAoBH,SAE1BZ,KAAKU,2BAA2BM,YAAWb,OAAAc,OAAAd,OAAAc,OAAA,GAEtCL,GAAO,CACVM,QAASN,EAAQM,QACZf,OAAAc,OAAA,CACKE,SAAUP,EAAQM,QAAQC,UACO,kBAA7BP,EAAQM,QAAQC,UAAgC,CAChDC,YAAaR,EAAQM,QAAQE,mBAGrCC,IAEVR,GAGGS,QAAQC,SACnB,6RAEA,QAAAC,GACI,OAAOF,QAAQG,OAAO,IAAIjB,EAC9B,CAEA,UAAAkB,GACI,OAAOJ,QAAQC,SACnB,CAEA,YAAAI,GACI,OAAOL,QAAQC,SACnB,ECpCJ,MAIAK,GCRIC,EDKAC,GACC,IAAIrB,EAAuBqB,GCL5BC,EDO4D,CAAC,CAAE7B,KAAM,yBCL9DC,OAAOc,OAAOY,EAAQ,CAAEE,gBAJpB,IACXF,EACAE","sources":["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/order-finalization-not-required-error.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/payment-integration-api/src/to-resolvable-module.ts"],"sourcesContent":["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 * 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 {\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\n console.log('payload =======1', payload)\n\n await this._paymentIntegrationService.submitOrder(\n {\n ...payload,\n payment: payload.payment\n ? {\n methodId: payload.payment.methodId,\n ...(payload.payment.methodId === 'purchaseorder' && {\n paymentData: payload.payment.paymentData,\n }),\n }\n : 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 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"],"names":["StandardError","Error","constructor","message","prototype","super","this","name","type","Object","setPrototypeOf","__proto__","captureStackTrace","stack","OrderFinalizationNotRequiredError","OfflinePaymentStrategy","_paymentIntegrationService","execute","payload","options","console","log","submitOrder","assign","payment","methodId","paymentData","undefined","Promise","resolve","finalize","reject","initialize","deinitialize","create_offline_payment_strategy","module","paymentIntegrationService","resolveIds"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"integrations/offline.js","mappings":"AAOe,MAAeA,UAAsBC,MAIhD,WAAAC,CAAYC,GCXD,IAAqCC,EDY5CC,MAAMF,GAAW,qCAJrBG,KAAAC,KAAO,gBACPD,KAAAE,KAAO,WCTyCJ,aDcZA,UCbhCK,OAAOC,eACPD,OAAOC,eDYQJ,KCZeF,GDYfE,KCVRK,UAAYP,EDYoB,mBAA5BH,MAAMW,kBACbX,MAAMW,kBAAkBN,iBAExBA,KAAKO,MAAQ,IAAIZ,MAAMK,KAAKH,SAASU,KAE7C,EEfW,MAAMC,UAA0Cd,EAC3D,WAAAE,GACIG,MAAM,kEAENC,KAAKC,KAAO,oCACZD,KAAKE,KAAO,iCAChB,ECJW,MAAMO,EACjB,WAAAb,CAAoBc,GAAAV,KAAAU,2BAAAA,CAAwD,CAEtE,OAAAC,CAAQC,EAA2BC,wCASrC,aARMb,KAAKU,2BAA2BI,YAAWX,OAAAY,OAAAZ,OAAAY,OAAA,GAEtCH,GAAO,CACVI,QAASJ,EAAQI,QAAU,CAAEC,SAAUL,EAAQI,QAAQC,eAAaC,IAExEL,GAGGM,QAAQC,SACnB,6RAEA,QAAAC,GACI,OAAOF,QAAQG,OAAO,IAAId,EAC9B,CAEA,UAAAe,GACI,OAAOJ,QAAQC,SACnB,CAEA,YAAAI,GACI,OAAOL,QAAQC,SACnB,EC1BJ,MAIAK,GCRIC,EDKAC,GACC,IAAIlB,EAAuBkB,GCL5BC,EDO4D,CAAC,CAAE1B,KAAM,yBCL9DC,OAAOY,OAAOW,EAAQ,CAAEE,gBAJpB,IACXF,EACAE","sources":["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/order-finalization-not-required-error.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/payment-integration-api/src/to-resolvable-module.ts"],"sourcesContent":["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 * 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 {\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 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"],"names":["StandardError","Error","constructor","message","prototype","super","this","name","type","Object","setPrototypeOf","__proto__","captureStackTrace","stack","OrderFinalizationNotRequiredError","OfflinePaymentStrategy","_paymentIntegrationService","execute","payload","options","submitOrder","assign","payment","methodId","undefined","Promise","resolve","finalize","reject","initialize","deinitialize","create_offline_payment_strategy","module","paymentIntegrationService","resolveIds"],"sourceRoot":""} \ No newline at end of file diff --git a/packages/offline-integration/src/offline-payment-strategy.spec.ts b/packages/offline-integration/src/offline-payment-strategy.spec.ts index d6b2900784..96a98e1747 100644 --- a/packages/offline-integration/src/offline-payment-strategy.spec.ts +++ b/packages/offline-integration/src/offline-payment-strategy.spec.ts @@ -1,4 +1,5 @@ import { + NonceInstrument, OrderFinalizationNotRequiredError, PaymentIntegrationService, } from '@bigcommerce/checkout-sdk/payment-integration-api'; @@ -45,6 +46,70 @@ describe('OfflinePaymentStrategy', () => { ); }); + it('includes only purchaseOrderNumber in paymentData when methodId is purchaseorder', async () => { + const payload = { + ...getOrderRequestBody(), + payment: { + methodId: 'purchaseorder', + paymentData: { + purchaseOrderNumber: '1111111', + shouldCreateAccount: true, + shouldSaveInstrument: false, + terms: false, + } as NonceInstrument, + }, + }; + + await strategy.execute(payload, undefined); + + expect(paymentIntegrationService.submitOrder).toHaveBeenCalledWith( + { + ...payload, + payment: { + methodId: 'purchaseorder', + paymentData: { + purchaseOrderNumber: '1111111', + }, + }, + }, + undefined, + ); + }); + + it('does not include paymentData when methodId is purchaseorder but paymentData is absent', async () => { + const payload = { + ...getOrderRequestBody(), + payment: { + methodId: 'purchaseorder', + }, + }; + + await strategy.execute(payload, undefined); + + expect(paymentIntegrationService.submitOrder).toHaveBeenCalledWith( + { + ...payload, + payment: { + methodId: 'purchaseorder', + }, + }, + undefined, + ); + }); + + it('does not include paymentData for non-purchaseorder offline methods', async () => { + await strategy.execute(getOrderRequestBody(), undefined); + + expect(paymentIntegrationService.submitOrder).toHaveBeenCalledWith( + expect.objectContaining({ + payment: { + methodId: 'authorizenet', + }, + }), + undefined, + ); + }); + it('passes the options to submitOrder', async () => { const options = { myOptions: 'option1', methodId: 'testgateway' }; diff --git a/packages/offline-integration/src/offline-payment-strategy.ts b/packages/offline-integration/src/offline-payment-strategy.ts index 01049921aa..f89e8d0fa8 100644 --- a/packages/offline-integration/src/offline-payment-strategy.ts +++ b/packages/offline-integration/src/offline-payment-strategy.ts @@ -1,4 +1,5 @@ import { + HostedInstrument, OrderFinalizationNotRequiredError, OrderRequestBody, PaymentIntegrationService, @@ -6,22 +7,32 @@ import { PaymentStrategy, } from '@bigcommerce/checkout-sdk/payment-integration-api'; +interface PurchaseOrderPaymentData extends HostedInstrument { + purchaseOrderNumber?: string; +} + +function isPurchaseOrderPaymentData(data: unknown): data is PurchaseOrderPaymentData { + return typeof data === 'object' && data !== null && 'purchaseOrderNumber' in data; +} + export default class OfflinePaymentStrategy implements PaymentStrategy { constructor(private _paymentIntegrationService: PaymentIntegrationService) {} async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise { + const { payment } = payload; + let purchaseOrderPaymentData: PurchaseOrderPaymentData | undefined; - console.log('payload =======1', payload) + if (payment?.methodId === 'purchaseorder' && isPurchaseOrderPaymentData(payment.paymentData)) { + purchaseOrderPaymentData = { purchaseOrderNumber: payment.paymentData.purchaseOrderNumber }; + } await this._paymentIntegrationService.submitOrder( { ...payload, - payment: payload.payment + payment: payment ? { - methodId: payload.payment.methodId, - ...(payload.payment.methodId === 'purchaseorder' && { - paymentData: payload.payment.paymentData, - }), + methodId: payment.methodId, + ...(purchaseOrderPaymentData && { paymentData: purchaseOrderPaymentData }), } : undefined, }, From 97083bc54fa06e1481472f5b1cf6fda33cb27c6e Mon Sep 17 00:00:00 2001 From: bc-alfreid Date: Mon, 18 May 2026 09:19:08 +1000 Subject: [PATCH 3/3] feat(payment): PAYMENTS-11577 Fix lint --- .../src/offline-payment-strategy.spec.ts | 3 +-- .../src/offline-payment-strategy.ts | 13 ++++++++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/packages/offline-integration/src/offline-payment-strategy.spec.ts b/packages/offline-integration/src/offline-payment-strategy.spec.ts index 96a98e1747..a8bcb1cfbe 100644 --- a/packages/offline-integration/src/offline-payment-strategy.spec.ts +++ b/packages/offline-integration/src/offline-payment-strategy.spec.ts @@ -1,5 +1,4 @@ import { - NonceInstrument, OrderFinalizationNotRequiredError, PaymentIntegrationService, } from '@bigcommerce/checkout-sdk/payment-integration-api'; @@ -56,7 +55,7 @@ describe('OfflinePaymentStrategy', () => { shouldCreateAccount: true, shouldSaveInstrument: false, terms: false, - } as NonceInstrument, + }, }, }; diff --git a/packages/offline-integration/src/offline-payment-strategy.ts b/packages/offline-integration/src/offline-payment-strategy.ts index f89e8d0fa8..2586a436cc 100644 --- a/packages/offline-integration/src/offline-payment-strategy.ts +++ b/packages/offline-integration/src/offline-payment-strategy.ts @@ -22,8 +22,13 @@ export default class OfflinePaymentStrategy implements PaymentStrategy { const { payment } = payload; let purchaseOrderPaymentData: PurchaseOrderPaymentData | undefined; - if (payment?.methodId === 'purchaseorder' && isPurchaseOrderPaymentData(payment.paymentData)) { - purchaseOrderPaymentData = { purchaseOrderNumber: payment.paymentData.purchaseOrderNumber }; + if ( + payment?.methodId === 'purchaseorder' && + isPurchaseOrderPaymentData(payment.paymentData) + ) { + purchaseOrderPaymentData = { + purchaseOrderNumber: payment.paymentData.purchaseOrderNumber, + }; } await this._paymentIntegrationService.submitOrder( @@ -32,7 +37,9 @@ export default class OfflinePaymentStrategy implements PaymentStrategy { payment: payment ? { methodId: payment.methodId, - ...(purchaseOrderPaymentData && { paymentData: purchaseOrderPaymentData }), + ...(purchaseOrderPaymentData && { + paymentData: purchaseOrderPaymentData, + }), } : undefined, },