@bigcommerce/checkout-sdk 1.817.0 → 1.818.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import{createFormPoster as e}from"@bigcommerce/form-poster";import{createRequestSender as t}from"@bigcommerce/request-sender";import{createScriptLoader as i,getScriptLoader as n}from"@bigcommerce/script-loader";import{isEqual as o,isNil as r,noop as a,omit as s,omitBy as d}from"lodash";var l={};function c(e,t){return Object.assign(e,{resolveIds:t})}l.d=(e,t)=>{for(var i in t)l.o(t,i)&&!l.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},l.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);const m={size:70,color:"#d9d9d9",backgroundColor:"#ffffff"},u="embedded-checkout-loading-indicator-rotation";class h{constructor(e){this.styles=Object.assign(Object.assign({},m),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=`${u} 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)`,e}setStyleAttribute(e,t){Object.keys(t).forEach(i=>{e.style.setProperty(i,t[i])})}defineAnimation(){var e;if(document.getElementById(u))return;const t=document.createElement("style");t.id=u,null===(e=document.head)||void 0===e||e.appendChild(t),t.sheet instanceof CSSStyleSheet&&t.sheet.insertRule(`\n @keyframes ${u} {\n 0% { transform: translateY(-50%) rotate(0deg); }\n 100% { transform: translateY(-50%) rotate(360deg); }\n }\n `,0)}}const y={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"};class p 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 g extends p{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 v;!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"}(v||(v={}));class f extends p{constructor(e){super(function(e){switch(e){case v.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case v.MissingCart:return"Unable to proceed because cart data is unavailable.";case v.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case v.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case v.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case v.MissingCheckoutConfig:case v.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case v.MissingOrder:return"Unable to proceed because order data is unavailable.";case v.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case v.MissingPayment:return"Unable to proceed because payment data is unavailable.";case v.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case v.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case v.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"}}class b extends p{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 P={body:{},headers:{},status:0};class S extends p{constructor(e,{message:t,errors:i}={}){const{body:n,headers:o,status:r}=e||P;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=n,this.headers=o,this.status=r,this.errors=i||[]}}var I,C,w,O,_,k,A,E;!function(e){e.BuyNow="BUY_NOW"}(I||(I={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(C||(C={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(w||(w={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(O||(O={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(_||(_={})),function(e){e.pill="pill",e.rect="rect"}(k||(k={})),function(e){e.OXXO="oxxo"}(A||(A={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(E||(E={}));var T=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class z{constructor(e,t,i,n){this.formPoster=e,this.paymentIntegrationService=t,this.bigCommercePaymentsRequestSender=i,this.bigCommercePaymentsScriptLoader=n}loadPayPalSdk(e,t,i,n){return T(this,void 0,void 0,function*(){const o=this.paymentIntegrationService.getState(),r=t||o.getCartOrThrow().currency.code,a=o.getPaymentMethodOrThrow(e);return this.paypalSdk=yield this.bigCommercePaymentsScriptLoader.getPayPalSDK(a,r,i,n),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new g;return this.paypalSdk}createBuyNowCartOrThrow(e){return T(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new f(v.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new b}})}createOrder(e,t){return T(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:n}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:i},t));return n})}createOrderCardFields(e,t){return T(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:n,setupToken:o}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:i},t));return Object.assign({orderId:n},o?{setupToken:o}:{})})}updateOrder(){return T(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),i=e.getConsignmentsOrThrow()[0];try{yield this.bigCommercePaymentsRequestSender.updateOrder({availableShippingOptions:i.availableShippingOptions,cartId:t.id,selectedShippingOption:i.selectedShippingOption})}catch(e){throw new S}})}getOrderStatus(e,t){return T(this,void 0,void 0,function*(){try{const{status:i}=yield this.bigCommercePaymentsRequestSender.getOrderStatus(e,t);return i}catch(e){throw new S}})}tokenizePayment(e,t){const i=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new f(v.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},i.source===I.BuyNow&&{cart_id:i.id}))}submitPayment(e,t,i){return T(this,void 0,void 0,function*(){const n={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:n},i?{gatewayId:i}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],i=t.availableShippingOptions||[],n=i.find(e=>e.isRecommended),o=(e?i.find(t=>t.id===e):i.find(e=>{var i;return e.id===(null===(i=t.selectedShippingOption)||void 0===i?void 0:i.id)}))||n||i[0];if(!o)throw new Error("Your order can't be shipped to this address");return o}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,i;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===(i=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===i?void 0:i.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:i}=e,{address:n,name:{full_name:o}}=i[0].shipping,[r,...a]=o.split(" ");return this.getAddress({firstName:r,lastName:a.join(" "),email:t.email_address,address1:n.address_line_1,address2:n.address_line_2,city:n.admin_area_2,countryCode:n.country_code,postalCode:n.postal_code,stateOrProvinceCode:n.admin_area_1})}getValidButtonStyle(e){const{color:t,height:i,label:n,shape:o}=e||{},a={color:t&&_[t]?t:void 0,height:this.getValidHeight(i),label:n&&O[n]?n:void 0,shape:o&&k[o]?o:void 0};return d(a,r)}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 F="This API endpoint is for internal use only and may change in the future";var B;!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(B||(B={}));const D=B,x={"X-Checkout-SDK-Version":"1.817.0"};var M=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class N{constructor(e){this.requestSender=e}createOrder(e,t){return M(this,void 0,void 0,function*(){const i=`/api/storefront/payment/${e}`,n=t,o=Object.assign({"X-API-INTERNAL":F,"Content-Type":D.Json},x);return(yield this.requestSender.post(i,{headers:o,body:n})).body})}updateOrder(e){return M(this,void 0,void 0,function*(){const t=e,i=Object.assign({"X-API-INTERNAL":F,"Content-Type":D.Json},x);return(yield this.requestSender.put("/api/storefront/initialization/bigcommerce_payments",{headers:i,body:t})).body})}getOrderStatus(e="bigcommerce_payments",t){return M(this,void 0,void 0,function*(){const i=`/api/storefront/initialization/${e}`,n=Object.assign({"X-API-INTERNAL":F,"Content-Type":D.Json},x);return(yield this.requestSender.get(i,Object.assign({headers:n},t))).body})}}var U=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class j{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,i,n){return U(this,void 0,void 0,function*(){const o=this.getPayPalSdkScriptConfigOrThrow(e,t,i);return this.loadPayPalSDK(o,n)})}loadPayPalSDK(e,t=!1){return U(this,void 0,void 0,function*(){if(!this.window.paypal||t){const t=this.transformConfig(e.options),i=this.transformConfig(e.attributes),n=`https://www.paypal.com/sdk/js?${new URLSearchParams(t).toString()}`;yield this.scriptLoader.loadScript(n,{async:!0,attributes:i})}if(!this.window.paypal)throw new g;return this.window.paypal})}getPayPalSdkScriptConfigOrThrow(e,t,i=!0){const{id:n,clientToken:o,initializationData:r}=e;if(!(null==r?void 0:r.clientId))throw new f(v.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:l,attributionId:c,isVenmoEnabled:m,isHostedCheckoutEnabled:u,isPayPalCreditAvailable:h,isDeveloperModeApplicable:y,availableAlternativePaymentMethods:p=[],enabledAlternativePaymentMethods:g=[],isGooglePayEnabled:b}=r,P=u||i,S="bigcommerce_payments_creditcards"===n,I=S?["card"]:[],C=S?[]:["card"],w=h?["credit","paylater"]:[],O=h?[]:["credit","paylater"],_=i||!P,k=m?["venmo"]:[],A=m?[]:["venmo"],E=_?g:[],T=_?p.filter(e=>!g.includes(e)):p,z=b?["googlepay"]:[],F=i?["card-fields"]:[],B=this.filterFundingOptions([...C,...O,...A,...T]),D=this.filterFundingOptions([...I,...w,...k,...E]);return{options:Object.assign({"client-id":s,"merchant-id":d,"enable-funding":D.length>0?D:void 0,"disable-funding":B.length>0?B:void 0,commit:P,components:["buttons","hosted-fields","payment-fields","legal",...z,...F],currency:t,intent:a},y&&{"buyer-country":l}),attributes:{"data-partner-attribution-id":c,"data-client-token":o}}}filterFundingOptions(e){const t=["klarna"];return e?e.filter(e=>!t.includes(e)):[]}transformConfig(e){let t={};return Object.keys(e).forEach(i=>{const n=e[i];null==n||""===n||Array.isArray(n)&&0===n.length||(t=Object.assign(Object.assign({},t),{[i]:Array.isArray(n)?n.join(","):n}))}),t}}const V=i=>{const{getHost:o}=i.getState();return new z(e(),i,new N(t({host:o()})),new j(n()))};class R extends p{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class L extends R{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 $ extends S{constructor(e){super(e,{message:"There is a problem processing your payment. Please try again later."}),this.name="PaymentMethodInvalidError",this.type="payment_method_invalid"}}class q extends p{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}function H(e){return!("object"!=typeof e||null===e||void 0!==e.shouldSaveInstrument&&"boolean"!=typeof e.shouldSaveInstrument||void 0!==e.shouldSetAsDefaultInstrument&&"boolean"!=typeof e.shouldSetAsDefaultInstrument)}function G(e){return Boolean(e.instrumentId)}function Y(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 W=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class K{constructor(e,t,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=i}initialize(e){var t,i;return W(this,void 0,void 0,function*(){const{methodId:n,bigcommerce_payments:o}=e||{};if(this.bigcommerce_payments=o,!n)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)throw new R('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n);this.loadingIndicatorContainer=o.container.split("#")[1],(null===(t=r.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(i=r.initializationData)||void 0===i?void 0:i.orderId:(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n),o.onInit&&"function"==typeof o.onInit&&o.onInit(()=>this.renderButton(n,o)),(void 0===o.shouldRenderPayPalButtonOnInitialization||o.shouldRenderPayPalButtonOnInitialization)&&this.renderButton(n,o))})}execute(e,t){return W(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(i[n[o]]=e[n[o]])}return i}(e,["payment"]),{onError:o}=this.bigcommerce_payments||{};if(!i)throw new L(["payment"]);const{methodId:r,paymentData:a}=i;if(this.isPayPalVaultedInstrumentPaymentData(a)&&!this.orderId&&(this.orderId=yield this.createOrder()),!this.orderId)throw new $;const s=this.isPayPalVaultedInstrumentPaymentData(a)?this.prepareVaultedInstrumentPaymentPayload(r,this.orderId,a):this.preparePaymentPayload(r,this.orderId,a);try{yield this.paymentIntegrationService.submitOrder(n,t),yield this.paymentIntegrationService.submitPayment(s)}catch(e){return this.isProviderError(e)&&(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i.methodId),yield new Promise((e,t)=>{var n;this.bigcommerce_payments&&(null===(n=this.paypalButton)||void 0===n||n.close(),this.renderButton(i.methodId,this.bigcommerce_payments),this.handleError(new Error("INSTRUMENT_DECLINED"),o)),t()})),this.handleError(e,o),Promise.reject()}})}finalize(){return Promise.reject(new q)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}prepareVaultedInstrumentPaymentPayload(e,t,i){const{instrumentId:n,shouldSetAsDefaultInstrument:o}=i,r=!this.isTrustedVaultingFlow(i);return r?{methodId:e,paymentData:{shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o,formattedPayload:{paypal_account:{order_id:t}}}}:{methodId:e,paymentData:{instrumentId:n,shouldSetAsDefaultInstrument:o,formattedPayload:{paypal_account:{order_id:t},bigpay_token:{token:n}}}}}preparePaymentPayload(e,t,i){const{shouldSaveInstrument:n=!1,shouldSetAsDefaultInstrument:o=!1}=H(i)?i:{};return{methodId:e,paymentData:{shouldSaveInstrument:n,shouldSetAsDefaultInstrument:o,formattedPayload:{paypal_account:{order_id:t}}}}}renderButton(e,t){const i=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:o}=n.initializationData||{},{checkoutPaymentButtonStyles:r}=o||{},{container:a,onError:s,onRenderButton:d,onValidate:l,submitForm:c}=t,m={fundingSource:i.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(r),createOrder:()=>this.createOrder(),onClick:(e,t)=>this.handleClick(t,l),onApprove:e=>this.handleApprove(e,c),onError:e=>this.handleError(e,s),onCancel:()=>this.toggleLoadingIndicator(!1)};this.paypalButton=i.Buttons(m),this.paypalButton.isEligible()&&(d&&"function"==typeof d&&d(),this.paypalButton.render(a))}handleClick(e,t){return W(this,void 0,void 0,function*(){const{resolve:i,reject:n}=e;yield t(()=>(this.toggleLoadingIndicator(!0),i()),n)})}handleApprove({orderID:e},t){this.orderId=e,t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createOrder(){return W(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&&G(e)){const t=this.paymentIntegrationService.getState().getInstruments(),i=null==t?void 0:t.find(t=>Y(t)&&t.bigpayToken===e.instrumentId);return!(Y(i)&&!i.trustedShippingAddress)}return!1}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isPayPalVaultedInstrumentPaymentData(e){return!!e&&G(e)&&H(e)}isProviderError(e){var t,i,n;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"INSTRUMENT_DECLINED"===(null===(n=null===(i=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===i?void 0:i.provider_error)||void 0===n?void 0:n.code)}}const J=c(e=>new K(e,V(e),new h({containerStyles:y})),[{id:"bigcommerce_payments"}]);var X,Z,Q,ee,te,ie,ne,oe,re=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ae{constructor(e){this.scriptLoader=e,this.window=window}getPayPalFastlaneSdk(e,t,i){return re(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const n=this.getPayPalFastlaneSdkConfiguration(e,t,i);if(yield this.loadPayPalSdk(n),!this.window.paypalFastlaneSdk)throw new g}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,i,n){return re(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||n){const n=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,i);yield this.loadPayPalSdk(n)}if(!this.window.paypalGooglePay)throw new g;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t){return re(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new g}return this.window.paypalApms})}getPayPalMessages(e,t){return re(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new g;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return re(this,void 0,void 0,function*(){const i=this.transformConfig(e),n=this.transformConfig(t),o=`https://www.paypal.com/sdk/js?${new URLSearchParams(i).toString()}`;yield this.scriptLoader.loadScript(o,{async:!0,attributes:n})})}getPayPalFastlaneSdkConfiguration(e,t,i){const{clientToken:n,initializationData:o}=e;if(!o||!o.clientId)throw new f(v.MissingPaymentMethod);const{intent:r,clientId:a,merchantId:s,attributionId:d}=o;return{options:{"client-id":a,"merchant-id":s,commit:!0,components:["fastlane","three-domain-secure"],currency:t,intent:r},attributes:{"data-client-metadata-id":i.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":d,"data-sdk-client-token":n}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,i=!0){const{clientToken:n,initializationData:o}=e;if(!o||!o.clientId)throw new f(v.MissingPaymentMethod);const{intent:r,clientId:a,merchantId:s,buyerCountry:d,attributionId:l,isHostedCheckoutEnabled:c,isDeveloperModeApplicable:m}=o,u=c||i;return{options:Object.assign({"client-id":a,"merchant-id":s,commit:u,components:["googlepay"],currency:t,intent:r},m&&{"buyer-country":d}),attributes:{"data-partner-attribution-id":l,"data-client-token":n,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t){const{initializationData:i}=e;if(!i||!i.clientId)throw new f(v.MissingPaymentMethod);const{intent:n,clientId:o,merchantId:r,buyerCountry:a,attributionId:s,isDeveloperModeApplicable:d,availableAlternativePaymentMethods:l=[],enabledAlternativePaymentMethods:c=[]}=i,m=this.filterFundingOptions(c),u=this.filterFundingOptions(l.filter(e=>!c.includes(e)));return{options:Object.assign({"client-id":o,"merchant-id":r,"enable-funding":m.length>0?m:void 0,"disable-funding":u.length>0?u:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:n},d&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":s,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t){const{initializationData:i}=e;if(!i||!i.clientId)throw new f(v.MissingPaymentMethod);const{clientId:n,merchantId:o,attributionId:r,isDeveloperModeApplicable:a,buyerCountry:s}=i;return{options:Object.assign({"client-id":n,"merchant-id":o,components:["messages"],currency:t},a&&{"buyer-country":s}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":r}}}filterFundingOptions(e){const t=["klarna"];return e?e.filter(e=>!t.includes(e)):[]}transformConfig(e){let t={};return Object.keys(e).forEach(i=>{const n=e[i];null==n||""===n||Array.isArray(n)&&0===n.length||(t=Object.assign(Object.assign({},t),{[i]:Array.isArray(n)?n.join(","):n}))}),t}}function se(){return new ae(i())}!function(e){e.CVV="cvv",e.PAN="pan"}(X||(X={}));class de{static get(e){const t=`${encodeURIComponent(`${e}`)}=`,i=document.cookie;let n=null;const o=i.indexOf(t);if(o>-1){let e=i.indexOf(";",o);-1===e&&(e=i.length),n=decodeURIComponent(i.substring(o+t.length,e))}return n}static set(e,t,i={secure:!0}){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;const{expires:o,path:r,domain:a,secure:s}=i;if(o)n+=`; expires=${o.toUTCString()}`;else{const e=new Date,t=60;e.setTime(e.getTime()+60*t*1e3),n+=`; expires=${e.toUTCString()}`}r&&(n+=`; path=${r}`),a&&(n+=`; domain=${a}`),s&&(n+="; secure"),document.cookie=n}static remove(e,t){de.set(e,"",Object.assign({expires:new Date(0)},t))}}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Z||(Z={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(Q||(Q={})),function(e){e.Succeeded="succeeded",e.Cancelled="cancelled",e.Errored="errored"}(ee||(ee={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(te||(te={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(ie||(ie={})),function(e){e.pill="pill",e.rect="rect"}(ne||(ne={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="canceled",e.UNRECOGNIZED="unrecognized"}(oe||(oe={}));var le=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ce{constructor(){this.window=window}initializePayPalFastlane(e,t,i){return le(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:i||t})}return this.window.paypalFastlane})}getPayPalFastlaneOrThrow(){if(!this.window.paypalFastlane)throw new g;return this.window.paypalFastlane}lookupCustomerOrThrow(e){return le(this,void 0,void 0,function*(){return this.getPayPalFastlaneOrThrow().identity.lookupCustomerByEmail(e)})}triggerAuthenticationFlowOrThrow(e){return le(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 i={expires:t,secure:!0};de.set("bc-fastlane-sessionId",e,i)}removeStorageSessionId(){de.remove("bc-fastlane-sessionId")}getStorageSessionId(){return de.get("bc-fastlane-sessionId")||""}mapPayPalFastlaneProfileToBcCustomerData(e,t){var i,n,o;const{authenticationState:r,profileData:a}=t,s=null===(o=null===(n=null===(i=null==a?void 0:a.card)||void 0===i?void 0:i.paymentSource)||void 0===n?void 0:n.card)||void 0===o?void 0:o.billingAddress,d=null==a?void 0:a.shippingAddress,l=null==a?void 0:a.name,c=null==a?void 0:a.card,m=d?this.mapPayPalToBcAddress(d.address,d.name,d.phoneNumber):void 0,u=s&&l?this.mapPayPalToBcAddress(s,l,null==d?void 0:d.phoneNumber):void 0,h=c?this.mapPayPalToBcInstrument(e,c):[],y=this.filterAddresses([m,u]);return{authenticationState:r||oe.UNRECOGNIZED,addresses:y,billingAddress:u,shippingAddress:m,instruments:h}}mapPayPalToBcInstrument(e,t){const{id:i,paymentSource:n}=t,{brand:o,expiry:r,lastDigits:a}=n.card,[s,d]=r.split("-");return[{bigpayToken:i,brand:o,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:X.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,i,n){const[o,r]=t.fullName.split(" "),a=(null==i?void 0:i.nationalNumber)||"",s=(null==i?void 0:i.countryCode)||"";return{id:Date.now(),type:"paypal-address",firstName:t.firstName||o||"",lastName:t.lastName||r||"",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:n||[]}}filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this.isEqualAddresses(e,t))?e:[...e,t]:e,[])}isEqualAddresses(e,t){return o(this.normalizeAddress(e),this.normalizeAddress(t))}normalizeAddress(e){return s(e,["id","phone"])}}function me(){return new ce}function ue(e){return"string"!=typeof e}function he(e,t){if(t||e)return function(e){var t,i;const n={},o=d(e.root,ue),r=d(e.input,ue),a=d(e.toggle,ue),s=d(null===(t=e.text)||void 0===t?void 0:t.body,ue),l=d(null===(i=e.text)||void 0===i?void 0:i.caption,ue),c=e.branding;return Object.keys(o).length&&(n.root=o),Object.keys(r).length&&(n.input=r),Object.keys(a).length&&(n.toggle=a),Object.keys(s).length&&(n.text={},n.text.body=s),Object.keys(l).length&&(n.text=Object.assign({},n.text),n.text.caption=l),c&&(n.branding=c),n}(function(e,t){var i,n,o,r,a,s,d,l,c,m,u,h,y,p,g,v,f,b,P,S,I,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.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===(l=null==t?void 0:t.input)||void 0===l?void 0:l.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(c=null==t?void 0:t.input)||void 0===c?void 0:c.focusBorderColor),backgroundColor:(null==e?void 0:e.fastlaneInputSettingsBackgroundColor)||(null===(m=null==t?void 0:t.input)||void 0===m?void 0:m.backgroundColor),borderWidth:(null==e?void 0:e.fastlaneInputSettingsBorderWidth)||(null===(u=null==t?void 0:t.input)||void 0===u?void 0:u.borderWidth),textColorBase:(null==e?void 0:e.fastlaneInputSettingsTextColorBase)||(null===(h=null==t?void 0:t.input)||void 0===h?void 0:h.textColorBase)},toggle:{colorPrimary:(null==e?void 0:e.fastlaneToggleSettingsColorPrimary)||(null===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorPrimary),colorSecondary:(null==e?void 0:e.fastlaneToggleSettingsColorSecondary)||(null===(p=null==t?void 0:t.toggle)||void 0===p?void 0:p.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===(b=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===b?void 0:b.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(S=null===(P=null==t?void 0:t.text)||void 0===P?void 0:P.caption)||void 0===S?void 0:S.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))}function ye(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}function pe(e,t,i=!0){var n;return null!==(n=e[t])&&void 0!==n?n:i}var ge=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ve{constructor(e,t,i,n){this.paymentIntegrationService=e,this.bigCommercePaymentsRequestSender=t,this.bigCommercePaymentsSdk=i,this.bigCommercePaymentsFastlaneUtils=n}initialize(e){var t,i;return ge(this,void 0,void 0,function*(){const{methodId:n,bigcommerce_payments_fastlane:o}=e;if(!n)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(this.methodId=n,!o)throw new R('Unable to initialize payment because "options.bigcommerce_payments_fastlane" argument is not provided.');if(this.bigcommerce_payments_fastlane=o,!o.onInit||"function"!=typeof o.onInit)throw new R('Unable to initialize payment because "options.bigcommerce_payments_fastlane.onInit" argument is not provided or it is not a function.');if(!o.onChange||"function"!=typeof o.onChange)throw new R('Unable to initialize payment because "options.bigcommerce_payments_fastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(n);const r=this.paymentIntegrationService.getState(),a=r.getCartOrThrow(),s=r.getPaymentMethodOrThrow(n),{isDeveloperModeApplicable:d,isFastlaneStylingEnabled:l}=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 c=he(l?null===(i=null==s?void 0:s.initializationData)||void 0===i?void 0:i.fastlaneStyles:{},null==o?void 0:o.styles);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(this.paypalFastlaneSdk,!!d,c),this.shouldRunAuthenticationFlow()&&(yield this.runPayPalAuthenticationFlowOrThrow(n)),yield this.initializePayPalPaymentComponent(),o.onInit(e=>this.renderPayPalPaymentComponent(e)),o.onChange(()=>this.handlePayPalStoredInstrumentChange(n))})}execute(e,t){return ge(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(i[n[o]]=e[n[o]])}return i}(e,["payment"]);if(!i)throw new L(["payment"]);const{paymentData:o,methodId:r}=i,a=o&&G(o);try{yield this.paymentIntegrationService.submitOrder(n,t);const e=a?yield this.prepareVaultedInstrumentPaymentPayload(r,o):yield this.preparePaymentPayload(r,o);yield this.paymentIntegrationService.submitPayment(e),this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId()}catch(e){if(function(e){return"object"==typeof e&&null!==e&&"message"in e&&"response"in e&&"name"in e.response}(e)&&"INVALID_REQUEST"===e.response.name){const e={translationKey:"payment.errors.invalid_request_error"};return this.handleError(e),Promise.reject()}if(e instanceof Error&&"FastlaneError"!==e.name)throw e;return Promise.reject()}})}finalize(){return Promise.reject(new q)}deinitialize(){return ge(this,void 0,void 0,function*(){return Promise.resolve()})}shouldRunAuthenticationFlow(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),i=e.getCustomerOrThrow(),n=e.getPaymentProviderCustomer(),o=ye(n)?n:{},r=this.bigCommercePaymentsFastlaneUtils.getStorageSessionId();return!(!i.isGuest||(null==o?void 0:o.authenticationState)===oe.CANCELED||(null==o?void 0:o.authenticationState)||r!==t.id)}runPayPalAuthenticationFlowOrThrow(e){return ge(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getCustomer(),o=t.getBillingAddress(),r=(null==n?void 0:n.email)||(null==o?void 0:o.email)||"",{customerContextId:a}=yield this.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(r),s=yield this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(a),{authenticationState:d,addresses:l,instruments:c}=this.bigCommercePaymentsFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,s);yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:d,addresses:l,instruments:c}),s.authenticationState===oe.CANCELED?this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId():this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(i.id)}catch(e){}})}initializePayPalPaymentComponent(){return ge(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),t=e.phone,i=`${e.firstName} ${e.lastName}`.trim(),n=this.bigCommercePaymentsFastlaneUtils.getPayPalFastlaneOrThrow(),o={fields:Object.assign({cardholderName:{prefill:i,enabled:!0}},t&&{phoneNumber:{prefill:t}})};this.paypalComponentMethods=yield n.FastlaneCardComponent(o)})}renderPayPalPaymentComponent(e){const t=this.getPayPalComponentMethodsOrThrow();if(!e)throw new R('Unable to render card component because "container" argument is not provided.');t.render(e)}getPayPalComponentMethodsOrThrow(){if(!this.paypalComponentMethods)throw new g;return this.paypalComponentMethods}prepareVaultedInstrumentPaymentPayload(e,t){return ge(this,void 0,void 0,function*(){const{instrumentId:i}=t,n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),o=this.isBigcommercePaymentsFastlaneThreeDSAvailable()&&n.config.is3dsEnabled;o||(yield this.createOrder(i));const r=o?yield this.get3DSNonce(i):i;return{methodId:e,paymentData:{formattedPayload:{paypal_fastlane_token:{order_id:this.orderId,token:r}}}}})}preparePaymentPayload(e,t){return ge(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=i.getBillingAddressOrThrow(),o=i.getPaymentMethodOrThrow(e),r=`${n.firstName} ${n.lastName}`.trim(),{getPaymentToken:a}=this.getPayPalComponentMethodsOrThrow(),{id:s}=yield a({name:{fullName:r},billingAddress:this.bigCommercePaymentsFastlaneUtils.mapBcToPayPalAddress(n)}),d=this.isBigcommercePaymentsFastlaneThreeDSAvailable()&&o.config.is3dsEnabled;d||(yield this.createOrder(s));const{shouldSaveInstrument:l=!1,shouldSetAsDefaultInstrument:c=!1}=H(t)?t:{},m=d?yield this.get3DSNonce(s):s;return{methodId:e,paymentData:Object.assign(Object.assign({},t),{shouldSaveInstrument:l,shouldSetAsDefaultInstrument:c,formattedPayload:{paypal_fastlane_token:{order_id:this.orderId,token:m}}})}})}createOrder(e){return ge(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getCartOrThrow().id;if(this.methodId){const{orderId:i}=yield this.bigCommercePaymentsRequestSender.createOrder(this.methodId,{cartId:t,fastlaneToken:e});this.orderId=i}})}get3DSNonce(e){var t;return ge(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=i.getCartOrThrow(),o=i.getOrderOrThrow(),r=i.getStoreConfigOrThrow().links.checkoutLink,a=null===(t=this.paypalFastlaneSdk)||void 0===t?void 0:t.ThreeDomainSecureClient;if(!a)throw new g;const s={amount:o.orderAmount.toFixed(2),currency:n.currency.code,nonce:e,threeDSRequested:"SCA_ALWAYS"===this.threeDSVerificationMethod,transactionContext:{experience_context:{locale:"en-US",return_url:r,cancel_url:r}}};if(yield a.isEligible(s)){const{liabilityShift:t,authenticationState:i,nonce:n}=yield a.show();if(t===C.No||t===C.Unknown)throw new $;if(yield this.createOrder(e),i===ee.Succeeded)return n;if(i===ee.Errored)throw new $;if(i===ee.Cancelled)throw console.error("3DS check was canceled"),new $}return e})}handlePayPalStoredInstrumentChange(e){return ge(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsFastlaneUtils.getPayPalFastlaneOrThrow(),{selectionChanged:i,selectedCard:n}=yield t.profile.showCardSelector();if(i){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),i=ye(t)?t:{},o=this.bigCommercePaymentsFastlaneUtils.mapPayPalToBcInstrument(e,n)[0];return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},i),{instruments:[o]})),o}})}isBigcommercePaymentsFastlaneThreeDSAvailable(){return pe(this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features,"PROJECT-7080.bcp_fastlane_three_ds")}handleError(e){var t;(null===(t=this.bigcommerce_payments_fastlane)||void 0===t?void 0:t.onError)&&"function"==typeof this.bigcommerce_payments_fastlane.onError&&this.bigcommerce_payments_fastlane.onError(e)}}const fe=c(e=>{const{getHost:i}=e.getState();return new ve(e,new N(t({host:i()})),se(),me())},[{id:"bigcommerce_payments_fastlane"}]),be=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};class Pe extends p{constructor(e){super(e||"Not implemented."),this.name="NotImplementedError",this.type="not_implemented"}}var Se=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ie{constructor(e,t,i,n){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=i,this.paypalSdkHelper=n}initialize(e){return Se(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_paylater:i}=e||{};if(!t)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new R('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState(),o=n.getPaymentMethodOrThrow(t),{paypalBNPLConfiguration:r=[],orderId:a}=o.initializationData||{},{bannerContainerId:s,container:d}=i;if(void 0!==s){if(!document.getElementById(s))return void console.error("Unable to create banner without valid banner container ID.");const e=r&&r.find(({id:e})=>"checkout"===e);if(!(null==e?void 0:e.status))return;const t=yield this.paypalSdkHelper.getPayPalMessages(o,n.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,i))})}execute(e,t){return Se(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(i[n[o]]=e[n[o]])}return i}(e,["payment"]);if(!i)throw new L(["payment"]);if(!this.orderId)throw new $;yield this.paymentIntegrationService.submitOrder(n,t),yield this.bigCommercePaymentsIntegrationService.submitPayment(i.methodId,this.orderId)})}finalize(){return Promise.reject(new q)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.bigCommercePaymentsButtons)||void 0===e||e.close(),Promise.resolve()}renderButton(e,t){if(!(null==t?void 0:t.container))throw new R('Unable to initialize payment because "container" argument is not provided.');const i=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:o}=n.initializationData||{},{checkoutPaymentButtonStyles:r}=o||{},{container:a,onError:s,onRenderButton:d,onValidate:l,submitForm:c}=t,m=[i.FUNDING.PAYLATER,i.FUNDING.CREDIT];let u=!1;m.forEach(e=>{if(u)return;const t={fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(r),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onClick:(e,t)=>this.handleClick(t,l),onApprove:e=>this.handleApprove(e,c),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.bigCommercePaymentsButtons=i.Buttons(t),this.bigCommercePaymentsButtons.isEligible()||e!==i.FUNDING.PAYLATER){if(!this.bigCommercePaymentsButtons.isEligible()&&e===i.FUNDING.CREDIT)throw new Pe(`BigCommercePayments ${e} is not available for your region. Please use BigCommercePayments Checkout instead.`);d&&"function"==typeof d&&d(),this.bigCommercePaymentsButtons.render(a),u=!0}})}handleClick(e,t){return Se(this,void 0,void 0,function*(){const{resolve:i,reject:n}=e;t&&"function"==typeof t&&(yield t(()=>(this.toggleLoadingIndicator(!0),i()),n))})}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,i){const n={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:be(i)};e.Messages(n).render(`#${t}`)}}const Ce=c(e=>new Ie(e,V(e),new h({containerStyles:y}),se()),[{id:"bigcommerce_payments_paylater"}]);class we extends S{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}var Oe=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class _e{constructor(e,t,i,n=3e3,o=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=i,this.pollingInterval=n,this.maxPollingIntervalTime=o,this.pollingTimer=0,this.stopPolling=a}initialize(e){return Oe(this,void 0,void 0,function*(){const{gatewayId:t,methodId:i,bigcommerce_payments_ratepay:n}=e;if(!i)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new R('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!n)throw new R('Unable to initialize payment because "options.bigcommerce_payments_ratepay" argument is not provided.');const{legalTextContainer:o,container:r,loadingContainerId:a}=n;if(!r)throw new R('Unable to initialize payment because "options.container" argument is not provided.');if(!o)throw new R('Unable to initialize payment because "options.legalTextContainer" argument is not provided.');if(!a)throw new R('Unable to initialize payment because "options.loadingContainerId" argument is not provided.');this.loadingIndicatorContainer=a;const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,t),{merchantId:d}=s.initializationData||{};if(!d)throw new R("Unable to initialize payment because merchantId argument is not provided.");this.bigcommerce_payments_ratepay=n,yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i),this.createFraudNetScript(d,i,t),this.loadFraudnetConfig(),this.renderLegalText(o,r)})}execute(e,t){return Oe(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(i[n[o]]=e[n[o]])}return i}(e,["payment"]),{getFieldsValues:o}=this.bigcommerce_payments_ratepay||{};if(!i)throw new L(["payment"]);if(!o||"function"!=typeof o)throw new R('Unable to initialize payment because "options.getFieldsValues" argument is not provided.');this.toggleLoadingIndicator(!0);try{const e=yield this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apmscheckout",{metadataId:this.guid}),{ratepayBirthDate:r,ratepayPhoneNumber:a,ratepayPhoneCountryCode:s}=o(),d={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:i.methodId,rate_pay:{birth_date:this.normalizeDate(r),phone:{national_number:a,country_code:s.split("+")[1]}},paypal_account:{order_id:e}}};return yield this.paymentIntegrationService.submitOrder(n,t),yield this.paymentIntegrationService.submitPayment({methodId:i.methodId,paymentData:d}),yield new Promise((e,t)=>{this.initializePollingMechanism(i.methodId,e,t,i.gatewayId)})}catch(e){return this.handleError(e),new Promise((e,t)=>t())}})}finalize(){return Promise.reject(new q)}deinitialize(){const{legalTextContainer:e}=this.bigcommerce_payments_ratepay||{},t=document.querySelectorAll('[data-id="fraudnetScript"]')[0],i=document.querySelectorAll('[data-id="fraudnetConfig"]')[0];if(this.deinitializePollingMechanism(),t.remove(),i.remove(),e){const t=document.getElementById(e);null==t||t.remove()}return Promise.resolve()}normalizeDate(e){const t=this.formatDate(e.getDate()),i=this.formatDate(e.getMonth()+1);return`${e.getFullYear()}-${i}-${t}`}formatDate(e){return`${e<10?0:""}${e}`}renderLegalText(e,t){const i=e,n=t.split("#")[1],o=document.getElementById(n),r=null==o?void 0:o.parentNode,a=document.createElement("div");a.style.marginBottom="20px",a.setAttribute("id",i),null==r||r.prepend(a);const s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=s.Legal({fundingSource:s.Legal.FUNDING.PAY_UPON_INVOICE});if(!document.getElementById(i))throw new R('Unable to initialize payment because "legalTextContainerElement" argument is not found.');d.render(`#${i}`)}handleError(e){const{onError:t}=this.bigcommerce_payments_ratepay||{};this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createFraudNetScript(e,t,i){const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,i),{testMode:o}=n.config,r=document.createElement("script");r.setAttribute("type","application/json"),r.setAttribute("fncls","fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99"),r.setAttribute("data-id","fraudnetScript"),this.guid=this.generateGUID();const a={f:this.guid,s:`${e}_checkout-page`,sandbox:o};r.innerHTML=JSON.stringify(a),document.body.appendChild(r)}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 Oe(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}initializePollingMechanism(e,t,i,n){return Oe(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const i=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(i),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const o=yield this.bigCommercePaymentsIntegrationService.getOrderStatus("bigcommerce_payments_apms",{params:{useMetadata:!0}}),r=o===E.PollingStop,a=o===E.PollingError;if(r)return this.deinitializePollingMechanism(),t();if(a)return i();if(!r&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,i,n);yield this.reinitializeStrategy({methodId:e,gatewayId:n,bigcommerce_payments_ratepay:this.bigcommerce_payments_ratepay}),this.handleError(new we)}catch(e){this.handleError(e),i()}})}deinitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deinitializePollingMechanism()}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const ke=c(e=>new _e(e,V(e),new h({containerStyles:Object.assign(Object.assign({},y),{position:"fixed"})})),[{gateway:"bigcommerce_payments_apms",id:"ratepay"}]);var Ae;!function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification",e.CardExpiryVerification="cardExpiryVerification"}(Ae||(Ae={}));const Ee=Ae;function Te(e){return Ee.CardNumber in e&&Ee.CardName in e&&Ee.CardExpiry in e}function ze(e){return Ee.CardNumberVerification in e&&Ee.CardCodeVerification in e&&Ee.CardExpiryVerification in e}class Fe extends p{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"}}var Be;!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"}(Be||(Be={}));class De extends p{constructor(e){super(function(e){switch(e){case Be.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case Be.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case Be.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case Be.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 xe extends p{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"}}var Me=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ne{constructor(e,t,i,n){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdk=i,this.bigCommercePaymentsFastlaneUtils=n}initialize(e){return Me(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_creditcards:i}=e,n=i,{form:o,onCreditCardFieldsRenderingError:r,onLoadComplete:a}=n||{};if(!t)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)throw new R('Unable to proceed because "options.bigcommerce_payments_creditcards.form" argument is not provided.');this.hostedFormOptions=o,this.isCreditCardForm=Te(o.fields),this.isCreditCardVaultedForm=ze(o.fields)&&!this.hasUndefinedValues(),yield this.paymentIntegrationService.loadPaymentMethod(t),yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t,void 0,!0,!0),null==a||a(),(this.isCreditCardForm||this.isCreditCardVaultedForm)&&(yield this.initializeFields(o,r)),this.shouldInitializePayPalFastlane(t)&&(yield this.initializePayPalFastlaneOrThrow(t))})}execute(e,t){return Me(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(i[n[o]]=e[n[o]])}return i}(e,["payment"]),{methodId:o,paymentData:r}=i||{};if(!i||!o)throw new L(["payment"]);if(this.executionPaymentData=r,this.isCreditCardForm||this.isCreditCardVaultedForm)yield this.validateHostedFormOrThrow(),yield this.submitHostedForm();else{const{orderId:e}=yield this.bigCommercePaymentsIntegrationService.createOrderCardFields("bigcommerce_payments_creditcardscheckout",this.getInstrumentParams());this.returnedOrderId=e}const a=this.preparePaymentPayload(o,r,this.returnedOrderId,this.returnedVaultedToken);yield this.paymentIntegrationService.submitOrder(n,t),yield this.paymentIntegrationService.submitPayment(a)})}finalize(){return Promise.reject(new q)}deinitialize(){var e,t,i,n;return Me(this,void 0,void 0,function*(){return yield null===(e=this.cvvField)||void 0===e?void 0:e.close(),yield null===(t=this.expiryField)||void 0===t?void 0:t.close(),yield null===(i=this.numberField)||void 0===i?void 0:i.close(),yield null===(n=this.nameField)||void 0===n?void 0:n.close(),Promise.resolve()})}preparePaymentPayload(e,t,i,n){const{shouldSaveInstrument:o=!1,shouldSetAsDefaultInstrument:a=!1}=H(t)?t:{},s=t&&G(t)?t.instrumentId:void 0,l=d({verification_nonce:n,token:s},r);return{methodId:e,paymentData:{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a,instrumentId:s,formattedPayload:Object.assign(Object.assign({},n||s?{bigpay_token:l}:{}),i?{card_with_order:{order_id:i}}:{})}}}initializeFields(e,t){return Me(this,void 0,void 0,function*(){const{fields:i,styles:n}=e,o=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),r=this.getExecuteCallback(i),a=Object.assign({style:this.getInputStyles(n),onApprove:({orderID:e,vaultSetupToken:t,liabilityShift:i})=>{if(i===C.No||i===C.Unknown)throw new Error;return this.handleApprove({orderID:e,vaultSetupToken:t})},onError:()=>{throw new Fe},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)}},r);if(this.cardFields=yield o.CardFields(a),!this.cardFields.isEligible())throw new De(Be.PaymentNotInitialized);try{this.stylizeInputContainers(i),Te(i)&&(yield this.renderFields(i)),ze(i)&&(yield this.renderVaultedFields(i))}catch(e){"function"==typeof t&&t(e)}})}getExecuteCallback(e){return ze(e)?this.createVaultSetupTokenCallback():this.createOrderCallback()}createVaultSetupTokenCallback(){return{createVaultSetupToken:()=>Me(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:()=>Me(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,i,n,o;return Me(this,void 0,void 0,function*(){const r=this.getCardFieldsOrThrow();(null===(t=e.cardCode)||void 0===t?void 0:t.containerId)&&(this.cvvField=r.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCode.containerId}`)),(null===(i=e.cardExpiry)||void 0===i?void 0:i.containerId)&&(this.expiryField=r.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiry.containerId}`)),(null===(n=e.cardName)||void 0===n?void 0:n.containerId)&&(this.nameField=r.NameField({placeholder:""}),yield this.nameField.render(`#${e.cardName.containerId}`)),(null===(o=e.cardNumber)||void 0===o?void 0:o.containerId)&&(this.numberField=r.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumber.containerId}`))})}renderVaultedFields(e){var t,i,n;return Me(this,void 0,void 0,function*(){const o=this.getCardFieldsOrThrow();(null===(t=e.cardCodeVerification)||void 0===t?void 0:t.containerId)&&(this.cvvField=o.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCodeVerification.containerId}`)),(null===(i=e.cardExpiryVerification)||void 0===i?void 0:i.containerId)&&(this.expiryField=o.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiryVerification.containerId}`)),(null===(n=e.cardNumberVerification)||void 0===n?void 0:n.containerId)&&(this.numberField=o.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumberVerification.containerId}`))})}getInstrumentParams(){if(!this.executionPaymentData)return{};if(H(this.executionPaymentData)){const{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}=this.executionPaymentData;return{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}}if(G(this.executionPaymentData)){const{instrumentId:e}=this.executionPaymentData;return{instrumentId:e}}return{}}getFieldTypeByEmittedField({emittedBy:e}){return{fieldType:this.mapFieldType(e)}}submitHostedForm(){return Me(this,void 0,void 0,function*(){const e=this.getCardFieldsOrThrow(),t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),i={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(i)}catch(e){throw new Fe("Failed authentication. Please try to authorize again.")}})}validateHostedFormOrThrow(){var e,t;return Me(this,void 0,void 0,function*(){const i=this.getCardFieldsOrThrow(),n=yield i.getState().then(e=>e),o=this.getValidityData(n);if(!o.isValid)throw null===(t=null===(e=this.hostedFormOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,o),new xe(this.mapValidationErrors(o.errors))})}getValidityData({fields:e}){const t=Object.assign({},e);delete t.cardNameField;const i=Object.keys(t);return{isValid:i.every(e=>{var i;return null===(i=t[e])||void 0===i?void 0:i.isValid}),errors:i.reduce((e,i)=>{var n;const o=this.mapFieldType(i);return Object.assign(Object.assign({},e),{[o]:(null===(n=t[i])||void 0===n?void 0:n.isValid)?void 0:[this.getInvalidErrorByFieldType(o)]})},{})}}getInvalidErrorByFieldType(e){switch(e){case Ee.CardCode:case Ee.CardCodeVerification:return{fieldType:e,message:"Invalid card code",type:"invalid_card_code"};case Ee.CardNumber:case Ee.CardNumberVerification:return{fieldType:e,message:"Invalid card number",type:"invalid_card_number"};case Ee.CardExpiry:case Ee.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(i=>{var n,o;t[i]=[{message:(null===(o=null===(n=e[i])||void 0===n?void 0:n[0])||void 0===o?void 0:o.message)||"",type:i}]}),t}mapFieldType(e){switch(e){case"name":return Ee.CardName;case"cardNumberField":case"number":return this.isCreditCardForm?Ee.CardNumber:Ee.CardNumberVerification;case"cardExpiryField":case"expiry":return this.isCreditCardForm?Ee.CardExpiry:Ee.CardExpiryVerification;case"cardCvvField":case"cvv":return this.isCreditCardForm?Ee.CardCode:Ee.CardCodeVerification;default:throw new Error("Unexpected field type")}}getCardFieldsOrThrow(){if(!this.cardFields)throw new De(Be.PaymentNotInitialized);return this.cardFields}getInputStyles(e){var t,i,n;const o={"font-size":(null===(t=null==e?void 0:e.default)||void 0===t?void 0:t.fontSize)||"1rem","font-family":(null===(i=null==e?void 0:e.default)||void 0===i?void 0:i.fontFamily)||"Montserrat, Arial, Helvetica, sans-serif","font-weight":(null===(n=null==e?void 0:e.default)||void 0===n?void 0:n.fontWeight)||"400",outline:"none",padding:"9px 13px"},r=Object.assign(Object.assign({},o),{color:"#333333"});return{input:r,".invalid":Object.assign(Object.assign({},o),{color:"red"}),".valid":r,":focus":r}}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 i;null===(i=null==e?void 0:e.onValidate)||void 0===i||i.call(e,this.getValidityData(t))}onFocusHandler(e,t){var i;null===(i=null==e?void 0:e.onFocus)||void 0===i||i.call(e,this.getFieldTypeByEmittedField(t))}onBlurHandler(e,t){var i;null===(i=null==e?void 0:e.onBlur)||void 0===i||i.call(e,this.getFieldTypeByEmittedField(t))}onInputSubmitRequest(e,t){var i;null===(i=null==e?void 0:e.onEnter)||void 0===i||i.call(e,this.getFieldTypeByEmittedField(t))}shouldInitializePayPalFastlane(e){var t,i;const n=this.paymentIntegrationService.getState(),o=n.getPaymentMethodOrThrow(e),r=n.getPaymentProviderCustomer(),a=(s=r)&&("authenticationState"in s||"addresses"in s||"instruments"in s)?r:{};var s;return(null===(t=null==o?void 0:o.initializationData)||void 0===t?void 0:t.isAcceleratedCheckoutEnabled)&&(null===(i=null==o?void 0:o.initializationData)||void 0===i?void 0:i.isBigCommercePaymentsAnalyticsV2Enabled)&&!(null==a?void 0:a.authenticationState)}initializePayPalFastlaneOrThrow(e){return Me(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getPaymentMethodOrThrow(e),{initializationData:o}=n;if(!(null==o?void 0:o.connectClientToken))return;const r=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(n,i.currency.code,i.id);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(r,!!(null==o?void 0:o.isDeveloperModeApplicable))}catch(e){}})}}const Ue=c(e=>new Ne(e,V(e),se(),me()),[{id:"bigcommerce_payments_creditcards"}]);var je=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ve{constructor(e,t,i,n,o=3e3,r=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdkHelper=i,this.loadingIndicator=n,this.pollingInterval=o,this.maxPollingIntervalTime=r,this.pollingTimer=0,this.stopPolling=a,this.isPollingEnabled=!1}initialize(e){return je(this,void 0,void 0,function*(){const{gatewayId:t,methodId:i,bigcommerce_payments_apms:n}=e;if(this.bigCommercePaymentsAlternativeMethods=n,!i)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new R('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!n)throw new R('Unable to initialize payment because "options.bigcommerce_payments_apms" argument is not provided.');const o=this.paymentIntegrationService.getState(),r=o.getPaymentMethodOrThrow(i,t),{orderId:a,shouldRenderFields:s}=r.initializationData||{},d=o.getStoreConfigOrThrow().checkoutSettings.features;this.isPollingEnabled=pe(d,"PAYPAL-5624.bcp_ideal_polling"),a?this.orderId=a:(this.paypalApms=yield this.bigCommercePaymentsSdkHelper.getPayPalApmsSdk(r,o.getCartOrThrow().currency.code),this.loadingIndicatorContainer=n.container.split("#")[1],this.renderButton(i,t,n),s&&this.renderFields(i,n))})}execute(e,t){return je(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(i[n[o]]=e[n[o]])}return i}(e,["payment"]);if(!i)throw new L(["payment"]);const{methodId:o,gatewayId:r}=i;if(!this.orderId)throw new $;this.isPollingEnabled&&"ideal"===o&&(yield new Promise((e,t)=>{this.initializePollingMechanism(o,e,t,r)})),this.isNonInstantPaymentMethod(o)||(yield this.paymentIntegrationService.submitOrder(n,t)),yield this.bigCommercePaymentsIntegrationService.submitPayment(o,this.orderId,r)})}finalize(){return Promise.reject(new q)}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,i,n){return je(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const i=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(i),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const o=yield this.bigCommercePaymentsIntegrationService.getOrderStatus(n),r=o===E.Approved,a=o===E.PollingError;if(r)return this.deInitializePollingMechanism(),t();if(a)return i();if(!r&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,i,n);yield this.reinitializeStrategy({methodId:e,gatewayId:n,bigCommercePaymentsAlternativeMethods:this.bigCommercePaymentsAlternativeMethods}),this.handleError(new we)}catch(e){i()}})}deInitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deInitializePollingMechanism()}reinitializeStrategy(e){return je(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}handleError(e){const{onError:t}=this.bigCommercePaymentsAlternativeMethods||{};this.isPollingEnabled&&this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderButton(e,t,i){const n=this.getPaypalAmpsSdkOrThrow(),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t),{buttonStyle:r}=o.initializationData||{},{container:a,onError:s,onRenderButton:d,submitForm:l}=i,c={fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(r),onInit:(e,t)=>i.onInitButton(t),createOrder:()=>this.onCreateOrder(e,t,i),onApprove:e=>this.handleApprove(e,l),onCancel:()=>{this.toggleLoadingIndicator(!1),this.deInitializePollingMechanism()},onError:e=>{this.deInitializePollingMechanism(),this.handleFailure(e,s)},onClick:(e,t)=>je(this,void 0,void 0,function*(){return i.onValidate(t.resolve,t.reject)})};this.bigCommercePaymentsButton=n.Buttons(c),this.bigCommercePaymentsButton.isEligible()&&(d&&"function"==typeof d&&d(),this.bigCommercePaymentsButton.render(a))}onCreateOrder(e,t,i){return je(this,void 0,void 0,function*(){const{onValidate:n}=i;yield n(()=>(this.toggleLoadingIndicator(!0),()=>Promise.resolve()),a);const o=yield this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apms");if(this.isNonInstantPaymentMethod(e)){const i={useStoreCredit:!1},n={params:{methodId:e,gatewayId:t}};yield this.paymentIntegrationService.submitOrder(i,n),yield this.bigCommercePaymentsIntegrationService.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 i=this.getPaypalAmpsSdkOrThrow(),n=this.paymentIntegrationService.getState(),{firstName:o,lastName:r,email:a}=n.getBillingAddressOrThrow(),{apmFieldsContainer:s,apmFieldsStyles:d}=t;if(!s)throw new R('Unable to initialize payment because "options.bigcommerce_payments_apms" argument should contain "apmFieldsContainer".');const l=document.querySelector(s);l&&(l.innerHTML="");const c={fundingSource:e,style:d||{},fields:{name:{value:`${o} ${r}`},email:{value:a}}};i.PaymentFields(c).render(s)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isNonInstantPaymentMethod(e){return e.toUpperCase()in A}getPaypalAmpsSdkOrThrow(){if(!this.paypalApms)throw new g;return this.paypalApms}}const Re=c(e=>new Ve(e,V(e),se(),new h({containerStyles:y})),[{gateway:"bigcommerce_payments_apms"}]);var Le=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class $e{constructor(e,t,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=i}initialize(e){var t,i;return Le(this,void 0,void 0,function*(){const{methodId:n,bigcommerce_payments_venmo:o}=e||{};if(!n)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)throw new R('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n);(null===(t=r.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(i=r.initializationData)||void 0===i?void 0:i.orderId:(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n),this.loadingIndicatorContainer=o.container.split("#")[1],this.renderButton(n,o))})}execute(e,t){return Le(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(i[n[o]]=e[n[o]])}return i}(e,["payment"]);if(!i)throw new L(["payment"]);if(!this.orderId)throw new $;yield this.paymentIntegrationService.submitOrder(n,t),yield this.bigCommercePaymentsIntegrationService.submitPayment(i.methodId,this.orderId)})}finalize(){return Promise.reject(new q)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}renderButton(e,t){const i=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:o}=n.initializationData||{},{checkoutPaymentButtonStyles:r}=o||{},{container:a,onError:s,onRenderButton:d,onValidate:l,submitForm:c}=t,m={fundingSource:i.FUNDING.VENMO,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(r),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo_checkout"),onClick:(e,t)=>this.handleClick(t,l),onApprove:e=>this.handleApprove(e,c),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=i.Buttons(m),!this.paypalButton.isEligible())throw new Pe("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 Le(this,void 0,void 0,function*(){const{resolve:i,reject:n}=e;yield t(()=>(this.toggleLoadingIndicator(!0),i()),n)})}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 qe=c(e=>new $e(e,V(e),new h({styles:{backgroundColor:"black"}})),[{id:"bigcommerce_payments_venmo"}]);var He=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ge{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=a}initialize(e){return He(this,void 0,void 0,function*(){const{bigcommerce_payments:t,methodId:i}=e;if(!i)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new R('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');if(!t.container)throw new R('Unable to initialize payment because "options.bigcommerce_payments.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new R('Unable to initialize payment because "options.bigcommerce_payments.onClick" argument is not a function.');this.onError=t.onError||a,this.paymentIntegrationService.getState().getPaymentMethod(i)||(yield this.paymentIntegrationService.loadPaymentMethod(i));const n=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i);n&&n.Buttons&&"function"==typeof n.Buttons?this.renderButton(i,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 He(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return He(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){const{container:i,onClick:n,onComplete:o}=t,r=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:s,paymentButtonStyles:d}=a.initializationData||{},{checkoutTopButtonStyles:l}=d||{},c=Object.assign({createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},n&&{onClick:()=>n()}),m={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(t,i)=>this.onHostedCheckoutApprove(t,i,e,o)},u=Object.assign(Object.assign({fundingSource:r.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},l),{height:36}))},c),s&&m),h=r.Buttons(u);h.isEligible()?h.render(`#${i}`):this.bigCommercePaymentsIntegrationService.removeElement(i)}onHostedCheckoutApprove(e,t,i,n){return He(this,void 0,void 0,function*(){if(!e.orderID)throw new f(v.MissingOrderId);const o=this.paymentIntegrationService.getState().getCartOrThrow(),r=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(r);if(yield this.paymentIntegrationService.updateBillingAddress(t),o.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(r);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:i}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return He(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 He(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 Ye=c(e=>new Ge(e,V(e)),[{id:"bigcommerce_payments"}]);var We=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ke{constructor(e,t,i){this.paymentIntegrationService=e,this.bigCommercePaymentsSdk=t,this.bigCommercePaymentsFastlaneUtils=i}initialize(e){var t;return We(this,void 0,void 0,function*(){const{methodId:i,bigcommerce_payments_fastlane:n}=e;if(!i)throw new R('Unable to proceed because "methodId" argument is not provided.');try{yield this.paymentIntegrationService.loadPaymentMethod(i);const e=this.paymentIntegrationService.getState(),o=e.getCartOrThrow(),r=e.getPaymentMethodOrThrow(i),a=!!(null===(t=r.initializationData)||void 0===t?void 0:t.isDeveloperModeApplicable),s=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(r,o.currency.code,o.id);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(s,a,this.getFastlaneStyles(i,n))}catch(e){}return Promise.resolve()})}deinitialize(){return We(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return We(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return We(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return We(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:i,methodId:n}=e||{};if(!n)throw new R('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof i)throw new R('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(n)}catch(e){}}i()})}runPayPalAuthenticationFlowOrThrow(e){return We(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow().id,n=t.getCustomer(),o=t.getBillingAddress(),r=(null==n?void 0:n.email)||(null==o?void 0:o.email)||"",{customerContextId:a}=yield this.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(r),s=yield this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(a),d=s.authenticationState===oe.CANCELED;yield this.updateCustomerDataState(e,s),d?this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId():this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(i)})}updateCustomerDataState(e,t){var i;return We(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow(),{authenticationState:o,addresses:r,billingAddress:a,shippingAddress:s,instruments:d}=this.bigCommercePaymentsFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,t);if(yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:o,addresses:r,instruments:d}),a&&(yield this.paymentIntegrationService.updateBillingAddress(a)),s&&n.lineItems.physicalItems.length>0){const t=yield this.paymentIntegrationService.updateShippingAddress(s),n=t.getPaymentMethodOrThrow(e),{isFastlaneShippingOptionAutoSelectEnabled:o}=n.initializationData||{},r=t.getConsignments()||[],a=(null===(i=r[0])||void 0===i?void 0:i.availableShippingOptions)||[],d=a[0],l=a.find(e=>e.isRecommended);if((l||d)&&o){const e=(null==l?void 0:l.id)||d.id;yield this.paymentIntegrationService.selectShippingOption(e)}}})}getFastlaneStyles(e,t){const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{fastlaneStyles:n,isFastlaneStylingEnabled:o}=i.initializationData||{};return he(o?n:{},null==t?void 0:t.styles)}}const Je=c(e=>new Ke(e,se(),me()),[{id:"bigcommerce_payments_fastlane"},{id:"bigcommerce_payments_creditcards"}]);var Xe=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ze{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=a}initialize(e){return Xe(this,void 0,void 0,function*(){const{bigcommerce_payments_paylater:t,methodId:i}=e;if(!i)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new R('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');if(!t.container)throw new R('Unable to initialize payment because "options.bigcommerce_payments_paylater.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new R('Unable to initialize payment because "options.bigcommerce_payments_paylater.onClick" argument is not a function.');this.onError=t.onError||a,this.paymentIntegrationService.getState().getPaymentMethod(i)||(yield this.paymentIntegrationService.loadPaymentMethod(i));const n=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i);n&&n.Buttons&&"function"==typeof n.Buttons?this.renderButton(i,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 Xe(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Xe(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:i,onComplete:n,onClick:o}=t,r=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:s,paymentButtonStyles:d}=a.initializationData||{},{checkoutTopButtonStyles:l}=d||{},c=Object.assign({createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},o&&{onClick:()=>o()}),m={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(t,i)=>this.onHostedCheckoutApprove(t,i,e,n)},u=[r.FUNDING.PAYLATER,r.FUNDING.CREDIT];let h=!1;u.forEach(e=>{if(!h){const t=Object.assign(Object.assign({fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},l),{height:36}))},c),s&&m),n=r.Buttons(t);n.isEligible()&&(n.render(`#${i}`),h=!0)}}),h||this.bigCommercePaymentsIntegrationService.removeElement(i)}onHostedCheckoutApprove(e,t,i,n){return Xe(this,void 0,void 0,function*(){if(!e.orderID)throw new f(v.MissingOrderId);const o=this.paymentIntegrationService.getState().getCartOrThrow(),r=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(r);if(yield this.paymentIntegrationService.updateBillingAddress(t),o.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(r);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:i}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Xe(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 Xe(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 Qe=c(e=>new Ze(e,V(e)),[{id:"bigcommerce_payments_paylater"}]);var et=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class tt{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return et(this,void 0,void 0,function*(){const{bigcommerce_payments_venmo:t,methodId:i}=e;if(!i)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new R('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');if(!t.container)throw new R('Unable to initialize payment because "options.bigcommerce_payments_venmo.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new R('Unable to initialize payment because "options.bigcommerce_payments_venmo.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(i)||(yield this.paymentIntegrationService.loadPaymentMethod(i));const n=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i);n&&n.Buttons&&"function"==typeof n.Buttons?this.renderButton(i,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 et(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return et(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:i,onClick:n}=t,o=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:a}=r.initializationData||{},{checkoutTopButtonStyles:s}=a||{},d=Object.assign({fundingSource:o.FUNDING.VENMO,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},s),{height:36})),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},n&&{onClick:()=>n()}),l=o.Buttons(d);l.isEligible()?l.render(`#${i}`):this.bigCommercePaymentsIntegrationService.removeElement(i)}}const it=c(e=>new tt(e,V(e)),[{id:"bigcommerce_payments_venmo"}]);var nt=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ot{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){var t;return nt(this,void 0,void 0,function*(){const{bigcommerce_payments:i,containerId:n,methodId:o}=e,r=Boolean(null==i?void 0:i.buyNowInitializeOptions);if(!o)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new R('Unable to initialize payment because "options.containerId" argument is not provided.');if(!i)throw new R('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');if(r&&!i.currencyCode)throw new R('Unable to initialize payment because "options.bigcommerce_payments.currencyCode" argument is not provided.');if(r&&"function"!=typeof(null===(t=i.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody))throw new R('Unable to initialize payment because "options.bigcommerce_payments.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');r||(yield this.paymentIntegrationService.loadDefaultCheckout());const a=r?i.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(o,a,!1),this.renderButton(n,o,i)})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{buyNowInitializeOptions:n,style:o,onComplete:r,onEligibilityFailure:a}=i,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:l}=d.initializationData||{},c={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},m={onClick:()=>this.handleClick(n),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},u={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(e,i)=>this.onHostedCheckoutApprove(e,i,t,r)},h=Object.assign(Object.assign(Object.assign({fundingSource:s.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o)},c),n&&m),l&&u),y=s.Buttons(h);y.isEligible()?y.render(`#${e}`):a&&"function"==typeof a?a():this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return nt(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,i,n){return nt(this,void 0,void 0,function*(){if(!e.orderID)throw new f(v.MissingOrderId);const o=this.paymentIntegrationService.getState().getCartOrThrow(),r=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(r);if(yield this.paymentIntegrationService.updateBillingAddress(t),o.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(r);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:i}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return nt(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 nt(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 rt=c(e=>new ot(e,V(e)),[{id:"bigcommerce_payments"}]);var at=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class st{constructor(e,t,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.payPalSdkHelper=i}initialize(e){return at(this,void 0,void 0,function*(){const{bigcommerce_payments_paylater:t,containerId:i,methodId:n}=e,{buyNowInitializeOptions:o,currencyCode:r,messagingContainerId:a}=t||{},s=!!o;if(!n)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new R('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new R('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');if(s&&!r)throw new R('Unable to initialize payment because "options.bigcommerce_payments_paylater.currencyCode" argument is not provided.');if(s&&"function"!=typeof(null==o?void 0:o.getBuyNowCartRequestBody))throw new R('Unable to initialize payment because "options.bigcommerce_payments_paylater.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');s||(yield this.paymentIntegrationService.loadDefaultCheckout());const d=this.paymentIntegrationService.getState(),l=s?r:d.getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n,l,!1),this.renderButton(i,n,t);const c=a&&document.getElementById(a);if(l&&c){const e=d.getPaymentMethodOrThrow(n),{paypalBNPLConfiguration:t=[]}=e.initializationData||{},i=t&&t.find(({id:e})=>"cart"===e);if(!(null==i?void 0:i.status))return;c.removeAttribute("data-pp-style-logo-type"),c.removeAttribute("data-pp-style-logo-position"),c.removeAttribute("data-pp-style-text-color"),c.removeAttribute("data-pp-style-text-size");const o=yield this.payPalSdkHelper.getPayPalMessages(e,l);this.renderMessages(o,a,i)}})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{buyNowInitializeOptions:n,style:o,onComplete:r,onEligibilityFailure:a}=i,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:l}=d.initializationData||{},c={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},m={onClick:()=>this.handleClick(n),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},u={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(e,i)=>this.onHostedCheckoutApprove(e,i,t,r)},h=[s.FUNDING.PAYLATER,s.FUNDING.CREDIT];let y=!1;h.forEach(t=>{if(!y){const i=Object.assign(Object.assign(Object.assign({fundingSource:t,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o)},c),n&&m),l&&u),r=s.Buttons(i);r.isEligible()?(r.render(`#${e}`),y=!0):a&&"function"==typeof a&&a()}}),y||this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return at(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,i,n){return at(this,void 0,void 0,function*(){if(!e.orderID)throw new f(v.MissingOrderId);const o=this.paymentIntegrationService.getState().getCartOrThrow(),r=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(r);if(yield this.paymentIntegrationService.updateBillingAddress(t),o.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(r);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:i}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return at(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 at(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}})}renderMessages(e,t,i){const n={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"cart",style:be(i)};e.Messages(n).render(`#${t}`)}}const dt=c(e=>new st(e,V(e),se()),[{id:"bigcommerce_payments_paylater"}]);var lt=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ct{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return lt(this,void 0,void 0,function*(){const{bigcommerce_payments_apms:t,containerId:i,methodId:n}=e,{apm:o,buyNowInitializeOptions:r,currencyCode:a}=t||{},s=!!r;if(!n)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new R('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new R('Unable to initialize payment because "options.bigcommerce_payments_apms" argument is not provided.');if(!o)throw new R('Unable to initialize payment because "options.bigcommerce_payments_apms.apm" argument is not provided.');if(s&&!a)throw new R('Unable to initialize payment because "options.bigcommerce_payments_apms.currencyCode" argument is not provided.');if(s&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new R('Unable to initialize payment because "options.bigcommerce_payments_apms.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');s||(yield this.paymentIntegrationService.loadDefaultCheckout());const d=s?a:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n,d,!1),this.renderButton(i,n,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{apm:n,buyNowInitializeOptions:o,style:r,onEligibilityFailure:a}=i,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();if(!Object.values(s.FUNDING).includes(n))throw new R('Unable to initialize PayPal button because "options.bigcommerce_payments_apms.apm" argument is not valid funding source.');const d={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apms"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},l={onClick:()=>this.handleClick(o),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},c=Object.assign(Object.assign({fundingSource:n,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(r)},d),o&&l),m=s.Buttons(c);m.isEligible()?m.render(`#${e}`):a&&"function"==typeof a?a():this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return lt(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const mt=c(e=>new ct(e,V(e)),[{id:"bigcommerce_payments_apms"}]);var ut=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ht{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return ut(this,void 0,void 0,function*(){const{bigcommerce_payments_venmo:t,containerId:i,methodId:n}=e,{buyNowInitializeOptions:o,currencyCode:r}=t||{},a=!!o;if(!n)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new R('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new R('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');if(a&&!r)throw new R('Unable to initialize payment because "options.bigcommerce_payments_venmo.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==o?void 0:o.getBuyNowCartRequestBody))throw new R('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?r:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n,s,!1),this.renderButton(i,n,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{buyNowInitializeOptions:n,style:o,onEligibilityFailure:r}=i,a=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),s=a.FUNDING.VENMO,d={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},l={onClick:()=>this.handleClick(n),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},c=Object.assign(Object.assign({fundingSource:s,style:this.getValidVenmoButtonStyles(o)},d),n&&l),m=a.Buttons(c);m.isEligible()?m.render(`#${e}`):r&&"function"==typeof r?r():this.bigCommercePaymentsIntegrationService.removeElement(e)}getValidVenmoButtonStyles(e){const t=this.bigCommercePaymentsIntegrationService.getValidButtonStyle(e);return t.color===_.gold?Object.assign(Object.assign({},t),{color:void 0}):t}handleClick(e){return ut(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const yt=c(e=>new ht(e,V(e)),[{id:"bigcommerce_payments_venmo"}]);export{mt as createBigCommercePaymentsAlternativeMethodsButtonStrategy,Re as createBigCommercePaymentsAlternativeMethodsPaymentStrategy,rt as createBigCommercePaymentsButtonStrategy,Ue as createBigCommercePaymentsCreditCardsPaymentStrategy,Ye as createBigCommercePaymentsCustomerStrategy,Je as createBigCommercePaymentsFastlaneCustomerStrategy,fe as createBigCommercePaymentsFastlanePaymentStrategy,dt as createBigCommercePaymentsPayLaterButtonStrategy,Qe as createBigCommercePaymentsPayLaterCustomerStrategy,Ce as createBigCommercePaymentsPayLaterPaymentStrategy,J as createBigCommercePaymentsPaymentStrategy,ke as createBigCommercePaymentsRatePayPayPaymentStrategy,yt as createBigCommercePaymentsVenmoButtonStrategy,it as createBigCommercePaymentsVenmoCustomerStrategy,qe as createBigCommercePaymentsVenmoPaymentStrategy};
1
+ import{createFormPoster as e}from"@bigcommerce/form-poster";import{createRequestSender as t}from"@bigcommerce/request-sender";import{createScriptLoader as i,getScriptLoader as n}from"@bigcommerce/script-loader";import{isEqual as o,isNil as r,noop as a,omit as s,omitBy as d}from"lodash";var l={};function c(e,t){return Object.assign(e,{resolveIds:t})}l.d=(e,t)=>{for(var i in t)l.o(t,i)&&!l.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},l.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);const m={size:70,color:"#d9d9d9",backgroundColor:"#ffffff"},u="embedded-checkout-loading-indicator-rotation";class h{constructor(e){this.styles=Object.assign(Object.assign({},m),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=`${u} 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)`,e}setStyleAttribute(e,t){Object.keys(t).forEach(i=>{e.style.setProperty(i,t[i])})}defineAnimation(){var e;if(document.getElementById(u))return;const t=document.createElement("style");t.id=u,null===(e=document.head)||void 0===e||e.appendChild(t),t.sheet instanceof CSSStyleSheet&&t.sheet.insertRule(`\n @keyframes ${u} {\n 0% { transform: translateY(-50%) rotate(0deg); }\n 100% { transform: translateY(-50%) rotate(360deg); }\n }\n `,0)}}const y={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"};class p 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 g extends p{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 v;!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"}(v||(v={}));class f extends p{constructor(e){super(function(e){switch(e){case v.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case v.MissingCart:return"Unable to proceed because cart data is unavailable.";case v.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case v.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case v.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case v.MissingCheckoutConfig:case v.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case v.MissingOrder:return"Unable to proceed because order data is unavailable.";case v.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case v.MissingPayment:return"Unable to proceed because payment data is unavailable.";case v.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case v.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case v.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"}}class b extends p{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 P={body:{},headers:{},status:0};class S extends p{constructor(e,{message:t,errors:i}={}){const{body:n,headers:o,status:r}=e||P;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=n,this.headers=o,this.status=r,this.errors=i||[]}}var I,C,w,O,_,k,A,E;!function(e){e.BuyNow="BUY_NOW"}(I||(I={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(C||(C={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(w||(w={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(O||(O={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(_||(_={})),function(e){e.pill="pill",e.rect="rect"}(k||(k={})),function(e){e.OXXO="oxxo"}(A||(A={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(E||(E={}));var T=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class z{constructor(e,t,i,n){this.formPoster=e,this.paymentIntegrationService=t,this.bigCommercePaymentsRequestSender=i,this.bigCommercePaymentsScriptLoader=n}loadPayPalSdk(e,t,i,n){return T(this,void 0,void 0,function*(){const o=this.paymentIntegrationService.getState(),r=t||o.getCartOrThrow().currency.code,a=o.getPaymentMethodOrThrow(e);return this.paypalSdk=yield this.bigCommercePaymentsScriptLoader.getPayPalSDK(a,r,i,n),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new g;return this.paypalSdk}createBuyNowCartOrThrow(e){return T(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new f(v.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new b}})}createOrder(e,t){return T(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:n}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:i},t));return n})}createOrderCardFields(e,t){return T(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:n,setupToken:o}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:i},t));return Object.assign({orderId:n},o?{setupToken:o}:{})})}updateOrder(){return T(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),i=e.getConsignmentsOrThrow()[0];try{yield this.bigCommercePaymentsRequestSender.updateOrder({availableShippingOptions:i.availableShippingOptions,cartId:t.id,selectedShippingOption:i.selectedShippingOption})}catch(e){throw new S}})}getOrderStatus(e,t){return T(this,void 0,void 0,function*(){try{const{status:i}=yield this.bigCommercePaymentsRequestSender.getOrderStatus(e,t);return i}catch(e){throw new S}})}tokenizePayment(e,t){const i=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new f(v.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},i.source===I.BuyNow&&{cart_id:i.id}))}submitPayment(e,t,i){return T(this,void 0,void 0,function*(){const n={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:n},i?{gatewayId:i}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],i=t.availableShippingOptions||[],n=i.find(e=>e.isRecommended),o=(e?i.find(t=>t.id===e):i.find(e=>{var i;return e.id===(null===(i=t.selectedShippingOption)||void 0===i?void 0:i.id)}))||n||i[0];if(!o)throw new Error("Your order can't be shipped to this address");return o}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,i;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===(i=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===i?void 0:i.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:i}=e,{address:n,name:{full_name:o}}=i[0].shipping,[r,...a]=o.split(" ");return this.getAddress({firstName:r,lastName:a.join(" "),email:t.email_address,address1:n.address_line_1,address2:n.address_line_2,city:n.admin_area_2,countryCode:n.country_code,postalCode:n.postal_code,stateOrProvinceCode:n.admin_area_1})}getValidButtonStyle(e){const{color:t,height:i,label:n,shape:o}=e||{},a={color:t&&_[t]?t:void 0,height:this.getValidHeight(i),label:n&&O[n]?n:void 0,shape:o&&k[o]?o:void 0};return d(a,r)}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 F="This API endpoint is for internal use only and may change in the future";var B;!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(B||(B={}));const D=B,x={"X-Checkout-SDK-Version":"1.818.0"};var M=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class N{constructor(e){this.requestSender=e}createOrder(e,t){return M(this,void 0,void 0,function*(){const i=`/api/storefront/payment/${e}`,n=t,o=Object.assign({"X-API-INTERNAL":F,"Content-Type":D.Json},x);return(yield this.requestSender.post(i,{headers:o,body:n})).body})}updateOrder(e){return M(this,void 0,void 0,function*(){const t=e,i=Object.assign({"X-API-INTERNAL":F,"Content-Type":D.Json},x);return(yield this.requestSender.put("/api/storefront/initialization/bigcommerce_payments",{headers:i,body:t})).body})}getOrderStatus(e="bigcommerce_payments",t){return M(this,void 0,void 0,function*(){const i=`/api/storefront/initialization/${e}`,n=Object.assign({"X-API-INTERNAL":F,"Content-Type":D.Json},x);return(yield this.requestSender.get(i,Object.assign({headers:n},t))).body})}}var U=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class j{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,i,n){return U(this,void 0,void 0,function*(){const o=this.getPayPalSdkScriptConfigOrThrow(e,t,i);return this.loadPayPalSDK(o,n)})}loadPayPalSDK(e,t=!1){return U(this,void 0,void 0,function*(){if(!this.window.paypal||t){const t=this.transformConfig(e.options),i=this.transformConfig(e.attributes),n=`https://www.paypal.com/sdk/js?${new URLSearchParams(t).toString()}`;yield this.scriptLoader.loadScript(n,{async:!0,attributes:i})}if(!this.window.paypal)throw new g;return this.window.paypal})}getPayPalSdkScriptConfigOrThrow(e,t,i=!0){const{id:n,clientToken:o,initializationData:r}=e;if(!(null==r?void 0:r.clientId))throw new f(v.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:l,attributionId:c,isVenmoEnabled:m,isHostedCheckoutEnabled:u,isPayPalCreditAvailable:h,isDeveloperModeApplicable:y,availableAlternativePaymentMethods:p=[],enabledAlternativePaymentMethods:g=[],isGooglePayEnabled:b}=r,P=u||i,S="bigcommerce_payments_creditcards"===n,I=S?["card"]:[],C=S?[]:["card"],w=h?["credit","paylater"]:[],O=h?[]:["credit","paylater"],_=i||!P,k=m?["venmo"]:[],A=m?[]:["venmo"],E=_?g:[],T=_?p.filter(e=>!g.includes(e)):p,z=b?["googlepay"]:[],F=i?["card-fields"]:[],B=this.filterFundingOptions([...C,...O,...A,...T]),D=this.filterFundingOptions([...I,...w,...k,...E]);return{options:Object.assign({"client-id":s,"merchant-id":d,"enable-funding":D.length>0?D:void 0,"disable-funding":B.length>0?B:void 0,commit:P,components:["buttons","hosted-fields","payment-fields","legal",...z,...F],currency:t,intent:a},y&&{"buyer-country":l}),attributes:{"data-partner-attribution-id":c,"data-client-token":o}}}filterFundingOptions(e){const t=["klarna"];return e?e.filter(e=>!t.includes(e)):[]}transformConfig(e){let t={};return Object.keys(e).forEach(i=>{const n=e[i];null==n||""===n||Array.isArray(n)&&0===n.length||(t=Object.assign(Object.assign({},t),{[i]:Array.isArray(n)?n.join(","):n}))}),t}}const V=i=>{const{getHost:o}=i.getState();return new z(e(),i,new N(t({host:o()})),new j(n()))};class R extends p{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class L extends R{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 $ extends S{constructor(e){super(e,{message:"There is a problem processing your payment. Please try again later."}),this.name="PaymentMethodInvalidError",this.type="payment_method_invalid"}}class q extends p{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}function H(e){return!("object"!=typeof e||null===e||void 0!==e.shouldSaveInstrument&&"boolean"!=typeof e.shouldSaveInstrument||void 0!==e.shouldSetAsDefaultInstrument&&"boolean"!=typeof e.shouldSetAsDefaultInstrument)}function G(e){return Boolean(e.instrumentId)}function Y(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 W=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class K{constructor(e,t,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=i}initialize(e){var t,i;return W(this,void 0,void 0,function*(){const{methodId:n,bigcommerce_payments:o}=e||{};if(this.bigcommerce_payments=o,!n)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)throw new R('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n);this.loadingIndicatorContainer=o.container.split("#")[1],(null===(t=r.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(i=r.initializationData)||void 0===i?void 0:i.orderId:(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n),o.onInit&&"function"==typeof o.onInit&&o.onInit(()=>this.renderButton(n,o)),(void 0===o.shouldRenderPayPalButtonOnInitialization||o.shouldRenderPayPalButtonOnInitialization)&&this.renderButton(n,o))})}execute(e,t){return W(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(i[n[o]]=e[n[o]])}return i}(e,["payment"]),{onError:o}=this.bigcommerce_payments||{};if(!i)throw new L(["payment"]);const{methodId:r,paymentData:a}=i;if(this.isPayPalVaultedInstrumentPaymentData(a)&&!this.orderId&&(this.orderId=yield this.createOrder()),!this.orderId)throw new $;const s=this.isPayPalVaultedInstrumentPaymentData(a)?this.prepareVaultedInstrumentPaymentPayload(r,this.orderId,a):this.preparePaymentPayload(r,this.orderId,a);try{yield this.paymentIntegrationService.submitOrder(n,t),yield this.paymentIntegrationService.submitPayment(s)}catch(e){return this.isProviderError(e)&&(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i.methodId),yield new Promise((e,t)=>{var n;this.bigcommerce_payments&&(null===(n=this.paypalButton)||void 0===n||n.close(),this.renderButton(i.methodId,this.bigcommerce_payments),this.handleError(new Error("INSTRUMENT_DECLINED"),o)),t()})),this.handleError(e,o),Promise.reject()}})}finalize(){return Promise.reject(new q)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}prepareVaultedInstrumentPaymentPayload(e,t,i){const{instrumentId:n,shouldSetAsDefaultInstrument:o}=i,r=!this.isTrustedVaultingFlow(i);return r?{methodId:e,paymentData:{shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o,formattedPayload:{paypal_account:{order_id:t}}}}:{methodId:e,paymentData:{instrumentId:n,shouldSetAsDefaultInstrument:o,formattedPayload:{paypal_account:{order_id:t},bigpay_token:{token:n}}}}}preparePaymentPayload(e,t,i){const{shouldSaveInstrument:n=!1,shouldSetAsDefaultInstrument:o=!1}=H(i)?i:{};return{methodId:e,paymentData:{shouldSaveInstrument:n,shouldSetAsDefaultInstrument:o,formattedPayload:{paypal_account:{order_id:t}}}}}renderButton(e,t){const i=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:o}=n.initializationData||{},{checkoutPaymentButtonStyles:r}=o||{},{container:a,onError:s,onRenderButton:d,onValidate:l,submitForm:c}=t,m={fundingSource:i.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(r),createOrder:()=>this.createOrder(),onClick:(e,t)=>this.handleClick(t,l),onApprove:e=>this.handleApprove(e,c),onError:e=>this.handleError(e,s),onCancel:()=>this.toggleLoadingIndicator(!1)};this.paypalButton=i.Buttons(m),this.paypalButton.isEligible()&&(d&&"function"==typeof d&&d(),this.paypalButton.render(a))}handleClick(e,t){return W(this,void 0,void 0,function*(){const{resolve:i,reject:n}=e;yield t(()=>(this.toggleLoadingIndicator(!0),i()),n)})}handleApprove({orderID:e},t){this.orderId=e,t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createOrder(){return W(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&&G(e)){const t=this.paymentIntegrationService.getState().getInstruments(),i=null==t?void 0:t.find(t=>Y(t)&&t.bigpayToken===e.instrumentId);return!(Y(i)&&!i.trustedShippingAddress)}return!1}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isPayPalVaultedInstrumentPaymentData(e){return!!e&&G(e)&&H(e)}isProviderError(e){var t,i,n;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"INSTRUMENT_DECLINED"===(null===(n=null===(i=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===i?void 0:i.provider_error)||void 0===n?void 0:n.code)}}const J=c(e=>new K(e,V(e),new h({containerStyles:y})),[{id:"bigcommerce_payments"}]);var X,Z,Q,ee,te,ie,ne,oe,re=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ae{constructor(e){this.scriptLoader=e,this.window=window}getPayPalFastlaneSdk(e,t,i){return re(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const n=this.getPayPalFastlaneSdkConfiguration(e,t,i);if(yield this.loadPayPalSdk(n),!this.window.paypalFastlaneSdk)throw new g}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,i,n){return re(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||n){const n=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,i);yield this.loadPayPalSdk(n)}if(!this.window.paypalGooglePay)throw new g;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t){return re(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new g}return this.window.paypalApms})}getPayPalMessages(e,t){return re(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new g;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return re(this,void 0,void 0,function*(){const i=this.transformConfig(e),n=this.transformConfig(t),o=`https://www.paypal.com/sdk/js?${new URLSearchParams(i).toString()}`;yield this.scriptLoader.loadScript(o,{async:!0,attributes:n})})}getPayPalFastlaneSdkConfiguration(e,t,i){const{clientToken:n,initializationData:o}=e;if(!o||!o.clientId)throw new f(v.MissingPaymentMethod);const{intent:r,clientId:a,merchantId:s,attributionId:d}=o;return{options:{"client-id":a,"merchant-id":s,commit:!0,components:["fastlane","three-domain-secure"],currency:t,intent:r},attributes:{"data-client-metadata-id":i.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":d,"data-sdk-client-token":n}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,i=!0){const{clientToken:n,initializationData:o}=e;if(!o||!o.clientId)throw new f(v.MissingPaymentMethod);const{intent:r,clientId:a,merchantId:s,buyerCountry:d,attributionId:l,isHostedCheckoutEnabled:c,isDeveloperModeApplicable:m}=o,u=c||i;return{options:Object.assign({"client-id":a,"merchant-id":s,commit:u,components:["googlepay"],currency:t,intent:r},m&&{"buyer-country":d}),attributes:{"data-partner-attribution-id":l,"data-client-token":n,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t){const{initializationData:i}=e;if(!i||!i.clientId)throw new f(v.MissingPaymentMethod);const{intent:n,clientId:o,merchantId:r,buyerCountry:a,attributionId:s,isDeveloperModeApplicable:d,availableAlternativePaymentMethods:l=[],enabledAlternativePaymentMethods:c=[]}=i,m=this.filterFundingOptions(c),u=this.filterFundingOptions(l.filter(e=>!c.includes(e)));return{options:Object.assign({"client-id":o,"merchant-id":r,"enable-funding":m.length>0?m:void 0,"disable-funding":u.length>0?u:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:n},d&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":s,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t){const{initializationData:i}=e;if(!i||!i.clientId)throw new f(v.MissingPaymentMethod);const{clientId:n,merchantId:o,attributionId:r,isDeveloperModeApplicable:a,buyerCountry:s}=i;return{options:Object.assign({"client-id":n,"merchant-id":o,components:["messages"],currency:t},a&&{"buyer-country":s}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":r}}}filterFundingOptions(e){const t=["klarna"];return e?e.filter(e=>!t.includes(e)):[]}transformConfig(e){let t={};return Object.keys(e).forEach(i=>{const n=e[i];null==n||""===n||Array.isArray(n)&&0===n.length||(t=Object.assign(Object.assign({},t),{[i]:Array.isArray(n)?n.join(","):n}))}),t}}function se(){return new ae(i())}!function(e){e.CVV="cvv",e.PAN="pan"}(X||(X={}));class de{static get(e){const t=`${encodeURIComponent(`${e}`)}=`,i=document.cookie;let n=null;const o=i.indexOf(t);if(o>-1){let e=i.indexOf(";",o);-1===e&&(e=i.length),n=decodeURIComponent(i.substring(o+t.length,e))}return n}static set(e,t,i={secure:!0}){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;const{expires:o,path:r,domain:a,secure:s}=i;if(o)n+=`; expires=${o.toUTCString()}`;else{const e=new Date,t=60;e.setTime(e.getTime()+60*t*1e3),n+=`; expires=${e.toUTCString()}`}r&&(n+=`; path=${r}`),a&&(n+=`; domain=${a}`),s&&(n+="; secure"),document.cookie=n}static remove(e,t){de.set(e,"",Object.assign({expires:new Date(0)},t))}}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Z||(Z={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(Q||(Q={})),function(e){e.Succeeded="succeeded",e.Cancelled="cancelled",e.Errored="errored"}(ee||(ee={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(te||(te={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(ie||(ie={})),function(e){e.pill="pill",e.rect="rect"}(ne||(ne={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="canceled",e.UNRECOGNIZED="unrecognized"}(oe||(oe={}));var le=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ce{constructor(){this.window=window}initializePayPalFastlane(e,t,i){return le(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:i||t})}return this.window.paypalFastlane})}getPayPalFastlaneOrThrow(){if(!this.window.paypalFastlane)throw new g;return this.window.paypalFastlane}lookupCustomerOrThrow(e){return le(this,void 0,void 0,function*(){return this.getPayPalFastlaneOrThrow().identity.lookupCustomerByEmail(e)})}triggerAuthenticationFlowOrThrow(e){return le(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 i={expires:t,secure:!0};de.set("bc-fastlane-sessionId",e,i)}removeStorageSessionId(){de.remove("bc-fastlane-sessionId")}getStorageSessionId(){return de.get("bc-fastlane-sessionId")||""}mapPayPalFastlaneProfileToBcCustomerData(e,t){var i,n,o;const{authenticationState:r,profileData:a}=t,s=null===(o=null===(n=null===(i=null==a?void 0:a.card)||void 0===i?void 0:i.paymentSource)||void 0===n?void 0:n.card)||void 0===o?void 0:o.billingAddress,d=null==a?void 0:a.shippingAddress,l=null==a?void 0:a.name,c=null==a?void 0:a.card,m=d?this.mapPayPalToBcAddress(d.address,d.name,d.phoneNumber):void 0,u=s&&l?this.mapPayPalToBcAddress(s,l,null==d?void 0:d.phoneNumber):void 0,h=c?this.mapPayPalToBcInstrument(e,c):[],y=this.filterAddresses([m,u]);return{authenticationState:r||oe.UNRECOGNIZED,addresses:y,billingAddress:u,shippingAddress:m,instruments:h}}mapPayPalToBcInstrument(e,t){const{id:i,paymentSource:n}=t,{brand:o,expiry:r,lastDigits:a}=n.card,[s,d]=r.split("-");return[{bigpayToken:i,brand:o,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:X.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,i,n){const[o,r]=t.fullName.split(" "),a=(null==i?void 0:i.nationalNumber)||"",s=(null==i?void 0:i.countryCode)||"";return{id:Date.now(),type:"paypal-address",firstName:t.firstName||o||"",lastName:t.lastName||r||"",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:n||[]}}filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this.isEqualAddresses(e,t))?e:[...e,t]:e,[])}isEqualAddresses(e,t){return o(this.normalizeAddress(e),this.normalizeAddress(t))}normalizeAddress(e){return s(e,["id","phone"])}}function me(){return new ce}function ue(e){return"string"!=typeof e}function he(e,t){if(t||e)return function(e){var t,i;const n={},o=d(e.root,ue),r=d(e.input,ue),a=d(e.toggle,ue),s=d(null===(t=e.text)||void 0===t?void 0:t.body,ue),l=d(null===(i=e.text)||void 0===i?void 0:i.caption,ue),c=e.branding;return Object.keys(o).length&&(n.root=o),Object.keys(r).length&&(n.input=r),Object.keys(a).length&&(n.toggle=a),Object.keys(s).length&&(n.text={},n.text.body=s),Object.keys(l).length&&(n.text=Object.assign({},n.text),n.text.caption=l),c&&(n.branding=c),n}(function(e,t){var i,n,o,r,a,s,d,l,c,m,u,h,y,p,g,v,f,b,P,S,I,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.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===(l=null==t?void 0:t.input)||void 0===l?void 0:l.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(c=null==t?void 0:t.input)||void 0===c?void 0:c.focusBorderColor),backgroundColor:(null==e?void 0:e.fastlaneInputSettingsBackgroundColor)||(null===(m=null==t?void 0:t.input)||void 0===m?void 0:m.backgroundColor),borderWidth:(null==e?void 0:e.fastlaneInputSettingsBorderWidth)||(null===(u=null==t?void 0:t.input)||void 0===u?void 0:u.borderWidth),textColorBase:(null==e?void 0:e.fastlaneInputSettingsTextColorBase)||(null===(h=null==t?void 0:t.input)||void 0===h?void 0:h.textColorBase)},toggle:{colorPrimary:(null==e?void 0:e.fastlaneToggleSettingsColorPrimary)||(null===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorPrimary),colorSecondary:(null==e?void 0:e.fastlaneToggleSettingsColorSecondary)||(null===(p=null==t?void 0:t.toggle)||void 0===p?void 0:p.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===(b=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===b?void 0:b.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(S=null===(P=null==t?void 0:t.text)||void 0===P?void 0:P.caption)||void 0===S?void 0:S.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))}function ye(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}function pe(e,t,i=!0){var n;return null!==(n=e[t])&&void 0!==n?n:i}var ge=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ve{constructor(e,t,i,n){this.paymentIntegrationService=e,this.bigCommercePaymentsRequestSender=t,this.bigCommercePaymentsSdk=i,this.bigCommercePaymentsFastlaneUtils=n}initialize(e){var t,i;return ge(this,void 0,void 0,function*(){const{methodId:n,bigcommerce_payments_fastlane:o}=e;if(!n)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(this.methodId=n,!o)throw new R('Unable to initialize payment because "options.bigcommerce_payments_fastlane" argument is not provided.');if(this.bigcommerce_payments_fastlane=o,!o.onInit||"function"!=typeof o.onInit)throw new R('Unable to initialize payment because "options.bigcommerce_payments_fastlane.onInit" argument is not provided or it is not a function.');if(!o.onChange||"function"!=typeof o.onChange)throw new R('Unable to initialize payment because "options.bigcommerce_payments_fastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(n);const r=this.paymentIntegrationService.getState(),a=r.getCartOrThrow(),s=r.getPaymentMethodOrThrow(n),{isDeveloperModeApplicable:d,isFastlaneStylingEnabled:l}=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 c=he(l?null===(i=null==s?void 0:s.initializationData)||void 0===i?void 0:i.fastlaneStyles:{},null==o?void 0:o.styles);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(this.paypalFastlaneSdk,!!d,c),this.shouldRunAuthenticationFlow()&&(yield this.runPayPalAuthenticationFlowOrThrow(n)),yield this.initializePayPalPaymentComponent(),o.onInit(e=>this.renderPayPalPaymentComponent(e)),o.onChange(()=>this.handlePayPalStoredInstrumentChange(n))})}execute(e,t){return ge(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(i[n[o]]=e[n[o]])}return i}(e,["payment"]);if(!i)throw new L(["payment"]);const{paymentData:o,methodId:r}=i,a=o&&G(o);try{yield this.paymentIntegrationService.submitOrder(n,t);const e=a?yield this.prepareVaultedInstrumentPaymentPayload(r,o):yield this.preparePaymentPayload(r,o);yield this.paymentIntegrationService.submitPayment(e),this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId()}catch(e){if(function(e){return"object"==typeof e&&null!==e&&"message"in e&&"response"in e&&"name"in e.response}(e)&&"INVALID_REQUEST"===e.response.name){const e={translationKey:"payment.errors.invalid_request_error"};return this.handleError(e),Promise.reject()}if(e instanceof Error&&"FastlaneError"!==e.name)throw e;return Promise.reject()}})}finalize(){return Promise.reject(new q)}deinitialize(){return ge(this,void 0,void 0,function*(){return Promise.resolve()})}shouldRunAuthenticationFlow(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),i=e.getCustomerOrThrow(),n=e.getPaymentProviderCustomer(),o=ye(n)?n:{},r=this.bigCommercePaymentsFastlaneUtils.getStorageSessionId();return!(!i.isGuest||(null==o?void 0:o.authenticationState)===oe.CANCELED||(null==o?void 0:o.authenticationState)||r!==t.id)}runPayPalAuthenticationFlowOrThrow(e){return ge(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getCustomer(),o=t.getBillingAddress(),r=(null==n?void 0:n.email)||(null==o?void 0:o.email)||"",{customerContextId:a}=yield this.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(r),s=yield this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(a),{authenticationState:d,addresses:l,instruments:c}=this.bigCommercePaymentsFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,s);yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:d,addresses:l,instruments:c}),s.authenticationState===oe.CANCELED?this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId():this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(i.id)}catch(e){}})}initializePayPalPaymentComponent(){return ge(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),t=e.phone,i=`${e.firstName} ${e.lastName}`.trim(),n=this.bigCommercePaymentsFastlaneUtils.getPayPalFastlaneOrThrow(),o={fields:Object.assign({cardholderName:{prefill:i,enabled:!0}},t&&{phoneNumber:{prefill:t}})};this.paypalComponentMethods=yield n.FastlaneCardComponent(o)})}renderPayPalPaymentComponent(e){const t=this.getPayPalComponentMethodsOrThrow();if(!e)throw new R('Unable to render card component because "container" argument is not provided.');t.render(e)}getPayPalComponentMethodsOrThrow(){if(!this.paypalComponentMethods)throw new g;return this.paypalComponentMethods}prepareVaultedInstrumentPaymentPayload(e,t){return ge(this,void 0,void 0,function*(){const{instrumentId:i}=t,n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),o=this.isBigcommercePaymentsFastlaneThreeDSAvailable()&&n.config.is3dsEnabled;o||(yield this.createOrder(i));const r=o?yield this.get3DSNonce(i):i;return{methodId:e,paymentData:{formattedPayload:{paypal_fastlane_token:{order_id:this.orderId,token:r}}}}})}preparePaymentPayload(e,t){return ge(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=i.getBillingAddressOrThrow(),o=i.getPaymentMethodOrThrow(e),r=`${n.firstName} ${n.lastName}`.trim(),{getPaymentToken:a}=this.getPayPalComponentMethodsOrThrow(),{id:s}=yield a({name:{fullName:r},billingAddress:this.bigCommercePaymentsFastlaneUtils.mapBcToPayPalAddress(n)}),d=this.isBigcommercePaymentsFastlaneThreeDSAvailable()&&o.config.is3dsEnabled;d||(yield this.createOrder(s));const{shouldSaveInstrument:l=!1,shouldSetAsDefaultInstrument:c=!1}=H(t)?t:{},m=d?yield this.get3DSNonce(s):s;return{methodId:e,paymentData:Object.assign(Object.assign({},t),{shouldSaveInstrument:l,shouldSetAsDefaultInstrument:c,formattedPayload:{paypal_fastlane_token:{order_id:this.orderId,token:m}}})}})}createOrder(e){return ge(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getCartOrThrow().id;if(this.methodId){const{orderId:i}=yield this.bigCommercePaymentsRequestSender.createOrder(this.methodId,{cartId:t,fastlaneToken:e});this.orderId=i}})}get3DSNonce(e){var t;return ge(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=i.getCartOrThrow(),o=i.getOrderOrThrow(),r=i.getStoreConfigOrThrow().links.checkoutLink,a=null===(t=this.paypalFastlaneSdk)||void 0===t?void 0:t.ThreeDomainSecureClient;if(!a)throw new g;const s={amount:o.orderAmount.toFixed(2),currency:n.currency.code,nonce:e,threeDSRequested:"SCA_ALWAYS"===this.threeDSVerificationMethod,transactionContext:{experience_context:{locale:"en-US",return_url:r,cancel_url:r}}};if(yield a.isEligible(s)){const{liabilityShift:t,authenticationState:i,nonce:n}=yield a.show();if(t===C.No||t===C.Unknown)throw new $;if(yield this.createOrder(e),i===ee.Succeeded)return n;if(i===ee.Errored)throw new $;if(i===ee.Cancelled)throw console.error("3DS check was canceled"),new $}return e})}handlePayPalStoredInstrumentChange(e){return ge(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsFastlaneUtils.getPayPalFastlaneOrThrow(),{selectionChanged:i,selectedCard:n}=yield t.profile.showCardSelector();if(i){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),i=ye(t)?t:{},o=this.bigCommercePaymentsFastlaneUtils.mapPayPalToBcInstrument(e,n)[0];return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},i),{instruments:[o]})),o}})}isBigcommercePaymentsFastlaneThreeDSAvailable(){return pe(this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features,"PROJECT-7080.bcp_fastlane_three_ds")}handleError(e){var t;(null===(t=this.bigcommerce_payments_fastlane)||void 0===t?void 0:t.onError)&&"function"==typeof this.bigcommerce_payments_fastlane.onError&&this.bigcommerce_payments_fastlane.onError(e)}}const fe=c(e=>{const{getHost:i}=e.getState();return new ve(e,new N(t({host:i()})),se(),me())},[{id:"bigcommerce_payments_fastlane"}]),be=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};class Pe extends p{constructor(e){super(e||"Not implemented."),this.name="NotImplementedError",this.type="not_implemented"}}var Se=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ie{constructor(e,t,i,n){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=i,this.paypalSdkHelper=n}initialize(e){return Se(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_paylater:i}=e||{};if(!t)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new R('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState(),o=n.getPaymentMethodOrThrow(t),{paypalBNPLConfiguration:r=[],orderId:a}=o.initializationData||{},{bannerContainerId:s,container:d}=i;if(void 0!==s){if(!document.getElementById(s))return void console.error("Unable to create banner without valid banner container ID.");const e=r&&r.find(({id:e})=>"checkout"===e);if(!(null==e?void 0:e.status))return;const t=yield this.paypalSdkHelper.getPayPalMessages(o,n.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,i))})}execute(e,t){return Se(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(i[n[o]]=e[n[o]])}return i}(e,["payment"]);if(!i)throw new L(["payment"]);if(!this.orderId)throw new $;yield this.paymentIntegrationService.submitOrder(n,t),yield this.bigCommercePaymentsIntegrationService.submitPayment(i.methodId,this.orderId)})}finalize(){return Promise.reject(new q)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.bigCommercePaymentsButtons)||void 0===e||e.close(),Promise.resolve()}renderButton(e,t){if(!(null==t?void 0:t.container))throw new R('Unable to initialize payment because "container" argument is not provided.');const i=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:o}=n.initializationData||{},{checkoutPaymentButtonStyles:r}=o||{},{container:a,onError:s,onRenderButton:d,onValidate:l,submitForm:c}=t,m=[i.FUNDING.PAYLATER,i.FUNDING.CREDIT];let u=!1;m.forEach(e=>{if(u)return;const t={fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(r),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onClick:(e,t)=>this.handleClick(t,l),onApprove:e=>this.handleApprove(e,c),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.bigCommercePaymentsButtons=i.Buttons(t),this.bigCommercePaymentsButtons.isEligible()||e!==i.FUNDING.PAYLATER){if(!this.bigCommercePaymentsButtons.isEligible()&&e===i.FUNDING.CREDIT)throw new Pe(`BigCommercePayments ${e} is not available for your region. Please use BigCommercePayments Checkout instead.`);d&&"function"==typeof d&&d(),this.bigCommercePaymentsButtons.render(a),u=!0}})}handleClick(e,t){return Se(this,void 0,void 0,function*(){const{resolve:i,reject:n}=e;t&&"function"==typeof t&&(yield t(()=>(this.toggleLoadingIndicator(!0),i()),n))})}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,i){const n={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:be(i)};e.Messages(n).render(`#${t}`)}}const Ce=c(e=>new Ie(e,V(e),new h({containerStyles:y}),se()),[{id:"bigcommerce_payments_paylater"}]);class we extends S{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}var Oe=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class _e{constructor(e,t,i,n=3e3,o=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=i,this.pollingInterval=n,this.maxPollingIntervalTime=o,this.pollingTimer=0,this.stopPolling=a}initialize(e){return Oe(this,void 0,void 0,function*(){const{gatewayId:t,methodId:i,bigcommerce_payments_ratepay:n}=e;if(!i)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new R('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!n)throw new R('Unable to initialize payment because "options.bigcommerce_payments_ratepay" argument is not provided.');const{legalTextContainer:o,container:r,loadingContainerId:a}=n;if(!r)throw new R('Unable to initialize payment because "options.container" argument is not provided.');if(!o)throw new R('Unable to initialize payment because "options.legalTextContainer" argument is not provided.');if(!a)throw new R('Unable to initialize payment because "options.loadingContainerId" argument is not provided.');this.loadingIndicatorContainer=a;const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,t),{merchantId:d}=s.initializationData||{};if(!d)throw new R("Unable to initialize payment because merchantId argument is not provided.");this.bigcommerce_payments_ratepay=n,yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i),this.createFraudNetScript(d,i,t),this.loadFraudnetConfig(),this.renderLegalText(o,r)})}execute(e,t){return Oe(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(i[n[o]]=e[n[o]])}return i}(e,["payment"]),{getFieldsValues:o}=this.bigcommerce_payments_ratepay||{};if(!i)throw new L(["payment"]);if(!o||"function"!=typeof o)throw new R('Unable to initialize payment because "options.getFieldsValues" argument is not provided.');this.toggleLoadingIndicator(!0);try{const e=yield this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apmscheckout",{metadataId:this.guid}),{ratepayBirthDate:r,ratepayPhoneNumber:a,ratepayPhoneCountryCode:s}=o(),d={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:i.methodId,rate_pay:{birth_date:this.normalizeDate(r),phone:{national_number:a,country_code:s.split("+")[1]}},paypal_account:{order_id:e}}};return yield this.paymentIntegrationService.submitOrder(n,t),yield this.paymentIntegrationService.submitPayment({methodId:i.methodId,paymentData:d}),yield new Promise((e,t)=>{this.initializePollingMechanism(i.methodId,e,t,i.gatewayId)})}catch(e){return this.handleError(e),new Promise((e,t)=>t())}})}finalize(){return Promise.reject(new q)}deinitialize(){const{legalTextContainer:e}=this.bigcommerce_payments_ratepay||{},t=document.querySelectorAll('[data-id="fraudnetScript"]')[0],i=document.querySelectorAll('[data-id="fraudnetConfig"]')[0];if(this.deinitializePollingMechanism(),t.remove(),i.remove(),e){const t=document.getElementById(e);null==t||t.remove()}return Promise.resolve()}normalizeDate(e){const t=this.formatDate(e.getDate()),i=this.formatDate(e.getMonth()+1);return`${e.getFullYear()}-${i}-${t}`}formatDate(e){return`${e<10?0:""}${e}`}renderLegalText(e,t){const i=e,n=t.split("#")[1],o=document.getElementById(n),r=null==o?void 0:o.parentNode,a=document.createElement("div");a.style.marginBottom="20px",a.setAttribute("id",i),null==r||r.prepend(a);const s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=s.Legal({fundingSource:s.Legal.FUNDING.PAY_UPON_INVOICE});if(!document.getElementById(i))throw new R('Unable to initialize payment because "legalTextContainerElement" argument is not found.');d.render(`#${i}`)}handleError(e){const{onError:t}=this.bigcommerce_payments_ratepay||{};this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createFraudNetScript(e,t,i){const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,i),{testMode:o}=n.config,r=document.createElement("script");r.setAttribute("type","application/json"),r.setAttribute("fncls","fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99"),r.setAttribute("data-id","fraudnetScript"),this.guid=this.generateGUID();const a={f:this.guid,s:`${e}_checkout-page`,sandbox:o};r.innerHTML=JSON.stringify(a),document.body.appendChild(r)}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 Oe(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}initializePollingMechanism(e,t,i,n){return Oe(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const i=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(i),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const o=yield this.bigCommercePaymentsIntegrationService.getOrderStatus("bigcommerce_payments_apms",{params:{useMetadata:!0}}),r=o===E.PollingStop,a=o===E.PollingError;if(r)return this.deinitializePollingMechanism(),t();if(a)return i();if(!r&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,i,n);yield this.reinitializeStrategy({methodId:e,gatewayId:n,bigcommerce_payments_ratepay:this.bigcommerce_payments_ratepay}),this.handleError(new we)}catch(e){this.handleError(e),i()}})}deinitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deinitializePollingMechanism()}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const ke=c(e=>new _e(e,V(e),new h({containerStyles:Object.assign(Object.assign({},y),{position:"fixed"})})),[{gateway:"bigcommerce_payments_apms",id:"ratepay"}]);var Ae;!function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification",e.CardExpiryVerification="cardExpiryVerification"}(Ae||(Ae={}));const Ee=Ae;function Te(e){return Ee.CardNumber in e&&Ee.CardName in e&&Ee.CardExpiry in e}function ze(e){return Ee.CardNumberVerification in e&&Ee.CardCodeVerification in e&&Ee.CardExpiryVerification in e}class Fe extends p{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"}}var Be;!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"}(Be||(Be={}));class De extends p{constructor(e){super(function(e){switch(e){case Be.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case Be.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case Be.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case Be.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 xe extends p{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"}}var Me=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ne{constructor(e,t,i,n){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdk=i,this.bigCommercePaymentsFastlaneUtils=n}initialize(e){return Me(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_creditcards:i}=e,n=i,{form:o,onCreditCardFieldsRenderingError:r,onLoadComplete:a}=n||{};if(!t)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)throw new R('Unable to proceed because "options.bigcommerce_payments_creditcards.form" argument is not provided.');this.hostedFormOptions=o,this.isCreditCardForm=Te(o.fields),this.isCreditCardVaultedForm=ze(o.fields)&&!this.hasUndefinedValues(),yield this.paymentIntegrationService.loadPaymentMethod(t),yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t,void 0,!0,!0),null==a||a(),(this.isCreditCardForm||this.isCreditCardVaultedForm)&&(yield this.initializeFields(o,r)),this.shouldInitializePayPalFastlane(t)&&(yield this.initializePayPalFastlaneOrThrow(t))})}execute(e,t){return Me(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(i[n[o]]=e[n[o]])}return i}(e,["payment"]),{methodId:o,paymentData:r}=i||{};if(!i||!o)throw new L(["payment"]);if(this.executionPaymentData=r,this.isCreditCardForm||this.isCreditCardVaultedForm)yield this.validateHostedFormOrThrow(),yield this.submitHostedForm();else{const{orderId:e}=yield this.bigCommercePaymentsIntegrationService.createOrderCardFields("bigcommerce_payments_creditcardscheckout",this.getInstrumentParams());this.returnedOrderId=e}const a=this.preparePaymentPayload(o,r,this.returnedOrderId,this.returnedVaultedToken);yield this.paymentIntegrationService.submitOrder(n,t),yield this.paymentIntegrationService.submitPayment(a)})}finalize(){return Promise.reject(new q)}deinitialize(){var e,t,i,n;return Me(this,void 0,void 0,function*(){return yield null===(e=this.cvvField)||void 0===e?void 0:e.close(),yield null===(t=this.expiryField)||void 0===t?void 0:t.close(),yield null===(i=this.numberField)||void 0===i?void 0:i.close(),yield null===(n=this.nameField)||void 0===n?void 0:n.close(),Promise.resolve()})}preparePaymentPayload(e,t,i,n){const{shouldSaveInstrument:o=!1,shouldSetAsDefaultInstrument:a=!1}=H(t)?t:{},s=t&&G(t)?t.instrumentId:void 0,l=d({verification_nonce:n,token:s},r);return{methodId:e,paymentData:{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a,instrumentId:s,formattedPayload:Object.assign(Object.assign({},n||s?{bigpay_token:l}:{}),i?{card_with_order:{order_id:i}}:{})}}}initializeFields(e,t){return Me(this,void 0,void 0,function*(){const{fields:i,styles:n}=e,o=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),r=this.getExecuteCallback(i),a=Object.assign({style:this.getInputStyles(n),onApprove:({orderID:e,vaultSetupToken:t,liabilityShift:i})=>{if(i===C.No||i===C.Unknown)throw new Error;return this.handleApprove({orderID:e,vaultSetupToken:t})},onError:()=>{throw new Fe},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)}},r);if(this.cardFields=yield o.CardFields(a),!this.cardFields.isEligible())throw new De(Be.PaymentNotInitialized);try{this.stylizeInputContainers(i),Te(i)&&(yield this.renderFields(i)),ze(i)&&(yield this.renderVaultedFields(i))}catch(e){"function"==typeof t&&t(e)}})}getExecuteCallback(e){return ze(e)?this.createVaultSetupTokenCallback():this.createOrderCallback()}createVaultSetupTokenCallback(){return{createVaultSetupToken:()=>Me(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:()=>Me(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,i,n,o;return Me(this,void 0,void 0,function*(){const r=this.getCardFieldsOrThrow();(null===(t=e.cardCode)||void 0===t?void 0:t.containerId)&&(this.cvvField=r.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCode.containerId}`)),(null===(i=e.cardExpiry)||void 0===i?void 0:i.containerId)&&(this.expiryField=r.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiry.containerId}`)),(null===(n=e.cardName)||void 0===n?void 0:n.containerId)&&(this.nameField=r.NameField({placeholder:""}),yield this.nameField.render(`#${e.cardName.containerId}`)),(null===(o=e.cardNumber)||void 0===o?void 0:o.containerId)&&(this.numberField=r.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumber.containerId}`))})}renderVaultedFields(e){var t,i,n;return Me(this,void 0,void 0,function*(){const o=this.getCardFieldsOrThrow();(null===(t=e.cardCodeVerification)||void 0===t?void 0:t.containerId)&&(this.cvvField=o.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCodeVerification.containerId}`)),(null===(i=e.cardExpiryVerification)||void 0===i?void 0:i.containerId)&&(this.expiryField=o.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiryVerification.containerId}`)),(null===(n=e.cardNumberVerification)||void 0===n?void 0:n.containerId)&&(this.numberField=o.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumberVerification.containerId}`))})}getInstrumentParams(){if(!this.executionPaymentData)return{};if(H(this.executionPaymentData)){const{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}=this.executionPaymentData;return{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}}if(G(this.executionPaymentData)){const{instrumentId:e}=this.executionPaymentData;return{instrumentId:e}}return{}}getFieldTypeByEmittedField({emittedBy:e}){return{fieldType:this.mapFieldType(e)}}submitHostedForm(){return Me(this,void 0,void 0,function*(){const e=this.getCardFieldsOrThrow(),t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),i={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(i)}catch(e){throw new Fe("Failed authentication. Please try to authorize again.")}})}validateHostedFormOrThrow(){var e,t;return Me(this,void 0,void 0,function*(){const i=this.getCardFieldsOrThrow(),n=yield i.getState().then(e=>e),o=this.getValidityData(n);if(!o.isValid)throw null===(t=null===(e=this.hostedFormOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,o),new xe(this.mapValidationErrors(o.errors))})}getValidityData({fields:e}){const t=Object.assign({},e);delete t.cardNameField;const i=Object.keys(t);return{isValid:i.every(e=>{var i;return null===(i=t[e])||void 0===i?void 0:i.isValid}),errors:i.reduce((e,i)=>{var n;const o=this.mapFieldType(i);return Object.assign(Object.assign({},e),{[o]:(null===(n=t[i])||void 0===n?void 0:n.isValid)?void 0:[this.getInvalidErrorByFieldType(o)]})},{})}}getInvalidErrorByFieldType(e){switch(e){case Ee.CardCode:case Ee.CardCodeVerification:return{fieldType:e,message:"Invalid card code",type:"invalid_card_code"};case Ee.CardNumber:case Ee.CardNumberVerification:return{fieldType:e,message:"Invalid card number",type:"invalid_card_number"};case Ee.CardExpiry:case Ee.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(i=>{var n,o;t[i]=[{message:(null===(o=null===(n=e[i])||void 0===n?void 0:n[0])||void 0===o?void 0:o.message)||"",type:i}]}),t}mapFieldType(e){switch(e){case"name":return Ee.CardName;case"cardNumberField":case"number":return this.isCreditCardForm?Ee.CardNumber:Ee.CardNumberVerification;case"cardExpiryField":case"expiry":return this.isCreditCardForm?Ee.CardExpiry:Ee.CardExpiryVerification;case"cardCvvField":case"cvv":return this.isCreditCardForm?Ee.CardCode:Ee.CardCodeVerification;default:throw new Error("Unexpected field type")}}getCardFieldsOrThrow(){if(!this.cardFields)throw new De(Be.PaymentNotInitialized);return this.cardFields}getInputStyles(e){var t,i,n;const o={"font-size":(null===(t=null==e?void 0:e.default)||void 0===t?void 0:t.fontSize)||"1rem","font-family":(null===(i=null==e?void 0:e.default)||void 0===i?void 0:i.fontFamily)||"Montserrat, Arial, Helvetica, sans-serif","font-weight":(null===(n=null==e?void 0:e.default)||void 0===n?void 0:n.fontWeight)||"400",outline:"none",padding:"9px 13px"},r=Object.assign(Object.assign({},o),{color:"#333333"});return{input:r,".invalid":Object.assign(Object.assign({},o),{color:"red"}),".valid":r,":focus":r}}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 i;null===(i=null==e?void 0:e.onValidate)||void 0===i||i.call(e,this.getValidityData(t))}onFocusHandler(e,t){var i;null===(i=null==e?void 0:e.onFocus)||void 0===i||i.call(e,this.getFieldTypeByEmittedField(t))}onBlurHandler(e,t){var i;null===(i=null==e?void 0:e.onBlur)||void 0===i||i.call(e,this.getFieldTypeByEmittedField(t))}onInputSubmitRequest(e,t){var i;null===(i=null==e?void 0:e.onEnter)||void 0===i||i.call(e,this.getFieldTypeByEmittedField(t))}shouldInitializePayPalFastlane(e){var t,i;const n=this.paymentIntegrationService.getState(),o=n.getPaymentMethodOrThrow(e),r=n.getPaymentProviderCustomer(),a=(s=r)&&("authenticationState"in s||"addresses"in s||"instruments"in s)?r:{};var s;return(null===(t=null==o?void 0:o.initializationData)||void 0===t?void 0:t.isAcceleratedCheckoutEnabled)&&(null===(i=null==o?void 0:o.initializationData)||void 0===i?void 0:i.isBigCommercePaymentsAnalyticsV2Enabled)&&!(null==a?void 0:a.authenticationState)}initializePayPalFastlaneOrThrow(e){return Me(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getPaymentMethodOrThrow(e),{initializationData:o}=n;if(!(null==o?void 0:o.connectClientToken))return;const r=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(n,i.currency.code,i.id);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(r,!!(null==o?void 0:o.isDeveloperModeApplicable))}catch(e){}})}}const Ue=c(e=>new Ne(e,V(e),se(),me()),[{id:"bigcommerce_payments_creditcards"}]);var je=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ve{constructor(e,t,i,n,o=3e3,r=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdkHelper=i,this.loadingIndicator=n,this.pollingInterval=o,this.maxPollingIntervalTime=r,this.pollingTimer=0,this.stopPolling=a,this.isPollingEnabled=!1}initialize(e){return je(this,void 0,void 0,function*(){const{gatewayId:t,methodId:i,bigcommerce_payments_apms:n}=e;if(this.bigCommercePaymentsAlternativeMethods=n,!i)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new R('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!n)throw new R('Unable to initialize payment because "options.bigcommerce_payments_apms" argument is not provided.');const o=this.paymentIntegrationService.getState(),r=o.getPaymentMethodOrThrow(i,t),{orderId:a,shouldRenderFields:s}=r.initializationData||{},d=o.getStoreConfigOrThrow().checkoutSettings.features;this.isPollingEnabled=pe(d,"PAYPAL-5624.bcp_ideal_polling"),a?this.orderId=a:(this.paypalApms=yield this.bigCommercePaymentsSdkHelper.getPayPalApmsSdk(r,o.getCartOrThrow().currency.code),this.loadingIndicatorContainer=n.container.split("#")[1],this.renderButton(i,t,n),s&&this.renderFields(i,n))})}execute(e,t){return je(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(i[n[o]]=e[n[o]])}return i}(e,["payment"]);if(!i)throw new L(["payment"]);const{methodId:o,gatewayId:r}=i;if(!this.orderId)throw new $;this.isPollingEnabled&&"ideal"===o&&(yield new Promise((e,t)=>{this.initializePollingMechanism(o,e,t,r)})),this.isNonInstantPaymentMethod(o)||(yield this.paymentIntegrationService.submitOrder(n,t)),yield this.bigCommercePaymentsIntegrationService.submitPayment(o,this.orderId,r)})}finalize(){return Promise.reject(new q)}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,i,n){return je(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const i=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(i),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const o=yield this.bigCommercePaymentsIntegrationService.getOrderStatus(n),r=o===E.Approved,a=o===E.PollingError;if(r)return this.deInitializePollingMechanism(),t();if(a)return i();if(!r&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,i,n);yield this.reinitializeStrategy({methodId:e,gatewayId:n,bigCommercePaymentsAlternativeMethods:this.bigCommercePaymentsAlternativeMethods}),this.handleError(new we)}catch(e){i()}})}deInitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deInitializePollingMechanism()}reinitializeStrategy(e){return je(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}handleError(e){const{onError:t}=this.bigCommercePaymentsAlternativeMethods||{};this.isPollingEnabled&&this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderButton(e,t,i){const n=this.getPaypalAmpsSdkOrThrow(),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t),{buttonStyle:r}=o.initializationData||{},{container:a,onError:s,onRenderButton:d,submitForm:l}=i,c={fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(r),onInit:(e,t)=>i.onInitButton(t),createOrder:()=>this.onCreateOrder(e,t,i),onApprove:e=>this.handleApprove(e,l),onCancel:()=>{this.toggleLoadingIndicator(!1),this.deInitializePollingMechanism()},onError:e=>{this.deInitializePollingMechanism(),this.handleFailure(e,s)},onClick:(e,t)=>je(this,void 0,void 0,function*(){return i.onValidate(t.resolve,t.reject)})};this.bigCommercePaymentsButton=n.Buttons(c),this.bigCommercePaymentsButton.isEligible()&&(d&&"function"==typeof d&&d(),this.bigCommercePaymentsButton.render(a))}onCreateOrder(e,t,i){return je(this,void 0,void 0,function*(){const{onValidate:n}=i;yield n(()=>(this.toggleLoadingIndicator(!0),()=>Promise.resolve()),a);const o=yield this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apms");if(this.isNonInstantPaymentMethod(e)){const i={useStoreCredit:!1},n={params:{methodId:e,gatewayId:t}};yield this.paymentIntegrationService.submitOrder(i,n),yield this.bigCommercePaymentsIntegrationService.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 i=this.getPaypalAmpsSdkOrThrow(),n=this.paymentIntegrationService.getState(),{firstName:o,lastName:r,email:a}=n.getBillingAddressOrThrow(),{apmFieldsContainer:s,apmFieldsStyles:d}=t;if(!s)throw new R('Unable to initialize payment because "options.bigcommerce_payments_apms" argument should contain "apmFieldsContainer".');const l=document.querySelector(s);l&&(l.innerHTML="");const c={fundingSource:e,style:d||{},fields:{name:{value:`${o} ${r}`},email:{value:a}}};i.PaymentFields(c).render(s)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isNonInstantPaymentMethod(e){return e.toUpperCase()in A}getPaypalAmpsSdkOrThrow(){if(!this.paypalApms)throw new g;return this.paypalApms}}const Re=c(e=>new Ve(e,V(e),se(),new h({containerStyles:y})),[{gateway:"bigcommerce_payments_apms"}]);var Le=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class $e{constructor(e,t,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=i}initialize(e){var t,i;return Le(this,void 0,void 0,function*(){const{methodId:n,bigcommerce_payments_venmo:o}=e||{};if(!n)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)throw new R('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n);(null===(t=r.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(i=r.initializationData)||void 0===i?void 0:i.orderId:(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n),this.loadingIndicatorContainer=o.container.split("#")[1],this.renderButton(n,o))})}execute(e,t){return Le(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(i[n[o]]=e[n[o]])}return i}(e,["payment"]);if(!i)throw new L(["payment"]);if(!this.orderId)throw new $;yield this.paymentIntegrationService.submitOrder(n,t),yield this.bigCommercePaymentsIntegrationService.submitPayment(i.methodId,this.orderId)})}finalize(){return Promise.reject(new q)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}renderButton(e,t){const i=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:o}=n.initializationData||{},{checkoutPaymentButtonStyles:r}=o||{},{container:a,onError:s,onRenderButton:d,onValidate:l,submitForm:c}=t,m={fundingSource:i.FUNDING.VENMO,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(r),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo_checkout"),onClick:(e,t)=>this.handleClick(t,l),onApprove:e=>this.handleApprove(e,c),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=i.Buttons(m),!this.paypalButton.isEligible())throw new Pe("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 Le(this,void 0,void 0,function*(){const{resolve:i,reject:n}=e;yield t(()=>(this.toggleLoadingIndicator(!0),i()),n)})}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 qe=c(e=>new $e(e,V(e),new h({styles:{backgroundColor:"black"}})),[{id:"bigcommerce_payments_venmo"}]);var He=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ge{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=a}initialize(e){return He(this,void 0,void 0,function*(){const{bigcommerce_payments:t,methodId:i}=e;if(!i)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new R('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');if(!t.container)throw new R('Unable to initialize payment because "options.bigcommerce_payments.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new R('Unable to initialize payment because "options.bigcommerce_payments.onClick" argument is not a function.');this.onError=t.onError||a,this.paymentIntegrationService.getState().getPaymentMethod(i)||(yield this.paymentIntegrationService.loadPaymentMethod(i));const n=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i);n&&n.Buttons&&"function"==typeof n.Buttons?this.renderButton(i,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 He(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return He(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){const{container:i,onClick:n,onComplete:o}=t,r=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:s,paymentButtonStyles:d}=a.initializationData||{},{checkoutTopButtonStyles:l}=d||{},c=Object.assign({createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},n&&{onClick:()=>n()}),m={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(t,i)=>this.onHostedCheckoutApprove(t,i,e,o)},u=Object.assign(Object.assign({fundingSource:r.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},l),{height:36}))},c),s&&m),h=r.Buttons(u);h.isEligible()?h.render(`#${i}`):this.bigCommercePaymentsIntegrationService.removeElement(i)}onHostedCheckoutApprove(e,t,i,n){return He(this,void 0,void 0,function*(){if(!e.orderID)throw new f(v.MissingOrderId);const o=this.paymentIntegrationService.getState().getCartOrThrow(),r=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(r);if(yield this.paymentIntegrationService.updateBillingAddress(t),o.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(r);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:i}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return He(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 He(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 Ye=c(e=>new Ge(e,V(e)),[{id:"bigcommerce_payments"}]);var We=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ke{constructor(e,t,i){this.paymentIntegrationService=e,this.bigCommercePaymentsSdk=t,this.bigCommercePaymentsFastlaneUtils=i}initialize(e){var t;return We(this,void 0,void 0,function*(){const{methodId:i,bigcommerce_payments_fastlane:n}=e;if(!i)throw new R('Unable to proceed because "methodId" argument is not provided.');try{yield this.paymentIntegrationService.loadPaymentMethod(i);const e=this.paymentIntegrationService.getState(),o=e.getCartOrThrow(),r=e.getPaymentMethodOrThrow(i),a=!!(null===(t=r.initializationData)||void 0===t?void 0:t.isDeveloperModeApplicable),s=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(r,o.currency.code,o.id);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(s,a,this.getFastlaneStyles(i,n))}catch(e){}return Promise.resolve()})}deinitialize(){return We(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return We(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return We(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return We(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:i,methodId:n}=e||{};if(!n)throw new R('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof i)throw new R('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(n)}catch(e){}}i()})}runPayPalAuthenticationFlowOrThrow(e){return We(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow().id,n=t.getCustomer(),o=t.getBillingAddress(),r=(null==n?void 0:n.email)||(null==o?void 0:o.email)||"",{customerContextId:a}=yield this.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(r),s=yield this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(a),d=s.authenticationState===oe.CANCELED;yield this.updateCustomerDataState(e,s),d?this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId():this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(i)})}updateCustomerDataState(e,t){var i;return We(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow(),{authenticationState:o,addresses:r,billingAddress:a,shippingAddress:s,instruments:d}=this.bigCommercePaymentsFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,t);if(yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:o,addresses:r,instruments:d}),a&&(yield this.paymentIntegrationService.updateBillingAddress(a)),s&&n.lineItems.physicalItems.length>0){const t=yield this.paymentIntegrationService.updateShippingAddress(s),n=t.getPaymentMethodOrThrow(e),{isFastlaneShippingOptionAutoSelectEnabled:o}=n.initializationData||{},r=t.getConsignments()||[],a=(null===(i=r[0])||void 0===i?void 0:i.availableShippingOptions)||[],d=a[0],l=a.find(e=>e.isRecommended);if((l||d)&&o){const e=(null==l?void 0:l.id)||d.id;yield this.paymentIntegrationService.selectShippingOption(e)}}})}getFastlaneStyles(e,t){const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{fastlaneStyles:n,isFastlaneStylingEnabled:o}=i.initializationData||{};return he(o?n:{},null==t?void 0:t.styles)}}const Je=c(e=>new Ke(e,se(),me()),[{id:"bigcommerce_payments_fastlane"},{id:"bigcommerce_payments_creditcards"}]);var Xe=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ze{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=a}initialize(e){return Xe(this,void 0,void 0,function*(){const{bigcommerce_payments_paylater:t,methodId:i}=e;if(!i)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new R('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');if(!t.container)throw new R('Unable to initialize payment because "options.bigcommerce_payments_paylater.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new R('Unable to initialize payment because "options.bigcommerce_payments_paylater.onClick" argument is not a function.');this.onError=t.onError||a,this.paymentIntegrationService.getState().getPaymentMethod(i)||(yield this.paymentIntegrationService.loadPaymentMethod(i));const n=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i);n&&n.Buttons&&"function"==typeof n.Buttons?this.renderButton(i,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 Xe(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Xe(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:i,onComplete:n,onClick:o}=t,r=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:s,paymentButtonStyles:d}=a.initializationData||{},{checkoutTopButtonStyles:l}=d||{},c=Object.assign({createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},o&&{onClick:()=>o()}),m={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(t,i)=>this.onHostedCheckoutApprove(t,i,e,n)},u=[r.FUNDING.PAYLATER,r.FUNDING.CREDIT];let h=!1;u.forEach(e=>{if(!h){const t=Object.assign(Object.assign({fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},l),{height:36}))},c),s&&m),n=r.Buttons(t);n.isEligible()&&(n.render(`#${i}`),h=!0)}}),h||this.bigCommercePaymentsIntegrationService.removeElement(i)}onHostedCheckoutApprove(e,t,i,n){return Xe(this,void 0,void 0,function*(){if(!e.orderID)throw new f(v.MissingOrderId);const o=this.paymentIntegrationService.getState().getCartOrThrow(),r=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(r);if(yield this.paymentIntegrationService.updateBillingAddress(t),o.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(r);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:i}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Xe(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 Xe(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 Qe=c(e=>new Ze(e,V(e)),[{id:"bigcommerce_payments_paylater"}]);var et=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class tt{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return et(this,void 0,void 0,function*(){const{bigcommerce_payments_venmo:t,methodId:i}=e;if(!i)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new R('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');if(!t.container)throw new R('Unable to initialize payment because "options.bigcommerce_payments_venmo.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new R('Unable to initialize payment because "options.bigcommerce_payments_venmo.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(i)||(yield this.paymentIntegrationService.loadPaymentMethod(i));const n=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i);n&&n.Buttons&&"function"==typeof n.Buttons?this.renderButton(i,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 et(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return et(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:i,onClick:n}=t,o=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:a}=r.initializationData||{},{checkoutTopButtonStyles:s}=a||{},d=Object.assign({fundingSource:o.FUNDING.VENMO,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},s),{height:36})),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},n&&{onClick:()=>n()}),l=o.Buttons(d);l.isEligible()?l.render(`#${i}`):this.bigCommercePaymentsIntegrationService.removeElement(i)}}const it=c(e=>new tt(e,V(e)),[{id:"bigcommerce_payments_venmo"}]);var nt=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ot{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){var t;return nt(this,void 0,void 0,function*(){const{bigcommerce_payments:i,containerId:n,methodId:o}=e,r=Boolean(null==i?void 0:i.buyNowInitializeOptions);if(!o)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new R('Unable to initialize payment because "options.containerId" argument is not provided.');if(!i)throw new R('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');if(r&&!i.currencyCode)throw new R('Unable to initialize payment because "options.bigcommerce_payments.currencyCode" argument is not provided.');if(r&&"function"!=typeof(null===(t=i.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody))throw new R('Unable to initialize payment because "options.bigcommerce_payments.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');r||(yield this.paymentIntegrationService.loadDefaultCheckout());const a=r?i.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(o,a,!1),this.renderButton(n,o,i)})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{buyNowInitializeOptions:n,style:o,onComplete:r,onEligibilityFailure:a}=i,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:l}=d.initializationData||{},c={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},m={onClick:()=>this.handleClick(n),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},u={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(e,i)=>this.onHostedCheckoutApprove(e,i,t,r)},h=Object.assign(Object.assign(Object.assign({fundingSource:s.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o)},c),n&&m),l&&u),y=s.Buttons(h);y.isEligible()?y.render(`#${e}`):a&&"function"==typeof a?a():this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return nt(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,i,n){return nt(this,void 0,void 0,function*(){if(!e.orderID)throw new f(v.MissingOrderId);const o=this.paymentIntegrationService.getState().getCartOrThrow(),r=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(r);if(yield this.paymentIntegrationService.updateBillingAddress(t),o.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(r);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:i}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return nt(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 nt(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 rt=c(e=>new ot(e,V(e)),[{id:"bigcommerce_payments"}]);var at=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class st{constructor(e,t,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.payPalSdkHelper=i}initialize(e){return at(this,void 0,void 0,function*(){const{bigcommerce_payments_paylater:t,containerId:i,methodId:n}=e,{buyNowInitializeOptions:o,currencyCode:r,messagingContainerId:a}=t||{},s=!!o;if(!n)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new R('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new R('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');if(s&&!r)throw new R('Unable to initialize payment because "options.bigcommerce_payments_paylater.currencyCode" argument is not provided.');if(s&&"function"!=typeof(null==o?void 0:o.getBuyNowCartRequestBody))throw new R('Unable to initialize payment because "options.bigcommerce_payments_paylater.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');s||(yield this.paymentIntegrationService.loadDefaultCheckout());const d=this.paymentIntegrationService.getState(),l=s?r:d.getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n,l,!1),this.renderButton(i,n,t);const c=a&&document.getElementById(a);if(l&&c){const e=d.getPaymentMethodOrThrow(n),{paypalBNPLConfiguration:t=[]}=e.initializationData||{},i=t&&t.find(({id:e})=>"cart"===e);if(!(null==i?void 0:i.status))return;c.removeAttribute("data-pp-style-logo-type"),c.removeAttribute("data-pp-style-logo-position"),c.removeAttribute("data-pp-style-text-color"),c.removeAttribute("data-pp-style-text-size");const o=yield this.payPalSdkHelper.getPayPalMessages(e,l);this.renderMessages(o,a,i)}})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{buyNowInitializeOptions:n,style:o,onComplete:r,onEligibilityFailure:a}=i,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:l}=d.initializationData||{},c={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},m={onClick:()=>this.handleClick(n),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},u={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(e,i)=>this.onHostedCheckoutApprove(e,i,t,r)},h=[s.FUNDING.PAYLATER,s.FUNDING.CREDIT];let y=!1;h.forEach(t=>{if(!y){const i=Object.assign(Object.assign(Object.assign({fundingSource:t,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o)},c),n&&m),l&&u),r=s.Buttons(i);r.isEligible()?(r.render(`#${e}`),y=!0):a&&"function"==typeof a&&a()}}),y||this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return at(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,i,n){return at(this,void 0,void 0,function*(){if(!e.orderID)throw new f(v.MissingOrderId);const o=this.paymentIntegrationService.getState().getCartOrThrow(),r=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(r);if(yield this.paymentIntegrationService.updateBillingAddress(t),o.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(r);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:i}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return at(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 at(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}})}renderMessages(e,t,i){const n={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"cart",style:be(i)};e.Messages(n).render(`#${t}`)}}const dt=c(e=>new st(e,V(e),se()),[{id:"bigcommerce_payments_paylater"}]);var lt=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ct{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return lt(this,void 0,void 0,function*(){const{bigcommerce_payments_apms:t,containerId:i,methodId:n}=e,{apm:o,buyNowInitializeOptions:r,currencyCode:a}=t||{},s=!!r;if(!n)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new R('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new R('Unable to initialize payment because "options.bigcommerce_payments_apms" argument is not provided.');if(!o)throw new R('Unable to initialize payment because "options.bigcommerce_payments_apms.apm" argument is not provided.');if(s&&!a)throw new R('Unable to initialize payment because "options.bigcommerce_payments_apms.currencyCode" argument is not provided.');if(s&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new R('Unable to initialize payment because "options.bigcommerce_payments_apms.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');s||(yield this.paymentIntegrationService.loadDefaultCheckout());const d=s?a:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n,d,!1),this.renderButton(i,n,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{apm:n,buyNowInitializeOptions:o,style:r,onEligibilityFailure:a}=i,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();if(!Object.values(s.FUNDING).includes(n))throw new R('Unable to initialize PayPal button because "options.bigcommerce_payments_apms.apm" argument is not valid funding source.');const d={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apms"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},l={onClick:()=>this.handleClick(o),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},c=Object.assign(Object.assign({fundingSource:n,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(r)},d),o&&l),m=s.Buttons(c);m.isEligible()?m.render(`#${e}`):a&&"function"==typeof a?a():this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return lt(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const mt=c(e=>new ct(e,V(e)),[{id:"bigcommerce_payments_apms"}]);var ut=function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function a(e){try{d(n.next(e))}catch(e){r(e)}}function s(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ht{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return ut(this,void 0,void 0,function*(){const{bigcommerce_payments_venmo:t,containerId:i,methodId:n}=e,{buyNowInitializeOptions:o,currencyCode:r}=t||{},a=!!o;if(!n)throw new R('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new R('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new R('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');if(a&&!r)throw new R('Unable to initialize payment because "options.bigcommerce_payments_venmo.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==o?void 0:o.getBuyNowCartRequestBody))throw new R('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?r:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n,s,!1),this.renderButton(i,n,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{buyNowInitializeOptions:n,style:o,onEligibilityFailure:r}=i,a=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),s=a.FUNDING.VENMO,d={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},l={onClick:()=>this.handleClick(n),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},c=Object.assign(Object.assign({fundingSource:s,style:this.getValidVenmoButtonStyles(o)},d),n&&l),m=a.Buttons(c);m.isEligible()?m.render(`#${e}`):r&&"function"==typeof r?r():this.bigCommercePaymentsIntegrationService.removeElement(e)}getValidVenmoButtonStyles(e){const t=this.bigCommercePaymentsIntegrationService.getValidButtonStyle(e);return t.color===_.gold?Object.assign(Object.assign({},t),{color:void 0}):t}handleClick(e){return ut(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const yt=c(e=>new ht(e,V(e)),[{id:"bigcommerce_payments_venmo"}]);export{mt as createBigCommercePaymentsAlternativeMethodsButtonStrategy,Re as createBigCommercePaymentsAlternativeMethodsPaymentStrategy,rt as createBigCommercePaymentsButtonStrategy,Ue as createBigCommercePaymentsCreditCardsPaymentStrategy,Ye as createBigCommercePaymentsCustomerStrategy,Je as createBigCommercePaymentsFastlaneCustomerStrategy,fe as createBigCommercePaymentsFastlanePaymentStrategy,dt as createBigCommercePaymentsPayLaterButtonStrategy,Qe as createBigCommercePaymentsPayLaterCustomerStrategy,Ce as createBigCommercePaymentsPayLaterPaymentStrategy,J as createBigCommercePaymentsPaymentStrategy,ke as createBigCommercePaymentsRatePayPayPaymentStrategy,yt as createBigCommercePaymentsVenmoButtonStrategy,it as createBigCommercePaymentsVenmoCustomerStrategy,qe as createBigCommercePaymentsVenmoPaymentStrategy};
2
2
  //# sourceMappingURL=bigcommerce-payments.js.map