{"version":3,"sources":["webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/Subscriber.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/Observable.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/innerSubscribe.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/Subscription.ts","webpack://checkout/../../../src/common/utils/index.js","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/Subject.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/isArray.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduler/async.ts","webpack://checkout//webpack/bootstrap","webpack://checkout/webpack:/external \"tslib\"","webpack://checkout/webpack:/external \"lodash\"","webpack://checkout/webpack:/external \"@bigcommerce/data-store\"","webpack://checkout/webpack:/external \"rxjs\"","webpack://checkout/webpack:/external \"@bigcommerce/memoize\"","webpack://checkout//src/shipping/consignment-actions.ts","webpack://checkout/webpack:/external \"rxjs/operators\"","webpack://checkout//src/payment/payment-strategy-type.ts","webpack://checkout//src/shipping/shipping-strategy-actions.ts","webpack://checkout//src/customer/customer-strategy-actions.ts","webpack://checkout//src/payment/payment-strategy-actions.ts","webpack://checkout//src/common/error/errors/missing-data-error.ts","webpack://checkout//src/checkout/checkout-actions.ts","webpack://checkout//src/order/order-actions.ts","webpack://checkout//src/payment/payment-method-actions.ts","webpack://checkout//src/billing/billing-address-actions.ts","webpack://checkout//src/checkout-buttons/checkout-button-actions.ts","webpack://checkout//src/coupon/coupon-actions.ts","webpack://checkout//src/common/error/errors/standard-error.ts","webpack://checkout//src/common/utility/set-prototype-of.ts","webpack://checkout//src/customer/customer-actions.ts","webpack://checkout//src/embedded-checkout/embedded-checkout-events.ts","webpack://checkout//src/payment/instrument/instrument-actions.ts","webpack://checkout//src/coupon/gift-certificate-actions.ts","webpack://checkout//src/payment/strategies/googlepay/googlepay.ts","webpack://checkout//src/remote-checkout/remote-checkout-actions.ts","webpack://checkout/webpack:/external \"@bigcommerce/script-loader\"","webpack://checkout//src/common/http-request/content-type.ts","webpack://checkout//src/payment/payment-status-types.ts","webpack://checkout/webpack:/external \"card-validator\"","webpack://checkout//src/common/error/errors/request-error.ts","webpack://checkout//src/payment/is-vaulted-instrument.ts","webpack://checkout//src/config/config-actions.ts","webpack://checkout//src/form/form-fields-actions.ts","webpack://checkout//src/payment/errors/payment-method-client-unavailable-error.ts","webpack://checkout//src/common/utility/is-plain-object.ts","webpack://checkout//src/geography/country-actions.ts","webpack://checkout//src/shipping/shipping-country-actions.ts","webpack://checkout//src/signin-email/signin-email-actions.ts","webpack://checkout/webpack:/external \"@bigcommerce/request-sender\"","webpack://checkout//src/store-credit/store-credit-actions.ts","webpack://checkout//src/hosted-form/iframe-content/hosted-input-events.ts","webpack://checkout//src/common/url/parse-url.ts","webpack://checkout//src/common/error/errors/invalid-argument-error.ts","webpack://checkout//src/common/iframe/is-iframe-event.ts","webpack://checkout//src/payment/payment-method-types.ts","webpack://checkout//src/address/map-to-internal-address.ts","webpack://checkout//src/common/http-request/internal-api-headers.ts","webpack://checkout//src/payment/payment-actions.ts","webpack://checkout//src/common/http-request/join-includes.ts","webpack://checkout//src/cart/map-to-internal-line-items.ts","webpack://checkout//src/cart/map-gift-certificate-to-internal-line-item.ts","webpack://checkout/webpack:/external \"local-storage-fallback\"","webpack://checkout//src/spam-protection/spam-protection-actions.ts","webpack://checkout/webpack:/external \"shallowequal\"","webpack://checkout//src/hosted-form/hosted-field-events.ts","webpack://checkout//src/common/utility/is-equal.ts","webpack://checkout/webpack:/external \"@bigcommerce/form-poster\"","webpack://checkout//src/cart/map-to-internal-line-item.ts","webpack://checkout/webpack:/external \"reselect\"","webpack://checkout//src/shipping/map-to-internal-shipping-option.ts","webpack://checkout//src/common/utility/amount-transformer.ts","webpack://checkout//src/common/selector/with-memoized-combiner.ts","webpack://checkout//src/common/error/error-actions.ts","webpack://checkout//src/payment/payment-method-action-creator.ts","webpack://checkout//src/payment/payment-method-request-sender.ts","webpack://checkout//src/checkout/checkout-default-includes.ts","webpack://checkout//src/common/error/throw-error-action.ts","webpack://checkout//src/payment/errors/payment-method-failed-error.ts","webpack://checkout//src/common/data-store/cache-action.ts","webpack://checkout//src/common/data-store/is-action-options.ts","webpack://checkout//src/common/data-store/cachable-action-decorator.ts","webpack://checkout//src/common/utility/bind-decorator.ts","webpack://checkout//src/customer/map-to-internal-customer.ts","webpack://checkout//src/order/map-to-internal-order.ts","webpack://checkout//src/cart/map-to-internal-cart.ts","webpack://checkout//src/promotion/map-to-discount-notifications.ts","webpack://checkout/webpack:/external \"@bigcommerce/bigpay-client\"","webpack://checkout//src/payment/strategies/amazon-pay-v2/amazon-pay-v2.ts","webpack://checkout//src/payment/strategies/braintree/braintree-script-loader.ts","webpack://checkout//src/payment/strategies/braintree/braintree-sdk-creator.ts","webpack://checkout//src/embedded-checkout/iframe-content/embedded-content-events.ts","webpack://checkout//src/billing/is-billing-address-like.ts","webpack://checkout//src/hosted-form/iframe-content/card-expiry-formatter.ts","webpack://checkout//src/hosted-form/iframe-content/card-number-formatter.ts","webpack://checkout//src/coupon/map-to-internal-coupon.ts","webpack://checkout//src/common/url/append-www.ts","webpack://checkout//src/common/error/errors/not-initialized-error.ts","webpack://checkout//src/common/http-request/join-or-merge-includes.ts","webpack://checkout//src/common/http-request/merge-includes.ts","webpack://checkout/webpack:/external \"iframe-resizer\"","webpack://checkout/webpack:/external \"iframe-resizer/js/iframeResizer.contentWindow\"","webpack://checkout//src/common/utility/omit-deep.ts","webpack://checkout//src/checkout/checkout-action-creator.ts","webpack://checkout//src/shipping/consignment-action-creator.ts","webpack://checkout//src/shipping/consignment-request-sender.ts","webpack://checkout//src/payment/strategies/masterpass/get-callback-url.ts","webpack://checkout//src/payment/payment-request-transformer.ts","webpack://checkout//src/payment/payment-request-sender.ts","webpack://checkout//src/common/utility/is-private.ts","webpack://checkout//src/common/error/errors/unrecoverable-error.ts","webpack://checkout//src/common/error/errors/map-from-internal-error-response.ts","webpack://checkout//src/common/error/request-error-factory.ts","webpack://checkout//src/common/error/errors/map-from-storefront-error-response.ts","webpack://checkout//src/common/error/clear-error-reducer.ts","webpack://checkout//src/common/utility/replace.ts","webpack://checkout//src/common/utility/object-set.ts","webpack://checkout//src/billing/billing-address-state.ts","webpack://checkout//src/billing/billing-address-reducer.ts","webpack://checkout//src/common/utility/array-replace.ts","webpack://checkout//src/common/utility/object-merge.ts","webpack://checkout//src/cart/cart-state.ts","webpack://checkout//src/cart/cart-reducer.ts","webpack://checkout//src/checkout-buttons/checkout-button-state.ts","webpack://checkout//src/checkout-buttons/checkout-button-reducer.ts","webpack://checkout//src/config/config-state.ts","webpack://checkout//src/config/config-reducer.ts","webpack://checkout//src/coupon/coupon-state.ts","webpack://checkout//src/coupon/coupon-reducer.ts","webpack://checkout//src/coupon/gift-certificate-state.ts","webpack://checkout//src/coupon/gift-certificate-reducer.ts","webpack://checkout//src/customer/customer-state.ts","webpack://checkout//src/customer/customer-reducer.ts","webpack://checkout//src/customer/customer-strategy-state.ts","webpack://checkout//src/customer/customer-strategy-reducer.ts","webpack://checkout//src/form/form-fields-state.ts","webpack://checkout//src/form/form-fields-reducer.ts","webpack://checkout//src/geography/country-state.ts","webpack://checkout//src/geography/country-reducer.ts","webpack://checkout//src/order/order-state.ts","webpack://checkout//src/order/order-reducer.ts","webpack://checkout//src/payment/payment-reducer.ts","webpack://checkout//src/payment/payment-method-state.ts","webpack://checkout//src/payment/payment-method-reducer.ts","webpack://checkout//src/common/utility/merge-or-push.ts","webpack://checkout//src/payment/payment-strategy-state.ts","webpack://checkout//src/payment/payment-strategy-reducer.ts","webpack://checkout//src/payment/instrument/instrument-state.ts","webpack://checkout//src/payment/instrument/instrument-reducer.ts","webpack://checkout//src/remote-checkout/remote-checkout-state.ts","webpack://checkout//src/remote-checkout/remote-checkout-reducer.ts","webpack://checkout//src/shipping/consignment-state.ts","webpack://checkout//src/shipping/consignment-reducer.ts","webpack://checkout//src/shipping/shipping-country-state.ts","webpack://checkout//src/shipping/shipping-country-reducer.ts","webpack://checkout//src/shipping/shipping-strategy-state.ts","webpack://checkout//src/shipping/shipping-strategy-reducer.ts","webpack://checkout//src/signin-email/signin-email-state.ts","webpack://checkout//src/signin-email/signin-email-reducer.ts","webpack://checkout//src/store-credit/store-credit-reducer.ts","webpack://checkout//src/subscription/subscriptions-state.ts","webpack://checkout//src/subscription/subscriptions-reducer.ts","webpack://checkout//src/checkout/checkout-state.ts","webpack://checkout//src/checkout/checkout-reducer.ts","webpack://checkout//src/common/utility/guard.ts","webpack://checkout//src/common/utility/create-freeze-proxy.ts","webpack://checkout//src/payment/instrument/supported-payment-instruments.ts","webpack://checkout//src/address/is-address-equal.ts","webpack://checkout//src/store-credit/store-credit-state.ts","webpack://checkout//src/checkout/create-internal-checkout-selectors.ts","webpack://checkout//src/billing/billing-address-selector.ts","webpack://checkout//src/checkout-buttons/checkout-button-selector.ts","webpack://checkout//src/coupon/coupon-selector.ts","webpack://checkout//src/customer/customer-selector.ts","webpack://checkout//src/remote-checkout/remote-checkout-selector.ts","webpack://checkout//src/shipping/shipping-address-selector.ts","webpack://checkout//src/payment/payment-selector.ts","webpack://checkout//src/signin-email/signin-email-selector.ts","webpack://checkout//src/cart/cart-selector.ts","webpack://checkout//src/config/config-selector.ts","webpack://checkout//src/geography/country-selector.ts","webpack://checkout//src/customer/customer-strategy-selector.ts","webpack://checkout//src/coupon/gift-certificate-selector.ts","webpack://checkout//src/payment/instrument/instrument-selector.ts","webpack://checkout//src/form/form-selector.ts","webpack://checkout//src/payment/payment-method-selector.ts","webpack://checkout//src/payment/payment-strategy-selector.ts","webpack://checkout//src/shipping/shipping-country-selector.ts","webpack://checkout//src/shipping/shipping-strategy-selector.ts","webpack://checkout//src/shipping/consignment-selector.ts","webpack://checkout//src/checkout/checkout-selector.ts","webpack://checkout//src/order/order-selector.ts","webpack://checkout//src/store-credit/store-credit-selector.ts","webpack://checkout//src/subscription/subscriptions-selector.ts","webpack://checkout//src/checkout/create-checkout-store.ts","webpack://checkout//src/checkout/create-action-transformer.ts","webpack://checkout//src/common/error/create-request-error-factory.ts","webpack://checkout//src/checkout/create-checkout-store-reducer.ts","webpack://checkout//src/checkout/errors/checkout-not-available-error.ts","webpack://checkout//src/checkout/checkout-request-sender.ts","webpack://checkout//src/checkout/checkout-params.ts","webpack://checkout//src/coupon/map-to-internal-gift-certificate.ts","webpack://checkout//src/common/iframe/iframe-event-poster.ts","webpack://checkout//src/common/iframe/iframe-event-listener.ts","webpack://checkout//src/common/selector/selector-decorator.ts","webpack://checkout//src/checkout-buttons/checkout-button-error-selector.ts","webpack://checkout//src/checkout-buttons/checkout-button-status-selector.ts","webpack://checkout//src/checkout-buttons/create-checkout-button-selectors.ts","webpack://checkout//src/checkout-buttons/checkout-button-initializer.ts","webpack://checkout//src/checkout-buttons/strategies/checkout-button-method-type.ts","webpack://checkout//src/common/dom/is-element-id.ts","webpack://checkout//src/common/dom/set-unique-element-id.ts","webpack://checkout//src/checkout-buttons/checkout-button-strategy-action-creator.ts","webpack://checkout//src/checkout-buttons/strategies/amazon-pay-v2/amazon-pay-v2-button-strategy.ts","webpack://checkout//src/checkout-buttons/strategies/braintree/braintree-paypal-button-strategy.ts","webpack://checkout//src/checkout-buttons/strategies/googlepay/googlepay-button-strategy.ts","webpack://checkout//src/checkout-buttons/strategies/masterpass/masterpass-button-strategy.ts","webpack://checkout//src/checkout-buttons/strategies/paypal/paypal-button-strategy.ts","webpack://checkout//src/checkout-buttons/strategies/paypal-commerce/paypal-commerce-button-strategy.ts","webpack://checkout//src/checkout-buttons/create-checkout-button-initializer.ts","webpack://checkout//src/checkout-buttons/create-checkout-button-registry.ts","webpack://checkout//src/embedded-checkout/errors/not-embeddable-error.ts","webpack://checkout//src/common/storage/browser-storage.ts","webpack://checkout//src/embedded-checkout/errors/invalid-login-token-error.ts","webpack://checkout//src/embedded-checkout/embedded-checkout.ts","webpack://checkout//src/embedded-checkout/resizable-iframe-creator.ts","webpack://checkout//src/embedded-checkout/embed-checkout.ts","webpack://checkout//src/embedded-checkout/iframe-content/handle-frame-loaded-event.ts","webpack://checkout//src/common/error/errors/custom-error.ts","webpack://checkout//src/embedded-checkout/iframe-content/iframe-embedded-checkout-messenger.ts","webpack://checkout//src/embedded-checkout/iframe-content/noop-embedded-checkout-messenger.ts","webpack://checkout//src/embedded-checkout/iframe-content/create-embedded-checkout-messenger.ts","webpack://checkout//src/common/utility/cache-key-maps.ts","webpack://checkout//src/common/utility/cache-key-resolver.ts","webpack://checkout/webpack:/external \"@braintree/browser-detection\"","webpack://checkout/webpack:/external \"messageformat\"","webpack://checkout//src/common/error/errors/map-from-payment-error-response.ts","webpack://checkout//src/common/error/errors/timeout-error.ts","webpack://checkout//src/payment/errors/payment-method-invalid-error.ts","webpack://checkout//src/common/selector/create-selector.ts","webpack://checkout//src/subscription/subscriptions-actions.ts","webpack://checkout//src/config/config-action-creator.ts","webpack://checkout//src/config/config-request-sender.ts","webpack://checkout//src/subscription/subscriptions-request-sender.ts","webpack://checkout//src/form/form-fields-action-creator.ts","webpack://checkout//src/form/form-fields-request-sender.ts","webpack://checkout//src/billing/billing-address-request-sender.ts","webpack://checkout//src/common/registry/registry.ts","webpack://checkout//src/common/error/errors/not-implemented-error.ts","webpack://checkout//src/remote-checkout/errors/remote-checkout-synchronization-error.ts","webpack://checkout//src/payment/strategies/googlepay/googlepay-adyenv2-initializer.ts","webpack://checkout//src/payment/strategies/masterpass/masterpass-script-loader.ts","webpack://checkout//src/payment/strategies/googlepay/googlepay-authorizenet-initializer.ts","webpack://checkout//src/payment/strategies/googlepay/googlepay-braintree-initializer.ts","webpack://checkout//src/payment/strategies/googlepay/googlepay-checkoutcom-initializer.ts","webpack://checkout//src/payment/strategies/googlepay/googlepay-cybersourcev2-initializer.ts","webpack://checkout//src/payment/strategies/googlepay/googlepay-stripe-initializer.ts","webpack://checkout//src/hosted-form/errors/invalid-hosted-form-config-error.ts","webpack://checkout//src/hosted-form/errors/invalid-hosted-form-value-error.ts","webpack://checkout//src/payment/strategies/paypal/paypal-script-loader.ts","webpack://checkout//src/payment/strategies/paypal-commerce/paypal-commerce-request-sender.ts","webpack://checkout//src/common/loading-indicator/loading-indicator.ts","webpack://checkout//src/common/iframe/iframe-resizer.ts","webpack://checkout//src/common/error/error-action-creator.ts","webpack://checkout//src/common/utility/get-environment.ts","webpack://checkout//src/common/log/create-logger.ts","webpack://checkout//src/common/log/console-logger.ts","webpack://checkout//src/common/log/noop-logger.ts","webpack://checkout//src/common/log/get-default-logger.ts","webpack://checkout//src/coupon/coupon-action-creator.ts","webpack://checkout//src/coupon/coupon-request-sender.ts","webpack://checkout//src/coupon/gift-certificate-action-creator.ts","webpack://checkout//src/coupon/gift-certificate-request-sender.ts","webpack://checkout//src/spam-protection/is-spam-protection-succeeded-action.ts","webpack://checkout//src/customer/customer-action-creator.ts","webpack://checkout//src/customer/customer-request-sender.ts","webpack://checkout//src/customer/customer-strategy-action-creator.ts","webpack://checkout//src/payment/strategies/amazon-pay/amazon-pay-script-loader.ts","webpack://checkout//src/payment/strategies/braintree/braintree-visacheckout-payment-processor.ts","webpack://checkout//src/payment/strategies/braintree/create-braintree-visacheckout-payment-processor.ts","webpack://checkout//src/payment/strategies/braintree/visacheckout-script-loader.ts","webpack://checkout//src/payment/strategies/chasepay/chasepay-script-loader.ts","webpack://checkout//src/payment/strategies/googlepay/googlepay-orbital-initializer.ts","webpack://checkout//src/remote-checkout/remote-checkout-request-sender.ts","webpack://checkout//src/remote-checkout/remote-checkout-action-creator.ts","webpack://checkout//src/spam-protection/errors/spam-protection-challenge-not-completed-error.ts","webpack://checkout//src/spam-protection/errors/spam-protection-failed-error.ts","webpack://checkout//src/spam-protection/spam-protection-action-creator.ts","webpack://checkout//src/common/dom/mutation-observer.ts","webpack://checkout//src/spam-protection/errors/spam-protection-not-loaded-error.ts","webpack://checkout//src/spam-protection/google-recaptcha.ts","webpack://checkout//src/spam-protection/google-recaptcha-script-loader.ts","webpack://checkout//src/spam-protection/create-spam-protection.ts","webpack://checkout//src/spam-protection/spam-protection-request-sender.ts","webpack://checkout//src/customer/strategies/amazon/amazon-pay-customer-strategy.ts","webpack://checkout//src/customer/strategies/amazon-pay-v2/amazon-pay-v2-customer-strategy.ts","webpack://checkout//src/customer/strategies/braintree/braintree-visacheckout-customer-strategy.ts","webpack://checkout//src/customer/strategies/chasepay/chasepay-customer-strategy.ts","webpack://checkout//src/customer/strategies/default/default-customer-strategy.ts","webpack://checkout//src/customer/strategies/googlepay/googlepay-customer-strategy.ts","webpack://checkout//src/customer/strategies/masterpass/masterpass-customer-strategy.ts","webpack://checkout//src/customer/strategies/square/square-customer-strategy.ts","webpack://checkout//src/geography/country-action-creator.ts","webpack://checkout//src/geography/country-request-sender.ts","webpack://checkout//src/order/order-request-sender.ts","webpack://checkout//src/spam-protection/errors/spam-protection-not-completed-error.ts","webpack://checkout//src/order/order-action-creator.ts","webpack://checkout//src/order/errors/order-finalization-not-required-error.ts","webpack://checkout//src/payment/payment-strategy-action-creator.ts","webpack://checkout//src/cart/cart-comparator.ts","webpack://checkout//src/cart/errors/cart-changed-error.ts","webpack://checkout//src/checkout/checkout-validator.ts","webpack://checkout//src/common/utility/cancellable-promise.ts","webpack://checkout//src/common/dom/errors/unexpected-detachment-error.ts","webpack://checkout//src/common/dom/detachment-observer.ts","webpack://checkout//src/spam-protection/errors/carding-protection-challenge-not-completed-error.ts","webpack://checkout//src/spam-protection/errors/carding-protection-failed-error.ts","webpack://checkout//src/spam-protection/payment-human-verification-handler.ts","webpack://checkout//src/hosted-form/errors/invalid-hosted-form-error.ts","webpack://checkout//src/hosted-form/hosted-field.ts","webpack://checkout//src/hosted-form/hosted-form.ts","webpack://checkout//src/hosted-form/hosted-form-order-data-transformer.ts","webpack://checkout//src/hosted-form/hosted-form-factory.ts","webpack://checkout//src/store-credit/store-credit-action-creator.ts","webpack://checkout//src/store-credit/store-credit-request-sender.ts","webpack://checkout//src/payment/payment-action-creator.ts","webpack://checkout//src/payment/ppsdk-payment-method.ts","webpack://checkout//src/payment/payment-strategy-registry.ts","webpack://checkout//src/payment/storefront-payment-request-sender.ts","webpack://checkout//src/common/browser-info/get-browser-info.ts","webpack://checkout//src/payment/strategies/adyenv2/adyenv2.ts","webpack://checkout//src/payment/errors/payment-argument-invalid-error.ts","webpack://checkout//src/payment/errors/payment-method-cancelled-error.ts","webpack://checkout//src/payment/strategies/adyenv2/adyenv2-payment-strategy.ts","webpack://checkout//src/order/order-params.ts","webpack://checkout//src/payment/strategies/adyenv2/adyenv2-script-loader.ts","webpack://checkout//src/payment/strategies/affirm/affirm-payment-strategy.ts","webpack://checkout//src/payment/strategies/affirm/affirm-script-loader.ts","webpack://checkout//src/payment/strategies/affirm/affirmJs.ts","webpack://checkout//src/payment/strategies/afterpay/afterpay-payment-strategy.ts","webpack://checkout//src/payment/strategies/afterpay/afterpay-script-loader.ts","webpack://checkout//src/address/is-internal-address-equal.ts","webpack://checkout//src/common/utility/omit-private.ts","webpack://checkout//src/address/map-from-internal-address.ts","webpack://checkout//src/payment/strategies/bolt/bolt.ts","webpack://checkout//src/payment/strategies/amazon-pay/amazon-pay-payment-strategy.ts","webpack://checkout//src/payment/strategies/amazon-pay-v2/amazon-pay-v2-payment-strategy.ts","webpack://checkout//src/payment/strategies/credit-card/credit-card-payment-strategy.ts","webpack://checkout//src/payment/strategies/barclays/barclays-payment-strategy.ts","webpack://checkout//src/payment/strategies/bluesnapv2/bluesnapv2-payment-strategy.ts","webpack://checkout//src/payment/strategies/bolt/bolt-payment-strategy.ts","webpack://checkout//src/payment/is-nonce-like.ts","webpack://checkout//src/payment/strategies/bolt/bolt-script-loader.ts","webpack://checkout//src/payment/strategies/braintree/braintree-payment-options.ts","webpack://checkout//src/common/overlay/overlay.ts","webpack://checkout//src/common/overlay/overlay-style.ts","webpack://checkout//src/payment/errors/payment-invalid-form-error.ts","webpack://checkout//src/payment/strategies/braintree/braintree-regular-field.ts","webpack://checkout//src/payment/strategies/braintree/braintree-hosted-form.ts","webpack://checkout//src/payment/strategies/braintree/is-braintree-form-fields-map.ts","webpack://checkout//src/payment/strategies/cardinal/cardinal.ts","webpack://checkout//src/payment/strategies/braintree/braintree-payment-processor.ts","webpack://checkout//src/payment/strategies/braintree/braintree-credit-card-payment-strategy.ts","webpack://checkout//src/payment/strategies/braintree/braintree-paypal-payment-strategy.ts","webpack://checkout//src/payment/strategies/braintree/is-braintree-error.ts","webpack://checkout//src/payment/strategies/braintree/map-to-braintree-shipping-address-override.ts","webpack://checkout//src/payment/strategies/braintree/braintree-visacheckout-payment-strategy.ts","webpack://checkout//src/payment/strategies/cardinal/cardinal-three-d-secure-flow-v2.ts","webpack://checkout//src/payment/is-credit-card-like.ts","webpack://checkout//src/payment/strategies/cardinal/cardinal-client.ts","webpack://checkout//src/payment/strategies/chasepay/chasepay.ts","webpack://checkout//src/payment/strategies/cardinal/cardinal-script-loader.ts","webpack://checkout//src/payment/strategies/cardinal/cardinal-three-d-secure-flow.ts","webpack://checkout//src/payment/strategies/chasepay/chasepay-payment-strategy.ts","webpack://checkout//src/payment/payment-response-body.ts","webpack://checkout//src/payment/strategies/checkoutcom-custom/checkoutcom-custom-payment-strategy.ts","webpack://checkout//src/payment/strategies/digitalriver/digitalriver.ts","webpack://checkout//src/payment/strategies/checkoutcom-custom/checkoutcom-apm/checkoutcom-apm-payment-strategy.ts","webpack://checkout//src/payment/strategies/checkoutcom-custom/checkoutcom-sepa/checkoutcom-sepa-payment-strategy.ts","webpack://checkout//src/payment/strategies/checkoutcom-custom/checkoutcom-ideal/checkoutcom-ideal-payment-strategy.ts","webpack://checkout//src/payment/strategies/checkoutcom-custom/checkoutcom-sepa/checkoutcom-fawry-payment-strategy.ts","webpack://checkout//src/payment/strategies/clearpay/clearpay-payment-strategy.ts","webpack://checkout//src/payment/strategies/clearpay/clearpay-script-loader.ts","webpack://checkout//src/payment/strategies/converge/converge-payment-strategy.ts","webpack://checkout//src/payment/strategies/credit-card-redirect/credit-card-redirect-payment-strategy.ts","webpack://checkout//src/payment/strategies/cybersource/cybersource-payment-strategy.ts","webpack://checkout//src/payment/strategies/cybersourcev2/cybersourcev2-payment-strategy.ts","webpack://checkout//src/payment/strategies/digitalriver/digitalriver-payment-strategy.ts","webpack://checkout//src/payment/strategies/mollie/mollie-payment-strategy.ts","webpack://checkout//src/payment/strategies/digitalriver/digitalriver-script-loader.ts","webpack://checkout//src/payment/strategies/external/external-payment-strategy.ts","webpack://checkout//src/payment/strategies/googlepay/googlepay-payment-strategy.ts","webpack://checkout//src/payment/strategies/googlepay/googlepay-adyenv2-payment-processor.ts","webpack://checkout//src/payment/strategies/klarnav2/klarna-supported-countries.ts","webpack://checkout//src/payment/strategies/klarna/klarna-payment-strategy.ts","webpack://checkout//src/payment/strategies/klarna/klarna-script-loader.ts","webpack://checkout//src/payment/strategies/klarnav2/klarnav2-payment-strategy.ts","webpack://checkout//src/payment/strategies/klarnav2/klarnav2-script-loader.ts","webpack://checkout//src/payment/strategies/legacy/legacy-payment-strategy.ts","webpack://checkout//src/payment/strategies/masterpass/masterpass-payment-strategy.ts","webpack://checkout//src/payment/strategies/paypal-commerce/paypal-commerce-payment-initialize-options.ts","webpack://checkout//src/payment/strategies/paypal-commerce/paypal-commerce-hosted-form.ts","webpack://checkout//src/payment/strategies/mollie/mollie-script-loader.ts","webpack://checkout//src/payment/strategies/moneris/moneris-payment-strategy.ts","webpack://checkout//src/payment/strategies/no-payment/no-payment-data-required-strategy.ts","webpack://checkout//src/payment/strategies/offline/offline-payment-strategy.ts","webpack://checkout//src/payment/strategies/offsite/offsite-payment-strategy.ts","webpack://checkout//src/payment/strategies/paypal/paypal-pro-payment-strategy.ts","webpack://checkout//src/payment/strategies/paypal/paypal-express-payment-strategy.ts","webpack://checkout//src/payment/strategies/paypal-commerce/paypal-commerce-credit-card-payment-strategy.ts","webpack://checkout//src/payment/strategies/paypal-commerce/paypal-commerce-regular-field.ts","webpack://checkout//src/payment/strategies/ppsdk/ppsdk-payment-processor-type.ts","webpack://checkout//src/payment/strategies/paypal-commerce/paypal-commerce-payment-strategy.ts","webpack://checkout//src/payment/strategies/paypal-commerce/paypal-commerce-funding-key-resolver.ts","webpack://checkout//src/payment/strategies/ppsdk/step-handler/continue-handler/continue-handler.ts","webpack://checkout//src/payment/strategies/ppsdk/step-handler/continue-handler/redirect.ts","webpack://checkout//src/payment/strategies/ppsdk/step-handler/step-handler.ts","webpack://checkout//src/payment/strategies/ppsdk/step-handler/server-error.ts","webpack://checkout//src/payment/strategies/ppsdk/step-handler/success.ts","webpack://checkout//src/payment/strategies/ppsdk/step-handler/failed.ts","webpack://checkout//src/payment/strategies/ppsdk/step-handler/error.ts","webpack://checkout//src/payment/strategies/ppsdk/step-handler/create-step-handler.ts","webpack://checkout//src/payment/strategies/ppsdk/get-ppsdk-payment-method.ts","webpack://checkout//src/payment/strategies/ppsdk/ppsdk-strategy.ts","webpack://checkout//src/payment/strategies/ppsdk/payment-processors/none-payment-processor.ts","webpack://checkout//src/payment/strategies/ppsdk/ppsdk-payment-processor-registry.ts","webpack://checkout//src/payment/strategies/square/square-form.ts","webpack://checkout//src/payment/strategies/ppsdk/initialization-strategies/none.ts","webpack://checkout//src/payment/strategies/ppsdk/create-ppsdk-payment-processor-registry.ts","webpack://checkout//src/payment/strategies/ppsdk/ppsdk-payment-resumer.ts","webpack://checkout//src/payment/strategies/quadpay/quadpay-payment-strategy.ts","webpack://checkout//src/payment/strategies/sage-pay/sage-pay-payment-strategy.ts","webpack://checkout//src/common/error/errors/unsupported-browser-error.ts","webpack://checkout//src/payment/strategies/square/square-payment-strategy.ts","webpack://checkout//src/payment/strategies/stripev3/stripev3.ts","webpack://checkout//src/payment/strategies/square/square-script-loader.ts","webpack://checkout//src/payment/strategies/stripev3/stripev3-payment-strategy.ts","webpack://checkout//src/payment/strategies/stripev3/stripev3-script-loader.ts","webpack://checkout//src/payment/strategies/wepay/wepay-risk-client.ts","webpack://checkout//src/payment/strategies/wepay/wepay-payment-strategy.ts","webpack://checkout//src/payment/errors/payment-method-declined-error.ts","webpack://checkout//src/payment/strategies/zip/zip-payment-strategy.ts","webpack://checkout//src/payment/strategies/zip/zip-script-loader.ts","webpack://checkout//src/common/data-store/create-data-store-projection.ts","webpack://checkout//src/payment/instrument/instrument-action-creator.ts","webpack://checkout//src/common/date-time/is-future.ts","webpack://checkout//src/common/date-time/add-minutes.ts","webpack://checkout//src/payment/instrument/instrument-response-transformer.ts","webpack://checkout//src/payment/instrument/map-to-paypal-instrument.ts","webpack://checkout//src/payment/instrument/map-to-bank-instrument.ts","webpack://checkout//src/payment/instrument/map-to-card-instrument.ts","webpack://checkout//src/payment/instrument/instrument-request-sender.ts","webpack://checkout//src/shipping/shipping-country-action-creator.ts","webpack://checkout//src/shipping/shipping-country-request-sender.ts","webpack://checkout//src/shipping/shipping-strategy-action-creator.ts","webpack://checkout//src/shipping/strategies/amazon/amazon-pay-shipping-strategy.ts","webpack://checkout//src/shipping/strategies/amazon-pay-v2/amazon-pay-v2-shipping-strategy.ts","webpack://checkout//src/shipping/strategies/default/default-shipping-strategy.ts","webpack://checkout//src/signin-email/signin-email-action-creator.ts","webpack://checkout//src/signin-email/signin-email-request-sender.ts","webpack://checkout//src/common/utility/clone-result.ts","webpack://checkout//src/common/selector/create-shallow-equal-selector.ts","webpack://checkout//src/checkout/create-checkout-selectors.ts","webpack://checkout//src/checkout/checkout-store-selector.ts","webpack://checkout//src/checkout/checkout-store-error-selector.ts","webpack://checkout//src/checkout/checkout-store-status-selector.ts","webpack://checkout//src/common/error/error-message-transformer.ts","webpack://checkout//src/common/utility/to-single-line.ts","webpack://checkout//src/checkout/checkout-service.ts","webpack://checkout//src/checkout/create-checkout-service-error-transformer.ts","webpack://checkout//src/checkout/create-checkout-service.ts","webpack://checkout//src/payment/create-payment-client.ts","webpack://checkout//src/customer/create-customer-strategy-registry.ts","webpack://checkout//src/payment/create-payment-strategy-registry.ts","webpack://checkout//src/payment/strategies/braintree/create-braintree-payment-processor.ts","webpack://checkout//src/shipping/create-shipping-strategy-registry.ts","webpack://checkout//src/locale/language-service.ts","webpack://checkout//src/locale/create-language-service.ts","webpack://checkout//src/currency/currency-formatter.ts","webpack://checkout//src/currency/currency-service.ts","webpack://checkout//src/currency/create-currency-service.ts","webpack://checkout//src/analytics/analytics-step-tracker.ts","webpack://checkout//src/analytics/noop-step-tracker.ts","webpack://checkout//src/analytics/create-step-tracker.ts","webpack://checkout//src/analytics/is-analytics-step-tracker-window.ts","webpack://checkout//src/bundles/checkout-sdk.ts","webpack://checkout//src/payment/strategies/paypal-commerce/paypal-commerce-sdk.ts","webpack://checkout//src/payment/strategies/paypal-commerce/paypal-commerce-script-loader.ts","webpack://checkout//src/payment/strategies/paypal-commerce/paypal-commerce-payment-processor.ts","webpack://checkout//src/payment/strategies/paypal-commerce/create-paypal-commerce-payment-processor.ts","webpack://checkout//src/payment/strategies/googlepay/googlepay-payment-processor.ts","webpack://checkout//src/payment/strategies/googlepay/googlepay-script-loader.ts","webpack://checkout//src/payment/strategies/googlepay/create-googlepay-payment-processor.ts","webpack://checkout//src/payment/strategies/amazon-pay-v2/amazon-pay-v2-payment-processor.ts","webpack://checkout//src/payment/strategies/amazon-pay-v2/amazon-pay-v2-script-loader.ts","webpack://checkout//src/payment/strategies/amazon-pay-v2/create-amazon-pay-v2-payment-processor.ts","webpack://checkout//src/shipping/getShippableItemsCount.ts","webpack://checkout//src/shipping/getLineItemsCount.ts","webpack://checkout//src/subscription/errors/update-subscriptions-error.ts","webpack://checkout//src/subscription/subscriptions-action-creator.ts","webpack://checkout//src/billing/errors/unable-to-continue-as-guest-error.ts","webpack://checkout//src/billing/billing-address-action-creator.ts","webpack://checkout/../src/index.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/map.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/empty.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/isScheduler.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/from.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/identity.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/OuterSubscriber.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/subscribeToResult.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/symbol/observable.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/filter.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/multicast.ts","webpack://checkout/./node_modules/@bigcommerce/script-loader/node_modules/@bigcommerce/request-sender/node_modules/tslib/tslib.js","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/@bigcommerce/request-sender/node_modules/tslib/tslib.js","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/isFunction.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduler/AsyncAction.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduler/AsyncScheduler.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/fromArray.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/ArgumentOutOfRangeError.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/EmptyError.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/symbol/iterator.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/defaultIfEmpty.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/config.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/ObjectUnsubscribedError.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/Notification.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/of.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/AsyncSubject.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/subscribeTo.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/concat.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/mergeMap.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/isNumeric.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/throwIfEmpty.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/reduce.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/canReportError.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/hostReportError.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/isObject.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/symbol/rxSubscriber.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/pipe.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/refCount.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/ReplaySubject.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduled/scheduleArray.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/throwError.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/noop.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/combineLatest.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/mergeAll.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/defer.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/zip.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/take.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/takeLast.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/scan.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/switchMap.ts","webpack://checkout/../src/timeout.ts","webpack://checkout/../../../src/common/utils/is-nil.js","webpack://checkout/../../../src/common/utils/omit-property.js","webpack://checkout/../../../src/payment/payment-method-mappers/payment-method-id-mapper.js","webpack://checkout/../../src/payment/url-helper.js","webpack://checkout/../../../src/common/http-request/request-sender.js","webpack://checkout/../../../src/common/http-request/method-types.js","webpack://checkout/../src/data-store.ts","webpack://checkout/../src/deep-freeze.ts","webpack://checkout/../src/combine-reducers.ts","webpack://checkout/../src/create-action.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/Observer.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/UnsubscriptionError.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/ConnectableObservable.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/SubjectSubscription.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/groupBy.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/BehaviorSubject.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduler/queue.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/Scheduler.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/observeOn.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/subscribeToArray.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduler/asap.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/TimeoutError.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/isArrayLike.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/isPromise.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/concatAll.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduled/scheduled.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/merge.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/never.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/not.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/race.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/timer.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/audit.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/concatMap.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/isDate.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/distinctUntilChanged.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/find.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/throttle.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/timeoutWith.ts","webpack://checkout/../src/script-loader.ts","webpack://checkout/../src/create-script-loader.ts","webpack://checkout/./node_modules/@bigcommerce/script-loader/node_modules/query-string/index.js","webpack://checkout/../src/request-sender.ts","webpack://checkout/../src/browser-support.ts","webpack://checkout/../src/stylesheet-loader.ts","webpack://checkout/../src/create-stylesheet-loader.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/query-string/index.js","webpack://checkout/../src/form-poster.ts","webpack://checkout/../../src/payment/payment-types.js","webpack://checkout/../../../src/common/utils/is-object.js","webpack://checkout/../../../src/common/http-request/content-types.js","webpack://checkout/./node_modules/@bigcommerce/request-sender/node_modules/query-string/index.js","webpack://checkout/../src/is-observable-action-like.ts","webpack://checkout/../src/noop-action-transformer.ts","webpack://checkout/../src/noop-state-transformer.ts","webpack://checkout/../src/compose-reducers.ts","webpack://checkout/../src/create-data-store.ts","webpack://checkout/../src/create-error-action.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/index.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/toSubscriber.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduler/QueueAction.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduler/Action.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduler/QueueScheduler.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduler/AsapAction.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/Immediate.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduler/AsapScheduler.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduler/animationFrame.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduler/AnimationFrameAction.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduler/AnimationFrameScheduler.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduler/VirtualTimeScheduler.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/isObservable.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/bindCallback.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/bindNodeCallback.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/InnerSubscriber.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/subscribeToPromise.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/subscribeToIterable.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/subscribeToObservable.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduled/scheduleObservable.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduled/schedulePromise.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/scheduled/scheduleIterable.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/isInteropObservable.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/util/isIterable.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/forkJoin.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/fromEvent.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/fromEventPattern.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/generate.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/iif.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/interval.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/onErrorResumeNext.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/pairs.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/partition.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/range.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/using.ts","webpack://checkout/../src/memoize.ts","webpack://checkout/../src/cache-key-resolver.ts","webpack://checkout/../src/cache-key-maps.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/operators/index.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/auditTime.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/buffer.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/bufferCount.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/bufferTime.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/bufferToggle.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/bufferWhen.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/catchError.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/combineAll.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/combineLatest.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/concat.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/concatMapTo.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/count.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/debounce.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/debounceTime.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/delay.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/delayWhen.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/dematerialize.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/distinct.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/distinctUntilKeyChanged.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/elementAt.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/endWith.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/every.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/exhaust.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/exhaustMap.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/expand.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/finalize.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/findIndex.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/first.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/ignoreElements.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/isEmpty.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/last.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/mapTo.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/materialize.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/max.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/merge.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/mergeMapTo.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/mergeScan.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/min.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/onErrorResumeNext.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/pairwise.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/partition.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/pluck.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/publish.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/publishBehavior.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/publishLast.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/publishReplay.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/race.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/repeat.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/repeatWhen.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/retry.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/retryWhen.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/sample.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/sampleTime.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/sequenceEqual.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/share.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/shareReplay.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/single.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/skip.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/skipLast.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/skipUntil.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/skipWhile.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/startWith.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/subscribeOn.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/observable/SubscribeOnObservable.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/switchAll.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/switchMapTo.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/takeUntil.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/takeWhile.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/tap.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/throttleTime.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/timeInterval.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/timeout.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/timestamp.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/toArray.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/window.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/windowCount.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/windowTime.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/windowToggle.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/windowWhen.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/withLatestFrom.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/zip.ts","webpack://checkout/./node_modules/@bigcommerce/checkout-sdk/node_modules/rxjs/src/internal/operators/zipAll.ts","webpack://checkout/../src/create-request-sender.ts","webpack://checkout/../src/payload-transformer.ts","webpack://checkout/../src/to-form-url-encoded.ts","webpack://checkout/../src/request-factory.ts","webpack://checkout/../src/cache.ts","webpack://checkout/../src/is-promise.ts","webpack://checkout/../src/create-timeout.ts","webpack://checkout/../src/get-script-loader.ts","webpack://checkout/../src/get-stylesheet-loader.ts","webpack://checkout/../src/create-form-poster.ts","webpack://checkout/../src/form-builder.ts","webpack://checkout/../src/url-utils.ts","webpack://checkout/../src/index.js","webpack://checkout/../../src/client/client.js","webpack://checkout/../../src/payment/offsite-payment-initializer.js","webpack://checkout/../../../src/payment/offsite-payment-mappers/payload-mapper.js","webpack://checkout/../../../src/common/utils/includes.js","webpack://checkout/../../../src/common/utils/omit-emptystring-and-nil.js","webpack://checkout/../../../src/common/utils/is-emptystring-or-nil.js","webpack://checkout/../../../src/common/utils/is-empty-string.js","webpack://checkout/../../../src/common/utils/omit-nil.js","webpack://checkout/../../../src/common/utils/to-number.js","webpack://checkout/../../../src/common/utils/to-snake-case.js","webpack://checkout/../../../src/common/utils/to-string.js","webpack://checkout/../../../src/payment/offsite-payment-mappers/address-mapper.js","webpack://checkout/../../../src/payment/offsite-payment-mappers/customer-mapper.js","webpack://checkout/../../../src/payment/offsite-payment-mappers/meta-mapper.js","webpack://checkout/../../src/payment/payment-method-types.js","webpack://checkout/../../src/payment/payment-method-ids.js","webpack://checkout/../../../src/payment/offsite-payment-mappers/store-mapper.js","webpack://checkout/../../src/payment/payment-submitter.js","webpack://checkout/../../../../src/payment/v1/payment-mappers/payload-mapper.js","webpack://checkout/../../../../src/payment/v1/payment-mappers/customer-mapper.js","webpack://checkout/../../../../src/payment/v1/payment-mappers/order-mapper.js","webpack://checkout/../../../../src/payment/v1/payment-mappers/payment-mapper.js","webpack://checkout/../../../../src/payment/v1/payment-mappers/store-mapper.js","webpack://checkout/../../../src/common/http-request/default-options.js","webpack://checkout/../../../src/common/http-request/payload-transformer.js","webpack://checkout/../../../src/common/http-request/request-factory.js","webpack://checkout/../../src/payment/client-token-generator.js","webpack://checkout/../../../../src/payment/v2/payment-mappers/client-token-mapper.js","webpack://checkout/../../../../src/payment/v2/payment-mappers/cart-mapper.js","webpack://checkout/../../../../src/payment/v2/payment-mappers/gateway-mapper.js","webpack://checkout/../../../../src/payment/v2/payment-mappers/quote-mapper.js","webpack://checkout/../../../../src/payment/v2/payment-mappers/store-mapper.js","webpack://checkout/../../src/store/store-request-sender.js","webpack://checkout/../../src/store/url-helper.js","webpack://checkout/../../../../src/store/v2/mappers/index.js","webpack://checkout/../../src/client/default-config.js"],"names":["destinationOrNext","error","complete","syncErrorValue","syncErrorThrown","syncErrorThrowable","isStopped","arguments","length","destination","empty","Subscriber","add","SafeSubscriber","rxSubscriber","this","create","next","subscriber","value","_next","err","_error","_complete","unsubscribe","closed","_unsubscribeAndRecycle","_parentOrParents","Subscription","_parentSubscriber","observerOrNext","context","isFunction","Object","bind","_context","config","useDeprecatedSynchronousErrorHandling","__tryOrSetError","__tryOrUnsub","hostReportError","wrappedComplete","call","fn","parent","Error","_unsubscribe","subscribe","_isScalar","_subscribe","lift","operator","observable","Observable","source","sink","toSubscriber","_trySubscribe","canReportError","console","warn","forEach","promiseCtor","getPromiseCtor","resolve","reject","subscription","pipe","operations","pipeFromArray","toPromise","x","Promise","notifyNext","notifyError","notifyComplete","SimpleInnerSubscriber","outerValue","outerIndex","ComplexInnerSubscriber","innerValue","SimpleOuterSubscriber","_outerValue","_outerIndex","_innerSub","ComplexOuterSubscriber","result","innerSubscriber","subscribeTo","_subscriptions","_ctorUnsubscribe","errors","remove","index","undefined","e","UnsubscriptionError","flattenUnsubscriptionErrors","isArray","len","sub","isObject","concat","push","teardown","EMPTY","tmp","indexOf","subscriptions","subscriptionIndex","splice","reduce","errs","SubjectSubscriber","observers","hasError","thrownError","subject","AnonymousSubject","ObjectUnsubscribedError","copy","slice","i","SubjectSubscription","asObservable","Subject","Array","asyncScheduler","AsyncScheduler","AsyncAction","async","installedModules","__webpack_require__","moduleId","exports","module","l","modules","m","c","d","name","getter","o","defineProperty","enumerable","get","r","Symbol","toStringTag","t","mode","__esModule","ns","key","n","object","property","prototype","hasOwnProperty","p","s","require","ConsignmentActionType","CreateConsignmentsRequested","CreateConsignmentsSucceeded","CreateConsignmentsFailed","UpdateConsignmentRequested","UpdateConsignmentSucceeded","UpdateConsignmentFailed","DeleteConsignmentRequested","DeleteConsignmentSucceeded","DeleteConsignmentFailed","UpdateShippingOptionRequested","UpdateShippingOptionSucceeded","UpdateShippingOptionFailed","LoadShippingOptionsRequested","LoadShippingOptionsSucceeded","LoadShippingOptionsFailed","PaymentStrategyType","ADYENV2","ADYENV2_GOOGLEPAY","AFFIRM","AFTERPAY","AMAZON","AUTHORIZENET_GOOGLE_PAY","AMAZONPAYV2","BARCLAYS","BLUESNAPV2","BOLT","CHECKOUTCOM","CHECKOUTCOM_APM","CHECKOUTCOM_FAWRY","CHECKOUTCOM_SEPA","CHECKOUTCOM_IDEAL","CREDIT_CARD","CHECKOUTCOM_GOOGLE_PAY","CLEARPAY","CONVERGE","CYBERSOURCE","CYBERSOURCEV2","DIGITALRIVER","CYBERSOURCEV2_GOOGLE_PAY","KLARNA","KLARNAV2","LAYBUY","LEGACY","MOLLIE","MONERIS","NO_PAYMENT_DATA_REQUIRED","OFFLINE","OFFSITE","ORBITAL_GOOGLE_PAY","PAYPAL","PAYPAL_EXPRESS","PAYPAL_EXPRESS_CREDIT","PAYPAL_COMMERCE","PAYPAL_COMMERCE_CREDIT","PAYPAL_COMMERCE_CREDIT_CARD","PAYPAL_COMMERCE_ALTERNATIVE_METHODS","PPSDK","QUADPAY","SAGE_PAY","SQUARE","STRIPEV3","BRAINTREE","BRAINTREE_PAYPAL","BRAINTREE_PAYPAL_CREDIT","BRAINTREE_VISA_CHECKOUT","BRAINTREE_GOOGLE_PAY","CHASE_PAY","WE_PAY","MASTERPASS","STRIPE_GOOGLE_PAY","SEZZLE","ZIP","ShippingStrategyActionType","UpdateAddressFailed","UpdateAddressRequested","UpdateAddressSucceeded","SelectOptionFailed","SelectOptionRequested","SelectOptionSucceeded","InitializeFailed","InitializeRequested","InitializeSucceeded","DeinitializeFailed","DeinitializeRequested","DeinitializeSucceeded","WidgetInteractionStarted","WidgetInteractionFinished","WidgetInteractionFailed","CustomerStrategyActionType","SignInFailed","SignInRequested","SignInSucceeded","SignOutFailed","SignOutRequested","SignOutSucceeded","PaymentStrategyActionType","ExecuteFailed","ExecuteRequested","ExecuteSucceeded","FinalizeFailed","FinalizeRequested","FinalizeSucceeded","MissingDataErrorType","MissingBillingAddress","MissingCart","MissingCheckout","MissingConsignments","MissingCustomer","MissingCheckoutConfig","MissingOrder","MissingOrderConfig","MissingOrderId","MissingPayment","MissingPaymentInstrument","MissingPaymentMethod","MissingPaymentToken","MissingShippingAddress","subtype","type","CheckoutActionType","LoadCheckoutRequested","LoadCheckoutSucceeded","LoadCheckoutFailed","UpdateCheckoutRequested","UpdateCheckoutSucceeded","UpdateCheckoutFailed","OrderActionType","LoadOrderRequested","LoadOrderSucceeded","LoadOrderFailed","LoadOrderPaymentsRequested","LoadOrderPaymentsSucceeded","LoadOrderPaymentsFailed","SubmitOrderRequested","SubmitOrderSucceeded","SubmitOrderFailed","FinalizeOrderRequested","FinalizeOrderSucceeded","FinalizeOrderFailed","PaymentMethodActionType","LoadPaymentMethodRequested","LoadPaymentMethodSucceeded","LoadPaymentMethodFailed","LoadPaymentMethodsRequested","LoadPaymentMethodsSucceeded","LoadPaymentMethodsFailed","BillingAddressActionType","UpdateBillingAddressRequested","UpdateBillingAddressSucceeded","UpdateBillingAddressFailed","ContinueAsGuestRequested","ContinueAsGuestSucceeded","ContinueAsGuestFailed","CheckoutButtonActionType","InitializeButtonFailed","InitializeButtonRequested","InitializeButtonSucceeded","DeinitializeButtonFailed","DeinitializeButtonRequested","DeinitializeButtonSucceeded","CouponActionType","ApplyCouponRequested","ApplyCouponSucceeded","ApplyCouponFailed","RemoveCouponRequested","RemoveCouponSucceeded","RemoveCouponFailed","message","setPrototypeOf","__proto__","captureStackTrace","stack","CustomerActionType","SignInCustomerRequested","SignInCustomerSucceeded","SignInCustomerFailed","SignOutCustomerRequested","SignOutCustomerSucceeded","SignOutCustomerFailed","CreateCustomerRequested","CreateCustomerSucceeded","CreateCustomerFailed","CreateCustomerAddressRequested","CreateCustomerAddressSucceeded","CreateCustomerAddressFailed","EmbeddedCheckoutEventType","CheckoutComplete","CheckoutError","CheckoutLoaded","FrameError","FrameLoaded","SignedOut","InstrumentActionType","LoadInstrumentsRequested","LoadInstrumentsSucceeded","LoadInstrumentsFailed","DeleteInstrumentRequested","DeleteInstrumentSucceeded","DeleteInstrumentFailed","GiftCertificateActionType","ApplyGiftCertificateRequested","ApplyGiftCertificateSucceeded","ApplyGiftCertificateFailed","RemoveGiftCertificateRequested","RemoveGiftCertificateSucceeded","RemoveGiftCertificateFailed","ButtonType","ButtonColor","BillingAddressFormat","Long","Short","Default","Black","White","Min","Full","RemoteCheckoutActionType","InitializeRemoteBillingRequested","InitializeRemoteBillingSucceeded","InitializeRemoteBillingFailed","InitializeRemoteShippingRequested","InitializeRemoteShippingSucceeded","InitializeRemoteShippingFailed","InitializeRemotePaymentRequested","InitializeRemotePaymentSucceeded","InitializeRemotePaymentFailed","LoadRemoteSettingsRequested","LoadRemoteSettingsSucceeded","LoadRemoteSettingsFailed","SignOutRemoteCustomerRequested","SignOutRemoteCustomerSucceeded","SignOutRemoteCustomerFailed","UpdateRemoteCheckout","ContentType","Json","JsonV1","ACKNOWLEDGE","FINALIZE","DEFAULT_RESPONSE","body","headers","status","response","isVaultedInstrument","instrument","Boolean","instrumentId","isHostedVaultedInstrument","isFormattedVaultedInstrument","formattedInstrument","formattedPayload","bigpay_token","token","ConfigActionType","LoadConfigRequested","LoadConfigSucceeded","LoadConfigFailed","FormFieldsActionType","LoadFormFieldsRequested","LoadFormFieldsSucceeded","LoadFormFieldsFailed","isPlainObject","CountryActionType","LoadCountriesRequested","LoadCountriesSucceeded","LoadCountriesFailed","ShippingCountryActionType","LoadShippingCountriesRequested","LoadShippingCountriesSucceeded","LoadShippingCountriesFailed","SignInEmailActionType","SendSignInEmailRequested","SendSignInEmailSucceeded","SendSignInEmailFailed","StoreCreditActionType","ApplyStoreCreditRequested","ApplyStoreCreditSucceeded","ApplyStoreCreditFailed","HostedInputEventType","AttachSucceeded","AttachFailed","BinChanged","Blurred","Changed","CardTypeChanged","Entered","Focused","SubmitSucceeded","SubmitFailed","Validated","parseUrl","url","test","anchor","document","createElement","href","port","hostname","hash","origin","protocol","pathname","search","isIframeEvent","HOSTED","mapToInternalAddress","address","consignments","addressId","id","firstName","lastName","company","addressLine1","address1","addressLine2","address2","city","province","stateOrProvince","provinceCode","stateOrProvinceCode","postCode","postalCode","country","countryCode","phone","customFields","INTERNAL_USE_ONLY","PaymentActionType","SubmitPaymentRequested","SubmitPaymentSucceeded","SubmitPaymentFailed","InitializeOffsitePaymentRequested","InitializeOffsitePaymentSucceeded","InitializeOffsitePaymentFailed","joinIncludes","includes","uniq","join","mapToInternalLineItems","itemMap","decimalPlaces","idKey","keys","map","item","amountTransformer","imageUrl","amount","amountAfterDiscount","discount","integerAmount","toInteger","integerAmountAfterDiscount","integerUnitPrice","integerUnitPriceAfterDiscount","integerDiscount","quantity","sender","recipient","attributes","variantId","SpamProtectionActionType","VerifyCheckoutRequested","VerifyCheckoutSucceeded","VerifyCheckoutFailed","HostedFieldEventType","AttachRequested","SubmitRequested","ValidateRequested","isEqual","objectA","objectB","options","Date","getTime","RegExp","toString","filter","keyFilter","keysA","keysB","mapToInternalLineItem","extendedListPrice","extendedSalePrice","discountAmount","listPrice","salePrice","downloadsPageUrl","downloadPageUrl","brand","sku","categoryNames","productId","option","addedByPromotion","mapToInternalShippingOption","isSelected","description","price","cost","selected","isRecommended","transitTime","_decimalPlaces","Math","round","pow","withMemoizedCombiner","creator","combiner","args","pop","combinerArgs","memoize","ErrorActionType","ClearError","_requestSender","loadPaymentMethods","observer","createAction","then","meta","deviceSessionId","sessionHash","catch","createErrorAction","loadPaymentMethod","methodId","timeout","Accept","throwErrorAction","action","of","throwError","payload","cacheAction","from","shareReplay","store","isActionOptions","param","useCache","cachableActionDecorator","_","descriptor","memoizedMethods","WeakMap","decorateMethod","method","lastArg","instanceMethods","set","bindMethodDecorator","boundMethod","target","decoratedTarget","getOwnPropertyNames","getOwnPropertyDescriptor","mapToInternalCustomer","customer","billingAddress","addresses","customerId","isGuest","storeCredit","email","fullName","customerGroupName","customerGroup","mapToInternalOrder","order","orderMeta","payments","items","currency","orderId","lineItems","code","customerCanBeCreated","payment","mapToInternalOrderPayment","subtotal","baseAmount","coupon","discountedAmount","coupons","sum","orderToken","callbackUrl","discountNotifications","giftCertificate","providerId","totalDiscountedAmount","appliedGiftCertificates","keyBy","detail","remainingBalance","remaining","balance","purchaseDate","socialData","mapToInternalSocialDataList","hasDigitalItems","isDownloadable","isComplete","shipping","shippingCostTotal","amountBeforeDiscount","shippingCostBeforeDiscount","integerAmountBeforeDiscount","mapToStoreCredit","taxes","taxTotal","handling","handlingCostTotal","grandTotal","orderAmount","orderAmountAsInteger","mapToInternalPaymentStatus","find","isDefaultOrderPayment","step","helpText","instructions","returnUrl","socialDataObject","physicalItems","digitalItems","lineItem","socialMedia","image","link","shareText","text","sharingLink","channelName","channel","channelCode","mapToInternalCart","checkout","promotions","notifications","cart","promotion","banners","placeholders","discountType","messageHtml","banner","giftCertificates","certificate","used","required","some","isShippingRequired","taxSubtotal","AmazonPayV2Regions","AmazonPayV2CheckoutLanguage","AmazonPayV2Placement","AmazonPayV2LedgerCurrency","AmazonPayV2PayOptions","de","jp","uk","us","en_US","en_GB","de_DE","fr_FR","it_IT","es_ES","ja_JP","Home","Product","Cart","Checkout","Other","USD","EUR","GBP","JPY","PayAndShip","PayOnly","_scriptLoader","_window","loadClient","loadScript","braintree","client","load3DS","threeDSecure","loadDataCollector","dataCollector","loadPaypal","paypal","loadPaypalCheckout","paypalCheckout","loadVisaCheckout","visaCheckout","loadGooglePayment","googlePayment","loadHostedFields","hostedFields","_braintreeScriptLoader","_dataCollectors","initialize","clientToken","_clientToken","getClient","PaymentNotInitialized","_client","authorization","getPaypal","_paypal","all","getPaypalCheckout","renderButtonCallback","_paypalCheckout","_paypalcheckoutInstance","instance","loadPayPalSDK","get3DS","_3ds","version","getDataCollector","cacheKey","cached","kount","deviceData","getVisaCheckout","_visaCheckout","getGooglePaymentComponent","_googlePay","createHostedFields","_teardown","default","EmbeddedContentEventType","StyleConfigured","isBillingAddressLike","format","split","trimmedMonth","month","trimmedYear","year","toObject","number","card","maxLength","max","creditCardType","info","lengths","unformattedValue","unformat","gaps","gapIndex","output","replace","couponTypes","mapToInternalCoupon","displayName","couponType","appendWww","NotInitializedErrorType","CheckoutButtonNotInitialized","CustomerNotInitialized","ShippingNotInitialized","SpamProtectionNotInitialized","joinOrMergeIncludes","baseIncludes","includeDictionaryOrList","includesDictionary","deletions","pickBy","on","additions","difference","omitDeep","predicate","transform","omitBy","_checkoutRequestSender","_configActionCreator","_formFieldsActionCreator","loadCheckout","merge","loadConfig","loadFormFields","defer","catchError","loadDefaultCheckout","state","getState","getContextConfig","checkoutId","updateCheckout","getCheckout","loadCurrentCheckout","_consignmentRequestSender","unassignItemsByAddress","consignment","existingConsignment","getConsignmentByAddress","shippingAddress","_removeLineItems","getCart","updateConsignment","deleteConsignment","assignItemsByAddress","_createOrUpdateConsignment","_addLineItems","selectShippingOption","getConsignments","consignmentUpdateBody","shippingOptionId","consignmentMeta","loadShippingOptions","params","include","AvailableShippingOptions","updateAddress","_getUpdateAddressRequestBody","createConsignments","consignmentId","updateShippingOption","_isUpdateConsignmentRequest","customItems","itemId","_hydrateLineItems","lineItemIds","sharedItem","existingItem","request","DEFAULT_INCLUDES","post","put","delete","getCallbackUrl","window","location","_cardExpiryFormatter","_cardNumberFormatter","checkoutState","getBillingAddress","getCustomer","getOrder","paymentMethod","paymentMethods","getPaymentMethod","gatewayId","getShippingAddress","shippingOption","getShippingOption","storeConfig","getStoreConfig","contextConfig","instrumentMeta","instruments","getInstrumentsMeta","paymentMeta","getPaymentMethodsMeta","getOrderMeta","internalCustomer","authToken","paymentData","getPaymentToken","vaultAccessToken","additionalAction","_transformPaymentMethod","quoteMeta","geoCountryCode","pick","storeProfile","transformWithHostedFormData","values","data","nonce","paymentMethodMeta","selectedShippingOption","_transformHostedInputValues","gateway","initializationData","ccCvv","cardCodeVerification","ccNumber","cardNumberVerification","hostedFormNonce","cardCode","ccExpiry","cardExpiry","ccName","cardName","cardNumber","submitPayment","_transformResponse","initializeOffsitePayment","statusText","isPrivate","joinErrors","_factoryMethods","register","title","factoryMethod","createError","_getType","_isStorefrontErrorResponseBody","_isInternalErrorResponseBody","internalType","last","errorResponse","storefrontErrorResponse","internalErrorResponse","clearErrorReducer","currentValue","newValue","objectSet","DEFAULT_STATE","statuses","billingAddressReducer","combineReducers","dataReducer","composeReducers","errorsReducer","statusesReducer","O","UpdateSubscriptionsRequested","UpdateSubscriptionsSucceeded","UpdateSubscriptionsFailed","arrayReplace","currentArray","newArray","a","b","sameAsCurrentCount","sameAsNewCount","countSameAsReplaced","replacedValue","newItem","currentItem","matchObject","objectMerge","currentObject","newObject","cartReducer","DEFAULT_DATA_STATE","initializedContainers","DEFAULT_ERROR_STATE","DEFAULT_STATUS_STATE","checkoutButtonReducer","reducer","containerId","configReducer","couponReducer","giftCertificateReducer","customerReducer","customerStrategyReducer","isInitialized","initializeError","initializeMethodId","deinitializeError","deinitializeMethodId","signInError","signInMethodId","signOutError","signOutMethodId","widgetInteractionError","widgetInteractionMethodId","isInitializing","isDeinitializing","isSigningIn","isSigningOut","isWidgetInteracting","formFieldsReducer","countryReducer","orderReducer","metaReducer","omit","paymentReducer","paymentMethodReducer","array","defaultPredicate","findIndex","methodA","methodB","loadMethodId","loadMethodError","isLoadingMethod","paymentStrategyReducer","executeError","executeMethodId","finalizeError","finalizeMethodId","isExecuting","isFinalizing","instrumentReducer","vaultedInstruments","deleteError","failedInstrument","isDeleting","deletingInstrument","remoteCheckoutReducer","billing","updateShippingOptionError","updateError","isUpdating","isUpdatingShippingOption","consignmentReducer","shippingCountryReducer","shippingStrategyReducer","updateAddressError","updateAddressMethodId","selectOptionError","selectOptionMethodId","isUpdatingAddress","isSelectingOption","signInEmailReducer","storeCreditReducer","subscriptionsReducer","checkoutReducer","guard","errorFactory","createFreezeProxy","trap","proxy","iteratee","getPrototypeOf","charAt","deepFreeze","provider","barclays","braintreepaypal","authorizenet","elavon","checkoutcom","stripe","cybersource","cybersourcev2","converge","bluesnapv2","orbital","paymetric","bolt","digitalriver","normalize","identity","createInternalCheckoutSelectorsFactory","getBillingAddressOrThrow","getUpdateError","getContinueAsGuestError","getLoadError","isContinuingAsGuest","isLoading","getInitializeError","getDeinitializeError","getCoupons","getRemoveError","getApplyError","isApplying","isRemoving","getCustomerOrThrow","getCreateAccountError","isCreatingCustomerAccount","getCreateAddressError","isCreatingCustomerAddress","getInternalPayment","getGatewayPayment","getHostedPayment","getPaymentId","getPaymentStatus","getPaymentRedirectUrl","isPaymentDataRequired","isPaymentDataSubmitted","getEmail","getSendError","isSending","createBillingAddressSelector","continueAsGuestError","loadError","memoizeOne","createCartSelector","getCartOrThrow","createCheckoutButtonSelector","createConfigSelector","getConfig","getFlashMessages","filterType","flashMessages","formState","formFields","getStoreConfigOrThrow","getExternalSource","externalSource","getVariantIdentificationToken","variantIdentificationToken","createCountrySelector","getCountries","createCouponSelector","removeCouponError","applyCouponError","isApplyingCoupon","isRemovingCoupon","createCustomerSelector","isCreating","createAddressError","isCreatingAddress","createCustomerStrategySelector","getSignInError","getSignOutError","getWidgetInteractionError","createGiftCertificateSelector","getGiftCertificates","removeGiftCertificateError","applyGiftCertificateError","isApplyingGiftCertificate","isRemovingGiftCertificate","createInstrumentSelector","getInstrumentsByPaymentMethod","paymentMethodKey","currentMethod","getCardInstrument","cards","bigpayToken","isMatch","getInstruments","flatMap","supportedProvider","getDeleteError","createFormSelector","getShippingAddressFields","countries","selectedCountry","field","getBillingAddressFields","getCustomerAccountFields","customerAccount","processField","label","fieldType","itemtype","subdivisions","requiresState","hasPostalCodes","createFormSelectorFactory","createPaymentMethodSelector","getPaymentMethods","getPaymentMethodOrThrow","getLoadMethodError","createPaymentStrategySelector","getExecuteError","getFinalizeError","getWidgetInteractingError","createRemoteCheckoutSelector","createShippingAddressSelector","createShippingCountrySelector","getShippingCountries","createShippingStrategySelector","getUpdateAddressError","getSelectOptionError","createConsignmentSelector","getConsignmentById","addressA","addressB","getCreateError","getLoadShippingOptionsError","loadShippingOptionsError","getUnassignedItems","assignedLineItemIds","itemIds","getItemAssignmentError","getUpdateShippingOptionError","isLoadingShippingOptions","isAssigningItems","createConsignmentSelectorFactory","createCheckoutSelector","getCheckoutOrThrow","getOutstandingBalance","useStoreCredit","outstandingBalance","isExecutingSpamCheck","createOrderSelector","getOrderOrThrow","currentPayment","paymentId","createPaymentSelector","internalPayment","redirectUrl","createStoreCreditSelector","applyError","createSubscriptionsSelector","createSignInEmailSelector","sendError","checkoutButton","customerStrategies","form","paymentStrategies","remoteCheckout","shippingCountries","shippingStrategies","signInEmail","selectors","shouldWarnMutation","createCheckoutStore","initialState","requestErrorFactory","factory","actionTransformer","action$","every","createInternalCheckoutSelectors","createDataStore","stateTransformer","CheckoutIncludes","PhysicalItemsCategoryNames","DigitalItemsCategoryNames","mapToInternalGiftCertificate","targetOrigin","_targetWindow","_targetOrigin","event","targetWindow","fromEvent","successType","errorType","take","postMessage","setTarget","sourceOrigin","_sourceOrigins","_isListening","_listeners","listen","addEventListener","_handleMessage","stopListen","removeEventListener","addListener","listener","listeners","removeListener","trigger","selectorDecorator","resolver","memoizedMethod","cachedValue","getUsedCount","cache","getKey","_checkoutButton","getInitializeButtonError","getDeinitializeButtonError","isInitializingButton","isDeinitializingButton","createCheckoutButtonSelectors","CheckoutButtonMethodType","C","_store","_buttonStrategyActionCreator","_state","filters","initializeButton","containerIds","selector","idPrefix","containers","querySelectorAll","container","u","uniqueId","queueId","dispatch","deinitializeButton","deinitialize","_registry","_paymentMethodActionCreator","AMAZON_PAY_V2","GOOGLEPAY_ADYENV2","GOOGLEPAY_AUTHORIZENET","GOOGLEPAY_BRAINTREE","GOOGLEPAY_CHECKOUTCOM","GOOGLEPAY_CYBERSOURCEV2","GOOGLEPAY_ORBITAL","GOOGLEPAY_STRIPE","PAYPALEXPRESS","PAYPALCOMMERCE","_checkoutActionCreator","_amazonPayV2PaymentProcessor","amazonpay","_createSignInButton","_walletButton","parentNode","removeChild","getElementById","_getAmazonPayV2ButtonOptions","amazonButtonOptions","createButton","shopPath","merchantId","testMode","checkoutLanguage","ledgerCurrency","checkoutSessionMethod","extractAmazonCheckoutSessionId","createCheckoutSession","sandbox","productType","placement","_braintreeSDKCreator","_formPoster","_offerCredit","_renderButtonsData","paypalOptions","braintreepaypalcredit","_paymentMethod","storeState","shopperCurrency","paypalCheckoutInstance","renderButtons","updatedPaypalOptions","FUNDING_SOURCES","fundingKey","FUNDING","skipCreditSource","allowCredit","toLowerCase","_validateHeight","button","Buttons","env","fundingSource","commit","style","shape","createOrder","_setupPayment","onPaymentError","onApprove","_tokenizePayment","shouldProcessPayment","onAuthorizeError","isEligible","render","height","onError","createPayment","flow","enableShippingAddress","shippingAddressEditable","shippingAddressOverride","_mapToBraintreeAddress","offerCredit","tokenizePayment","postForm","payment_type","device_data","shipping_address","JSON","stringify","_mapToLegacyShippingAddress","billing_address","_mapToLegacyBillingAddress","details","recipientName","first_name","last_name","phone_number","address_line_1","line1","address_line_2","line2","country_code","postal_code","_googlePayPaymentProcessor","googlePayOptions","_getGooglePayOptions","_methodId","_getMethodId","buttonOptions","buttonType","buttonColor","googlePayButton","_handleWalletButtonClick","appendChild","googlepayadyenv2","googlepayauthorizenet","googlepaybraintree","googlepaycheckoutcom","googlepaycybersourcev2","googlepayorbital","googlepaystripe","preventDefault","hasPhysicalItems","displayWallet","handleSuccess","updateShippingAddress","_onPaymentSelectComplete","_masterpassScriptLoader","masterpassScriptLoaderParams","useMasterpassSrc","isMasterpassSrcEnabled","language","storeLanguage","load","_masterpassClient","masterpass","_signInButton","buttonContainer","subdomain","src","_createMasterpassPayload","allowedCardTypes","cartAmount","cartId","_paypalScriptLoader","_host","clientId","allowedSources","disallowedSources","CREDIT","Button","funding","allowed","disallowed","size","actions","onAuthorize","_onError","paymentID","payerID","payerId","payerInfo","payer","payer_info","_paypalCommercePaymentProcessor","buttonParams","onClick","_handleClickButtonProvider","paypalCommerce","messagingContainer","isMessagesAvailable","_getParamsScript","renderMessages","_isCredit","orderID","order_id","intent","isPayPalCreditAvailable","attributionId","disableFunding","components","createCheckoutButtonInitializer","host","requestSender","createRequestSender","formPoster","createFormPoster","registry","scriptLoader","getScriptLoader","checkoutActionCreator","paypalCommercePaymentProcessor","G","NotEmbeddableErrorType","_namespace","getItem","rawValue","withNamespace","parse","removeItem","getItemOnce","setItem","MissingContainer","MissingContent","UnknownError","_iframeCreator","_messageListener","_messagePoster","_loadingIndicator","_storage","_location","_options","_isAttached","onComplete","onLoad","onFrameLoad","onSignOut","_configureStyles","attach","show","_allowCookie","_attemptLogin","createFrame","_iframe","iframe","hide","_retryAllowCookie","detach","iFrameResizer","close","contentWindow","styles","now","encodeURIComponent","visibility","lastAttempt","Number","border","display","width","allowPaymentRequest","_toResizableFrame","timeoutInterval","setTimeout","handleMessage","contentId","iframes","scrolling","sizeWidth","heightCalculationMethod","clearTimeout","STORAGE_PREFIX","embedCheckout","loadingIndicator","handleFrameLoadedEvent","hasAttribute","setAttribute","isCustomError","_untargetedMessagePoster","_messageHandlers","postComplete","_postMessage","postError","_transformError","postFrameError","untargeted","postFrameLoaded","postLoaded","postSignedOut","receiveStyles","handler","_notifyMessageHandlers","createEmbeddedCheckoutMessenger","parentWindow","parentOrigin","isTerminalCacheKeyMap","_lastId","_map","maps","_usedMaps","maxSize","onExpire","noop","_resolveMap","parentMap","usedCount","_generateMap","_removeLeastUsedMap","isMatched","mapIndex","unshift","terminalMap","recentlyUsedMap","_removeMap","mapFromPaymentErrorResponse","SubscriptionsActionType","_configRequestSender","updateSubscriptions","_formFieldsRequestSender","loadFields","DEFAULT_PARAMS","createAddress","_factories","_instances","defaultToken","cacheToken","_getInstance","_hasFactory","_hasInstance","hasShippingAddress","_getGooglePayPaymentDataRequest","parseResponse","cardType","lastFour","currencyCode","gatewayMerchantId","merchantName","apiVersion","apiVersionMinor","merchantInfo","authJwt","allowedPaymentMethods","parameters","allowedAuthMethods","allowedCardNetworks","billingAddressRequired","billingAddressParameters","phoneNumberRequired","tokenizationSpecification","transactionInfo","totalPriceStatus","totalPrice","toFixed","emailRequired","shippingAddressRequired","shippingAddressParameters","sourceUrl","baseRequest","_getGooglePaymentDataRequest","btoa","supportedCards","paymentGatewaySpecification","_getPaymentGatewaySpecification","cardPaymentMethod","_getCardPaymentMethod","_googlePaymentInstance","googleBraintreePaymentInstance","_createGooglePayPayload","paymentMethodData","tokenizationData","androidPayCards","lastTwo","binData","platformToken","googlePayBraintreePaymentDataRequest","googleMerchantName","googleMerchantId","cardRequirements","billingAddressFormat","_mapGooglePayBraintreeDataRequestToGooglePayDataRequestV2","createPaymentDataRequest","googlePayBraintreeDataRequestV1","paymentMethodTokenizationParameters","_publishableKey","_testMode","checkoutcomkey","_mapGooglePayCheckoutcomDataRequestToGooglePayDataRequestV2","signature","protocolVersion","signedMessage","_convertToken","cardNetwork","cardDetails","_requestCheckoutcomTokenize","token_data","checkoutcomToken","checkoutcomKey","credentials","Authorization","last4","stripeVersion","stripePublishableKey","stripeConnectedAccount","fieldErrors","scriptSrc","setupPayment","isCredit","isCheckout","isCreditCard","isAPM","getOrderStatus","DEFAULT_STYLES","color","backgroundColor","ROTATION_ANIMATION","_styles","_defineAnimation","_container","_buildContainer","_indicator","_buildIndicator","parentId","opacity","handleTransitionEnd","bottom","left","position","right","top","transition","indicator","borderRadius","borderColor","margin","transformStyle","animation","head","sheet","CSSStyleSheet","insertRule","iframeResizer","setupContentWindowForIframeResizer","clearError","getEnvironment","process","isEnabled","_console","log","_logToConsole","messages","debug","logger","getDefaultLogger","_couponRequestSender","applyCoupon","removeCoupon","couponCode","_giftCertificateRequestSender","applyGiftCertificate","removeGiftCertificate","giftCertificateCode","isSpamProtectionExecuteSucceededAction","succeededAction","_customerRequestSender","_spamProtectionActionCreator","createCustomer","isStorefrontSpamProtectionEnabled","checkoutSettings","createAccount","switchMap","customerAddress","signInCustomer","signOutCustomer","_strategyRegistry","signIn","signOut","widgetInteraction","loadWidget","onPaymentReady","region","_configureWidget","onLoginReady","amazon","Login","setClientId","setUseCookie","onAmazonLoginReady","OffAmazonPayments","onAmazonPaymentsReady","createInitOptions","settings","locale","collectShipping","paymentRequest","String","braintreeVisaCheckout","tokenize","tokenizedPayload","_toVisaCheckoutAddress","_postForm","cardInformation","userEmail","userData","card_information","_getCardInformation","_getAddress","phoneNumber","streetAddress","extendedAddress","locality","createBraintreeVisaCheckoutPaymentProcessor","braintreeScriptLoader","braintreeSDKCreator","V","JPMC","initializeBilling","methodName","initializeShipping","initializePayment","loadSettings","generateToken","trackAuthorizationEvent","_remoteCheckoutRequestSender","_googleRecaptcha","spamProtectionElementId","spamProtectionElement","recaptchaSitekey","googleRecaptchaSitekey","verifyCheckoutSpamProtection","validate","execute","callback","MutationObserver","googleRecaptchaScriptLoader","mutationObserverFactory","_memoized","recaptcha","sitekey","event$","_widgetId","getResponse","reset","_event$","_recaptcha","element","querySelector","retryWhen","delay","TIMEOUT","_watchRecaptchaChallengeWindow","iframeContainer","parentElement","observe","attributeFilter","_loadPromise","_loadScript","grecaptcha","createSpamProtection","MutationObserverFactory","_remoteCheckoutActionCreator","amazonOptions","useAmazonAddressBook","_handleAuthorization","authorize","popup","scope","tokenPrefix","signout","_customerStrategyActionCreator","_braintreeVisaCheckoutPaymentProcessor","_visaCheckoutScriptLoader","_buttonClassName","visaCheckoutOptions","initOptions","signInButton","init","paymentSuccessPayload","_paymentInstrumentSelected","buttonClass","_insertVisaCheckoutButton","visaCheckoutButton","flexDirection","className","innerHTML","_chasePayScriptLoader","chasePayOptions","digitalSessionId","ChasePay","configure","isChasePayUp","insertButtons","EventType","START_CHECKOUT","sessionId","startCheckout","COMPLETE_CHECKOUT","requestId","merchantRequestId","_setExternalCheckoutData","_reloadPage","sessionToken","sendRequest","fromChasePay","_customerActionCreator","masterpassOptions","suppressShippingAddress","Masterpass","_countryRequestSender","loadCountries","_config","loadOrder","submitOrder","checkoutVariant","isNil","finalizeOrder","_orderRequestSender","_checkoutValidator","loadOrderPayments","loadCurrentOrder","_getCurrentOrderId","shouldExecuteSpamCheck","_mapToOrderRequestBody","customerMessage","_orderActionCreator","strategy","getByMethod","finalize","_loadOrderPaymentsIfNeeded","cartA","cartB","_normalize","sort","itemA","itemB","localeCompare","giftWrapping","previous","updated","comparator","_compareCoupons","_compareGiftCertificates","_getComparableCheckout","couponsA","couponsB","giftCertificatesA","giftCertificatesB","promise","cancellable","cancel","race","_mutationObserver","ensurePresence","targets","mutationsList","mutation","removedNodes","node","contains","childList","subtree","disconnect","handle","_isPaymentHumanVerificationRequest","_initialize","additional_action_required","human_verification_token","cardingProtectionElement","_type","_containerId","_placeholder","_accessibilityLabel","_eventPoster","_eventListener","_detachmentObserver","_cardInstrument","overflow","getType","accessibilityLabel","cardInstrument","fontUrls","_getFontUrls","placeholder","submitForm","fields","_isSubmitErrorEvent","validateForm","isValid","links","fontFamily","family","_fields","_payloadTransformer","_eventCallbacks","_paymentHumanVerificationHandler","_handleEnter","onBlur","onCardTypeChange","onFocus","onValidate","_cardType","_bin","bin","getBin","getCardType","_getFirstField","otherFields","without","submit","fieldOptions","_getCardInstrument","createScriptLoader","_storeCreditRequestSender","applyStoreCredit","removeStoreCredit","_paymentRequestSender","_paymentRequestTransformer","shouldSaveInstrument","shouldSetAsDefaultInstrument","vault_payment_instrument","set_as_default_stored_instrument","isPPSDKPaymentMethod","initializationStrategy","checkoutcomStrategies","credit_card","sepa","ideal","fawry","_getToken","features","_hasFactoryForMethod","_isLegacyMethod","paymentSettings","clientSidePaymentProviders","saveExternalId","externalId","getBrowserInfo","color_depth","screen","colorDepth","java_enabled","navigator","javaEnabled","userLanguage","screen_height","screen_width","time_zone_offset","getTimezoneOffset","AdyenActionType","AdyenComponentType","AdyenPaymentMethodType","HTTPMethod","ResultCode","invalidFields","isCardState","encryptedSecurityCode","encryptedExpiryMonth","ThreeDS2Fingerprint","ThreeDS2Challenge","Redirect","QRCode","Voucher","SecuredFields","ACH","AliPay","Bancontact","CreditCard","Klarna","KlarnaPayNow","KlarnaAccount","iDEAL","GiroPay","GooglePay","SEPA","Sofort","Vipps","WeChatPayQR","POST","ChallengeShopper","IdentifyShopper","OrderIncludes","_paymentActionCreator","adyenv2","_paymentInitializeOptions","clientSideAuthentication","originKey","clientKey","environment","paymentMethodsResponse","_adyenClient","_mountPaymentComponent","_paymentComponent","_mountCardVerificationComponent","_cardVerificationComponent","componentState","_componentState","encryptedCardNumber","credit_card_number_confirmation","expiry_month","expiry_year","verification_value","browser_info","credit_card_token","_processAdditionalAction","unmount","_getAdyenClient","_getPaymentInitializeOptions","_getThreeDS2ChallengeWidgetSize","threeDS2Options","_handleAction","threeDS2ContainerId","additionalActionOptions","onBeforeLoad","adyenAction","additionalActionComponent","createFromAction","onAdditionalDetails","additionalActionState","paymentPayload","paymentMethodType","mount","_mapAdyenPlaceholderData","holderName","street","houseNumberOrName","cardVerificationComponent","adyenClient","cardVerificationContainerId","onChange","_updateComponentState","paymentComponent","hasVaultedInstruments","provider_data","_stylesheetLoader","configuration","loadStylesheet","AdyenCheckout","DigitalItemsCategories","PhysicalItemsCategories","_affirmScriptLoader","publicKey","_affirm","affirm","requestOptions","_getCheckoutInformation","open","onFail","failObject","reason","onSuccess","successObject","ui","checkout_token","_getBillingAddress","merchant","user_confirmation_url","checkoutLink","user_cancel_url","user_confirmation_url_action","_getShippingAddress","_getItems","metadata","shipping_type","_getShippingType","platform_type","platform_version","platform_affirm","discounts","_getDiscounts","shipping_amount","tax_amount","total","first","full","zipcode","display_name","unit_price","qty","item_image_url","item_url","categories","_getCategories","line","discount_amount","discount_display_name","DISCOUNTED_AMOUNT","apikey","scriptURI","_getScriptURI","g","h","k","getElementsByTagName","f","a1","c1","a2","c2","insertBefore","public_api_key","script","_storeCreditActionCreator","_afterpayScriptLoader","storeCountryName","storeCountry","_mapCountryToISO2","_afterpaySdk","_redirectToAfterpay","countryName","redirect","AfterPay","isInternalAddressEqual","ignoredKeys","mapFromInternalAddress","BoltDeveloperMode","_billingAddressActionCreator","_isPaymentMethodSelected","_walletOptions","_createWallet","referenceId","_getOrderReferenceId","sellerId","_getMerchantId","is3dsEnabled","_processPaymentWith3ds","_getOrderReferenceIdFromInitializationData","orderReferenceId","walletOptions","amazonOrderReferenceId","design","designMode","onPaymentSelect","_synchronizeBillingAddress","orderReference","onReady","_updateOrderReference","widget","Widgets","Wallet","remoteAddress","internalBillingAddress","getAmazonOrderReferenceId","initConfirmationFlow","confirmationFlow","success","_paymentStrategyActionCreator","paymentToken","buttonId","editButtonId","_bindEditButton","orderRequest","redirect_url","click","changeAction","clone","cloneNode","replaceChild","_showLoadingSpinner","bindButton","_createContainer","_hostedFormFactory","_isHostedPaymentFormEnabled","_shouldRenderHostedForm","_executeWithHostedForm","_executeWithoutHostedForm","_isHostedFieldAvailable","formOptions","creditCard","_hostedForm","isHostedFormEnabled","orderActionCreator","paymentActionCreator","hostedFormFactory","_threeDSecureFlow","prepare","start","_initializeOptions","frame","_createIframe","_boltScriptLoader","_useBoltClient","useBigCommerceCheckout","publishableKey","developerConfig","_boltClient","_executeWithBoltClient","_executeWithBoltCheckout","boltClient","callbacks","transaction","reference","SandboxMode","StagingMode","DevelopmentMode","BraintreeFormFieldType","developerModeParams","getDomainURL","BoltCheckout","developerMode","developerDomain","_createElements","closeElement","mainElement","_element","_closeElement","_mainElement","_registerClick","_unregisterClick","_removeAfterTransition","classLayout","classClose","classOverlayText","background","transitionDuration","hasCloseButton","innerHtml","overlayText","addClassLayout","innerText","_addEventListener","_removeEventListener","handleTransition","propertyName","CardCode","CardCodeVerification","CardExpiry","CardName","CardNumber","CardNumberVerification","BraintreeHostedFormType","_handleBlur","_applyStyles","_handleFocus","focus","_input","outline","padding","getValue","off","isBraintreeFormFieldsMap","StoredCardVerification","CardinalInitializationType","CardinalEventType","CardinalValidatedAction","CardinalPaymentType","CardinalTriggerEvents","CardinalPaymentBrand","CardinalSignatureVerification","_formOptions","_mapFieldType","emittedBy","_handleNameBlur","_handleNameFocus","_handleCardTypeChange","_handleInputSubmitRequest","onEnter","_handleValidityChange","_mapValidationErrors","_mapFieldOptions","isEmpty","_mapStyleOptions","_cardFields","_cardNameField","_mapBillingAddress","cardholderName","_mapTokenizeError","tokenizeForStoredCardVerification","expirationDate","cvv","mapStyles","fontSize","fontWeight","input","fieldKey","_createInvalidError","_createRequiredError","invalidFieldKeys","_braintreeHostedForm","_overlay","_threeDSecureOptions","preloadPaypal","tokenizeCard","requestData","_mapToCreditCard","verifyCard","_present3DSChallenge","newWindowFlow","supportsPopups","focusWindow","useraction","getSessionId","appendSessionId","processedPayment","initializeHostedForm","deinitializeHostedForm","tokenizeHostedForm","tokenizeHostedFormForStoredCardVerification","verifyCardWithHostedForm","addFrame","removeFrame","cancelVerifyCard","verification","onLookupComplete","_data","countryCodeAlpha2","endpoint","_braintreePaymentProcessor","_isHostedFormInitialized","_is3dsEnabled","_deviceSessionId","_handleError","_prepareHostedPaymentData","_preparePaymentData","commonPaymentData","_isSubmittingWithStoredCard","_isStoringNewCard","_shouldPerform3DSVerification","_mapToNonceInstrument","_mapToVaultedInstrumentWithNonceVerification","_credit","braintreeOptions","_loadPaypal","isVaultingEnabled","_formattedPayload","vaultPaymentInstrument","device_info","paypal_account","visaInitOptions","_cardinalClient","hostedForm","xid","three_ds_result","payer_auth_request","_getBin","runBinProcess","_submitPayment","threeDsResult","getThreeDSecureData","_getOrderData","iin","CardinalSignatureValidationErrors","Init","Complete","Confirm","SetupCompleted","Success","NoAction","Failure","CCA","Paypal","VisaCheckout","ApplePay","DiscoverWallet","BinProcess","Yes","No","ChasePayEventType","_provider","_configurationToken","_sdk","_getClientSDK","ActionCode","ErrorNumber","ErrorDescription","setup","jwt","binNumber","Status","threeDSecureData","orderData","Payment","ExtendedData","SignatureVerification","continueObject","AcsUrl","acs_url","Payload","merchant_data","partialOrder","_mapToPartialOrder","continue","transactionId","consumer","BillingAddress","_mapToCardinalAddress","Account","_mapToCardinalAccount","Email1","ShippingAddress","Consumer","OrderDetails","OrderNumber","Amount","CurrencyCode","OrderChannel","TransactionId","AccountNumber","ExpirationMonth","ExpirationYear","NameOnAccount","cardinalAddress","FirstName","LastName","Address1","City","State","PostalCode","CountryCode","Address2","Phone1","Cardinal","_getClientToken","StartCheckout","CompleteCheckout","CancelCheckout","AdditionalActionType","_wepayRiskClient","_walletEvent$","chasepay","walletButton","_configureWallet","_chasePayClient","_getPayment","_displayWallet","_createOrder","logoContainer","insertBrandings","onCancel","_setSessionToken","showLoadingAnimation","getRiskToken","paymentCryptogram","cryptogramId","eci","reqTokenId","expDate","substr","accountNum","accountMask","extraData","riskToken","OffsiteRedirect","AuthenticationSourceStatus","_processResponse","additionalActionRequired","_performRedirect","DOCUMENT_SUPPORTED_APMS","_createFormattedPayload","ccDocument","iban","bic","customerMobile","customerEmail","_clearpayScriptLoader","_clearpaySdk","_isCountrySupported","_redirectToClearpay","_getScriptUrl","PaReq","TermUrl","callback_url","MD","authentication_not_required","failed","MolliePaymentMethodType","_digitalRiverScriptLoader","_digitalRiverInitializeOptions","_getDigitalRiverInitializeOptions","_digitalRiverJS","_loadWidget","_digitalRiverCheckoutData","_submitVaultedInstrument","_isAuthenticateSourceAction","_authenticateSource","_loadSuccessResponse","readyForStorage","_getDigitalRiverJs","_getErrorMessage","_onSuccessResponse","_submitFormEvent","browserInfo","reusable","_onReadyResponse","onRenderButton","paymentMethodConfiguration","onSubmitForm","digitalRiverConfiguration","showSavePaymentAgreement","descriptiveError","createDropin","_digitalRiverDropComponent","authenticateSource","sourceId","source_id","sourceClientSecret","source_client_secret","authenticateSourceResponse","confirm","DigitalRiver","_isAdditionalActionRequired","_googlePayAdyenV2PaymentProcessor","_googlePayOptions","_buttonClickEventHandler","_handleButtonClickedEvent","processAdditionalAction","requireRenewNonce","_encodeNonce","googlePayToken","statusCode","supportedCountries","supportedCountriesRequiringStates","_klarnaScriptLoader","_klarnaCredit","klarnaCredit","_authorize","authorizationToken","klarna","client_token","_getUpdateSessionData","_mapToKlarnaAddress","_needsStateCode","klarnaAddress","street_address","given_name","family_name","street_address2","updateSessionData","res","approved","show_form","Credit","_klarnav2ScriptLoader","_klarnaPayments","klarnaPayments","_loadPaymentsWidget","klarnav2","_updateOrder","payment_method_category","Payments","creditcard","PaypalCommerceFormFieldType","PaypalCommerceHostedFormType","_mollieScriptLoader","mollie","shouldShowTSVHostedForm","_mountCardVerificationfields","_loadMollieJs","_mollieClient","_mountElements","executeWithVaulted","executeWithCC","executeWithAPM","removeMollieComponents","_getMollieClient","createToken","issuer","bigpayBaseUrl","_getInitializeOptions","mollieComponents","each","controllers","testmode","cardNumberId","cardCvcId","cardExpiryId","cardHolderId","mollieClient","_cardHolderElement","createComponent","_cardNumberElement","_verificationCodeElement","_expiryDateElement","_isMollieWindow","Mollie","monerisOptions","profileId","frameref","_monerisURL","_windowEventListener","_handleMonerisResponse","monerisQueryParams","pmmsg","display_labels","enable_exp","enable_cvd","css_body","cssBody","css_textbox","cssTextbox","css_textbox_pan","cssTextboxPan","css_textbox_exp","cssTextboxExpiry","css_textbox_cvd","csstexboxCvd","pan_label","creditCardLabel","exp_label","expiryDateLabel","cvd_label","cvdLabel","queryString","monerisResponse","responseCode","errorMessage","dataKey","orderPayload","_shouldSubmitFullPayload","_useRedirectFlow","paypalexpress","useRedirectFlow","_isInContextEnabled","_paypalSdk","closeFlow","_isAcknowledgedOrFinalized","initXO","startFlow","_paypalCommerceHostedForm","paypalcommerce","_isPaypalCommerceOptionsPayments","paramsScript","_getOptionsScript","PaymentProcessorType","_isPaypalCommerceFormFieldsMap","events","blur","cardTypeChange","validityChange","inputSubmitRequest","renderHostedFields","contingencies","submitHostedFields","liabilityShift","getHostedFieldsValidationState","updatedStyles","kebabCase","_paypalCommerceFundingKeyResolver","_paypalCommerceRequestSender","_pollingInterval","_pollingTimer","buttonStyle","shouldRenderFields","_isAPM","_orderId","apmFieldsContainer","apmFieldsStyles","loadingIndicatorContainerId","_deinitializePollingTimer","_initializePollingMechanism","renderFields","paramsForProvider","method_id","getOrderId","_reinitializeButtons","apmMehodId","isAnyContinue","overSome","isString","isUndefined","_continueHandler","failedResponse","handleFailed","createStepHandler","getPPSDKMethod","_paymentProcessorRegistry","_paymentResumer","paymentProcessor","resume","_paymentProcessor","_stepHandler","payment_method_id","NONE","UNSUPPORTED","CardBrand","DigitalWalletType","getToken","cond","constant","stubTrue","createPaymentProcessorRegistry","stepHandler","NonePaymentProcessor","_storefrontPaymentRequestSender","_prepareForReferredRegistration","americanExpress","discover","discoverDiners","JCB","masterCard","unionPay","unknown","visa","squareGift","applePay","none","IconStyle","StripeElementType","StripePaymentMethodType","_syncPaymentMethod","_paymentForm","createSquareForm","_getFormOptions","build","_getNonceInstrument","_getCountryCode","toUpperCase","_deferredRequestNonce","requestCardNonce","deferred","squareOptions","_squareOptions","cardNonceResponseReceived","cardData","billingContact","shippingContact","digital_wallet_type","_handleWalletNonceResponse","_handleCardNonceResponse","createPaymentRequest","_paymentRequestPayload","methodsSupported","_showPaymentMethods","methods","paymentFormLoaded","_setPostalCode","unsupportedBrowserDetected","requestShippingAddress","requestBillingInfo","storeName","pending","setPostalCode","masterpassBtn","elementId","SqPaymentForm","isIndividualCardElementOptions","individualCardElementOptions","cardNumberElementOptions","cardCvcElementOptions","cardExpiryElementOptions","Solid","Alipay","CardCvc","Sepa","APM_REDIRECT","_stripeScriptLoader","_locale","useIndividualCardFields","_useIndividualCardFields","_loadStripeJs","_stripeV3Client","_mountElement","_stripeElement","shouldSubmitOrderBeforeLoadingAPM","_confirmStripePayment","paymentIntent","stripeError","_buildPaymentPayload","_handleEmptyPaymentIntentError","_unmountElement","isAdditionalActionError","isThreeDSecureRequiredError","clientSecret","_getStripeJs","handleCardAction","confirmAlipayPayment","return_url","handleActions","_getStripeCardElements","_getStripeElement","billingDetails","_mapStripeBillingDetails","createPaymentMethod","billing_details","_mapStripePaymentData","confirmIdealPayment","confirmSepaDebitPayment","_getStripeInitializeOptions","stripev3","_stripeCardElements","stripeElement","stripeElementType","_stripeElements","elements","cardNumberElement","getElement","cardExpiryElement","cardCvcElement","_mapStripeAddress","trim","zipCodeElementOptions","arg2","payment_method","_mapStripeShippingAddress","setup_future_usage","stripeAccount","Stripe","betas","_riskClient","WePay","risk","generate_risk_token","get_risk_token","payloadWithToken","_zipScriptLoader","zip","_zipClient","zipClient","_redirectFlowIsTrue","deferredFlowV2Enabled","onCheckout","openModal","redirectFlowV2Enabled","Zip","ProjectionActionType","_instrumentRequestSender","loadInstruments","session","_getSessionContext","_getCurrentAccessToken","_getValidAccessToken","currentToken","deleteInstrument","_isValidVaultAccessToken","date","valueOf","vaultAccessExpiry","newDate","setMinutes","getMinutes","getVaultAccessToken","storeId","isTransactional","transformResponse","_transformVaultedInstruments","vaulted_instruments","transformErrorResponse","transformVaultAccessResponse","expires_at","_isPayPalInstrument","defaultInstrument","default_instrument","external_id","trustedShippingAddress","trusted_shipping_address","_isBankInstrument","accountNumber","account_number","last_4","expiryMonth","expiryYear","method_type","_transformer","requestContext","_loadInstrumentsWithAddress","_loadInstruments","deleteShopperInstrument","loadInstrumentsWithAddress","_shippingCountryRequestSender","selectOption","mergedOptions","_consignmentActionCreator","_createAddressBook","updateAddressRequestBody","optionId","AddressBook","onAddressSelect","_synchronizeShippingAddress","_shippingStrategyActionCreator","editAddressButtonId","sendSignInEmail","emailRequest","Synchronize","cloneDeep","cloneDeepSafe","cloneResult","createShallowEqualSelector","createSelectorCreator","defaultMemoize","createCheckoutSelectorsFactory","getShippingOptions","getSelectedShippingOption","getBillingCountries","getSelectedPaymentMethod","getSignInEmail","getError","getSelectShippingOptionError","isPending","isSelectingShippingOption","isCustomerStepPending","isShippingStepPending","isPaymentStepPending","isSubmittingOrder","createCheckoutStoreSelector","availableShippingOptions","val","createCheckoutStoreErrorSelector","getLoadCheckoutError","getUpdateCheckoutError","getSubmitOrderError","getFinalizeOrderError","getLoadOrderError","getLoadCartError","getLoadBillingCountriesError","getLoadShippingCountriesError","getLoadPaymentMethodsError","getLoadPaymentMethodError","getInitializePaymentError","getInitializeCustomerError","getUpdateBillingAddressError","getUpdateSubscriptionsError","getUpdateShippingAddressError","getDeleteConsignmentError","getUpdateConsignmentError","getCreateConsignmentsError","getInitializeShippingError","getApplyStoreCreditError","getApplyCouponError","getRemoveCouponError","getApplyGiftCertificateError","getRemoveGiftCertificateError","getLoadInstrumentsError","getDeleteInstrumentError","getLoadConfigError","getSignInEmailError","getCreateCustomerAccountError","getCreateCustomerAddressError","createCheckoutStoreStatusSelector","isLoadingCheckout","isUpdatingCheckout","isFinalizingOrder","isLoadingOrder","isLoadingCart","isLoadingBillingCountries","isLoadingShippingCountries","isLoadingPaymentMethods","isLoadingPaymentMethod","isInitializingPayment","isInitializingCustomer","isUpdatingBillingAddress","isUpdatingSubscriptions","isUpdatingShippingAddress","isUpdatingConsignment","isDeletingConsignment","isCreatingConsignments","isInitializingShipping","isApplyingStoreCredit","isLoadingInstruments","isDeletingInstrument","isLoadingConfig","isSendingSignInEmail","_messageCustomizer","_countryActionCreator","_couponActionCreator","_errorActionCreator","_giftCertificateActionCreator","_instrumentActionCreator","_shippingCountryActionCreator","_signInEmailActionCreator","_subscriptionsActionCreator","isDevelopment","projection","_errorTransformer","_selectorsFactory","_storeProjection","initial","notifyState","_dispatch","loadCheckoutAction","formFieldsAction","loadConfigAction","finalizeOrderIfNeeded","deinitializePayment","loadBillingCountries","loadShippingCountries","loadBillingAddressFields","loadShippingAddressFields","initializeCustomer","deinitializeCustomer","signInEmailRequest","createCustomerAccount","createCustomerAddress","continueAsGuest","deinitializeShipping","assignItemsToAddress","unassignItemsToAddress","selectConsignmentShippingOption","updateBillingAddress","initializeSpamProtection","executeSpamCheck","createCheckoutService","checkoutVariantIdentificationToken","paymentClient","setHost","orderRequestSender","checkoutRequestSender","configActionCreator","spamProtection","spamProtectionRequestSender","spamProtectionActionCreator","subscriptionsActionCreator","formFieldsActionCreator","paymentMethodActionCreator","remoteCheckoutRequestSender","remoteCheckoutActionCreator","paymentRequestTransformer","paymentRequestSender","billingAddressActionCreator","braintreePaymentProcessor","braintreeHostedForm","overlay","checkoutValidator","storeCreditActionCreator","paymentHumanVerificationHandler","paymentStrategyActionCreator","storefrontPaymentRequestSender","getStylesheetLoader","PaymentResumer","createPaymentStrategyRegistry","consignmentRequestSender","consignmentActionCreator","_logger","_transformConfig","locales","translations","_locales","_translations","_formatters","mapKeys","translationKey","KEY_PREFIX","getLocale","_hasTranslations","translate","prefixedKey","messageFormat","compile","_transformData","defaultTranslations","_flattenObject","fallbackTranslations","union","defaultLocale","fallbackLocale","parentKey","resultKey","createLanguageService","currencySettings","symbolLocation","symbol","thousandsSeparator","decimalSeparator","parseInt","_symbolLocation","_symbol","_thousandsSeparator","_decimalSeparator","formattedNumber","_formatNumber","formattedCurrency","_formatCurrency","positiveAmount","abs","_toFixed","parsedIntegerAmount","decimalAmount","precision","_storeConfig","_customerFormatter","_storeFormatter","toCustomerCurrency","exchangeRate","toStoreCurrency","createCurrencyService","AnalyticStepId","CUSTOMER","SHIPPING","BILLING","PAYMENT","ANALYTIC_STEPS","checkoutService","storage","analytics","checkoutSteps","_checkoutStarted","_completedSteps","_viewedSteps","_analyticStepOrder","trackCheckoutStarted","extraItemsData","saveExtraItemsData","track","getTrackingPayload","revenue","tax","trackOrderComplete","readExtraItemsData","isEcommerceGAEnabled","hasPayloadLimit","hit","affiliation","products","product","category","clearExtraItemData","trackStepViewed","stepId","getIdFromStep","hasStepViewed","trackViewed","backfill","trackStepCompleted","hasStepCompleted","trackCompleted","shippingMethod","getShopperCurrency","getPaymentMethodName","shippingMethodId","completedStepId","getStoreProfile","toShopperCurrency","getProducts","getStorageKey","ORDER_ITEMS_STORAGE_KEY","itemsData","product_id","giftCertificateItems","physicalAndDigitalItems","itemAttributes","image_url","variant","createStepTracker","stepTrackerConfig","StyleButtonLabel","StyleButtonLayout","StyleButtonColor","StyleButtonShape","loadPaypalCommerce","isProgressiveOnboardingAvailable","_validateParams","paypalLoadScript","buynow","pay","installment","vertical","horizontal","gold","blue","silver","black","white","pill","rect","_validateStyleParams","updatedStyle","layout","tagline","_gatewayId","optionalParams","_fundingSource","_paypalButtons","_processNotEligible","Fields","fieldsParams","_paypalFields","fieldContainerElement","cartTotal","Messages","_paypalMessages","HostedFields","paymentsSDK","_hostedFields","PAYLATER","createPaypalCommercePaymentProcessor","paypalScriptLoader","paypalCommerceRequestSender","_googlePayScriptLoader","_googlePayInitializer","_googlePayClient","loadPaymentData","_getPaymentDataRequest","tokenizePayload","_updateBillingAddress","_mapGooglePayAddressToShippingAddress","googlePay","paymentDataRequest","_getGooglePayClient","_paymentDataRequest","isReadyToPay","google","api","PaymentsClient","_mapGooglePayAddressToBillingAddress","companyName","address3","administrativeArea","postPaymentData","remoteBillingAddress","googlePayAddressMapped","createGooglePayPaymentProcessor","initializer","_amazonPayV2ScriptLoader","_amazonPayV2SDK","_getAmazonPayV2SDK","Pay","bindChangeAction","amazonCheckoutSessionId","renderButton","amazonPayV2Region","createAmazonPayV2PaymentProcessor","getShippableItemsCount","_subscriptionsRequestSender","_subscriptionActionCreator","billingAddressRequestBody","existingBillingAddressRequestBody","_createOrUpdateBillingAddress","_updateCustomerConsent","acceptsAbandonedCartEmails","acceptsMarketingNewsletter","project","thisArg","TypeError","MapOperator","MapSubscriber","count","scheduler","schedule","emptyScheduled","scheduled","innerIndex","innerSub","OuterSubscriber","outerSubscriber","InnerSubscriber","FilterOperator","FilterSubscriber","subjectOrSubjectFactory","subjectFactory","MulticastOperator","connectable","connectableObservableDescriptor","__extends","__assign","__rest","__decorate","__param","__metadata","__awaiter","__generator","__exportStar","__values","__read","__spread","__spreadArrays","__await","__asyncGenerator","__asyncDelegator","__asyncValues","__makeTemplateObject","__importStar","__importDefault","__classPrivateFieldGet","__classPrivateFieldSet","__createBinding","root","global","self","createExporter","v","exporter","extendStatics","__","constructor","assign","getOwnPropertySymbols","propertyIsEnumerable","decorators","desc","Reflect","decorate","paramIndex","decorator","metadataKey","metadataValue","_arguments","P","generator","fulfilled","rejected","done","apply","y","sent","trys","ops","verb","iterator","op","k2","ar","il","j","jl","asyncIterator","q","fulfill","settle","shift","cooked","raw","mod","receiver","privateMap","has","work","recycleAsyncId","requestAsyncId","setInterval","flush","clearInterval","_execute","errored","errorValue","Action","SchedulerAction","Scheduler","delegate","active","scheduleArray","subscribeToArray","ArgumentOutOfRangeErrorImpl","ArgumentOutOfRangeError","EmptyErrorImpl","EmptyError","getSymbolIterator","$$iterator","defaultValue","DefaultIfEmptyOperator","DefaultIfEmptySubscriber","_enable_super_gross_mode_that_will_cause_bad_things","ObjectUnsubscribedErrorImpl","NotificationKind","kind","hasValue","do","accept","nextOrObserver","toObservable","createNext","Notification","undefinedValueNotification","createComplete","completeNotification","isScheduler","fromArray","hasNext","hasCompleted","AsyncSubject","subscribeToObservable","isArrayLike","isPromise","subscribeToPromise","subscribeToIterable","concatAll","observables","mergeMap","resultSelector","concurrent","POSITIVE_INFINITY","ii","MergeMapOperator","MergeMapSubscriber","buffer","_tryNext","ish","innerSubscription","innerSubscribe","parseFloat","ThrowIfEmptyOperator","ThrowIfEmptySubscriber","defaultErrorFactory","accumulator","seed","scan","takeLast","defaultIfEmpty","acc","random","$$rxSubscriber","fns","prev","RefCountOperator","_refCount","refCounter","RefCountSubscriber","connection","connect","refCount","sharedConnection","_connection","bufferSize","windowTime","_events","_infiniteTimeWindow","_bufferSize","_windowTime","nextInfiniteTimeWindow","nextTimeWindow","ReplayEvent","_getNow","_trimBufferThenGetEvents","ObserveOnSubscriber","queue","eventsCount","spliceCount","time","ReplaySubject","CombineLatestOperator","CombineLatestSubscriber","toRespond","subscribeToResult","unused","oldVal","_tryResultSelector","observableFactory","ZipOperator","ZipSubscriber","iterators","StaticArrayIterator","StaticIterator","ZipBufferIterator","stillUnsubscribed","notifyInactive","checkIterators","shouldComplete","_tryresultSelector","nextResult","TakeOperator","TakeSubscriber","TakeLastOperator","TakeLastSubscriber","ring","idx","hasSeed","ScanOperator","ScanSubscriber","_seed","SwitchMapOperator","SwitchMapSubscriber","_delay","_resolve","_promise","_timeoutToken","predicateFn","PaymentMethodIdMapper","MULTI_OPTION","BRAINTREE_VISACHECKOUT","BRAINTREE_GOOGLEPAY","isBraintreePaymentMethod","PAYPAL_COMMERCE_CREDIT_CARDS","isPaypalCommercePaymentMethod","UrlHelper","RequestSender","RequestFactory","PayloadTransformer","DEFAULT_OPTIONS","xhr","requestFactory","createRequest","payloadTransformer","toRequest","_reducer","equalityCheck","shallowEqual","_state$","BehaviorSubject","_notification$","_dispatchers","_dispatchQueue$","_errors","dispatcher$","concatMap","states","_transformStates","transformedState","distinctUntilChanged","stateA","stateB","_dispatchObservableAction","_dispatchThunkAction","_dispatchAction","state$","filterFn","skip","newState","previousValue","_getDispatchError","error$","transformedAction$","_getDispatcher","tap","thunkAction","isFrozen","freeze","reducers","currentState","UnsubscriptionErrorImpl","connectableProto","_isComplete","getSubject","_subject","ConnectableSubscriber","ConnectableObservable","writable","subscriberIndex","keySelector","elementSelector","durationSelector","subjectSelector","GroupByOperator","GroupBySubscriber","groups","attemptedToUnsubscribe","_group","Map","group","groupedObservable","GroupedObservable","duration","GroupDurationSubscriber","clear","removeGroup","groupSubject","refCountSubscription","InnerRefCountSubscription","_value","queueScheduler","QueueScheduler","QueueAction","ObserveOnOperator","arg","notification","scheduleMessage","ObserveOnMessage","asapScheduler","AsapScheduler","AsapAction","asap","TimeoutErrorImpl","TimeoutError","mergeAll","isInteropObservable","scheduleObservable","schedulePromise","isIterable","scheduleIterable","NEVER","pred","notPred","RaceOperator","RaceSubscriber","hasFirst","period","dueTime","periodOrScheduler","isNumeric","due","AuditOperator","AuditSubscriber","throttled","clearThrottle","isNaN","compare","DistinctUntilChangedOperator","DistinctUntilChangedSubscriber","hasKey","FindValueOperator","yieldIndex","FindValueSubscriber","defaultThrottleConfig","leading","trailing","ThrottleOperator","ThrottleSubscriber","_leading","_trailing","_hasValue","_sendValue","_throttled","send","throttle","tryDurationSelector","throttlingDone","withObservable","absoluteTimeout","isDate","waitFor","TimeoutWithOperator","TimeoutWithSubscriber","scheduleTimeout","dispatchTimeout","_browserSupport","_scripts","_preloadedScripts","onload","onreadystatechange","onerror","loadScripts","urls","preloadScript","prefetch","rel","canSupportRel","preloadedScript","as","preloadScripts","strictUriEncode","objectAssign","decodeComponent","encode","opts","strict","extract","str","queryStart","formatter","arrayFormat","exec","parserForArrayFormat","ret","parts","keysSorter","obj","encoderForArrayFormat","val2","query","_requestFactory","_cookie","_cache","DefaultCache","_mergeDefaultOptions","cachedRequest","_getCachedRequest","_prependHost","requestHandler","toResponse","_cacheRequest","onabort","ontimeout","toRequestBody","patch","defaultOptions","encodeParams","csrfToken","_isAssetRequest","_shouldCacheRequest","read","write","relList","supports","_stylesheets","_preloadedStylesheets","stylesheet","prepend","children","loadStylesheets","preloadStylesheet","preloadedStylesheet","preloadStylesheets","_formBuilder","handleUnload","isAbsoluteUrl","joinPaths","flowRight","curryRight","animationFrame","animationFrameScheduler","VirtualTimeScheduler","VirtualAction","isObservable","bindCallback","bindNodeCallback","combineLatest","forkJoin","fromEventPattern","generate","iif","interval","never","onErrorResumeNext","pairs","partition","range","timer","using","Immediate","setImmediate","clearImmediate","nextHandle","RESOLVED","activeHandles","findAndClearHandle","cb","TestTools","AnimationFrameScheduler","AnimationFrameAction","requestAnimationFrame","cancelAnimationFrame","maxFrames","frameTimeFactor","sortActions","callbackFunc","innerArgs","dispatchNext","dispatchError","iterable","return","obs","forkJoinInternal","sources","completed","emitted","eventName","setupSubscription","sourceObj","isEventTarget","isJQueryStyleEventEmitter","isNodeStyleEventEmitter","addHandler","removeHandler","retValue","condition","needIterate","iterate","conditionResult","initialStateOrOptions","resultSelectorOrObservable","trueResult","falseResult","counter","subNext","remainder","not","current","resourceFactory","resource","memoized","isRootCacheKeyMap","audit","auditTime","bufferCount","bufferTime","bufferToggle","bufferWhen","combineAll","concatMapTo","debounce","debounceTime","delayWhen","dematerialize","distinct","distinctUntilKeyChanged","elementAt","endWith","exhaust","exhaustMap","expand","groupBy","ignoreElements","mapTo","materialize","mergeMapTo","mergeScan","min","multicast","observeOn","pairwise","pluck","publish","publishBehavior","publishLast","publishReplay","repeat","repeatWhen","retry","sample","sampleTime","sequenceEqual","share","single","skipLast","skipUntil","skipWhile","startWith","subscribeOn","switchAll","switchMapTo","takeUntil","takeWhile","throttleTime","throwIfEmpty","timeInterval","timeoutWith","timestamp","toArray","windowCount","windowToggle","windowWhen","withLatestFrom","zipAll","closingNotifier","BufferOperator","BufferSubscriber","startBufferEvery","BufferCountOperator","subscriberClass","BufferSkipCountSubscriber","BufferCountSubscriber","buffers","bufferTimeSpan","bufferCreationInterval","maxBufferSize","BufferTimeOperator","BufferTimeSubscriber","contexts","openContext","timespanOnly","timeSpanOnlyState","closeAction","dispatchBufferTimeSpanOnly","closeState","creationState","dispatchBufferClose","dispatchBufferCreation","filledBufferContext","onBufferFull","closeContext","Context","prevContext","openings","closingSelector","BufferToggleOperator","BufferToggleSubscriber","closeBuffer","openBuffer","trySubscribe","BufferWhenOperator","BufferWhenSubscriber","subscribing","closingSubscription","CatchOperator","caught","CatchSubscriber","err2","innerObservable","CountOperator","CountSubscriber","_tryPredicate","DebounceOperator","DebounceSubscriber","emitValue","durationSubscription","DebounceTimeOperator","DebounceTimeSubscriber","debouncedSubscription","lastValue","clearDebounce","debouncedNext","delayFor","DelayOperator","DelaySubscriber","_schedule","scheduleNotification","DelayMessage","delayDurationSelector","subscriptionDelay","SubscriptionDelayObservable","DelayWhenOperator","DelayWhenSubscriber","delayNotifierSubscriptions","_innerValue","_innerIndex","removeSubscription","tryComplete","delayNotifier","tryDelay","subscriptionIdx","notifierSubscription","SubscriptionDelaySubscriber","sourceSubscribed","subscribeToSource","DeMaterializeOperator","DeMaterializeSubscriber","flushes","DistinctOperator","DistinctSubscriber","Set","_useKeySelector","_finalizeNext","hasDefaultValue","EveryOperator","EverySubscriber","everyValueMatch","SwitchFirstSubscriber","hasSubscription","ExhaustMapOperator","ExhaustMapSubscriber","tryNext","ExpandOperator","ExpandSubscriber","subscribeToProjection","FinallyOperator","FinallySubscriber","IgnoreElementsOperator","IgnoreElementsSubscriber","IsEmptySubscriber","MapToOperator","MapToSubscriber","MaterializeOperator","MaterializeSubscriber","comparer","MergeScanOperator","MergeScanSubscriber","nextSources","OnErrorResumeNextOperator","OnErrorResumeNextSubscriber","subscribeToNextSource","PairwiseSubscriber","hasPrev","pair","properties","props","currentProp","plucker","selectorOrScheduler","RepeatOperator","RepeatSubscriber","notifier","RepeatWhenOperator","RepeatWhenSubscriber","sourceIsBeingSubscribedTo","retries","subscribeToRetries","retriesSubscription","RetryOperator","RetrySubscriber","RetryWhenOperator","RetryWhenSubscriber","SampleOperator","sampleSubscriber","SampleSubscriber","SampleTimeOperator","SampleTimeSubscriber","dispatchNotification","compareTo","SequenceEqualOperator","SequenceEqualSubscriber","_a","_b","_oneComplete","SequenceEqualCompareToSubscriber","emit","checkValues","areEqual","nextB","completeB","shareSubjectFactory","configOrBufferSize","useRefCount","shareReplayOperator","SingleOperator","SingleSubscriber","seenValue","applySingleValue","singleValue","SkipOperator","SkipSubscriber","SkipLastOperator","_skipCount","SkipLastSubscriber","_count","_ring","skipCount","currentIndex","oldValue","SkipUntilOperator","SkipUntilSubscriber","SkipWhileOperator","SkipWhileSubscriber","skipping","tryCallPredicate","SubscribeOnOperator","SubscribeOnObservable","delayTime","TakeUntilOperator","takeUntilSubscriber","TakeUntilSubscriber","inclusive","TakeWhileOperator","TakeWhileSubscriber","nextOrComplete","predicateResult","DoOperator","TapSubscriber","_tapNext","_tapError","_tapComplete","ThrottleTimeOperator","ThrottleTimeSubscriber","_hasTrailingValue","_trailingValue","TimeInterval","Timestamp","toArrayReducer","arr","windowBoundaries","WindowOperator","windowSubscriber","WindowSubscriber","sourceSubscription","openWindow","prevWindow","newWindow","windowSize","startWindowEvery","WindowCountOperator","WindowCountSubscriber","windows","windowTimeSpan","windowCreationInterval","maxWindowSize","WindowTimeOperator","WindowTimeSubscriber","_numberOfNextedValues","dispatchWindowClose","dispatchWindowCreation","dispatchWindowTimeSpanOnly","numberOfNextedValues","closeWindow","CountedSubject","timeSpanState","WindowToggleOperator","WindowToggleSubscriber","openSubscription","inner","unsubscribeClosingNotification","closingNotification","WithLatestFromOperator","WithLatestFromSubscriber","found","_tryProject","cookie","JSON_CONTENT_TYPE_REGEXP","FORM_URLENCODED_CONTENT_TYPE_REGEXP","contentType","_getHeader","_parseResponseHeaders","getAllResponseHeaders","_parseResponseBody","responseText","rawHeaders","XMLHttpRequest","_configureRequest","_formatUrl","_configureRequestHeaders","withCredentials","formBuilder","_createInput","pathA","pathB","path","removeLeadingSlash","Client","clientConfig","DEFAULT_CONFIG","offsitePaymentInitializer","OffsitePaymentInitializer","PaymentSubmitter","ClientTokenGenerator","StoreRequestSender","PayloadMapper","payloadMapper","mapToPayload","urlHelper","AddressMapper","CustomerMapper","MetaMapper","StoreMapper","bc_auth_token","paymentMethodIdMapper","mapToId","notify_url","page_title","reference_id","addressMapper","mapToBillingAddress","customerMapper","mapToCustomer","metaMapper","mapToMeta","mapToShippingAddress","storeMapper","mapToStore","omitNil","isEmptyStringOrNil","string","mapToAddress","addressKey","formattedAddressKey","toSnakeCase","customer_browser_info","customer_email","customer_first_name","customer_geo_ip_country_code","customer_id","customer_last_name","customer_locale","customer_name","customer_phone","customer_reference","meta_referrer","meta_source","meta_user_agent","userAgent","store_hash","store_id","API","mapToHeaders","OrderMapper","PaymentMapper","orderMapper","mapToOrder","paymentMapper","mapToPayment","additional_action","customer_group","geo_ip_country_code","session_token","mapToCoupons","mapToItems","mapToShipping","totals","mapToOrderTotals","omitEmptyStringAndNil","transit_time","state_code","street_1","street_2","itemData","variant_id","grand_total","device","fingerprint_id","deviceFingerprint","mapToBigPayToken","credit_card_cryptogram","mapToCryptogram","mapToCreditCard","account_name","toNumber","customer_code","three_d_secure","hosted_form_nonce","verification_nonce","payment_cryptogram","account_mask","APPLICATION_JSON","GET","parseResponseHeaders","headerKeys","ClientTokenMapper","clientTokenMapper","mapToClientToken","CartMapper","GatewayMapper","QuoteMapper","cartMapper","mapToCart","gatewayMapper","mapToGateway","quote","quoteMapper","mapToQuote","currency_code","discount_total","shipping_total","surcharge_total","tax_total","ItemPhysicalEntity","ItemDigitalEntity","ItemGiftCertificateEntity","mapToLocale","store_identity","mapToIdentity","mapToUrls","language_code","confirmation","home","getInstrumentsUrl","getTrustedShippingAddressUrl","mapToTrustedShippingAddressPayload","getInstrumentByIdUrl","DELETE","providerName","cardholder_name","verification_code","issue_month","issue_year","issue_number","track_data","is_manual_entry","icc_data","fallback_reason","is_contactless","encrypted_pin_cryptogram","encrypted_pin_ksn","setRequestHeader"],"mappings":";uwBAAA,aACA,SAEA,QACA,SACA,SACA,SAYA,cAuCE,WAAYA,EACAC,EACAC,GAFZ,MA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,EAAIz6F,QAAUxD,EAAQwD,UAItB,YAAA+/G,yBAAR,SAAiCtlB,EAAqBxmG,GAClDnX,OAAO4d,KAAKzG,GAASvV,SAAQ,SAAA6F,GACzBk2G,EAAI8uB,iBAAiBhlI,EAAK0P,EAAQ1P,QAIlC,YAAAu7H,WAAR,SAAmB1oH,EAAa8a,EAAiBi0F,GAC7C,YAD6C,IAAAA,OAAA,GACxCj0F,GAAyC,IAA/Bp1B,OAAO4d,KAAKwX,GAAQ72B,OAIzB+b,EAAG,IAAIqtE,EAAY5wC,UAAU3hB,EAAQ,CAAEgyF,OAAQiC,IAH9C/uG,GAKnB,EAtCA,G,oHCLA,E,KAAA,qBAcA,0BACqB,KAAAiuG,OAAmB,GAqBxC,OAnBI,YAAAkB,KAAA,SAAQnvG,EAAaoF,GACjB,IAAM6P,EAAWzwB,KAAKmxC,OAAO31B,EAAKoF,EAAQ0V,QAE1C,OAAOt2B,KAAKypH,OAAOh5F,IAAa,MAGpC,YAAAm6F,MAAA,SAASpvG,EAAaoF,EAAyBrI,GAC3C,IAAMkY,EAAWzwB,KAAKmxC,OAAO31B,EAAKoF,EAAQ0V,QAE1Ct2B,KAAKypH,OAAOh5F,GAAYlY,GAGpB,YAAA44B,OAAR,SAAe31B,EAAa8a,GACxB,YADwB,IAAAA,MAAA,IACW,IAA/Bp1B,OAAO4d,KAAKwX,GAAQ72B,OACb+b,EAGDA,EAAG,IAAIqtE,EAAY5wC,UAAU3hB,IAE/C,EAtBA,GAAa,EAAAozF,gB,uVCdb,mBAAkC/vD,GAC9B,QAASA,IACe,WAAnB,EAAOA,IAA2C,mBAAZA,IACf,mBAAjBA,EAAQ/1C,O,kFCHvB,E,KAAA,wBAEA,mBAAsC4vC,GAClC,OAAO,IAAI,UAAQA","file":"transients~checkout-15143180.js","sourcesContent":["import { isFunction } from './util/isFunction';\nimport { empty as emptyObserver } from './Observer';\nimport { Observer, PartialObserver, TeardownLogic } from './types';\nimport { Subscription } from './Subscription';\nimport { rxSubscriber as rxSubscriberSymbol } from '../internal/symbol/rxSubscriber';\nimport { config } from './config';\nimport { hostReportError } from './util/hostReportError';\n\n/**\n * Implements the {@link Observer} interface and extends the\n * {@link Subscription} class. While the {@link Observer} is the public API for\n * consuming the values of an {@link Observable}, all Observers get converted to\n * a Subscriber, in order to provide Subscription-like capabilities such as\n * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for\n * implementing operators, but it is rarely used as a public API.\n *\n * @class Subscriber<T>\n */\nexport class Subscriber<T> extends Subscription implements Observer<T> {\n\n  [rxSubscriberSymbol]() { return this; }\n\n  /**\n   * A static factory for a Subscriber, given a (potentially partial) definition\n   * of an Observer.\n   * @param {function(x: ?T): void} [next] The `next` callback of an Observer.\n   * @param {function(e: ?any): void} [error] The `error` callback of an\n   * Observer.\n   * @param {function(): void} [complete] The `complete` callback of an\n   * Observer.\n   * @return {Subscriber<T>} A Subscriber wrapping the (partially defined)\n   * Observer represented by the given arguments.\n   * @nocollapse\n   */\n  static create<T>(next?: (x?: T) => void,\n                   error?: (e?: any) => void,\n                   complete?: () => void): Subscriber<T> {\n    const subscriber = new Subscriber(next, error, complete);\n    subscriber.syncErrorThrowable = false;\n    return subscriber;\n  }\n\n  /** @internal */ syncErrorValue: any = null;\n  /** @internal */ syncErrorThrown: boolean = false;\n  /** @internal */ syncErrorThrowable: boolean = false;\n\n  protected isStopped: boolean = false;\n  protected destination: PartialObserver<any> | Subscriber<any>; // this `any` is the escape hatch to erase extra type param (e.g. R)\n\n  /**\n   * @param {Observer|function(value: T): void} [destinationOrNext] A partially\n   * defined Observer or a `next` callback function.\n   * @param {function(e: ?any): void} [error] The `error` callback of an\n   * Observer.\n   * @param {function(): void} [complete] The `complete` callback of an\n   * Observer.\n   */\n  constructor(destinationOrNext?: PartialObserver<any> | ((value: T) => void),\n              error?: (e?: any) => void,\n              complete?: () => void) {\n    super();\n\n    switch (arguments.length) {\n      case 0:\n        this.destination = emptyObserver;\n        break;\n      case 1:\n        if (!destinationOrNext) {\n          this.destination = emptyObserver;\n          break;\n        }\n        if (typeof destinationOrNext === 'object') {\n          if (destinationOrNext instanceof Subscriber) {\n            this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;\n            this.destination = destinationOrNext;\n            destinationOrNext.add(this);\n          } else {\n            this.syncErrorThrowable = true;\n            this.destination = new SafeSubscriber<T>(this, <PartialObserver<any>> destinationOrNext);\n          }\n          break;\n        }\n      default:\n        this.syncErrorThrowable = true;\n        this.destination = new SafeSubscriber<T>(this, <((value: T) => void)> destinationOrNext, error, complete);\n        break;\n    }\n  }\n\n  /**\n   * The {@link Observer} callback to receive notifications of type `next` from\n   * the Observable, with a value. The Observable may call this method 0 or more\n   * times.\n   * @param {T} [value] The `next` value.\n   * @return {void}\n   */\n  next(value?: T): void {\n    if (!this.isStopped) {\n      this._next(value);\n    }\n  }\n\n  /**\n   * The {@link Observer} callback to receive notifications of type `error` from\n   * the Observable, with an attached `Error`. Notifies the Observer that\n   * the Observable has experienced an error condition.\n   * @param {any} [err] The `error` exception.\n   * @return {void}\n   */\n  error(err?: any): void {\n    if (!this.isStopped) {\n      this.isStopped = true;\n      this._error(err);\n    }\n  }\n\n  /**\n   * The {@link Observer} callback to receive a valueless notification of type\n   * `complete` from the Observable. Notifies the Observer that the Observable\n   * has finished sending push-based notifications.\n   * @return {void}\n   */\n  complete(): void {\n    if (!this.isStopped) {\n      this.isStopped = true;\n      this._complete();\n    }\n  }\n\n  unsubscribe(): void {\n    if (this.closed) {\n      return;\n    }\n    this.isStopped = true;\n    super.unsubscribe();\n  }\n\n  protected _next(value: T): void {\n    this.destination.next(value);\n  }\n\n  protected _error(err: any): void {\n    this.destination.error(err);\n    this.unsubscribe();\n  }\n\n  protected _complete(): void {\n    this.destination.complete();\n    this.unsubscribe();\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _unsubscribeAndRecycle(): Subscriber<T> {\n    const {  _parentOrParents } = this;\n    this._parentOrParents = null;\n    this.unsubscribe();\n    this.closed = false;\n    this.isStopped = false;\n    this._parentOrParents = _parentOrParents;\n    return this;\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class SafeSubscriber<T> extends Subscriber<T> {\n\n  private _context: any;\n\n  constructor(private _parentSubscriber: Subscriber<T>,\n              observerOrNext?: PartialObserver<T> | ((value: T) => void),\n              error?: (e?: any) => void,\n              complete?: () => void) {\n    super();\n\n    let next: ((value: T) => void);\n    let context: any = this;\n\n    if (isFunction(observerOrNext)) {\n      next = (<((value: T) => void)> observerOrNext);\n    } else if (observerOrNext) {\n      next = (<PartialObserver<T>> observerOrNext).next;\n      error = (<PartialObserver<T>> observerOrNext).error;\n      complete = (<PartialObserver<T>> observerOrNext).complete;\n      if (observerOrNext !== emptyObserver) {\n        context = Object.create(observerOrNext);\n        if (isFunction(context.unsubscribe)) {\n          this.add(<() => void> context.unsubscribe.bind(context));\n        }\n        context.unsubscribe = this.unsubscribe.bind(this);\n      }\n    }\n\n    this._context = context;\n    this._next = next;\n    this._error = error;\n    this._complete = complete;\n  }\n\n  next(value?: T): void {\n    if (!this.isStopped && this._next) {\n      const { _parentSubscriber } = this;\n      if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n        this.__tryOrUnsub(this._next, value);\n      } else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {\n        this.unsubscribe();\n      }\n    }\n  }\n\n  error(err?: any): void {\n    if (!this.isStopped) {\n      const { _parentSubscriber } = this;\n      const { useDeprecatedSynchronousErrorHandling } = config;\n      if (this._error) {\n        if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n          this.__tryOrUnsub(this._error, err);\n          this.unsubscribe();\n        } else {\n          this.__tryOrSetError(_parentSubscriber, this._error, err);\n          this.unsubscribe();\n        }\n      } else if (!_parentSubscriber.syncErrorThrowable) {\n        this.unsubscribe();\n        if (useDeprecatedSynchronousErrorHandling) {\n          throw err;\n        }\n        hostReportError(err);\n      } else {\n        if (useDeprecatedSynchronousErrorHandling) {\n          _parentSubscriber.syncErrorValue = err;\n          _parentSubscriber.syncErrorThrown = true;\n        } else {\n          hostReportError(err);\n        }\n        this.unsubscribe();\n      }\n    }\n  }\n\n  complete(): void {\n    if (!this.isStopped) {\n      const { _parentSubscriber } = this;\n      if (this._complete) {\n        const wrappedComplete = () => this._complete.call(this._context);\n\n        if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n          this.__tryOrUnsub(wrappedComplete);\n          this.unsubscribe();\n        } else {\n          this.__tryOrSetError(_parentSubscriber, wrappedComplete);\n          this.unsubscribe();\n        }\n      } else {\n        this.unsubscribe();\n      }\n    }\n  }\n\n  private __tryOrUnsub(fn: Function, value?: any): void {\n    try {\n      fn.call(this._context, value);\n    } catch (err) {\n      this.unsubscribe();\n      if (config.useDeprecatedSynchronousErrorHandling) {\n        throw err;\n      } else {\n        hostReportError(err);\n      }\n    }\n  }\n\n  private __tryOrSetError(parent: Subscriber<T>, fn: Function, value?: any): boolean {\n    if (!config.useDeprecatedSynchronousErrorHandling) {\n      throw new Error('bad call');\n    }\n    try {\n      fn.call(this._context, value);\n    } catch (err) {\n      if (config.useDeprecatedSynchronousErrorHandling) {\n        parent.syncErrorValue = err;\n        parent.syncErrorThrown = true;\n        return true;\n      } else {\n        hostReportError(err);\n        return true;\n      }\n    }\n    return false;\n  }\n\n  /** @internal This is an internal implementation detail, do not use. */\n  _unsubscribe(): void {\n    const { _parentSubscriber } = this;\n    this._context = null;\n    this._parentSubscriber = null;\n    _parentSubscriber.unsubscribe();\n  }\n}\n","import { Operator } from './Operator';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { TeardownLogic, OperatorFunction, PartialObserver, Subscribable } from './types';\nimport { canReportError } from './util/canReportError';\nimport { toSubscriber } from './util/toSubscriber';\nimport { iif } from './observable/iif';\nimport { throwError } from './observable/throwError';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\n\n/**\n * A representation of any set of values over any amount of time. This is the most basic building block\n * of RxJS.\n *\n * @class Observable<T>\n */\nexport class Observable<T> implements Subscribable<T> {\n\n  /** Internal implementation detail, do not use directly. */\n  public _isScalar: boolean = false;\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  source: Observable<any>;\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  operator: Operator<any, T>;\n\n  /**\n   * @constructor\n   * @param {Function} subscribe the function that is called when the Observable is\n   * initially subscribed to. This function is given a Subscriber, to which new values\n   * can be `next`ed, or an `error` method can be called to raise an error, or\n   * `complete` can be called to notify of a successful completion.\n   */\n  constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic) {\n    if (subscribe) {\n      this._subscribe = subscribe;\n    }\n  }\n\n  // HACK: Since TypeScript inherits static properties too, we have to\n  // fight against TypeScript here so Subject can have a different static create signature\n  /**\n   * Creates a new cold Observable by calling the Observable constructor\n   * @static true\n   * @owner Observable\n   * @method create\n   * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor\n   * @return {Observable} a new cold observable\n   * @nocollapse\n   * @deprecated use new Observable() instead\n   */\n  static create: Function = <T>(subscribe?: (subscriber: Subscriber<T>) => TeardownLogic) => {\n    return new Observable<T>(subscribe);\n  }\n\n  /**\n   * Creates a new Observable, with this Observable as the source, and the passed\n   * operator defined as the new observable's operator.\n   * @method lift\n   * @param {Operator} operator the operator defining the operation to take on the observable\n   * @return {Observable} a new observable with the Operator applied\n   */\n  lift<R>(operator: Operator<T, R>): Observable<R> {\n    const observable = new Observable<R>();\n    observable.source = this;\n    observable.operator = operator;\n    return observable;\n  }\n\n  subscribe(observer?: PartialObserver<T>): Subscription;\n  /** @deprecated Use an observer instead of a complete callback */\n  subscribe(next: null | undefined, error: null | undefined, complete: () => void): Subscription;\n  /** @deprecated Use an observer instead of an error callback */\n  subscribe(next: null | undefined, error: (error: any) => void, complete?: () => void): Subscription;\n  /** @deprecated Use an observer instead of a complete callback */\n  subscribe(next: (value: T) => void, error: null | undefined, complete: () => void): Subscription;\n  subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;\n  /**\n   * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.\n   *\n   * <span class=\"informal\">Use it when you have all these Observables, but still nothing is happening.</span>\n   *\n   * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It\n   * might be for example a function that you passed to Observable's constructor, but most of the time it is\n   * a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means\n   * that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often\n   * the thought.\n   *\n   * Apart from starting the execution of an Observable, this method allows you to listen for values\n   * that an Observable emits, as well as for when it completes or errors. You can achieve this in two\n   * of the following ways.\n   *\n   * The first way is creating an object that implements {@link Observer} interface. It should have methods\n   * defined by that interface, but note that it should be just a regular JavaScript object, which you can create\n   * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do\n   * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also\n   * that your object does not have to implement all methods. If you find yourself creating a method that doesn't\n   * do anything, you can simply omit it. Note however, if the `error` method is not provided, all errors will\n   * be left uncaught.\n   *\n   * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.\n   * This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent\n   * of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of Observer,\n   * if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`,\n   * since `subscribe` recognizes these functions by where they were placed in function call. When it comes\n   * to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown.\n   *\n   * Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object.\n   * This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean\n   * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback\n   * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.\n   *\n   * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.\n   * It is an Observable itself that decides when these functions will be called. For example {@link of}\n   * by default emits all its values synchronously. Always check documentation for how given Observable\n   * will behave when subscribed and if its default behavior can be modified with a `scheduler`.\n   *\n   * ## Example\n   * ### Subscribe with an Observer\n   * ```ts\n   * import { of } from 'rxjs';\n   *\n   * const sumObserver = {\n   *   sum: 0,\n   *   next(value) {\n   *     console.log('Adding: ' + value);\n   *     this.sum = this.sum + value;\n   *   },\n   *   error() {\n   *     // We actually could just remove this method,\n   *     // since we do not really care about errors right now.\n   *   },\n   *   complete() {\n   *     console.log('Sum equals: ' + this.sum);\n   *   }\n   * };\n   *\n   * of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.\n   *   .subscribe(sumObserver);\n   *\n   * // Logs:\n   * // \"Adding: 1\"\n   * // \"Adding: 2\"\n   * // \"Adding: 3\"\n   * // \"Sum equals: 6\"\n   * ```\n   *\n   * ### Subscribe with functions\n   * ```ts\n   * import { of } from 'rxjs'\n   *\n   * let sum = 0;\n   *\n   * of(1, 2, 3).subscribe(\n   *   value => {\n   *     console.log('Adding: ' + value);\n   *     sum = sum + value;\n   *   },\n   *   undefined,\n   *   () => console.log('Sum equals: ' + sum)\n   * );\n   *\n   * // Logs:\n   * // \"Adding: 1\"\n   * // \"Adding: 2\"\n   * // \"Adding: 3\"\n   * // \"Sum equals: 6\"\n   * ```\n   *\n   * ### Cancel a subscription\n   * ```ts\n   * import { interval } from 'rxjs';\n   *\n   * const subscription = interval(1000).subscribe(\n   *   num => console.log(num),\n   *   undefined,\n   *   () => {\n   *     // Will not be called, even when cancelling subscription.\n   *     console.log('completed!');\n   *   }\n   * );\n   *\n   * setTimeout(() => {\n   *   subscription.unsubscribe();\n   *   console.log('unsubscribed!');\n   * }, 2500);\n   *\n   * // Logs:\n   * // 0 after 1s\n   * // 1 after 2s\n   * // \"unsubscribed!\" after 2.5s\n   * ```\n   *\n   * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,\n   *  or the first of three possible handlers, which is the handler for each value emitted from the subscribed\n   *  Observable.\n   * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,\n   *  the error will be thrown as unhandled.\n   * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.\n   * @return {ISubscription} a subscription reference to the registered handlers\n   * @method subscribe\n   */\n  subscribe(observerOrNext?: PartialObserver<T> | ((value: T) => void),\n            error?: (error: any) => void,\n            complete?: () => void): Subscription {\n\n    const { operator } = this;\n    const sink = toSubscriber(observerOrNext, error, complete);\n\n    if (operator) {\n      sink.add(operator.call(sink, this.source));\n    } else {\n      sink.add(\n        this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?\n        this._subscribe(sink) :\n        this._trySubscribe(sink)\n      );\n    }\n\n    if (config.useDeprecatedSynchronousErrorHandling) {\n      if (sink.syncErrorThrowable) {\n        sink.syncErrorThrowable = false;\n        if (sink.syncErrorThrown) {\n          throw sink.syncErrorValue;\n        }\n      }\n    }\n\n    return sink;\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _trySubscribe(sink: Subscriber<T>): TeardownLogic {\n    try {\n      return this._subscribe(sink);\n    } catch (err) {\n      if (config.useDeprecatedSynchronousErrorHandling) {\n        sink.syncErrorThrown = true;\n        sink.syncErrorValue = err;\n      }\n      if (canReportError(sink)) {\n        sink.error(err);\n      } else {\n        console.warn(err);\n      }\n    }\n  }\n\n  /**\n   * @method forEach\n   * @param {Function} next a handler for each value emitted by the observable\n   * @param {PromiseConstructor} [promiseCtor] a constructor function used to instantiate the Promise\n   * @return {Promise} a promise that either resolves on observable completion or\n   *  rejects with the handled error\n   */\n  forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise<void> {\n    promiseCtor = getPromiseCtor(promiseCtor);\n\n    return new promiseCtor<void>((resolve, reject) => {\n      // Must be declared in a separate statement to avoid a ReferenceError when\n      // accessing subscription below in the closure due to Temporal Dead Zone.\n      let subscription: Subscription;\n      subscription = this.subscribe((value) => {\n        try {\n          next(value);\n        } catch (err) {\n          reject(err);\n          if (subscription) {\n            subscription.unsubscribe();\n          }\n        }\n      }, reject, resolve);\n    }) as Promise<void>;\n  }\n\n  /** @internal This is an internal implementation detail, do not use. */\n  _subscribe(subscriber: Subscriber<any>): TeardownLogic {\n    const { source } = this;\n    return source && source.subscribe(subscriber);\n  }\n\n  // `if` and `throw` are special snow flakes, the compiler sees them as reserved words. Deprecated in\n  // favor of iif and throwError functions.\n  /**\n   * @nocollapse\n   * @deprecated In favor of iif creation function: import { iif } from 'rxjs';\n   */\n  static if: typeof iif;\n  /**\n   * @nocollapse\n   * @deprecated In favor of throwError creation function: import { throwError } from 'rxjs';\n   */\n  static throw: typeof throwError;\n\n  /**\n   * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable\n   * @method Symbol.observable\n   * @return {Observable} this instance of the observable\n   */\n  [Symbol_observable]() {\n    return this;\n  }\n\n  /* tslint:disable:max-line-length */\n  pipe(): Observable<T>;\n  pipe<A>(op1: OperatorFunction<T, A>): Observable<A>;\n  pipe<A, B>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>): Observable<B>;\n  pipe<A, B, C>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>): Observable<C>;\n  pipe<A, B, C, D>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>): Observable<D>;\n  pipe<A, B, C, D, E>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>): Observable<E>;\n  pipe<A, B, C, D, E, F>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>): Observable<F>;\n  pipe<A, B, C, D, E, F, G>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>): Observable<G>;\n  pipe<A, B, C, D, E, F, G, H>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>): Observable<H>;\n  pipe<A, B, C, D, E, F, G, H, I>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>, op9: OperatorFunction<H, I>): Observable<I>;\n  pipe<A, B, C, D, E, F, G, H, I>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>, op9: OperatorFunction<H, I>, ...operations: OperatorFunction<any, any>[]): Observable<{}>;\n  /* tslint:enable:max-line-length */\n\n  /**\n   * Used to stitch together functional operators into a chain.\n   * @method pipe\n   * @return {Observable} the Observable result of all of the operators having\n   * been called in the order they were passed in.\n   *\n   * ### Example\n   * ```ts\n   * import { interval } from 'rxjs';\n   * import { map, filter, scan } from 'rxjs/operators';\n   *\n   * interval(1000)\n   *   .pipe(\n   *     filter(x => x % 2 === 0),\n   *     map(x => x + x),\n   *     scan((acc, x) => acc + x)\n   *   )\n   *   .subscribe(x => console.log(x))\n   * ```\n   */\n  pipe(...operations: OperatorFunction<any, any>[]): Observable<any> {\n    if (operations.length === 0) {\n      return this as any;\n    }\n\n    return pipeFromArray(operations)(this);\n  }\n\n  /* tslint:disable:max-line-length */\n  toPromise<T>(this: Observable<T>): Promise<T>;\n  toPromise<T>(this: Observable<T>, PromiseCtor: typeof Promise): Promise<T>;\n  toPromise<T>(this: Observable<T>, PromiseCtor: PromiseConstructorLike): Promise<T>;\n  /* tslint:enable:max-line-length */\n\n  toPromise(promiseCtor?: PromiseConstructorLike): Promise<T> {\n    promiseCtor = getPromiseCtor(promiseCtor);\n\n    return new promiseCtor((resolve, reject) => {\n      let value: any;\n      this.subscribe((x: T) => value = x, (err: any) => reject(err), () => resolve(value));\n    }) as Promise<T>;\n  }\n}\n\n/**\n * Decides between a passed promise constructor from consuming code,\n * A default configured promise constructor, and the native promise\n * constructor and returns it. If nothing can be found, it will throw\n * an error.\n * @param promiseCtor The optional promise constructor to passed by consuming code\n */\nfunction getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) {\n  if (!promiseCtor) {\n    promiseCtor = config.Promise || Promise;\n  }\n\n  if (!promiseCtor) {\n    throw new Error('no Promise impl found');\n  }\n\n  return promiseCtor;\n}\n","/** @prettier */\nimport { Subscription } from './Subscription';\nimport { Subscriber } from './Subscriber';\nimport { Observable } from './Observable';\nimport { subscribeTo } from './util/subscribeTo';\n\ninterface SimpleOuterSubscriberLike<T> {\n  /**\n   * A handler for inner next notifications from the inner subscription\n   * @param innerValue the value nexted by the inner producer\n   */\n  notifyNext(innerValue: T): void;\n  /**\n   * A handler for inner error notifications from the inner subscription\n   * @param err the error from the inner producer\n   */\n  notifyError(err: any): void;\n  /**\n   * A handler for inner complete notifications from the inner subscription.\n   */\n  notifyComplete(): void;\n}\n\nexport class SimpleInnerSubscriber<T> extends Subscriber<T> {\n  constructor(private parent: SimpleOuterSubscriberLike<any>) {\n    super();\n  }\n\n  protected _next(value: T): void {\n    this.parent.notifyNext(value);\n  }\n\n  protected _error(error: any): void {\n    this.parent.notifyError(error);\n    this.unsubscribe();\n  }\n\n  protected _complete(): void {\n    this.parent.notifyComplete();\n    this.unsubscribe();\n  }\n}\n\nexport class ComplexInnerSubscriber<T, R> extends Subscriber<R> {\n  constructor(private parent: ComplexOuterSubscriber<T, R>, public outerValue: T, public outerIndex: number) {\n    super();\n  }\n\n  protected _next(value: R): void {\n    this.parent.notifyNext(this.outerValue, value, this.outerIndex, this);\n  }\n\n  protected _error(error: any): void {\n    this.parent.notifyError(error);\n    this.unsubscribe();\n  }\n\n  protected _complete(): void {\n    this.parent.notifyComplete(this);\n    this.unsubscribe();\n  }\n}\n\nexport class SimpleOuterSubscriber<T, R> extends Subscriber<T> implements SimpleOuterSubscriberLike<R> {\n  notifyNext(innerValue: R): void {\n    this.destination.next(innerValue);\n  }\n\n  notifyError(err: any): void {\n    this.destination.error(err);\n  }\n\n  notifyComplete(): void {\n    this.destination.complete();\n  }\n}\n\n/**\n * DO NOT USE (formerly \"OuterSubscriber\")\n * TODO: We want to refactor this and remove it. It is retaining values it shouldn't for long\n * periods of time.\n */\nexport class ComplexOuterSubscriber<T, R> extends Subscriber<T> {\n  /**\n   * @param _outerValue Used by: bufferToggle, delayWhen, windowToggle\n   * @param innerValue Used by: subclass default, combineLatest, race, bufferToggle, windowToggle, withLatestFrom\n   * @param _outerIndex Used by: combineLatest, race, withLatestFrom\n   * @param _innerSub Used by: delayWhen\n   */\n  notifyNext(_outerValue: T, innerValue: R, _outerIndex: number, _innerSub: ComplexInnerSubscriber<T, R>): void {\n    this.destination.next(innerValue);\n  }\n\n  notifyError(error: any): void {\n    this.destination.error(error);\n  }\n\n  /**\n   * @param _innerSub Used by: race, bufferToggle, delayWhen, windowToggle, windowWhen\n   */\n  notifyComplete(_innerSub: ComplexInnerSubscriber<T, R>): void {\n    this.destination.complete();\n  }\n}\n\nexport function innerSubscribe(result: any, innerSubscriber: Subscriber<any>): Subscription | undefined {\n  if (innerSubscriber.closed) {\n    return undefined;\n  }\n  if (result instanceof Observable) {\n    return result.subscribe(innerSubscriber);\n  }\n  let subscription: Subscription;\n  try {\n    subscription = subscribeTo(result)(innerSubscriber) as Subscription;\n  } catch (error) {\n    innerSubscriber.error(error);\n  }\n  return subscription;\n}\n","import { isArray } from './util/isArray';\nimport { isObject } from './util/isObject';\nimport { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nimport { SubscriptionLike, TeardownLogic } from './types';\n\n/**\n * Represents a disposable resource, such as the execution of an Observable. A\n * Subscription has one important method, `unsubscribe`, that takes no argument\n * and just disposes the resource held by the subscription.\n *\n * Additionally, subscriptions may be grouped together through the `add()`\n * method, which will attach a child Subscription to the current Subscription.\n * When a Subscription is unsubscribed, all its children (and its grandchildren)\n * will be unsubscribed as well.\n *\n * @class Subscription\n */\nexport class Subscription implements SubscriptionLike {\n  /** @nocollapse */\n  public static EMPTY: Subscription = (function(empty: any) {\n    empty.closed = true;\n    return empty;\n  }(new Subscription()));\n\n  /**\n   * A flag to indicate whether this Subscription has already been unsubscribed.\n   * @type {boolean}\n   */\n  public closed: boolean = false;\n\n  /** @internal */\n  protected _parentOrParents: Subscription | Subscription[] = null;\n  /** @internal */\n  private _subscriptions: SubscriptionLike[] = null;\n\n  /**\n   * @param {function(): void} [unsubscribe] A function describing how to\n   * perform the disposal of resources when the `unsubscribe` method is called.\n   */\n  constructor(unsubscribe?: () => void) {\n    if (unsubscribe) {\n      (this as any)._ctorUnsubscribe = true;\n      (this as any)._unsubscribe = unsubscribe;\n    }\n  }\n\n  /**\n   * Disposes the resources held by the subscription. May, for instance, cancel\n   * an ongoing Observable execution or cancel any other type of work that\n   * started when the Subscription was created.\n   * @return {void}\n   */\n  unsubscribe(): void {\n    let errors: any[];\n\n    if (this.closed) {\n      return;\n    }\n\n    let { _parentOrParents, _ctorUnsubscribe, _unsubscribe, _subscriptions } = (this as any);\n\n    this.closed = true;\n    this._parentOrParents = null;\n    // null out _subscriptions first so any child subscriptions that attempt\n    // to remove themselves from this subscription will noop\n    this._subscriptions = null;\n\n    if (_parentOrParents instanceof Subscription) {\n      _parentOrParents.remove(this);\n    } else if (_parentOrParents !== null) {\n      for (let index = 0; index < _parentOrParents.length; ++index) {\n        const parent = _parentOrParents[index];\n        parent.remove(this);\n      }\n    }\n\n    if (isFunction(_unsubscribe)) {\n      // It's only possible to null _unsubscribe - to release the reference to\n      // any teardown function passed in the constructor - if the property was\n      // actually assigned in the constructor, as there are some classes that\n      // are derived from Subscriber (which derives from Subscription) that\n      // implement an _unsubscribe method as a mechanism for obtaining\n      // unsubscription notifications and some of those subscribers are\n      // recycled. Also, in some of those subscribers, _unsubscribe switches\n      // from a prototype method to an instance property - see notifyNext in\n      // RetryWhenSubscriber.\n      if (_ctorUnsubscribe) {\n        (this as any)._unsubscribe = undefined;\n      }\n      try {\n        _unsubscribe.call(this);\n      } catch (e) {\n        errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];\n      }\n    }\n\n    if (isArray(_subscriptions)) {\n      let index = -1;\n      let len = _subscriptions.length;\n\n      while (++index < len) {\n        const sub = _subscriptions[index];\n        if (isObject(sub)) {\n          try {\n            sub.unsubscribe();\n          } catch (e) {\n            errors = errors || [];\n            if (e instanceof UnsubscriptionError) {\n              errors = errors.concat(flattenUnsubscriptionErrors(e.errors));\n            } else {\n              errors.push(e);\n            }\n          }\n        }\n      }\n    }\n\n    if (errors) {\n      throw new UnsubscriptionError(errors);\n    }\n  }\n\n  /**\n   * Adds a tear down to be called during the unsubscribe() of this\n   * Subscription. Can also be used to add a child subscription.\n   *\n   * If the tear down being added is a subscription that is already\n   * unsubscribed, is the same reference `add` is being called on, or is\n   * `Subscription.EMPTY`, it will not be added.\n   *\n   * If this subscription is already in an `closed` state, the passed\n   * tear down logic will be executed immediately.\n   *\n   * When a parent subscription is unsubscribed, any child subscriptions that were added to it are also unsubscribed.\n   *\n   * @param {TeardownLogic} teardown The additional logic to execute on\n   * teardown.\n   * @return {Subscription} Returns the Subscription used or created to be\n   * added to the inner subscriptions list. This Subscription can be used with\n   * `remove()` to remove the passed teardown logic from the inner subscriptions\n   * list.\n   */\n  add(teardown: TeardownLogic): Subscription {\n    let subscription = (<Subscription>teardown);\n\n    if (!teardown) {\n      return Subscription.EMPTY;\n    }\n\n    switch (typeof teardown) {\n      case 'function':\n        subscription = new Subscription(<(() => void)>teardown);\n      case 'object':\n        if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {\n          // This also covers the case where `subscription` is `Subscription.EMPTY`, which is always in `closed` state.\n          return subscription;\n        } else if (this.closed) {\n          subscription.unsubscribe();\n          return subscription;\n        } else if (!(subscription instanceof Subscription)) {\n          const tmp = subscription;\n          subscription = new Subscription();\n          subscription._subscriptions = [tmp];\n        }\n        break;\n      default: {\n        throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');\n      }\n    }\n\n    // Add `this` as parent of `subscription` if that's not already the case.\n    let { _parentOrParents } = subscription;\n    if (_parentOrParents === null) {\n      // If we don't have a parent, then set `subscription._parents` to\n      // the `this`, which is the common case that we optimize for.\n      subscription._parentOrParents = this;\n    } else if (_parentOrParents instanceof Subscription) {\n      if (_parentOrParents === this) {\n        // The `subscription` already has `this` as a parent.\n        return subscription;\n      }\n      // If there's already one parent, but not multiple, allocate an\n      // Array to store the rest of the parent Subscriptions.\n      subscription._parentOrParents = [_parentOrParents, this];\n    } else if (_parentOrParents.indexOf(this) === -1) {\n      // Only add `this` to the _parentOrParents list if it's not already there.\n      _parentOrParents.push(this);\n    } else {\n      // The `subscription` already has `this` as a parent.\n      return subscription;\n    }\n\n    // Optimize for the common case when adding the first subscription.\n    const subscriptions = this._subscriptions;\n    if (subscriptions === null) {\n      this._subscriptions = [subscription];\n    } else {\n      subscriptions.push(subscription);\n    }\n\n    return subscription;\n  }\n\n  /**\n   * Removes a Subscription from the internal list of subscriptions that will\n   * unsubscribe during the unsubscribe process of this Subscription.\n   * @param {Subscription} subscription The subscription to remove.\n   * @return {void}\n   */\n  remove(subscription: Subscription): void {\n    const subscriptions = this._subscriptions;\n    if (subscriptions) {\n      const subscriptionIndex = subscriptions.indexOf(subscription);\n      if (subscriptionIndex !== -1) {\n        subscriptions.splice(subscriptionIndex, 1);\n      }\n    }\n  }\n}\n\nfunction flattenUnsubscriptionErrors(errors: any[]) {\n return errors.reduce((errs, err) => errs.concat((err instanceof UnsubscriptionError) ? err.errors : err), []);\n}\n","export { default as includes } from './includes';\nexport { default as isNil } from './is-nil';\nexport { default as isObject } from './is-object';\nexport { default as omitEmptyStringAndNil } from './omit-emptystring-and-nil';\nexport { default as omitNil } from './omit-nil';\nexport { default as omitProperty } from './omit-property';\nexport { default as toNumber } from './to-number';\nexport { default as toSnakeCase } from './to-snake-case';\nexport { default as toString } from './to-string';\n","import { Operator } from './Operator';\nimport { Observable } from './Observable';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { Observer, SubscriptionLike, TeardownLogic } from './types';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nimport { SubjectSubscription } from './SubjectSubscription';\nimport { rxSubscriber as rxSubscriberSymbol } from '../internal/symbol/rxSubscriber';\n\n/**\n * @class SubjectSubscriber<T>\n */\nexport class SubjectSubscriber<T> extends Subscriber<T> {\n  constructor(protected destination: Subject<T>) {\n    super(destination);\n  }\n}\n\n/**\n * A Subject is a special type of Observable that allows values to be\n * multicasted to many Observers. Subjects are like EventEmitters.\n *\n * Every Subject is an Observable and an Observer. You can subscribe to a\n * Subject, and you can call next to feed values as well as error and complete.\n *\n * @class Subject<T>\n */\nexport class Subject<T> extends Observable<T> implements SubscriptionLike {\n\n  [rxSubscriberSymbol]() {\n    return new SubjectSubscriber(this);\n  }\n\n  observers: Observer<T>[] = [];\n\n  closed = false;\n\n  isStopped = false;\n\n  hasError = false;\n\n  thrownError: any = null;\n\n  constructor() {\n    super();\n  }\n\n  /**@nocollapse\n   * @deprecated use new Subject() instead\n  */\n  static create: Function = <T>(destination: Observer<T>, source: Observable<T>): AnonymousSubject<T> => {\n    return new AnonymousSubject<T>(destination, source);\n  }\n\n  lift<R>(operator: Operator<T, R>): Observable<R> {\n    const subject = new AnonymousSubject(this, this);\n    subject.operator = <any>operator;\n    return <any>subject;\n  }\n\n  next(value?: T) {\n    if (this.closed) {\n      throw new ObjectUnsubscribedError();\n    }\n    if (!this.isStopped) {\n      const { observers } = this;\n      const len = observers.length;\n      const copy = observers.slice();\n      for (let i = 0; i < len; i++) {\n        copy[i].next(value);\n      }\n    }\n  }\n\n  error(err: any) {\n    if (this.closed) {\n      throw new ObjectUnsubscribedError();\n    }\n    this.hasError = true;\n    this.thrownError = err;\n    this.isStopped = true;\n    const { observers } = this;\n    const len = observers.length;\n    const copy = observers.slice();\n    for (let i = 0; i < len; i++) {\n      copy[i].error(err);\n    }\n    this.observers.length = 0;\n  }\n\n  complete() {\n    if (this.closed) {\n      throw new ObjectUnsubscribedError();\n    }\n    this.isStopped = true;\n    const { observers } = this;\n    const len = observers.length;\n    const copy = observers.slice();\n    for (let i = 0; i < len; i++) {\n      copy[i].complete();\n    }\n    this.observers.length = 0;\n  }\n\n  unsubscribe() {\n    this.isStopped = true;\n    this.closed = true;\n    this.observers = null;\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _trySubscribe(subscriber: Subscriber<T>): TeardownLogic {\n    if (this.closed) {\n      throw new ObjectUnsubscribedError();\n    } else {\n      return super._trySubscribe(subscriber);\n    }\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _subscribe(subscriber: Subscriber<T>): Subscription {\n    if (this.closed) {\n      throw new ObjectUnsubscribedError();\n    } else if (this.hasError) {\n      subscriber.error(this.thrownError);\n      return Subscription.EMPTY;\n    } else if (this.isStopped) {\n      subscriber.complete();\n      return Subscription.EMPTY;\n    } else {\n      this.observers.push(subscriber);\n      return new SubjectSubscription(this, subscriber);\n    }\n  }\n\n  /**\n   * Creates a new Observable with this Subject as the source. You can do this\n   * to create customize Observer-side logic of the Subject and conceal it from\n   * code that uses the Observable.\n   * @return {Observable} Observable that the Subject casts to\n   */\n  asObservable(): Observable<T> {\n    const observable = new Observable<T>();\n    (<any>observable).source = this;\n    return observable;\n  }\n}\n\n/**\n * @class AnonymousSubject<T>\n */\nexport class AnonymousSubject<T> extends Subject<T> {\n  constructor(protected destination?: Observer<T>, source?: Observable<T>) {\n    super();\n    this.source = source;\n  }\n\n  next(value: T) {\n    const { destination } = this;\n    if (destination && destination.next) {\n      destination.next(value);\n    }\n  }\n\n  error(err: any) {\n    const { destination } = this;\n    if (destination && destination.error) {\n      this.destination.error(err);\n    }\n  }\n\n  complete() {\n    const { destination } = this;\n    if (destination && destination.complete) {\n      this.destination.complete();\n    }\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _subscribe(subscriber: Subscriber<T>): Subscription {\n    const { source } = this;\n    if (source) {\n      return this.source.subscribe(subscriber);\n    } else {\n      return Subscription.EMPTY;\n    }\n  }\n}\n","export const isArray = (() => Array.isArray || (<T>(x: any): x is T[] => x && typeof x.length === 'number'))();\n","import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\n/**\n *\n * Async Scheduler\n *\n * <span class=\"informal\">Schedule task as if you used setTimeout(task, duration)</span>\n *\n * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript\n * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating\n * in intervals.\n *\n * If you just want to \"defer\" task, that is to perform it right after currently\n * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),\n * better choice will be the {@link asapScheduler} scheduler.\n *\n * ## Examples\n * Use async scheduler to delay task\n * ```ts\n * import { asyncScheduler } from 'rxjs';\n *\n * const task = () => console.log('it works!');\n *\n * asyncScheduler.schedule(task, 2000);\n *\n * // After 2 seconds logs:\n * // \"it works!\"\n * ```\n *\n * Use async scheduler to repeat task in intervals\n * ```ts\n * import { asyncScheduler } from 'rxjs';\n *\n * function task(state) {\n *   console.log(state);\n *   this.schedule(state + 1, 1000); // `this` references currently executing Action,\n *                                   // which we reschedule with new state and delay\n * }\n *\n * asyncScheduler.schedule(task, 3000, 0);\n *\n * // Logs:\n * // 0 after 3s\n * // 1 after 4s\n * // 2 after 5s\n * // 3 after 6s\n * ```\n */\nexport const asyncScheduler = new AsyncScheduler(AsyncAction);\n\n/**\n * @deprecated renamed. Use {@link asyncScheduler}\n */\nexport const async = asyncScheduler;"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 201);\n","module.exports = require(\"tslib\");","module.exports = require(\"lodash\");","module.exports = require(\"@bigcommerce/data-store\");","module.exports = require(\"rxjs\");","module.exports = require(\"@bigcommerce/memoize\");","import { Action } from '@bigcommerce/data-store';\n\nimport { Checkout } from '../checkout';\n\nimport { ConsignmentMeta } from './consignment';\n\nexport enum ConsignmentActionType {\n    CreateConsignmentsRequested = 'CREATE_CONSIGNMENTS_REQUESTED',\n    CreateConsignmentsSucceeded = 'CREATE_CONSIGNMENTS_SUCCEEDED',\n    CreateConsignmentsFailed = 'CREATE_CONSIGNMENTS_FAILED',\n\n    UpdateConsignmentRequested = 'UPDATE_CONSIGNMENT_REQUESTED',\n    UpdateConsignmentSucceeded = 'UPDATE_CONSIGNMENT_SUCCEEDED',\n    UpdateConsignmentFailed = 'UPDATE_CONSIGNMENT_FAILED',\n\n    DeleteConsignmentRequested = 'DELETE_CONSIGNMENT_REQUESTED',\n    DeleteConsignmentSucceeded = 'DELETE_CONSIGNMENT_SUCCEEDED',\n    DeleteConsignmentFailed = 'DELETE_CONSIGNMENT_FAILED',\n\n    UpdateShippingOptionRequested = 'UPDATE_SHIPPING_OPTION_REQUESTED',\n    UpdateShippingOptionSucceeded = 'UPDATE_SHIPPING_OPTION_SUCCEEDED',\n    UpdateShippingOptionFailed = 'UPDATE_SHIPPING_OPTION_FAILED',\n\n    LoadShippingOptionsRequested = 'LOAD_SHIPPING_OPTIONS_REQUESTED',\n    LoadShippingOptionsSucceeded = 'LOAD_SHIPPING_OPTIONS_SUCCEEDED',\n    LoadShippingOptionsFailed = 'LOAD_SHIPPING_OPTIONS_FAILED',\n}\n\nexport type ConsignmentAction =\n    CreateConsignmentsAction |\n    UpdateConsignmentAction |\n    DeleteConsignmentAction |\n    UpdateShippingOptionAction |\n    LoadShippingOptionsAction;\n\nexport type CreateConsignmentsAction =\n    CreateConsignmentsRequestedAction |\n    CreateConsignmentsSucceededAction |\n    CreateConsignmentsFailedAction;\n\nexport type UpdateConsignmentAction =\n    UpdateConsignmentRequestedAction |\n    UpdateConsignmentSucceededAction |\n    UpdateConsignmentFailedAction;\n\nexport type DeleteConsignmentAction =\n    DeleteConsignmentRequestedAction |\n    DeleteConsignmentSucceededAction |\n    DeleteConsignmentFailedAction;\n\nexport type UpdateShippingOptionAction =\n    UpdateShippingOptionRequestedAction |\n    UpdateShippingOptionSucceededAction |\n    UpdateShippingOptionFailedAction;\n\nexport type LoadShippingOptionsAction =\n    LoadShippingOptionsRequestedAction |\n    LoadShippingOptionsSucceededAction |\n    LoadShippingOptionsFailedAction;\n\nexport interface CreateConsignmentsRequestedAction extends Action {\n    type: ConsignmentActionType.CreateConsignmentsRequested;\n}\n\nexport interface CreateConsignmentsSucceededAction extends Action<Checkout> {\n    type: ConsignmentActionType.CreateConsignmentsSucceeded;\n}\n\nexport interface CreateConsignmentsFailedAction extends Action<Error> {\n    type: ConsignmentActionType.CreateConsignmentsFailed;\n}\n\nexport interface UpdateConsignmentRequestedAction extends Action<null, ConsignmentMeta> {\n    type: ConsignmentActionType.UpdateConsignmentRequested;\n}\n\nexport interface UpdateConsignmentSucceededAction extends Action<Checkout, ConsignmentMeta> {\n    type: ConsignmentActionType.UpdateConsignmentSucceeded;\n}\n\nexport interface UpdateConsignmentFailedAction extends Action<Error, ConsignmentMeta> {\n    type: ConsignmentActionType.UpdateConsignmentFailed;\n}\n\nexport interface DeleteConsignmentRequestedAction extends Action<null, ConsignmentMeta> {\n    type: ConsignmentActionType.DeleteConsignmentRequested;\n}\n\nexport interface DeleteConsignmentSucceededAction extends Action<Checkout, ConsignmentMeta> {\n    type: ConsignmentActionType.DeleteConsignmentSucceeded;\n}\n\nexport interface DeleteConsignmentFailedAction extends Action<Error, ConsignmentMeta> {\n    type: ConsignmentActionType.DeleteConsignmentFailed;\n}\n\nexport interface UpdateShippingOptionRequestedAction extends Action<null, ConsignmentMeta> {\n    type: ConsignmentActionType.UpdateShippingOptionRequested;\n}\n\nexport interface UpdateShippingOptionSucceededAction extends Action<Checkout, ConsignmentMeta> {\n    type: ConsignmentActionType.UpdateShippingOptionSucceeded;\n}\n\nexport interface UpdateShippingOptionFailedAction extends Action<Error, ConsignmentMeta> {\n    type: ConsignmentActionType.UpdateShippingOptionFailed;\n}\n\nexport interface LoadShippingOptionsRequestedAction extends Action {\n    type: ConsignmentActionType.LoadShippingOptionsRequested;\n}\n\nexport interface LoadShippingOptionsSucceededAction extends Action<Checkout> {\n    type: ConsignmentActionType.LoadShippingOptionsSucceeded;\n}\n\nexport interface LoadShippingOptionsFailedAction extends Action<Error> {\n    type: ConsignmentActionType.LoadShippingOptionsFailed;\n}\n","module.exports = require(\"rxjs/operators\");","enum PaymentStrategyType {\n    ADYENV2 = 'adyenv2',\n    ADYENV2_GOOGLEPAY = 'googlepayadyenv2',\n    AFFIRM = 'affirm',\n    AFTERPAY = 'afterpay',\n    AMAZON = 'amazon',\n    AUTHORIZENET_GOOGLE_PAY = 'googlepayauthorizenet',\n    AMAZONPAYV2 = 'amazonpay',\n    BARCLAYS = 'barclays',\n    BLUESNAPV2 = 'bluesnapv2',\n    BOLT = 'bolt',\n    CHECKOUTCOM = 'checkoutcom',\n    CHECKOUTCOM_APM = 'checkoutcomapm',\n    CHECKOUTCOM_FAWRY = 'checkoutcomfawry',\n    CHECKOUTCOM_SEPA = 'checkoutcomsepa',\n    CHECKOUTCOM_IDEAL = 'checkoutcomideal',\n    CREDIT_CARD = 'creditcard',\n    CHECKOUTCOM_GOOGLE_PAY = 'googlepaycheckoutcom',\n    CLEARPAY = 'clearpay',\n    CONVERGE = 'converge',\n    CYBERSOURCE = 'cybersource',\n    CYBERSOURCEV2 = 'cybersourcev2',\n    DIGITALRIVER = 'digitalriver',\n    CYBERSOURCEV2_GOOGLE_PAY = 'googlepaycybersourcev2',\n    KLARNA = 'klarna',\n    KLARNAV2 = 'klarnav2',\n    LAYBUY = 'laybuy',\n    LEGACY = 'legacy',\n    MOLLIE = 'mollie',\n    MONERIS = 'moneris',\n    NO_PAYMENT_DATA_REQUIRED = 'nopaymentdatarequired',\n    OFFLINE = 'offline',\n    OFFSITE = 'offsite',\n    ORBITAL_GOOGLE_PAY = 'googlepayorbital',\n    PAYPAL = 'paypal',\n    PAYPAL_EXPRESS = 'paypalexpress',\n    PAYPAL_EXPRESS_CREDIT = 'paypalexpresscredit',\n    PAYPAL_COMMERCE = 'paypalcommerce',\n    PAYPAL_COMMERCE_CREDIT = 'paypalcommercecredit',\n    PAYPAL_COMMERCE_CREDIT_CARD = 'paypalcommercecreditcards',\n    PAYPAL_COMMERCE_ALTERNATIVE_METHODS = 'paypalcommercealternativemethods',\n    PPSDK = 'PAYMENT_TYPE_SDK',\n    QUADPAY = 'quadpay',\n    SAGE_PAY = 'sagepay',\n    SQUARE = 'squarev2',\n    STRIPEV3 = 'stripev3',\n    BRAINTREE = 'braintree',\n    BRAINTREE_PAYPAL = 'braintreepaypal',\n    BRAINTREE_PAYPAL_CREDIT = 'braintreepaypalcredit',\n    BRAINTREE_VISA_CHECKOUT = 'braintreevisacheckout',\n    BRAINTREE_GOOGLE_PAY = 'googlepaybraintree',\n    CHASE_PAY = 'chasepay',\n    WE_PAY = 'wepay',\n    MASTERPASS = 'masterpass',\n    STRIPE_GOOGLE_PAY = 'googlepaystripe',\n    SEZZLE = 'sezzle',\n    ZIP = 'zip',\n}\n\nexport default PaymentStrategyType;\n","import { Action } from '@bigcommerce/data-store';\n\nexport enum ShippingStrategyActionType {\n    UpdateAddressFailed = 'SHIPPING_STRATEGY_UPDATE_ADDRESS_FAILED',\n    UpdateAddressRequested = 'SHIPPING_STRATEGY_UPDATE_ADDRESS_REQUESTED',\n    UpdateAddressSucceeded = 'SHIPPING_STRATEGY_UPDATE_ADDRESS_SUCCEEDED',\n    SelectOptionFailed = 'SHIPPING_STRATEGY_SELECT_OPTION_FAILED',\n    SelectOptionRequested = 'SHIPPING_STRATEGY_SELECT_OPTION_REQUESTED',\n    SelectOptionSucceeded = 'SHIPPING_STRATEGY_SELECT_OPTION_SUCCEEDED',\n    InitializeFailed = 'SHIPPING_STRATEGY_INITIALIZE_FAILED',\n    InitializeRequested = 'SHIPPING_STRATEGY_INITIALIZE_REQUESTED',\n    InitializeSucceeded = 'SHIPPING_STRATEGY_INITIALIZE_SUCCEEDED',\n    DeinitializeFailed = 'SHIPPING_STRATEGY_DEINITIALIZE_FAILED',\n    DeinitializeRequested = 'SHIPPING_STRATEGY_DEINITIALIZE_REQUESTED',\n    DeinitializeSucceeded = 'SHIPPING_STRATEGY_DEINITIALIZE_SUCCEEDED',\n    WidgetInteractionStarted = 'SHIPPING_STRATEGY_WIDGET_INTERACTION_STARTED',\n    WidgetInteractionFinished = 'SHIPPING_STRATEGY_WIDGET_INTERACTION_FINISHED',\n    WidgetInteractionFailed = 'SHIPPING_STRATEGY_WIDGET_INTERACTION_FAILED',\n}\n\nexport type ShippingStrategyAction =\n    ShippingStrategyUpdateAddressAction |\n    ShippingStrategySelectOptionAction |\n    ShippingStrategyInitializeAction |\n    ShippingStrategyDeinitializeAction |\n    ShippingStrategyWidgetAction;\n\nexport type ShippingStrategyUpdateAddressAction =\n    UpdateAddressRequestedAction |\n    UpdateAddressSucceededAction |\n    UpdateAddressFailedAction;\n\nexport type ShippingStrategySelectOptionAction =\n    SelectOptionRequestedAction |\n    SelectOptionSucceededAction |\n    SelectOptionFailedAction;\n\nexport type ShippingStrategyInitializeAction =\n    InitializeRequestedAction |\n    InitializeSucceededAction |\n    InitializeFailedAction;\n\nexport type ShippingStrategyDeinitializeAction =\n    DeinitializeRequestedAction |\n    DeinitializeSucceededAction |\n    DeinitializeFailedAction;\n\nexport type ShippingStrategyWidgetAction =\n    WidgetInteractionStartedAction |\n    WidgetInteractionFinishedAction |\n    WidgetInteractionFailedAction;\n\nexport interface UpdateAddressRequestedAction extends Action {\n    type: ShippingStrategyActionType.UpdateAddressRequested;\n}\n\nexport interface UpdateAddressSucceededAction extends Action {\n    type: ShippingStrategyActionType.UpdateAddressSucceeded;\n}\n\nexport interface UpdateAddressFailedAction extends Action<Error> {\n    type: ShippingStrategyActionType.UpdateAddressFailed;\n}\n\nexport interface SelectOptionRequestedAction extends Action {\n    type: ShippingStrategyActionType.SelectOptionRequested;\n}\n\nexport interface SelectOptionSucceededAction extends Action {\n    type: ShippingStrategyActionType.SelectOptionSucceeded;\n}\n\nexport interface SelectOptionFailedAction extends Action<Error> {\n    type: ShippingStrategyActionType.SelectOptionFailed;\n}\n\nexport interface InitializeRequestedAction extends Action {\n    type: ShippingStrategyActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n    type: ShippingStrategyActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action<Error> {\n    type: ShippingStrategyActionType.InitializeFailed;\n}\n\nexport interface DeinitializeRequestedAction extends Action {\n    type: ShippingStrategyActionType.DeinitializeRequested;\n}\n\nexport interface DeinitializeSucceededAction extends Action {\n    type: ShippingStrategyActionType.DeinitializeSucceeded;\n}\n\nexport interface DeinitializeFailedAction extends Action<Error> {\n    type: ShippingStrategyActionType.DeinitializeFailed;\n}\n\nexport interface WidgetInteractionStartedAction extends Action {\n    type: ShippingStrategyActionType.WidgetInteractionStarted;\n}\n\nexport interface WidgetInteractionFinishedAction extends Action {\n    type: ShippingStrategyActionType.WidgetInteractionFinished;\n}\n\nexport interface WidgetInteractionFailedAction extends Action<Error> {\n    type: ShippingStrategyActionType.WidgetInteractionFailed;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nexport enum CustomerStrategyActionType {\n    SignInFailed = 'CUSTOMER_STRATEGY_SIGN_IN_FAILED',\n    SignInRequested = 'CUSTOMER_STRATEGY_SIGN_IN_REQUESTED',\n    SignInSucceeded = 'CUSTOMER_STRATEGY_SIGN_IN_SUCCEEDED',\n    SignOutFailed = 'CUSTOMER_STRATEGY_SIGN_OUT_FAILED',\n    SignOutRequested = 'CUSTOMER_STRATEGY_SIGN_OUT_REQUESTED',\n    SignOutSucceeded = 'CUSTOMER_STRATEGY_SIGN_OUT_SUCCEEDED',\n    InitializeFailed = 'CUSTOMER_STRATEGY_INITIALIZE_FAILED',\n    InitializeRequested = 'CUSTOMER_STRATEGY_INITIALIZE_REQUESTED',\n    InitializeSucceeded = 'CUSTOMER_STRATEGY_INITIALIZE_SUCCEEDED',\n    DeinitializeFailed = 'CUSTOMER_STRATEGY_DEINITIALIZE_FAILED',\n    DeinitializeRequested = 'CUSTOMER_STRATEGY_DEINITIALIZE_REQUESTED',\n    DeinitializeSucceeded = 'CUSTOMER_STRATEGY_DEINITIALIZE_SUCCEEDED',\n    WidgetInteractionStarted = 'CUSTOMER_STRATEGY_WIDGET_INTERACTION_STARTED',\n    WidgetInteractionFinished = 'CUSTOMER_STRATEGY_WIDGET_INTERACTION_FINISHED',\n    WidgetInteractionFailed = 'CUSTOMER_STRATEGY_WIDGET_INTERACTION_FAILED',\n}\n\nexport type CustomerStrategyAction =\n    CustomerStrategySignInAction |\n    CustomerStrategySignOutAction |\n    CustomerStrategyInitializeAction |\n    CustomerStrategyDeinitializeAction |\n    CustomerStrategyWidgetAction;\n\nexport type CustomerStrategySignInAction =\n    SignInRequestedAction |\n    SignInSucceededAction |\n    SignInFailedAction;\n\nexport type CustomerStrategySignOutAction =\n    SignOutRequestedAction |\n    SignOutSucceededAction |\n    SignOutFailedAction;\n\nexport type CustomerStrategyInitializeAction =\n    InitializeRequestedAction |\n    InitializeSucceededAction |\n    InitializeFailedAction;\n\nexport type CustomerStrategyDeinitializeAction =\n    DeinitializeRequestedAction |\n    DeinitializeSucceededAction |\n    DeinitializeFailedAction;\n\nexport type CustomerStrategyWidgetAction =\n    WidgetInteractionStartedAction |\n    WidgetInteractionFinishedAction |\n    WidgetInteractionFailedAction;\n\nexport interface SignInRequestedAction extends Action {\n    type: CustomerStrategyActionType.SignInRequested;\n}\n\nexport interface SignInSucceededAction extends Action {\n    type: CustomerStrategyActionType.SignInSucceeded;\n}\n\nexport interface SignInFailedAction extends Action<Error> {\n    type: CustomerStrategyActionType.SignInFailed;\n}\n\nexport interface SignOutRequestedAction extends Action {\n    type: CustomerStrategyActionType.SignOutRequested;\n}\n\nexport interface SignOutSucceededAction extends Action {\n    type: CustomerStrategyActionType.SignOutSucceeded;\n}\n\nexport interface SignOutFailedAction extends Action<Error> {\n    type: CustomerStrategyActionType.SignOutFailed;\n}\n\nexport interface InitializeRequestedAction extends Action {\n    type: CustomerStrategyActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n    type: CustomerStrategyActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action<Error> {\n    type: CustomerStrategyActionType.InitializeFailed;\n}\n\nexport interface DeinitializeRequestedAction extends Action {\n    type: CustomerStrategyActionType.DeinitializeRequested;\n}\n\nexport interface DeinitializeSucceededAction extends Action {\n    type: CustomerStrategyActionType.DeinitializeSucceeded;\n}\n\nexport interface DeinitializeFailedAction extends Action<Error> {\n    type: CustomerStrategyActionType.DeinitializeFailed;\n}\n\nexport interface WidgetInteractionStartedAction extends Action {\n    type: CustomerStrategyActionType.WidgetInteractionStarted;\n}\n\nexport interface WidgetInteractionFinishedAction extends Action {\n    type: CustomerStrategyActionType.WidgetInteractionFinished;\n}\n\nexport interface WidgetInteractionFailedAction extends Action<Error> {\n    type: CustomerStrategyActionType.WidgetInteractionFailed;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadOrderPaymentsAction } from '../order';\n\nexport enum PaymentStrategyActionType {\n    ExecuteFailed = 'PAYMENT_STRATEGY_EXECUTE_FAILED',\n    ExecuteRequested = 'PAYMENT_STRATEGY_EXECUTE_REQUESTED',\n    ExecuteSucceeded = 'PAYMENT_STRATEGY_EXECUTE_SUCCEEDED',\n    FinalizeFailed = 'PAYMENT_STRATEGY_FINALIZE_FAILED',\n    FinalizeRequested = 'PAYMENT_STRATEGY_FINALIZE_REQUESTED',\n    FinalizeSucceeded = 'PAYMENT_STRATEGY_FINALIZE_SUCCEEDED',\n    InitializeFailed = 'PAYMENT_STRATEGY_INITIALIZE_FAILED',\n    InitializeRequested = 'PAYMENT_STRATEGY_INITIALIZE_REQUESTED',\n    InitializeSucceeded = 'PAYMENT_STRATEGY_INITIALIZE_SUCCEEDED',\n    DeinitializeFailed = 'PAYMENT_STRATEGY_DEINITIALIZE_FAILED',\n    DeinitializeRequested = 'PAYMENT_STRATEGY_DEINITIALIZE_REQUESTED',\n    DeinitializeSucceeded = 'PAYMENT_STRATEGY_DEINITIALIZE_SUCCEEDED',\n    WidgetInteractionStarted = 'PAYMENT_STRATEGY_WIDGET_INTERACTION_STARTED',\n    WidgetInteractionFinished = 'PAYMENT_STRATEGY_WIDGET_INTERACTION_FINISHED',\n    WidgetInteractionFailed = 'PAYMENT_STRATEGY_WIDGET_INTERACTION_FAILED',\n}\n\nexport type PaymentStrategyAction =\n    PaymentStrategyExecuteAction |\n    PaymentStrategyFinalizeAction |\n    PaymentStrategyInitializeAction |\n    PaymentStrategyDeinitializeAction |\n    PaymentStrategyWidgetAction;\n\nexport type PaymentStrategyExecuteAction =\n    ExecuteRequestedAction |\n    ExecuteSucceededAction |\n    ExecuteFailedAction |\n    LoadOrderPaymentsAction;\n\nexport type PaymentStrategyFinalizeAction =\n    FinalizeRequestedAction |\n    FinalizeSucceededAction |\n    FinalizeFailedAction |\n    LoadOrderPaymentsAction;\n\nexport type PaymentStrategyInitializeAction =\n    InitializeRequestedAction |\n    InitializeSucceededAction |\n    InitializeFailedAction;\n\nexport type PaymentStrategyDeinitializeAction =\n    DeinitializeRequestedAction |\n    DeinitializeSucceededAction |\n    DeinitializeFailedAction;\n\nexport type PaymentStrategyWidgetAction =\n    WidgetInteractionStartedAction |\n    WidgetInteractionFinishedAction |\n    WidgetInteractionFailedAction;\n\nexport interface ExecuteRequestedAction extends Action {\n    type: PaymentStrategyActionType.ExecuteRequested;\n}\n\nexport interface ExecuteSucceededAction extends Action {\n    type: PaymentStrategyActionType.ExecuteSucceeded;\n}\n\nexport interface ExecuteFailedAction extends Action<Error> {\n    type: PaymentStrategyActionType.ExecuteFailed;\n}\n\nexport interface FinalizeRequestedAction extends Action {\n    type: PaymentStrategyActionType.FinalizeRequested;\n}\n\nexport interface FinalizeSucceededAction extends Action {\n    type: PaymentStrategyActionType.FinalizeSucceeded;\n}\n\nexport interface FinalizeFailedAction extends Action<Error> {\n    type: PaymentStrategyActionType.FinalizeFailed;\n}\n\nexport interface InitializeRequestedAction extends Action {\n    type: PaymentStrategyActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n    type: PaymentStrategyActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action<Error> {\n    type: PaymentStrategyActionType.InitializeFailed;\n}\n\nexport interface DeinitializeRequestedAction extends Action {\n    type: PaymentStrategyActionType.DeinitializeRequested;\n}\n\nexport interface DeinitializeSucceededAction extends Action {\n    type: PaymentStrategyActionType.DeinitializeSucceeded;\n}\n\nexport interface DeinitializeFailedAction extends Action<Error> {\n    type: PaymentStrategyActionType.DeinitializeFailed;\n}\n\nexport interface WidgetInteractionStartedAction extends Action {\n    type: PaymentStrategyActionType.WidgetInteractionStarted;\n}\n\nexport interface WidgetInteractionFinishedAction extends Action {\n    type: PaymentStrategyActionType.WidgetInteractionFinished;\n}\n\nexport interface WidgetInteractionFailedAction extends Action<Error> {\n    type: PaymentStrategyActionType.WidgetInteractionFailed;\n}\n","import StandardError from './standard-error';\n\nexport enum MissingDataErrorType {\n    MissingBillingAddress,\n    MissingCart,\n    MissingCheckout,\n    MissingConsignments,\n    MissingCustomer,\n    MissingCheckoutConfig,\n    MissingOrder,\n    MissingOrderConfig,\n    MissingOrderId,\n    MissingPayment,\n    MissingPaymentInstrument,\n    MissingPaymentMethod,\n    MissingPaymentToken,\n    MissingShippingAddress,\n}\n\n/**\n * Throw this error when data that is expected to exist is missing. Usually it\n * is due to the fact that certain data has not been retrieved from or saved to\n * the server yet. And such data is required to perform certain actions.\n */\nexport default class MissingDataError extends StandardError {\n    constructor(\n        public subtype: MissingDataErrorType\n    ) {\n        super(getErrorMessage(subtype));\n\n        this.name = 'MissingDataError';\n        this.type = 'missing_data';\n    }\n}\n\nfunction getErrorMessage(type: MissingDataErrorType): string {\n    switch (type) {\n    case MissingDataErrorType.MissingBillingAddress:\n        return 'Unable to proceed because billing address data is unavailable.';\n\n    case MissingDataErrorType.MissingCart:\n        return 'Unable to proceed because cart data is unavailable.';\n\n    case MissingDataErrorType.MissingConsignments:\n        return 'Unable to proceed because consignments data is unavailable.';\n\n    case MissingDataErrorType.MissingCheckout:\n        return 'Unable to proceed because checkout data is unavailable.';\n\n    case MissingDataErrorType.MissingCustomer:\n        return 'Unable to proceed because customer data is unavailable.';\n\n    case MissingDataErrorType.MissingCheckoutConfig:\n    case MissingDataErrorType.MissingOrderConfig:\n        return 'Unable to proceed because configuration data is unavailable.';\n\n    case MissingDataErrorType.MissingOrder:\n        return 'Unable to proceed because order data is unavailable.';\n\n    case MissingDataErrorType.MissingOrderId:\n        return 'Unable to proceed because order ID is unavailable or not generated yet.';\n\n    case MissingDataErrorType.MissingPayment:\n        return 'Unable to proceed because payment data is unavailable.';\n\n    case MissingDataErrorType.MissingPaymentToken:\n        return 'Unable to proceed because the token required to submit a payment is missing.';\n\n    case MissingDataErrorType.MissingPaymentMethod:\n        return 'Unable to proceed because payment method data is unavailable or not properly configured.';\n\n    case MissingDataErrorType.MissingShippingAddress:\n        return 'Unable to proceed because shipping address data is unavailable.';\n\n    default:\n        return 'Unable to proceed because the required data is unavailable.';\n    }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadConfigAction } from '../config';\nimport { LoadFormFieldsAction } from '../form';\n\nimport Checkout from './checkout';\n\nexport enum CheckoutActionType {\n    LoadCheckoutRequested = 'LOAD_CHECKOUT_REQUESTED',\n    LoadCheckoutSucceeded = 'LOAD_CHECKOUT_SUCCEEDED',\n    LoadCheckoutFailed = 'LOAD_CHECKOUT_FAILED',\n\n    UpdateCheckoutRequested = 'UPDATE_CHECKOUT_REQUESTED',\n    UpdateCheckoutSucceeded = 'UPDATE_CHECKOUT_SUCCEEDED',\n    UpdateCheckoutFailed = 'UPDATE_CHECKOUT_FAILED',\n}\n\nexport type CheckoutAction = LoadCheckoutAction | UpdateCheckoutAction;\n\nexport type LoadCheckoutAction =\n    LoadCheckoutRequestedAction |\n    LoadCheckoutSucceededAction |\n    LoadCheckoutFailedAction |\n    LoadFormFieldsAction |\n    LoadConfigAction;\n\nexport type UpdateCheckoutAction =\n    UpdateCheckoutRequestedAction |\n    UpdateCheckoutSucceededAction |\n    UpdateCheckoutFailedAction;\n\nexport interface LoadCheckoutRequestedAction extends Action {\n    type: CheckoutActionType.LoadCheckoutRequested;\n}\n\nexport interface LoadCheckoutSucceededAction extends Action<Checkout> {\n    type: CheckoutActionType.LoadCheckoutSucceeded;\n}\n\nexport interface LoadCheckoutFailedAction extends Action<Error> {\n    type: CheckoutActionType.LoadCheckoutFailed;\n}\n\nexport interface UpdateCheckoutRequestedAction extends Action {\n    type: CheckoutActionType.UpdateCheckoutRequested;\n}\n\nexport interface UpdateCheckoutSucceededAction extends Action<Checkout> {\n    type: CheckoutActionType.UpdateCheckoutSucceeded;\n}\n\nexport interface UpdateCheckoutFailedAction extends Action<Error> {\n    type: CheckoutActionType.UpdateCheckoutFailed;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { InternalOrderResponseData } from './internal-order-responses';\nimport Order from './order';\n\nexport enum OrderActionType {\n    LoadOrderRequested = 'LOAD_ORDER_REQUESTED',\n    LoadOrderSucceeded = 'LOAD_ORDER_SUCCEEDED',\n    LoadOrderFailed = 'LOAD_ORDER_FAILED',\n\n    LoadOrderPaymentsRequested = 'LOAD_ORDER_PAYMENTS_REQUESTED',\n    LoadOrderPaymentsSucceeded = 'LOAD_ORDER_PAYMENTS_SUCCEEDED',\n    LoadOrderPaymentsFailed = 'LOAD_ORDER_PAYMENTS_FAILED',\n\n    SubmitOrderRequested = 'SUBMIT_ORDER_REQUESTED',\n    SubmitOrderSucceeded = 'SUBMIT_ORDER_SUCCEEDED',\n    SubmitOrderFailed = 'SUBMIT_ORDER_FAILED',\n\n    FinalizeOrderRequested = 'FINALIZE_ORDER_REQUESTED',\n    FinalizeOrderSucceeded = 'FINALIZE_ORDER_SUCCEEDED',\n    FinalizeOrderFailed = 'FINALIZE_ORDER_FAILED',\n}\n\nexport type OrderAction = LoadOrderAction |\n    LoadOrderPaymentsAction |\n    SubmitOrderAction |\n    FinalizeOrderAction;\n\nexport type LoadOrderPaymentsAction = LoadOrderPaymentsRequestedAction |\n    LoadOrderPaymentsSucceededAction |\n    LoadOrderPaymentsFailedAction;\n\nexport type LoadOrderAction =\n    LoadOrderRequestedAction |\n    LoadOrderSucceededAction |\n    LoadOrderFailedAction;\n\nexport type SubmitOrderAction =\n    SubmitOrderRequestedAction |\n    SubmitOrderSucceededAction |\n    SubmitOrderFailedAction |\n    LoadOrderAction;\n\nexport type FinalizeOrderAction =\n    FinalizeOrderRequestedAction |\n    FinalizeOrderSucceededAction |\n    FinalizeOrderFailedAction |\n    LoadOrderAction;\n\nexport interface LoadOrderRequestedAction extends Action {\n    type: OrderActionType.LoadOrderRequested;\n}\n\nexport interface LoadOrderSucceededAction extends Action<Order> {\n    type: OrderActionType.LoadOrderSucceeded;\n}\n\nexport interface LoadOrderFailedAction extends Action<Error> {\n    type: OrderActionType.LoadOrderFailed;\n}\n\nexport interface LoadOrderPaymentsRequestedAction extends Action {\n    type: OrderActionType.LoadOrderPaymentsRequested;\n}\n\nexport interface LoadOrderPaymentsSucceededAction extends Action<Order> {\n    type: OrderActionType.LoadOrderPaymentsSucceeded;\n}\n\nexport interface LoadOrderPaymentsFailedAction extends Action<Error> {\n    type: OrderActionType.LoadOrderPaymentsFailed;\n}\n\nexport interface SubmitOrderRequestedAction extends Action {\n    type: OrderActionType.SubmitOrderRequested;\n}\n\nexport interface SubmitOrderSucceededAction extends Action<InternalOrderResponseData> {\n    type: OrderActionType.SubmitOrderSucceeded;\n}\n\nexport interface SubmitOrderFailedAction extends Action<Error> {\n    type: OrderActionType.SubmitOrderFailed;\n}\n\nexport interface FinalizeOrderRequestedAction extends Action {\n    type: OrderActionType.FinalizeOrderRequested;\n}\n\nexport interface FinalizeOrderSucceededAction extends Action<InternalOrderResponseData> {\n    type: OrderActionType.FinalizeOrderSucceeded;\n}\n\nexport interface FinalizeOrderFailedAction extends Action<Error> {\n    type: OrderActionType.FinalizeOrderFailed;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport PaymentMethod from './payment-method';\nimport PaymentMethodMeta from './payment-method-meta';\n\nexport enum PaymentMethodActionType {\n    LoadPaymentMethodRequested = 'LOAD_PAYMENT_METHOD_REQUESTED',\n    LoadPaymentMethodSucceeded = 'LOAD_PAYMENT_METHOD_SUCCEEDED',\n    LoadPaymentMethodFailed = 'LOAD_PAYMENT_METHOD_FAILED',\n\n    LoadPaymentMethodsRequested = 'LOAD_PAYMENT_METHODS_REQUESTED',\n    LoadPaymentMethodsSucceeded = 'LOAD_PAYMENT_METHODS_SUCCEEDED',\n    LoadPaymentMethodsFailed = 'LOAD_PAYMENT_METHODS_FAILED',\n}\n\nexport type PaymentMethodAction = LoadPaymentMethodAction | LoadPaymentMethodsAction;\n\nexport type LoadPaymentMethodAction =\n    LoadPaymentMethodRequestedAction |\n    LoadPaymentMethodSucceededAction |\n    LoadPaymentMethodFailedAction;\n\nexport type LoadPaymentMethodsAction =\n    LoadPaymentMethodsRequestedAction |\n    LoadPaymentMethodsSucceededAction |\n    LoadPaymentMethodsFailedAction;\n\nexport interface LoadPaymentMethodRequestedAction extends Action {\n    type: PaymentMethodActionType.LoadPaymentMethodRequested;\n}\n\nexport interface LoadPaymentMethodSucceededAction extends Action<PaymentMethod> {\n    type: PaymentMethodActionType.LoadPaymentMethodSucceeded;\n}\n\nexport interface LoadPaymentMethodFailedAction extends Action<Error> {\n    type: PaymentMethodActionType.LoadPaymentMethodFailed;\n}\n\nexport interface LoadPaymentMethodsRequestedAction extends Action {\n    type: PaymentMethodActionType.LoadPaymentMethodsRequested;\n}\n\nexport interface LoadPaymentMethodsSucceededAction extends Action<PaymentMethod[], PaymentMethodMeta> {\n    type: PaymentMethodActionType.LoadPaymentMethodsSucceeded;\n}\n\nexport interface LoadPaymentMethodsFailedAction extends Action<Error> {\n    type: PaymentMethodActionType.LoadPaymentMethodsFailed;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Checkout } from '../checkout';\n\nexport enum BillingAddressActionType {\n    UpdateBillingAddressRequested = 'UPDATE_BILLING_ADDRESS_REQUESTED',\n    UpdateBillingAddressSucceeded = 'UPDATE_BILLING_ADDRESS_SUCCEEDED',\n    UpdateBillingAddressFailed = 'UPDATE_BILLING_ADDRESS_FAILED',\n\n    ContinueAsGuestRequested = 'CONTINUE_AS_GUEST_REQUESTED',\n    ContinueAsGuestSucceeded = 'CONTINUE_AS_GUEST_SUCCEEDED',\n    ContinueAsGuestFailed = 'CONTINUE_AS_GUEST_FAILED',\n}\n\nexport type BillingAddressAction =\n    ContinueAsGuestAction |\n    UpdateBillingAddressAction;\n\nexport type UpdateBillingAddressAction =\n    UpdateBillingAddressRequested |\n    UpdateBillingAddressSucceeded |\n    UpdateBillingAddressFailed;\n\nexport type ContinueAsGuestAction =\n    ContinueAsGuestRequested |\n    ContinueAsGuestSucceeded |\n    ContinueAsGuestFailed;\n\nexport interface UpdateBillingAddressRequested extends Action {\n    type: BillingAddressActionType.UpdateBillingAddressRequested;\n}\n\nexport interface UpdateBillingAddressSucceeded extends Action<Checkout> {\n    type: BillingAddressActionType.UpdateBillingAddressSucceeded;\n}\n\nexport interface UpdateBillingAddressFailed extends Action<Error> {\n    type: BillingAddressActionType.UpdateBillingAddressFailed;\n}\n\nexport interface ContinueAsGuestRequested extends Action {\n    type: BillingAddressActionType.ContinueAsGuestRequested;\n}\n\nexport interface ContinueAsGuestSucceeded extends Action<Checkout> {\n    type: BillingAddressActionType.ContinueAsGuestSucceeded;\n}\n\nexport interface ContinueAsGuestFailed extends Action<Error> {\n    type: BillingAddressActionType.ContinueAsGuestFailed;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadPaymentMethodAction } from '../payment';\n\nimport { CheckoutButtonMethodType } from './strategies';\n\nexport enum CheckoutButtonActionType {\n    InitializeButtonFailed = 'INITIALIZE_BUTTON_FAILED',\n    InitializeButtonRequested = 'INITIALIZE_BUTTON_REQUESTED',\n    InitializeButtonSucceeded = 'INITIALIZE_BUTTON_SUCCEEDED',\n\n    DeinitializeButtonFailed = 'DEINITIALIZE_BUTTON_FAILED',\n    DeinitializeButtonRequested = 'DEINITIALIZE_BUTTON_REQUESTED',\n    DeinitializeButtonSucceeded = 'DEINITIALIZE_BUTTON_SUCCEEDED',\n}\n\nexport type CheckoutButtonAction = InitializeButtonAction | DeinitializeButtonAction;\n\nexport type InitializeButtonAction =\n    InitializeButtonRequestedAction |\n    InitializeButtonSucceededAction |\n    InitializeButtonFailedAction |\n    LoadPaymentMethodAction;\n\nexport type DeinitializeButtonAction =\n    DeinitializeButtonRequestedAction |\n    DeinitializeButtonSucceededAction |\n    DeinitializeButtonFailedAction;\n\nexport interface CheckoutButtonActionMeta {\n    methodId: CheckoutButtonMethodType;\n}\n\nexport interface InitializeButtonActionMeta extends CheckoutButtonActionMeta {\n    containerId: string;\n}\n\nexport interface InitializeButtonRequestedAction extends Action<undefined, InitializeButtonActionMeta> {\n    type: CheckoutButtonActionType.InitializeButtonRequested;\n}\n\nexport interface InitializeButtonSucceededAction extends Action<undefined, InitializeButtonActionMeta> {\n    type: CheckoutButtonActionType.InitializeButtonSucceeded;\n}\n\nexport interface InitializeButtonFailedAction extends Action<Error, InitializeButtonActionMeta> {\n    type: CheckoutButtonActionType.InitializeButtonFailed;\n}\n\nexport interface DeinitializeButtonRequestedAction extends Action<undefined, CheckoutButtonActionMeta> {\n    type: CheckoutButtonActionType.DeinitializeButtonRequested;\n}\n\nexport interface DeinitializeButtonSucceededAction extends Action<undefined, CheckoutButtonActionMeta> {\n    type: CheckoutButtonActionType.DeinitializeButtonSucceeded;\n}\n\nexport interface DeinitializeButtonFailedAction extends Action<Error, CheckoutButtonActionMeta> {\n    type: CheckoutButtonActionType.DeinitializeButtonFailed;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Checkout } from '../checkout';\nimport { StorefrontErrorResponseBody } from '../common/error';\nimport { RequestError } from '../common/error/errors';\n\nexport enum CouponActionType {\n    ApplyCouponRequested = 'APPLY_COUPON_REQUESTED',\n    ApplyCouponSucceeded = 'APPLY_COUPON_SUCCEEDED',\n    ApplyCouponFailed = 'APPLY_COUPON_FAILED',\n\n    RemoveCouponRequested = 'REMOVE_COUPON_REQUESTED',\n    RemoveCouponSucceeded = 'REMOVE_COUPON_SUCCEEDED',\n    RemoveCouponFailed = 'REMOVE_COUPON_FAILED',\n}\n\nexport type CouponAction =\n    ApplyCouponAction |\n    RemoveCouponAction;\n\nexport type ApplyCouponAction =\n    ApplyCouponRequestedAction |\n    ApplyCouponSucceededAction |\n    ApplyCouponFailedAction;\n\nexport type RemoveCouponAction =\n    RemoveCouponRequestedAction |\n    RemoveCouponSucceededAction |\n    RemoveCouponFailedAction;\n\nexport interface ApplyCouponRequestedAction extends Action {\n    type: CouponActionType.ApplyCouponRequested;\n}\n\nexport interface ApplyCouponSucceededAction extends Action<Checkout> {\n    type: CouponActionType.ApplyCouponSucceeded;\n}\n\nexport interface ApplyCouponFailedAction extends Action<RequestError<StorefrontErrorResponseBody>> {\n    type: CouponActionType.ApplyCouponFailed;\n}\n\nexport interface RemoveCouponRequestedAction extends Action {\n    type: CouponActionType.RemoveCouponRequested;\n}\n\nexport interface RemoveCouponSucceededAction extends Action<Checkout> {\n    type: CouponActionType.RemoveCouponSucceeded;\n}\n\nexport interface RemoveCouponFailedAction extends Action<RequestError> {\n    type: CouponActionType.RemoveCouponFailed;\n}\n","import { setPrototypeOf } from '../../utility';\n\nimport CustomError from './custom-error';\n\n/**\n * This error type should not be constructed directly. It is a base class for\n * all custom errors thrown in this library.\n */\nexport default abstract class StandardError extends Error implements CustomError {\n    name = 'StandardError';\n    type = 'standard';\n\n    constructor(message?: string) {\n        super(message || 'An unexpected error has occurred.');\n\n        setPrototypeOf(this, new.target.prototype);\n\n        if (typeof Error.captureStackTrace === 'function') {\n            Error.captureStackTrace(this, new.target);\n        } else {\n            this.stack = (new Error(this.message)).stack;\n        }\n    }\n}\n","export default function setPrototypeOf(object: any, prototype: object) {\n    if (Object.setPrototypeOf) {\n        Object.setPrototypeOf(object, prototype);\n    } else {\n        object.__proto__ = prototype;\n    }\n\n    return object;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadCheckoutAction } from '../checkout';\nimport { SpamProtectionAction } from '../spam-protection';\n\nimport Customer from './customer';\nimport { InternalCustomerResponseData } from './internal-customer-responses';\n\nexport enum CustomerActionType {\n    SignInCustomerRequested = 'SIGN_IN_CUSTOMER_REQUESTED',\n    SignInCustomerSucceeded = 'SIGN_IN_CUSTOMER_SUCCEEDED',\n    SignInCustomerFailed = 'SIGN_IN_CUSTOMER_FAILED',\n\n    SignOutCustomerRequested = 'SIGN_OUT_CUSTOMER_REQUESTED',\n    SignOutCustomerSucceeded = 'SIGN_OUT_CUSTOMER_SUCCEEDED',\n    SignOutCustomerFailed = 'SIGN_OUT_CUSTOMER_FAILED',\n\n    CreateCustomerRequested = 'CREATE_CUSTOMER_REQUESTED',\n    CreateCustomerSucceeded = 'CREATE_CUSTOMER_SUCCEEDED',\n    CreateCustomerFailed = 'CREATE_CUSTOMER_FAILED',\n\n    CreateCustomerAddressRequested = 'CREATE_CUSTOMER_ADDRESS_REQUESTED',\n    CreateCustomerAddressSucceeded = 'CREATE_CUSTOMER_ADDRESS_SUCCEEDED',\n    CreateCustomerAddressFailed = 'CREATE_CUSTOMER_ADDRESS_FAILED',\n}\n\nexport type CustomerAction =\n    SignInCustomerAction |\n    SignOutCustomerAction |\n    CreateCustomerAddressAction |\n    CreateCustomerAction;\n\nexport type CreateCustomerAction =\n    CreateCustomerRequestedAction |\n    CreateCustomerSucceededAction |\n    CreateCustomerFailedAction |\n    SpamProtectionAction |\n    LoadCheckoutAction;\n\nexport type CreateCustomerAddressAction =\n    CreateCustomerAddressRequestedAction |\n    CreateCustomerAddressSucceededAction |\n    CreateCustomerAddressFailedAction |\n    LoadCheckoutAction;\n\nexport type SignInCustomerAction =\n    SignInCustomerRequestedAction |\n    SignInCustomerSucceededAction |\n    SignInCustomerFailedAction |\n    LoadCheckoutAction;\n\nexport type SignOutCustomerAction =\n    SignOutCustomerRequestedAction |\n    SignOutCustomerSucceededAction |\n    SignOutCustomerFailedAction |\n    LoadCheckoutAction;\n\nexport interface SignInCustomerRequestedAction extends Action {\n    type: CustomerActionType.SignInCustomerRequested;\n}\n\nexport interface SignInCustomerSucceededAction extends Action<InternalCustomerResponseData> {\n    type: CustomerActionType.SignInCustomerSucceeded;\n}\n\nexport interface SignInCustomerFailedAction extends Action<Error> {\n    type: CustomerActionType.SignInCustomerFailed;\n}\n\nexport interface SignOutCustomerRequestedAction extends Action {\n    type: CustomerActionType.SignOutCustomerRequested;\n}\n\nexport interface SignOutCustomerSucceededAction extends Action<InternalCustomerResponseData> {\n    type: CustomerActionType.SignOutCustomerSucceeded;\n}\n\nexport interface SignOutCustomerFailedAction extends Action<Error> {\n    type: CustomerActionType.SignOutCustomerFailed;\n}\n\nexport interface CreateCustomerRequestedAction extends Action {\n    type: CustomerActionType.CreateCustomerRequested;\n}\n\nexport interface CreateCustomerSucceededAction extends Action {\n    type: CustomerActionType.CreateCustomerSucceeded;\n}\n\nexport interface CreateCustomerFailedAction extends Action<Error> {\n    type: CustomerActionType.CreateCustomerFailed;\n}\n\nexport interface CreateCustomerAddressRequestedAction extends Action {\n    type: CustomerActionType.CreateCustomerAddressRequested;\n}\n\nexport interface CreateCustomerAddressSucceededAction extends Action<Customer> {\n    type: CustomerActionType.CreateCustomerAddressSucceeded;\n}\n\nexport interface CreateCustomerAddressFailedAction extends Action<Error> {\n    type: CustomerActionType.CreateCustomerAddressFailed;\n}\n","import EmbeddedCheckoutError from './embedded-checkout-error';\nimport { EmbeddedContentOptions } from './iframe-content';\n\nexport enum EmbeddedCheckoutEventType {\n    CheckoutComplete = 'CHECKOUT_COMPLETE',\n    CheckoutError = 'CHECKOUT_ERROR',\n    CheckoutLoaded = 'CHECKOUT_LOADED',\n    FrameError = 'FRAME_ERROR',\n    FrameLoaded = 'FRAME_LOADED',\n    SignedOut = 'SIGNED_OUT',\n}\n\nexport interface EmbeddedCheckoutEventMap {\n    [EmbeddedCheckoutEventType.CheckoutComplete]: EmbeddedCheckoutCompleteEvent;\n    [EmbeddedCheckoutEventType.CheckoutError]: EmbeddedCheckoutErrorEvent;\n    [EmbeddedCheckoutEventType.CheckoutLoaded]: EmbeddedCheckoutLoadedEvent;\n    [EmbeddedCheckoutEventType.FrameError]: EmbeddedCheckoutFrameErrorEvent;\n    [EmbeddedCheckoutEventType.FrameLoaded]: EmbeddedCheckoutFrameLoadedEvent;\n    [EmbeddedCheckoutEventType.SignedOut]: EmbeddedCheckoutSignedOutEvent;\n}\n\nexport type EmbeddedCheckoutEvent = (\n    EmbeddedCheckoutCompleteEvent |\n    EmbeddedCheckoutErrorEvent |\n    EmbeddedCheckoutFrameErrorEvent |\n    EmbeddedCheckoutFrameLoadedEvent |\n    EmbeddedCheckoutLoadedEvent |\n    EmbeddedCheckoutSignedOutEvent\n);\n\nexport interface EmbeddedCheckoutCompleteEvent {\n    type: EmbeddedCheckoutEventType.CheckoutComplete;\n}\n\nexport interface EmbeddedCheckoutErrorEvent {\n    type: EmbeddedCheckoutEventType.CheckoutError;\n    payload: EmbeddedCheckoutError;\n}\n\nexport interface EmbeddedCheckoutLoadedEvent {\n    type: EmbeddedCheckoutEventType.CheckoutLoaded;\n}\n\nexport interface EmbeddedCheckoutFrameErrorEvent {\n    type: EmbeddedCheckoutEventType.FrameError;\n    payload: EmbeddedCheckoutError;\n}\n\nexport interface EmbeddedCheckoutFrameLoadedEvent {\n    type: EmbeddedCheckoutEventType.FrameLoaded;\n    payload?: EmbeddedContentOptions;\n}\n\nexport interface EmbeddedCheckoutSignedOutEvent {\n    type: EmbeddedCheckoutEventType.SignedOut;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { VaultAccessToken } from './instrument';\nimport { InstrumentsResponseBody } from './instrument-response-body';\n\nexport enum InstrumentActionType {\n    LoadInstrumentsRequested = 'LOAD_INSTRUMENTS_REQUESTED',\n    LoadInstrumentsSucceeded = 'LOAD_INSTRUMENTS_SUCCEEDED',\n    LoadInstrumentsFailed = 'LOAD_INSTRUMENTS_FAILED',\n\n    DeleteInstrumentRequested = 'DELETE_INSTRUMENT_REQUESTED',\n    DeleteInstrumentSucceeded = 'DELETE_INSTRUMENT_SUCCEEDED',\n    DeleteInstrumentFailed = 'DELETE_INSTRUMENT_FAILED',\n}\n\nexport type InstrumentAction =\n    LoadInstrumentsAction |\n    DeleteInstrumentAction;\n\nexport type LoadInstrumentsAction =\n    LoadInstrumentsRequestedAction |\n    LoadInstrumentsSucceededAction |\n    LoadInstrumentsFailedAction;\n\nexport type DeleteInstrumentAction =\n    DeleteInstrumentRequestedAction |\n    DeleteInstrumentSucceededAction |\n    DeleteInstrumentFailedAction;\n\nexport interface LoadInstrumentsRequestedAction extends Action {\n    type: InstrumentActionType.LoadInstrumentsRequested;\n}\n\nexport interface LoadInstrumentsSucceededAction extends Action<InstrumentsResponseBody, VaultAccessToken> {\n    type: InstrumentActionType.LoadInstrumentsSucceeded;\n}\n\nexport interface LoadInstrumentsFailedAction extends Action<Error> {\n    type: InstrumentActionType.LoadInstrumentsFailed;\n}\n\nexport interface DeleteInstrumentRequestedAction extends Action {\n    type: InstrumentActionType.DeleteInstrumentRequested;\n}\n\nexport interface DeleteInstrumentSucceededAction extends Action<InstrumentsResponseBody, VaultAccessToken & { instrumentId: string }> {\n    type: InstrumentActionType.DeleteInstrumentSucceeded;\n}\n\nexport interface DeleteInstrumentFailedAction extends Action<Error> {\n    type: InstrumentActionType.DeleteInstrumentFailed;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Checkout } from '../checkout';\nimport { StorefrontErrorResponseBody } from '../common/error';\nimport { RequestError } from '../common/error/errors';\n\nexport enum GiftCertificateActionType {\n    ApplyGiftCertificateRequested = 'APPLY_GIFT_CERTIFICATE_REQUESTED',\n    ApplyGiftCertificateSucceeded = 'APPLY_GIFT_CERTIFICATE_SUCCEEDED',\n    ApplyGiftCertificateFailed = 'APPLY_GIFT_CERTIFICATE_FAILED',\n\n    RemoveGiftCertificateRequested = 'REMOVE_GIFT_CERTIFICATE_REQUESTED',\n    RemoveGiftCertificateSucceeded = 'REMOVE_GIFT_CERTIFICATE_SUCCEEDED',\n    RemoveGiftCertificateFailed = 'REMOVE_GIFT_CERTIFICATE_FAILED',\n}\n\nexport type GiftCertificateAction =\n    ApplyGiftCertificateAction |\n    RemoveGiftCertificateAction;\n\nexport type ApplyGiftCertificateAction =\n    ApplyGiftCertificateRequestedAction |\n    ApplyGiftCertificateSucceededAction |\n    ApplyGiftCertificateFailedAction;\n\nexport type RemoveGiftCertificateAction =\n    RemoveGiftCertificateRequestedAction |\n    RemoveGiftCertificateSucceededAction |\n    RemoveGiftCertificateFailedAction;\n\nexport interface ApplyGiftCertificateRequestedAction extends Action {\n    type: GiftCertificateActionType.ApplyGiftCertificateRequested;\n}\n\nexport interface ApplyGiftCertificateSucceededAction extends Action<Checkout> {\n    type: GiftCertificateActionType.ApplyGiftCertificateSucceeded;\n}\n\nexport interface ApplyGiftCertificateFailedAction extends Action<RequestError<StorefrontErrorResponseBody>> {\n    type: GiftCertificateActionType.ApplyGiftCertificateFailed;\n}\n\nexport interface RemoveGiftCertificateRequestedAction extends Action {\n    type: GiftCertificateActionType.RemoveGiftCertificateRequested;\n}\n\nexport interface RemoveGiftCertificateSucceededAction extends Action<Checkout> {\n    type: GiftCertificateActionType.RemoveGiftCertificateSucceeded;\n}\n\nexport interface RemoveGiftCertificateFailedAction extends Action<RequestError<StorefrontErrorResponseBody>> {\n    type: GiftCertificateActionType.RemoveGiftCertificateFailed;\n}\n","import { Checkout } from '../../../checkout';\nimport PaymentMethod from '../../payment-method';\nimport { BraintreeModuleCreator, GooglePayBraintreeSDK } from '../braintree';\n\nexport type EnvironmentType = 'PRODUCTION' | 'TEST';\nexport type TokenizeType = 'AndroidPayCard' | 'CreditCard' | 'CARD';\n\nexport interface GooglePayInitializer {\n    initialize(checkout: Checkout, paymentMethod: PaymentMethod, hasShippingAddress: boolean, publishableKey?: string): Promise<GooglePayPaymentDataRequestV2>;\n    teardown(): Promise<void>;\n    parseResponse(paymentData: GooglePaymentData): Promise<TokenizePayload>;\n}\n\nexport interface GooglePayCreator extends BraintreeModuleCreator<GooglePayBraintreeSDK> {}\n\nexport interface GooglePayPaymentOptions {\n    environment: EnvironmentType;\n}\n\nexport interface GooglePayIsReadyToPayResponse {\n    result: boolean;\n    paymentMethodPresend?: boolean;\n}\n\nexport interface GooglePaySDK {\n    payments: {\n        api: {\n            PaymentsClient: new(options: GooglePayPaymentOptions) => GooglePayClient;\n        };\n    };\n}\n\nexport interface GooglePayClient {\n    isReadyToPay(options: object): Promise<GooglePayIsReadyToPayResponse>;\n    loadPaymentData(paymentDataRequest: GooglePayPaymentDataRequestV2): Promise<GooglePaymentData>;\n    createButton(options: { [key: string]: string | object }): HTMLElement;\n}\n\nexport interface GooglePayHostWindow extends Window {\n    google?: GooglePaySDK;\n}\n\nexport interface TokenizePayload {\n    nonce: string;\n    details: {\n        cardType: string;\n        lastFour: string;\n        lastTwo?: string;\n    };\n    description?: string;\n    type: TokenizeType;\n    binData?: {\n        commercial: string;\n        countryOfIssuance: string;\n        debit: string;\n        durbinRegulated: string;\n        healthcare: string;\n        issuingBank: string;\n        payroll: string;\n        prepaid: string;\n        productId: string;\n    };\n}\n\nexport interface GooglePaymentData {\n    apiVersion: number;\n    apiVersionMinor: number;\n    paymentMethodData: {\n        description: string;\n        info: {\n            cardDetails: string;\n            cardNetwork: string;\n            billingAddress: GooglePayAddress;\n        };\n        tokenizationData: {\n            token: string;\n            type: string;\n        };\n        type: TokenizeType;\n    };\n    shippingAddress: GooglePayAddress;\n    email: string;\n}\n\nexport interface GooglePayAddress {\n    address1: string;\n    address2: string;\n    address3: string;\n    administrativeArea: string;\n    companyName: string;\n    countryCode: string;\n    locality: string;\n    name: string;\n    postalCode: string;\n    sortingCode: string;\n    phoneNumber: string;\n}\n\nexport interface GooglePaymentsError {\n    statusCode: string;\n    statusMessage?: string;\n}\n\nexport interface PaymentMethodData {\n    methodId: string;\n    paymentData: {\n        method: string;\n        nonce: string;\n        cardInformation: {\n            type: string;\n            number: string;\n        };\n    };\n}\n\nexport enum ButtonType {\n    Long = 'long',\n    Short = 'short',\n}\nexport enum ButtonColor {\n    Default = 'default',\n    Black = 'black',\n    White = 'white',\n}\n\nexport interface TokenizationSpecification {\n    type: string;\n    parameters: {\n        gateway: string;\n        gatewayMerchantId?: string;\n        'braintree:apiVersion'?: string;\n        'braintree:clientKey'?: string;\n        'braintree:merchantId'?: string;\n        'braintree:sdkVersion'?: string;\n        'braintree:authorizationFingerprint'?: string;\n        'stripe:version'?: string;\n        'stripe:publishableKey'?: string;\n    };\n}\n\nexport enum BillingAddressFormat {\n    /*\n     * Name, country code, and postal code (default).\n     */\n    Min = 'MIN',\n    /*\n     * Name, street address, locality, region, country code, and postal code.\n     */\n    Full = 'FULL',\n}\n\nexport interface GooglePayPaymentDataRequestV2 {\n    apiVersion: number;\n    apiVersionMinor: number;\n    merchantInfo: {\n        authJwt?: string;\n        merchantId?: string;\n        merchantName?: string;\n    };\n    allowedPaymentMethods: [{\n        type: string;\n        parameters: {\n            allowedAuthMethods: string[];\n            allowedCardNetworks: string[];\n            allowPrepaidCards?: boolean;\n            billingAddressRequired?: boolean;\n            billingAddressParameters?: {\n                format?: BillingAddressFormat;\n                phoneNumberRequired?: boolean;\n            };\n        };\n        tokenizationSpecification?: TokenizationSpecification;\n    }];\n    transactionInfo: {\n        currencyCode: string;\n        countryCode?: string;\n        totalPriceStatus: string;\n        totalPrice?: string;\n        checkoutOption?: string;\n    };\n    emailRequired?: boolean;\n    shippingAddressRequired?: boolean;\n    shippingAddressParameters?: {\n        allowedCountryCodes?: string[];\n        phoneNumberRequired?: boolean;\n    };\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { AmazonPayRemoteCheckout } from './methods';\n\nexport enum RemoteCheckoutActionType {\n    InitializeRemoteBillingRequested = 'INITIALIZE_REMOTE_BILLING_REQUESTED',\n    InitializeRemoteBillingSucceeded = 'INITIALIZE_REMOTE_BILLING_SUCCEEDED',\n    InitializeRemoteBillingFailed = 'INITIALIZE_REMOTE_BILLING_FAILED',\n\n    InitializeRemoteShippingRequested = 'INITIALIZE_REMOTE_SHIPPING_REQUESTED',\n    InitializeRemoteShippingSucceeded = 'INITIALIZE_REMOTE_SHIPPING_SUCCEEDED',\n    InitializeRemoteShippingFailed = 'INITIALIZE_REMOTE_SHIPPING_FAILED',\n\n    InitializeRemotePaymentRequested = 'INITIALIZE_REMOTE_PAYMENT_REQUESTED',\n    InitializeRemotePaymentSucceeded = 'INITIALIZE_REMOTE_PAYMENT_SUCCEEDED',\n    InitializeRemotePaymentFailed = 'INITIALIZE_REMOTE_PAYMENT_FAILED',\n\n    LoadRemoteSettingsRequested = 'LOAD_REMOTE_SETTINGS_REQUESTED',\n    LoadRemoteSettingsSucceeded = 'LOAD_REMOTE_SETTINGS_SUCCEEDED',\n    LoadRemoteSettingsFailed = 'LOAD_REMOTE_SETTINGS_FAILED',\n\n    SignOutRemoteCustomerRequested = 'SIGN_OUT_REMOTE_CUSTOMER_REQUESTED',\n    SignOutRemoteCustomerSucceeded = 'SIGN_OUT_REMOTE_CUSTOMER_SUCCEEDED',\n    SignOutRemoteCustomerFailed = 'SIGN_OUT_REMOTE_CUSTOMER_FAILED',\n\n    UpdateRemoteCheckout = 'UPDATE_REMOTE_CHECKOUT',\n}\n\nexport type RemoteCheckoutAction = InitializeRemoteBillingAction |\n    InitializeRemoteShippingAction |\n    InitializeRemotePaymentAction |\n    SignOutRemoteCustomerAction |\n    LoadRemoteSettingsAction |\n    UpdateRemoteCheckoutAction;\n\nexport type InitializeRemoteBillingAction = InitializeRemoteBillingSucceededAction |\n    InitializeRemoteBillingFailedAction |\n    InitializeRemoteBillingRequestedAction;\n\nexport interface InitializeRemoteBillingSucceededAction extends Action<AmazonPayRemoteCheckout> {\n    type: RemoteCheckoutActionType.InitializeRemoteBillingSucceeded;\n}\n\nexport interface InitializeRemoteBillingFailedAction extends Action {\n    type: RemoteCheckoutActionType.InitializeRemoteBillingFailed;\n}\n\nexport interface InitializeRemoteBillingRequestedAction extends Action {\n    type: RemoteCheckoutActionType.InitializeRemoteBillingRequested;\n}\n\nexport type InitializeRemoteShippingAction = InitializeRemoteShippingSucceededAction |\n    InitializeRemoteShippingFailedAction |\n    InitializeRemoteShippingRequestedAction;\n\nexport interface InitializeRemoteShippingSucceededAction extends Action<AmazonPayRemoteCheckout> {\n    type: RemoteCheckoutActionType.InitializeRemoteShippingSucceeded;\n}\n\nexport interface InitializeRemoteShippingFailedAction extends Action {\n    type: RemoteCheckoutActionType.InitializeRemoteShippingFailed;\n}\n\nexport interface InitializeRemoteShippingRequestedAction extends Action {\n    type: RemoteCheckoutActionType.InitializeRemoteShippingRequested;\n}\n\nexport type InitializeRemotePaymentAction = InitializeRemotePaymentSucceededAction |\n    InitializeRemotePaymentFailedAction |\n    InitializeRemotePaymentRequestedAction;\n\nexport interface InitializeRemotePaymentSucceededAction extends Action {\n    type: RemoteCheckoutActionType.InitializeRemotePaymentSucceeded;\n}\n\nexport interface InitializeRemotePaymentFailedAction extends Action {\n    type: RemoteCheckoutActionType.InitializeRemotePaymentFailed;\n}\n\nexport interface InitializeRemotePaymentRequestedAction extends Action {\n    type: RemoteCheckoutActionType.InitializeRemotePaymentRequested;\n}\n\nexport type SignOutRemoteCustomerAction = SignOutRemoteCustomerSucceededAction |\n    SignOutRemoteCustomerFailedAction |\n    SignOutRemoteCustomerRequestedAction;\n\nexport interface SignOutRemoteCustomerSucceededAction extends Action {\n    type: RemoteCheckoutActionType.SignOutRemoteCustomerSucceeded;\n}\n\nexport interface SignOutRemoteCustomerFailedAction extends Action {\n    type: RemoteCheckoutActionType.SignOutRemoteCustomerFailed;\n}\n\nexport interface SignOutRemoteCustomerRequestedAction extends Action {\n    type: RemoteCheckoutActionType.SignOutRemoteCustomerRequested;\n}\n\nexport type LoadRemoteSettingsAction = LoadRemoteSettingsSucceededAction |\n    LoadRemoteSettingsRequestedAction |\n    LoadRemoteSettingsFailedAction;\n\nexport interface LoadRemoteSettingsSucceededAction extends Action {\n    type: RemoteCheckoutActionType.LoadRemoteSettingsSucceeded;\n}\n\nexport interface LoadRemoteSettingsRequestedAction extends Action {\n    type: RemoteCheckoutActionType.LoadRemoteSettingsRequested;\n}\n\nexport interface LoadRemoteSettingsFailedAction extends Action {\n    type: RemoteCheckoutActionType.LoadRemoteSettingsFailed;\n}\n\nexport interface UpdateRemoteCheckoutAction extends Action {\n    type: RemoteCheckoutActionType.UpdateRemoteCheckout;\n}\n","module.exports = require(\"@bigcommerce/script-loader\");","enum ContentType {\n    Json = 'application/json',\n    JsonV1 = 'application/vnd.bc.v1+json',\n}\n\nexport default ContentType;\n","export const ACKNOWLEDGE = 'ACKNOWLEDGE';\nexport const FINALIZE = 'FINALIZE';\nexport const INITIALIZE = 'INITIALIZE';\n","module.exports = require(\"card-validator\");","import { Response } from '@bigcommerce/request-sender';\n\nimport StandardError from './standard-error';\n\nconst DEFAULT_RESPONSE = {\n    body: {},\n    headers: {},\n    status: 0,\n};\n\n/**\n * Throw this error if we are unable to make a request to the server. It wraps\n * any server response into a JS error object.\n */\nexport default class RequestError<TBody = any> extends StandardError {\n    body: TBody | {};\n    headers: { [key: string]: any };\n    errors: Array<{ code: string; message?: string }>;\n    status: number;\n\n    constructor(\n        response?: Response<TBody | {}>,\n        { message, errors }: {\n            message?: string;\n            errors?: Array<{ code: string; message?: string }>;\n        } = {}\n    ) {\n        const { body, headers, status } = response || DEFAULT_RESPONSE;\n\n        super(message || 'An unexpected error has occurred.');\n\n        this.name = 'RequestError';\n        this.type = 'request';\n        this.body = body;\n        this.headers = headers;\n        this.status = status;\n        this.errors = errors || [];\n    }\n}\n","import { FormattedPayload, FormattedVaultedInstrument, HostedVaultedInstrument, PaymentInstrument, VaultedInstrument } from './payment';\n\nexport default function isVaultedInstrument(instrument: PaymentInstrument): instrument is VaultedInstrument {\n    return Boolean((instrument as VaultedInstrument).instrumentId);\n}\n\nexport function isHostedVaultedInstrument(instrument: PaymentInstrument): instrument is HostedVaultedInstrument {\n    return (\n        Boolean((instrument as HostedVaultedInstrument).instrumentId) &&\n        !instrument.hasOwnProperty('ccNumber') &&\n        !instrument.hasOwnProperty('ccCvv')\n    );\n}\n\nexport function isFormattedVaultedInstrument(instrument: PaymentInstrument): instrument is FormattedPayload<FormattedVaultedInstrument> {\n    const formattedInstrument = (instrument as FormattedPayload<FormattedVaultedInstrument>).formattedPayload;\n\n    if (!formattedInstrument) {\n        return false;\n    }\n\n    return typeof formattedInstrument.bigpay_token === 'string' ||\n        Boolean(formattedInstrument.bigpay_token && formattedInstrument.bigpay_token.token);\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport Config from './config';\n\nexport enum ConfigActionType {\n    LoadConfigRequested = 'LOAD_CONFIG_REQUESTED',\n    LoadConfigSucceeded = 'LOAD_CONFIG_SUCCEEDED',\n    LoadConfigFailed = 'LOAD_CONFIG_FAILED',\n}\n\nexport type LoadConfigAction =\n    LoadConfigRequestedAction |\n    LoadConfigSucceededAction |\n    LoadConfigFailedAction;\n\nexport interface LoadConfigRequestedAction extends Action {\n    type: ConfigActionType.LoadConfigRequested;\n}\n\nexport interface LoadConfigSucceededAction extends Action<Config> {\n    type: ConfigActionType.LoadConfigSucceeded;\n}\n\nexport interface LoadConfigFailedAction extends Action<Error> {\n    type: ConfigActionType.LoadConfigFailed;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { FormFields } from './form-field';\n\nexport enum FormFieldsActionType {\n    LoadFormFieldsRequested = 'LOAD_FORM_FIELDS_REQUESTED',\n    LoadFormFieldsSucceeded = 'LOAD_FORM_FIELDS_SUCCEEDED',\n    LoadFormFieldsFailed = 'LOAD_FORM_FIELDS_FAILED',\n}\n\nexport type LoadFormFieldsAction =\n    LoadFormFieldsRequestedAction |\n    LoadFormFieldsSucceededAction |\n    LoadFormFieldsFailedAction;\n\nexport interface LoadFormFieldsRequestedAction extends Action {\n    type: FormFieldsActionType.LoadFormFieldsRequested;\n}\n\nexport interface LoadFormFieldsSucceededAction extends Action<FormFields> {\n    type: FormFieldsActionType.LoadFormFieldsSucceeded;\n}\n\nexport interface LoadFormFieldsFailedAction extends Action<Error> {\n    type: FormFieldsActionType.LoadFormFieldsFailed;\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when the client library of a payment method fails\n * to load, or for some reason, it is inaccessible.\n */\nexport default class PaymentMethodClientUnavailableError extends StandardError {\n    constructor(message?: string) {\n        super(message || 'Unable to proceed because the client library of a payment method is not loaded or ready to be used.');\n\n        this.name = 'PaymentMethodClientUnavailableError';\n        this.type = 'payment_method_client_unavailable';\n    }\n}\n","import { isPlainObject as lodashIsPlainObject } from 'lodash';\n\n// We need this wrapper because Lodash's version doesn't act as a type guard\nexport default function isPlainObject(value: any): value is object {\n    return lodashIsPlainObject(value);\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport Country from './country';\n\nexport enum CountryActionType {\n    LoadCountriesRequested = 'LOAD_COUNTRIES_REQUESTED',\n    LoadCountriesSucceeded = 'LOAD_COUNTRIES_SUCCEEDED',\n    LoadCountriesFailed = 'LOAD_COUNTRIES_FAILED',\n}\n\nexport type LoadCountriesAction =\n    LoadCountriesRequestedAction |\n    LoadCountriesSucceededAction |\n    LoadCountriesFailedAction;\n\nexport interface LoadCountriesRequestedAction extends Action {\n    type: CountryActionType.LoadCountriesRequested;\n}\n\nexport interface LoadCountriesSucceededAction extends Action<Country[]> {\n    type: CountryActionType.LoadCountriesSucceeded;\n}\n\nexport interface LoadCountriesFailedAction extends Action<Error> {\n    type: CountryActionType.LoadCountriesFailed;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Country } from '../geography';\n\nexport enum ShippingCountryActionType {\n    LoadShippingCountriesRequested = 'LOAD_SHIPPING_COUNTRIES_REQUESTED',\n    LoadShippingCountriesSucceeded = 'LOAD_SHIPPING_COUNTRIES_SUCCEEDED',\n    LoadShippingCountriesFailed = 'LOAD_SHIPPING_COUNTRIES_FAILED',\n}\n\nexport type LoadShippingCountriesAction = LoadShippingCountriesRequestedAction |\n    LoadShippingCountriesSucceededAction |\n    LoadShippingCountriesFailedAction;\n\nexport interface LoadShippingCountriesRequestedAction extends Action {\n    type: ShippingCountryActionType.LoadShippingCountriesRequested;\n}\n\nexport interface LoadShippingCountriesSucceededAction extends Action<Country[]> {\n    type: ShippingCountryActionType.LoadShippingCountriesSucceeded;\n}\n\nexport interface LoadShippingCountriesFailedAction extends Action<Error> {\n    type: ShippingCountryActionType.LoadShippingCountriesFailed;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { SignInEmail } from './signin-email';\n\nexport enum SignInEmailActionType {\n    SendSignInEmailRequested = 'SEND_SIGNIN_EMAIL_REQUESTED',\n    SendSignInEmailSucceeded = 'SEND_SIGNIN_EMAIL_SUCCEEDED',\n    SendSignInEmailFailed = 'SEND_SIGNIN_EMAIL_FAILED',\n}\nexport type SendSignInEmailAction =\n    SendSignInEmailRequestedAction |\n    SendSignInEmailSucceededAction |\n    SendSignInEmailFailedAction;\n\nexport interface SendSignInEmailRequestedAction extends Action {\n    type: SignInEmailActionType.SendSignInEmailRequested;\n}\n\nexport interface SendSignInEmailSucceededAction extends Action<SignInEmail> {\n    type: SignInEmailActionType.SendSignInEmailSucceeded;\n}\n\nexport interface SendSignInEmailFailedAction extends Action<Error> {\n    type: SignInEmailActionType.SendSignInEmailFailed;\n}\n","module.exports = require(\"@bigcommerce/request-sender\");","import { Action } from '@bigcommerce/data-store';\n\nimport { Checkout } from '../checkout';\nimport { StorefrontErrorResponseBody } from '../common/error';\nimport { RequestError } from '../common/error/errors';\n\nexport enum StoreCreditActionType {\n    ApplyStoreCreditRequested = 'APPLY_STORE_CREDIT_REQUESTED',\n    ApplyStoreCreditSucceeded = 'APPLY_STORE_CREDIT_SUCCEEDED',\n    ApplyStoreCreditFailed = 'APPLY_STORE_CREDIT_FAILED',\n}\n\nexport type StoreCreditAction =\n    ApplyStoreCreditAction;\n\nexport type ApplyStoreCreditAction =\n    ApplyStoreCreditRequestedAction |\n    ApplyStoreCreditSucceededAction |\n    ApplyStoreCreditFailedAction;\n\nexport interface ApplyStoreCreditRequestedAction extends Action {\n    type: StoreCreditActionType.ApplyStoreCreditRequested;\n}\n\nexport interface ApplyStoreCreditSucceededAction extends Action<Checkout> {\n    type: StoreCreditActionType.ApplyStoreCreditSucceeded;\n}\n\nexport interface ApplyStoreCreditFailedAction extends Action<RequestError<StorefrontErrorResponseBody>> {\n    type: StoreCreditActionType.ApplyStoreCreditFailed;\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { PaymentErrorData, PaymentErrorResponseBody } from '../../common/error';\nimport HostedFieldType from '../hosted-field-type';\n\nimport HostedInputInitializeErrorData from './hosted-input-initialize-error-data';\nimport HostedInputValidateResults from './hosted-input-validate-results';\n\n// Event types\nexport enum HostedInputEventType {\n    AttachSucceeded = 'HOSTED_INPUT:ATTACH_SUCCEEDED',\n    AttachFailed = 'HOSTED_INPUT:ATTACH_FAILED',\n    BinChanged = 'HOSTED_INPUT:BIN_CHANGED',\n    Blurred = 'HOSTED_INPUT:BLURRED',\n    Changed = 'HOSTED_INPUT:CHANGED',\n    CardTypeChanged = 'HOSTED_INPUT:CARD_TYPE_CHANGED',\n    Entered = 'HOSTED_INPUT:ENTERED',\n    Focused = 'HOSTED_INPUT:FOCUSED',\n    SubmitSucceeded = 'HOSTED_INPUT:SUBMIT_SUCCEEDED',\n    SubmitFailed = 'HOSTED_INPUT:SUBMIT_FAILED',\n    Validated = 'HOSTED_INPUT:VALIDATED',\n}\n\n// Event mapping\nexport interface HostedInputEventMap {\n    [HostedInputEventType.AttachSucceeded]: HostedInputAttachSuccessEvent;\n    [HostedInputEventType.AttachFailed]: HostedInputAttachErrorEvent;\n    [HostedInputEventType.BinChanged]: HostedInputBinChangeEvent;\n    [HostedInputEventType.Blurred]: HostedInputBlurEvent;\n    [HostedInputEventType.Changed]: HostedInputChangeEvent;\n    [HostedInputEventType.CardTypeChanged]: HostedInputCardTypeChangeEvent;\n    [HostedInputEventType.Entered]: HostedInputEnterEvent;\n    [HostedInputEventType.Focused]: HostedInputFocusEvent;\n    [HostedInputEventType.SubmitSucceeded]: HostedInputSubmitSuccessEvent;\n    [HostedInputEventType.SubmitFailed]: HostedInputSubmitErrorEvent;\n    [HostedInputEventType.Validated]: HostedInputValidateEvent;\n}\n\n// Events\nexport type HostedInputEvent = (\n    HostedInputAttachSuccessEvent |\n    HostedInputAttachErrorEvent |\n    HostedInputBinChangeEvent |\n    HostedInputBlurEvent |\n    HostedInputChangeEvent |\n    HostedInputCardTypeChangeEvent |\n    HostedInputEnterEvent |\n    HostedInputFocusEvent |\n    HostedInputSubmitSuccessEvent |\n    HostedInputSubmitErrorEvent |\n    HostedInputValidateEvent\n);\n\nexport interface HostedInputAttachSuccessEvent {\n    type: HostedInputEventType.AttachSucceeded;\n}\n\nexport interface HostedInputAttachErrorEvent {\n    type: HostedInputEventType.AttachFailed;\n    payload: {\n        error: HostedInputInitializeErrorData;\n    };\n}\n\nexport interface HostedInputBinChangeEvent {\n    type: HostedInputEventType.BinChanged;\n    payload: {\n        bin?: string;\n    };\n}\n\nexport interface HostedInputBlurEvent {\n    type: HostedInputEventType.Blurred;\n    payload: {\n        fieldType: HostedFieldType;\n    };\n}\n\nexport interface HostedInputChangeEvent {\n    type: HostedInputEventType.Changed;\n    payload: {\n        fieldType: HostedFieldType;\n    };\n}\n\nexport interface HostedInputCardTypeChangeEvent {\n    type: HostedInputEventType.CardTypeChanged;\n    payload: {\n        cardType?: string;\n    };\n}\n\nexport interface HostedInputFocusEvent {\n    type: HostedInputEventType.Focused;\n    payload: {\n        fieldType: HostedFieldType;\n    };\n}\n\nexport interface HostedInputEnterEvent {\n    type: HostedInputEventType.Entered;\n    payload: {\n        fieldType: HostedFieldType;\n    };\n}\n\nexport interface HostedInputSubmitSuccessEvent {\n    type: HostedInputEventType.SubmitSucceeded;\n}\n\nexport interface HostedInputSubmitErrorEvent {\n    type: HostedInputEventType.SubmitFailed;\n    payload: {\n        error: PaymentErrorData;\n        response?: Response<PaymentErrorResponseBody>;\n    };\n}\n\nexport interface HostedInputValidateEvent {\n    type: HostedInputEventType.Validated;\n    payload: HostedInputValidateResults;\n}\n","import { InvalidArgumentError } from '../error/errors';\n\nimport Url from './url';\n\nexport default function parseUrl(url: string): Url {\n    if (!/^(https?:)?\\/\\//.test(url)) {\n        throw new InvalidArgumentError('The provided URL must be absolute.');\n    }\n\n    // new URL() is not supported in IE11, use anchor tag instead\n    const anchor = document.createElement('a');\n\n    anchor.href = url;\n\n    // IE11 returns 80 or 443 for the port number depending on the URL scheme,\n    // even if the port number is not specified in the URL.\n    const port = anchor.port && url.indexOf(`${anchor.hostname}:${anchor.port}`) !== -1 ?\n        anchor.port :\n        '';\n\n    return {\n        hash: anchor.hash,\n        hostname: anchor.hostname,\n        href: anchor.href,\n        origin: `${anchor.protocol}//${anchor.hostname}${port ? ':' + port : ''}`,\n        pathname: anchor.pathname,\n        port,\n        protocol: anchor.protocol,\n        search: anchor.search,\n    };\n}\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when a method is unable to proceed because the\n * caller has not provided all the arguments according to their requirements,\n * i.e.: if an argument is missing or it is not the expected data type.\n */\nexport default class InvalidArgumentError extends StandardError {\n    constructor(message?: string) {\n        super(message || 'Invalid arguments have been provided.');\n\n        this.name = 'InvalidArgumentError';\n        this.type = 'invalid_argument';\n    }\n}\n","import IframeEvent from './iframe-event';\n\nexport default function isIframeEvent<TEvent extends IframeEvent<TType>, TType extends string>(\n    object: any,\n    type: TType\n): object is TEvent {\n    return object.type === type;\n}\n","export const HOSTED = 'PAYMENT_TYPE_HOSTED';\nexport const OFFLINE = 'PAYMENT_TYPE_OFFLINE';\n","import { isBillingAddressLike, BillingAddress } from '../billing';\nimport { Consignment } from '../shipping';\n\nimport Address from './address';\nimport InternalAddress from './internal-address';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalAddress(\n    address: Address | BillingAddress,\n    consignments?: Consignment[]\n): InternalAddress<any> {\n    let addressId;\n\n    if (isBillingAddressLike(address)) {\n        addressId = address.id;\n    } else if (consignments && consignments.length) {\n        addressId = consignments[0].id;\n    }\n\n    return {\n        id: addressId,\n        firstName: address.firstName,\n        lastName: address.lastName,\n        company: address.company,\n        addressLine1: address.address1,\n        addressLine2: address.address2,\n        city: address.city,\n        province: address.stateOrProvince,\n        provinceCode: address.stateOrProvinceCode,\n        postCode: address.postalCode,\n        country: address.country,\n        countryCode: address.countryCode,\n        phone: address.phone,\n        customFields: address.customFields,\n    };\n}\n","export const INTERNAL_USE_ONLY = 'This API endpoint is for internal use only and may change in the future';\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadOrderAction } from '../order';\n\nimport PaymentResponseBody from './payment-response-body';\n\nexport enum PaymentActionType {\n    SubmitPaymentRequested = 'SUBMIT_PAYMENT_REQUESTED',\n    SubmitPaymentSucceeded = 'SUBMIT_PAYMENT_SUCCEEDED',\n    SubmitPaymentFailed = 'SUBMIT_PAYMENT_FAILED',\n\n    InitializeOffsitePaymentRequested = 'INITIALIZE_OFFSITE_PAYMENT_REQUESTED',\n    InitializeOffsitePaymentSucceeded = 'INITIALIZE_OFFSITE_PAYMENT_SUCCEEDED',\n    InitializeOffsitePaymentFailed = 'INITIALIZE_OFFSITE_PAYMENT_FAILED',\n}\n\nexport type PaymentAction = SubmitPaymentAction |\n    InitializeOffsitePaymentAction;\n\nexport type SubmitPaymentAction =\n    SubmitPaymentRequestedAction |\n    SubmitPaymentSucceededAction |\n    SubmitPaymentFailedAction |\n    LoadOrderAction;\n\nexport type InitializeOffsitePaymentAction =\n    InitializeOffsitePaymentRequestedAction |\n    InitializeOffsitePaymentSucceededAction |\n    InitializeOffsitePaymentFailedAction;\n\nexport interface SubmitPaymentRequestedAction extends Action {\n    type: PaymentActionType.SubmitPaymentRequested;\n}\n\nexport interface SubmitPaymentSucceededAction extends Action<PaymentResponseBody> {\n    type: PaymentActionType.SubmitPaymentSucceeded;\n}\n\nexport interface SubmitPaymentFailedAction extends Action<Error> {\n    type: PaymentActionType.SubmitPaymentFailed;\n}\n\nexport interface InitializeOffsitePaymentRequestedAction extends Action {\n    type: PaymentActionType.InitializeOffsitePaymentRequested;\n}\n\nexport interface InitializeOffsitePaymentSucceededAction extends Action {\n    type: PaymentActionType.InitializeOffsitePaymentSucceeded;\n}\n\nexport interface InitializeOffsitePaymentFailedAction extends Action<Error> {\n    type: PaymentActionType.InitializeOffsitePaymentFailed;\n}\n","import { uniq } from 'lodash';\n\nexport default function joinIncludes<T>(includes: T[]): string {\n    return uniq(includes).join(',');\n}\n","import InternalLineItem from './internal-line-item';\nimport { LineItem } from './line-item';\nimport LineItemMap from './line-item-map';\nimport mapGiftCertificateToInternalLineItem from './map-gift-certificate-to-internal-line-item';\nimport mapToInternalLineItem from './map-to-internal-line-item';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalLineItems(\n    itemMap: LineItemMap,\n    decimalPlaces: number,\n    idKey: keyof LineItem = 'id'\n): InternalLineItem[] {\n    return (Object.keys(itemMap) as Array<keyof LineItemMap>)\n        .reduce((result, key) => [\n            ...result,\n            ...(itemMap[key] as LineItem[]).map((item: any) => {\n                if (key === 'giftCertificates') {\n                    return mapGiftCertificateToInternalLineItem(item, decimalPlaces);\n                }\n\n                return mapToInternalLineItem(\n                    item,\n                    mapToInternalLineItemType(key),\n                    decimalPlaces,\n                    idKey\n                );\n            }),\n        ], [] as InternalLineItem[]);\n}\n\nfunction mapToInternalLineItemType(type: string): string {\n    switch (type) {\n        case 'physicalItems':\n            return 'ItemPhysicalEntity';\n\n        case 'digitalItems':\n            return 'ItemDigitalEntity';\n\n        case 'giftCertificates':\n            return 'ItemGiftCertificateEntity';\n\n        default:\n            return '';\n    }\n}\n","import { AmountTransformer } from '../common/utility';\n\nimport InternalLineItem from './internal-line-item';\nimport { GiftCertificateItem } from './line-item';\n\nexport default function mapGiftCertificateToInternalLineItem(\n    item: GiftCertificateItem,\n    decimalPlaces: number\n): InternalLineItem {\n    const amountTransformer = new AmountTransformer(decimalPlaces);\n\n    return {\n        id: item.id,\n        imageUrl: '',\n        name: item.name,\n        amount: item.amount,\n        amountAfterDiscount: item.amount,\n        discount: 0,\n        integerAmount: amountTransformer.toInteger(item.amount),\n        integerAmountAfterDiscount: amountTransformer.toInteger(item.amount),\n        integerUnitPrice: amountTransformer.toInteger(item.amount),\n        integerUnitPriceAfterDiscount: amountTransformer.toInteger(item.amount),\n        integerDiscount: 0,\n        quantity: 1,\n        sender: item.sender,\n        recipient: item.recipient,\n        type: 'ItemGiftCertificateEntity',\n        attributes: [],\n        variantId: null,\n    };\n}\n","module.exports = require(\"local-storage-fallback\");","import { Action } from '@bigcommerce/data-store';\n\nimport { Checkout } from '../checkout';\n\nexport enum SpamProtectionActionType {\n    InitializeFailed = 'SPAM_PROTECTION_INITIALIZE_FAILED',\n    InitializeSucceeded = 'SPAM_PROTECTION_INITIALIZE_SUCCEEDED',\n    InitializeRequested = 'SPAM_PROTECTION_INITIALIZE_REQUESTED',\n    VerifyCheckoutRequested = 'SPAM_PROTECTION_CHECKOUT_VERIFY_REQUESTED',\n    VerifyCheckoutSucceeded = 'SPAM_PROTECTION_CHECKOUT_VERIFY_SUCCEEDED',\n    VerifyCheckoutFailed = 'SPAM_PROTECTION_CHECKOUT_VERIFY_FAILED',\n    ExecuteRequested = 'SPAM_PROTECTION_EXECUTE_REQUESTED',\n    ExecuteSucceeded = 'SPAM_PROTECTION_EXECUTE_SUCCEEDED',\n    ExecuteFailed = 'SPAM_PROTECTION_EXECUTE_FAILED',\n}\n\nexport type SpamProtectionAction =\n    InitializeRequestedAction |\n    InitializeSucceededAction |\n    InitializeFailedAction |\n    ExecuteRequestedAction |\n    ExecuteSucceededAction |\n    ExecuteFailedAction |\n    CheckoutVerifyRequestedAction |\n    CheckoutVerifyFailedAction |\n    CheckoutVerifySucceededAction;\n\nexport interface InitializeRequestedAction extends Action {\n    type: SpamProtectionActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n    type: SpamProtectionActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action<Error> {\n    type: SpamProtectionActionType.InitializeFailed;\n}\n\nexport interface ExecuteRequestedAction extends Action {\n    type: SpamProtectionActionType.ExecuteRequested;\n}\n\nexport interface ExecuteSucceededAction extends Action<{ token: string }> {\n    type: SpamProtectionActionType.ExecuteSucceeded;\n}\n\nexport interface ExecuteFailedAction extends Action {\n    type: SpamProtectionActionType.ExecuteFailed;\n}\n\nexport interface CheckoutVerifyRequestedAction extends Action {\n    type: SpamProtectionActionType.VerifyCheckoutRequested;\n}\n\nexport interface CheckoutVerifyFailedAction extends Action<Error> {\n    type: SpamProtectionActionType.VerifyCheckoutFailed;\n}\n\nexport interface CheckoutVerifySucceededAction extends Action<Checkout> {\n    type: SpamProtectionActionType.VerifyCheckoutSucceeded;\n}\n","module.exports = require(\"shallowequal\");","import { CardInstrument } from '../payment/instrument';\n\nimport HostedFieldType from './hosted-field-type';\nimport { HostedFieldStylesMap } from './hosted-form-options';\nimport HostedFormOrderData from './hosted-form-order-data';\n\nexport enum HostedFieldEventType {\n    AttachRequested = 'HOSTED_FIELD:ATTACH_REQUESTED',\n    SubmitRequested = 'HOSTED_FIELD:SUBMITTED_REQUESTED',\n    ValidateRequested = 'HOSTED_FIELD:VALIDATE_REQUESTED',\n}\n\nexport interface HostedFieldEventMap {\n    [HostedFieldEventType.AttachRequested]: HostedFieldAttachEvent;\n    [HostedFieldEventType.SubmitRequested]: HostedFieldSubmitRequestEvent;\n    [HostedFieldEventType.ValidateRequested]: HostedFieldValidateRequestEvent;\n}\n\nexport type HostedFieldEvent = (\n    HostedFieldAttachEvent |\n    HostedFieldSubmitRequestEvent |\n    HostedFieldValidateRequestEvent\n);\n\nexport interface HostedFieldAttachEvent {\n    type: HostedFieldEventType.AttachRequested;\n    payload: {\n        accessibilityLabel?: string;\n        cardInstrument?: CardInstrument;\n        fontUrls?: string[];\n        placeholder?: string;\n        styles?: HostedFieldStylesMap;\n        origin?: string;\n        type: HostedFieldType;\n    };\n}\n\nexport interface HostedFieldSubmitRequestEvent {\n    type: HostedFieldEventType.SubmitRequested;\n    payload: {\n        data: HostedFormOrderData;\n        fields: HostedFieldType[];\n    };\n}\n\nexport interface HostedFieldValidateRequestEvent {\n    type: HostedFieldEventType.ValidateRequested;\n}\n","export interface CompareOptions {\n    keyFilter?(key: string): boolean;\n}\n\nexport default function isEqual(objectA: any, objectB: any, options?: CompareOptions): boolean {\n    if (objectA === objectB) {\n        return true;\n    }\n\n    if (objectA && objectB && typeof objectA === 'object' && typeof objectB === 'object') {\n        if (Array.isArray(objectA) && Array.isArray(objectB)) {\n            return isArrayEqual(objectA, objectB, options);\n        }\n\n        if (Array.isArray(objectA) || Array.isArray(objectB)) {\n            return false;\n        }\n\n        if ((objectA instanceof Date) && (objectB instanceof Date)) {\n            return isDateEqual(objectA, objectB);\n        }\n\n        if ((objectA instanceof Date) || (objectB instanceof Date)) {\n            return false;\n        }\n\n        if ((objectA instanceof RegExp) && (objectB instanceof RegExp)) {\n            return isRegExpEqual(objectA, objectB);\n        }\n\n        if ((objectA instanceof RegExp) || (objectB instanceof RegExp)) {\n            return false;\n        }\n\n        return isObjectEqual(objectA, objectB, options);\n    }\n\n    return objectA === objectB;\n}\n\nfunction isRegExpEqual(objectA: RegExp, objectB: RegExp): boolean {\n    return objectA.toString() === objectB.toString();\n}\n\nfunction isDateEqual(objectA: Date, objectB: Date): boolean {\n    return objectA.getTime() === objectB.getTime();\n}\n\nfunction isArrayEqual(objectA: any[], objectB: any[], options?: CompareOptions): boolean {\n    if (objectA.length !== objectB.length) {\n        return false;\n    }\n\n    for (let index = 0, length = objectA.length; index < length; index++) {\n        if (!isEqual(objectA[index], objectB[index], options)) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nfunction isObjectEqual(\n    objectA: { [key: string]: any },\n    objectB: { [key: string]: any },\n    options?: CompareOptions\n): boolean {\n    const filter = options && options.keyFilter;\n    const keysA = filter ? Object.keys(objectA).filter(filter) : Object.keys(objectA);\n    const keysB = filter ? Object.keys(objectB).filter(filter) : Object.keys(objectB);\n\n    if (keysA.length !== keysB.length) {\n        return false;\n    }\n\n    for (let index = 0, length = keysA.length; index < length; index++) {\n        const key = keysA[index];\n\n        if (!objectB.hasOwnProperty(key)) {\n            return false;\n        }\n\n        if (!isEqual(objectA[key], objectB[key], options)) {\n            return false;\n        }\n    }\n\n    return true;\n}\n","module.exports = require(\"@bigcommerce/form-poster\");","import { AmountTransformer } from '../common/utility';\n\nimport InternalLineItem from './internal-line-item';\nimport { DigitalItem, LineItem } from './line-item';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalLineItem(\n    item: LineItem,\n    type: string,\n    decimalPlaces: number,\n    idKey: keyof LineItem = 'id'\n): InternalLineItem {\n    const amountTransformer = new AmountTransformer(decimalPlaces);\n\n    return {\n        id: (item[idKey] as string | number),\n        imageUrl: item.imageUrl,\n        amount: item.extendedListPrice,\n        amountAfterDiscount: item.extendedSalePrice,\n        discount: item.discountAmount,\n        integerAmount: amountTransformer.toInteger(item.extendedListPrice),\n        integerAmountAfterDiscount: amountTransformer.toInteger(item.extendedSalePrice),\n        integerDiscount: amountTransformer.toInteger(item.discountAmount),\n        integerUnitPrice: amountTransformer.toInteger(item.listPrice),\n        integerUnitPriceAfterDiscount: amountTransformer.toInteger(item.salePrice),\n        downloadsPageUrl: (item as DigitalItem).downloadPageUrl,\n        name: item.name,\n        quantity: item.quantity,\n        brand: item.brand,\n        sku: item.sku,\n        categoryNames: item.categoryNames,\n        variantId: item.variantId,\n        productId: item.productId,\n        attributes: (item.options || []).map(option => ({\n            name: option.name,\n            value: option.value,\n        })),\n        addedByPromotion: item.addedByPromotion,\n        type,\n    };\n}\n","module.exports = require(\"reselect\");","import InternalShippingOption from './internal-shipping-option';\nimport ShippingOption from './shipping-option';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalShippingOption(option: ShippingOption, isSelected: boolean): InternalShippingOption {\n    return {\n        description: option.description,\n        module: option.type,\n        price: option.cost,\n        id: option.id,\n        selected: isSelected,\n        isRecommended: option.isRecommended,\n        imageUrl: option.imageUrl,\n        transitTime: option.transitTime,\n    };\n}\n","export default class AmountTransformer {\n    constructor(private _decimalPlaces: number) {}\n\n    toInteger(amount: number): number {\n        return Math.round(amount * Math.pow(10, this._decimalPlaces));\n    }\n}\n","import { memoize } from '@bigcommerce/memoize';\nimport { createSelector as defaultSelectorCreator } from 'reselect';\n\n/**\n * Decorate selector creators with the ability to memoize the return value of\n * their combiner if it is a function (which effectively works as a partially\n * applied combiner).\n */\nexport default function withMemoizedCombiner<T extends typeof defaultSelectorCreator>(\n    creator: T\n): T {\n    return ((...args: any[]) => {\n        const combiner = args.pop();\n\n        // Reselect's default `createSelector` has many overloads. To avoid having\n        // to redefine all of them, we're using `any` to bypass the typechecker.\n        return (creator as any)(...args, (...combinerArgs: any[]) => {\n            // Although there are many overloads, all of them have the last argument\n            // as the combiner.\n            const result = combiner(...combinerArgs);\n\n            if (typeof result === 'function') {\n                return memoize(result);\n            }\n\n            return result;\n        });\n    }) as T;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nexport enum ErrorActionType {\n    ClearError = 'CLEAR_ERROR',\n}\n\nexport type ErrorAction = ClearErrorAction;\n\nexport interface ClearErrorAction extends Action {\n    type: ErrorActionType.ClearError;\n    payload: Error;\n}\n","import { createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { cachableAction, ActionOptions } from '../common/data-store';\nimport { RequestOptions } from '../common/http-request';\n\nimport { LoadPaymentMethodsAction, LoadPaymentMethodAction, PaymentMethodActionType } from './payment-method-actions';\nimport PaymentMethodRequestSender from './payment-method-request-sender';\n\nexport default class PaymentMethodActionCreator {\n    constructor(\n        private _requestSender: PaymentMethodRequestSender\n    ) {}\n\n    loadPaymentMethods(options?: RequestOptions): Observable<LoadPaymentMethodsAction> {\n        return Observable.create((observer: Observer<LoadPaymentMethodsAction>) => {\n            observer.next(createAction(PaymentMethodActionType.LoadPaymentMethodsRequested));\n\n            this._requestSender.loadPaymentMethods(options)\n                .then(response => {\n                    const meta = {\n                        deviceSessionId: response.headers['x-device-session-id'],\n                        sessionHash: response.headers['x-session-hash'],\n                    };\n\n                    observer.next(createAction(PaymentMethodActionType.LoadPaymentMethodsSucceeded, response.body, meta));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(PaymentMethodActionType.LoadPaymentMethodsFailed, response));\n                });\n        });\n    }\n\n    @cachableAction\n    loadPaymentMethod(methodId: string, options?: RequestOptions & ActionOptions): Observable<LoadPaymentMethodAction> {\n        return Observable.create((observer: Observer<LoadPaymentMethodAction>) => {\n            observer.next(createAction(PaymentMethodActionType.LoadPaymentMethodRequested, undefined, { methodId }));\n\n            this._requestSender.loadPaymentMethod(methodId, options)\n                .then(response => {\n                    observer.next(createAction(PaymentMethodActionType.LoadPaymentMethodSucceeded, response.body, { methodId }));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(PaymentMethodActionType.LoadPaymentMethodFailed, response, { methodId }));\n                });\n        });\n    }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, INTERNAL_USE_ONLY, RequestOptions } from '../common/http-request';\n\nimport PaymentMethod from './payment-method';\n\nexport default class PaymentMethodRequestSender {\n    constructor(\n        private _requestSender: RequestSender\n    ) {}\n\n    loadPaymentMethods({ timeout }: RequestOptions = {}): Promise<Response<PaymentMethod[]>> {\n        const url = '/api/storefront/payments';\n\n        return this._requestSender.get(url, {\n            timeout,\n            headers: {\n                Accept: ContentType.JsonV1,\n                'X-API-INTERNAL': INTERNAL_USE_ONLY,\n            },\n        });\n    }\n\n    loadPaymentMethod(methodId: string, { timeout }: RequestOptions = {}): Promise<Response<PaymentMethod>> {\n        const url = `/api/storefront/payments/${methodId}`;\n\n        return this._requestSender.get(url, {\n            timeout,\n            headers: {\n                Accept: ContentType.JsonV1,\n                'X-API-INTERNAL': INTERNAL_USE_ONLY,\n            },\n        });\n    }\n}\n","const CHECKOUT_DEFAULT_INCLUDES = [\n    'cart.lineItems.physicalItems.options',\n    'cart.lineItems.digitalItems.options',\n    'customer',\n    'customer.customerGroup',\n    'payments',\n    'promotions.banners',\n];\n\nexport default CHECKOUT_DEFAULT_INCLUDES;\n","import { createErrorAction, Action } from '@bigcommerce/data-store';\nimport { concat, of, throwError, Observable } from 'rxjs';\n\nexport default function throwErrorAction<TPayload, TMeta, TType extends string>(\n    type: TType,\n    error?: TPayload,\n    meta?: TMeta\n): Observable<Action<TPayload, TMeta, TType>> {\n    if (isErrorAction(error)) {\n        return concat(of(error), throwError(createErrorAction(type, error.payload, meta)));\n    }\n\n    return throwError(createErrorAction(type, error, meta));\n}\n\nfunction isErrorAction(action: any): action is Action {\n    return action && action.type && action.error;\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when a payment method experiences some kind of\n * failure (i.e.: its client library returns a rejected promise). And there is\n * no other error type that is more specific than this one.\n */\nexport default class PaymentMethodFailedError extends StandardError {\n    constructor(message?: string) {\n        super(message || 'Unable to proceed because the client library of a payment method has thrown an unexpected error.');\n\n        this.name = 'PaymentMethodFailedError';\n        this.type = 'payment_method_client_invalid';\n    }\n}\n","import { Action, ThunkAction } from '@bigcommerce/data-store';\nimport { memoize } from '@bigcommerce/memoize';\nimport { from, Observable } from 'rxjs';\nimport { shareReplay } from 'rxjs/operators';\n\nexport default function cacheAction<TFunction extends CreateActionFn>(\n    fn: TFunction\n): TFunction {\n    function decoratedFn(this: any, ...args: any[]) {\n        const action = fn.call(this, ...args);\n\n        if (action instanceof Observable) {\n            return from(action).pipe(shareReplay());\n        }\n\n        if (typeof action === 'function') {\n            return memoize(store => from(action(store)).pipe(shareReplay()));\n        }\n\n        return action;\n    }\n\n    return memoize(decoratedFn as TFunction);\n}\n\ntype CreateActionFn = (...args: any[]) => Observable<Action> | ThunkAction<Action> | Action;\n","import ActionOptions from './action-options';\n\nexport default function isActionOptions(param: any): param is ActionOptions {\n    return param && typeof param.useCache === 'boolean';\n}\n","import cacheAction from './cache-action';\nimport isActionOptions from './is-action-options';\n\nexport default function cachableActionDecorator<TMethod extends (...args: any[]) => any>(\n    _: object,\n    key: string,\n    descriptor: TypedPropertyDescriptor<TMethod>\n): TypedPropertyDescriptor<TMethod> {\n    const memoizedMethods = new WeakMap<object, { [key: string]: TMethod }>();\n\n    function decorateMethod(this: object, method: TMethod): TMethod {\n        return ((...args: any[]) => {\n            const lastArg = args[args.length - 1];\n            const { useCache } = isActionOptions(lastArg) ? lastArg : { useCache: false };\n\n            if (!useCache) {\n                return method.call(this, ...args);\n            }\n\n            const instanceMethods = memoizedMethods.get(this) || {};\n\n            if (!memoizedMethods.get(this)) {\n                memoizedMethods.set(this, instanceMethods);\n            }\n\n            if (!instanceMethods[key]) {\n                instanceMethods[key] = cacheAction(method);\n            }\n\n            return instanceMethods[key].call(this, ...args);\n        }) as TMethod;\n    }\n\n    return {\n        get() {\n            if (typeof descriptor.value !== 'function') {\n                throw new Error('Decorator should be used in functions');\n            }\n\n            const value = decorateMethod.call(this, descriptor.value);\n\n            Object.defineProperty(this, key, { ...descriptor, value });\n\n            return value;\n        },\n    };\n}\n","/**\n * Decorates a class or a method by binding all its prototype methods or itself\n * to the calling instance respectively.\n */\nfunction bindDecorator<T extends Method>(target: object, key: string, descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T>;\nfunction bindDecorator<T extends Constructor<object>>(target: T): T;\nfunction bindDecorator(target: any, key?: any, descriptor?: any): any {\n    if (!key || !descriptor) {\n        return bindClassDecorator(target);\n    }\n\n    return bindMethodDecorator(target, key, descriptor);\n}\n\nexport default bindDecorator;\n\n/**\n * Decorates a class by binding all its prototype methods to the calling\n * instance.\n */\nexport function bindClassDecorator<T extends Constructor<object>>(target: T): T {\n    const decoratedTarget = class extends target {};\n\n    Object.getOwnPropertyNames(target.prototype)\n        .forEach(key => {\n            const descriptor = Object.getOwnPropertyDescriptor(target.prototype, key);\n\n            if (!descriptor || key === 'constructor') {\n                return;\n            }\n\n            Object.defineProperty(\n                decoratedTarget.prototype,\n                key,\n                bindMethodDecorator(target.prototype, key, descriptor)\n            );\n        });\n\n    return decoratedTarget;\n}\n\n/**\n * Decorates a method by binding it to the calling instance.\n */\nexport function bindMethodDecorator<T extends Method>(_: object, key: string, descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T> {\n    if (typeof descriptor.value !== 'function') {\n        return descriptor;\n    }\n\n    let method: T = descriptor.value;\n\n    return {\n        get() {\n            const boundMethod = method.bind(this) as T;\n\n            Object.defineProperty(this, key, {\n                ...descriptor,\n                value: boundMethod,\n            });\n\n            return boundMethod;\n        },\n        set(value) {\n            method = value;\n        },\n    };\n}\n\nexport type Constructor<T> = new (...args: any[]) => T;\nexport type Method = (...args: any[]) => any;\n","import { mapToInternalAddress } from '../address';\nimport { BillingAddress } from '../billing';\n\nimport { Customer } from '.';\nimport InternalCustomer from './internal-customer';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalCustomer(customer: Customer, billingAddress: BillingAddress): InternalCustomer {\n    const firstName = customer.firstName || billingAddress.firstName || '';\n    const lastName = customer.lastName || billingAddress.lastName || '';\n\n    return {\n        addresses: (customer.addresses || []).map(address => mapToInternalAddress(address)),\n        customerId: customer.id,\n        isGuest: customer.isGuest,\n        storeCredit: customer.storeCredit,\n        email: customer.email || billingAddress.email || '',\n        firstName,\n        lastName,\n        name: customer.fullName || [firstName, lastName].join(' '),\n        customerGroupName: customer.customerGroup && customer.customerGroup.name,\n    };\n}\n","import { filter, find, keyBy, reduce } from 'lodash';\n\nimport { mapToInternalLineItems, LineItem } from '../cart';\nimport { Checkout } from '../checkout';\nimport { AmountTransformer } from '../common/utility';\nimport { mapToInternalCoupon } from '../coupon';\nimport { HOSTED } from '../payment';\n\nimport InternalOrder, { InternalGiftCertificateList, InternalIncompleteOrder, InternalOrderPayment, InternalSocialDataList } from './internal-order';\nimport Order, { GatewayOrderPayment, GiftCertificateOrderPayment, OrderPayment, OrderPayments } from './order';\nimport { OrderMetaState } from './order-state';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalOrder(order: Order, orderMeta: OrderMetaState = {}): InternalOrder {\n    const decimalPlaces = order.currency.decimalPlaces;\n    const amountTransformer = new AmountTransformer(decimalPlaces);\n\n    return {\n        id: order.orderId,\n        items: mapToInternalLineItems(order.lineItems, order.currency.decimalPlaces, 'productId'),\n        orderId: order.orderId,\n        currency: order.currency.code,\n        customerCanBeCreated: order.customerCanBeCreated,\n        payment: mapToInternalOrderPayment(order.payments, orderMeta.payment),\n        subtotal: {\n            amount: order.baseAmount,\n            integerAmount: amountTransformer.toInteger(order.baseAmount),\n        },\n        coupon: {\n            discountedAmount: reduce(order.coupons, (sum, coupon) => {\n                return sum + coupon.discountedAmount;\n            }, 0),\n            coupons: order.coupons.map(mapToInternalCoupon),\n        },\n        discount: {\n            amount: order.discountAmount,\n            integerAmount: amountTransformer.toInteger(order.discountAmount),\n        },\n        token: orderMeta.orderToken,\n        callbackUrl: orderMeta.callbackUrl,\n        discountNotifications: [],\n        giftCertificate: mapToGiftCertificates(order.payments),\n        socialData: mapToInternalSocialDataList(order),\n        status: order.status,\n        hasDigitalItems: order.hasDigitalItems,\n        isDownloadable: order.isDownloadable,\n        isComplete: order.isComplete,\n        shipping: {\n            amount: order.shippingCostTotal,\n            integerAmount: amountTransformer.toInteger(order.shippingCostTotal),\n            amountBeforeDiscount: order.shippingCostBeforeDiscount,\n            integerAmountBeforeDiscount: amountTransformer.toInteger(order.shippingCostBeforeDiscount),\n        },\n        storeCredit: {\n            amount: mapToStoreCredit(order.payments),\n        },\n        taxes: order.taxes,\n        taxTotal: {\n            amount: order.taxTotal,\n            integerAmount: amountTransformer.toInteger(order.taxTotal),\n        },\n        handling: {\n            amount: order.handlingCostTotal,\n            integerAmount: amountTransformer.toInteger(order.handlingCostTotal),\n        },\n        grandTotal: {\n            amount: order.orderAmount,\n            integerAmount: order.orderAmountAsInteger,\n        },\n    };\n}\n\nexport function mapToInternalIncompleteOrder(checkout: Checkout): InternalIncompleteOrder {\n    const payment = find(checkout.payments, { providerType: HOSTED });\n\n    return {\n        orderId: null,\n        isComplete: false,\n        payment: !payment ? {} : {\n            id: payment.providerId,\n            gateway: payment.gatewayId,\n            status: mapToInternalPaymentStatus(payment.detail.step),\n        },\n    };\n}\n\nfunction mapToInternalPaymentStatus(status: string): string {\n    return `PAYMENT_STATUS_${status}`;\n}\n\nfunction mapToStoreCredit(payments?: OrderPayments): number {\n    const item = find(payments, { providerId: 'storecredit' });\n\n    return item ? item.amount : 0;\n}\n\nfunction mapToGiftCertificates(payments?: OrderPayments): InternalGiftCertificateList {\n    const items = filter(payments, { providerId: 'giftcertificate' }) as GiftCertificateOrderPayment[];\n\n    return {\n        totalDiscountedAmount: reduce(items, (sum, item) => item.amount + sum, 0),\n        appliedGiftCertificates: keyBy(items.map(item => ({\n            code: item.detail.code,\n            discountedAmount: item.amount,\n            remainingBalance: item.detail.remaining,\n            giftCertificate: {\n                balance: item.amount + item.detail.remaining,\n                code: item.detail.code,\n                purchaseDate: '',\n            },\n        })), 'code'),\n    };\n}\n\nfunction mapToInternalOrderPayment(payments?: OrderPayments, payment: InternalOrderPayment = {}): InternalOrderPayment {\n    const item = find(payments, isDefaultOrderPayment) as GatewayOrderPayment;\n\n    if (!item) {\n        return {};\n    }\n\n    return {\n        id: item.providerId,\n        status: mapToInternalPaymentStatus(item.detail.step),\n        helpText: item.detail.instructions,\n        returnUrl: payment.returnUrl,\n    };\n}\n\nfunction isDefaultOrderPayment(payment: OrderPayment): payment is GatewayOrderPayment {\n    return payment.providerId !== 'giftcertificate' && payment.providerId !== 'storecredit';\n}\n\nfunction mapToInternalSocialDataList(order: Order): { [itemId: string]: InternalSocialDataList } | undefined {\n    const socialDataObject: { [itemId: string]: InternalSocialDataList } = {};\n    const items = [\n        ...order.lineItems.physicalItems,\n        ...order.lineItems.digitalItems,\n    ];\n\n    items.forEach(item => {\n        socialDataObject[item.id] = mapToInternalSocialData(item);\n    });\n\n    return socialDataObject;\n}\n\nfunction mapToInternalSocialData(lineItem: LineItem): InternalSocialDataList {\n    const codes = ['fb', 'tw', 'gp'];\n\n    return codes.reduce((socialData, code) => {\n        const item = lineItem.socialMedia && find(lineItem.socialMedia, item => item.code === code);\n\n        if (!item) {\n            return socialData;\n        }\n\n        socialData[code] = {\n            name: lineItem.name,\n            description: lineItem.name,\n            image: lineItem.imageUrl,\n            url: item.link,\n            shareText: item.text,\n            sharingLink: item.link,\n            channelName: item.channel,\n            channelCode: item.code,\n        };\n\n        return socialData;\n    }, {} as InternalSocialDataList);\n}\n","import { keyBy, reduce, some } from 'lodash';\n\nimport { Checkout } from '../checkout';\nimport { AmountTransformer } from '../common/utility';\nimport { mapToInternalCoupon, mapToInternalGiftCertificate } from '../coupon';\nimport { mapToDiscountNotifications } from '../promotion';\n\nimport InternalCart from './internal-cart';\nimport mapToInternalLineItems from './map-to-internal-line-items';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalCart(checkout: Checkout): InternalCart {\n    const decimalPlaces = checkout.cart.currency.decimalPlaces;\n    const amountTransformer = new AmountTransformer(decimalPlaces);\n\n    return {\n        id: checkout.cart.id,\n        items: mapToInternalLineItems(checkout.cart.lineItems, decimalPlaces),\n        currency: checkout.cart.currency.code,\n        coupon: {\n            discountedAmount: reduce(checkout.cart.coupons, (sum, coupon) => {\n                return sum + coupon.discountedAmount;\n            }, 0),\n            coupons: checkout.cart.coupons.map(mapToInternalCoupon),\n        },\n        discount: {\n            amount: checkout.cart.discountAmount,\n            integerAmount: amountTransformer.toInteger(checkout.cart.discountAmount),\n        },\n        discountNotifications: mapToDiscountNotifications(checkout.promotions),\n        giftCertificate: {\n            totalDiscountedAmount: reduce(checkout.giftCertificates, (sum, certificate) => {\n                return sum + certificate.used;\n            }, 0),\n            appliedGiftCertificates: keyBy(checkout.giftCertificates.map(mapToInternalGiftCertificate), 'code'),\n        },\n        shipping: {\n            amount: checkout.shippingCostTotal,\n            integerAmount: amountTransformer.toInteger(checkout.shippingCostTotal),\n            amountBeforeDiscount: checkout.shippingCostBeforeDiscount,\n            integerAmountBeforeDiscount: amountTransformer.toInteger(checkout.shippingCostBeforeDiscount),\n            required: some(checkout.cart.lineItems.physicalItems, lineItem => lineItem.isShippingRequired),\n        },\n        subtotal: {\n            amount: checkout.subtotal,\n            integerAmount: amountTransformer.toInteger(checkout.subtotal),\n        },\n        storeCredit: {\n            amount: checkout.customer ? checkout.customer.storeCredit : 0,\n        },\n        taxSubtotal: {\n            amount: checkout.taxTotal,\n            integerAmount: amountTransformer.toInteger(checkout.taxTotal),\n        },\n        taxes: checkout.taxes,\n        taxTotal: {\n            amount: checkout.taxTotal,\n            integerAmount: amountTransformer.toInteger(checkout.taxTotal),\n        },\n        handling: {\n            amount: checkout.handlingCostTotal,\n            integerAmount: amountTransformer.toInteger(checkout.handlingCostTotal),\n        },\n        grandTotal: {\n            amount: checkout.grandTotal,\n            integerAmount: amountTransformer.toInteger(checkout.grandTotal),\n        },\n    };\n}\n","import { DiscountNotification } from '../discount';\n\nimport { Promotion } from '.';\n\nexport default function mapToDiscountNotifications(promotions?: Promotion[]): DiscountNotification[] {\n    const notifications: DiscountNotification[] = [];\n\n    (promotions || []).forEach(promotion => {\n        (promotion.banners || []).forEach(banner => {\n            notifications.push({\n                placeholders: [],\n                discountType: null,\n                message: '',\n                messageHtml: banner.text,\n            });\n        });\n    });\n\n    return notifications;\n}\n","module.exports = require(\"@bigcommerce/bigpay-client\");","export type EnvironmentType = 'PRODUCTION' | 'TEST';\n\nexport interface AmazonPayV2Options {\n    environment: EnvironmentType;\n}\n\nexport interface AmazonPayV2SDK {\n    Pay: AmazonPayV2Client;\n}\n\nexport interface AmazonPayV2Client {\n    /**\n     * Render the Amazon Pay button to a HTML container element.\n     *\n     * @param containerId - HTML element id.\n     * @param params - Button rendering params.\n     */\n    renderButton(containerId: string, params: AmazonPayV2ButtonParams): HTMLElement;\n\n    /**\n     * Bind click events to HTML elements, so that when the element is clicked, the buyer can select a different shipping address or payment method.\n     *\n     * @param buttonId - HTML element id.\n     * @param options - Element binding options.\n     */\n    bindChangeAction(buttonId: string, options: AmazonPayV2ChangeActionOptions): void;\n\n    /**\n     * Allow buyers to sign out from their Amazon account.\n     */\n    signout(): void;\n}\n\nexport interface AmazonPayV2HostWindow extends Window {\n    amazon?: AmazonPayV2SDK;\n}\n\nexport interface AmazonPayV2ButtonParams {\n    /**\n     * Amazon Pay merchant account identifier.\n     */\n    merchantId: string;\n\n    /**\n     * Configuration for calling the endpoint to Create Checkout Session.\n     */\n    createCheckoutSession: AmazonPayV2CheckoutSession;\n\n    /**\n     * Placement of the Amazon Pay button on your website.\n     */\n    placement: AmazonPayV2Placement;\n\n    /**\n     * Ledger currency provided during registration for the given merchant identifier.\n     */\n    ledgerCurrency: AmazonPayV2LedgerCurrency;\n\n    /**\n     * Product type selected for checkout. Default is 'PayAndShip'.\n     */\n    productType?: AmazonPayV2PayOptions;\n\n    /**\n     * Language used to render the button and text on Amazon Pay hosted pages.\n     */\n    checkoutLanguage?: AmazonPayV2CheckoutLanguage;\n\n    /**\n     * Sets button to Sandbox environment. Default is false.\n     */\n    sandbox?: boolean;\n}\n\nexport interface AmazonPayV2CheckoutSession {\n    /**\n     * Endpoint URL to Create Checkout Session.\n     */\n    url: string;\n\n    /**\n     * HTTP request method. Default is 'POST'.\n     */\n    method?: 'GET' | 'POST';\n\n    /**\n     * Checkout Session ID parameter in the response. Default is 'checkoutSessionId'.\n     */\n    extractAmazonCheckoutSessionId?: string;\n}\n\nexport type AmazonPayV2ChangeActionType = 'changeAddress' | 'changePayment';\n\nexport interface AmazonPayV2ChangeActionOptions {\n    /**\n     * Amazon Pay Checkout Session identifier.\n     */\n    amazonCheckoutSessionId: string;\n\n    /**\n     * Update requested by the buyer.\n     */\n    changeAction: AmazonPayV2ChangeActionType;\n}\n\nexport enum AmazonPayV2Regions {\n    de = 'eu',\n    jp = 'fe',\n    uk = 'eu',\n    us = 'na',\n}\n\nexport enum AmazonPayV2CheckoutLanguage {\n    en_US = 'en_US',\n    en_GB = 'en_GB',\n    de_DE = 'de_DE',\n    fr_FR = 'fr_FR',\n    it_IT = 'it_IT',\n    es_ES = 'es_ES',\n    ja_JP = 'ja_JP',\n}\n\nexport enum AmazonPayV2Placement {\n    /** Initial or main page. */\n    Home = 'Home',\n\n    /** Product details page. */\n    Product = 'Product',\n\n    /** Cart review page before buyer starts checkout. */\n    Cart = 'Cart',\n\n    /** Any page after buyer starts checkout. */\n    Checkout = 'Checkout',\n\n    /** Any page that doesn't fit the previous descriptions. */\n    Other = 'Other',\n}\n\nexport enum AmazonPayV2LedgerCurrency {\n    USD = 'USD',\n    EUR = 'EUR',\n    GBP = 'GBP',\n    JPY = 'JPY',\n}\n\nexport enum AmazonPayV2PayOptions {\n    /** Select this product type if you need the buyer's shipping details. */\n    PayAndShip = 'PayAndShip',\n\n    /** Select this product type if you do not need the buyer's shipping details. */\n    PayOnly = 'PayOnly',\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\nimport { GooglePayCreator } from '../googlepay';\n\nimport { BraintreeClientCreator, BraintreeDataCollectorCreator, BraintreeHostedFieldsCreator, BraintreeHostWindow, BraintreePaypalCheckoutCreator, BraintreePaypalCreator, BraintreeThreeDSecureCreator, BraintreeVisaCheckoutCreator } from './braintree';\n\nexport default class BraintreeScriptLoader {\n    constructor(\n        private _scriptLoader: ScriptLoader,\n        private _window: BraintreeHostWindow = window\n    ) {}\n\n    loadClient(): Promise<BraintreeClientCreator> {\n        return this._scriptLoader\n            .loadScript('//js.braintreegateway.com/web/3.70.0/js/client.min.js')\n            .then(() => {\n                if (!this._window.braintree || !this._window.braintree.client) {\n                    throw new PaymentMethodClientUnavailableError();\n                }\n\n                return this._window.braintree.client;\n            });\n    }\n\n    load3DS(): Promise<BraintreeThreeDSecureCreator> {\n        return this._scriptLoader\n            .loadScript('//js.braintreegateway.com/web/3.70.0/js/three-d-secure.min.js')\n            .then(() => {\n                if (!this._window.braintree || !this._window.braintree.threeDSecure) {\n                    throw new PaymentMethodClientUnavailableError();\n                }\n\n                return this._window.braintree.threeDSecure;\n            });\n    }\n\n    loadDataCollector(): Promise<BraintreeDataCollectorCreator> {\n        return this._scriptLoader\n            .loadScript('//js.braintreegateway.com/web/3.70.0/js/data-collector.min.js')\n            .then(() => {\n                if (!this._window.braintree || !this._window.braintree.dataCollector) {\n                    throw new PaymentMethodClientUnavailableError();\n                }\n\n                return this._window.braintree.dataCollector;\n            });\n    }\n\n    loadPaypal(): Promise<BraintreePaypalCreator> {\n\n        return this._scriptLoader\n            .loadScript('//js.braintreegateway.com/web/3.70.0/js/paypal.min.js')\n            .then(() => {\n                if (!this._window.braintree || !this._window.braintree.paypal) {\n                    throw new PaymentMethodClientUnavailableError();\n                }\n\n                return this._window.braintree.paypal;\n            });\n    }\n\n    loadPaypalCheckout(): Promise<BraintreePaypalCheckoutCreator> {\n\n        return this._scriptLoader\n            .loadScript('//js.braintreegateway.com/web/3.70.0/js/paypal-checkout.min.js')\n            .then(() => {\n                if (!this._window.braintree || !this._window.braintree.paypalCheckout) {\n                    throw new PaymentMethodClientUnavailableError();\n                }\n\n                return this._window.braintree.paypalCheckout;\n            });\n    }\n\n    loadVisaCheckout(): Promise<BraintreeVisaCheckoutCreator> {\n        return this._scriptLoader\n            .loadScript('//js.braintreegateway.com/web/3.70.0/js/visa-checkout.min.js')\n            .then(() => {\n                if (!this._window.braintree || !this._window.braintree.visaCheckout) {\n                    throw new PaymentMethodClientUnavailableError();\n                }\n\n                return this._window.braintree.visaCheckout;\n            });\n    }\n\n    loadGooglePayment(): Promise<GooglePayCreator> {\n        return this._scriptLoader\n            .loadScript('//js.braintreegateway.com/web/3.70.0/js/google-payment.min.js')\n            .then(() => {\n                if (!this._window.braintree || !this._window.braintree.googlePayment) {\n                    throw new PaymentMethodClientUnavailableError();\n                }\n\n                return this._window.braintree.googlePayment;\n            });\n    }\n\n    async loadHostedFields(): Promise<BraintreeHostedFieldsCreator> {\n        await this._scriptLoader.loadScript('//js.braintreegateway.com/web/3.70.0/js/hosted-fields.min.js');\n\n        if (!this._window.braintree || !this._window.braintree.hostedFields) {\n            throw new PaymentMethodClientUnavailableError();\n        }\n\n        return this._window.braintree.hostedFields;\n    }\n}\n","import { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\n\nimport { BraintreeClient,\n    BraintreeDataCollector,\n    BraintreeHostedFields,\n    BraintreeHostedFieldsCreatorConfig,\n    BraintreeModule,\n    BraintreePaypal,\n    BraintreePaypalCheckout,\n    BraintreeThreeDSecure,\n    BraintreeVisaCheckout, Config,\n    GooglePayBraintreeSDK,\n    PaypalClientInstance,\n    RenderButtons } from './braintree';\nimport BraintreeScriptLoader from './braintree-script-loader';\n\nexport default class BraintreeSDKCreator {\n    private _client?: Promise<BraintreeClient>;\n    private _3ds?: Promise<BraintreeThreeDSecure>;\n    private _paypal?: Promise<BraintreePaypal>;\n    private _paypalCheckout?: Promise<BraintreePaypalCheckout>;\n    private _clientToken?: string;\n    private _visaCheckout?: Promise<BraintreeVisaCheckout>;\n    private _dataCollectors: {\n        default?: Promise<BraintreeDataCollector>;\n        paypal?: Promise<BraintreeDataCollector>;\n    } = {};\n    private _googlePay?: Promise<GooglePayBraintreeSDK>;\n    private _paypalcheckoutInstance?: PaypalClientInstance;\n\n    constructor(\n        private _braintreeScriptLoader: BraintreeScriptLoader\n    ) {}\n\n    initialize(clientToken: string) {\n        this._clientToken = clientToken;\n    }\n\n    getClient(): Promise<BraintreeClient> {\n        if (!this._clientToken) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        if (!this._client) {\n            this._client = this._braintreeScriptLoader.loadClient()\n                .then(client => client.create({ authorization: this._clientToken }));\n        }\n\n        return this._client;\n    }\n\n    getPaypal(): Promise<BraintreePaypal> {\n        if (!this._paypal) {\n            this._paypal = Promise.all([\n                this.getClient(),\n                this._braintreeScriptLoader.loadPaypal(),\n            ])\n                .then(([client, paypal]) => paypal.create({ client }));\n        }\n\n        return this._paypal;\n    }\n\n    getPaypalCheckout(config: Config, renderButtonCallback: RenderButtons): Promise<BraintreePaypalCheckout> {\n        if (!this._paypalCheckout) {\n            this._paypalCheckout = Promise.all([\n                this.getClient(),\n                this._braintreeScriptLoader.loadPaypalCheckout(),\n            ])\n                .then(([client, paypalCheckout]) => paypalCheckout.create({ client }, (_error: string, instance: PaypalClientInstance) =>  {\n                    this._paypalcheckoutInstance = instance;\n                    instance.loadPayPalSDK({\n                        currency: config.currency,\n                    }, () => {\n                        renderButtonCallback(instance);\n                    });\n                }));\n        } else if (this._paypalcheckoutInstance) {\n            renderButtonCallback(this._paypalcheckoutInstance);\n        }\n\n        return this._paypalCheckout;\n    }\n\n    get3DS(): Promise<BraintreeThreeDSecure> {\n        if (!this._3ds) {\n            this._3ds = Promise.all([\n                this.getClient(),\n                this._braintreeScriptLoader.load3DS(),\n            ])\n                .then(([client, threeDSecure]) => threeDSecure.create({ client, version: 2}));\n        }\n\n        return this._3ds;\n    }\n\n    getDataCollector(options?: { paypal: boolean }): Promise<BraintreeDataCollector> {\n        const cacheKey = options && options.paypal ? 'paypal' : 'default';\n        let cached = this._dataCollectors[cacheKey];\n\n        if (!cached) {\n            cached = Promise.all([\n                this.getClient(),\n                this._braintreeScriptLoader.loadDataCollector(),\n            ])\n                .then(([client, dataCollector]) => dataCollector.create({ client, kount: true, ...options }))\n                .catch(error => {\n                    if (error && error.code === 'DATA_COLLECTOR_KOUNT_NOT_ENABLED') {\n                        return { deviceData: undefined, teardown: () => Promise.resolve() };\n                    }\n\n                    throw error;\n                });\n\n            this._dataCollectors[cacheKey] = cached;\n        }\n\n        return cached;\n    }\n\n    getVisaCheckout(): Promise<BraintreeVisaCheckout> {\n        if (!this._visaCheckout) {\n            this._visaCheckout = Promise.all([\n                this.getClient(),\n                this._braintreeScriptLoader.loadVisaCheckout(),\n            ])\n                .then(([client, visaCheckout]) => visaCheckout.create({ client }));\n        }\n\n        return this._visaCheckout;\n    }\n\n    getGooglePaymentComponent(): Promise<GooglePayBraintreeSDK> {\n        if (!this._googlePay) {\n            this._googlePay = Promise.all ([\n                this.getClient(),\n                this._braintreeScriptLoader.loadGooglePayment(),\n            ])\n                .then(([client, googlePay]) => googlePay.create({ client }));\n        }\n\n        return this._googlePay;\n    }\n\n    async createHostedFields(\n        options: Pick<BraintreeHostedFieldsCreatorConfig, 'fields' | 'styles'>\n    ): Promise<BraintreeHostedFields> {\n        const [client, hostedFields] = await Promise.all([\n            this.getClient(),\n            this._braintreeScriptLoader.loadHostedFields(),\n        ]);\n\n        return hostedFields.create({ ...options, client });\n    }\n\n    teardown(): Promise<void> {\n        return Promise.all([\n            this._teardown(this._3ds),\n            this._teardown(this._dataCollectors.default),\n            this._teardown(this._dataCollectors.paypal),\n            this._teardown(this._visaCheckout),\n            this._teardown(this._googlePay),\n        ]).then(() => {\n            this._3ds = undefined;\n            this._visaCheckout = undefined;\n            this._dataCollectors = {};\n            this._googlePay = undefined;\n        });\n    }\n\n    private _teardown(module?: Promise<BraintreeModule>) {\n        return module ?\n            module.then(mod => mod.teardown()) :\n            Promise.resolve();\n    }\n}\n","import EmbeddedCheckoutStyles from '../embedded-checkout-styles';\n\nexport enum EmbeddedContentEventType {\n    StyleConfigured = 'STYLE_CONFIGURED',\n}\n\nexport interface EmbeddedContentEventMap {\n    [EmbeddedContentEventType.StyleConfigured]: EmbeddedContentStyleConfiguredEvent;\n}\n\nexport type EmbeddedContentEvent = (\n    EmbeddedContentStyleConfiguredEvent\n);\n\nexport interface EmbeddedContentStyleConfiguredEvent {\n    type: EmbeddedContentEventType.StyleConfigured;\n    payload: EmbeddedCheckoutStyles;\n}\n","import { Address } from '../address';\n\nimport BillingAddress from './billing-address';\n\nexport default function isBillingAddressLike(address: Address): address is BillingAddress {\n    const billingAddress = address as BillingAddress;\n\n    return typeof billingAddress.id !== 'undefined';\n}\n","import CardExpiryDate from './card-expiry-date';\n\nconst NUMBER_SEPARATOR = '/';\n\nexport default class CardExpiryFormatter {\n    format(value: string): string {\n        const [month = '', year = ''] = value.split(new RegExp(`\\\\s*${NUMBER_SEPARATOR}\\\\s*`));\n        const trimmedMonth = month.slice(0, 2);\n        const trimmedYear = year.length === 4 ? year.slice(-2) : (year ? year.slice(0, 2) : month.slice(2));\n\n        // i.e.: '1'\n        if (value.length < 2) {\n            return month;\n        }\n\n        // ie.: '10 /' (without trailing space)\n        if (value.length > 3 && !trimmedYear) {\n            return trimmedMonth;\n        }\n\n        return `${trimmedMonth} ${NUMBER_SEPARATOR} ${trimmedYear}`;\n    }\n\n    toObject(value: string): CardExpiryDate {\n        const [month = '', year = ''] = value.split(new RegExp(`\\\\s*${NUMBER_SEPARATOR}\\\\s*`));\n\n        if (!/^\\d+$/.test(month) || !/^\\d+$/.test(year)) {\n            return { month: '', year: '' };\n        }\n\n        return {\n            month: month.length === 1 ? `0${month}` : month.slice(0, 2),\n            year: year.length === 2 ? `20${year}` : year.slice(0, 4),\n        };\n    }\n}\n","import { creditCardType, number } from 'card-validator';\nimport { max } from 'lodash';\n\nconst NUMBER_SEPARATOR = ' ';\n\nexport default class CardNumberFormatter {\n    format(value: string): string {\n        const { card } = number(value);\n\n        if (!card) {\n            return value;\n        }\n\n        const maxLength = max(creditCardType(value).map(info => max(info.lengths)));\n        const unformattedValue = this.unformat(value).slice(0, maxLength);\n\n        return card.gaps\n            .filter(gapIndex => unformattedValue.length > gapIndex)\n            .reduce((output, gapIndex, index) => (\n                [\n                    output.slice(0, gapIndex + index),\n                    output.slice(gapIndex + index),\n                ].join(NUMBER_SEPARATOR)\n            ), unformattedValue);\n    }\n\n    unformat(value: string): string {\n        const { card } = number(value);\n\n        if (!card) {\n            return value;\n        }\n\n        return value.replace(new RegExp(NUMBER_SEPARATOR, 'g'), '');\n    }\n}\n","import Coupon from './coupon';\nimport InternalCoupon from './internal-coupon';\n\nconst couponTypes = [\n    'per_item_discount',\n    'percentage_discount',\n    'per_total_discount',\n    'shipping_discount',\n    'free_shipping',\n];\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalCoupon(coupon: Coupon): InternalCoupon {\n    return {\n        code: coupon.code,\n        discount: coupon.displayName,\n        discountType: couponTypes.indexOf(coupon.couponType),\n    };\n}\n","import parseUrl from './parse-url';\nimport Url from './url';\n\nexport default function appendWww(url: Url): Url {\n    return parseUrl(\n        url.hostname.indexOf('www') === 0 ?\n            url.href :\n            url.href.replace(url.hostname, `www.${url.hostname}`)\n    );\n}\n","import StandardError from './standard-error';\n\nexport enum NotInitializedErrorType {\n    CheckoutButtonNotInitialized,\n    CustomerNotInitialized,\n    PaymentNotInitialized,\n    ShippingNotInitialized,\n    SpamProtectionNotInitialized,\n}\n\n/**\n * Throw this error if a method requires a certain initialization call to be\n * made first. Some objects can be constructed but they cannot be used until a\n * separate initialization call is made.\n */\nexport default class NotInitializedError extends StandardError {\n    constructor(\n        public subtype: NotInitializedErrorType\n    ) {\n        super(getErrorMessage(subtype));\n\n        this.name = 'NotInitializedError';\n        this.type = 'not_initialized';\n    }\n}\n\nfunction getErrorMessage(type: NotInitializedErrorType): string {\n    switch (type) {\n    case NotInitializedErrorType.CustomerNotInitialized:\n        return 'Unable to proceed because the customer step of checkout has not been initialized.';\n\n    case NotInitializedErrorType.PaymentNotInitialized:\n        return 'Unable to proceed because the payment step of checkout has not been initialized.';\n\n    case NotInitializedErrorType.ShippingNotInitialized:\n        return 'Unable to proceed because the shipping step of checkout has not been initialized.';\n\n    case NotInitializedErrorType.SpamProtectionNotInitialized:\n        return 'Unable to proceed because the checkout spam protection has not been initialized.';\n\n    default:\n        return 'Unable to proceed because the required component has not been initialized.';\n    }\n}\n","import joinIncludes from './join-includes';\nimport mergeIncludes from './merge-includes';\n\n/**\n * Joins or merges a base list of includes with a set of additional includes.\n */\nexport default function joinOrMergeIncludes<T extends string>(\n    baseIncludes: T[],\n    includeDictionaryOrList: { [key in T]?: boolean } | T[] = []\n): string {\n    return Array.isArray(includeDictionaryOrList) ?\n        joinIncludes([\n            ...baseIncludes,\n            ...includeDictionaryOrList,\n        ]) :\n        mergeIncludes(baseIncludes, includeDictionaryOrList);\n}\n","import { difference, filter, keys, pickBy } from 'lodash';\n\nimport joinIncludes from './join-includes';\n\n/**\n * Merges includes given a list of base includes and a dictionary\n * of includes\n */\nexport default function mergeIncludes<T extends string>(\n    baseIncludes: T[],\n    includesDictionary?: { [key in T]?: boolean }\n): string {\n    const deletions = keys(pickBy(includesDictionary, on => !on));\n    const additions = keys(filter(includesDictionary));\n\n    return joinIncludes([\n            ...difference(baseIncludes, deletions),\n            ...additions,\n        ]);\n}\n","module.exports = require(\"iframe-resizer\");","module.exports = require(\"iframe-resizer/js/iframeResizer.contentWindow\");","import { isPlainObject, omitBy, transform } from 'lodash';\n\nexport default function omitDeep(object: any, predicate: (value: any, key: string) => boolean): any {\n    if (Array.isArray(object)) {\n        return object.map(value => omitDeep(value, predicate));\n    }\n\n    if (isPlainObject(object)) {\n        return transform(omitBy(object, predicate), (result, value, key) => {\n            result[key] = omitDeep(value, predicate);\n        }, {} as { [key: string]: any });\n    }\n\n    return object;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, merge, of, Observable } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { ConfigActionCreator } from '../config';\nimport { FormFieldsActionCreator } from '../form';\n\nimport { CheckoutRequestBody } from './checkout';\nimport { CheckoutActionType, LoadCheckoutAction, UpdateCheckoutAction } from './checkout-actions';\nimport CheckoutRequestSender from './checkout-request-sender';\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\nexport default class CheckoutActionCreator {\n    constructor(\n        private _checkoutRequestSender: CheckoutRequestSender,\n        private _configActionCreator: ConfigActionCreator,\n        private _formFieldsActionCreator: FormFieldsActionCreator\n    ) {}\n\n    loadCheckout(id: string, options?: RequestOptions): Observable<LoadCheckoutAction> {\n        return concat(\n            of(createAction(CheckoutActionType.LoadCheckoutRequested)),\n            merge(\n                this._configActionCreator.loadConfig({ ...options, useCache: true }),\n                this._formFieldsActionCreator.loadFormFields({ ...options, useCache: true }),\n                defer(() => this._checkoutRequestSender.loadCheckout(id, options)\n                    .then(({ body }) => createAction(CheckoutActionType.LoadCheckoutSucceeded, body)))\n            )\n        ).pipe(\n            catchError(error => throwErrorAction(CheckoutActionType.LoadCheckoutFailed, error))\n        );\n    }\n\n    loadDefaultCheckout(options?: RequestOptions): ThunkAction<LoadCheckoutAction, InternalCheckoutSelectors> {\n        return store => concat(\n            of(createAction(CheckoutActionType.LoadCheckoutRequested)),\n            merge(\n                this._configActionCreator.loadConfig(),\n                this._formFieldsActionCreator.loadFormFields({ ...options, useCache: true })\n            ),\n            defer(async () => {\n                const state = store.getState();\n                const context = state.config.getContextConfig();\n\n                if (!context || !context.checkoutId) {\n                    throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n                }\n\n                const { body } = await this._checkoutRequestSender.loadCheckout(context.checkoutId, options);\n\n                return createAction(CheckoutActionType.LoadCheckoutSucceeded, body);\n            })\n        ).pipe(\n            catchError(error => throwErrorAction(CheckoutActionType.LoadCheckoutFailed, error))\n        );\n    }\n\n    updateCheckout(\n        body: CheckoutRequestBody,\n        options?: RequestOptions\n    ): ThunkAction<UpdateCheckoutAction, InternalCheckoutSelectors> {\n        return store => new Observable(observer => {\n            const state = store.getState();\n            const checkout = state.checkout.getCheckout();\n\n            if (!checkout) {\n                throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n            }\n\n            observer.next(createAction(CheckoutActionType.UpdateCheckoutRequested));\n\n            this._checkoutRequestSender.updateCheckout(checkout.id, body, options)\n                .then(({ body }) => {\n                    observer.next(createAction(CheckoutActionType.UpdateCheckoutSucceeded, body));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(CheckoutActionType.UpdateCheckoutFailed, response));\n                });\n        });\n    }\n\n    loadCurrentCheckout(options?: RequestOptions): ThunkAction<LoadCheckoutAction, InternalCheckoutSelectors> {\n        return store => {\n            const state = store.getState();\n            const checkout = state.checkout.getCheckout();\n\n            if (!checkout) {\n                throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n            }\n\n            return this.loadCheckout(checkout.id, options);\n        };\n    }\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { find } from 'lodash';\nimport { Observable, Observer } from 'rxjs';\n\nimport { AddressRequestBody } from '../address';\nimport { Cart } from '../cart';\nimport { CheckoutIncludes, CheckoutParams, CheckoutRequestSender, InternalCheckoutSelectors, ReadableCheckoutStore } from '../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport Consignment, { ConsignmentsRequestBody, ConsignmentAssignmentRequestBody, ConsignmentCreateRequestBody, ConsignmentLineItem, ConsignmentRequestBody, ConsignmentShippingOptionRequestBody, ConsignmentUpdateRequestBody } from './consignment';\nimport { ConsignmentActionType, CreateConsignmentsAction, DeleteConsignmentAction, LoadShippingOptionsAction, UpdateConsignmentAction, UpdateShippingOptionAction } from './consignment-actions';\nimport ConsignmentRequestSender from './consignment-request-sender';\n\nexport default class ConsignmentActionCreator {\n    constructor(\n        private _consignmentRequestSender: ConsignmentRequestSender,\n        private _checkoutRequestSender: CheckoutRequestSender\n    ) {}\n\n    unassignItemsByAddress(\n        consignment: ConsignmentAssignmentRequestBody,\n        options?: RequestOptions\n    ): ThunkAction<DeleteConsignmentAction | UpdateConsignmentAction, InternalCheckoutSelectors> {\n        return store => {\n            const state = store.getState();\n            const checkout = state.checkout.getCheckout();\n\n            if (!checkout) {\n                throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n            }\n\n            const existingConsignment = state.consignments.getConsignmentByAddress(consignment.shippingAddress);\n\n            if (!existingConsignment) {\n                throw new InvalidArgumentError('No consignment found for the specified address');\n            }\n\n            const lineItems = this._removeLineItems(\n                consignment.lineItems,\n                existingConsignment,\n                state.cart.getCart()\n            );\n\n            if (!lineItems.length) {\n                return this.deleteConsignment(existingConsignment.id, options)(store);\n            }\n\n            return this.updateConsignment({\n                id: existingConsignment.id,\n                shippingAddress: consignment.shippingAddress,\n                lineItems,\n            }, options)(store);\n        };\n    }\n\n    assignItemsByAddress(\n        consignment: ConsignmentAssignmentRequestBody,\n        options?: RequestOptions\n    ): ThunkAction<UpdateConsignmentAction | CreateConsignmentsAction, InternalCheckoutSelectors> {\n        return store => {\n            const state = store.getState();\n            const existingConsignment = state.consignments.getConsignmentByAddress(consignment.shippingAddress);\n\n            return this._createOrUpdateConsignment({\n                id: existingConsignment && existingConsignment.id,\n                shippingAddress: consignment.shippingAddress,\n                lineItems: this._addLineItems(\n                    consignment.lineItems,\n                    existingConsignment,\n                    state.cart.getCart()\n                ),\n            }, options)(store);\n        };\n    }\n\n    selectShippingOption(\n        id: string,\n        options?: RequestOptions\n    ): ThunkAction<UpdateShippingOptionAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<UpdateShippingOptionAction>) => {\n            const state = store.getState();\n            const checkout = state.checkout.getCheckout();\n            const consignments = state.consignments.getConsignments();\n\n            if (!checkout) {\n                throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n            }\n\n            if (!consignments || !consignments.length) {\n                throw new MissingDataError(MissingDataErrorType.MissingConsignments);\n            }\n\n            const consignmentUpdateBody = {\n                id: consignments[0].id,\n                shippingOptionId: id,\n            };\n\n            const consignmentMeta = {\n                id: consignments[0].id,\n            };\n\n            observer.next(createAction(ConsignmentActionType.UpdateShippingOptionRequested, undefined, consignmentMeta));\n\n            this._consignmentRequestSender.updateConsignment(checkout.id, consignmentUpdateBody, options)\n                .then(({ body }) => {\n                    observer.next(createAction(\n                        ConsignmentActionType.UpdateShippingOptionSucceeded,\n                        body,\n                        consignmentMeta\n                    ));\n\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(\n                        ConsignmentActionType.UpdateShippingOptionFailed,\n                        response,\n                        consignmentMeta\n                    ));\n                });\n        });\n    }\n\n    loadShippingOptions(options?: RequestOptions): ThunkAction<LoadShippingOptionsAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<LoadShippingOptionsAction>) => {\n            const checkout = store.getState().checkout.getCheckout();\n\n            if (!checkout) {\n                throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n            }\n\n            observer.next(createAction(ConsignmentActionType.LoadShippingOptionsRequested));\n\n            this._checkoutRequestSender.loadCheckout(checkout.id, {\n                ...options,\n                params: {\n                    include: [CheckoutIncludes.AvailableShippingOptions],\n                },\n            })\n            .then(({ body }) => {\n                observer.next(createAction(ConsignmentActionType.LoadShippingOptionsSucceeded, body));\n                observer.complete();\n            })\n            .catch(response => {\n                observer.error(createErrorAction(ConsignmentActionType.LoadShippingOptionsFailed, response));\n            });\n        });\n    }\n\n    updateAddress(\n        address: AddressRequestBody,\n        options?: RequestOptions<CheckoutParams>\n    ): ThunkAction<CreateConsignmentsAction | UpdateConsignmentAction, InternalCheckoutSelectors> {\n        return store => {\n            const consignment = this._getUpdateAddressRequestBody(address, store);\n            const consignments = store.getState().consignments.getConsignments();\n\n            if (consignments && consignments.length) {\n                (consignment as ConsignmentUpdateRequestBody).id = consignments[0].id;\n            }\n\n            return this._createOrUpdateConsignment(consignment, options)(store);\n        };\n    }\n\n    createConsignments(\n        consignments: ConsignmentsRequestBody,\n        options?: RequestOptions<CheckoutParams>\n    ): ThunkAction<CreateConsignmentsAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<CreateConsignmentsAction>) => {\n            const checkout = store.getState().checkout.getCheckout();\n\n            if (!checkout || !checkout.id) {\n                throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n            }\n\n            observer.next(createAction(ConsignmentActionType.CreateConsignmentsRequested));\n\n            this._consignmentRequestSender.createConsignments(checkout.id, consignments, options)\n                .then(({ body }) => {\n                    observer.next(createAction(ConsignmentActionType.CreateConsignmentsSucceeded, body));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(ConsignmentActionType.CreateConsignmentsFailed, response));\n                });\n        });\n    }\n\n    updateConsignment(\n        consignment: ConsignmentUpdateRequestBody,\n        options?: RequestOptions<CheckoutParams>\n    ): ThunkAction<UpdateConsignmentAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<UpdateConsignmentAction>) => {\n            const checkout = store.getState().checkout.getCheckout();\n\n            if (!checkout || !checkout.id) {\n                throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n            }\n\n            const consignmentMeta = { id: consignment.id };\n\n            observer.next(createAction(ConsignmentActionType.UpdateConsignmentRequested, undefined, consignmentMeta));\n\n            this._consignmentRequestSender.updateConsignment(checkout.id, consignment, options)\n                .then(({ body }) => {\n                    observer.next(createAction(ConsignmentActionType.UpdateConsignmentSucceeded, body, consignmentMeta));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(ConsignmentActionType.UpdateConsignmentFailed, response, consignmentMeta));\n                });\n        });\n    }\n\n    deleteConsignment(\n        consignmentId: string,\n        options?: RequestOptions\n    ): ThunkAction<DeleteConsignmentAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<DeleteConsignmentAction>) => {\n            const checkout = store.getState().checkout.getCheckout();\n            const consignmentMeta = { id: consignmentId };\n\n            if (!checkout || !checkout.id) {\n                throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n            }\n\n            observer.next(createAction(ConsignmentActionType.DeleteConsignmentRequested, undefined, consignmentMeta));\n\n            this._consignmentRequestSender.deleteConsignment(checkout.id, consignmentId, options)\n                .then(({ body }) => {\n                    observer.next(createAction(ConsignmentActionType.DeleteConsignmentSucceeded, body, consignmentMeta));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(ConsignmentActionType.DeleteConsignmentFailed, response, consignmentMeta));\n                });\n        });\n    }\n\n    updateShippingOption(\n        consignment: ConsignmentShippingOptionRequestBody,\n        options?: RequestOptions\n    ): ThunkAction<UpdateShippingOptionAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<UpdateShippingOptionAction>) => {\n            const checkout = store.getState().checkout.getCheckout();\n\n            if (!checkout || !checkout.id) {\n                throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n            }\n\n            const consignmentMeta = { id: consignment.id };\n\n            observer.next(createAction(ConsignmentActionType.UpdateShippingOptionRequested, undefined, consignmentMeta));\n\n            this._consignmentRequestSender.updateConsignment(checkout.id, consignment, options)\n                .then(({ body }) => {\n                    observer.next(createAction(ConsignmentActionType.UpdateShippingOptionSucceeded, body, consignmentMeta));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(ConsignmentActionType.UpdateShippingOptionFailed, response, consignmentMeta));\n                });\n        });\n    }\n\n    private _createOrUpdateConsignment(\n        consignment: ConsignmentCreateRequestBody | ConsignmentUpdateRequestBody,\n        options?: RequestOptions<CheckoutParams>\n    ): ThunkAction<UpdateConsignmentAction | CreateConsignmentsAction, InternalCheckoutSelectors> {\n        return store => {\n            const checkout = store.getState().checkout.getCheckout();\n\n            if (!checkout || !checkout.id) {\n                throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n            }\n\n            if (this._isUpdateConsignmentRequest(consignment)) {\n                return this.updateConsignment(consignment, options)(store);\n            }\n\n            return this.createConsignments([consignment], options)(store);\n        };\n    }\n\n    private _getUpdateAddressRequestBody(\n        shippingAddress: AddressRequestBody,\n        store: ReadableCheckoutStore\n    ): ConsignmentRequestBody {\n        const state = store.getState();\n        const cart = state.cart.getCart();\n\n        if (!cart) {\n            throw new MissingDataError(MissingDataErrorType.MissingCart);\n        }\n        const { physicalItems, customItems = [] } = cart.lineItems;\n\n        return {\n            shippingAddress,\n            lineItems: [ ...physicalItems, ...customItems ].map(item => ({\n                itemId: item.id,\n                quantity: item.quantity,\n            })),\n        };\n    }\n\n    private _removeLineItems(\n        lineItems: ConsignmentLineItem[],\n        consignment: Consignment,\n        cart?: Cart\n    ): ConsignmentLineItem[] {\n        if (!cart) {\n            throw new MissingDataError(MissingDataErrorType.MissingCart);\n        }\n\n        return this._hydrateLineItems(consignment.lineItemIds, cart).map(existingItem => {\n            const sharedItem = find(lineItems, lineItem => lineItem.itemId === existingItem.itemId);\n\n            return {\n                ...existingItem,\n                quantity: sharedItem ? (existingItem.quantity - sharedItem.quantity) : existingItem.quantity,\n            };\n        }).filter(lineItem => lineItem.quantity > 0);\n    }\n\n    private _addLineItems(\n        lineItems: ConsignmentLineItem[],\n        consignment?: Consignment,\n        cart?: Cart\n    ): ConsignmentLineItem[] {\n        if (!consignment) {\n            return lineItems;\n        }\n\n        if (!cart) {\n            throw new MissingDataError(MissingDataErrorType.MissingCart);\n        }\n\n        return lineItems\n            .concat(this._hydrateLineItems(consignment.lineItemIds, cart))\n            .filter(lineItem => lineItem.quantity > 0);\n    }\n\n    private _hydrateLineItems(lineItemIds: string[], cart: Cart): ConsignmentLineItem[] {\n        return lineItemIds.map(itemId => {\n            const item = find(cart.lineItems.physicalItems, lineItem => lineItem.id === itemId);\n\n            return {\n                itemId,\n                quantity: item ? item.quantity : 0,\n            };\n        });\n    }\n\n    private _isUpdateConsignmentRequest(\n        request: ConsignmentRequestBody\n    ): request is ConsignmentUpdateRequestBody {\n        const updateRequest = request as ConsignmentUpdateRequestBody;\n\n        return !!updateRequest.id;\n    }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CheckoutParams } from '../checkout';\nimport { joinIncludes, joinOrMergeIncludes, ContentType, RequestOptions } from '../common/http-request';\n\nimport { ConsignmentsRequestBody, ConsignmentUpdateRequestBody } from './consignment';\n\nconst DEFAULT_INCLUDES = [\n        'consignments.availableShippingOptions',\n        'cart.lineItems.physicalItems.options',\n        'cart.lineItems.digitalItems.options',\n        'customer',\n        'promotions.banners',\n    ];\n\nexport default class ConsignmentRequestSender {\n    constructor(\n        private _requestSender: RequestSender\n    ) {}\n\n    createConsignments(\n        checkoutId: string,\n        consignments: ConsignmentsRequestBody,\n        { timeout, params: { include } = {} }: RequestOptions<CheckoutParams> = {}\n    ): Promise<Response<Checkout>> {\n        const url = `/api/storefront/checkouts/${checkoutId}/consignments`;\n        const headers = { Accept: ContentType.JsonV1 };\n\n        return this._requestSender.post(url, {\n            body: consignments,\n            params: {\n                include: joinOrMergeIncludes(DEFAULT_INCLUDES, include),\n            },\n            headers,\n            timeout,\n        });\n    }\n\n    updateConsignment(\n        checkoutId: string,\n        consignment: ConsignmentUpdateRequestBody,\n        { timeout, params: { include } = {} }: RequestOptions<CheckoutParams> = {}\n    ): Promise<Response<Checkout>> {\n        const { id, ...body } = consignment;\n        const url = `/api/storefront/checkouts/${checkoutId}/consignments/${id}`;\n        const headers = { Accept: ContentType.JsonV1 };\n\n        return this._requestSender.put(url, {\n            body,\n            params: {\n                include: joinOrMergeIncludes(DEFAULT_INCLUDES, include),\n            },\n            headers,\n            timeout,\n        });\n    }\n\n    deleteConsignment(\n        checkoutId: string,\n        consignmentId: string,\n        { timeout }: RequestOptions = {}\n    ): Promise<Response<Checkout>> {\n        const url = `/api/storefront/checkouts/${checkoutId}/consignments/${consignmentId}`;\n        const headers = { Accept: ContentType.JsonV1 };\n        const include = joinIncludes(DEFAULT_INCLUDES);\n\n        return this._requestSender.delete(url, { params: { include }, headers, timeout });\n    }\n}\n","export default function getCallbackUrl(origin: string): string {\n    return `${window.location.origin}/checkout.php?action=set_external_checkout&provider=masterpass&gateway=stripe&origin=${origin}`;\n}\n","import { pick } from 'lodash';\n\nimport { mapToInternalAddress } from '../address';\nimport { mapToInternalCart } from '../cart';\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { mapToInternalCustomer } from '../customer';\nimport { HostedFormOrderData } from '../hosted-form';\nimport { CardExpiryFormatter, CardNumberFormatter, HostedInputValues } from '../hosted-form/iframe-content';\nimport { mapToInternalOrder } from '../order';\nimport { mapToInternalShippingOption } from '../shipping';\n\nimport isVaultedInstrument, { isFormattedVaultedInstrument } from './is-vaulted-instrument';\nimport Payment, { HostedCreditCardInstrument, HostedVaultedInstrument, PaymentInstrument } from './payment';\nimport PaymentMethod from './payment-method';\nimport PaymentRequestBody from './payment-request-body';\n\nexport default class PaymentRequestTransformer {\n    private _cardExpiryFormatter = new CardExpiryFormatter();\n    private _cardNumberFormatter = new CardNumberFormatter();\n\n    transform(payment: Payment, checkoutState: InternalCheckoutSelectors): PaymentRequestBody {\n        const billingAddress = checkoutState.billingAddress.getBillingAddress();\n        const checkout = checkoutState.checkout.getCheckout();\n        const customer = checkoutState.customer.getCustomer();\n        const order = checkoutState.order.getOrder();\n        const paymentMethod = checkoutState.paymentMethods.getPaymentMethod(payment.methodId, payment.gatewayId);\n        const shippingAddress = checkoutState.shippingAddress.getShippingAddress();\n        const consignments = checkoutState.consignments.getConsignments();\n        const shippingOption = checkoutState.consignments.getShippingOption();\n        const storeConfig = checkoutState.config.getStoreConfig();\n        const contextConfig = checkoutState.config.getContextConfig();\n        const instrumentMeta = checkoutState.instruments.getInstrumentsMeta();\n        const paymentMeta = checkoutState.paymentMethods.getPaymentMethodsMeta();\n        const orderMeta = checkoutState.order.getOrderMeta();\n        const internalCustomer = customer && billingAddress && mapToInternalCustomer(customer, billingAddress);\n\n        const authToken = instrumentMeta && payment.paymentData &&\n            (isVaultedInstrument(payment.paymentData) || isFormattedVaultedInstrument(payment.paymentData)) ?\n            `${checkoutState.payment.getPaymentToken()}, ${instrumentMeta.vaultAccessToken}` :\n            checkoutState.payment.getPaymentToken();\n\n        if (!authToken) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n        }\n\n        return {\n            additionalAction: payment.additionalAction,\n            authToken,\n            customer: internalCustomer,\n            billingAddress: billingAddress && mapToInternalAddress(billingAddress),\n            shippingAddress: shippingAddress && mapToInternalAddress(shippingAddress, consignments),\n            shippingOption: shippingOption && mapToInternalShippingOption(shippingOption, true),\n            cart: checkout && mapToInternalCart(checkout),\n            order: order && mapToInternalOrder(order, orderMeta),\n            orderMeta,\n            payment: payment.paymentData,\n            paymentMethod: paymentMethod && this._transformPaymentMethod(paymentMethod),\n            quoteMeta: {\n                request: {\n                    ...paymentMeta,\n                    geoCountryCode: contextConfig && contextConfig.geoCountryCode,\n                },\n            },\n            source: 'bigcommerce-checkout-js-sdk',\n            store: pick(storeConfig && storeConfig.storeProfile, [\n                'storeHash',\n                'storeId',\n                'storeLanguage',\n                'storeName',\n            ]),\n        };\n    }\n\n    transformWithHostedFormData(values: HostedInputValues, data: HostedFormOrderData, nonce: string): PaymentRequestBody {\n        const { additionalAction, authToken, checkout, config, order, orderMeta, payment = {}, paymentMethod, paymentMethodMeta } = data;\n        const consignment = checkout && checkout.consignments[0];\n        const shippingAddress = consignment && consignment.shippingAddress;\n        const shippingOption = consignment && consignment.selectedShippingOption;\n\n        return {\n            additionalAction,\n            authToken,\n            paymentMethod: paymentMethod && this._transformPaymentMethod(paymentMethod),\n            customer: order && order.billingAddress && checkout && mapToInternalCustomer(checkout.customer, order.billingAddress),\n            billingAddress: order && order.billingAddress && mapToInternalAddress(order.billingAddress),\n            shippingAddress: shippingAddress && checkout && mapToInternalAddress(shippingAddress, checkout.consignments),\n            shippingOption: shippingOption && mapToInternalShippingOption(shippingOption, true),\n            cart: checkout && mapToInternalCart(checkout),\n            order: order && mapToInternalOrder(order, orderMeta),\n            orderMeta,\n            payment: this._transformHostedInputValues(values, payment, nonce),\n            quoteMeta: {\n                request: {\n                    ...paymentMethodMeta,\n                    geoCountryCode: config && config.context.geoCountryCode,\n                },\n            },\n            source: 'bigcommerce-checkout-js-sdk',\n            store: config && pick(config.storeConfig.storeProfile, [\n                'storeHash',\n                'storeId',\n                'storeLanguage',\n                'storeName',\n            ]),\n        };\n    }\n\n    private _transformPaymentMethod(paymentMethod: PaymentMethod): PaymentMethod {\n        if (paymentMethod.method === 'multi-option' && !paymentMethod.gateway) {\n            return { ...paymentMethod, gateway: paymentMethod.id };\n        }\n\n        if (paymentMethod.initializationData && paymentMethod.initializationData.gateway) {\n            return { ...paymentMethod, id: paymentMethod.initializationData.gateway };\n        }\n\n        return paymentMethod;\n    }\n\n    private _transformHostedInputValues(\n        values: HostedInputValues,\n        payment: HostedCreditCardInstrument | HostedVaultedInstrument,\n        nonce: string\n    ): PaymentInstrument {\n        return 'instrumentId' in payment ?\n            {\n                ...payment,\n                ccCvv: values.cardCodeVerification,\n                ccNumber: values.cardNumberVerification && this._cardNumberFormatter.unformat(values.cardNumberVerification),\n                hostedFormNonce: nonce,\n            } :\n            {\n                ...payment,\n                ccCvv: values.cardCode,\n                ccExpiry: this._cardExpiryFormatter.toObject(values.cardExpiry || ''),\n                ccName: values.cardName || '',\n                ccNumber: this._cardNumberFormatter.unformat(values.cardNumber || ''),\n                hostedFormNonce: nonce,\n            };\n    }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport PaymentRequestBody from './payment-request-body';\n\n/**\n * @todo Convert this file into TypeScript properly\n */\nexport default class PaymentRequestSender {\n    /**\n     * @constructor\n     * @param {BigpayClient} client\n     */\n    constructor(\n        private _client: any\n    ) {}\n\n    submitPayment(payload: PaymentRequestBody): Promise<Response<any>> {\n        return new Promise((resolve, reject) => {\n            this._client.submitPayment(payload, (error: any, response: any) => {\n                if (error) {\n                    reject(this._transformResponse(error));\n                } else {\n                    resolve(this._transformResponse(response));\n                }\n            });\n        });\n    }\n\n    initializeOffsitePayment(payload: PaymentRequestBody, target?: string): Promise<void> {\n        return new Promise(() => {\n            this._client.initializeOffsitePayment(payload, null, target);\n        });\n    }\n\n    private _transformResponse(response: any): Response<any> {\n        return {\n            headers: response.headers,\n            body: response.data,\n            status: response.status,\n            statusText: response.statusText,\n        };\n    }\n}\n","export default function isPrivate(key: string): boolean {\n    return `${key}`.indexOf('$$') === 0 || `${key}`.indexOf('_') === 0;\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport RequestError from './request-error';\n\n/**\n * Throw this error if there is an unexpected error and it is not possible to\n * recover from unless the shopper creates a new checkout session.\n */\nexport default class UnrecoverableError<T = any> extends RequestError {\n    constructor(response: Response<T>, message?: string) {\n        super(response, {\n            message: message || 'An unexpected error has occurred. The checkout process cannot continue as a result.',\n        });\n\n        this.name = 'UnrecoverableError';\n        this.type = 'unrecoverable';\n    }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { InternalErrorResponseBody } from '../error-response-body';\n\nimport RequestError from './request-error';\n\nexport default function mapFromInternalErrorResponse(\n    response: Response<InternalErrorResponseBody>,\n    message?: string\n): RequestError {\n    const { body } = response;\n    const { errors = [] } = body;\n\n    return new RequestError(response, {\n        message: joinErrors(errors) || body.detail || body.title || message,\n        errors: errors.length ?\n            errors.map(message => ({ code: body.type, message })) :\n            [{ code: body.type, message: body.detail || body.title }],\n    });\n}\n\nfunction joinErrors(errors: string[]): string | undefined {\n    return errors.reduce((result: string[], error) => {\n        if (error) {\n            return [...result, error];\n        }\n\n        return result;\n    }, []).join(' ');\n}\n","import { Response } from '@bigcommerce/request-sender';\nimport { last } from 'lodash';\n\nimport ErrorResponseBody, { InternalErrorResponseBody, StorefrontErrorResponseBody } from './error-response-body';\nimport { mapFromInternalErrorResponse, mapFromPaymentErrorResponse, mapFromStorefrontErrorResponse, RequestError, TimeoutError } from './errors';\n\nexport default class RequestErrorFactory {\n    private _factoryMethods: { [key: string]: ErrorFactoryMethod } = {};\n\n    constructor() {\n        this.register('default', (response, message) => new RequestError(response, { message }));\n        this.register('internal', (response, message) => mapFromInternalErrorResponse(response, message));\n        this.register('storefront', (response, message) => mapFromStorefrontErrorResponse(response, message));\n        this.register('payment', (response, message) => mapFromPaymentErrorResponse(response, message));\n        this.register('timeout', response => new TimeoutError(response));\n    }\n\n    register(type: string, factoryMethod: ErrorFactoryMethod): void {\n        this._factoryMethods[type] = factoryMethod;\n    }\n\n    createError(response: Response<any>, message?: string): RequestError {\n        const factoryMethod = this._factoryMethods[this._getType(response)] || this._factoryMethods.default;\n\n        return factoryMethod(response, message);\n    }\n\n    private _getType(response: Response<ErrorResponseBody>): string {\n        if (response.status === 0) {\n            return 'timeout';\n        }\n\n        if (this._isStorefrontErrorResponseBody(response.body)) {\n            return 'storefront';\n        }\n\n        if (this._isInternalErrorResponseBody(response.body)) {\n            const internalType = last(response.body.type.split('/'));\n\n            return internalType && this._factoryMethods[internalType] ?\n                internalType :\n                'internal';\n        }\n\n        const error = last(response.body && response.body.errors);\n\n        if (error && error.code && this._factoryMethods[error.code]) {\n            return error.code;\n        }\n\n        return 'payment';\n    }\n\n    private _isStorefrontErrorResponseBody(\n        errorResponse: ErrorResponseBody\n    ): errorResponse is StorefrontErrorResponseBody {\n        const storefrontErrorResponse = errorResponse as StorefrontErrorResponseBody;\n\n        return !this._isInternalErrorResponseBody(errorResponse) &&\n            typeof storefrontErrorResponse.title === 'string' &&\n            typeof storefrontErrorResponse.type === 'string' &&\n            typeof storefrontErrorResponse.status === 'number' &&\n            typeof storefrontErrorResponse.detail === 'string';\n    }\n\n    private _isInternalErrorResponseBody(\n        errorResponse: ErrorResponseBody\n    ): errorResponse is InternalErrorResponseBody {\n        const internalErrorResponse = errorResponse as InternalErrorResponseBody;\n\n        return typeof internalErrorResponse.errors === 'object' &&\n            typeof internalErrorResponse.title === 'string' &&\n            typeof internalErrorResponse.type === 'string' &&\n            typeof internalErrorResponse.status === 'number';\n    }\n}\n\nexport type ErrorFactoryMethod<T = any> = (response: Response<T>, message?: string) => RequestError;\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { StorefrontErrorResponseBody } from '../error-response-body';\n\nimport RequestError from './request-error';\n\nexport default function mapFromStorefrontErrorResponse(\n    response: Response<StorefrontErrorResponseBody>,\n    message?: string\n): RequestError<StorefrontErrorResponseBody> {\n    const { body } = response;\n\n    return new RequestError(response, {\n        message: message || body.detail || body.title,\n        errors: [{\n            code: body.code || body.type,\n            message: body.detail || body.title,\n        }],\n    });\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { omitDeep } from '../utility';\n\nimport { ClearErrorAction, ErrorActionType } from './error-actions';\n\nexport default function clearErrorReducer<TState extends { [key: string]: any }, TAction extends Action>(\n    state: TState,\n    action: TAction\n): TState | undefined {\n    if (isClearErrorAction(action)) {\n        return omitDeep(state, value => value === action.payload);\n    }\n\n    return state;\n}\n\nfunction isClearErrorAction(action: Action): action is ClearErrorAction {\n    return action.type === ErrorActionType.ClearError;\n}\n","import isEqual from './is-equal';\n\n/**\n * Replace the current value with a new value if the former is different to the\n * latter.\n */\nexport default function replace<T>(currentValue: T, newValue?: T): T {\n    if (newValue === undefined || isEqual(currentValue, newValue)) {\n        return currentValue;\n    }\n\n    return newValue;\n}\n","import isEqual from './is-equal';\n\n/**\n * Set a new value to an object under a key if the new value is different to the\n * current value of the key.\n */\nexport default function objectSet<T extends { [key: string]: any }, K extends keyof T>(\n    object: T | undefined,\n    key: K,\n    value: T[K]\n): T {\n    if (object && object.hasOwnProperty(key) && isEqual(object[key], value)) {\n        return object;\n    }\n\n    return {\n        ...object as any,\n        [key]: value,\n    };\n}\n","import BillingAddress from './billing-address';\n\nexport default interface BillingAddressState {\n    data?: BillingAddress;\n    errors: BillingAddressErrorsState;\n    statuses: BillingAddressStatusesState;\n}\n\nexport interface BillingAddressErrorsState {\n    loadError?: Error;\n    updateError?: Error;\n    continueAsGuestError?: Error;\n}\n\nexport interface BillingAddressStatusesState {\n    isLoading?: boolean;\n    isUpdating?: boolean;\n    isContinuingAsGuest?: boolean;\n}\n\nexport const DEFAULT_STATE: BillingAddressState = {\n    errors: {},\n    statuses: {},\n};\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectSet, replace } from '../common/utility';\nimport { OrderAction, OrderActionType } from '../order';\nimport { SubscriptionsActionType, UpdateSubscriptionsAction } from '../subscription';\n\nimport BillingAddress from './billing-address';\nimport { BillingAddressAction, BillingAddressActionType } from './billing-address-actions';\nimport BillingAddressState, { BillingAddressErrorsState, BillingAddressStatusesState, DEFAULT_STATE } from './billing-address-state';\n\nexport default function billingAddressReducer(\n    state: BillingAddressState = DEFAULT_STATE,\n    action: Action\n): BillingAddressState {\n    const reducer = combineReducers<BillingAddressState>({\n        data: dataReducer,\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: BillingAddress | undefined,\n    action: CheckoutAction | BillingAddressAction | OrderAction\n): BillingAddress | undefined {\n    switch (action.type) {\n    case BillingAddressActionType.UpdateBillingAddressSucceeded:\n    case BillingAddressActionType.ContinueAsGuestSucceeded:\n    case CheckoutActionType.LoadCheckoutSucceeded:\n    case OrderActionType.LoadOrderSucceeded:\n        return replace(data, action.payload && action.payload.billingAddress);\n\n    default:\n        return data;\n    }\n}\n\nfunction errorsReducer(\n    errors: BillingAddressErrorsState = DEFAULT_STATE.errors,\n    action: CheckoutAction | BillingAddressAction | OrderAction | UpdateSubscriptionsAction\n): BillingAddressErrorsState {\n    switch (action.type) {\n    case CheckoutActionType.LoadCheckoutRequested:\n    case CheckoutActionType.LoadCheckoutSucceeded:\n        return objectSet(errors, 'loadError', undefined);\n\n    case CheckoutActionType.LoadCheckoutFailed:\n        return objectSet(errors, 'loadError', action.payload);\n\n    case BillingAddressActionType.UpdateBillingAddressRequested:\n    case BillingAddressActionType.UpdateBillingAddressSucceeded:\n        return objectSet(errors, 'updateError', undefined);\n\n    case BillingAddressActionType.UpdateBillingAddressFailed:\n        return objectSet(errors, 'updateError', action.payload);\n\n    case SubscriptionsActionType.UpdateSubscriptionsRequested:\n    case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n    case BillingAddressActionType.ContinueAsGuestRequested:\n    case BillingAddressActionType.ContinueAsGuestSucceeded:\n        return objectSet(errors, 'continueAsGuestError', undefined);\n\n    case SubscriptionsActionType.UpdateSubscriptionsFailed:\n    case BillingAddressActionType.ContinueAsGuestFailed:\n        return objectSet(errors, 'continueAsGuestError', action.payload);\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: BillingAddressStatusesState = DEFAULT_STATE.statuses,\n    action: CheckoutAction | BillingAddressAction | OrderAction | UpdateSubscriptionsAction\n): BillingAddressStatusesState {\n    switch (action.type) {\n    case CheckoutActionType.LoadCheckoutRequested:\n        return objectSet(statuses, 'isLoading', true);\n\n    case CheckoutActionType.LoadCheckoutSucceeded:\n    case CheckoutActionType.LoadCheckoutFailed:\n        return objectSet(statuses, 'isLoading', false);\n\n    case BillingAddressActionType.UpdateBillingAddressRequested:\n        return objectSet(statuses, 'isUpdating', true);\n\n    case BillingAddressActionType.UpdateBillingAddressFailed:\n    case BillingAddressActionType.UpdateBillingAddressSucceeded:\n        return objectSet(statuses, 'isUpdating', false);\n\n    case BillingAddressActionType.ContinueAsGuestRequested:\n    case SubscriptionsActionType.UpdateSubscriptionsRequested:\n        return objectSet(statuses, 'isContinuingAsGuest', true);\n\n    case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n    case SubscriptionsActionType.UpdateSubscriptionsFailed:\n    case BillingAddressActionType.ContinueAsGuestFailed:\n    case BillingAddressActionType.ContinueAsGuestSucceeded:\n        return objectSet(statuses, 'isContinuingAsGuest', false);\n\n    default:\n        return statuses;\n    }\n}\n","import { isArray } from 'lodash';\n\nimport isPlainObject from './is-plain-object';\nimport objectMerge from './object-merge';\nimport replace from './replace';\n\nexport interface ArrayReplaceOptions {\n    matchObject(objectA: any, objectB: any): boolean;\n}\n\nfunction arrayReplace<T>(currentArray: T[] | undefined, newArray: T[], options?: ArrayReplaceOptions): T[];\nfunction arrayReplace<T>(currentArray: T[], newArray?: T[], options?: ArrayReplaceOptions): undefined;\nfunction arrayReplace<T>(currentArray?: T[], newArray?: T[], options?: ArrayReplaceOptions): T[] | undefined;\nfunction arrayReplace<T>(currentArray?: T[], newArray?: T[], options?: ArrayReplaceOptions): T[] | undefined {\n    const { matchObject = (a: any, b: any) => a.id !== undefined && a.id === b.id } = options || {};\n\n    // Return the new array if the current array does not exist\n    if (!currentArray) {\n        return newArray;\n    }\n\n    // If the new array does not exist, or the current array is strictly equal\n    // to the new array, exit early and return the current array so that the\n    // object reference doesn't change\n    if (!newArray || currentArray === newArray) {\n        return currentArray;\n    }\n\n    // Otherwise, try to replace the items of the current array with the new\n    // array. If the item from the two arrays are the same, keep the current\n    // one. Do it recursively until all arrays are replaced.\n    let sameAsCurrentCount = 0;\n    let sameAsNewCount = 0;\n\n    const countSameAsReplaced = <T>(replacedValue: T, currentValue: T, newValue: T): T => {\n        sameAsCurrentCount += replacedValue === currentValue ? 1 : 0;\n        sameAsNewCount += replacedValue === newValue ? 1 : 0;\n\n        return replacedValue;\n    };\n\n    const result = newArray.map((newItem, index) => {\n        const currentItem = currentArray && currentArray[index];\n\n        if (isPlainObject(currentItem) && isPlainObject(newItem)) {\n            if (matchObject(currentItem, newItem)) {\n                return countSameAsReplaced(\n                    objectMerge(currentItem, newItem),\n                    currentItem,\n                    newItem\n                );\n            }\n\n            return countSameAsReplaced(\n                replace(currentItem, newItem),\n                currentItem,\n                newItem\n            );\n        }\n\n        if (isArray(currentItem) && isArray(newItem)) {\n            return countSameAsReplaced(\n                arrayReplace(currentItem, newItem),\n                currentItem,\n                newItem\n            );\n        }\n\n        return countSameAsReplaced(\n            replace(currentItem, newItem),\n            currentItem,\n            newItem\n        );\n    }) as T[];\n\n    // If all items in the result are identical to the current array, and the\n    // current array and the new array have the same size, simply return the\n    // current array instead of the result.\n    if (sameAsCurrentCount === newArray.length && (currentArray && currentArray.length === newArray.length)) {\n        return currentArray;\n    }\n\n    // If all items in the result are identical to the new array, simply return\n    // the new array.\n    if (sameAsNewCount === newArray.length) {\n        return newArray;\n    }\n\n    return result;\n}\n\nexport default arrayReplace;\n","import { isArray } from 'lodash';\n\nimport arrayReplace from './array-replace';\nimport isPlainObject from './is-plain-object';\nimport objectSet from './object-set';\n\nfunction objectMerge<T extends object>(currentObject: T, newObject?: Partial<T>): T;\nfunction objectMerge<T extends object>(currentObject: T | undefined, newObject: Partial<T>): Partial<T>;\nfunction objectMerge<T extends object>(currentObject?: T, newObject?: Partial<T>): T | undefined;\nfunction objectMerge<T extends object>(currentObject?: T, newObject?: Partial<T>): T | Partial<T> | undefined {\n    if (!currentObject) {\n        return newObject;\n    }\n\n    // If the new object does not exist but the current object does, or the new\n    // object is strictly equal to the current object, return the current object\n    if (!newObject || currentObject === newObject) {\n        return currentObject;\n    }\n\n    // If both objects exist, but some values might be different, perform a merge.\n    // Retain values that are equal and only replace them with the new values if\n    // they are different.\n    return (Object.keys(newObject) as Array<keyof T>)\n        .reduce((result, key) => {\n            const currentValue = result[key];\n            const newValue = newObject[key];\n\n            if (isPlainObject(currentValue) && isPlainObject(newValue)) {\n                return objectSet(result, key, objectMerge(currentValue, newValue));\n            }\n\n            if (isArray(currentValue) && isArray(newValue)) {\n                return objectSet(result, key, arrayReplace(currentValue, newValue) as any);\n            }\n\n            return objectSet(result, key, newValue as any);\n        }, currentObject);\n}\n\nexport default objectMerge;\n","import Cart from './cart';\n\nexport default interface CartState {\n    data?: Cart;\n    errors: CartErrorsState;\n    statuses: CartStatusesState;\n}\n\nexport interface CartErrorsState {\n    loadError?: Error;\n}\n\nexport interface CartStatusesState {\n    isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: CartState = {\n    errors: {},\n    statuses: {},\n};\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\n\nimport { BillingAddressAction, BillingAddressActionType } from '../billing';\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\nimport { CouponAction, CouponActionType, GiftCertificateAction, GiftCertificateActionType } from '../coupon';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\n\nimport Cart from './cart';\nimport CartState, { CartErrorsState, CartStatusesState, DEFAULT_STATE } from './cart-state';\n\nexport default function cartReducer(\n    state: CartState = DEFAULT_STATE,\n    action: Action\n): CartState {\n    const reducer = combineReducers<CartState>({\n        data: dataReducer,\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: Cart | undefined,\n    action: BillingAddressAction | CheckoutAction | ConsignmentAction | CouponAction | GiftCertificateAction\n): Cart | undefined {\n    switch (action.type) {\n    case BillingAddressActionType.UpdateBillingAddressSucceeded:\n    case CheckoutActionType.LoadCheckoutSucceeded:\n    case ConsignmentActionType.CreateConsignmentsSucceeded:\n    case ConsignmentActionType.DeleteConsignmentSucceeded:\n    case ConsignmentActionType.UpdateConsignmentSucceeded:\n    case ConsignmentActionType.UpdateShippingOptionSucceeded:\n    case ConsignmentActionType.LoadShippingOptionsSucceeded:\n    case CouponActionType.ApplyCouponSucceeded:\n    case CouponActionType.RemoveCouponSucceeded:\n    case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n    case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n        return objectMerge(data, action.payload && action.payload.cart);\n\n    default:\n        return data;\n    }\n}\n\nfunction statusesReducer(\n    statuses: CartStatusesState = DEFAULT_STATE.statuses,\n    action: CheckoutAction\n): CartStatusesState {\n    switch (action.type) {\n    case CheckoutActionType.LoadCheckoutRequested:\n        return objectSet(statuses, 'isLoading', true);\n\n    case CheckoutActionType.LoadCheckoutFailed:\n    case CheckoutActionType.LoadCheckoutSucceeded:\n        return objectSet(statuses, 'isLoading', false);\n\n    default:\n        return statuses;\n    }\n}\n\nfunction errorsReducer(\n    errors: CartErrorsState = DEFAULT_STATE.errors,\n    action: CheckoutAction\n): CartErrorsState {\n    switch (action.type) {\n    case CheckoutActionType.LoadCheckoutRequested:\n    case CheckoutActionType.LoadCheckoutSucceeded:\n        return objectSet(errors, 'loadError', undefined);\n\n    case CheckoutActionType.LoadCheckoutFailed:\n        return objectSet(errors, 'loadError', action.payload);\n\n    default:\n        return errors;\n    }\n}\n","import { CheckoutButtonMethodType } from './strategies';\n\nexport default interface CheckoutButtonState {\n    data: {\n        [key in CheckoutButtonMethodType]?: CheckoutButtonDataState | undefined\n    };\n    errors: {\n        [key in CheckoutButtonMethodType]?: CheckoutButtonErrorsState | undefined\n    };\n    statuses: {\n        [key in CheckoutButtonMethodType]?: CheckoutButtonStatusesState | undefined\n    };\n}\n\nexport interface CheckoutButtonDataState {\n    initializedContainers: {\n        [key: string]: boolean;\n    };\n}\n\nexport interface CheckoutButtonErrorsState {\n    initializeError?: Error;\n    deinitializeError?: Error;\n}\n\nexport interface CheckoutButtonStatusesState {\n    isInitializing?: boolean;\n    isDeinitializing?: boolean;\n}\n\nexport const DEFAULT_STATE: CheckoutButtonState = {\n    data: {},\n    errors: {},\n    statuses: {},\n};\n","import { combineReducers } from '@bigcommerce/data-store';\n\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { CheckoutButtonAction, CheckoutButtonActionType } from './checkout-button-actions';\nimport CheckoutButtonState, { CheckoutButtonDataState, CheckoutButtonErrorsState, CheckoutButtonStatusesState, DEFAULT_STATE } from './checkout-button-state';\n\nconst DEFAULT_DATA_STATE: CheckoutButtonDataState = { initializedContainers: {} };\nconst DEFAULT_ERROR_STATE: CheckoutButtonErrorsState = {};\nconst DEFAULT_STATUS_STATE: CheckoutButtonStatusesState = {};\n\nexport default function checkoutButtonReducer(\n    state: CheckoutButtonState = DEFAULT_STATE,\n    action: CheckoutButtonAction\n): CheckoutButtonState {\n    if (!action.meta || !action.meta.methodId) {\n        return state;\n    }\n\n    const reducer = combineReducers<CheckoutButtonState>({\n        data: combineReducers({\n            [action.meta.methodId]: dataReducer,\n        }),\n        errors: combineReducers({\n            [action.meta.methodId]: errorsReducer,\n        }),\n        statuses: combineReducers({\n            [action.meta.methodId]: statusesReducer,\n        }),\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: CheckoutButtonDataState = DEFAULT_DATA_STATE,\n    action: CheckoutButtonAction\n): CheckoutButtonDataState {\n    switch (action.type) {\n    case CheckoutButtonActionType.InitializeButtonSucceeded:\n        if (!action.meta || !action.meta.containerId) {\n            return data;\n        }\n\n        return objectMerge(data, {\n            initializedContainers: {\n                [action.meta.containerId]: true,\n            },\n        });\n\n    case CheckoutButtonActionType.DeinitializeButtonSucceeded:\n        return objectSet(data, 'initializedContainers', {});\n    }\n\n    return data;\n}\n\nfunction errorsReducer(\n    errors: CheckoutButtonErrorsState = DEFAULT_ERROR_STATE,\n    action: CheckoutButtonAction\n): CheckoutButtonErrorsState {\n    switch (action.type) {\n    case CheckoutButtonActionType.InitializeButtonRequested:\n    case CheckoutButtonActionType.InitializeButtonSucceeded:\n        return objectSet(errors, 'initializeError', undefined);\n\n    case CheckoutButtonActionType.InitializeButtonFailed:\n        return objectSet(errors, 'initializeError', action.payload);\n\n    case CheckoutButtonActionType.DeinitializeButtonRequested:\n    case CheckoutButtonActionType.DeinitializeButtonSucceeded:\n        return objectSet(errors, 'deinitializeError', undefined);\n\n    case CheckoutButtonActionType.DeinitializeButtonFailed:\n        return objectSet(errors, 'deinitializeError', action.payload);\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: CheckoutButtonStatusesState = DEFAULT_STATUS_STATE,\n    action: CheckoutButtonAction\n): CheckoutButtonStatusesState {\n    switch (action.type) {\n    case CheckoutButtonActionType.InitializeButtonRequested:\n        return objectSet(statuses, 'isInitializing', true);\n\n    case CheckoutButtonActionType.InitializeButtonFailed:\n    case CheckoutButtonActionType.InitializeButtonSucceeded:\n        return objectSet(statuses, 'isInitializing', false);\n\n    case CheckoutButtonActionType.DeinitializeButtonRequested:\n        return objectSet(statuses, 'isDeinitializing', true);\n\n    case CheckoutButtonActionType.DeinitializeButtonFailed:\n    case CheckoutButtonActionType.DeinitializeButtonSucceeded:\n        return objectSet(statuses, 'isDeinitializing', false);\n\n    default:\n        return statuses;\n    }\n}\n","import Config from './config';\n\nexport default interface ConfigState {\n    data?: Config;\n    meta?: ConfigMetaState;\n    errors: ConfigErrorsState;\n    statuses: ConfigStatusesState;\n}\n\nexport interface ConfigMetaState {\n    externalSource?: string;\n    variantIdentificationToken?: string;\n}\n\nexport interface ConfigErrorsState {\n    loadError?: Error;\n}\n\nexport interface ConfigStatusesState {\n    isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: ConfigState = {\n    meta: {},\n    errors: {},\n    statuses: {},\n};\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport Config from './config';\nimport { ConfigActionType, LoadConfigAction } from './config-actions';\nimport ConfigState, { ConfigErrorsState, ConfigStatusesState, DEFAULT_STATE } from './config-state';\n\nexport default function configReducer(\n    state: ConfigState = DEFAULT_STATE,\n    action: Action\n): ConfigState {\n    const reducer = combineReducers<ConfigState>({\n        data: dataReducer,\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: Config | undefined,\n    action: LoadConfigAction\n): Config | undefined {\n    switch (action.type) {\n    case ConfigActionType.LoadConfigSucceeded:\n        return objectMerge(data, action.payload);\n\n    default:\n        return data;\n    }\n}\n\nfunction errorsReducer(\n    errors: ConfigErrorsState = DEFAULT_STATE.errors,\n    action: LoadConfigAction\n): ConfigErrorsState {\n    switch (action.type) {\n    case ConfigActionType.LoadConfigSucceeded:\n        return objectSet(errors, 'loadError', undefined);\n\n    case ConfigActionType.LoadConfigFailed:\n        return objectSet(errors, 'loadError', action.payload);\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: ConfigStatusesState = DEFAULT_STATE.statuses,\n    action: LoadConfigAction\n): ConfigStatusesState {\n    switch (action.type) {\n    case ConfigActionType.LoadConfigRequested:\n        return objectSet(statuses, 'isLoading', true);\n\n    case ConfigActionType.LoadConfigSucceeded:\n    case ConfigActionType.LoadConfigFailed:\n        return objectSet(statuses, 'isLoading', false);\n\n    default:\n        return statuses;\n    }\n}\n","import { StorefrontErrorResponseBody } from '../common/error';\nimport { RequestError } from '../common/error/errors';\n\nimport Coupon from './coupon';\n\nexport default interface CouponState {\n    data?: Coupon[];\n    errors: CouponErrorsState;\n    statuses: CouponStatusesState;\n}\n\nexport interface CouponErrorsState {\n    applyCouponError?: RequestError<StorefrontErrorResponseBody>;\n    removeCouponError?: RequestError<StorefrontErrorResponseBody>;\n}\n\nexport interface CouponStatusesState {\n    isApplyingCoupon?: boolean;\n    isRemovingCoupon?: boolean;\n}\n\nexport const DEFAULT_STATE: CouponState = {\n    errors: {},\n    statuses: {},\n};\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\nimport { OrderAction, OrderActionType } from '../order';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\n\nimport Coupon from './coupon';\nimport { CouponAction, CouponActionType } from './coupon-actions';\nimport CouponState, { CouponErrorsState, CouponStatusesState, DEFAULT_STATE } from './coupon-state';\n\nexport default function couponReducer(\n    state: CouponState = DEFAULT_STATE,\n    action: Action\n): CouponState {\n    const reducer = combineReducers<CouponState>({\n        data: dataReducer,\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: Coupon[] | undefined,\n    action: CouponAction | CheckoutAction | OrderAction | ConsignmentAction\n): Coupon[] | undefined {\n    switch (action.type) {\n    case CheckoutActionType.LoadCheckoutSucceeded:\n    case CouponActionType.ApplyCouponSucceeded:\n    case ConsignmentActionType.UpdateShippingOptionSucceeded:\n    case CouponActionType.RemoveCouponSucceeded:\n    case OrderActionType.LoadOrderSucceeded:\n        return arrayReplace(data, action.payload && action.payload.coupons);\n\n    default:\n        return data;\n    }\n}\n\nfunction errorsReducer(\n    errors: CouponErrorsState = {},\n    action: CouponAction\n): CouponErrorsState {\n    switch (action.type) {\n    case CouponActionType.ApplyCouponRequested:\n    case CouponActionType.ApplyCouponSucceeded:\n        return objectSet(errors, 'applyCouponError', undefined);\n\n    case CouponActionType.ApplyCouponFailed:\n        return objectSet(errors, 'applyCouponError', action.payload);\n\n    case CouponActionType.RemoveCouponRequested:\n    case CouponActionType.RemoveCouponSucceeded:\n        return objectSet(errors, 'removeCouponError', undefined);\n\n    case CouponActionType.RemoveCouponFailed:\n        return objectSet(errors, 'removeCouponError', action.payload);\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: CouponStatusesState = {},\n    action: CouponAction\n): CouponStatusesState {\n    switch (action.type) {\n    case CouponActionType.ApplyCouponRequested:\n        return objectSet(statuses, 'isApplyingCoupon', true);\n\n    case CouponActionType.ApplyCouponSucceeded:\n    case CouponActionType.ApplyCouponFailed:\n        return objectSet(statuses, 'isApplyingCoupon', false);\n\n    case CouponActionType.RemoveCouponRequested:\n        return objectSet(statuses, 'isRemovingCoupon', true);\n\n    case CouponActionType.RemoveCouponSucceeded:\n    case CouponActionType.RemoveCouponFailed:\n        return objectSet(statuses, 'isRemovingCoupon', false);\n\n    default:\n        return statuses;\n    }\n}\n","import { StorefrontErrorResponseBody } from '../common/error';\nimport { RequestError } from '../common/error/errors';\n\nimport GiftCertificate from './gift-certificate';\n\nexport default interface GiftCertificateState {\n    data?: GiftCertificate[];\n    errors: GiftCertificateErrorsState;\n    statuses: GiftCertificateStatusesState;\n}\n\nexport interface GiftCertificateErrorsState {\n    applyGiftCertificateError?: RequestError<StorefrontErrorResponseBody>;\n    removeGiftCertificateError?: RequestError<StorefrontErrorResponseBody>;\n}\n\nexport interface GiftCertificateStatusesState {\n    isApplyingGiftCertificate?: boolean;\n    isRemovingGiftCertificate?: boolean;\n}\n\nexport const DEFAULT_STATE: GiftCertificateState = {\n    errors: {},\n    statuses: {},\n};\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\n\nimport { CouponAction, CouponActionType } from './coupon-actions';\nimport GiftCertificate from './gift-certificate';\nimport { GiftCertificateAction, GiftCertificateActionType } from './gift-certificate-actions';\nimport GiftCertificateState, { DEFAULT_STATE, GiftCertificateErrorsState, GiftCertificateStatusesState } from './gift-certificate-state';\n\nexport default function giftCertificateReducer(\n    state: GiftCertificateState = DEFAULT_STATE,\n    action: Action\n): GiftCertificateState {\n    const reducer = combineReducers<GiftCertificateState>({\n        data: dataReducer,\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: GiftCertificate[] | undefined,\n    action: CheckoutAction | GiftCertificateAction | ConsignmentAction | CouponAction\n): GiftCertificate[] | undefined {\n    switch (action.type) {\n    case CheckoutActionType.LoadCheckoutSucceeded:\n    case ConsignmentActionType.CreateConsignmentsSucceeded:\n    case ConsignmentActionType.UpdateConsignmentSucceeded:\n    case ConsignmentActionType.DeleteConsignmentSucceeded:\n    case ConsignmentActionType.UpdateShippingOptionSucceeded:\n    case CouponActionType.ApplyCouponSucceeded:\n    case CouponActionType.RemoveCouponSucceeded:\n    case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n    case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n        return arrayReplace(data, action.payload && action.payload.giftCertificates);\n\n    default:\n        return data;\n    }\n}\n\nfunction errorsReducer(\n    errors: GiftCertificateErrorsState = DEFAULT_STATE.errors,\n    action: GiftCertificateAction\n): GiftCertificateErrorsState {\n    switch (action.type) {\n    case GiftCertificateActionType.ApplyGiftCertificateRequested:\n    case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n        return objectSet(errors, 'applyGiftCertificateError', undefined);\n\n    case GiftCertificateActionType.ApplyGiftCertificateFailed:\n        return objectSet(errors, 'applyGiftCertificateError', action.payload);\n\n    case GiftCertificateActionType.RemoveGiftCertificateRequested:\n    case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n        return objectSet(errors, 'removeGiftCertificateError', undefined);\n\n    case GiftCertificateActionType.RemoveGiftCertificateFailed:\n        return objectSet(errors, 'removeGiftCertificateError', action.payload);\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: GiftCertificateStatusesState = DEFAULT_STATE.statuses,\n    action: GiftCertificateAction\n): GiftCertificateStatusesState {\n    switch (action.type) {\n    case GiftCertificateActionType.ApplyGiftCertificateRequested:\n        return objectSet(statuses, 'isApplyingGiftCertificate', true);\n\n    case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n    case GiftCertificateActionType.ApplyGiftCertificateFailed:\n        return objectSet(statuses, 'isApplyingGiftCertificate', false);\n\n    case GiftCertificateActionType.RemoveGiftCertificateRequested:\n        return objectSet(statuses, 'isRemovingGiftCertificate', true);\n\n    case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n    case GiftCertificateActionType.RemoveGiftCertificateFailed:\n        return objectSet(statuses, 'isRemovingGiftCertificate', false);\n\n    default:\n        return statuses;\n    }\n}\n","import Customer from './customer';\n\nexport default interface CustomerState {\n    data?: Customer;\n    statuses: CustomerStatusesState;\n    errors: CustomerErrorsState;\n}\n\nexport interface CustomerErrorsState {\n    createError?: Error;\n    createAddressError?: Error;\n}\n\nexport interface CustomerStatusesState {\n    isCreating?: boolean;\n    isCreatingAddress?: boolean;\n}\n\nexport const DEFAULT_STATE: CustomerState = {\n    errors: {},\n    statuses: {},\n};\n","import { combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { BillingAddressActionType, ContinueAsGuestAction } from '../billing';\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport Customer from './customer';\nimport { CustomerAction, CustomerActionType } from './customer-actions';\nimport CustomerState, { CustomerErrorsState, CustomerStatusesState, DEFAULT_STATE } from './customer-state';\n\nexport default function customerReducer(\n    state: CustomerState = DEFAULT_STATE,\n    action: CheckoutAction | ContinueAsGuestAction | CustomerAction\n): CustomerState {\n    const reducer = combineReducers<CustomerState, CheckoutAction | CustomerAction | ContinueAsGuestAction>({\n        data: dataReducer,\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: Customer | undefined,\n    action: CheckoutAction | ContinueAsGuestAction | CustomerAction\n): Customer | undefined {\n    switch (action.type) {\n    case BillingAddressActionType.ContinueAsGuestSucceeded:\n    case CheckoutActionType.LoadCheckoutSucceeded:\n        return objectMerge(data, action.payload && action.payload.customer);\n\n    case CustomerActionType.CreateCustomerAddressSucceeded:\n            return objectMerge(data, action.payload);\n\n    default:\n        return data;\n    }\n}\n\nfunction errorsReducer(\n    errors: CustomerErrorsState = DEFAULT_STATE.errors,\n    action: CheckoutAction | ContinueAsGuestAction | CustomerAction\n): CustomerErrorsState {\n    switch (action.type) {\n    case CustomerActionType.CreateCustomerRequested:\n    case CustomerActionType.CreateCustomerSucceeded:\n        return objectSet(errors, 'createError', undefined);\n\n    case CustomerActionType.CreateCustomerFailed:\n        return objectSet(errors, 'createError', action.payload);\n\n    case CustomerActionType.CreateCustomerAddressRequested:\n    case CustomerActionType.CreateCustomerAddressSucceeded:\n        return objectSet(errors, 'createAddressError', undefined);\n\n    case CustomerActionType.CreateCustomerAddressFailed:\n        return objectSet(errors, 'createAddressError', action.payload);\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: CustomerStatusesState = DEFAULT_STATE.statuses,\n    action: CheckoutAction | ContinueAsGuestAction | CustomerAction\n): CustomerStatusesState {\n    switch (action.type) {\n    case CustomerActionType.CreateCustomerRequested:\n        return objectSet(statuses, 'isCreating', true);\n\n    case CustomerActionType.CreateCustomerFailed:\n    case CustomerActionType.CreateCustomerSucceeded:\n        return objectSet(statuses, 'isCreating', false);\n\n    case CustomerActionType.CreateCustomerAddressRequested:\n        return objectSet(statuses, 'isCreatingAddress', true);\n\n    case CustomerActionType.CreateCustomerAddressFailed:\n    case CustomerActionType.CreateCustomerAddressSucceeded:\n        return objectSet(statuses, 'isCreatingAddress', false);\n    default:\n        return statuses;\n    }\n}\n","export default interface CustomerStrategyState {\n    data: CustomerStrategyDataState;\n    errors: CustomerStrategyErrorsState;\n    statuses: CustomerStrategyStatusesState;\n}\n\nexport interface CustomerStrategyDataState {\n    [key: string]: {\n        isInitialized: boolean;\n    };\n}\n\nexport interface CustomerStrategyErrorsState {\n    deinitializeError?: Error;\n    deinitializeMethodId?: string;\n    initializeError?: Error;\n    initializeMethodId?: string;\n    signInError?: Error;\n    signInMethodId?: string;\n    signOutError?: Error;\n    signOutMethodId?: string;\n    widgetInteractionError?: Error;\n    widgetInteractionMethodId?: string;\n}\n\nexport interface CustomerStrategyStatusesState {\n    deinitializeMethodId?: string;\n    initializeMethodId?: string;\n    isDeinitializing?: boolean;\n    isInitializing?: boolean;\n    isSigningIn?: boolean;\n    isSigningOut?: boolean;\n    signInMethodId?: string;\n    signOutMethodId?: string;\n    isWidgetInteracting?: boolean;\n    widgetInteractionMethodId?: string;\n}\n\nexport const DEFAULT_STATE: CustomerStrategyState = {\n    data: {},\n    errors: {},\n    statuses: {},\n};\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge } from '../common/utility';\n\nimport { CustomerStrategyAction, CustomerStrategyActionType } from './customer-strategy-actions';\nimport CustomerStrategyState, { CustomerStrategyDataState, CustomerStrategyErrorsState, CustomerStrategyStatusesState, DEFAULT_STATE } from './customer-strategy-state';\n\nexport default function customerStrategyReducer(\n    state: CustomerStrategyState = DEFAULT_STATE,\n    action: Action\n): CustomerStrategyState {\n    const reducer = combineReducers<CustomerStrategyState, CustomerStrategyAction>({\n        data: dataReducer,\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: CustomerStrategyDataState = DEFAULT_STATE.data,\n    action: CustomerStrategyAction\n): CustomerStrategyDataState {\n    switch (action.type) {\n    case CustomerStrategyActionType.InitializeSucceeded:\n        return objectMerge(data, {\n            [action.meta && action.meta.methodId]: {\n                isInitialized: true,\n            },\n        });\n\n    case CustomerStrategyActionType.DeinitializeSucceeded:\n        return objectMerge(data, {\n            [action.meta && action.meta.methodId]: {\n                isInitialized: false,\n            },\n        });\n    }\n\n    return data;\n}\n\nfunction errorsReducer(\n    errors: CustomerStrategyErrorsState = DEFAULT_STATE.errors,\n    action: CustomerStrategyAction\n): CustomerStrategyErrorsState {\n    switch (action.type) {\n    case CustomerStrategyActionType.InitializeRequested:\n    case CustomerStrategyActionType.InitializeSucceeded:\n        return objectMerge(errors, {\n            initializeError: undefined,\n            initializeMethodId: undefined,\n        });\n\n    case CustomerStrategyActionType.InitializeFailed:\n        return objectMerge(errors, {\n            initializeError: action.payload,\n            initializeMethodId: action.meta && action.meta.methodId,\n        });\n\n    case CustomerStrategyActionType.DeinitializeRequested:\n    case CustomerStrategyActionType.DeinitializeSucceeded:\n        return objectMerge(errors, {\n            deinitializeError: undefined,\n            deinitializeMethodId: undefined,\n        });\n\n    case CustomerStrategyActionType.DeinitializeFailed:\n        return objectMerge(errors, {\n            deinitializeError: action.payload,\n            deinitializeMethodId: action.meta && action.meta.methodId,\n        });\n\n    case CustomerStrategyActionType.SignInRequested:\n    case CustomerStrategyActionType.SignInSucceeded:\n        return objectMerge(errors, {\n            signInError: undefined,\n            signInMethodId: undefined,\n        });\n\n    case CustomerStrategyActionType.SignInFailed:\n        return objectMerge(errors, {\n            signInError: action.payload,\n            signInMethodId: action.meta && action.meta.methodId,\n        });\n\n    case CustomerStrategyActionType.SignOutRequested:\n    case CustomerStrategyActionType.SignOutSucceeded:\n        return objectMerge(errors, {\n            signOutError: undefined,\n            signOutMethodId: undefined,\n        });\n\n    case CustomerStrategyActionType.SignOutFailed:\n        return objectMerge(errors, {\n            signOutError: action.payload,\n            signOutMethodId: action.meta && action.meta.methodId,\n        });\n\n    case CustomerStrategyActionType.WidgetInteractionStarted:\n    case CustomerStrategyActionType.WidgetInteractionFinished:\n        return objectMerge(errors, {\n            widgetInteractionError: undefined,\n            widgetInteractionMethodId: undefined,\n        });\n\n    case CustomerStrategyActionType.WidgetInteractionFailed:\n        return objectMerge(errors, {\n            widgetInteractionError: action.payload,\n            widgetInteractionMethodId: action.meta.methodId,\n        });\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: CustomerStrategyStatusesState = DEFAULT_STATE.statuses,\n    action: CustomerStrategyAction\n): CustomerStrategyStatusesState {\n    switch (action.type) {\n    case CustomerStrategyActionType.InitializeRequested:\n        return objectMerge(statuses, {\n            isInitializing: true,\n            initializeMethodId: action.meta && action.meta.methodId,\n        });\n\n    case CustomerStrategyActionType.InitializeFailed:\n    case CustomerStrategyActionType.InitializeSucceeded:\n        return objectMerge(statuses, {\n            isInitializing: false,\n            initializeMethodId: undefined,\n        });\n\n    case CustomerStrategyActionType.DeinitializeRequested:\n        return objectMerge(statuses, {\n            isDeinitializing: true,\n            deinitializeMethodId: action.meta && action.meta.methodId,\n        });\n\n    case CustomerStrategyActionType.DeinitializeFailed:\n    case CustomerStrategyActionType.DeinitializeSucceeded:\n        return objectMerge(statuses, {\n            isDeinitializing: false,\n            deinitializeMethodId: undefined,\n        });\n\n    case CustomerStrategyActionType.SignInRequested:\n        return objectMerge(statuses, {\n            isSigningIn: true,\n            signInMethodId: action.meta && action.meta.methodId,\n        });\n\n    case CustomerStrategyActionType.SignInFailed:\n    case CustomerStrategyActionType.SignInSucceeded:\n        return objectMerge(statuses, {\n            isSigningIn: false,\n            signInMethodId: undefined,\n        });\n\n    case CustomerStrategyActionType.SignOutRequested:\n        return objectMerge(statuses, {\n            isSigningOut: true,\n            signOutMethodId: action.meta && action.meta.methodId,\n        });\n\n    case CustomerStrategyActionType.SignOutFailed:\n    case CustomerStrategyActionType.SignOutSucceeded:\n        return objectMerge(statuses, {\n            isSigningOut: false,\n            signOutMethodId: undefined,\n        });\n\n    case CustomerStrategyActionType.WidgetInteractionStarted:\n        return objectMerge(statuses, {\n            isWidgetInteracting: true,\n            widgetInteractionMethodId: action.meta.methodId,\n         });\n\n    case CustomerStrategyActionType.WidgetInteractionFinished:\n    case CustomerStrategyActionType.WidgetInteractionFailed:\n        return objectMerge(statuses, {\n            isWidgetInteracting: false,\n            widgetInteractionMethodId: undefined,\n         });\n\n    default:\n        return statuses;\n    }\n}\n","import { FormFields } from './form-field';\n\nexport default interface FormFieldsState {\n    data?: FormFields;\n    errors: FormFieldsErrorState;\n    statuses: FormFieldsStatusesState;\n}\n\nexport interface FormFieldsErrorState {\n    loadError?: Error;\n}\n\nexport interface FormFieldsStatusesState {\n    isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: FormFieldsState = {\n    errors: {},\n    statuses: {},\n};\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { FormFields } from './form-field';\nimport { FormFieldsActionType, LoadFormFieldsAction } from './form-fields-actions';\nimport FormFieldsState, { DEFAULT_STATE, FormFieldsErrorState, FormFieldsStatusesState } from './form-fields-state';\n\nexport default function formFieldsReducer(\n    state: FormFieldsState = DEFAULT_STATE,\n    action: Action\n): FormFieldsState {\n    const reducer = combineReducers<FormFieldsState>({\n        data: dataReducer,\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: FormFields | undefined,\n    action: LoadFormFieldsAction\n): FormFields | undefined {\n    switch (action.type) {\n    case FormFieldsActionType.LoadFormFieldsSucceeded:\n        return objectMerge(data, action.payload);\n\n    default:\n        return data;\n    }\n}\n\nfunction errorsReducer(\n    errors: FormFieldsErrorState = DEFAULT_STATE.errors,\n    action: LoadFormFieldsAction\n): FormFieldsErrorState {\n    switch (action.type) {\n    case FormFieldsActionType.LoadFormFieldsSucceeded:\n        return objectSet(errors, 'loadError', undefined);\n\n    case FormFieldsActionType.LoadFormFieldsFailed:\n        return objectSet(errors, 'loadError', action.payload);\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: FormFieldsStatusesState = DEFAULT_STATE.statuses,\n    action: LoadFormFieldsAction\n): FormFieldsStatusesState {\n    switch (action.type) {\n    case FormFieldsActionType.LoadFormFieldsRequested:\n        return objectSet(statuses, 'isLoading', true);\n\n    case FormFieldsActionType.LoadFormFieldsSucceeded:\n    case FormFieldsActionType.LoadFormFieldsFailed:\n        return objectSet(statuses, 'isLoading', false);\n\n    default:\n        return statuses;\n    }\n}\n","import Country from './country';\n\nexport default interface CountryState {\n    data?: Country[];\n    errors: CountryErrorsState;\n    statuses: CountryStatusesState;\n}\n\nexport interface CountryErrorsState {\n    loadError?: Error;\n}\n\nexport interface CountryStatusesState {\n    isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: CountryState = {\n    errors: {},\n    statuses: {},\n};\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\n\nimport Country from './country';\nimport { CountryActionType, LoadCountriesAction } from './country-actions';\nimport CountryState, { CountryErrorsState, CountryStatusesState, DEFAULT_STATE } from './country-state';\n\nexport default function countryReducer(\n    state: CountryState = DEFAULT_STATE,\n    action: Action\n): CountryState {\n    const reducer = combineReducers<CountryState>({\n        data: dataReducer,\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: Country[] | undefined,\n    action: LoadCountriesAction\n): Country[] | undefined {\n    switch (action.type) {\n    case CountryActionType.LoadCountriesSucceeded:\n        return arrayReplace(data, action.payload);\n\n    default:\n        return data;\n    }\n}\n\nfunction errorsReducer(\n    errors: CountryErrorsState = DEFAULT_STATE.errors,\n    action: LoadCountriesAction\n): CountryErrorsState {\n    switch (action.type) {\n    case CountryActionType.LoadCountriesRequested:\n    case CountryActionType.LoadCountriesSucceeded:\n        return objectSet(errors, 'loadError', undefined);\n\n    case CountryActionType.LoadCountriesFailed:\n        return objectSet(errors, 'loadError', action.payload);\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: CountryStatusesState = DEFAULT_STATE.statuses,\n    action: LoadCountriesAction\n): CountryStatusesState {\n    switch (action.type) {\n    case CountryActionType.LoadCountriesRequested:\n        return objectSet(statuses, 'isLoading', true);\n\n    case CountryActionType.LoadCountriesSucceeded:\n    case CountryActionType.LoadCountriesFailed:\n        return objectSet(statuses, 'isLoading', false);\n\n    default:\n        return statuses;\n    }\n}\n","import { Omit } from '../common/types';\n\nimport { InternalOrderMeta, InternalOrderPayment } from './internal-order';\nimport Order from './order';\n\nexport default interface OrderState {\n    data?: OrderDataState;\n    meta?: OrderMetaState;\n    errors: OrderErrorsState;\n    statuses: OrderStatusesState;\n}\n\nexport type OrderDataState = Omit<Order, 'billingAddress' | 'coupons'>;\n\nexport interface OrderMetaState extends InternalOrderMeta {\n    token?: string;\n    orderToken?: string;\n    callbackUrl?: string;\n    payment?: InternalOrderPayment;\n}\n\nexport interface OrderErrorsState {\n    loadError?: Error;\n    submitError?: Error;\n    finalizeError?: Error;\n}\n\nexport interface OrderStatusesState {\n    isLoading?: boolean;\n    isSubmitting?: boolean;\n    isFinalizing?: boolean;\n}\n\nexport const DEFAULT_STATE: OrderState = {\n    errors: {},\n    meta: {},\n    statuses: {},\n};\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\nimport { omit } from 'lodash';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { OrderAction, OrderActionType } from './order-actions';\nimport OrderState, { DEFAULT_STATE, OrderDataState, OrderErrorsState, OrderMetaState, OrderStatusesState } from './order-state';\n\nexport default function orderReducer(\n    state: OrderState = DEFAULT_STATE,\n    action: Action\n): OrderState {\n    const reducer = combineReducers<OrderState>({\n        data: dataReducer,\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        meta: metaReducer,\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: OrderDataState | undefined,\n    action: OrderAction\n): OrderDataState | undefined {\n    switch (action.type) {\n    case OrderActionType.LoadOrderSucceeded:\n    case OrderActionType.LoadOrderPaymentsSucceeded:\n        return objectMerge(data, omit(action.payload, ['billingAddress', 'coupons'])) as OrderDataState;\n\n    default:\n        return data;\n    }\n}\n\nfunction metaReducer(\n    meta: OrderMetaState | undefined,\n    action: OrderAction\n): OrderMetaState | undefined {\n    switch (action.type) {\n    case OrderActionType.FinalizeOrderSucceeded:\n    case OrderActionType.SubmitOrderSucceeded:\n        return objectMerge(meta, {\n            ...action.meta,\n            callbackUrl: action.payload && action.payload.order.callbackUrl,\n            orderToken: action.payload && action.payload.order.token,\n            payment: action.payload && action.payload.order && action.payload.order.payment,\n        });\n\n    default:\n        return meta;\n    }\n}\n\nfunction errorsReducer(\n    errors: OrderErrorsState = DEFAULT_STATE.errors,\n    action: OrderAction\n): OrderErrorsState {\n    switch (action.type) {\n    case OrderActionType.LoadOrderRequested:\n    case OrderActionType.LoadOrderSucceeded:\n    case OrderActionType.LoadOrderPaymentsSucceeded:\n    case OrderActionType.LoadOrderPaymentsRequested:\n        return objectSet(errors, 'loadError', undefined);\n\n    case OrderActionType.LoadOrderFailed:\n    case OrderActionType.LoadOrderPaymentsFailed:\n        return objectSet(errors, 'loadError', action.payload);\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: OrderStatusesState = DEFAULT_STATE.statuses,\n    action: OrderAction\n): OrderStatusesState {\n    switch (action.type) {\n    case OrderActionType.LoadOrderRequested:\n    case OrderActionType.LoadOrderPaymentsRequested:\n        return objectSet(statuses, 'isLoading', true);\n\n    case OrderActionType.LoadOrderSucceeded:\n    case OrderActionType.LoadOrderFailed:\n    case OrderActionType.LoadOrderPaymentsSucceeded:\n    case OrderActionType.LoadOrderPaymentsFailed:\n        return objectSet(statuses, 'isLoading', false);\n\n    default:\n        return statuses;\n    }\n}\n","import { combineReducers } from '@bigcommerce/data-store';\n\nimport { PaymentAction, PaymentActionType } from './payment-actions';\nimport PaymentResponseBody from './payment-response-body';\nimport PaymentState from './payment-state';\n\nexport default function paymentReducer(state: PaymentState = {}, action: PaymentAction): PaymentState {\n    const reducer = combineReducers<PaymentState, PaymentAction>({\n        data: dataReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(data: PaymentResponseBody | undefined, action: PaymentAction): PaymentResponseBody | undefined {\n    switch (action.type) {\n    case PaymentActionType.SubmitPaymentSucceeded:\n        return action.payload;\n\n    default:\n        return data;\n    }\n}\n","import PaymentMethod from './payment-method';\nimport PaymentMethodMeta from './payment-method-meta';\n\nexport default interface PaymentMethodState {\n    data?: PaymentMethod[];\n    meta?: PaymentMethodMeta;\n    errors: PaymentMethodErrorsState;\n    statuses: PaymentMethodStatusesState;\n}\n\nexport interface PaymentMethodErrorsState {\n    loadMethodId?: string;\n    loadError?: Error;\n    loadMethodError?: Error;\n}\n\nexport interface PaymentMethodStatusesState {\n    loadMethodId?: string;\n    isLoading?: boolean;\n    isLoadingMethod?: boolean;\n}\n\nexport const DEFAULT_STATE: PaymentMethodState = {\n    errors: {},\n    statuses: {},\n};\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, mergeOrPush, objectMerge, objectSet } from '../common/utility';\n\nimport PaymentMethod from './payment-method';\nimport { PaymentMethodAction, PaymentMethodActionType } from './payment-method-actions';\nimport PaymentMethodMeta from './payment-method-meta';\nimport PaymentMethodState, { DEFAULT_STATE, PaymentMethodErrorsState, PaymentMethodStatusesState } from './payment-method-state';\n\nexport default function paymentMethodReducer(\n    state: PaymentMethodState = DEFAULT_STATE,\n    action: Action\n): PaymentMethodState {\n    const reducer = combineReducers<PaymentMethodState>({\n        data: dataReducer,\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        meta: metaReducer,\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: PaymentMethod[] | undefined,\n    action: PaymentMethodAction\n): PaymentMethod[] | undefined {\n    switch (action.type) {\n    case PaymentMethodActionType.LoadPaymentMethodSucceeded:\n        return mergeOrPush(data || [], action.payload, action.payload && {\n            id: action.payload.id,\n            gateway: action.payload.gateway,\n        });\n\n    case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n        return arrayReplace(data, action.payload, {\n            matchObject: (methodA, methodB) => (\n                methodA.id === methodB.id && methodA.gateway === methodB.gateway\n            ),\n        });\n\n    default:\n        return data;\n    }\n}\n\nfunction metaReducer(\n    meta: PaymentMethodMeta | undefined,\n    action: PaymentMethodAction\n): PaymentMethodMeta | undefined {\n    switch (action.type) {\n    case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n        return objectMerge(meta, action.meta);\n\n    default:\n        return meta;\n    }\n}\n\nfunction errorsReducer(\n    errors: PaymentMethodErrorsState = DEFAULT_STATE.errors,\n    action: PaymentMethodAction\n): PaymentMethodErrorsState {\n    switch (action.type) {\n    case PaymentMethodActionType.LoadPaymentMethodsRequested:\n    case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n        return objectSet(errors, 'loadError', undefined);\n\n    case PaymentMethodActionType.LoadPaymentMethodsFailed:\n        return objectSet(errors, 'loadError', action.payload);\n\n    case PaymentMethodActionType.LoadPaymentMethodRequested:\n    case PaymentMethodActionType.LoadPaymentMethodSucceeded:\n        return objectMerge(errors, {\n            loadMethodId: undefined,\n            loadMethodError: undefined,\n        });\n\n    case PaymentMethodActionType.LoadPaymentMethodFailed:\n        return objectMerge(errors, {\n            loadMethodId: action.meta.methodId,\n            loadMethodError: action.payload,\n        });\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: PaymentMethodStatusesState = DEFAULT_STATE.statuses,\n    action: PaymentMethodAction\n): PaymentMethodStatusesState {\n    switch (action.type) {\n    case PaymentMethodActionType.LoadPaymentMethodsRequested:\n        return objectSet(statuses, 'isLoading', true);\n\n    case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n    case PaymentMethodActionType.LoadPaymentMethodsFailed:\n        return objectSet(statuses, 'isLoading', false);\n\n    case PaymentMethodActionType.LoadPaymentMethodRequested:\n        return objectMerge(statuses, {\n            isLoadingMethod: true,\n            loadMethodId: action.meta.methodId,\n        });\n\n    case PaymentMethodActionType.LoadPaymentMethodSucceeded:\n    case PaymentMethodActionType.LoadPaymentMethodFailed:\n        return objectMerge(statuses, {\n            isLoadingMethod: false,\n            loadMethodId: undefined,\n        });\n\n    default:\n        return statuses;\n    }\n}\n","import { findIndex, pick, pickBy, ValueKeyIteratee } from 'lodash';\n\nimport isPlainObject from './is-plain-object';\nimport objectMerge from './object-merge';\n\n/**\n * Push an item to an array if it doesn't exist in the array. Otherwise, merge\n * with the existing item in the array. This function always returns a new array.\n */\nexport default function mergeOrPush<T>(\n    array: T[],\n    item?: T,\n    predicate?: ValueKeyIteratee<T>\n): T[] {\n    if (!item) {\n        return array;\n    }\n\n    const defaultPredicate = pick(item, 'id');\n    const index = findIndex(array, typeof predicate === 'object' ? pickBy(predicate) : (predicate || defaultPredicate));\n    const newArray = [...array];\n\n    if (index === -1) {\n        newArray.push(item);\n    } else {\n        const existingItem = array[index];\n\n        newArray[index] = isPlainObject(existingItem) && isPlainObject(item) ?\n            objectMerge(existingItem, item) :\n            item;\n    }\n\n    return newArray;\n}\n","export default interface PaymentStrategyState {\n    data: PaymentStrategyDataState;\n    errors: PaymentStrategyErrorsState;\n    statuses: PaymentStrategyStatusesState;\n}\n\nexport interface PaymentStrategyDataState {\n    [key: string]: {\n        isInitialized: boolean;\n    };\n}\n\nexport interface PaymentStrategyErrorsState {\n    deinitializeError?: Error;\n    deinitializeMethodId?: string;\n    executeError?: Error;\n    executeMethodId?: string;\n    finalizeError?: Error;\n    finalizeMethodId?: string;\n    initializeError?: Error;\n    initializeMethodId?: string;\n    widgetInteractionError?: Error;\n    widgetInteractionMethodId?: string;\n}\n\nexport interface PaymentStrategyStatusesState {\n    deinitializeMethodId?: string;\n    executeMethodId?: string;\n    finalizeMethodId?: string;\n    initializeMethodId?: string;\n    isDeinitializing?: boolean;\n    isExecuting?: boolean;\n    isFinalizing?: boolean;\n    isInitializing?: boolean;\n    isWidgetInteracting?: boolean;\n    widgetInteractionMethodId?: string;\n}\n\nexport const DEFAULT_STATE: PaymentStrategyState = {\n    data: {},\n    errors: {},\n    statuses: {},\n};\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge } from '../common/utility';\n\nimport { PaymentStrategyAction, PaymentStrategyActionType } from './payment-strategy-actions';\nimport PaymentStrategyState, { DEFAULT_STATE, PaymentStrategyDataState, PaymentStrategyErrorsState, PaymentStrategyStatusesState } from './payment-strategy-state';\n\nexport default function paymentStrategyReducer(\n    state: PaymentStrategyState = DEFAULT_STATE,\n    action: Action\n): PaymentStrategyState {\n    const reducer = combineReducers<PaymentStrategyState, PaymentStrategyAction>({\n        data: dataReducer,\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: PaymentStrategyDataState = DEFAULT_STATE.data,\n    action: PaymentStrategyAction\n): PaymentStrategyDataState {\n    switch (action.type) {\n    case PaymentStrategyActionType.InitializeSucceeded:\n        return objectMerge(data, {\n            [action.meta && action.meta.methodId]: {\n                isInitialized: true,\n            },\n        });\n\n    case PaymentStrategyActionType.DeinitializeSucceeded:\n        return objectMerge(data, {\n            [action.meta && action.meta.methodId]: {\n                isInitialized: false,\n            },\n        });\n    }\n\n    return data;\n}\n\nfunction errorsReducer(\n    errors: PaymentStrategyErrorsState = DEFAULT_STATE.errors,\n    action: PaymentStrategyAction\n): PaymentStrategyErrorsState {\n    switch (action.type) {\n    case PaymentStrategyActionType.InitializeRequested:\n    case PaymentStrategyActionType.InitializeSucceeded:\n        return objectMerge(errors, {\n            initializeError: undefined,\n            initializeMethodId: undefined,\n        });\n\n    case PaymentStrategyActionType.InitializeFailed:\n        return objectMerge(errors, {\n            initializeError: action.payload,\n            initializeMethodId: action.meta && action.meta.methodId,\n        });\n\n    case PaymentStrategyActionType.DeinitializeRequested:\n    case PaymentStrategyActionType.DeinitializeSucceeded:\n        return objectMerge(errors, {\n            deinitializeError: undefined,\n            deinitializeMethodId: undefined,\n        });\n\n    case PaymentStrategyActionType.DeinitializeFailed:\n        return objectMerge(errors, {\n            deinitializeError: action.payload,\n            deinitializeMethodId: action.meta && action.meta.methodId,\n        });\n\n    case PaymentStrategyActionType.ExecuteRequested:\n    case PaymentStrategyActionType.ExecuteSucceeded:\n        return objectMerge(errors, {\n            executeError: undefined,\n            executeMethodId: undefined,\n        });\n\n    case PaymentStrategyActionType.ExecuteFailed:\n        return objectMerge(errors, {\n            executeError: action.payload,\n            executeMethodId: action.meta && action.meta.methodId,\n        });\n\n    case PaymentStrategyActionType.FinalizeRequested:\n    case PaymentStrategyActionType.FinalizeSucceeded:\n        return objectMerge(errors, {\n            finalizeError: undefined,\n            finalizeMethodId: undefined,\n        });\n\n    case PaymentStrategyActionType.FinalizeFailed:\n        return objectMerge(errors, {\n            finalizeError: action.payload,\n            finalizeMethodId: action.meta && action.meta.methodId,\n        });\n\n    case PaymentStrategyActionType.WidgetInteractionStarted:\n    case PaymentStrategyActionType.WidgetInteractionFinished:\n        return objectMerge(errors, {\n            widgetInteractionError: undefined,\n            widgetInteractionMethodId: undefined,\n        });\n\n    case PaymentStrategyActionType.WidgetInteractionFailed:\n        return objectMerge(errors, {\n            widgetInteractionError: action.payload,\n            widgetInteractionMethodId: action.meta.methodId,\n        });\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: PaymentStrategyStatusesState = DEFAULT_STATE.statuses,\n    action: PaymentStrategyAction\n): PaymentStrategyStatusesState {\n    switch (action.type) {\n    case PaymentStrategyActionType.InitializeRequested:\n        return objectMerge(statuses, {\n            isInitializing: true,\n            initializeMethodId: action.meta && action.meta.methodId,\n        });\n\n    case PaymentStrategyActionType.InitializeFailed:\n    case PaymentStrategyActionType.InitializeSucceeded:\n        return objectMerge(statuses, {\n            isInitializing: false,\n            initializeMethodId: undefined,\n        });\n\n    case PaymentStrategyActionType.DeinitializeRequested:\n        return objectMerge(statuses, {\n            isDeinitializing: true,\n            deinitializeMethodId: action.meta && action.meta.methodId,\n        });\n\n    case PaymentStrategyActionType.DeinitializeFailed:\n    case PaymentStrategyActionType.DeinitializeSucceeded:\n        return objectMerge(statuses, {\n            isDeinitializing: false,\n            deinitializeMethodId: undefined,\n        });\n\n    case PaymentStrategyActionType.ExecuteRequested:\n        return objectMerge(statuses, {\n            isExecuting: true,\n            executeMethodId: action.meta && action.meta.methodId,\n        });\n\n    case PaymentStrategyActionType.ExecuteFailed:\n    case PaymentStrategyActionType.ExecuteSucceeded:\n        return objectMerge(statuses, {\n            isExecuting: false,\n            executeMethodId: undefined,\n        });\n\n    case PaymentStrategyActionType.FinalizeRequested:\n        return objectMerge(statuses, {\n            isFinalizing: true,\n            finalizeMethodId: action.meta && action.meta.methodId,\n        });\n\n    case PaymentStrategyActionType.FinalizeFailed:\n    case PaymentStrategyActionType.FinalizeSucceeded:\n        return objectMerge(statuses, {\n            isFinalizing: false,\n            finalizeMethodId: undefined,\n        });\n\n    case PaymentStrategyActionType.WidgetInteractionStarted:\n        return objectMerge(statuses, {\n            isWidgetInteracting: true,\n            widgetInteractionMethodId: action.meta.methodId,\n        });\n\n    case PaymentStrategyActionType.WidgetInteractionFinished:\n    case PaymentStrategyActionType.WidgetInteractionFailed:\n        return objectMerge(statuses, {\n            isWidgetInteracting: false,\n            widgetInteractionMethodId: undefined,\n        });\n\n    default:\n        return statuses;\n    }\n}\n","import PaymentInstrument, { VaultAccessToken } from './instrument';\n\nexport default interface InstrumentState {\n    data?: PaymentInstrument[];\n    meta?: InstrumentMeta;\n    errors: InstrumentErrorState;\n    statuses: InstrumentStatusState;\n}\n\nexport interface InstrumentErrorState {\n    deleteError?: Error;\n    failedInstrument?: string;\n    loadError?: Error;\n    vaultError?: Error;\n}\n\nexport interface InstrumentStatusState {\n    isDeleting?: boolean;\n    isLoading?: boolean;\n    isVaulting?: boolean;\n    deletingInstrument?: string;\n}\n\nexport type InstrumentMeta = VaultAccessToken;\n\nexport const DEFAULT_STATE = {\n    data: [],\n    errors: {},\n    statuses: {},\n};\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../../common/error';\nimport { arrayReplace, objectMerge, objectSet } from '../../common/utility';\n\nimport PaymentInstrument from './instrument';\nimport { InstrumentAction, InstrumentActionType } from './instrument-actions';\nimport InstrumentState, { DEFAULT_STATE, InstrumentErrorState, InstrumentMeta, InstrumentStatusState } from './instrument-state';\n\nexport default function instrumentReducer(\n    state: InstrumentState = DEFAULT_STATE,\n    action: Action\n): InstrumentState {\n    const reducer = combineReducers<InstrumentState>({\n        data: dataReducer,\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        meta: metaReducer,\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: PaymentInstrument[] = DEFAULT_STATE.data,\n    action: InstrumentAction\n): PaymentInstrument[] {\n    switch (action.type) {\n    case InstrumentActionType.LoadInstrumentsSucceeded:\n        return arrayReplace(data, action.payload && action.payload.vaultedInstruments || []);\n\n    default:\n        return data;\n    }\n}\n\nfunction metaReducer(\n    meta: InstrumentMeta | undefined,\n    action: InstrumentAction\n): InstrumentMeta | undefined {\n    switch (action.type) {\n    case InstrumentActionType.LoadInstrumentsSucceeded:\n    case InstrumentActionType.DeleteInstrumentSucceeded:\n        return objectMerge(meta, action.meta);\n\n    default:\n        return meta;\n    }\n}\n\nfunction errorsReducer(\n    errors: InstrumentErrorState = DEFAULT_STATE.errors,\n    action: InstrumentAction\n): InstrumentErrorState {\n    switch (action.type) {\n    case InstrumentActionType.LoadInstrumentsRequested:\n    case InstrumentActionType.LoadInstrumentsSucceeded:\n        return objectSet(errors, 'loadError', undefined);\n\n    case InstrumentActionType.DeleteInstrumentRequested:\n    case InstrumentActionType.DeleteInstrumentSucceeded:\n        return objectMerge(errors, {\n            deleteError: undefined,\n            failedInstrument: undefined,\n        });\n\n    case InstrumentActionType.LoadInstrumentsFailed:\n        return objectSet(errors, 'loadError', action.payload);\n\n    case InstrumentActionType.DeleteInstrumentFailed:\n        return objectMerge(errors, {\n            deleteError: action.payload,\n            failedInstrument: action.meta.instrumentId,\n        });\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: InstrumentStatusState = DEFAULT_STATE.statuses,\n    action: InstrumentAction\n): InstrumentStatusState {\n    switch (action.type) {\n    case InstrumentActionType.LoadInstrumentsRequested:\n        return objectSet(statuses, 'isLoading', true);\n\n    case InstrumentActionType.DeleteInstrumentRequested:\n        return objectMerge(statuses, {\n            isDeleting: true,\n            deletingInstrument: action.meta.instrumentId,\n        });\n\n    case InstrumentActionType.LoadInstrumentsSucceeded:\n    case InstrumentActionType.LoadInstrumentsFailed:\n        return objectSet(statuses, 'isLoading', false);\n\n    case InstrumentActionType.DeleteInstrumentSucceeded:\n    case InstrumentActionType.DeleteInstrumentFailed:\n        return objectMerge(statuses, {\n            isDeleting: false,\n            deletingInstrument: undefined,\n        });\n\n    default:\n        return statuses;\n    }\n}\n","import { AmazonPayRemoteCheckout } from './methods';\n\nexport default interface RemoteCheckoutState {\n    data: RemoteCheckoutStateData;\n}\n\nexport interface RemoteCheckoutStateData {\n    amazon?: AmazonPayRemoteCheckout;\n}\n\nexport const DEFAULT_STATE: RemoteCheckoutState = {\n    data: {},\n};\n","import { combineReducers } from '@bigcommerce/data-store';\n\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport RemoteCheckout from './remote-checkout';\nimport { RemoteCheckoutAction, RemoteCheckoutActionType } from './remote-checkout-actions';\nimport RemoteCheckoutState, { DEFAULT_STATE, RemoteCheckoutStateData } from './remote-checkout-state';\n\nexport default function remoteCheckoutReducer(\n    state: RemoteCheckoutState = DEFAULT_STATE,\n    action: RemoteCheckoutAction\n): RemoteCheckoutState {\n    if (!action.meta || !action.meta.methodId) {\n        return state;\n    }\n\n    const reducer = combineReducers<RemoteCheckoutState>({\n        data: combineReducers<RemoteCheckoutStateData>({\n            [action.meta.methodId]: dataReducer,\n        }),\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: RemoteCheckout,\n    action: RemoteCheckoutAction\n): RemoteCheckout {\n    switch (action.type) {\n    case RemoteCheckoutActionType.InitializeRemoteBillingSucceeded:\n        return objectSet(data, 'billing' as any, action.payload && action.payload.billing);\n\n    case RemoteCheckoutActionType.InitializeRemoteShippingSucceeded:\n        return objectSet(data, 'shipping' as any, action.payload && action.payload.shipping);\n\n    case RemoteCheckoutActionType.LoadRemoteSettingsSucceeded:\n        return objectSet(data, 'settings', action.payload);\n\n    case RemoteCheckoutActionType.UpdateRemoteCheckout:\n        return objectMerge(data, action.payload);\n\n    default:\n        return data;\n    }\n}\n","import Consignment from './consignment';\n\nexport default interface ConsignmentState {\n    data?: Consignment[];\n    errors: ConsignmentErrorsState;\n    statuses: ConsignmentStatusesState;\n}\n\nexport interface ConsignmentErrorsState {\n    loadError?: Error;\n    loadShippingOptionsError?: Error;\n    createError?: Error;\n    updateError: { [key: string]: Error | undefined };\n    deleteError: { [key: string]: Error | undefined };\n    updateShippingOptionError: { [key: string]: Error | undefined };\n}\n\nexport interface ConsignmentStatusesState {\n    isLoading?: boolean;\n    isLoadingShippingOptions?: boolean;\n    isCreating?: boolean;\n    isUpdating: { [key: string]: boolean };\n    isDeleting: { [key: string]: boolean };\n    isUpdatingShippingOption: { [key: string]: boolean };\n}\n\nexport const DEFAULT_STATE: ConsignmentState = {\n    errors: {\n        updateShippingOptionError: {},\n        updateError: {},\n        deleteError: {},\n    },\n    statuses: {\n        isUpdating: {},\n        isUpdatingShippingOption: {},\n        isDeleting: {},\n    },\n};\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectMerge, objectSet } from '../common/utility';\nimport { CouponAction, CouponActionType } from '../coupon';\nimport { CustomerAction, CustomerActionType } from '../customer';\n\nimport Consignment from './consignment';\nimport { ConsignmentAction, ConsignmentActionType } from './consignment-actions';\nimport ConsignmentState, { ConsignmentErrorsState, ConsignmentStatusesState, DEFAULT_STATE } from './consignment-state';\n\nexport default function consignmentReducer(\n    state: ConsignmentState = DEFAULT_STATE,\n    action: Action\n): ConsignmentState {\n    const reducer = combineReducers<ConsignmentState, ConsignmentAction | CheckoutAction>({\n        data: dataReducer,\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: Consignment[] | undefined,\n    action: ConsignmentAction | CheckoutAction | CouponAction | CustomerAction\n): Consignment[] | undefined {\n    switch (action.type) {\n    case CheckoutActionType.LoadCheckoutSucceeded:\n    case ConsignmentActionType.LoadShippingOptionsSucceeded:\n    case ConsignmentActionType.CreateConsignmentsSucceeded:\n    case ConsignmentActionType.UpdateConsignmentSucceeded:\n    case ConsignmentActionType.DeleteConsignmentSucceeded:\n    case ConsignmentActionType.UpdateShippingOptionSucceeded:\n    case CouponActionType.ApplyCouponSucceeded:\n    case CouponActionType.RemoveCouponSucceeded:\n        return arrayReplace(data, action.payload && action.payload.consignments);\n\n    case CustomerActionType.SignOutCustomerSucceeded:\n        return arrayReplace(data, []);\n\n    default:\n        return data;\n    }\n}\n\nfunction errorsReducer(\n    errors: ConsignmentErrorsState = DEFAULT_STATE.errors,\n    action: ConsignmentAction | CheckoutAction\n): ConsignmentErrorsState {\n    switch (action.type) {\n    case CheckoutActionType.LoadCheckoutRequested:\n    case CheckoutActionType.LoadCheckoutSucceeded:\n    case ConsignmentActionType.LoadShippingOptionsSucceeded:\n    case ConsignmentActionType.LoadShippingOptionsRequested:\n        return objectSet(errors, 'loadError', undefined);\n\n    case CheckoutActionType.LoadCheckoutFailed:\n    case ConsignmentActionType.LoadShippingOptionsFailed:\n        return objectSet(errors, 'loadError', action.payload);\n\n    case ConsignmentActionType.CreateConsignmentsRequested:\n    case ConsignmentActionType.CreateConsignmentsSucceeded:\n        return objectSet(errors, 'createError', undefined);\n\n    case ConsignmentActionType.CreateConsignmentsFailed:\n        return objectSet(errors, 'createError', action.payload);\n\n    case ConsignmentActionType.UpdateConsignmentSucceeded:\n    case ConsignmentActionType.UpdateConsignmentRequested:\n        if (action.meta) {\n            return objectMerge(errors, {\n                updateError: {\n                    [action.meta.id]: undefined,\n                },\n            });\n        }\n\n        return errors;\n\n    case ConsignmentActionType.UpdateConsignmentFailed:\n        if (action.meta) {\n            return objectMerge(errors, {\n                updateError: {\n                    [action.meta.id]: action.payload,\n                },\n            });\n        }\n\n        return errors;\n\n    case ConsignmentActionType.DeleteConsignmentSucceeded:\n    case ConsignmentActionType.DeleteConsignmentRequested:\n        if (action.meta) {\n            return objectMerge(errors, {\n                deleteError: {\n                    [action.meta.id]: undefined,\n                },\n            });\n        }\n\n        return errors;\n\n    case ConsignmentActionType.DeleteConsignmentFailed:\n        if (action.meta) {\n            return objectMerge(errors, {\n                deleteError: {\n                    [action.meta.id]: action.payload,\n                },\n            });\n        }\n\n        return errors;\n\n    case ConsignmentActionType.UpdateShippingOptionRequested:\n    case ConsignmentActionType.UpdateShippingOptionSucceeded:\n        if (action.meta) {\n            return objectMerge(errors, {\n                updateShippingOptionError: {\n                    [action.meta.id]: undefined,\n                },\n            });\n        }\n\n        return errors;\n\n    case ConsignmentActionType.UpdateShippingOptionFailed:\n        if (action.meta) {\n            return objectMerge(errors, {\n                updateShippingOptionError: {\n                    [action.meta.id]: action.payload,\n                },\n            });\n        }\n\n        return errors;\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: ConsignmentStatusesState = DEFAULT_STATE.statuses,\n    action: ConsignmentAction | CheckoutAction\n): ConsignmentStatusesState {\n    switch (action.type) {\n    case CheckoutActionType.LoadCheckoutRequested:\n        return objectSet(statuses, 'isLoading', true);\n\n    case ConsignmentActionType.LoadShippingOptionsRequested:\n        return objectSet(statuses, 'isLoadingShippingOptions', true);\n\n    case CheckoutActionType.LoadCheckoutSucceeded:\n    case CheckoutActionType.LoadCheckoutFailed:\n        return objectSet(statuses, 'isLoading', false);\n\n    case ConsignmentActionType.LoadShippingOptionsSucceeded:\n    case ConsignmentActionType.LoadShippingOptionsFailed:\n        return objectSet(statuses, 'isLoadingShippingOptions', false);\n\n    case ConsignmentActionType.CreateConsignmentsRequested:\n        return objectSet(statuses, 'isCreating', true);\n\n    case ConsignmentActionType.CreateConsignmentsSucceeded:\n    case ConsignmentActionType.CreateConsignmentsFailed:\n        return objectSet(statuses, 'isCreating', false);\n\n    case ConsignmentActionType.UpdateConsignmentRequested:\n        if (action.meta) {\n            return objectMerge(statuses, {\n                isUpdating: {\n                    [action.meta.id]: true,\n                },\n            });\n        }\n\n        return statuses;\n\n    case ConsignmentActionType.UpdateConsignmentSucceeded:\n    case ConsignmentActionType.UpdateConsignmentFailed:\n        if (action.meta) {\n            return objectMerge(statuses, {\n                isUpdating: {\n                    [action.meta.id]: false,\n                },\n            });\n        }\n\n        return statuses;\n\n    case ConsignmentActionType.DeleteConsignmentRequested:\n        if (action.meta) {\n            return objectMerge(statuses, {\n                isDeleting: {\n                    [action.meta.id]: true,\n                },\n            });\n        }\n\n        return statuses;\n\n    case ConsignmentActionType.DeleteConsignmentSucceeded:\n    case ConsignmentActionType.DeleteConsignmentFailed:\n        if (action.meta) {\n            return objectMerge(statuses, {\n                isDeleting: {\n                    [action.meta.id]: false,\n                },\n            });\n        }\n\n        return statuses;\n\n    case ConsignmentActionType.UpdateShippingOptionRequested:\n        if (action.meta) {\n            return objectMerge(statuses, {\n                isUpdatingShippingOption: {\n                    [action.meta.id]: true,\n                },\n            });\n        }\n\n        return statuses;\n\n    case ConsignmentActionType.UpdateShippingOptionSucceeded:\n    case ConsignmentActionType.UpdateShippingOptionFailed:\n        if (action.meta) {\n            return objectMerge(statuses, {\n                isUpdatingShippingOption: {\n                    [action.meta.id]: false,\n                },\n            });\n        }\n\n        return statuses;\n\n    default:\n        return statuses;\n    }\n}\n","import { Country } from '../geography';\n\nexport default interface ShippingCountryState {\n    data?: Country[];\n    errors: ShippingCountryErrorsState;\n    statuses: ShippingCountryStatusesState;\n}\n\nexport interface ShippingCountryErrorsState {\n    loadError?: Error;\n}\n\nexport interface ShippingCountryStatusesState {\n    isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: ShippingCountryState = {\n    errors: {},\n    statuses: {},\n};\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\nimport { Country } from '../geography';\n\nimport { LoadShippingCountriesAction, ShippingCountryActionType } from './shipping-country-actions';\nimport ShippingCountryState, { DEFAULT_STATE, ShippingCountryErrorsState, ShippingCountryStatusesState } from './shipping-country-state';\n\nexport default function shippingCountryReducer(\n    state: ShippingCountryState = DEFAULT_STATE,\n    action: Action\n): ShippingCountryState {\n    const reducer = combineReducers<ShippingCountryState>({\n        data: dataReducer,\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: Country[] | undefined,\n    action: LoadShippingCountriesAction\n): Country[] | undefined {\n    switch (action.type) {\n    case ShippingCountryActionType.LoadShippingCountriesSucceeded:\n        return arrayReplace(data, action.payload);\n\n    default:\n        return data;\n    }\n}\n\nfunction errorsReducer(\n    errors: ShippingCountryErrorsState = DEFAULT_STATE.errors,\n    action: LoadShippingCountriesAction\n): ShippingCountryErrorsState {\n    switch (action.type) {\n    case ShippingCountryActionType.LoadShippingCountriesRequested:\n    case ShippingCountryActionType.LoadShippingCountriesSucceeded:\n        return objectSet(errors, 'loadError', undefined);\n\n    case ShippingCountryActionType.LoadShippingCountriesFailed:\n        return objectSet(errors, 'loadError', action.payload);\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: ShippingCountryStatusesState = DEFAULT_STATE.statuses,\n    action: LoadShippingCountriesAction\n): ShippingCountryStatusesState {\n    switch (action.type) {\n    case ShippingCountryActionType.LoadShippingCountriesRequested:\n        return objectSet(statuses, 'isLoading', true);\n\n    case ShippingCountryActionType.LoadShippingCountriesSucceeded:\n    case ShippingCountryActionType.LoadShippingCountriesFailed:\n        return objectSet(statuses, 'isLoading', false);\n\n    default:\n        return statuses;\n    }\n}\n","export default interface ShippingStrategyState {\n    data: ShippingStrategyDataState;\n    errors: ShippingStrategyErrorsState;\n    statuses: ShippingStrategyStatusesState;\n}\n\nexport interface ShippingStrategyDataState {\n    [key: string]: {\n        isInitialized: boolean;\n    };\n}\n\nexport interface ShippingStrategyErrorsState {\n    deinitializeError?: Error;\n    deinitializeMethodId?: string;\n    initializeError?: Error;\n    initializeMethodId?: string;\n    updateAddressError?: Error;\n    updateAddressMethodId?: string;\n    selectOptionError?: Error;\n    selectOptionMethodId?: string;\n    widgetInteractionError?: Error;\n    widgetInteractionMethodId?: string;\n}\n\nexport interface ShippingStrategyStatusesState {\n    deinitializeMethodId?: string;\n    initializeMethodId?: string;\n    isDeinitializing?: boolean;\n    isInitializing?: boolean;\n    isUpdatingAddress?: boolean;\n    isSelectingOption?: boolean;\n    updateAddressMethodId?: string;\n    selectOptionMethodId?: string;\n    isWidgetInteracting?: boolean;\n    widgetInteractionMethodId?: string;\n}\n\nexport const DEFAULT_STATE: ShippingStrategyState = {\n    data: {},\n    errors: {},\n    statuses: {},\n};\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge } from '../common/utility';\n\nimport { ShippingStrategyAction, ShippingStrategyActionType } from './shipping-strategy-actions';\nimport ShippingStrategyState, { DEFAULT_STATE, ShippingStrategyDataState, ShippingStrategyErrorsState, ShippingStrategyStatusesState } from './shipping-strategy-state';\n\nexport default function shippingStrategyReducer(\n    state: ShippingStrategyState = DEFAULT_STATE,\n    action: Action\n): ShippingStrategyState {\n    const reducer = combineReducers<ShippingStrategyState, ShippingStrategyAction>({\n        data: dataReducer,\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: ShippingStrategyDataState = DEFAULT_STATE.data,\n    action: ShippingStrategyAction\n): ShippingStrategyDataState {\n    switch (action.type) {\n    case ShippingStrategyActionType.InitializeSucceeded:\n        return objectMerge(data, {\n            [action.meta && action.meta.methodId]: {\n                isInitialized: true,\n            },\n        });\n\n    case ShippingStrategyActionType.DeinitializeSucceeded:\n        return objectMerge(data, {\n            [action.meta && action.meta.methodId]: {\n                isInitialized: false,\n            },\n        });\n    }\n\n    return data;\n}\n\nfunction errorsReducer(\n    errors: ShippingStrategyErrorsState = DEFAULT_STATE.errors,\n    action: ShippingStrategyAction\n): ShippingStrategyErrorsState {\n    switch (action.type) {\n    case ShippingStrategyActionType.InitializeRequested:\n    case ShippingStrategyActionType.InitializeSucceeded:\n        return objectMerge(errors, {\n            initializeError: undefined,\n            initializeMethodId: undefined,\n        });\n\n    case ShippingStrategyActionType.InitializeFailed:\n        return objectMerge(errors, {\n            initializeError: action.payload,\n            initializeMethodId: action.meta && action.meta.methodId,\n        });\n\n    case ShippingStrategyActionType.DeinitializeRequested:\n    case ShippingStrategyActionType.DeinitializeSucceeded:\n        return objectMerge(errors, {\n            deinitializeError: undefined,\n            deinitializeMethodId: undefined,\n        });\n\n    case ShippingStrategyActionType.DeinitializeFailed:\n        return objectMerge(errors, {\n            deinitializeError: action.payload,\n            deinitializeMethodId: action.meta && action.meta.methodId,\n        });\n\n    case ShippingStrategyActionType.UpdateAddressRequested:\n    case ShippingStrategyActionType.UpdateAddressSucceeded:\n        return objectMerge(errors, {\n            updateAddressError: undefined,\n            updateAddressMethodId: undefined,\n        });\n\n    case ShippingStrategyActionType.UpdateAddressFailed:\n        return objectMerge(errors, {\n            updateAddressError: action.payload,\n            updateAddressMethodId: action.meta && action.meta.methodId,\n        });\n\n    case ShippingStrategyActionType.SelectOptionRequested:\n    case ShippingStrategyActionType.SelectOptionSucceeded:\n        return objectMerge(errors, {\n            selectOptionError: undefined,\n            selectOptionMethodId: undefined,\n        });\n\n    case ShippingStrategyActionType.SelectOptionFailed:\n        return objectMerge(errors, {\n            selectOptionError: action.payload,\n            selectOptionMethodId: action.meta && action.meta.methodId,\n        });\n\n    case ShippingStrategyActionType.WidgetInteractionStarted:\n    case ShippingStrategyActionType.WidgetInteractionFinished:\n        return objectMerge(errors, {\n            widgetInteractionError: undefined,\n            widgetInteractionMethodId: undefined,\n        });\n\n    case ShippingStrategyActionType.WidgetInteractionFailed:\n        return objectMerge(errors, {\n            widgetInteractionError: action.payload,\n            widgetInteractionMethodId: action.meta && action.meta.methodId,\n        });\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: ShippingStrategyStatusesState = DEFAULT_STATE.statuses,\n    action: ShippingStrategyAction\n): ShippingStrategyStatusesState {\n    switch (action.type) {\n    case ShippingStrategyActionType.InitializeRequested:\n        return objectMerge(statuses, {\n            isInitializing: true,\n            initializeMethodId: action.meta && action.meta.methodId,\n        });\n\n    case ShippingStrategyActionType.InitializeFailed:\n    case ShippingStrategyActionType.InitializeSucceeded:\n        return objectMerge(statuses, {\n            isInitializing: false,\n            initializeMethodId: undefined,\n        });\n\n    case ShippingStrategyActionType.DeinitializeRequested:\n        return objectMerge(statuses, {\n            isDeinitializing: true,\n            deinitializeMethodId: action.meta && action.meta.methodId,\n        });\n\n    case ShippingStrategyActionType.DeinitializeFailed:\n    case ShippingStrategyActionType.DeinitializeSucceeded:\n        return objectMerge(statuses, {\n            isDeinitializing: false,\n            deinitializeMethodId: undefined,\n        });\n\n    case ShippingStrategyActionType.UpdateAddressRequested:\n        return objectMerge(statuses, {\n            isUpdatingAddress: true,\n            updateAddressMethodId: action.meta && action.meta.methodId,\n        });\n\n    case ShippingStrategyActionType.UpdateAddressFailed:\n    case ShippingStrategyActionType.UpdateAddressSucceeded:\n        return objectMerge(statuses, {\n            isUpdatingAddress: false,\n            updateAddressMethodId: undefined,\n        });\n\n    case ShippingStrategyActionType.SelectOptionRequested:\n        return objectMerge(statuses, {\n            isSelectingOption: true,\n            selectOptionMethodId: action.meta && action.meta.methodId,\n        });\n\n    case ShippingStrategyActionType.SelectOptionFailed:\n    case ShippingStrategyActionType.SelectOptionSucceeded:\n        return objectMerge(statuses, {\n            isSelectingOption: false,\n            selectOptionMethodId: undefined,\n        });\n\n    case ShippingStrategyActionType.WidgetInteractionStarted:\n        return objectMerge(statuses, {\n            isWidgetInteracting: true,\n            widgetInteractionMethodId: action.meta && action.meta.methodId,\n        });\n\n    case ShippingStrategyActionType.WidgetInteractionFinished:\n    case ShippingStrategyActionType.WidgetInteractionFailed:\n        return objectMerge(statuses, {\n            isWidgetInteracting: false,\n            widgetInteractionMethodId: undefined,\n        });\n\n    default:\n        return statuses;\n    }\n}\n","import { SignInEmail } from './signin-email';\n\nexport default interface SignInEmailState {\n    data?: SignInEmail;\n    errors: SignInEmailErrorsState;\n    statuses: SignInEmailStatusesState;\n}\n\nexport interface SignInEmailErrorsState {\n    sendError?: Error;\n}\n\nexport interface SignInEmailStatusesState {\n    isSending?: boolean;\n}\n\nexport const DEFAULT_STATE: SignInEmailState = {\n    errors: {},\n    statuses: {},\n};\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { SignInEmail } from './signin-email';\nimport { SendSignInEmailAction, SignInEmailActionType } from './signin-email-actions';\nimport SignInEmailState, { DEFAULT_STATE, SignInEmailErrorsState, SignInEmailStatusesState } from './signin-email-state';\n\nexport default function signInEmailReducer(\n    state: SignInEmailState = DEFAULT_STATE,\n    action: Action\n): SignInEmailState {\n    const reducer = combineReducers<SignInEmailState>({\n        data: dataReducer,\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: SignInEmail | undefined,\n    action: SendSignInEmailAction\n): SignInEmail | undefined {\n    switch (action.type) {\n    case SignInEmailActionType.SendSignInEmailSucceeded:\n        return objectMerge(data, action.payload);\n\n    default:\n        return data;\n    }\n}\n\nfunction errorsReducer(\n    errors: SignInEmailErrorsState = DEFAULT_STATE.errors,\n    action: SendSignInEmailAction\n): SignInEmailErrorsState {\n    switch (action.type) {\n    case SignInEmailActionType.SendSignInEmailRequested:\n    case SignInEmailActionType.SendSignInEmailSucceeded:\n        return objectSet(errors, 'sendError', undefined);\n\n    case SignInEmailActionType.SendSignInEmailFailed:\n        return objectSet(errors, 'sendError', action.payload);\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: SignInEmailStatusesState = DEFAULT_STATE.statuses,\n    action: SendSignInEmailAction\n): SignInEmailStatusesState {\n    switch (action.type) {\n    case SignInEmailActionType.SendSignInEmailRequested:\n        return objectSet(statuses, 'isSending', true);\n\n    case SignInEmailActionType.SendSignInEmailFailed:\n    case SignInEmailActionType.SendSignInEmailSucceeded:\n        return objectSet(statuses, 'isSending', false);\n    default:\n        return statuses;\n    }\n}\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectSet } from '../common/utility';\n\nimport { StoreCreditAction, StoreCreditActionType } from './store-credit-actions';\nimport StoreCreditState, { StoreCreditErrorsState, StoreCreditStatusesState } from './store-credit-state';\n\nconst DEFAULT_STATE: StoreCreditState = {\n    errors: {},\n    statuses: {},\n};\n\nexport default function storeCreditReducer(\n    state: StoreCreditState = DEFAULT_STATE,\n    action: Action\n): StoreCreditState {\n    const reducer = combineReducers<StoreCreditState>({\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction errorsReducer(\n    errors: StoreCreditErrorsState = DEFAULT_STATE.errors,\n    action: StoreCreditAction\n): StoreCreditErrorsState {\n    switch (action.type) {\n    case StoreCreditActionType.ApplyStoreCreditRequested:\n    case StoreCreditActionType.ApplyStoreCreditSucceeded:\n        return objectSet(errors, 'applyError', undefined);\n\n    case StoreCreditActionType.ApplyStoreCreditFailed:\n        return objectSet(errors, 'applyError', action.payload);\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: StoreCreditStatusesState = DEFAULT_STATE.statuses,\n    action: StoreCreditAction\n): StoreCreditStatusesState {\n    switch (action.type) {\n    case StoreCreditActionType.ApplyStoreCreditRequested:\n        return objectSet(statuses, 'isApplying', true);\n\n    case StoreCreditActionType.ApplyStoreCreditSucceeded:\n    case StoreCreditActionType.ApplyStoreCreditFailed:\n        return objectSet(statuses, 'isApplying', false);\n\n    default:\n        return statuses;\n    }\n}\n","export default interface SubscriptionsState {\n    errors: SubscriptionsErrorsState;\n    statuses: SubscriptionsStatusesState;\n}\n\nexport interface SubscriptionsErrorsState {\n    updateError?: Error;\n}\n\nexport interface SubscriptionsStatusesState {\n    isUpdating?: boolean;\n}\n\nexport const DEFAULT_STATE: SubscriptionsState = {\n    errors: {},\n    statuses: {},\n};\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectSet } from '../common/utility';\nimport { SubscriptionsActionType, UpdateSubscriptionsAction } from '../subscription';\n\nimport SubscriptionsState, { DEFAULT_STATE, SubscriptionsErrorsState, SubscriptionsStatusesState } from './subscriptions-state';\n\nexport default function subscriptionsReducer(\n    state: SubscriptionsState = DEFAULT_STATE,\n    action: Action\n): SubscriptionsState {\n    const reducer = combineReducers<SubscriptionsState>({\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction errorsReducer(\n    errors: SubscriptionsErrorsState = DEFAULT_STATE.errors,\n    action: UpdateSubscriptionsAction\n): SubscriptionsErrorsState {\n    switch (action.type) {\n    case SubscriptionsActionType.UpdateSubscriptionsRequested:\n    case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n        return objectSet(errors, 'updateError', undefined);\n\n    case SubscriptionsActionType.UpdateSubscriptionsFailed:\n        return objectSet(errors, 'updateError', action.payload);\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: SubscriptionsStatusesState = DEFAULT_STATE.statuses,\n    action: UpdateSubscriptionsAction\n): SubscriptionsStatusesState {\n    switch (action.type) {\n    case SubscriptionsActionType.UpdateSubscriptionsRequested:\n        return objectSet(statuses, 'isUpdating', true);\n\n    case SubscriptionsActionType.UpdateSubscriptionsFailed:\n    case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n        return objectSet(statuses, 'isUpdating', false);\n    default:\n        return statuses;\n    }\n}\n","import { Omit } from '../common/types';\n\nimport Checkout from './checkout';\n\nexport default interface CheckoutState {\n    data?: CheckoutDataState;\n    errors: CheckoutErrorsState;\n    statuses: CheckoutStatusesState;\n}\n\nexport type CheckoutDataState = Omit<Checkout, 'billingAddress' | 'cart' | 'consignments' | 'coupons' | 'giftCertificates'>;\n\nexport interface CheckoutErrorsState {\n    loadError?: Error;\n    updateError?: Error;\n}\n\nexport interface CheckoutStatusesState {\n    isExecutingSpamCheck?: boolean;\n    isLoading?: boolean;\n    isUpdating?: boolean;\n}\n\nexport const DEFAULT_STATE: CheckoutState = {\n    errors: {},\n    statuses: {},\n};\n","import { combineReducers, composeReducers, Action } from '@bigcommerce/data-store';\nimport { omit } from 'lodash';\n\nimport { BillingAddressAction, BillingAddressActionType } from '../billing';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\nimport { CouponAction, CouponActionType, GiftCertificateAction, GiftCertificateActionType } from '../coupon';\nimport { OrderAction, OrderActionType } from '../order';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\nimport { SpamProtectionAction, SpamProtectionActionType } from '../spam-protection';\nimport { StoreCreditAction, StoreCreditActionType } from '../store-credit';\n\nimport { CheckoutAction, CheckoutActionType } from './checkout-actions';\nimport CheckoutState, { CheckoutDataState, CheckoutErrorsState, CheckoutStatusesState, DEFAULT_STATE } from './checkout-state';\n\nexport default function checkoutReducer(\n    state: CheckoutState = DEFAULT_STATE,\n    action: Action\n): CheckoutState {\n    const reducer = combineReducers<CheckoutState>({\n        data: dataReducer,\n        errors: composeReducers(errorsReducer, clearErrorReducer),\n        statuses: statusesReducer,\n    });\n\n    return reducer(state, action);\n}\n\nfunction dataReducer(\n    data: CheckoutDataState | undefined,\n    action: CheckoutAction | BillingAddressAction | ConsignmentAction | CouponAction |\n        GiftCertificateAction | OrderAction | SpamProtectionAction | StoreCreditAction\n): CheckoutDataState | undefined {\n    switch (action.type) {\n    case CheckoutActionType.LoadCheckoutSucceeded:\n    case CheckoutActionType.UpdateCheckoutSucceeded:\n    case StoreCreditActionType.ApplyStoreCreditSucceeded:\n    case BillingAddressActionType.UpdateBillingAddressSucceeded:\n    case CouponActionType.ApplyCouponSucceeded:\n    case CouponActionType.RemoveCouponSucceeded:\n    case ConsignmentActionType.CreateConsignmentsSucceeded:\n    case ConsignmentActionType.UpdateConsignmentSucceeded:\n    case ConsignmentActionType.DeleteConsignmentSucceeded:\n    case ConsignmentActionType.UpdateShippingOptionSucceeded:\n    case ConsignmentActionType.LoadShippingOptionsSucceeded:\n    case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n    case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n    case SpamProtectionActionType.VerifyCheckoutSucceeded:\n        return objectMerge(data, omit(action.payload, [\n            'billingAddress',\n            'cart',\n            'consignments',\n            'customer',\n            'coupons',\n            'giftCertificates',\n        ])) as CheckoutDataState;\n\n    case OrderActionType.SubmitOrderSucceeded:\n        return objectSet(data, 'orderId', action.payload && action.payload.order.orderId) ;\n\n    default:\n        return data;\n    }\n}\n\nfunction errorsReducer(\n    errors: CheckoutErrorsState = DEFAULT_STATE.errors,\n    action: CheckoutAction | OrderAction\n): CheckoutErrorsState {\n    switch (action.type) {\n    case CheckoutActionType.LoadCheckoutRequested:\n    case CheckoutActionType.LoadCheckoutSucceeded:\n        return objectSet(errors, 'loadError', undefined);\n\n    case CheckoutActionType.LoadCheckoutFailed:\n        return objectSet(errors, 'loadError', action.payload);\n\n    case CheckoutActionType.UpdateCheckoutRequested:\n    case CheckoutActionType.UpdateCheckoutSucceeded:\n        return objectSet(errors, 'updateError', undefined);\n\n    case CheckoutActionType.UpdateCheckoutFailed:\n        return objectSet(errors, 'updateError', action.payload);\n\n    default:\n        return errors;\n    }\n}\n\nfunction statusesReducer(\n    statuses: CheckoutStatusesState = DEFAULT_STATE.statuses,\n    action: CheckoutAction | OrderAction | SpamProtectionAction\n): CheckoutStatusesState {\n    switch (action.type) {\n    case CheckoutActionType.LoadCheckoutRequested:\n        return objectSet(statuses, 'isLoading', true);\n\n    case CheckoutActionType.LoadCheckoutFailed:\n    case CheckoutActionType.LoadCheckoutSucceeded:\n        return objectSet(statuses, 'isLoading', false);\n\n    case CheckoutActionType.UpdateCheckoutRequested:\n        return objectSet(statuses, 'isUpdating', true);\n\n    case CheckoutActionType.UpdateCheckoutFailed:\n    case CheckoutActionType.UpdateCheckoutSucceeded:\n        return objectSet(statuses, 'isUpdating', false);\n\n    case SpamProtectionActionType.ExecuteRequested:\n        return objectSet(statuses, 'isExecutingSpamCheck', true);\n\n    case SpamProtectionActionType.ExecuteFailed:\n    case SpamProtectionActionType.ExecuteSucceeded:\n        return objectSet(statuses, 'isExecutingSpamCheck', false);\n\n    default:\n        return statuses;\n    }\n}\n","export default function guard<T>(value: T, errorFactory?: () => Error): NonNullable<T> {\n    if (value === undefined || value === null) {\n        throw errorFactory ? errorFactory() : new Error('An unexpected error has occurred.');\n    }\n\n    return value as NonNullable<T>;\n}\n","import { deepFreeze } from '@bigcommerce/data-store';\n\n// tslint:disable-next-line:ban-types\ntype FunctionProperties<T> = { [K in keyof T]: T[K] extends Function ? T[K] : never };\n\nexport default function createFreezeProxy<T extends object>(target: T): T {\n    return createProxy(target, (target, name) =>\n        (...args: any[]) => deepFreeze(target[name].call(target, ...args))\n    );\n}\n\nexport function createFreezeProxies<T extends object, TMap extends { [key: string]: T }>(map: TMap): TMap {\n    return Object.keys(map)\n        .reduce((result, key) => {\n            result[key] = createFreezeProxy(map[key]);\n\n            return result;\n        }, {} as { [key: string]: T }) as TMap;\n}\n\nfunction createProxy<T extends object>(target: T, trap: (target: FunctionProperties<T>, name: keyof FunctionProperties<T>, proxy: T) => any): T {\n    const proxy = Object.create(target);\n\n    traversePrototypeOf(target, prototype => {\n        Object.getOwnPropertyNames(prototype)\n            .forEach(name => {\n                if (name === 'constructor' || typeof proxy[name] !== 'function' || name.charAt(0) === '_') {\n                    return;\n                }\n\n                proxy[name] = trap(target as FunctionProperties<T>, name as keyof T, proxy);\n            });\n    });\n\n    return proxy;\n}\n\nfunction traversePrototypeOf(target: object, iteratee: (prototype: object) => void): void {\n    let prototype = Object.getPrototypeOf(target);\n\n    while (prototype) {\n        iteratee(prototype);\n\n        prototype = Object.getPrototypeOf(prototype);\n    }\n}\n","import PaymentInstrument from './instrument';\n\ninterface SupportedInstruments {\n    [key: string]: Pick<PaymentInstrument, 'method' | 'provider'>;\n}\n\nconst supportedInstruments: SupportedInstruments = {\n    'mollie.credit_card': {\n        provider: 'mollie',\n        method: 'credit_card',\n    },\n    'adyenv2.scheme': {\n        provider: 'adyenv2',\n        method: 'scheme',\n    },\n    'adyenv2.bcmc': {\n        provider: 'adyenv2',\n        method: 'bcmc',\n    },\n    'adyenv2.ideal': {\n        provider: 'adyenv2',\n        method: 'ideal',\n    },\n    'adyenv2.sepadirectdebit': {\n        provider: 'adyenv2',\n        method: 'sepadirectdebit',\n    },\n    'adyenv2.directEbanking': {\n        provider: 'adyenv2',\n        method: 'directEbanking',\n    },\n    'adyenv2.giropay': {\n        provider: 'adyenv2',\n        method: 'giropay',\n    },\n    barclays: {\n        provider: 'barclays',\n        method: 'credit_card',\n    },\n    braintree: {\n        provider: 'braintree',\n        method: 'credit_card',\n    },\n    braintreepaypal: {\n        provider: 'braintree',\n        method: 'paypal',\n    },\n    authorizenet: {\n        provider: 'authorizenet',\n        method: 'credit_card',\n    },\n    elavon: {\n        provider: 'elavon',\n        method: 'credit_card',\n    },\n    checkoutcom: {\n        provider: 'checkoutcom',\n        method: 'credit_card',\n    },\n    'checkoutcom.credit_card': {\n        provider: 'checkoutcom',\n        method: 'credit_card',\n    },\n    stripe: {\n        provider: 'stripe',\n        method: 'credit_card',\n    },\n    'stripev3.card': {\n        provider: 'stripev3',\n        method: 'card',\n    },\n    cybersource: {\n        provider: 'cybersource',\n        method: 'credit_card',\n    },\n    cybersourcev2: {\n        provider: 'cybersourcev2',\n        method: 'credit_card',\n    },\n    converge: {\n        provider: 'converge',\n        method: 'credit_card',\n    },\n    bluesnapv2: {\n        provider: 'bluesnapv2',\n        method: 'credit_card',\n    },\n    orbital: {\n        provider: 'orbital',\n        method: 'credit_card',\n    },\n    paymetric: {\n        provider: 'paymetric',\n        method: 'credit_card',\n    },\n    bolt: {\n        provider: 'bolt',\n        method: 'credit_card',\n    },\n    'barclaycard.credit_card': {\n        provider: 'barclaycard',\n        method: 'credit_card',\n    },\n    digitalriver: {\n        provider: 'digitalriver',\n        method: 'credit_card',\n    },\n};\n\nexport default supportedInstruments;\n","import { identity, isEqual, pickBy } from 'lodash';\n\nimport Address from './address';\n\nexport default function isAddressEqual(addressA: Partial<Address>, addressB: Partial<Address>): boolean {\n    return isEqual(normalize(addressA), normalize(addressB));\n}\n\nfunction normalize(address: Partial<Address>): Partial<Address> {\n    return pickBy({\n        firstName: address.firstName,\n        lastName: address.lastName,\n        company: address.company,\n        address1: address.address1,\n        address2: address.address2,\n        city: address.city,\n        stateOrProvince: address.stateOrProvince,\n        countryCode: address.countryCode,\n        postalCode: address.postalCode,\n        phone: address.phone,\n        customFields: address.customFields,\n    }, identity);\n}\n","import { StorefrontErrorResponseBody } from '../common/error';\nimport { RequestError } from '../common/error/errors';\n\nexport default interface StoreCreditState {\n    errors: StoreCreditErrorsState;\n    statuses: StoreCreditStatusesState;\n}\n\nexport interface StoreCreditErrorsState {\n    applyError?: RequestError<StorefrontErrorResponseBody>;\n}\n\nexport interface StoreCreditStatusesState {\n    isApplying?: boolean;\n}\n\nexport const DEFAULT_STATE: StoreCreditState = {\n    errors: {},\n    statuses: {},\n};\n","import { createBillingAddressSelectorFactory } from '../billing';\nimport { createCartSelectorFactory } from '../cart';\nimport { createCheckoutButtonSelectorFactory } from '../checkout-buttons';\nimport { createFreezeProxies } from '../common/utility';\nimport { createConfigSelectorFactory } from '../config';\nimport { createCouponSelectorFactory, createGiftCertificateSelectorFactory } from '../coupon';\nimport { createCustomerSelectorFactory, createCustomerStrategySelectorFactory } from '../customer';\nimport { createFormSelectorFactory } from '../form';\nimport { createCountrySelectorFactory } from '../geography';\nimport { createOrderSelectorFactory } from '../order';\nimport { createPaymentMethodSelectorFactory, createPaymentSelectorFactory, createPaymentStrategySelectorFactory } from '../payment';\nimport { createInstrumentSelectorFactory } from '../payment/instrument';\nimport { createRemoteCheckoutSelectorFactory } from '../remote-checkout';\nimport { createConsignmentSelectorFactory, createShippingAddressSelectorFactory, createShippingCountrySelectorFactory, createShippingStrategySelectorFactory } from '../shipping';\nimport { createSignInEmailSelectorFactory } from '../signin-email';\nimport { createStoreCreditSelectorFactory } from '../store-credit';\nimport { createSubscriptionsSelectorFactory } from '../subscription';\n\nimport { createCheckoutSelectorFactory } from './checkout-selector';\nimport { CheckoutStoreOptions } from './checkout-store';\nimport CheckoutStoreState from './checkout-store-state';\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\nexport type InternalCheckoutSelectorsFactory = (\n    state: CheckoutStoreState,\n    options?: CheckoutStoreOptions\n) => InternalCheckoutSelectors;\n\nexport function createInternalCheckoutSelectorsFactory(): InternalCheckoutSelectorsFactory {\n    const createBillingAddressSelector = createBillingAddressSelectorFactory();\n    const createCartSelector = createCartSelectorFactory();\n    const createCheckoutButtonSelector = createCheckoutButtonSelectorFactory();\n    const createConfigSelector = createConfigSelectorFactory();\n    const createCountrySelector = createCountrySelectorFactory();\n    const createCouponSelector = createCouponSelectorFactory();\n    const createCustomerSelector = createCustomerSelectorFactory();\n    const createCustomerStrategySelector = createCustomerStrategySelectorFactory();\n    const createGiftCertificateSelector = createGiftCertificateSelectorFactory();\n    const createInstrumentSelector = createInstrumentSelectorFactory();\n    const createFormSelector = createFormSelectorFactory();\n    const createPaymentMethodSelector = createPaymentMethodSelectorFactory();\n    const createPaymentStrategySelector = createPaymentStrategySelectorFactory();\n    const createRemoteCheckoutSelector = createRemoteCheckoutSelectorFactory();\n    const createShippingAddressSelector = createShippingAddressSelectorFactory();\n    const createShippingCountrySelector = createShippingCountrySelectorFactory();\n    const createShippingStrategySelector = createShippingStrategySelectorFactory();\n    const createConsignmentSelector = createConsignmentSelectorFactory();\n    const createCheckoutSelector = createCheckoutSelectorFactory();\n    const createOrderSelector = createOrderSelectorFactory();\n    const createPaymentSelector = createPaymentSelectorFactory();\n    const createStoreCreditSelector = createStoreCreditSelectorFactory();\n    const createSubscriptionsSelector = createSubscriptionsSelectorFactory();\n    const createSignInEmailSelector = createSignInEmailSelectorFactory();\n\n    return (state, options = {}) => {\n        const billingAddress = createBillingAddressSelector(state.billingAddress);\n        const cart = createCartSelector(state.cart);\n        const checkoutButton = createCheckoutButtonSelector(state.checkoutButton);\n        const countries = createCountrySelector(state.countries);\n        const coupons = createCouponSelector(state.coupons);\n        const customer = createCustomerSelector(state.customer);\n        const customerStrategies = createCustomerStrategySelector(state.customerStrategies);\n        const form = createFormSelector(state.formFields);\n        const giftCertificates = createGiftCertificateSelector(state.giftCertificates);\n        const instruments = createInstrumentSelector(state.instruments);\n        const paymentMethods = createPaymentMethodSelector(state.paymentMethods);\n        const paymentStrategies = createPaymentStrategySelector(state.paymentStrategies);\n        const remoteCheckout = createRemoteCheckoutSelector(state.remoteCheckout);\n        const shippingAddress = createShippingAddressSelector(state.consignments);\n        const shippingCountries = createShippingCountrySelector(state.shippingCountries);\n        const shippingStrategies = createShippingStrategySelector(state.shippingStrategies);\n        const subscriptions = createSubscriptionsSelector(state.subscriptions);\n        const storeCredit = createStoreCreditSelector(state.storeCredit);\n        const signInEmail = createSignInEmailSelector(state.signInEmail);\n\n        // Compose selectors\n        const consignments = createConsignmentSelector(state.consignments, cart);\n        const checkout = createCheckoutSelector(state.checkout, billingAddress, cart, consignments, coupons, customer, giftCertificates);\n        const order = createOrderSelector(state.order, billingAddress, coupons);\n        const payment = createPaymentSelector(checkout, order);\n        const config = createConfigSelector(state.config, state.formFields);\n\n        const selectors = {\n            billingAddress,\n            cart,\n            checkout,\n            checkoutButton,\n            config,\n            consignments,\n            countries,\n            coupons,\n            customer,\n            customerStrategies,\n            form,\n            giftCertificates,\n            instruments,\n            order,\n            payment,\n            paymentMethods,\n            paymentStrategies,\n            remoteCheckout,\n            shippingAddress,\n            shippingCountries,\n            shippingStrategies,\n            signInEmail,\n            subscriptions,\n            storeCredit,\n        };\n\n        return options.shouldWarnMutation ? createFreezeProxies(selectors) : selectors;\n    };\n}\n\nexport default function createInternalCheckoutSelectors(\n    state: CheckoutStoreState,\n    options?: CheckoutStoreOptions\n): InternalCheckoutSelectors {\n    return createInternalCheckoutSelectorsFactory()(state, options);\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport BillingAddress from './billing-address';\nimport BillingAddressState, { DEFAULT_STATE } from './billing-address-state';\n\nexport default interface BillingAddressSelector {\n    getBillingAddress(): BillingAddress | undefined;\n    getBillingAddressOrThrow(): BillingAddress;\n    getUpdateError(): Error | undefined;\n    getContinueAsGuestError(): Error | undefined;\n    getLoadError(): Error | undefined;\n    isUpdating(): boolean;\n    isContinuingAsGuest(): boolean;\n    isLoading(): boolean;\n}\n\nexport type BillingAddressSelectorFactory = (state: BillingAddressState) => BillingAddressSelector;\n\nexport function createBillingAddressSelectorFactory(): BillingAddressSelectorFactory {\n    const getBillingAddress = createSelector(\n        (state: BillingAddressState) => state.data,\n        data => () => data\n    );\n\n    const getBillingAddressOrThrow = createSelector(\n        getBillingAddress,\n        getBillingAddress => () => {\n            return guard(getBillingAddress(), () => new MissingDataError(MissingDataErrorType.MissingBillingAddress));\n        }\n    );\n\n    const getUpdateError = createSelector(\n        (state: BillingAddressState) => state.errors.updateError,\n        error => () => error\n    );\n\n    const getContinueAsGuestError = createSelector(\n        (state: BillingAddressState) => state.errors.continueAsGuestError,\n        error => () => error\n    );\n\n    const getLoadError = createSelector(\n        (state: BillingAddressState) => state.errors.loadError,\n        error => () => error\n    );\n\n    const isUpdating = createSelector(\n        (state: BillingAddressState) => !!state.statuses.isUpdating,\n        status => () => status\n    );\n\n    const isContinuingAsGuest = createSelector(\n        (state: BillingAddressState) => !!state.statuses.isContinuingAsGuest,\n        status => () => status\n    );\n\n    const isLoading = createSelector(\n        (state: BillingAddressState) => !!state.statuses.isLoading,\n        status => () => status\n    );\n\n    return memoizeOne((\n        state: BillingAddressState = DEFAULT_STATE\n    ): BillingAddressSelector => {\n        return {\n            getBillingAddress: getBillingAddress(state),\n            getBillingAddressOrThrow: getBillingAddressOrThrow(state),\n            getUpdateError: getUpdateError(state),\n            getContinueAsGuestError: getContinueAsGuestError(state),\n            getLoadError: getLoadError(state),\n            isUpdating: isUpdating(state),\n            isContinuingAsGuest: isContinuingAsGuest(state),\n            isLoading: isLoading(state),\n        };\n    });\n}\n","import { memoize, memoizeOne } from '@bigcommerce/memoize';\nimport { find, some, values } from 'lodash';\n\nimport { createSelector } from '../common/selector';\n\nimport CheckoutButtonState, { DEFAULT_STATE } from './checkout-button-state';\nimport { CheckoutButtonMethodType } from './strategies';\n\nexport default interface CheckoutButtonSelector {\n    getState(): CheckoutButtonState;\n    isInitializing(methodId?: CheckoutButtonMethodType): boolean;\n    isInitialized(methodId: CheckoutButtonMethodType, containerId?: string): boolean;\n    isDeinitializing(methodId?: CheckoutButtonMethodType): boolean;\n    getInitializeError(methodId?: CheckoutButtonMethodType): Error | undefined;\n    getDeinitializeError(methodId?: CheckoutButtonMethodType): Error | undefined;\n}\n\nexport type CheckoutButtonSelectorFactory = (state: CheckoutButtonState) => CheckoutButtonSelector;\n\nexport function createCheckoutButtonSelectorFactory(): CheckoutButtonSelectorFactory {\n    const getState = createSelector(\n        (state: CheckoutButtonState) => state,\n        state => () => state\n    );\n\n    const isInitializing = createSelector(\n        (state: CheckoutButtonState) => state.statuses,\n        statuses => memoize((methodId?: CheckoutButtonMethodType) => {\n            if (methodId) {\n                const method = statuses[methodId];\n\n                return (method && method.isInitializing) === true;\n            }\n\n            return some(statuses, { isInitializing: true });\n        })\n    );\n\n    const isInitialized = createSelector(\n        (state: CheckoutButtonState) => state.data,\n        data => memoize((methodId: CheckoutButtonMethodType, containerId?: string) => {\n            const method = data[methodId];\n\n            if (!method) {\n                return false;\n            }\n\n            if (!containerId) {\n                return some(method.initializedContainers, isInitialized => isInitialized === true);\n            }\n\n            return method.initializedContainers[containerId] === true;\n        })\n    );\n\n    const isDeinitializing = createSelector(\n        (state: CheckoutButtonState) => state.statuses,\n        statuses => memoize((methodId?: CheckoutButtonMethodType) => {\n            if (methodId) {\n                const method = statuses[methodId];\n\n                return (method && method.isDeinitializing) === true;\n            }\n\n            return some(statuses, { isDeinitializing: true });\n        })\n    );\n\n    const getInitializeError = createSelector(\n        (state: CheckoutButtonState) => state.errors,\n        errors => memoize((methodId?: CheckoutButtonMethodType) => {\n            const method = methodId ?\n                errors[methodId] :\n                find(values(errors), method => !!(method && method.initializeError));\n\n            return method && method.initializeError;\n        })\n    );\n\n    const getDeinitializeError = createSelector(\n        (state: CheckoutButtonState) => state.errors,\n        errors => memoize((methodId?: CheckoutButtonMethodType) => {\n            const method = methodId ?\n                errors[methodId] :\n                find(values(errors), method => !!(method && method.deinitializeError));\n\n            return method && method.deinitializeError;\n        })\n    );\n\n    return memoizeOne((\n        state: CheckoutButtonState = DEFAULT_STATE\n    ): CheckoutButtonSelector => {\n        return {\n            getState: getState(state),\n            isInitializing: isInitializing(state),\n            isInitialized: isInitialized(state),\n            isDeinitializing: isDeinitializing(state),\n            getInitializeError: getInitializeError(state),\n            getDeinitializeError: getDeinitializeError(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { RequestError } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\n\nimport Coupon from './coupon';\nimport CouponState, { DEFAULT_STATE } from './coupon-state';\n\nexport default interface CouponSelector {\n    getCoupons(): Coupon[] | undefined;\n    getRemoveError(): RequestError | undefined;\n    getApplyError(): RequestError | undefined;\n    isApplying(): boolean;\n    isRemoving(): boolean;\n}\n\nexport type CouponSelectorFactory = (state: CouponState) => CouponSelector;\n\nexport function createCouponSelectorFactory(): CouponSelectorFactory {\n    const getCoupons = createSelector(\n        (state: CouponState) => state.data,\n        data => () => data\n    );\n\n    const getRemoveError = createSelector(\n        (state: CouponState) => state.errors.removeCouponError,\n        error => () => error\n    );\n\n    const getApplyError = createSelector(\n        (state: CouponState) => state.errors.applyCouponError,\n        error => () => error\n    );\n\n    const isApplying = createSelector(\n        (state: CouponState) => !!state.statuses.isApplyingCoupon,\n        status => () => status\n    );\n\n    const isRemoving = createSelector(\n        (state: CouponState) => !!state.statuses.isRemovingCoupon,\n        status => () => status\n    );\n\n    return memoizeOne((\n        state: CouponState = DEFAULT_STATE\n    ): CouponSelector => {\n        return {\n            getCoupons: getCoupons(state),\n            getRemoveError: getRemoveError(state),\n            getApplyError: getApplyError(state),\n            isApplying: isApplying(state),\n            isRemoving: isRemoving(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport Customer from './customer';\nimport CustomerState, { DEFAULT_STATE } from './customer-state';\n\nexport default interface CustomerSelector {\n    getCustomer(): Customer | undefined;\n    getCustomerOrThrow(): Customer;\n    getCreateAccountError(): Error | undefined;\n    isCreatingCustomerAccount(): boolean;\n    getCreateAddressError(): Error | undefined;\n    isCreatingCustomerAddress(): boolean;\n}\n\nexport type CustomerSelectorFactory = (state: CustomerState) => CustomerSelector;\n\nexport function createCustomerSelectorFactory(): CustomerSelectorFactory {\n    const getCustomer = createSelector(\n        (state: CustomerState) => state.data,\n        customer => () => customer\n    );\n\n    const getCustomerOrThrow = createSelector(\n        getCustomer,\n        getCustomer => () => {\n            return guard(getCustomer(), () => new MissingDataError(MissingDataErrorType.MissingCustomer));\n        }\n    );\n\n    const getCreateAccountError = createSelector(\n        (state: CustomerState) => state.errors.createError,\n        error => () => error\n    );\n\n    const isCreatingCustomerAccount = createSelector(\n        (state: CustomerState) => !!state.statuses.isCreating,\n        status => () => status\n    );\n\n    const getCreateAddressError = createSelector(\n        (state: CustomerState) => state.errors.createAddressError,\n        error => () => error\n    );\n\n    const isCreatingCustomerAddress = createSelector(\n        (state: CustomerState) => !!state.statuses.isCreatingAddress,\n        status => () => status\n    );\n\n    return memoizeOne((\n        state: CustomerState = DEFAULT_STATE\n    ): CustomerSelector => {\n        return {\n            getCustomer: getCustomer(state),\n            getCustomerOrThrow: getCustomerOrThrow(state),\n            getCreateAccountError: getCreateAccountError(state),\n            isCreatingCustomerAccount: isCreatingCustomerAccount(state),\n            getCreateAddressError: getCreateAddressError(state),\n            isCreatingCustomerAddress: isCreatingCustomerAddress(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport RemoteCheckoutState, { DEFAULT_STATE, RemoteCheckoutStateData } from './remote-checkout-state';\n\nexport default interface RemoteCheckoutSelector {\n    getCheckout<TMethodId extends keyof RemoteCheckoutStateData>(\n        methodId: TMethodId\n    ): RemoteCheckoutStateData[TMethodId] | undefined;\n}\n\nexport type RemoteCheckoutSelectorFactory = (state: RemoteCheckoutState) => RemoteCheckoutSelector;\n\nexport function createRemoteCheckoutSelectorFactory(): RemoteCheckoutSelectorFactory {\n    const getCheckout = createSelector(\n        (state: RemoteCheckoutState) => state.data,\n        data => <TMethodId extends keyof RemoteCheckoutStateData>(methodId: TMethodId) => {\n            return data[methodId];\n        }\n    );\n\n    return memoizeOne((\n        state: RemoteCheckoutState = DEFAULT_STATE\n    ): RemoteCheckoutSelector => {\n        return {\n            getCheckout: getCheckout(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { Address } from '../address';\nimport { createSelector } from '../common/selector';\n\nimport ConsignmentState, { DEFAULT_STATE } from './consignment-state';\n\nexport default interface ShippingAddressSelector {\n    getShippingAddress(): Address | undefined;\n}\n\nexport type ShippingAddressSelectorFactory = (state: ConsignmentState) => ShippingAddressSelector;\n\nexport function createShippingAddressSelectorFactory(): ShippingAddressSelectorFactory {\n    const getShippingAddress = createSelector(\n        (state: ConsignmentState) => state.data,\n        consignments => () => {\n            if (!consignments || !consignments[0]) {\n                return;\n            }\n\n            return consignments[0].shippingAddress;\n        }\n    );\n\n    return memoizeOne((\n        state: ConsignmentState = DEFAULT_STATE\n    ): ShippingAddressSelector => {\n        return {\n            getShippingAddress: getShippingAddress(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { CheckoutSelector } from '../checkout';\nimport { createSelector } from '../common/selector';\nimport { GatewayOrderPayment, OrderSelector } from '../order';\n\nimport PaymentMethod from './payment-method';\nimport { HOSTED } from './payment-method-types';\nimport { ACKNOWLEDGE, FINALIZE } from './payment-status-types';\n\nexport default interface PaymentSelector {\n    getPaymentId(): { providerId: string; gatewayId?: string } | undefined;\n    getPaymentStatus(): string | undefined;\n    getPaymentToken(): string | undefined;\n    getPaymentRedirectUrl(): string | undefined;\n    isPaymentDataRequired(useStoreCredit?: boolean): boolean;\n    isPaymentDataSubmitted(paymentMethod?: PaymentMethod): boolean;\n}\n\nexport type PaymentSelectorFactory = (\n    checkout: CheckoutSelector,\n    order: OrderSelector\n) => PaymentSelector;\n\ninterface PaymentSelectorDependencies {\n    checkout: CheckoutSelector;\n    order: OrderSelector;\n}\n\nexport function createPaymentSelectorFactory(): PaymentSelectorFactory {\n    const getInternalPayment = createSelector(\n        ({ order }: PaymentSelectorDependencies) => order.getOrderMeta,\n        getOrderMeta => () => {\n            const meta = getOrderMeta();\n\n            return meta && meta.payment;\n        }\n    );\n\n    const getGatewayPayment = createSelector(\n        ({ order }: PaymentSelectorDependencies) => order.getOrder,\n        getOrder => () => {\n            const order = getOrder();\n\n            return find(order && order.payments, ({ providerId }) =>\n                providerId !== 'giftcertificate' && providerId !== 'storecredit'\n            ) as GatewayOrderPayment;\n        }\n    );\n\n    const getHostedPayment = createSelector(\n        ({ checkout }: PaymentSelectorDependencies) => checkout.getCheckout,\n        getCheckout => () => {\n            const checkout = getCheckout();\n\n            return find(checkout && checkout.payments, ({ providerType }) =>\n                providerType === HOSTED\n            );\n        }\n    );\n\n    const getPaymentId = createSelector(\n        getInternalPayment,\n        getHostedPayment,\n        getGatewayPayment,\n        (getInternalPayment, getHostedPayment, getGatewayPayment) => () => {\n            const internalPayment = getInternalPayment();\n\n            if (internalPayment && internalPayment.id) {\n                return {\n                    providerId: internalPayment.id,\n                    gatewayId: internalPayment.gateway,\n                };\n            }\n\n            const payment = getHostedPayment() || getGatewayPayment();\n\n            if (payment && payment.providerId) {\n                return {\n                    providerId: payment.providerId,\n                    gatewayId: payment.gatewayId,\n                };\n            }\n        }\n    );\n\n    const getPaymentStatus = createSelector(\n        getInternalPayment,\n        getHostedPayment,\n        getGatewayPayment,\n        (getInternalPayment, getHostedPayment, getGatewayPayment) => () => {\n            const internalPayment = getInternalPayment();\n\n            if (internalPayment && internalPayment.status) {\n                return internalPayment.status.replace('PAYMENT_STATUS_', '');\n            }\n\n            const payment = getHostedPayment() || getGatewayPayment();\n\n            if (payment) {\n                return payment.detail.step;\n            }\n        }\n    );\n\n    const getPaymentToken = createSelector(\n        ({ order }: PaymentSelectorDependencies) => order.getOrderMeta,\n        getOrderMeta => () => {\n            const meta = getOrderMeta();\n\n            return meta && meta.token;\n        }\n    );\n\n    const getPaymentRedirectUrl = createSelector(\n        getInternalPayment,\n        getInternalPayment => () => {\n            const payment = getInternalPayment();\n\n            return payment && payment.redirectUrl;\n        }\n    );\n\n    const isPaymentDataRequired = createSelector(\n        ({ checkout }: PaymentSelectorDependencies) => checkout.getOutstandingBalance,\n        getOutstandingBalance => (useStoreCredit: boolean = false) => {\n            const grandTotal = getOutstandingBalance(useStoreCredit);\n\n            return grandTotal ? grandTotal > 0 : false;\n        }\n    );\n\n    const isPaymentDataSubmitted = createSelector(\n        getPaymentStatus,\n        getPaymentStatus => (paymentMethod?: PaymentMethod) => {\n            if (paymentMethod && paymentMethod.nonce) {\n                return true;\n            }\n\n            return getPaymentStatus() === ACKNOWLEDGE || getPaymentStatus() === FINALIZE;\n        }\n    );\n\n    return memoizeOne((\n        checkout: CheckoutSelector,\n        order: OrderSelector\n    ): PaymentSelector => {\n        return {\n            getPaymentId: getPaymentId({ checkout, order }),\n            getPaymentStatus: getPaymentStatus({ checkout, order }),\n            getPaymentToken: getPaymentToken({ checkout, order }),\n            getPaymentRedirectUrl: getPaymentRedirectUrl({ checkout, order }),\n            isPaymentDataRequired: isPaymentDataRequired({ checkout, order }),\n            isPaymentDataSubmitted: isPaymentDataSubmitted({ checkout, order }),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport { SignInEmail } from './signin-email';\nimport SignInEmailState, { DEFAULT_STATE } from './signin-email-state';\n\nexport default interface SignInEmailSelector {\n    getEmail(): SignInEmail | undefined;\n    getSendError(): Error | undefined;\n    isSending(): boolean;\n}\n\nexport type SignInEmailSelectorFactory = (state: SignInEmailState) => SignInEmailSelector;\n\nexport function createSignInEmailSelectorFactory(): SignInEmailSelectorFactory {\n    const getEmail = createSelector(\n        (state: SignInEmailState) => state.data,\n        signInEmail => () => signInEmail\n    );\n\n    const getSendError = createSelector(\n        (state: SignInEmailState) => state.errors.sendError,\n        error => () => error\n    );\n\n    const isSending = createSelector(\n        (state: SignInEmailState) => !!state.statuses.isSending,\n        status => () => status\n    );\n\n    return memoizeOne((\n        state: SignInEmailState = DEFAULT_STATE\n    ): SignInEmailSelector => {\n        return {\n            getEmail: getEmail(state),\n            getSendError: getSendError(state),\n            isSending: isSending(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport Cart from './cart';\nimport CartState, { DEFAULT_STATE } from './cart-state';\n\nexport default interface CartSelector {\n    getCart(): Cart | undefined;\n    getCartOrThrow(): Cart;\n    getLoadError(): Error | undefined;\n    isLoading(): boolean;\n}\n\nexport type CartSelectorFactory = (state: CartState) => CartSelector;\n\nexport function createCartSelectorFactory() {\n    const getCart = createSelector(\n        (state: CartState) => state.data,\n        cart => () => cart\n    );\n\n    const getCartOrThrow = createSelector(\n        getCart,\n        getCart => () => {\n          return guard(getCart(), () => new MissingDataError(MissingDataErrorType.MissingCart));\n        }\n    );\n\n    const getLoadError = createSelector(\n        (state: CartState) => state.errors.loadError,\n        error => () => error\n    );\n\n    const isLoading = createSelector(\n        (state: CartState) => !!state.statuses.isLoading,\n        status => () => status\n    );\n\n    return memoizeOne((\n        state: CartState = DEFAULT_STATE\n    ): CartSelector => {\n        return {\n            getCart: getCart(state),\n            getCartOrThrow: getCartOrThrow(state),\n            getLoadError: getLoadError(state),\n            isLoading: isLoading(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { FormFieldsState } from '../form';\n\nimport Config, { ContextConfig, FlashMessage, FlashMessageType, StoreConfig } from './config';\nimport ConfigState, { DEFAULT_STATE } from './config-state';\n\nexport default interface ConfigSelector {\n    getConfig(): Config | undefined;\n    getFlashMessages(type?: FlashMessageType): FlashMessage[] | undefined;\n    getStoreConfig(): StoreConfig | undefined;\n    getStoreConfigOrThrow(): StoreConfig;\n    getContextConfig(): ContextConfig | undefined;\n    getExternalSource(): string | undefined;\n    getVariantIdentificationToken(): string | undefined;\n    getLoadError(): Error | undefined;\n    isLoading(): boolean;\n}\n\nexport type ConfigSelectorFactory = (\n    state: ConfigState,\n    formState: FormFieldsState\n) => ConfigSelector;\n\ninterface ConfigSelectorDependencies {\n    formState: FormFieldsState;\n}\n\nexport function createConfigSelectorFactory(): ConfigSelectorFactory {\n\n    const getConfig = createSelector(\n        (state: ConfigState) => state.data,\n        data => () => data\n    );\n\n    const getFlashMessages = createSelector(\n        (state: ConfigState) => state.data,\n        data => (filterType?: FlashMessageType) => {\n            if (!data) {\n                return;\n            }\n\n            const { flashMessages } = data.context;\n\n            if (!flashMessages) {\n                return;\n            }\n\n            return filterType !== undefined ?\n                flashMessages.filter(({ type }) => filterType === type) :\n                flashMessages;\n        }\n    );\n\n    const getStoreConfig = createSelector(\n        (state: ConfigState) => state.data,\n        (_: ConfigState, { formState }: ConfigSelectorDependencies) => formState && formState.data,\n        (data, formFields) => () => data && formFields ? ({\n            ...data.storeConfig,\n            formFields,\n        }) : undefined\n    );\n\n    const getStoreConfigOrThrow = createSelector(\n        getStoreConfig,\n        getStoreConfig => () => {\n          return guard(getStoreConfig(), () => new MissingDataError(MissingDataErrorType.MissingCheckoutConfig));\n        }\n    );\n\n    const getContextConfig = createSelector(\n        (state: ConfigState) => state.data && state.data.context,\n        data => () => data\n    );\n\n    const getExternalSource = createSelector(\n        (state: ConfigState) => state.meta && state.meta.externalSource,\n        data => () => data\n    );\n\n    const getVariantIdentificationToken = createSelector(\n        (state: ConfigState) => state.meta && state.meta.variantIdentificationToken,\n        data => () => data\n    );\n\n    const getLoadError = createSelector(\n        (state: ConfigState) => state.errors.loadError,\n        error => () => error\n    );\n\n    const isLoading = createSelector(\n        (state: ConfigState) => !!state.statuses.isLoading,\n        status => () => status\n    );\n\n    return memoizeOne((\n        state: ConfigState = DEFAULT_STATE,\n        formState: FormFieldsState\n    ): ConfigSelector => {\n        return {\n            getConfig: getConfig(state),\n            getFlashMessages: getFlashMessages(state),\n            getStoreConfig: getStoreConfig(state, { formState }),\n            getStoreConfigOrThrow: getStoreConfigOrThrow(state, { formState }),\n            getContextConfig: getContextConfig(state),\n            getExternalSource: getExternalSource(state),\n            getVariantIdentificationToken: getVariantIdentificationToken(state),\n            getLoadError: getLoadError(state),\n            isLoading: isLoading(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport Country from './country';\nimport CountryState, { DEFAULT_STATE } from './country-state';\n\nexport default interface CountrySelector {\n    getCountries(): Country[] | undefined;\n    getLoadError(): Error | undefined;\n    isLoading(): boolean;\n}\n\nexport type CountrySelectorFactory = (state: CountryState) => CountrySelector;\n\nexport function createCountrySelectorFactory(): CountrySelectorFactory {\n    const getCountries = createSelector(\n        (state: CountryState) => state.data,\n        countries => () => countries\n    );\n\n    const getLoadError = createSelector(\n        (state: CountryState) => state.errors.loadError,\n        error => () => error\n    );\n\n    const isLoading = createSelector(\n        (state: CountryState) => !!state.statuses.isLoading,\n        status => () => status\n    );\n\n    return memoizeOne((\n        state: CountryState = DEFAULT_STATE\n    ): CountrySelector => {\n        return {\n            getCountries: getCountries(state),\n            getLoadError: getLoadError(state),\n            isLoading: isLoading(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport CustomerStrategyState, { DEFAULT_STATE } from './customer-strategy-state';\n\nexport default interface CustomerStrategySelector {\n    getSignInError(methodId?: string): Error | undefined;\n    getSignOutError(methodId?: string): Error | undefined;\n    getInitializeError(methodId?: string): Error | undefined;\n    getWidgetInteractionError(methodId?: string): Error | undefined;\n    isSigningIn(methodId?: string): boolean;\n    isSigningOut(methodId?: string): boolean;\n    isInitializing(methodId?: string): boolean;\n    isInitialized(methodId: string): boolean;\n    isWidgetInteracting(methodId?: string): boolean;\n}\n\nexport type CustomerStrategySelectorFactory = (state: CustomerStrategyState) => CustomerStrategySelector;\n\nexport function createCustomerStrategySelectorFactory(): CustomerStrategySelectorFactory {\n    const getSignInError = createSelector(\n        (state: CustomerStrategyState) => state.errors.signInMethodId,\n        (state: CustomerStrategyState) => state.errors.signInError,\n        (signInMethodId, signInError) => (methodId?: string) => {\n            if (methodId && signInMethodId !== methodId) {\n                return;\n            }\n\n            return signInError;\n        }\n    );\n\n    const getSignOutError = createSelector(\n        (state: CustomerStrategyState) => state.errors.signOutMethodId,\n        (state: CustomerStrategyState) => state.errors.signOutError,\n        (signOutMethodId, signOutError) => (methodId?: string) => {\n            if (methodId && signOutMethodId !== methodId) {\n                return;\n            }\n\n            return signOutError;\n        }\n    );\n\n    const getInitializeError = createSelector(\n        (state: CustomerStrategyState) => state.errors.initializeMethodId,\n        (state: CustomerStrategyState) => state.errors.initializeError,\n        (initializeMethodId, initializeError) => (methodId?: string) => {\n            if (methodId && initializeMethodId !== methodId) {\n                return;\n            }\n\n            return initializeError;\n        }\n    );\n\n    const getWidgetInteractionError = createSelector(\n        (state: CustomerStrategyState) => state.errors.widgetInteractionMethodId,\n        (state: CustomerStrategyState) => state.errors.widgetInteractionError,\n        (widgetInteractionMethodId, widgetInteractionError) => (methodId?: string) => {\n            if (methodId && widgetInteractionMethodId !== methodId) {\n                return;\n            }\n\n            return widgetInteractionError;\n        }\n    );\n\n    const isSigningIn = createSelector(\n        (state: CustomerStrategyState) => state.statuses.signInMethodId,\n        (state: CustomerStrategyState) => state.statuses.isSigningIn,\n        (signInMethodId, isSigningIn) => (methodId?: string) => {\n            if (methodId && signInMethodId !== methodId) {\n                return false;\n            }\n\n            return !!isSigningIn;\n        }\n    );\n\n    const isSigningOut = createSelector(\n        (state: CustomerStrategyState) => state.statuses.signOutMethodId,\n        (state: CustomerStrategyState) => state.statuses.isSigningOut,\n        (signOutMethodId, isSigningOut) => (methodId?: string) => {\n            if (methodId && signOutMethodId !== methodId) {\n                return false;\n            }\n\n            return !!isSigningOut;\n        }\n    );\n\n    const isInitializing = createSelector(\n        (state: CustomerStrategyState) => state.statuses.initializeMethodId,\n        (state: CustomerStrategyState) => state.statuses.isInitializing,\n        (initializeMethodId, isInitializing) => (methodId?: string) => {\n            if (methodId && initializeMethodId !== methodId) {\n                return false;\n            }\n\n            return !!isInitializing;\n        }\n    );\n\n    const isInitialized = createSelector(\n        (state: CustomerStrategyState) => state.data,\n        data => (methodId: string) => {\n            return !!(\n                data[methodId] &&\n                data[methodId].isInitialized\n            );\n        }\n    );\n\n    const isWidgetInteracting = createSelector(\n        (state: CustomerStrategyState) => state.statuses.widgetInteractionMethodId,\n        (state: CustomerStrategyState) => state.statuses.isWidgetInteracting,\n        (widgetInteractionMethodId, isWidgetInteracting) => (methodId?: string) => {\n            if (methodId && widgetInteractionMethodId !== methodId) {\n                return false;\n            }\n\n            return !!isWidgetInteracting;\n        }\n    );\n\n    return memoizeOne((\n        state: CustomerStrategyState = DEFAULT_STATE\n    ): CustomerStrategySelector => {\n        return {\n            getSignInError: getSignInError(state),\n            getSignOutError: getSignOutError(state),\n            getInitializeError: getInitializeError(state),\n            getWidgetInteractionError: getWidgetInteractionError(state),\n            isSigningIn: isSigningIn(state),\n            isSigningOut: isSigningOut(state),\n            isInitializing: isInitializing(state),\n            isInitialized: isInitialized(state),\n            isWidgetInteracting: isWidgetInteracting(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { StorefrontErrorResponseBody } from '../common/error';\nimport { RequestError } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\n\nimport GiftCertificate from './gift-certificate';\nimport GiftCertificateState, { DEFAULT_STATE } from './gift-certificate-state';\n\nexport default interface GiftCertificateSelector {\n    getGiftCertificates(): GiftCertificate[] | undefined;\n    getRemoveError(): RequestError<StorefrontErrorResponseBody> | undefined;\n    getApplyError(): RequestError<StorefrontErrorResponseBody> | undefined;\n    isApplying(): boolean;\n    isRemoving(): boolean;\n}\n\nexport type GiftCertificateSelectorFactory = (state: GiftCertificateState) => GiftCertificateSelector;\n\nexport function createGiftCertificateSelectorFactory(): GiftCertificateSelectorFactory {\n    const getGiftCertificates = createSelector(\n        (state: GiftCertificateState) => state.data,\n        data => () => data\n    );\n\n    const getRemoveError = createSelector(\n        (state: GiftCertificateState) => state.errors.removeGiftCertificateError,\n        error => () => error\n    );\n\n    const getApplyError = createSelector(\n        (state: GiftCertificateState) => state.errors.applyGiftCertificateError,\n        error => () => error\n    );\n\n    const isApplying = createSelector(\n        (state: GiftCertificateState) => !!state.statuses.isApplyingGiftCertificate,\n        status => () => status\n    );\n\n    const isRemoving = createSelector(\n        (state: GiftCertificateState) => !!state.statuses.isRemovingGiftCertificate,\n        status => () => status\n    );\n\n    return memoizeOne((\n        state: GiftCertificateState = DEFAULT_STATE\n    ): GiftCertificateSelector => {\n        return {\n            getGiftCertificates: getGiftCertificates(state),\n            getRemoveError: getRemoveError(state),\n            getApplyError: getApplyError(state),\n            isApplying: isApplying(state),\n            isRemoving: isRemoving(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { filter, flatMap, isMatch, values } from 'lodash';\n\nimport { createSelector } from '../../common/selector';\nimport PaymentMethod from '../payment-method';\n\nimport PaymentInstrument, { CardInstrument } from './instrument';\nimport InstrumentState, { DEFAULT_STATE, InstrumentMeta } from './instrument-state';\nimport supportedInstruments from './supported-payment-instruments';\n\nexport default interface InstrumentSelector {\n    getCardInstrument(instrumentId: string): CardInstrument | undefined;\n    getInstruments(): PaymentInstrument[] | undefined;\n    getInstrumentsByPaymentMethod(paymentMethod: PaymentMethod): PaymentInstrument[] | undefined;\n    getInstrumentsMeta(): InstrumentMeta | undefined;\n    getLoadError(): Error | undefined;\n    getDeleteError(instrumentId?: string): Error | undefined;\n    isLoading(): boolean;\n    isDeleting(instrumentId?: string): boolean;\n}\n\nexport type InstrumentSelectorFactory = (state: InstrumentState) => InstrumentSelector;\n\nexport function createInstrumentSelectorFactory(): InstrumentSelectorFactory {\n    const getInstrumentsByPaymentMethod = createSelector(\n        (state: InstrumentState) => state.data,\n        instruments => (paymentMethod: PaymentMethod) => {\n            if (!instruments) {\n                return;\n            }\n\n            const paymentMethodKey = paymentMethod.gateway ? `${paymentMethod.gateway}.${paymentMethod.id}` : paymentMethod.id;\n\n            const currentMethod = supportedInstruments[paymentMethodKey];\n\n            if (!currentMethod) {\n                return [];\n            }\n\n            return filter<PaymentInstrument>(instruments, currentMethod);\n        }\n    );\n\n    const getCardInstrument = createSelector(\n        (state: InstrumentState) => state.data,\n        (instruments = []) => (instrumentId: string) => {\n            const cards = values(supportedInstruments);\n\n            return instruments.find((instrument): instrument is CardInstrument =>\n                instrument.bigpayToken === instrumentId &&\n                instrument.type === 'card' &&\n                cards.some(card => isMatch(instrument, card))\n            );\n        }\n    );\n\n    const getInstruments = createSelector(\n        (state: InstrumentState) => state.data,\n        instruments => () => {\n            if (!instruments) {\n                return;\n            }\n\n            const allSupportedInstruments = flatMap(supportedInstruments, supportedProvider =>\n                filter(instruments, (instrument: PaymentInstrument): instrument is PaymentInstrument => {\n                    return isMatch(instrument, supportedProvider);\n                })\n            );\n\n            return allSupportedInstruments;\n        }\n    );\n\n    const getInstrumentsMeta = createSelector(\n        (state: InstrumentState) => state.meta,\n        meta => () => meta\n    );\n\n    const getLoadError = createSelector(\n        (state: InstrumentState) => state.errors.loadError,\n        loadError => () => loadError\n    );\n\n    const getDeleteError = createSelector(\n        (state: InstrumentState) => state.errors.failedInstrument,\n        (state: InstrumentState) => state.errors.deleteError,\n        (failedInstrument, deleteError) => (instrumentId?: string) => {\n            if (instrumentId && failedInstrument !== instrumentId) {\n                return;\n            }\n\n            return deleteError;\n        }\n    );\n\n    const isLoading = createSelector(\n        (state: InstrumentState) => state.statuses.isLoading,\n        isLoading => () => !!isLoading\n    );\n\n    const isDeleting = createSelector(\n        (state: InstrumentState) => state.statuses.deletingInstrument,\n        (state: InstrumentState) => state.statuses.isDeleting,\n        (deletingInstrument, isDeleting) => (instrumentId?: string) => {\n            if (instrumentId && deletingInstrument !== instrumentId) {\n                return false;\n            }\n\n            return !!isDeleting;\n        }\n    );\n\n    return memoizeOne((\n        state: InstrumentState = DEFAULT_STATE\n    ): InstrumentSelector => {\n        return {\n            getCardInstrument: getCardInstrument(state),\n            getInstruments: getInstruments(state),\n            getInstrumentsByPaymentMethod: getInstrumentsByPaymentMethod(state),\n            getInstrumentsMeta: getInstrumentsMeta(state),\n            getLoadError: getLoadError(state),\n            getDeleteError: getDeleteError(state),\n            isLoading: isLoading(state),\n            isDeleting: isDeleting(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { createSelector } from '../common/selector';\nimport { Country } from '../geography';\n\nimport FormField from './form-field';\nimport FormFieldsState, { DEFAULT_STATE } from './form-fields-state';\n\nexport default interface FormSelector {\n    getShippingAddressFields(countries: Country[] | undefined, countryCode: string): FormField[];\n    getBillingAddressFields(countries: Country[] | undefined, countryCode: string): FormField[];\n    getCustomerAccountFields(): FormField[];\n    getLoadError(): Error | undefined;\n    isLoading(): boolean;\n}\n\nexport type FormSelectorFactory = (state: FormFieldsState) => FormSelector;\n\nexport function createFormSelectorFactory(): FormSelectorFactory {\n    const getShippingAddressFields = createSelector(\n        (state: FormFieldsState) => state.data,\n        formFields => (countries: Country[] = [], countryCode: string) => {\n            const selectedCountry = find(countries, { code: countryCode });\n            const fields = formFields ? formFields.shippingAddress : [];\n\n            return fields.map((field: any) => processField(field, countries, selectedCountry));\n        }\n    );\n\n    const getBillingAddressFields = createSelector(\n        (state: FormFieldsState) => state.data,\n        formFields => (countries: Country[] = [], countryCode: string) => {\n            const selectedCountry = find(countries, { code: countryCode });\n            const fields = formFields ? formFields.billingAddress : [];\n\n            return fields.map((field: any) => processField(field, countries, selectedCountry));\n        }\n    );\n\n    const getCustomerAccountFields = createSelector(\n        (state: FormFieldsState) => state.data,\n        formFields => () => formFields ? formFields.customerAccount : []\n    );\n\n    const getLoadError = createSelector(\n        (state: FormFieldsState) => state.errors.loadError,\n        error => () => error\n    );\n\n    const isLoading = createSelector(\n        (state: FormFieldsState) => !!state.statuses.isLoading,\n        status => () => status\n    );\n\n    function processField(field: FormField, countries: Country[], selectedCountry?: Country): FormField {\n        if (field.name === 'countryCode') {\n            return processCountry(field, countries, selectedCountry);\n        }\n\n        if (field.name === 'stateOrProvince') {\n            return processProvince(field, selectedCountry);\n        }\n\n        if (field.name === 'postalCode') {\n            return processsPostCode(field, selectedCountry);\n        }\n\n        return field;\n    }\n\n    function processCountry(field: FormField, countries: Country[] = [], country?: Country): FormField {\n        if (!countries.length) {\n            return field;\n        }\n\n        const { code = '' } = country || {};\n        const items = countries.map(({ code, name }: any) => ({\n            value: code,\n            label: name,\n        }));\n\n        return {\n            ...field,\n            options: { items },\n            default: code,\n            type: 'array',\n            fieldType: 'dropdown',\n            itemtype: 'string',\n        };\n    }\n\n    function processProvince(field: FormField, country?: Country): FormField {\n        const { subdivisions = [], requiresState } = country || {};\n\n        if (!subdivisions.length) {\n            return {\n                ...field,\n                required: requiresState == null ? false : requiresState,\n            };\n        }\n\n        const items = subdivisions.map(({ code, name }: any) => ({\n            value: code,\n            label: name,\n        }));\n\n        return {\n            ...field,\n            name: 'stateOrProvinceCode',\n            options: { items },\n            required: requiresState == null ? true : requiresState,\n            type: 'array',\n            fieldType: 'dropdown',\n            itemtype: 'string',\n        };\n    }\n\n    function processsPostCode(field: FormField, country?: Country): FormField {\n        const { hasPostalCodes = [] } = country || {};\n\n        if (hasPostalCodes === undefined) {\n            return field;\n        }\n\n        return { ...field, required: Boolean(hasPostalCodes) };\n    }\n\n    return memoizeOne((\n        state: FormFieldsState = DEFAULT_STATE\n    ): FormSelector => {\n        return {\n            getShippingAddressFields: getShippingAddressFields(state),\n            getBillingAddressFields: getBillingAddressFields(state),\n            getCustomerAccountFields: getCustomerAccountFields(state),\n            getLoadError: getLoadError(state),\n            isLoading: isLoading(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport PaymentMethod from './payment-method';\nimport PaymentMethodMeta from './payment-method-meta';\nimport PaymentMethodState, { DEFAULT_STATE } from './payment-method-state';\n\nexport default interface PaymentMethodSelector {\n    getPaymentMethods(): PaymentMethod[] | undefined;\n    getPaymentMethodsMeta(): PaymentMethodMeta | undefined;\n    getPaymentMethod(methodId: string, gatewayId?: string): PaymentMethod | undefined;\n    getPaymentMethodOrThrow(methodId: string, gatewayId ?: string): PaymentMethod;\n    getLoadError(): Error | undefined;\n    getLoadMethodError(methodId?: string): Error | undefined;\n    isLoading(): boolean;\n    isLoadingMethod(methodId?: string): boolean;\n}\n\nexport type PaymentMethodSelectorFactory = (state: PaymentMethodState) => PaymentMethodSelector;\n\nexport function createPaymentMethodSelectorFactory(): PaymentMethodSelectorFactory {\n    const getPaymentMethods = createSelector(\n        (state: PaymentMethodState) => state.data,\n        paymentMethods => () => paymentMethods\n    );\n\n    const getPaymentMethodsMeta = createSelector(\n        (state: PaymentMethodState) => state.meta,\n        meta => () => meta\n    );\n\n    const getPaymentMethod = createSelector(\n        (state: PaymentMethodState) => state.data,\n        paymentMethods => (methodId: string, gatewayId?: string) => {\n            return gatewayId ?\n                find(paymentMethods, { id: methodId, gateway: gatewayId }) :\n                find(paymentMethods, { id: methodId });\n        }\n    );\n\n    const getPaymentMethodOrThrow = createSelector(\n        getPaymentMethod,\n        getPaymentMethod => (methodId: string, gatewayId?: string) => {\n            return guard(getPaymentMethod(methodId, gatewayId), () => new MissingDataError(MissingDataErrorType.MissingPaymentMethod));\n        }\n    );\n\n    const getLoadError = createSelector(\n        (state: PaymentMethodState) => state.errors.loadError,\n        loadError => () => loadError\n    );\n\n    const getLoadMethodError = createSelector(\n        (state: PaymentMethodState) => state.errors.loadMethodId,\n        (state: PaymentMethodState) => state.errors.loadMethodError,\n        (loadMethodId, loadMethodError) => (methodId?: string) => {\n            if (methodId && loadMethodId !== methodId) {\n                return;\n            }\n\n            return loadMethodError;\n        }\n    );\n\n    const isLoading = createSelector(\n        (state: PaymentMethodState) => state.statuses.isLoading,\n        isLoading => () => !!isLoading\n    );\n\n    const isLoadingMethod = createSelector(\n        (state: PaymentMethodState) => state.statuses.loadMethodId,\n        (state: PaymentMethodState) => state.statuses.isLoadingMethod,\n        (loadMethodId, isLoadingMethod) => (methodId?: string) => {\n            if (methodId && loadMethodId !== methodId) {\n                return false;\n            }\n\n            return !!isLoadingMethod;\n        }\n    );\n\n    return memoizeOne((\n        state: PaymentMethodState = DEFAULT_STATE\n    ): PaymentMethodSelector => {\n        return {\n            getPaymentMethods: getPaymentMethods(state),\n            getPaymentMethodsMeta: getPaymentMethodsMeta(state),\n            getPaymentMethod: getPaymentMethod(state),\n            getPaymentMethodOrThrow: getPaymentMethodOrThrow(state),\n            getLoadError: getLoadError(state),\n            getLoadMethodError: getLoadMethodError(state),\n            isLoading: isLoading(state),\n            isLoadingMethod: isLoadingMethod(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport PaymentStrategyState, { DEFAULT_STATE } from './payment-strategy-state';\n\nexport default interface PaymentStrategySelector {\n    getInitializeError(methodId?: string): Error | undefined;\n    getExecuteError(methodId?: string): Error | undefined;\n    getFinalizeError(methodId?: string): Error | undefined;\n    getWidgetInteractingError(methodId?: string): Error | undefined;\n    isInitializing(methodId?: string): boolean;\n    isInitialized(methodId: string): boolean;\n    isExecuting(methodId?: string): boolean;\n    isFinalizing(methodId?: string): boolean;\n    isWidgetInteracting(methodId?: string): boolean;\n}\n\nexport type PaymentStrategySelectorFactory = (state: PaymentStrategyState) => PaymentStrategySelector;\n\nexport function createPaymentStrategySelectorFactory(): PaymentStrategySelectorFactory {\n    const getInitializeError = createSelector(\n        (state: PaymentStrategyState) => state.errors.initializeMethodId,\n        (state: PaymentStrategyState) => state.errors.initializeError,\n        (initializeMethodId, initializeError) => (methodId?: string) => {\n            if (methodId && initializeMethodId !== methodId) {\n                return;\n            }\n\n            return initializeError;\n        }\n    );\n\n    const getExecuteError = createSelector(\n        (state: PaymentStrategyState) => state.errors.executeMethodId,\n        (state: PaymentStrategyState) => state.errors.executeError,\n        (executeMethodId, executeError) => (methodId?: string) => {\n            if (methodId && executeMethodId !== methodId) {\n                return;\n            }\n\n            return executeError;\n        }\n    );\n\n    const getFinalizeError = createSelector(\n        (state: PaymentStrategyState) => state.errors.finalizeMethodId,\n        (state: PaymentStrategyState) => state.errors.finalizeError,\n        (finalizeMethodId, finalizeError) => (methodId?: string) => {\n            if (methodId && finalizeMethodId !== methodId) {\n                return;\n            }\n\n            return finalizeError;\n        }\n    );\n\n    const getWidgetInteractingError = createSelector(\n        (state: PaymentStrategyState) => state.errors.widgetInteractionMethodId,\n        (state: PaymentStrategyState) => state.errors.widgetInteractionError,\n        (widgetInteractionMethodId, widgetInteractionError) => (methodId?: string) => {\n            if (methodId && widgetInteractionMethodId !== methodId) {\n                return;\n            }\n\n            return widgetInteractionError;\n        }\n    );\n\n    const isInitializing = createSelector(\n        (state: PaymentStrategyState) => state.statuses.initializeMethodId,\n        (state: PaymentStrategyState) => state.statuses.isInitializing,\n        (initializeMethodId, isInitializing) => (methodId?: string) => {\n            if (methodId && initializeMethodId !== methodId) {\n                return false;\n            }\n\n            return !!isInitializing;\n        }\n    );\n\n    const isInitialized = createSelector(\n        (state: PaymentStrategyState) => state.data,\n        data => (methodId: string) => {\n            return !!(\n                data[methodId] &&\n                data[methodId].isInitialized\n            );\n        }\n    );\n\n    const isExecuting = createSelector(\n        (state: PaymentStrategyState) => state.statuses.executeMethodId,\n        (state: PaymentStrategyState) => state.statuses.isExecuting,\n        (executeMethodId, isExecuting) => (methodId?: string) => {\n            if (methodId && executeMethodId !== methodId) {\n                return false;\n            }\n\n            return !!isExecuting;\n        }\n    );\n\n    const isFinalizing = createSelector(\n        (state: PaymentStrategyState) => state.statuses.finalizeMethodId,\n        (state: PaymentStrategyState) => state.statuses.isFinalizing,\n        (finalizeMethodId, isFinalizing) => (methodId?: string) => {\n            if (methodId && finalizeMethodId !== methodId) {\n                return false;\n            }\n\n            return !!isFinalizing;\n        }\n    );\n\n    const isWidgetInteracting = createSelector(\n        (state: PaymentStrategyState) => state.statuses.widgetInteractionMethodId,\n        (state: PaymentStrategyState) => state.statuses.isWidgetInteracting,\n        (widgetInteractionMethodId, isWidgetInteracting) => (methodId?: string) => {\n            if (methodId && widgetInteractionMethodId !== methodId) {\n                return false;\n            }\n\n            return !!isWidgetInteracting;\n        }\n    );\n\n    return memoizeOne((\n        state: PaymentStrategyState = DEFAULT_STATE\n    ): PaymentStrategySelector => {\n        return {\n            getInitializeError: getInitializeError(state),\n            getExecuteError: getExecuteError(state),\n            getFinalizeError: getFinalizeError(state),\n            getWidgetInteractingError: getWidgetInteractingError(state),\n            isInitializing: isInitializing(state),\n            isInitialized: isInitialized(state),\n            isExecuting: isExecuting(state),\n            isFinalizing: isFinalizing(state),\n            isWidgetInteracting: isWidgetInteracting(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\nimport { Country } from '../geography';\n\nimport ShippingCountryState, { DEFAULT_STATE } from './shipping-country-state';\n\nexport default interface ShippingCountrySelector {\n    getShippingCountries(): Country[] | undefined;\n    getLoadError(): Error | undefined;\n    isLoading(): boolean;\n}\n\nexport type ShippingCountrySelectorFactory = (state: ShippingCountryState) => ShippingCountrySelector;\n\nexport function createShippingCountrySelectorFactory(): ShippingCountrySelectorFactory {\n    const getShippingCountries = createSelector(\n        (state: ShippingCountryState) => state.data,\n        data => () => data\n    );\n\n    const getLoadError = createSelector(\n        (state: ShippingCountryState) => state.errors.loadError,\n        error => () => error\n    );\n\n    const isLoading = createSelector(\n        (state: ShippingCountryState) => state.statuses.isLoading,\n        status => () => !!status\n    );\n\n    return memoizeOne((\n        state: ShippingCountryState = DEFAULT_STATE\n    ): ShippingCountrySelector => {\n        return {\n            getShippingCountries: getShippingCountries(state),\n            getLoadError: getLoadError(state),\n            isLoading: isLoading(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport ShippingStrategyState, { DEFAULT_STATE } from './shipping-strategy-state';\n\nexport default interface ShippingStrategySelector {\n    getUpdateAddressError(methodId?: string): Error | undefined;\n    getSelectOptionError(methodId?: string): Error | undefined;\n    getInitializeError(methodId?: string): Error | undefined;\n    getWidgetInteractionError(methodId?: string): Error | undefined;\n    isUpdatingAddress(methodId?: string): boolean;\n    isSelectingOption(methodId?: string): boolean;\n    isInitializing(methodId?: string): boolean;\n    isInitialized(methodId: string): boolean;\n    isWidgetInteracting(methodId?: string): boolean;\n}\n\nexport type ShippingStrategySelectorFactory = (state: ShippingStrategyState) => ShippingStrategySelector;\n\nexport function createShippingStrategySelectorFactory(): ShippingStrategySelectorFactory {\n    const getUpdateAddressError = createSelector(\n        (state: ShippingStrategyState) => state.errors.updateAddressMethodId,\n        (state: ShippingStrategyState) => state.errors.updateAddressError,\n        (updateAddressMethodId, updateAddressError) => (methodId?: string) => {\n            if (methodId && updateAddressMethodId !== methodId) {\n                return;\n            }\n\n            return updateAddressError;\n        }\n    );\n\n    const getSelectOptionError = createSelector(\n        (state: ShippingStrategyState) => state.errors.selectOptionMethodId,\n        (state: ShippingStrategyState) => state.errors.selectOptionError,\n        (selectOptionMethodId, selectOptionError) => (methodId?: string) => {\n            if (methodId && selectOptionMethodId !== methodId) {\n                return;\n            }\n\n            return selectOptionError;\n        }\n    );\n\n    const getInitializeError = createSelector(\n        (state: ShippingStrategyState) => state.errors.initializeMethodId,\n        (state: ShippingStrategyState) => state.errors.initializeError,\n        (initializeMethodId, initializeError) => (methodId?: string) => {\n            if (methodId && initializeMethodId !== methodId) {\n                return;\n            }\n\n            return initializeError;\n        }\n    );\n\n    const getWidgetInteractionError = createSelector(\n        (state: ShippingStrategyState) => state.errors.widgetInteractionMethodId,\n        (state: ShippingStrategyState) => state.errors.widgetInteractionError,\n        (widgetInteractionMethodId, widgetInteractionError) => (methodId?: string) => {\n            if (methodId && widgetInteractionMethodId !== methodId) {\n                return;\n            }\n\n            return widgetInteractionError;\n        }\n    );\n\n    const isUpdatingAddress = createSelector(\n        (state: ShippingStrategyState) => state.statuses.updateAddressMethodId,\n        (state: ShippingStrategyState) => state.statuses.isUpdatingAddress,\n        (updateAddressMethodId, isUpdatingAddress) => (methodId?: string) => {\n            if (methodId && updateAddressMethodId !== methodId) {\n                return false;\n            }\n\n            return !!isUpdatingAddress;\n        }\n    );\n\n    const isSelectingOption = createSelector(\n        (state: ShippingStrategyState) => state.statuses.selectOptionMethodId,\n        (state: ShippingStrategyState) => state.statuses.isSelectingOption,\n        (selectOptionMethodId, isSelectingOption) => (methodId?: string) => {\n            if (methodId && selectOptionMethodId !== methodId) {\n                return false;\n            }\n\n            return !!isSelectingOption;\n        }\n    );\n\n    const isInitializing = createSelector(\n        (state: ShippingStrategyState) => state.statuses.initializeMethodId,\n        (state: ShippingStrategyState) => state.statuses.isInitializing,\n        (initializeMethodId, isInitializing) => (methodId?: string) => {\n            if (methodId && initializeMethodId !== methodId) {\n                return false;\n            }\n\n            return !!isInitializing;\n        }\n    );\n\n    const isInitialized = createSelector(\n        (state: ShippingStrategyState) => state.data,\n        data => (methodId: string) => {\n            return !!(\n                data[methodId] &&\n                data[methodId].isInitialized\n            );\n        }\n    );\n\n    const isWidgetInteracting = createSelector(\n        (state: ShippingStrategyState) => state.statuses.widgetInteractionMethodId,\n        (state: ShippingStrategyState) => state.statuses.isWidgetInteracting,\n        (widgetInteractionMethodId, isWidgetInteracting) => (methodId?: string) => {\n            if (methodId && widgetInteractionMethodId !== methodId) {\n                return false;\n            }\n\n            return !!isWidgetInteracting;\n        }\n    );\n\n    return memoizeOne((\n        state: ShippingStrategyState = DEFAULT_STATE\n    ): ShippingStrategySelector => {\n        return {\n            getUpdateAddressError: getUpdateAddressError(state),\n            getSelectOptionError: getSelectOptionError(state),\n            getInitializeError: getInitializeError(state),\n            getWidgetInteractionError: getWidgetInteractionError(state),\n            isUpdatingAddress: isUpdatingAddress(state),\n            isSelectingOption: isSelectingOption(state),\n            isInitializing: isInitializing(state),\n            isInitialized: isInitialized(state),\n            isWidgetInteracting: isWidgetInteracting(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { isAddressEqual, AddressRequestBody } from '../address';\nimport { CartSelector, PhysicalItem } from '../cart';\nimport { createSelector } from '../common/selector';\n\nimport Consignment from './consignment';\nimport ConsignmentState, { DEFAULT_STATE } from './consignment-state';\nimport ShippingOption from './shipping-option';\n\nexport default interface ConsignmentSelector {\n    getConsignments(): Consignment[] | undefined;\n    getConsignmentById(id: string): Consignment | undefined;\n    getConsignmentByAddress(address: AddressRequestBody): Consignment | undefined;\n    getShippingOption(): ShippingOption | undefined;\n    getLoadError(): Error | undefined;\n    getCreateError(): Error | undefined;\n    getLoadShippingOptionsError(): Error | undefined;\n    getUnassignedItems(): PhysicalItem[];\n    getUpdateError(consignmentId?: string): Error | undefined;\n    getDeleteError(consignmentId?: string): Error | undefined;\n    getItemAssignmentError(address: AddressRequestBody): Error | undefined;\n    getUpdateShippingOptionError(consignmentId?: string): Error | undefined;\n    isLoading(): boolean;\n    isLoadingShippingOptions(): boolean;\n    isCreating(): boolean;\n    isUpdating(consignmentId?: string): boolean;\n    isDeleting(consignmentId?: string): boolean;\n    isAssigningItems(address: AddressRequestBody): boolean;\n    isUpdatingShippingOption(consignmentId?: string): boolean;\n}\n\nexport type ConsignmentSelectorFactory = (\n    state: ConsignmentState,\n    cart: CartSelector\n) => ConsignmentSelector;\n\ninterface ConsignmentSelectorDependencies {\n    cart: CartSelector;\n}\n\nexport function createConsignmentSelectorFactory(): ConsignmentSelectorFactory {\n    const getConsignments = createSelector(\n        (state: ConsignmentState) => state.data,\n        consignments => () => consignments\n    );\n\n    const getConsignmentById = createSelector(\n        (state: ConsignmentState) => state.data,\n        consignments => (id: string) => {\n            if (!consignments || !consignments.length) {\n                return;\n            }\n\n            return find(consignments, { id });\n        }\n    );\n\n    const getConsignmentByAddress = createSelector(\n        (state: ConsignmentState) => state.data,\n        consignments => (address: AddressRequestBody) => {\n            if (!consignments || !consignments.length) {\n                return;\n            }\n\n            return find(consignments, consignment =>\n                isAddressEqual(consignment.shippingAddress, address)\n            );\n        }\n    );\n\n    const getShippingOption = createSelector(\n        (state: ConsignmentState) => state.data,\n        consignments => () => {\n            if (consignments && consignments.length) {\n                return consignments[0].selectedShippingOption;\n            }\n        }\n    );\n\n    const getLoadError = createSelector(\n        (state: ConsignmentState) => state.errors.loadError,\n        error => () => error\n    );\n\n    const getCreateError = createSelector(\n        (state: ConsignmentState) => state.errors.createError,\n        error => () => error\n    );\n\n    const getLoadShippingOptionsError = createSelector(\n        (state: ConsignmentState) => state.errors.loadShippingOptionsError,\n        error => () => error\n    );\n\n    const getUnassignedItems = createSelector(\n        getConsignments,\n        (_: ConsignmentState, { cart }: ConsignmentSelectorDependencies) => cart.getCart,\n        (getConsignments, getCart) => () => {\n            const cart = getCart();\n\n            if (!cart) {\n                return [];\n            }\n\n            const assignedLineItemIds = (getConsignments() || []).reduce(\n                (itemIds, consignment) => itemIds.concat(consignment.lineItemIds),\n                [] as string[]\n            );\n\n            return (cart.lineItems.physicalItems || []).filter(\n                item => assignedLineItemIds.indexOf(item.id as string) < 0\n            );\n        }\n    );\n\n    const getUpdateError = createSelector(\n        (state: ConsignmentState) => state.errors.updateError,\n        updateError => (consignmentId?: string) => {\n            if (consignmentId) {\n                return updateError[consignmentId];\n            }\n\n            return find(updateError);\n        }\n    );\n\n    const getDeleteError = createSelector(\n        (state: ConsignmentState) => state.errors.deleteError,\n        deleteError => (consignmentId?: string) => {\n            if (consignmentId) {\n                return deleteError[consignmentId];\n            }\n\n            return find(deleteError);\n        }\n    );\n\n    const getItemAssignmentError = createSelector(\n        getConsignmentByAddress,\n        getUpdateError,\n        getCreateError,\n        (getConsignmentByAddress, getUpdateError, getCreateError) => (address: AddressRequestBody) => {\n            const consignment = getConsignmentByAddress(address);\n\n            return consignment ? getUpdateError(consignment.id) : getCreateError();\n        }\n    );\n\n    const getUpdateShippingOptionError = createSelector(\n        (state: ConsignmentState) => state.errors.updateShippingOptionError,\n        updateShippingOptionError => (consignmentId?: string) => {\n            if (consignmentId) {\n                return updateShippingOptionError[consignmentId];\n            }\n\n            return find(updateShippingOptionError);\n        }\n    );\n\n    const isLoading = createSelector(\n        (state: ConsignmentState) => state.statuses.isLoading,\n        isLoading => () => isLoading === true\n    );\n\n    const isLoadingShippingOptions = createSelector(\n        (state: ConsignmentState) => state.statuses.isLoadingShippingOptions,\n        isLoadingShippingOptions => () => isLoadingShippingOptions === true\n    );\n\n    const isCreating = createSelector(\n        (state: ConsignmentState) => state.statuses.isCreating,\n        isCreating => () => isCreating === true\n    );\n\n    const isUpdating = createSelector(\n        (state: ConsignmentState) => state.statuses.isUpdating,\n        isUpdating => (consignmentId?: string) => {\n            if (consignmentId) {\n                return isUpdating[consignmentId] === true;\n            }\n\n            return find(isUpdating) === true;\n        }\n    );\n\n    const isDeleting = createSelector(\n        (state: ConsignmentState) => state.statuses.isDeleting,\n        isDeleting => (consignmentId?: string) => {\n            if (consignmentId) {\n                return isDeleting[consignmentId] === true;\n            }\n\n            return find(isDeleting) === true;\n        }\n    );\n\n    const isAssigningItems = createSelector(\n        getConsignmentByAddress,\n        isUpdating,\n        isCreating,\n        (getConsignmentByAddress, isUpdating, isCreating) => (address: AddressRequestBody) => {\n            const consignment = getConsignmentByAddress(address);\n\n            return consignment ? isUpdating(consignment.id) : isCreating();\n        }\n    );\n\n    const isUpdatingShippingOption = createSelector(\n        (state: ConsignmentState) => state.statuses.isUpdatingShippingOption,\n        isUpdatingShippingOption => (consignmentId?: string) => {\n            if (consignmentId) {\n                return isUpdatingShippingOption[consignmentId] === true;\n            }\n\n            return find(isUpdatingShippingOption) === true;\n        }\n    );\n\n    return memoizeOne((\n        state: ConsignmentState = DEFAULT_STATE,\n        cart: CartSelector\n    ): ConsignmentSelector => {\n        return {\n            getConsignments: getConsignments(state),\n            getConsignmentById: getConsignmentById(state),\n            getConsignmentByAddress: getConsignmentByAddress(state),\n            getShippingOption: getShippingOption(state),\n            getLoadError: getLoadError(state),\n            getCreateError: getCreateError(state),\n            getLoadShippingOptionsError: getLoadShippingOptionsError(state),\n            getUnassignedItems: getUnassignedItems(state, { cart }),\n            getUpdateError: getUpdateError(state),\n            getDeleteError: getDeleteError(state),\n            getItemAssignmentError: getItemAssignmentError(state),\n            getUpdateShippingOptionError: getUpdateShippingOptionError(state),\n            isLoading: isLoading(state),\n            isLoadingShippingOptions: isLoadingShippingOptions(state),\n            isCreating: isCreating(state),\n            isUpdating: isUpdating(state),\n            isDeleting: isDeleting(state),\n            isAssigningItems: isAssigningItems(state),\n            isUpdatingShippingOption: isUpdatingShippingOption(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { BillingAddressSelector } from '../billing';\nimport { CartSelector } from '../cart';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { CouponSelector, GiftCertificateSelector } from '../coupon';\nimport { CustomerSelector } from '../customer';\nimport { ConsignmentSelector } from '../shipping';\n\nimport Checkout from './checkout';\nimport CheckoutState, { DEFAULT_STATE } from './checkout-state';\n\nexport default interface CheckoutSelector {\n    getCheckout(): Checkout | undefined;\n    getCheckoutOrThrow(): Checkout;\n    getOutstandingBalance(useStoreCredit?: boolean): number | undefined;\n    getLoadError(): Error | undefined;\n    getUpdateError(): Error | undefined;\n    isExecutingSpamCheck(): boolean;\n    isLoading(): boolean;\n    isUpdating(): boolean;\n}\n\nexport type CheckoutSelectorFactory = (\n    state: CheckoutState,\n    billingAddress: BillingAddressSelector,\n    cart: CartSelector,\n    consignments: ConsignmentSelector,\n    coupons: CouponSelector,\n    customer: CustomerSelector,\n    giftCertificates: GiftCertificateSelector\n) => CheckoutSelector;\n\ninterface CheckoutSelectorDependencies {\n    billingAddress: BillingAddressSelector;\n    cart: CartSelector;\n    consignments: ConsignmentSelector;\n    coupons: CouponSelector;\n    customer: CustomerSelector;\n    giftCertificates: GiftCertificateSelector;\n}\n\nexport function createCheckoutSelectorFactory(): CheckoutSelectorFactory {\n    const getCheckout = createSelector(\n        (state: CheckoutState) => state.data,\n        (_: CheckoutState, { billingAddress }: CheckoutSelectorDependencies) => billingAddress.getBillingAddress,\n        (_: CheckoutState, { cart }: CheckoutSelectorDependencies) => cart.getCart,\n        (_: CheckoutState, { customer }: CheckoutSelectorDependencies) => customer.getCustomer,\n        (_: CheckoutState, { consignments }: CheckoutSelectorDependencies) => consignments.getConsignments,\n        (_: CheckoutState, { coupons }: CheckoutSelectorDependencies) => coupons.getCoupons,\n        (_: CheckoutState, { giftCertificates }: CheckoutSelectorDependencies) => giftCertificates.getGiftCertificates,\n        (data, getBillingAddress, getCart, getCustomer, getConsignments, getCoupons, getGiftCertificates) => () => {\n            const billingAddress = getBillingAddress();\n            const cart = getCart();\n            const customer = getCustomer();\n            const consignments = getConsignments() || [];\n            const coupons = getCoupons() || [];\n            const giftCertificates = getGiftCertificates() || [];\n\n            if (!data || !cart || !customer) {\n                return;\n            }\n\n            return {\n                ...data,\n                billingAddress,\n                cart,\n                customer,\n                consignments,\n                coupons,\n                giftCertificates,\n            };\n        }\n    );\n\n    const getCheckoutOrThrow = createSelector(\n        getCheckout,\n        getCheckout => () => {\n            return guard(getCheckout(), () => new MissingDataError(MissingDataErrorType.MissingCheckout));\n        }\n    );\n\n    const getOutstandingBalance = createSelector(\n        getCheckout,\n        getCheckout => (useStoreCredit?: boolean) => {\n            const checkout = getCheckout();\n\n            if (!checkout) {\n                return;\n            }\n\n            const grandTotal = checkout.grandTotal || 0;\n            const storeCredit = checkout.customer.storeCredit || 0;\n\n            return useStoreCredit ? Math.max(grandTotal - storeCredit, 0) : checkout.outstandingBalance;\n        }\n    );\n\n    const getLoadError = createSelector(\n        (state: CheckoutState) => state.errors.loadError,\n        error => () => error\n    );\n\n    const getUpdateError = createSelector(\n        (state: CheckoutState) => state.errors.updateError,\n        error => () => error\n    );\n\n    const isExecutingSpamCheck = createSelector(\n        (state: CheckoutState) => state.statuses.isExecutingSpamCheck,\n        isExecutingSpamCheck => () => isExecutingSpamCheck === true\n    );\n\n    const isLoading = createSelector(\n        (state: CheckoutState) => state.statuses.isLoading,\n        isLoading => () => isLoading === true\n    );\n\n    const isUpdating = createSelector(\n        (state: CheckoutState) => state.statuses.isUpdating,\n        isUpdating => () => isUpdating === true\n    );\n\n    return memoizeOne((\n        state: CheckoutState = DEFAULT_STATE,\n        billingAddress: BillingAddressSelector,\n        cart: CartSelector,\n        consignments: ConsignmentSelector,\n        coupons: CouponSelector,\n        customer: CustomerSelector,\n        giftCertificates: GiftCertificateSelector\n    ): CheckoutSelector => {\n        return {\n            getCheckout: getCheckout(state, {\n                billingAddress,\n                cart,\n                consignments,\n                coupons,\n                customer,\n                giftCertificates,\n            }),\n            getCheckoutOrThrow: getCheckoutOrThrow(state, {\n                billingAddress,\n                cart,\n                consignments,\n                coupons,\n                customer,\n                giftCertificates,\n            }),\n            getOutstandingBalance: getOutstandingBalance(state, {\n                billingAddress,\n                cart,\n                consignments,\n                coupons,\n                customer,\n                giftCertificates,\n            }),\n            getLoadError: getLoadError(state),\n            getUpdateError: getUpdateError(state),\n            isExecutingSpamCheck: isExecutingSpamCheck(state),\n            isLoading: isLoading(state),\n            isUpdating: isUpdating(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { BillingAddressSelector } from '../billing';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { CouponSelector } from '../coupon';\n\nimport Order from './order';\nimport OrderState, { DEFAULT_STATE, OrderMetaState } from './order-state';\n\nexport default interface OrderSelector {\n    getOrder(): Order | undefined;\n    getOrderOrThrow(): Order;\n    getOrderMeta(): OrderMetaState | undefined;\n    getLoadError(): Error | undefined;\n    getPaymentId(methodId: string): string | undefined;\n    isLoading(): boolean;\n}\n\nexport type OrderSelectorFactory = (\n    state: OrderState,\n    billingAddress: BillingAddressSelector,\n    coupons: CouponSelector\n) => OrderSelector;\n\ninterface OrderSelectorDependencies {\n    billingAddress: BillingAddressSelector;\n    coupons: CouponSelector;\n}\n\nexport function createOrderSelectorFactory(): OrderSelectorFactory {\n    const getOrder = createSelector(\n        (state: OrderState) => state.data,\n        (_: OrderState, { billingAddress }: OrderSelectorDependencies) => billingAddress.getBillingAddress(),\n        (_: OrderState, { coupons }: OrderSelectorDependencies) => coupons.getCoupons(),\n        (data, billingAddress, coupons = []) => () => {\n            if (!data || !billingAddress) {\n                return;\n            }\n\n            return {\n                ...data,\n                billingAddress,\n                coupons,\n            };\n        }\n    );\n\n    const getOrderOrThrow = createSelector(\n        getOrder,\n        getOrder => () => {\n            return guard(getOrder(), () => new MissingDataError(MissingDataErrorType.MissingOrder));\n        }\n    );\n\n    const getOrderMeta = createSelector(\n        (state: OrderState) => state.meta,\n        meta => () => meta\n    );\n\n    const getLoadError = createSelector(\n        (state: OrderState) => state.errors.loadError,\n        error => () => error\n    );\n\n    const getPaymentId = createSelector(\n        (state: OrderState) => state.data?.payments,\n        (payments = []) => (methodId: string) => {\n            const currentPayment = payments.find(({ providerId }) => providerId === methodId);\n\n            return currentPayment?.paymentId;\n        }\n    );\n\n    const isLoading = createSelector(\n        (state: OrderState) => !!state.statuses.isLoading,\n        status => () => status\n    );\n\n    return memoizeOne((\n        state: OrderState = DEFAULT_STATE,\n        billingAddress: BillingAddressSelector,\n        coupons: CouponSelector\n    ): OrderSelector => {\n        return {\n            getOrder: getOrder(state, { billingAddress, coupons }),\n            getOrderOrThrow: getOrderOrThrow(state, { billingAddress, coupons }),\n            getOrderMeta: getOrderMeta(state),\n            getLoadError: getLoadError(state),\n            getPaymentId: getPaymentId(state),\n            isLoading: isLoading(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { RequestError } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\n\nimport StoreCreditState, { DEFAULT_STATE } from './store-credit-state';\n\nexport default interface StoreCreditSelector {\n    getApplyError(): RequestError | undefined;\n    isApplying(): boolean;\n}\n\nexport type StoreCreditSelectorFactory = (state: StoreCreditState) => StoreCreditSelector;\n\nexport function createStoreCreditSelectorFactory(): StoreCreditSelectorFactory {\n    const getApplyError = createSelector(\n        (state: StoreCreditState) => state.errors.applyError,\n        error => () => error\n    );\n\n    const isApplying = createSelector(\n        (state: StoreCreditState) => !!state.statuses.isApplying,\n        status => () => status\n    );\n\n    return memoizeOne((\n        state: StoreCreditState = DEFAULT_STATE\n    ): StoreCreditSelector => {\n        return {\n            getApplyError: getApplyError(state),\n            isApplying: isApplying(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport SubscriptionsState, { DEFAULT_STATE } from './subscriptions-state';\n\nexport default interface SubscriptionsSelector {\n    getUpdateError(): Error | undefined;\n    isUpdating(): boolean;\n}\n\nexport type SubscriptionsSelectorFactory = (state: SubscriptionsState) => SubscriptionsSelector;\n\nexport function createSubscriptionsSelectorFactory(): SubscriptionsSelectorFactory {\n    const getUpdateError = createSelector(\n        (state: SubscriptionsState) => state.errors.updateError,\n        error => () => error\n    );\n\n    const isUpdating = createSelector(\n        (state: SubscriptionsState) => !!state.statuses.isUpdating,\n        status => () => status\n    );\n\n    return memoizeOne((\n        state: SubscriptionsState = DEFAULT_STATE\n    ): SubscriptionsSelector => {\n        return {\n            getUpdateError: getUpdateError(state),\n            isUpdating: isUpdating(state),\n        };\n    });\n}\n","import { createDataStore } from '@bigcommerce/data-store';\n\nimport { createRequestErrorFactory } from '../common/error';\n\nimport CheckoutStore, { CheckoutStoreOptions } from './checkout-store';\nimport CheckoutStoreState from './checkout-store-state';\nimport createActionTransformer from './create-action-transformer';\nimport createCheckoutStoreReducer from './create-checkout-store-reducer';\nimport { createInternalCheckoutSelectorsFactory } from './create-internal-checkout-selectors';\n\nexport default function createCheckoutStore(\n    initialState: Partial<CheckoutStoreState> = {},\n    options?: CheckoutStoreOptions\n): CheckoutStore {\n    const actionTransformer = createActionTransformer(createRequestErrorFactory());\n    const createInternalCheckoutSelectors = createInternalCheckoutSelectorsFactory();\n    const stateTransformer = (state: CheckoutStoreState) => createInternalCheckoutSelectors(state);\n\n    return createDataStore(\n        createCheckoutStoreReducer(),\n        initialState,\n        { actionTransformer, stateTransformer, ...options }\n    );\n}\n","import { Action } from '@bigcommerce/data-store';\nimport { from, Observable, Subscribable } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { RequestErrorFactory } from '../common/error';\n\nexport default function createActionTransformer(\n    requestErrorFactory: RequestErrorFactory\n): (action: Subscribable<Action>) => Observable<Action> {\n    return action$ => from(action$).pipe(catchError<Action, never>(action => {\n        if (action instanceof Error || action.payload instanceof Error) {\n            throw action;\n        }\n\n        if (isResponse(action.payload)) {\n            const message = action.payload.body && action.payload.body.detail;\n\n            throw { ...action, payload: requestErrorFactory.createError(action.payload, message) };\n        }\n\n        throw action;\n    }));\n}\n\nfunction isResponse(object: any) {\n    if (!object || typeof object !== 'object') {\n        return false;\n    }\n\n    return ['body', 'headers', 'status', 'statusText'].every(key =>\n        object.hasOwnProperty(key)\n    );\n}\n","import { PaymentMethodInvalidError } from '../../payment/errors';\n\nimport { UnrecoverableError } from './errors';\nimport RequestErrorFactory from './request-error-factory';\n\nexport default function createRequestErrorFactory(): RequestErrorFactory {\n    const factory = new RequestErrorFactory();\n\n    const unrecoverableErrorTypes = [\n        'catalog_only',\n        'empty_cart',\n        'invalid_order_id',\n        'invalid_order_token',\n        'missing_order_token',\n        'missing_provider_token',\n        'missing_shipping_method',\n        'order_completion_error',\n        'order_could_not_be_finalized_error',\n        'order_create_failed',\n        'provider_fatal_error',\n        'provider_setup_error',\n        'stock_too_low',\n    ];\n\n    unrecoverableErrorTypes.forEach(type => {\n        factory.register(type, (response, message) => new UnrecoverableError(response, message));\n    });\n\n    factory.register('invalid_payment_provider', response => new PaymentMethodInvalidError(response));\n    factory.register('payment_config_not_found', response => new PaymentMethodInvalidError(response));\n\n    return factory;\n}\n","import { combineReducers, Action, Reducer } from '@bigcommerce/data-store';\n\nimport { billingAddressReducer } from '../billing';\nimport { cartReducer } from '../cart';\nimport { checkoutButtonReducer } from '../checkout-buttons';\nimport { configReducer } from '../config';\nimport { couponReducer, giftCertificateReducer } from '../coupon';\nimport { customerReducer, customerStrategyReducer } from '../customer';\nimport { formFieldsReducer } from '../form';\nimport { countryReducer } from '../geography';\nimport { orderReducer } from '../order';\nimport { paymentMethodReducer, paymentReducer, paymentStrategyReducer } from '../payment';\nimport { instrumentReducer } from '../payment/instrument';\nimport { remoteCheckoutReducer } from '../remote-checkout';\nimport { consignmentReducer, shippingCountryReducer, shippingStrategyReducer } from '../shipping';\nimport { signInEmailReducer } from '../signin-email';\nimport { storeCreditReducer } from '../store-credit';\nimport { subscriptionsReducer } from '../subscription';\n\nimport checkoutReducer from './checkout-reducer';\nimport CheckoutStoreState from './checkout-store-state';\n\nexport default function createCheckoutStoreReducer(): Reducer<CheckoutStoreState, Action> {\n    return combineReducers({\n        billingAddress: billingAddressReducer,\n        cart: cartReducer,\n        checkout: checkoutReducer,\n        checkoutButton: checkoutButtonReducer,\n        config: configReducer,\n        consignments: consignmentReducer,\n        countries: countryReducer,\n        coupons: couponReducer,\n        customer: customerReducer,\n        customerStrategies: customerStrategyReducer,\n        formFields: formFieldsReducer,\n        giftCertificates: giftCertificateReducer,\n        instruments: instrumentReducer,\n        order: orderReducer,\n        payment: paymentReducer,\n        paymentMethods: paymentMethodReducer,\n        paymentStrategies: paymentStrategyReducer,\n        remoteCheckout: remoteCheckoutReducer,\n        shippingCountries: shippingCountryReducer,\n        shippingStrategies: shippingStrategyReducer,\n        signInEmail: signInEmailReducer,\n        subscriptions: subscriptionsReducer,\n        storeCredit: storeCreditReducer,\n    });\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { InternalErrorResponseBody } from '../../common/error';\nimport { RequestError } from '../../common/error/errors';\n\n/**\n * Throw this error when we are unable to retrieve a checkout object from the\n * server using the provided ID. It could be because the shopper does not have\n * permission to view the object, or the ID itself is invalid.\n */\nexport default class CheckoutNotAvailableError extends RequestError {\n    constructor(response: Response<InternalErrorResponseBody>) {\n        super(response, { message: response.body.title });\n\n        this.name = 'CheckoutNotAvailableError';\n        this.type = 'checkout_not_available';\n    }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { joinOrMergeIncludes, ContentType, RequestOptions } from '../common/http-request';\n\nimport Checkout, { CheckoutRequestBody } from './checkout';\nimport CHECKOUT_DEFAULT_INCLUDES from './checkout-default-includes';\nimport CheckoutParams from './checkout-params';\nimport { CheckoutNotAvailableError } from './errors';\n\nexport default class CheckoutRequestSender {\n    constructor(\n        private _requestSender: RequestSender\n    ) {}\n\n    loadCheckout(id: string, { params: { include } = {}, timeout }: RequestOptions<CheckoutParams> = {}): Promise<Response<Checkout>> {\n        const url = `/api/storefront/checkout/${id}`;\n        const headers = { Accept: ContentType.JsonV1 };\n\n        return this._requestSender.get<Checkout>(url, {\n            params: {\n                include: joinOrMergeIncludes(CHECKOUT_DEFAULT_INCLUDES, include),\n            },\n            headers,\n            timeout,\n        }).catch(error => {\n            if (error.status >= 400 && error.status < 500) {\n                throw new CheckoutNotAvailableError(error);\n            }\n\n            throw error;\n        });\n    }\n\n    updateCheckout(id: string, body: CheckoutRequestBody, { params: { include } = {}, timeout }: RequestOptions<CheckoutParams> = {}): Promise<Response<Checkout>> {\n        const url = `/api/storefront/checkout/${id}`;\n        const headers = { Accept: ContentType.JsonV1 };\n\n        return this._requestSender.put(url, {\n            params: {\n                include: joinOrMergeIncludes(CHECKOUT_DEFAULT_INCLUDES, include),\n            },\n            body,\n            headers,\n            timeout,\n        });\n    }\n}\n","export enum CheckoutIncludes {\n    AvailableShippingOptions = 'consignments.availableShippingOptions',\n    PhysicalItemsCategoryNames = 'cart.lineItems.physicalItems.categoryNames',\n    DigitalItemsCategoryNames = 'cart.lineItems.digitalItems.categoryNames',\n}\n\nexport default interface CheckoutParams {\n    include?: CheckoutIncludes[] | CheckoutIncludeParam;\n}\n\nexport type CheckoutIncludeParam = {\n    [key in CheckoutIncludes]?: boolean;\n};\n","import GiftCertificate from './gift-certificate';\nimport InternalGiftCertificate from './internal-gift-certificate';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalGiftCertificate(giftCertificate: GiftCertificate): InternalGiftCertificate {\n    return {\n        code: giftCertificate.code,\n        discountedAmount: giftCertificate.used,\n        remainingBalance: giftCertificate.remaining,\n        giftCertificate: {\n            balance: giftCertificate.balance,\n            code: giftCertificate.code,\n            purchaseDate: giftCertificate.purchaseDate,\n        },\n    };\n}\n","import { fromEvent } from 'rxjs';\nimport { filter, map, take } from 'rxjs/operators';\n\nimport { parseUrl } from '../url';\n\nimport IframeEvent from './iframe-event';\nimport isIframeEvent from './is-iframe-event';\n\nexport interface IframeEventPostOptions<TSuccessEvent extends IframeEvent, TErrorEvent extends IframeEvent> {\n    errorType?: TErrorEvent['type'];\n    successType?: TSuccessEvent['type'];\n}\n\nexport default class IframeEventPoster<TEvent> {\n    private _targetOrigin: string;\n\n    constructor(\n        targetOrigin: string,\n        private _targetWindow?: Window\n    ) {\n        this._targetOrigin = targetOrigin === '*' ? '*' : parseUrl(targetOrigin).origin;\n    }\n\n    post(event: TEvent): void;\n    post<TSuccessEvent extends IframeEvent = IframeEvent, TErrorEvent extends IframeEvent = IframeEvent>(\n        event: TEvent,\n        options: IframeEventPostOptions<TSuccessEvent, TErrorEvent>\n    ): Promise<TSuccessEvent>;\n    post<TSuccessEvent extends IframeEvent = IframeEvent, TErrorEvent extends IframeEvent = IframeEvent>(\n        event: TEvent,\n        options?: IframeEventPostOptions<TSuccessEvent, TErrorEvent>\n    ): Promise<TSuccessEvent> | void {\n        const targetWindow = this._targetWindow;\n\n        if (window === targetWindow) {\n            return;\n        }\n\n        if (!targetWindow) {\n            throw new Error('Unable to post message because target window is not set.');\n        }\n\n        const result = options && fromEvent<MessageEvent>(window, 'message')\n            .pipe(\n                filter(event =>\n                    event.origin === this._targetOrigin &&\n                    isIframeEvent(event.data, event.data.type) &&\n                    [options.successType, options.errorType].indexOf(event.data.type) !== -1\n                ),\n                map(event => {\n                    if (options.errorType === event.data.type) {\n                        throw event.data;\n                    }\n\n                    return event.data;\n                }),\n                take(1)\n            )\n            .toPromise();\n\n        targetWindow.postMessage(event, this._targetOrigin);\n\n        return result;\n    }\n\n    setTarget(window: Window) {\n        this._targetWindow = window;\n    }\n}\n","import { appendWww, parseUrl } from '../url';\nimport { bindDecorator as bind } from '../utility';\n\nimport { IframeEventMap } from './iframe-event';\nimport isIframeEvent from './is-iframe-event';\n\nexport default class IframeEventListener<TEventMap extends IframeEventMap<keyof TEventMap>> {\n    private _isListening: boolean;\n    private _listeners: EventListeners<TEventMap>;\n    private _sourceOrigins: string[];\n\n    constructor(\n        sourceOrigin: string\n    ) {\n        this._sourceOrigins = [\n            parseUrl(sourceOrigin).origin,\n            appendWww(parseUrl(sourceOrigin)).origin,\n        ];\n        this._isListening = false;\n        this._listeners = {};\n    }\n\n    listen(): void {\n        if (this._isListening) {\n            return;\n        }\n\n        this._isListening = true;\n\n        window.addEventListener('message', this._handleMessage);\n    }\n\n    stopListen(): void {\n        if (!this._isListening) {\n            return;\n        }\n\n        this._isListening = false;\n\n        window.removeEventListener('message', this._handleMessage);\n    }\n\n    addListener<TType extends keyof TEventMap>(type: TType, listener: (event: TEventMap[TType]) => void): void {\n        let listeners = this._listeners[type];\n\n        if (!listeners) {\n            this._listeners[type] = listeners = [];\n        }\n\n        if (listeners.indexOf(listener) === -1) {\n            listeners.push(listener);\n        }\n    }\n\n    removeListener<TType extends keyof TEventMap>(type: TType, listener: (event: TEventMap[TType]) => void): void {\n        const listeners = this._listeners[type];\n\n        if (!listeners) {\n            return;\n        }\n\n        const index = listeners.indexOf(listener);\n\n        if (index >= 0) {\n            listeners.splice(index, 1);\n        }\n    }\n\n    trigger<TType extends keyof TEventMap>(event: TEventMap[TType]): void {\n        const listeners = this._listeners[event.type];\n\n        if (!listeners) {\n            return;\n        }\n\n        listeners.forEach(listener => listener(event));\n    }\n\n    @bind\n    private _handleMessage(event: MessageEvent): void {\n        if ((this._sourceOrigins.indexOf(event.origin) === -1) ||\n            !isIframeEvent(event.data as TEventMap[keyof TEventMap], event.data.type)\n        ) {\n            return;\n        }\n\n        this.trigger(event.data);\n    }\n}\n\ntype EventListeners<TEventMap> = {\n    [key in keyof TEventMap]?: Array<(event: TEventMap[key]) => void>;\n};\n","import { memoize } from '@bigcommerce/memoize';\n\nimport { bindDecorator, isEqual, isPrivate, CacheKeyResolver } from '../utility';\n\n/**\n * Decorates a class by patching all of its methods to cache their return values\n * and return them if they are called again with the same set of parameters. The\n * decorator also binds all the methods to the calling instance so it can be\n * destructed.\n */\nexport default function selectorDecorator<T extends Constructor<object>>(target: T): T {\n    const decoratedTarget = class extends target {};\n\n    Object.getOwnPropertyNames(target.prototype)\n        .forEach(key => {\n            const descriptor = Object.getOwnPropertyDescriptor(target.prototype, key);\n\n            if (!descriptor || key === 'constructor') {\n                return;\n            }\n\n            Object.defineProperty(\n                decoratedTarget.prototype,\n                key,\n                selectorMethodDecorator(target.prototype, key, descriptor)\n            );\n        });\n\n    return decoratedTarget;\n}\n\nfunction selectorMethodDecorator<T extends Method>(target: object, key: string, descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T> {\n    if (typeof descriptor.value !== 'function') {\n        return descriptor;\n    }\n\n    let resolver = new CacheKeyResolver();\n    let method = descriptor.value;\n    let memoizedMethod = memoize(method);\n\n    return bindDecorator(target, key, {\n        get() {\n            const value = ((...args: any[]) => {\n                const cachedValue = memoizedMethod.call(this, ...args);\n\n                if (resolver.getUsedCount(...args) === 1) {\n                    return cachedValue;\n                }\n\n                const newValue = method.call(this, ...args);\n\n                if (isEqual(newValue, cachedValue, { keyFilter: key => !isPrivate(key) })) {\n                    return cachedValue;\n                }\n\n                memoizedMethod.cache.set(resolver.getKey(...args), newValue);\n\n                return newValue;\n            }) as T;\n\n            Object.defineProperty(this, key, { ...descriptor, value });\n\n            return value;\n        },\n        set(value) {\n            resolver = new CacheKeyResolver();\n            method = value;\n            memoizedMethod = memoize(method);\n        },\n    });\n}\n\nexport type Constructor<T> = new (...args: any[]) => T;\ntype Method = (...args: any[]) => any;\n","import { InternalCheckoutSelectors } from '../checkout';\nimport { selector } from '../common/selector';\n\nimport CheckoutButtonSelector from './checkout-button-selector';\nimport { CheckoutButtonMethodType } from './strategies';\n\n@selector\nexport default class CheckoutButtonErrorSelector {\n    private _checkoutButton: CheckoutButtonSelector;\n\n    /**\n     * @internal\n     */\n    constructor(selectors: InternalCheckoutSelectors) {\n        this._checkoutButton = selectors.checkoutButton;\n    }\n\n    getInitializeButtonError(methodId?: CheckoutButtonMethodType): Error | undefined {\n        return this._checkoutButton.getInitializeError(methodId);\n    }\n\n    getDeinitializeButtonError(methodId?: CheckoutButtonMethodType): Error | undefined {\n        return this._checkoutButton.getDeinitializeError(methodId);\n    }\n}\n","import { InternalCheckoutSelectors } from '../checkout';\nimport { selector } from '../common/selector';\n\nimport CheckoutButtonSelector from './checkout-button-selector';\nimport { CheckoutButtonMethodType } from './strategies';\n\n@selector\nexport default class CheckoutButtonStatusSelector {\n    private _checkoutButton: CheckoutButtonSelector;\n\n    /**\n     * @internal\n     */\n    constructor(selectors: InternalCheckoutSelectors) {\n        this._checkoutButton = selectors.checkoutButton;\n    }\n\n    isInitializingButton(methodId?: CheckoutButtonMethodType): boolean {\n        return this._checkoutButton.isInitializing(methodId);\n    }\n\n    isDeinitializingButton(methodId?: CheckoutButtonMethodType): boolean {\n        return this._checkoutButton.isDeinitializing(methodId);\n    }\n}\n","import { InternalCheckoutSelectors } from '../checkout';\n\nimport CheckoutButtonErrorSelector from './checkout-button-error-selector';\nimport CheckoutButtonSelectors from './checkout-button-selectors';\nimport CheckoutButtonStatusSelector from './checkout-button-status-selector';\n\nexport default function createCheckoutButtonSelectors(selectors: InternalCheckoutSelectors): CheckoutButtonSelectors {\n    const errors = new CheckoutButtonErrorSelector(selectors);\n    const statuses = new CheckoutButtonStatusSelector(selectors);\n\n    return {\n        errors,\n        statuses,\n    };\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../checkout';\nimport { isElementId, setUniqueElementId } from '../common/dom';\nimport { bindDecorator as bind } from '../common/utility';\n\nimport { CheckoutButtonInitializeOptions, CheckoutButtonOptions } from './checkout-button-options';\nimport CheckoutButtonSelectors from './checkout-button-selectors';\nimport CheckoutButtonStrategyActionCreator from './checkout-button-strategy-action-creator';\nimport createCheckoutButtonSelectors from './create-checkout-button-selectors';\n\n@bind\nexport default class CheckoutButtonInitializer {\n    private _state: CheckoutButtonSelectors;\n\n    /**\n     * @internal\n     */\n    constructor(\n        private _store: CheckoutStore,\n        private _buttonStrategyActionCreator: CheckoutButtonStrategyActionCreator\n    ) {\n        this._state = createCheckoutButtonSelectors(this._store.getState());\n\n        this._store.subscribe(state => {\n            this._state = createCheckoutButtonSelectors(state);\n        });\n    }\n\n    /**\n     * Returns a snapshot of the current state.\n     *\n     * The method returns a new instance every time there is a change in the\n     * state. You can query the state by calling any of its getter methods.\n     *\n     * ```js\n     * const state = service.getState();\n     *\n     * console.log(state.errors.getInitializeButtonError());\n     * console.log(state.statuses.isInitializingButton());\n     * ```\n     *\n     * @returns The current customer's checkout state\n     */\n    getState(): CheckoutButtonSelectors {\n        return this._state;\n    }\n\n    /**\n     * Subscribes to any changes to the current state.\n     *\n     * The method registers a callback function and executes it every time there\n     * is a change in the current state.\n     *\n     * ```js\n     * service.subscribe(state => {\n     *     console.log(state.statuses.isInitializingButton());\n     * });\n     * ```\n     *\n     * The method can be configured to notify subscribers only regarding\n     * relevant changes, by providing a filter function.\n     *\n     * ```js\n     * const filter = state => state.errors.getInitializeButtonError();\n     *\n     * // Only trigger the subscriber when the cart changes.\n     * service.subscribe(state => {\n     *     console.log(state.errors.getInitializeButtonError())\n     * }, filter);\n     * ```\n     *\n     * @param subscriber - The function to subscribe to state changes.\n     * @param filters - One or more functions to filter out irrelevant state\n     * changes. If more than one function is provided, the subscriber will only\n     * be triggered if all conditions are met.\n     * @returns A function, if called, will unsubscribe the subscriber.\n     */\n    subscribe(\n        subscriber: (state: CheckoutButtonSelectors) => void,\n        ...filters: Array<(state: CheckoutButtonSelectors) => any>\n    ): () => void {\n        return this._store.subscribe(\n            () => subscriber(this.getState()),\n            state => state.checkoutButton.getState(),\n            ...filters.map(filter => (state: InternalCheckoutSelectors) => filter(createCheckoutButtonSelectors(state)))\n        );\n    }\n\n    /**\n     * Initializes the checkout button of a payment method.\n     *\n     * When the checkout button is initialized, it will be inserted into the DOM,\n     * ready to be interacted with by the customer.\n     *\n     * ```js\n     * initializer.initializeButton({\n     *     methodId: 'braintreepaypal',\n     *     containerId: 'checkoutButton',\n     *     braintreepaypal: {\n     *     },\n     * });\n     * ```\n     *\n     * @param options - Options for initializing the checkout button.\n     * @returns A promise that resolves to the current state.\n     */\n    initializeButton(options: CheckoutButtonInitializeOptions): Promise<CheckoutButtonSelectors> {\n        const containerIds = isElementId(options.containerId) ?\n            [options.containerId] :\n            setUniqueElementId(options.containerId, `${options.methodId}-container`);\n\n        return Promise.all(\n            containerIds.map(containerId => {\n                const action = this._buttonStrategyActionCreator.initialize({ ...options, containerId });\n                const queueId = `checkoutButtonStrategy:${options.methodId}:${containerId}`;\n\n                return this._store.dispatch(action, { queueId });\n            })\n        )\n            .then(() => this.getState());\n    }\n\n    /**\n     * De-initializes the checkout button by performing any necessary clean-ups.\n     *\n     * ```js\n     * await service.deinitializeButton({\n     *     methodId: 'braintreepaypal',\n     * });\n     * ```\n     *\n     * @param options - Options for deinitializing the checkout button.\n     * @returns A promise that resolves to the current state.\n     */\n    deinitializeButton(options: CheckoutButtonOptions): Promise<CheckoutButtonSelectors> {\n        const action = this._buttonStrategyActionCreator.deinitialize(options);\n        const queueId = `checkoutButtonStrategy:${options.methodId}`;\n\n        return this._store.dispatch(action, { queueId })\n            .then(() => this.getState());\n    }\n}\n","enum CheckoutButtonMethodType {\n    AMAZON_PAY_V2 = 'amazonpay',\n    BRAINTREE_PAYPAL = 'braintreepaypal',\n    BRAINTREE_PAYPAL_CREDIT = 'braintreepaypalcredit',\n    GOOGLEPAY_ADYENV2 = 'googlepayadyenv2',\n    GOOGLEPAY_AUTHORIZENET = 'googlepayauthorizenet',\n    GOOGLEPAY_BRAINTREE = 'googlepaybraintree',\n    GOOGLEPAY_CHECKOUTCOM = 'googlepaycheckoutcom',\n    GOOGLEPAY_CYBERSOURCEV2 = 'googlepaycybersourcev2',\n    GOOGLEPAY_ORBITAL = 'googlepayorbital',\n    GOOGLEPAY_STRIPE = 'googlepaystripe',\n    MASTERPASS = 'masterpass',\n    PAYPALEXPRESS = 'paypalexpress',\n    PAYPALCOMMERCE = 'paypalcommerce',\n}\n\nexport default CheckoutButtonMethodType;\n","export default function isElementId(id: string): boolean {\n    return /^\\w[\\w\\-\\:\\.]*$/.test(id);\n}\n","import { uniqueId } from 'lodash';\n\nimport { InvalidArgumentError } from '../error/errors';\n\nexport default function setUniqueElementId(selector: string, idPrefix: string): string[] {\n    const containers = document.querySelectorAll(selector);\n\n    if (!containers.length) {\n        throw new InvalidArgumentError(`Unable to find any element with the specified selector: ${selector}`);\n    }\n\n    return Array.prototype.slice.call(containers)\n        .map((container: HTMLElement) => {\n            if (!container.id) {\n                container.id = uniqueId(idPrefix);\n            }\n\n            return container.id;\n        });\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, empty, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { Registry } from '../common/registry';\nimport { PaymentMethodActionCreator } from '../payment';\n\nimport { CheckoutButtonActionType, DeinitializeButtonAction, InitializeButtonAction } from './checkout-button-actions';\nimport { CheckoutButtonInitializeOptions, CheckoutButtonOptions } from './checkout-button-options';\nimport { CheckoutButtonStrategy } from './strategies';\n\nexport default class CheckoutButtonStrategyActionCreator {\n    constructor(\n        private _registry: Registry<CheckoutButtonStrategy>,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator\n    ) {}\n\n    initialize(options: CheckoutButtonInitializeOptions): ThunkAction<InitializeButtonAction, InternalCheckoutSelectors> {\n        return store => {\n            const meta = { methodId: options.methodId, containerId: options.containerId };\n\n            if (store.getState().checkoutButton.isInitialized(options.methodId, options.containerId)) {\n                return empty();\n            }\n\n            return concat(\n                of(createAction(CheckoutButtonActionType.InitializeButtonRequested, undefined, meta)),\n                this._paymentMethodActionCreator.loadPaymentMethod(options.methodId, { timeout: options.timeout, useCache: true }),\n                defer(() => this._registry.get(options.methodId).initialize(options)\n                    .then(() => createAction(CheckoutButtonActionType.InitializeButtonSucceeded, undefined, meta)))\n            ).pipe(\n                catchError(error => throwErrorAction(CheckoutButtonActionType.InitializeButtonFailed, error, meta))\n            );\n        };\n    }\n\n    deinitialize(options: CheckoutButtonOptions): ThunkAction<DeinitializeButtonAction, InternalCheckoutSelectors> {\n        return store => {\n            const meta = { methodId: options.methodId };\n\n            if (!store.getState().checkoutButton.isInitialized(options.methodId)) {\n                return empty();\n            }\n\n            return concat(\n                of(createAction(CheckoutButtonActionType.DeinitializeButtonRequested, undefined, meta)),\n                defer(() => this._registry.get(options.methodId).deinitialize()\n                    .then(() => createAction(CheckoutButtonActionType.DeinitializeButtonSucceeded, undefined, meta)))\n            ).pipe(\n                catchError(error => throwErrorAction(CheckoutButtonActionType.DeinitializeButtonFailed, error, meta))\n            );\n        };\n    }\n}\n","import { CheckoutActionCreator, CheckoutStore } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType } from '../../../common/error/errors';\nimport { PaymentMethod } from '../../../payment';\nimport { AmazonPayV2ButtonParams, AmazonPayV2PaymentProcessor, AmazonPayV2PayOptions, AmazonPayV2Placement } from '../../../payment/strategies/amazon-pay-v2';\nimport { getShippableItemsCount } from '../../../shipping';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nimport { AmazonPayV2ButtonInitializeOptions } from './amazon-pay-v2-button-options';\n\nexport default class AmazonPayV2ButtonStrategy implements CheckoutButtonStrategy {\n    private _walletButton?: HTMLElement;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _checkoutActionCreator: CheckoutActionCreator,\n        private _amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor\n    ) { }\n\n    async initialize(options: CheckoutButtonInitializeOptions): Promise<void> {\n        const { containerId, methodId, amazonpay } = options;\n\n        if (!containerId || !methodId) {\n            throw new InvalidArgumentError('Unable to proceed because \"containerId\" or \"methodId\" argument is not provided.');\n        }\n\n        const paymentMethod = this._store.getState().paymentMethods.getPaymentMethodOrThrow(methodId);\n\n        await this._amazonPayV2PaymentProcessor.initialize(paymentMethod);\n        this._walletButton = await this._createSignInButton(containerId, paymentMethod, amazonpay);\n    }\n\n    deinitialize(): Promise<void> {\n        if (this._walletButton && this._walletButton.parentNode) {\n            this._walletButton.parentNode.removeChild(this._walletButton);\n            this._walletButton = undefined;\n        }\n\n        return Promise.resolve();\n    }\n\n    private async _createSignInButton(containerId: string, paymentMethod: PaymentMethod, options?: AmazonPayV2ButtonInitializeOptions): Promise<HTMLElement> {\n        const container = document.getElementById(containerId);\n\n        if (!container) {\n            throw new InvalidArgumentError('Unable to create sign-in button without valid container ID.');\n        }\n\n        const amazonButtonOptions = options ?? await this._getAmazonPayV2ButtonOptions(paymentMethod);\n\n        this._amazonPayV2PaymentProcessor.createButton(`#${containerId}`, amazonButtonOptions);\n\n        return container;\n    }\n\n    private async _getAmazonPayV2ButtonOptions(paymentMethod: PaymentMethod): Promise<AmazonPayV2ButtonParams> {\n        const state = await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n        const cart = state.cart.getCart();\n        const { storeProfile: { shopPath } } = state.config.getStoreConfigOrThrow();\n\n        const {\n            config: {\n                merchantId,\n                testMode,\n            },\n            initializationData: {\n                checkoutLanguage,\n                ledgerCurrency,\n                checkoutSessionMethod,\n                extractAmazonCheckoutSessionId,\n            },\n        } = paymentMethod;\n\n        if (!merchantId || !ledgerCurrency || !shopPath) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        return {\n            merchantId,\n            createCheckoutSession: {\n                url: `${shopPath}/remote-checkout/${paymentMethod.id}/payment-session`,\n                method: checkoutSessionMethod,\n                extractAmazonCheckoutSessionId,\n            },\n            sandbox: !!testMode,\n            ledgerCurrency,\n            checkoutLanguage,\n            productType: cart && getShippableItemsCount(cart) === 0 ?\n                AmazonPayV2PayOptions.PayOnly :\n                AmazonPayV2PayOptions.PayAndShip,\n            placement: AmazonPayV2Placement.Cart,\n        };\n    }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { pick } from 'lodash';\n\nimport { Address, LegacyAddress } from '../../../address';\nimport { CheckoutActionCreator, CheckoutStore } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType, StandardError } from '../../../common/error/errors';\nimport { PaymentMethod } from '../../../payment';\nimport { BraintreeError,\n    BraintreePaypalCheckout,\n    BraintreeShippingAddressOverride,\n    BraintreeSDKCreator,\n    BraintreeTokenizePayload,\n    PaypalClientInstance,\n    RenderButtonsData } from '../../../payment/strategies/braintree';\nimport { PaypalAuthorizeData, PaypalButtonStyleOptions, PaypalHostWindow } from '../../../payment/strategies/paypal';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nimport { BraintreePaypalButtonInitializeOptions } from './braintree-paypal-button-options';\n\nexport default class BraintreePaypalButtonStrategy implements CheckoutButtonStrategy {\n    private _paypalCheckout?: BraintreePaypalCheckout;\n    private _paymentMethod?: PaymentMethod;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _checkoutActionCreator: CheckoutActionCreator,\n        private _braintreeSDKCreator: BraintreeSDKCreator,\n        private _formPoster: FormPoster,\n        private _offerCredit: boolean = false,\n        private _window: PaypalHostWindow,\n        private _renderButtonsData?: RenderButtonsData\n    ) {}\n\n    async initialize(options: CheckoutButtonInitializeOptions): Promise<void> {\n        const paypalOptions = (this._offerCredit ? options.braintreepaypalcredit : options.braintreepaypal) || {};\n        const state = this._store.getState();\n        const paymentMethod = this._paymentMethod = state.paymentMethods.getPaymentMethod(options.methodId);\n        const storeState = await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n        const currency = storeState.config.getStoreConfig()?.shopperCurrency;\n\n        if (!paymentMethod || !paymentMethod.clientToken) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        this._braintreeSDKCreator.initialize(paymentMethod.clientToken);\n        const container = `#${options.containerId}`;\n\n        this._renderButtonsData = {\n            paymentMethod,\n            paypalOptions,\n            container,\n        };\n\n        return Promise.all([\n            this._braintreeSDKCreator.getPaypalCheckout({currency: currency?.code }, (paypalCheckoutInstance: PaypalClientInstance) => this.renderButtons(paypalCheckoutInstance)),\n            this._braintreeSDKCreator.getPaypal(),\n        ])\n            .then(([paypalCheckout]) => {\n                if (!this._paypalCheckout) {\n                    this._paypalCheckout = paypalCheckout;\n                }\n            });\n    }\n\n    renderButtons(paypalCheckoutInstance: PaypalClientInstance) {\n        const { paypalOptions, paymentMethod, container } = this._renderButtonsData as RenderButtonsData;\n        const { paypal } = this._window;\n        let updatedPaypalOptions: BraintreePaypalButtonInitializeOptions;\n\n        if (paypal) {\n            const FUNDING_SOURCES = [];\n            for (const fundingKey in paypal.FUNDING) {\n                if (paypal.FUNDING.hasOwnProperty(fundingKey)) {\n                    const skipCreditSource = (fundingKey === 'CREDIT' || fundingKey === 'PAYLATER') && !paypalOptions.allowCredit;\n                    if (fundingKey === 'CARD' || skipCreditSource) {\n                        continue;\n                    }\n                    FUNDING_SOURCES.push(fundingKey.toLowerCase());\n                }\n            }\n\n            if (paypalOptions) {\n                 updatedPaypalOptions = this._validateHeight(paypalOptions);\n            }\n\n            FUNDING_SOURCES.forEach(source => {\n                const button = paypal.Buttons({\n                    env: paymentMethod.config.testMode ? 'sandbox' : 'production',\n                    fundingSource: source,\n                    commit: false,\n                    style: {\n                        shape: 'rect',\n                        label: this._offerCredit ? 'credit' : undefined,\n                        ...pick(updatedPaypalOptions.style, 'layout', 'size', 'color', 'label', 'shape', 'tagline', 'fundingicons', 'height'),\n                    },\n                    createOrder: () => this._setupPayment(paypalCheckoutInstance, paypalOptions.shippingAddress, paypalOptions.onPaymentError),\n                    onApprove: (data: PaypalAuthorizeData) => this._tokenizePayment(data, paypalCheckoutInstance, paypalOptions.shouldProcessPayment, paypalOptions.onAuthorizeError),\n                });\n\n                if (button.isEligible()) {\n                    button.render(container);\n                }\n            });\n        }\n    }\n\n    deinitialize(): Promise<void> {\n        this._paymentMethod = undefined;\n        this._paypalCheckout = undefined;\n\n        this._braintreeSDKCreator.teardown();\n\n        return Promise.resolve();\n    }\n\n    private _validateHeight(paypalOptions: BraintreePaypalButtonInitializeOptions): BraintreePaypalButtonInitializeOptions {\n        const updatedPaypalOptions = {...paypalOptions};\n        const { style } = updatedPaypalOptions;\n        const { height } = style as PaypalButtonStyleOptions;\n\n        if (updatedPaypalOptions.style) {\n            if (typeof height === 'number') {\n                updatedPaypalOptions.style.height = height < 25\n                    ? 25\n                    : (height > 55 ? 55 : height);\n            } else {\n                delete updatedPaypalOptions.style.height;\n            }\n        }\n\n        return updatedPaypalOptions;\n    }\n\n    private _setupPayment(\n        paypalCheckoutInstance: PaypalClientInstance,\n        address?: Address | null,\n        onError?: (error: BraintreeError | StandardError) => void\n    ): Promise<string> {\n        return this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())\n            .then(state => {\n                const checkout = state.checkout.getCheckout();\n                const config = state.config.getStoreConfig();\n                const customer = state.customer.getCustomer();\n                const shippingAddress = address === undefined ?\n                    customer && customer.addresses && customer.addresses[0] :\n                    address;\n\n                if (!checkout) {\n                    throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n                }\n\n                if (!config) {\n                    throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n                }\n\n                return paypalCheckoutInstance.createPayment({\n                    flow: 'checkout',\n                    enableShippingAddress: true,\n                    shippingAddressEditable: false,\n                    shippingAddressOverride: shippingAddress ? this._mapToBraintreeAddress(shippingAddress) : undefined,\n                    amount: checkout?.outstandingBalance,\n                    currency: config?.currency.code,\n                    offerCredit: this._offerCredit,\n                });\n            })\n            .catch(error => {\n                if (onError) {\n                    onError(error);\n                }\n\n                throw error;\n            });\n    }\n\n    private _tokenizePayment(\n        data: PaypalAuthorizeData,\n        paypalCheckoutInstance: PaypalClientInstance,\n        shouldProcessPayment?: boolean,\n        onError?: (error: BraintreeError | StandardError) => void\n    ): Promise<BraintreeTokenizePayload> {\n        if (!this._paymentMethod || !paypalCheckoutInstance) {\n            throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n        }\n\n        const methodId = this._paymentMethod.id;\n\n        return Promise.all([\n            paypalCheckoutInstance.tokenizePayment(data),\n            this._braintreeSDKCreator.getDataCollector({ paypal: true }),\n        ])\n            .then(([payload, { deviceData }]) => {\n                this._formPoster.postForm('/checkout.php', {\n                    payment_type: 'paypal',\n                    provider: methodId,\n                    action: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n                    nonce: payload.nonce,\n                    device_data: deviceData,\n                    shipping_address: JSON.stringify(this._mapToLegacyShippingAddress(payload)),\n                    billing_address: JSON.stringify(this._mapToLegacyBillingAddress(payload)),\n                });\n\n                return payload;\n            })\n            .catch(error => {\n                if (onError) {\n                    onError(error);\n                }\n\n                throw error;\n            });\n    }\n\n    private _mapToLegacyShippingAddress(payload: BraintreeTokenizePayload): Partial<LegacyAddress> {\n        const shippingAddress = payload.details.shippingAddress;\n        const recipientName = shippingAddress && shippingAddress.recipientName || '';\n        const [firstName, lastName] = recipientName.split(' ');\n\n        return {\n            email: payload.details.email,\n            first_name: firstName,\n            last_name: lastName,\n            phone_number: payload.details.phone,\n            address_line_1: shippingAddress && shippingAddress.line1,\n            address_line_2: shippingAddress && shippingAddress.line2,\n            city: shippingAddress && shippingAddress.city,\n            state: shippingAddress && shippingAddress.state,\n            country_code: shippingAddress && shippingAddress.countryCode,\n            postal_code: shippingAddress && shippingAddress.postalCode,\n        };\n    }\n\n    private _mapToLegacyBillingAddress(payload: BraintreeTokenizePayload): Partial<LegacyAddress> {\n        const billingAddress = payload.details.billingAddress;\n        const shippingAddress = payload.details.shippingAddress;\n\n        if (billingAddress) {\n            return {\n                email: payload.details.email,\n                first_name: payload.details.firstName,\n                last_name: payload.details.lastName,\n                phone_number: payload.details.phone,\n                address_line_1: billingAddress.line1,\n                address_line_2: billingAddress.line2,\n                city: billingAddress.city,\n                state: billingAddress.state,\n                country_code: billingAddress.countryCode,\n                postal_code: billingAddress.postalCode,\n            };\n        }\n\n        return {\n            email: payload.details.email,\n            first_name: payload.details.firstName,\n            last_name: payload.details.lastName,\n            phone_number: payload.details.phone,\n            address_line_1: shippingAddress && shippingAddress.line1,\n            address_line_2: shippingAddress && shippingAddress.line2,\n            city: shippingAddress && shippingAddress.city,\n            state: shippingAddress && shippingAddress.state,\n            country_code: shippingAddress && shippingAddress.countryCode,\n            postal_code: shippingAddress && shippingAddress.postalCode,\n        };\n    }\n\n    private _mapToBraintreeAddress(address: Address): BraintreeShippingAddressOverride {\n        return {\n            line1: address.address1,\n            line2: address.address2,\n            city: address.city,\n            state: address.stateOrProvinceCode,\n            postalCode: address.postalCode,\n            countryCode: address.countryCode,\n            phone: address.phone,\n            recipientName: `${address.firstName} ${address.lastName}`,\n        };\n    }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { CheckoutActionCreator, CheckoutStore } from '../../../checkout';\nimport { InvalidArgumentError, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { bindDecorator as bind } from '../../../common/utility';\nimport { GooglePayPaymentProcessor } from '../../../payment/strategies/googlepay';\nimport { getShippableItemsCount } from '../../../shipping';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nimport { GooglePayButtonInitializeOptions } from './googlepay-button-options';\nexport default class GooglePayButtonStrategy implements CheckoutButtonStrategy {\n    private _methodId?: string;\n    private _walletButton?: HTMLElement;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _formPoster: FormPoster,\n        private _checkoutActionCreator: CheckoutActionCreator,\n        private _googlePayPaymentProcessor: GooglePayPaymentProcessor\n    ) {}\n\n    async initialize(options: CheckoutButtonInitializeOptions): Promise<void> {\n        const { containerId, methodId } = options;\n\n        const googlePayOptions = this._getGooglePayOptions(options);\n\n        if (!containerId || !methodId) {\n            throw new InvalidArgumentError('Unable to proceed because \"containerId\" argument is not provided.');\n        }\n\n        this._methodId = methodId;\n\n        await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n        await this._googlePayPaymentProcessor.initialize(this._getMethodId());\n\n        this._walletButton = this._createSignInButton(containerId, googlePayOptions);\n    }\n\n    deinitialize(): Promise<void> {\n        if (this._walletButton && this._walletButton.parentNode) {\n            this._walletButton.parentNode.removeChild(this._walletButton);\n            this._walletButton = undefined;\n        }\n\n        return this._googlePayPaymentProcessor.deinitialize();\n    }\n\n    private _createSignInButton(containerId: string, buttonOptions: GooglePayButtonInitializeOptions): HTMLElement {\n        const container = document.getElementById(containerId);\n        const { buttonType, buttonColor } = buttonOptions;\n\n        if (!container) {\n            throw new InvalidArgumentError('Unable to create sign-in button without valid container ID.');\n        }\n\n        const googlePayButton = this._googlePayPaymentProcessor.createButton(this._handleWalletButtonClick, buttonType, buttonColor);\n\n        container.appendChild(googlePayButton);\n\n        return googlePayButton;\n    }\n\n    private _getMethodId(): string {\n        if (!this._methodId) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        return this._methodId;\n    }\n\n    private _getGooglePayOptions(options: CheckoutButtonInitializeOptions): GooglePayButtonInitializeOptions {\n\n        if (options.methodId === 'googlepayadyenv2' && options.googlepayadyenv2) {\n            return options.googlepayadyenv2;\n        }\n\n        if (options.methodId === 'googlepayauthorizenet' && options.googlepayauthorizenet) {\n            return options.googlepayauthorizenet;\n        }\n\n        if (options.methodId === 'googlepaybraintree' && options.googlepaybraintree) {\n            return options.googlepaybraintree;\n        }\n\n        if (options.methodId === 'googlepaycheckoutcom' && options.googlepaycheckoutcom) {\n            return options.googlepaycheckoutcom;\n        }\n\n        if (options.methodId === 'googlepaycybersourcev2' && options.googlepaycybersourcev2) {\n            return options.googlepaycybersourcev2;\n        }\n\n        if (options.methodId === 'googlepayorbital' && options.googlepayorbital) {\n            return options.googlepayorbital;\n        }\n\n        if (options.methodId === 'googlepaystripe' && options.googlepaystripe) {\n            return options.googlepaystripe;\n        }\n\n        throw new InvalidArgumentError();\n    }\n\n    @bind\n    private async _handleWalletButtonClick(event: Event): Promise<void> {\n        event.preventDefault();\n        const cart = this._store.getState().cart.getCartOrThrow();\n        const hasPhysicalItems = getShippableItemsCount(cart) > 0;\n\n        try {\n            const paymentData = await this._googlePayPaymentProcessor.displayWallet();\n            await this._googlePayPaymentProcessor.handleSuccess(paymentData);\n            if (hasPhysicalItems && paymentData.shippingAddress) {\n                await this._googlePayPaymentProcessor.updateShippingAddress(paymentData.shippingAddress);\n            }\n            await this._onPaymentSelectComplete();\n        } catch (error) {\n            if (error && error.message !== 'CANCELED') {\n                throw error;\n            }\n        }\n    }\n\n    private _onPaymentSelectComplete(): void {\n        this._formPoster.postForm('/checkout.php', {\n            headers: {\n                Accept: 'text/html',\n                'Content-Type': 'application/x-www-form-urlencoded',\n            },\n        });\n    }\n}\n","import { CheckoutActionCreator, CheckoutStore } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { bindDecorator as bind } from '../../../common/utility';\nimport { getCallbackUrl, Masterpass, MasterpassCheckoutOptions, MasterpassScriptLoader } from '../../../payment/strategies/masterpass';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nexport default class MasterpassButtonStrategy implements CheckoutButtonStrategy {\n    private _masterpassClient?: Masterpass;\n    private _methodId?: string;\n    private _signInButton?: HTMLElement;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _checkoutActionCreator: CheckoutActionCreator,\n        private _masterpassScriptLoader: MasterpassScriptLoader\n    ) {}\n\n    initialize(options: CheckoutButtonInitializeOptions): Promise<void> {\n        const { containerId, methodId } = options;\n\n        if (!containerId || !methodId) {\n            throw new InvalidArgumentError('Unable to proceed because \"containerId\" argument is not provided.');\n        }\n\n        this._methodId = methodId;\n\n        return this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())\n            .then(state => {\n                const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n                const storeConfig = state.config.getStoreConfig();\n\n                if (!paymentMethod || !paymentMethod.initializationData.checkoutId) {\n                    throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n                }\n\n                if (!storeConfig) {\n                    throw new InvalidArgumentError('Unable to retrieve store configuration');\n                }\n\n                const masterpassScriptLoaderParams = {\n                    useMasterpassSrc: paymentMethod.initializationData.isMasterpassSrcEnabled,\n                    language: storeConfig.storeProfile.storeLanguage,\n                    testMode: paymentMethod.config.testMode,\n                    checkoutId: paymentMethod.initializationData.checkoutId,\n                };\n\n                return this._masterpassScriptLoader.load(masterpassScriptLoaderParams);\n            })\n            .then(masterpass => {\n                this._masterpassClient = masterpass;\n                this._signInButton = this._createSignInButton(containerId);\n            });\n    }\n\n    deinitialize(): Promise<void> {\n        if (this._signInButton && this._signInButton.parentNode) {\n            this._signInButton.removeEventListener('click', this._handleWalletButtonClick);\n            this._signInButton.parentNode.removeChild(this._signInButton);\n            this._signInButton = undefined;\n        }\n\n        return Promise.resolve();\n    }\n\n    private _createSignInButton(containerId: string): HTMLElement {\n        const buttonContainer = document.getElementById(containerId);\n        const state = this._store.getState();\n        const paymentMethod = this._methodId ? state.paymentMethods.getPaymentMethod(this._methodId) : null;\n        const storeConfig = state.config.getStoreConfig();\n\n        if (!buttonContainer) {\n            throw new Error('Need a container to place the button');\n        }\n\n        if (!paymentMethod) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        if (!storeConfig) {\n            throw new InvalidArgumentError('Unable to retrieve store configuration');\n        }\n\n        const button = document.createElement('input');\n\n        button.type = 'image';\n\n        if (paymentMethod.initializationData.isMasterpassSrcEnabled) {\n            const subdomain = paymentMethod.config.testMode ? 'sandbox.' : '';\n            const { storeLanguage } = storeConfig.storeProfile;\n            const { checkoutId } = paymentMethod.initializationData;\n\n            const params = [\n                `locale=${storeLanguage}`,\n                `paymentmethod=master,visa,amex,discover`,\n                `checkoutid=${checkoutId}`,\n            ];\n\n            button.src = [\n                `https://${subdomain}src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg`,\n                params.join('&'),\n            ].join('?');\n        } else {\n            button.src = 'https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg';\n        }\n\n        buttonContainer.appendChild(button);\n\n        button.addEventListener('click', this._handleWalletButtonClick);\n\n        return button;\n    }\n\n    private _createMasterpassPayload(): MasterpassCheckoutOptions {\n        const state = this._store.getState();\n        const checkout = state.checkout.getCheckout();\n        const paymentMethod = this._methodId ? state.paymentMethods.getPaymentMethod(this._methodId) : null;\n\n        if (!checkout) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n        }\n\n        if (!paymentMethod) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        return {\n            checkoutId: paymentMethod.initializationData.checkoutId,\n            allowedCardTypes: paymentMethod.initializationData.allowedCardTypes,\n            amount: checkout.cart.cartAmount.toString(),\n            currency: checkout.cart.currency.code,\n            cartId: checkout.cart.id,\n            callbackUrl: getCallbackUrl('cart'),\n        };\n    }\n\n    @bind\n    private _handleWalletButtonClick(): void {\n        if (!this._masterpassClient) {\n            throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n        }\n\n        this._masterpassClient.checkout(this._createMasterpassPayload());\n    }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { pick } from 'lodash';\n\nimport { CheckoutActionCreator, CheckoutStore } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType, StandardError } from '../../../common/error/errors';\nimport { INTERNAL_USE_ONLY } from '../../../common/http-request';\nimport { PaymentMethod } from '../../../payment';\nimport { PaypalActions, PaypalAuthorizeData, PaypalClientToken, PaypalScriptLoader } from '../../../payment/strategies/paypal';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nexport default class PaypalButtonStrategy implements CheckoutButtonStrategy {\n    private _paymentMethod?: PaymentMethod;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _checkoutActionCreator: CheckoutActionCreator,\n        private _paypalScriptLoader: PaypalScriptLoader,\n        private _formPoster: FormPoster,\n        private _host: string = ''\n    ) {}\n\n    initialize(options: CheckoutButtonInitializeOptions): Promise<void> {\n        const paypalOptions = options.paypal;\n        const state = this._store.getState();\n        const paymentMethod = this._paymentMethod = state.paymentMethods.getPaymentMethod(options.methodId);\n\n        if (!paypalOptions) {\n            throw new InvalidArgumentError();\n        }\n\n        if (!paymentMethod) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        return this._paypalScriptLoader.loadPaypal(paymentMethod.config.merchantId)\n            .then(paypal => {\n                if (!paymentMethod || !paymentMethod.config.merchantId) {\n                    throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n                }\n\n                const merchantId = paymentMethod.config.merchantId;\n                const env = paymentMethod.config.testMode ? 'sandbox' : 'production';\n                const clientToken: PaypalClientToken = { [env]: paypalOptions.clientId };\n\n                const allowedSources = [];\n                const disallowedSources = [];\n\n                if (paypalOptions.allowCredit) {\n                    allowedSources.push(paypal.FUNDING.CREDIT);\n                } else {\n                    disallowedSources.push(paypal.FUNDING.CREDIT);\n                }\n\n                return paypal.Button.render({\n                    env,\n                    client: clientToken,\n                    commit: paypalOptions.shouldProcessPayment,\n                    funding: {\n                        allowed: allowedSources,\n                        disallowed: disallowedSources,\n                    },\n                    style: {\n                        shape: 'rect',\n                        ...pick(paypalOptions.style, 'layout', 'color', 'label', 'shape', 'tagline', 'fundingicons'),\n                        size: (paymentMethod.id === 'paypalexpress' && paypalOptions.style?.size === 'small') ? 'responsive' : paypalOptions.style?.size,\n                    },\n                    payment: (_, actions) => this._setupPayment(merchantId, actions, paypalOptions.onPaymentError),\n                    onAuthorize: (data, actions) => this._tokenizePayment(data, actions, paypalOptions.shouldProcessPayment, paypalOptions.onAuthorizeError),\n                }, options.containerId);\n            });\n    }\n\n    deinitialize(): Promise<void> {\n        this._paymentMethod = undefined;\n\n        return Promise.resolve();\n    }\n\n    private _setupPayment(merchantId: string, actions?: PaypalActions, onError?: (error: StandardError) => void): Promise<string> {\n        if (!actions) {\n            throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n        }\n\n        return this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())\n            .then(state => {\n                const cart = state.cart.getCart();\n                const cartId = cart ? cart.id : '';\n\n                return actions.request.post(`${this._host}/api/storefront/payment/paypalexpress`, { merchantId, cartId }, {\n                    headers: {\n                        'X-API-INTERNAL': INTERNAL_USE_ONLY,\n                    },\n                });\n            })\n            .then(res => res.id)\n            .catch(error => {\n                if (onError) {\n                    onError(error);\n                }\n\n                throw error;\n            });\n    }\n\n    private _tokenizePayment(\n        data: PaypalAuthorizeData,\n        actions?: PaypalActions,\n        shouldProcessPayment?: boolean,\n        _onError?: (error: StandardError) => void // FIXME: This parameter seems to be unused\n    ): Promise<void> {\n        if (!this._paymentMethod) {\n            throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n        }\n\n        if (!actions) {\n            throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n        }\n\n        if (!data.paymentID || !data.payerID) {\n            throw new MissingDataError(MissingDataErrorType.MissingPayment);\n        }\n\n        const methodId = this._paymentMethod.id;\n\n        return actions.payment.get(data.paymentID).then(payload => {\n            this._formPoster.postForm('/checkout.php', {\n                payment_type: 'paypal',\n                provider: methodId,\n                action: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n                paymentId: data.paymentID,\n                payerId: data.payerID,\n                payerInfo: JSON.stringify(payload.payer.payer_info),\n            });\n        });\n    }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { Cart } from '../../../cart';\nimport { CheckoutActionCreator, CheckoutStore } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType } from '../../../common/error/errors';\nimport { ApproveDataOptions, ButtonsOptions, ClickDataOptions, DisableFundingType, PaypalCommerceInitializationData, PaypalCommercePaymentProcessor, PaypalCommerceScriptParams } from '../../../payment/strategies/paypal-commerce';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nexport default class PaypalCommerceButtonStrategy implements CheckoutButtonStrategy {\n    private _isCredit?: boolean;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _checkoutActionCreator: CheckoutActionCreator,\n        private _formPoster: FormPoster,\n        private _paypalCommercePaymentProcessor: PaypalCommercePaymentProcessor\n    ) {}\n\n    async initialize(options: CheckoutButtonInitializeOptions): Promise<void> {\n        let state = this._store.getState();\n        const { initializationData } = state.paymentMethods.getPaymentMethodOrThrow(options.methodId);\n\n        if (!initializationData.clientId) {\n            throw new InvalidArgumentError();\n        }\n\n        state = await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n        const cart = state.cart.getCartOrThrow();\n        const buttonParams: ButtonsOptions = {\n            onApprove: data => this._tokenizePayment(data),\n            onClick: data => this._handleClickButtonProvider(data),\n        };\n\n        if (options.paypalCommerce && options.paypalCommerce.style) {\n            buttonParams.style = options.paypalCommerce.style;\n        }\n\n        const messagingContainer = options.paypalCommerce?.messagingContainer;\n        const isMessagesAvailable = Boolean(messagingContainer && document.getElementById(messagingContainer));\n\n        await this._paypalCommercePaymentProcessor.initialize(this._getParamsScript(initializationData, cart));\n\n        this._paypalCommercePaymentProcessor.renderButtons(cart.id, `#${options.containerId}`, buttonParams);\n\n        if (isMessagesAvailable) {\n            this._paypalCommercePaymentProcessor.renderMessages(cart.cartAmount, `#${messagingContainer}`);\n        }\n\n        return Promise.resolve();\n    }\n\n    deinitialize(): Promise<void> {\n        this._isCredit = undefined;\n\n        return Promise.resolve();\n    }\n\n    private _handleClickButtonProvider({ fundingSource }: ClickDataOptions): void {\n        this._isCredit = fundingSource === 'credit' || fundingSource === 'paylater';\n    }\n\n    private _tokenizePayment({ orderID }: ApproveDataOptions) {\n        if (!orderID) {\n            throw new MissingDataError(MissingDataErrorType.MissingPayment);\n        }\n\n        return this._formPoster.postForm('/checkout.php', {\n            payment_type: 'paypal',\n            action: 'set_external_checkout',\n            provider: this._isCredit ? 'paypalcommercecredit' : 'paypalcommerce',\n            order_id: orderID,\n        });\n    }\n\n    private _getParamsScript(initializationData: PaypalCommerceInitializationData, cart: Cart): PaypalCommerceScriptParams {\n        const { clientId, intent, isPayPalCreditAvailable, merchantId, attributionId } = initializationData;\n        const disableFunding: DisableFundingType = [ 'card' ];\n\n        if (!isPayPalCreditAvailable) {\n            disableFunding.push('credit');\n        }\n\n        return {\n            'client-id': clientId,\n            'merchant-id': merchantId,\n            commit: false,\n            currency: cart.currency.code,\n            components: ['buttons', 'messages'],\n            'disable-funding': disableFunding,\n            intent,\n            'data-partner-attribution-id': attributionId,\n        };\n    }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { createCheckoutStore } from '../checkout';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\n\nimport CheckoutButtonInitializer from './checkout-button-initializer';\nimport CheckoutButtonInitializerOptions from './checkout-button-initializer-options';\nimport CheckoutButtonStrategyActionCreator from './checkout-button-strategy-action-creator';\nimport createCheckoutButtonRegistry from './create-checkout-button-registry';\n\n/**\n * Creates an instance of `CheckoutButtonInitializer`.\n *\n * @remarks\n * ```js\n * const initializer = createCheckoutButtonInitializer();\n *\n * initializer.initializeButton({\n *     methodId: 'braintreepaypal',\n *     braintreepaypal: {\n *         container: '#checkoutButton',\n *     },\n * });\n * ```\n *\n * @alpha\n * Please note that `CheckoutButtonInitializer` is currently in an early stage\n * of development. Therefore the API is unstable and not ready for public\n * consumption.\n *\n * @param options - A set of construction options.\n * @returns an instance of `CheckoutButtonInitializer`.\n */\nexport default function createCheckoutButtonInitializer(\n    options?: CheckoutButtonInitializerOptions\n): CheckoutButtonInitializer {\n    const host = options && options.host;\n    const store = createCheckoutStore();\n    const requestSender = createRequestSender({ host });\n    const formPoster = createFormPoster({ host });\n\n    return new CheckoutButtonInitializer(\n        store,\n        new CheckoutButtonStrategyActionCreator(\n            createCheckoutButtonRegistry(store, requestSender, formPoster, host),\n            new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender))\n        )\n    );\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { CheckoutActionCreator, CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { createAmazonPayV2PaymentProcessor } from '../payment/strategies/amazon-pay-v2';\nimport { BraintreeScriptLoader, BraintreeSDKCreator } from '../payment/strategies/braintree';\nimport { createGooglePayPaymentProcessor, GooglePayAdyenV2Initializer, GooglePayAuthorizeNetInitializer, GooglePayBraintreeInitializer, GooglePayCheckoutcomInitializer, GooglePayCybersourceV2Initializer, GooglePayStripeInitializer } from '../payment/strategies/googlepay';\nimport { MasterpassScriptLoader } from '../payment/strategies/masterpass';\nimport { PaypalScriptLoader } from '../payment/strategies/paypal';\nimport { createPaypalCommercePaymentProcessor } from '../payment/strategies/paypal-commerce';\n\nimport { CheckoutButtonMethodType, CheckoutButtonStrategy } from './strategies';\nimport { AmazonPayV2ButtonStrategy } from './strategies/amazon-pay-v2';\nimport { BraintreePaypalButtonStrategy } from './strategies/braintree';\nimport { GooglePayButtonStrategy } from './strategies/googlepay';\nimport { MasterpassButtonStrategy } from './strategies/masterpass';\nimport { PaypalButtonStrategy } from './strategies/paypal';\nimport { PaypalCommerceButtonStrategy } from './strategies/paypal-commerce';\n\nexport default function createCheckoutButtonRegistry(\n    store: CheckoutStore,\n    requestSender: RequestSender,\n    formPoster: FormPoster,\n    host?: string\n): Registry<CheckoutButtonStrategy, CheckoutButtonMethodType> {\n    const registry = new Registry<CheckoutButtonStrategy, CheckoutButtonMethodType>();\n    const scriptLoader = getScriptLoader();\n    const checkoutActionCreator = new CheckoutActionCreator(\n        new CheckoutRequestSender(requestSender),\n        new ConfigActionCreator(new ConfigRequestSender(requestSender)),\n        new FormFieldsActionCreator(new FormFieldsRequestSender(requestSender))\n    );\n    const paypalCommercePaymentProcessor = createPaypalCommercePaymentProcessor(scriptLoader, requestSender);\n\n    registry.register(CheckoutButtonMethodType.BRAINTREE_PAYPAL, () =>\n        new BraintreePaypalButtonStrategy(\n            store,\n            checkoutActionCreator,\n            new BraintreeSDKCreator(new BraintreeScriptLoader(scriptLoader)),\n            formPoster,\n            undefined,\n            window\n        )\n    );\n\n    registry.register(CheckoutButtonMethodType.BRAINTREE_PAYPAL_CREDIT, () =>\n        new BraintreePaypalButtonStrategy(\n            store,\n            checkoutActionCreator,\n            new BraintreeSDKCreator(new BraintreeScriptLoader(scriptLoader)),\n            formPoster,\n            true,\n            window\n        )\n    );\n\n    registry.register(CheckoutButtonMethodType.MASTERPASS, () =>\n        new MasterpassButtonStrategy(\n            store,\n            checkoutActionCreator,\n            new MasterpassScriptLoader(scriptLoader)\n        ));\n\n    registry.register(CheckoutButtonMethodType.GOOGLEPAY_ADYENV2, () =>\n        new GooglePayButtonStrategy(\n            store,\n            formPoster,\n            checkoutActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayAdyenV2Initializer()\n            )\n        )\n    );\n\n    registry.register(CheckoutButtonMethodType.GOOGLEPAY_AUTHORIZENET, () =>\n        new GooglePayButtonStrategy(\n            store,\n            formPoster,\n            checkoutActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayAuthorizeNetInitializer()\n            )\n        )\n    );\n\n    registry.register(CheckoutButtonMethodType.GOOGLEPAY_BRAINTREE, () =>\n        new GooglePayButtonStrategy(\n            store,\n            formPoster,\n            checkoutActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayBraintreeInitializer(\n                    new BraintreeSDKCreator(\n                        new BraintreeScriptLoader(scriptLoader)\n                    )\n                )\n            )\n        )\n    );\n\n    registry.register(CheckoutButtonMethodType.GOOGLEPAY_CHECKOUTCOM, () =>\n        new GooglePayButtonStrategy(\n            store,\n            formPoster,\n            checkoutActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayCheckoutcomInitializer(requestSender)\n            )\n        )\n    );\n\n    registry.register(CheckoutButtonMethodType.GOOGLEPAY_CYBERSOURCEV2, () =>\n        new GooglePayButtonStrategy(\n            store,\n            formPoster,\n            checkoutActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayCybersourceV2Initializer()\n            )\n        )\n    );\n\n    registry.register(CheckoutButtonMethodType.GOOGLEPAY_ORBITAL, () =>\n        new GooglePayButtonStrategy(\n            store,\n            formPoster,\n            checkoutActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayCybersourceV2Initializer()\n            )\n        )\n    );\n\n    registry.register(CheckoutButtonMethodType.GOOGLEPAY_STRIPE, () =>\n        new GooglePayButtonStrategy(\n            store,\n            formPoster,\n            checkoutActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayStripeInitializer()\n            )\n        )\n    );\n\n    registry.register(CheckoutButtonMethodType.PAYPALEXPRESS, () =>\n        new PaypalButtonStrategy(\n            store,\n            checkoutActionCreator,\n            new PaypalScriptLoader(scriptLoader),\n            formPoster,\n            host\n        )\n    );\n\n    registry.register(CheckoutButtonMethodType.PAYPALCOMMERCE, () =>\n        new PaypalCommerceButtonStrategy(\n            store,\n            checkoutActionCreator,\n            formPoster,\n            paypalCommercePaymentProcessor\n        )\n    );\n\n    registry.register(CheckoutButtonMethodType.AMAZON_PAY_V2, () =>\n        new AmazonPayV2ButtonStrategy(\n            store,\n            checkoutActionCreator,\n            createAmazonPayV2PaymentProcessor()\n        )\n    );\n\n    return registry;\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport enum NotEmbeddableErrorType {\n    MissingContainer = 'missing_container',\n    MissingContent = 'missing_content',\n    UnknownError = 'unknown_error',\n}\n\n/**\n * Throw this error if we are not able to embed the checkout form as an iframe.\n * This can be due to the fact that the provided container ID is invalid, or the\n * checkout form fails to load inside the iframe. It can also be due to an\n * unknown reason.\n */\nexport default class NotEmbeddableError extends StandardError {\n    constructor(\n        message?: string,\n        public subtype: NotEmbeddableErrorType = NotEmbeddableErrorType.UnknownError\n    ) {\n        super(message || 'Unable to embed the checkout form.');\n\n        this.name = 'NotEmbeddableError';\n        this.type = 'not_embeddable';\n    }\n}\n","import { default as storage } from 'local-storage-fallback';\n\nexport default class BrowserStorage {\n    constructor(\n        private _namespace: string\n    ) {}\n\n    getItem<TValue = any>(key: string): TValue | null {\n        const rawValue = storage.getItem(this.withNamespace(key));\n\n        if (rawValue === null) {\n            return null;\n        }\n\n        try {\n            return JSON.parse(rawValue);\n        } catch (error) {\n            // Clean up invalid values\n            this.removeItem(this.withNamespace(key));\n\n            return null;\n        }\n    }\n\n    getItemOnce<TValue = any>(key: string): TValue | null {\n        const value = this.getItem(key);\n\n        this.removeItem(key);\n\n        return value;\n    }\n\n    setItem<TValue = any>(key: string, value: TValue): void {\n        return storage.setItem(this.withNamespace(key), JSON.stringify(value));\n    }\n\n    removeItem(key: string): void {\n        return storage.removeItem(this.withNamespace(key));\n    }\n\n    private withNamespace(key: string): string {\n        return `${this._namespace}.${key}`;\n    }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { InternalErrorResponseBody } from '../../common/error';\nimport { RequestError } from '../../common/error/errors';\n\n/**\n * Throw this error we are not able to sign in a shopper because the provided\n * login token is invalid.\n */\nexport default class InvalidLoginTokenError extends RequestError {\n    constructor(response: Response<InternalErrorResponseBody>) {\n        super(response, { message: response.body.title });\n\n        this.name = 'InvalidLoginTokenError';\n        this.type = 'invalid_login_token';\n    }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { IframeEventListener, IframeEventPoster, IFrameComponent } from '../common/iframe';\nimport { LoadingIndicator } from '../common/loading-indicator';\nimport { BrowserStorage } from '../common/storage';\nimport { parseUrl } from '../common/url';\nimport { bindDecorator as bind } from '../common/utility';\n\nimport EmbeddedCheckoutError from './embedded-checkout-error';\nimport { EmbeddedCheckoutEventMap, EmbeddedCheckoutEventType } from './embedded-checkout-events';\nimport EmbeddedCheckoutOptions from './embedded-checkout-options';\nimport { InvalidLoginTokenError, NotEmbeddableError, NotEmbeddableErrorType } from './errors';\nimport { EmbeddedContentEvent, EmbeddedContentEventType } from './iframe-content';\nimport ResizableIframeCreator from './resizable-iframe-creator';\n\nexport const ALLOW_COOKIE_ATTEMPT_INTERVAL = 10 * 60 * 1000;\nexport const IS_COOKIE_ALLOWED_KEY = 'isCookieAllowed';\nexport const LAST_ALLOW_COOKIE_ATTEMPT_KEY = 'lastAllowCookieAttempt';\n\n@bind\nexport default class EmbeddedCheckout {\n    private _iframe?: IFrameComponent;\n    private _isAttached: boolean;\n\n    /**\n     * @internal\n     */\n    constructor(\n        private _iframeCreator: ResizableIframeCreator,\n        private _messageListener: IframeEventListener<EmbeddedCheckoutEventMap>,\n        private _messagePoster: IframeEventPoster<EmbeddedContentEvent>,\n        private _loadingIndicator: LoadingIndicator,\n        private _requestSender: RequestSender,\n        private _storage: BrowserStorage,\n        private _location: Location,\n        private _options: EmbeddedCheckoutOptions\n    ) {\n        this._isAttached = false;\n\n        if (this._options.onComplete) {\n            this._messageListener.addListener(EmbeddedCheckoutEventType.CheckoutComplete, this._options.onComplete);\n        }\n\n        if (this._options.onError) {\n            this._messageListener.addListener(EmbeddedCheckoutEventType.CheckoutError, this._options.onError);\n        }\n\n        if (this._options.onLoad) {\n            this._messageListener.addListener(EmbeddedCheckoutEventType.CheckoutLoaded, this._options.onLoad);\n        }\n\n        if (this._options.onFrameLoad) {\n            this._messageListener.addListener(EmbeddedCheckoutEventType.FrameLoaded, this._options.onFrameLoad);\n        }\n\n        if (this._options.onSignOut) {\n            this._messageListener.addListener(EmbeddedCheckoutEventType.SignedOut, this._options.onSignOut);\n        }\n\n        this._messageListener.addListener(EmbeddedCheckoutEventType.FrameLoaded, () => this._configureStyles());\n    }\n\n    attach(): Promise<this> {\n        if (this._isAttached) {\n            return Promise.resolve(this);\n        }\n\n        this._isAttached = true;\n        this._messageListener.listen();\n        this._loadingIndicator.show(this._options.containerId);\n\n        return this._allowCookie()\n            .then(() => this._attemptLogin())\n            .then(url => this._iframeCreator.createFrame(url, this._options.containerId))\n            .then(iframe => {\n                this._iframe = iframe;\n\n                this._configureStyles();\n                this._loadingIndicator.hide();\n            })\n            .catch(error => {\n                this._isAttached = false;\n\n                return this._retryAllowCookie(error)\n                    .catch(() => {\n                        this._messageListener.trigger({\n                            type: EmbeddedCheckoutEventType.FrameError,\n                            payload: error,\n                        });\n\n                        this._loadingIndicator.hide();\n\n                        throw error;\n                    });\n            })\n            .then(() => this);\n    }\n\n    detach(): void {\n        if (!this._isAttached) {\n            return;\n        }\n\n        this._isAttached = false;\n        this._messageListener.stopListen();\n\n        if (this._iframe && this._iframe.parentNode) {\n            this._iframe.parentNode.removeChild(this._iframe);\n            this._iframe.iFrameResizer.close();\n        }\n    }\n\n    private _configureStyles(): void {\n        if (!this._iframe || !this._iframe.contentWindow || !this._options.styles) {\n            return;\n        }\n\n        this._messagePoster.setTarget(this._iframe.contentWindow);\n\n        this._messagePoster.post({\n            type: EmbeddedContentEventType.StyleConfigured,\n            payload: this._options.styles,\n        });\n    }\n\n    private _attemptLogin(): Promise<string> {\n        if (!/^\\/login\\/token/.test(parseUrl(this._options.url).pathname)) {\n            return Promise.resolve(this._options.url);\n        }\n\n        return this._requestSender.post<{ redirectUrl: string }>(this._options.url)\n            .then(({ body: { redirectUrl } }) => redirectUrl)\n            .catch(response => Promise.reject(new InvalidLoginTokenError(response)));\n    }\n\n    /**\n     * This workaround is required for certain browsers (namely Safari) that\n     * prevent session cookies to be set for a third party website unless the\n     * user has recently visited such website. Therefore, before we attempt to\n     * login or set an active cart in the session, we need to first redirect the\n     * user to the domain of Embedded Checkout.\n     */\n    private _allowCookie(): Promise<void> {\n        if (this._storage.getItem(IS_COOKIE_ALLOWED_KEY)) {\n            return Promise.resolve();\n        }\n\n        this._storage.setItem(IS_COOKIE_ALLOWED_KEY, true);\n\n        // It could be possible that the flag is set to true but the browser has\n        // already removed the permission to store third-party cookies. In that\n        // case, we should try to redirect the user again. But we only want to\n        // do it once within a fixed interval. This is to avoid getting into a\n        // redirect loop if the shopper actually doesn't have a valid card\n        // session.\n        this._storage.setItem(LAST_ALLOW_COOKIE_ATTEMPT_KEY, Date.now());\n\n        const { origin } = parseUrl(this._options.url);\n        const redirectUrl = `${origin}/embedded-checkout/allow-cookie?returnUrl=${encodeURIComponent(this._location.href)}`;\n\n        document.body.style.visibility = 'hidden';\n        this._location.replace(redirectUrl);\n\n        return new Promise<never>(() => {});\n    }\n\n    private _retryAllowCookie(error: EmbeddedCheckoutError): Promise<void> {\n        const lastAttempt = Number(this._storage.getItem(LAST_ALLOW_COOKIE_ATTEMPT_KEY));\n        const canRetry = (\n            (!lastAttempt || Date.now() - lastAttempt > ALLOW_COOKIE_ATTEMPT_INTERVAL) &&\n            error instanceof NotEmbeddableError &&\n            error.subtype === NotEmbeddableErrorType.MissingContent\n        );\n\n        if (!canRetry) {\n            return Promise.reject();\n        }\n\n        this._storage.removeItem(LAST_ALLOW_COOKIE_ATTEMPT_KEY);\n        this._storage.removeItem(IS_COOKIE_ALLOWED_KEY);\n\n        return this._allowCookie();\n    }\n}\n","import { iframeResizer, isIframeEvent, IFrameComponent } from '../common/iframe';\nimport { parseUrl } from '../common/url';\n\nimport { EmbeddedCheckoutEventType } from './embedded-checkout-events';\nimport { NotEmbeddableError, NotEmbeddableErrorType } from './errors';\n\nexport default class ResizableIframeCreator {\n    constructor(\n        private _options?: { timeout: number }\n    ) {}\n\n    createFrame(src: string, containerId: string): Promise<IFrameComponent> {\n        const container = document.getElementById(containerId);\n        const { timeout = 60000 } = this._options || {};\n\n        if (!container) {\n            throw new NotEmbeddableError(\n                'Unable to embed the iframe because the container element could not be found.',\n                NotEmbeddableErrorType.MissingContainer\n            );\n        }\n\n        const iframe = document.createElement('iframe');\n\n        iframe.src = src;\n        iframe.style.border = 'none';\n        iframe.style.display = 'none';\n        iframe.style.width = '100%';\n        iframe.allowPaymentRequest = true;\n\n        container.appendChild(iframe);\n\n        return this._toResizableFrame(iframe, timeout)\n            .catch(error => {\n                container.removeChild(iframe);\n\n                throw error;\n            });\n    }\n\n    private _toResizableFrame(iframe: HTMLIFrameElement, timeoutInterval: number): Promise<IFrameComponent> {\n        // Can't simply listen to `load` event because it always gets triggered even if there's an error.\n        // Instead, listen to the `load` inside the iframe and let the parent frame know when it happens.\n        return new Promise((resolve, reject) => {\n            const timeout = window.setTimeout(() => {\n                reject(new NotEmbeddableError('Unable to embed the iframe because the content could not be loaded.'));\n            }, timeoutInterval);\n\n            const handleMessage = (event: MessageEvent) => {\n                if (event.origin !== parseUrl(iframe.src).origin) {\n                    return;\n                }\n\n                if (isIframeEvent(event.data, EmbeddedCheckoutEventType.FrameError)) {\n                    teardown();\n                    reject(new NotEmbeddableError(event.data.payload.message, NotEmbeddableErrorType.MissingContent));\n                }\n\n                if (isIframeEvent(event.data, EmbeddedCheckoutEventType.FrameLoaded)) {\n                    iframe.style.display = '';\n\n                    const contentId = event.data.payload && event.data.payload.contentId;\n                    const iframes = iframeResizer({\n                        scrolling: false,\n                        sizeWidth: false,\n                        heightCalculationMethod: contentId ? 'taggedElement' : 'lowestElement',\n                    }, iframe);\n\n                    teardown();\n                    resolve(iframes[iframes.length - 1]);\n                }\n            };\n\n            const teardown = () => {\n                window.removeEventListener('message', handleMessage);\n                window.clearTimeout(timeout);\n            };\n\n            window.addEventListener('message', handleMessage);\n        });\n    }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { LoadingIndicator } from '../common/loading-indicator';\nimport { BrowserStorage } from '../common/storage';\nimport { parseUrl } from '../common/url';\n\nimport EmbeddedCheckout from './embedded-checkout';\nimport { EmbeddedCheckoutEventMap } from './embedded-checkout-events';\nimport EmbeddedCheckoutOptions from './embedded-checkout-options';\nimport { EmbeddedContentEvent } from './iframe-content';\nimport ResizableIframeCreator from './resizable-iframe-creator';\n\nconst STORAGE_PREFIX = 'BigCommerce.EmbeddedCheckout';\n\n/**\n * Embed the checkout form in an iframe.\n *\n * @remarks\n * Once the iframe is embedded, it will automatically resize according to the\n * size of the checkout form. It will also notify the parent window when certain\n * events have occurred. i.e.: when the form is loaded and ready to be used.\n *\n * ```js\n * embedCheckout({\n *     url: 'https://checkout/url',\n *     containerId: 'container-id',\n * });\n * ```\n *\n * @param options - Options for embedding the checkout form.\n * @returns A promise that resolves to an instance of `EmbeddedCheckout`.\n */\nexport default function embedCheckout(options: EmbeddedCheckoutOptions): Promise<EmbeddedCheckout> {\n    const origin = parseUrl(options.url).origin;\n    const embeddedCheckout = new EmbeddedCheckout(\n        new ResizableIframeCreator(),\n        new IframeEventListener<EmbeddedCheckoutEventMap>(origin),\n        new IframeEventPoster<EmbeddedContentEvent>(origin),\n        new LoadingIndicator({ styles: options.styles && options.styles.loadingIndicator }),\n        createRequestSender(),\n        new BrowserStorage(STORAGE_PREFIX),\n        window.location,\n        options\n    );\n\n    return embeddedCheckout.attach();\n}\n","import { EmbeddedCheckoutFrameLoadedEvent } from '../embedded-checkout-events';\n\nexport default function handleFrameLoadedEvent(message: EmbeddedCheckoutFrameLoadedEvent): void {\n    if (!message.payload || !message.payload.contentId) {\n        return;\n    }\n\n    const body = document.getElementById(message.payload.contentId);\n\n    if (!body || body.hasAttribute('data-iframe-height')) {\n        return;\n    }\n\n    body.setAttribute('data-iframe-height', '');\n}\n","export default interface CustomError extends Error {\n    message: string;\n    type: string;\n    subtype?: string;\n}\n\nexport function isCustomError(error: any): error is CustomError {\n    return (\n        typeof error.message === 'string' &&\n        typeof error.type === 'string' &&\n        (typeof error.subtype === 'string' || !error.subtype) &&\n        error instanceof Error\n    );\n}\n","import { isCustomError, CustomError } from '../../common/error/errors';\nimport { IframeEventListener, IframeEventPoster } from '../../common/iframe';\nimport { bindDecorator as bind } from '../../common/utility';\nimport EmbeddedCheckoutError from '../embedded-checkout-error';\nimport { EmbeddedCheckoutCompleteEvent, EmbeddedCheckoutErrorEvent, EmbeddedCheckoutEvent, EmbeddedCheckoutEventMap, EmbeddedCheckoutEventType, EmbeddedCheckoutFrameErrorEvent, EmbeddedCheckoutFrameLoadedEvent, EmbeddedCheckoutLoadedEvent, EmbeddedCheckoutSignedOutEvent } from '../embedded-checkout-events';\nimport EmbeddedCheckoutStyles from '../embedded-checkout-styles';\n\nimport EmbeddedCheckoutMessenger from './embedded-checkout-messenger';\nimport { EmbeddedContentEventMap, EmbeddedContentEventType } from './embedded-content-events';\nimport EmbeddedContentOptions from './embedded-content-options';\n\n@bind\nexport default class IframeEmbeddedCheckoutMessenger implements EmbeddedCheckoutMessenger {\n    /**\n     * @internal\n     */\n    constructor(\n        private _messageListener: IframeEventListener<EmbeddedContentEventMap>,\n        private _messagePoster: IframeEventPoster<EmbeddedCheckoutEvent>,\n        private _untargetedMessagePoster: IframeEventPoster<EmbeddedCheckoutEvent>,\n        private _messageHandlers: EventCallbacks<EmbeddedCheckoutEventMap> = {}\n    ) {\n        this._messageListener.listen();\n    }\n\n    postComplete(): void {\n        const message: EmbeddedCheckoutCompleteEvent = {\n            type: EmbeddedCheckoutEventType.CheckoutComplete,\n        };\n\n        this._postMessage(message);\n    }\n\n    postError(payload: Error | CustomError): void {\n        const message: EmbeddedCheckoutErrorEvent = {\n            type: EmbeddedCheckoutEventType.CheckoutError,\n            payload: this._transformError(payload),\n        };\n\n        this._postMessage(message);\n    }\n\n    postFrameError(payload: Error | CustomError): void {\n        const message: EmbeddedCheckoutFrameErrorEvent = {\n            type: EmbeddedCheckoutEventType.FrameError,\n            payload: this._transformError(payload),\n        };\n\n        // Ideally, all messages should be targeted at a specific origin.\n        // However, for `FrameError` message, we have to post it in an\n        // untargeted fashion. This is because the error could be caused by a\n        // missing cart. That makes it not possible to determine of site origin\n        // of the parent window. Nevertheless, we still want to notify the\n        // parent window about the error.\n        this._postMessage(message, { untargeted: true });\n    }\n\n    postFrameLoaded(payload?: EmbeddedContentOptions): void {\n        const message: EmbeddedCheckoutFrameLoadedEvent = {\n            type: EmbeddedCheckoutEventType.FrameLoaded,\n            payload,\n        };\n\n        this._postMessage(message);\n    }\n\n    postLoaded(): void {\n        const message: EmbeddedCheckoutLoadedEvent = {\n            type: EmbeddedCheckoutEventType.CheckoutLoaded,\n        };\n\n        this._postMessage(message);\n    }\n\n    postSignedOut(): void {\n        const message: EmbeddedCheckoutSignedOutEvent = {\n            type: EmbeddedCheckoutEventType.SignedOut,\n        };\n\n        this._postMessage(message);\n    }\n\n    receiveStyles(handler: (styles: EmbeddedCheckoutStyles) => void): void {\n        this._messageListener.addListener(EmbeddedContentEventType.StyleConfigured, ({ payload }) => {\n            handler(payload);\n        });\n    }\n\n    private _postMessage(message: EmbeddedCheckoutEvent, options?: { untargeted?: boolean }): void {\n        this._notifyMessageHandlers(message);\n\n        if (options && options.untargeted) {\n            return this._untargetedMessagePoster.post(message);\n        }\n\n        this._messagePoster.post(message);\n    }\n\n    private _notifyMessageHandlers(message: EmbeddedCheckoutEvent): void {\n        Object.keys(this._messageHandlers)\n            .forEach(key => {\n                if (message.type !== key) {\n                    return;\n                }\n\n                const handler = this._messageHandlers[key];\n\n                if (handler) {\n                    (handler as (event: EmbeddedCheckoutEvent) => void).call(null, message);\n                }\n            });\n    }\n\n    private _transformError(error: Error | CustomError): EmbeddedCheckoutError {\n        return {\n            message: error.message,\n            type: isCustomError(error) ? error.type : undefined,\n            subtype: isCustomError(error) ? error.subtype : undefined,\n        };\n    }\n}\n\nexport type EventCallbacks<TEventMap> = {\n    [key in keyof TEventMap]?: (event: TEventMap[key]) => void;\n};\n","import { bindDecorator as bind } from '../../common/utility';\n\nimport EmbeddedCheckoutMessenger from './embedded-checkout-messenger';\n\n@bind\nexport default class NoopEmbeddedCheckoutMessenger implements EmbeddedCheckoutMessenger {\n    postComplete(): void {}\n\n    postError(): void {}\n\n    postFrameError(): void {}\n\n    postFrameLoaded(): void {}\n\n    postLoaded(): void {}\n\n    postSignedOut(): void {}\n\n    receiveStyles(): void {}\n}\n","import { setupContentWindowForIframeResizer, IframeEventListener, IframeEventPoster } from '../../common/iframe';\nimport { EmbeddedCheckoutEvent, EmbeddedCheckoutEventType } from '../embedded-checkout-events';\n\nimport EmbeddedCheckoutMessenger from './embedded-checkout-messenger';\nimport EmbeddedCheckoutMessengerOptions from './embedded-checkout-messenger-options';\nimport { EmbeddedContentEventMap } from './embedded-content-events';\nimport handleFrameLoadedEvent from './handle-frame-loaded-event';\nimport IframeEmbeddedCheckoutMessenger from './iframe-embedded-checkout-messenger';\nimport NoopEmbeddedCheckoutMessenger from './noop-embedded-checkout-messenger';\n\n/**\n * Create an instance of `EmbeddedCheckoutMessenger`.\n *\n * @remarks\n * The object is responsible for posting messages to the parent window from the\n * iframe when certain events have occurred. For example, when the checkout\n * form is first loaded, you should notify the parent window about it.\n *\n * The iframe can only be embedded in domains that are allowed by the store.\n *\n * ```ts\n * const messenger = createEmbeddedCheckoutMessenger({\n *     parentOrigin: 'https://some/website',\n * });\n *\n * messenger.postFrameLoaded();\n * ```\n *\n * @alpha\n * Please note that this feature is currently in an early stage of development.\n * Therefore the API is unstable and not ready for public consumption.\n *\n * @param options - Options for creating `EmbeddedCheckoutMessenger`\n * @returns - An instance of `EmbeddedCheckoutMessenger`\n */\nexport default function createEmbeddedCheckoutMessenger(options: EmbeddedCheckoutMessengerOptions): EmbeddedCheckoutMessenger {\n    setupContentWindowForIframeResizer();\n\n    const parentWindow = options.parentWindow || window.parent;\n\n    // Return a No-op messenger if it is not called inside an iframe\n    if (window === parentWindow) {\n        return new NoopEmbeddedCheckoutMessenger();\n    }\n\n    return new IframeEmbeddedCheckoutMessenger(\n        new IframeEventListener<EmbeddedContentEventMap>(options.parentOrigin),\n        new IframeEventPoster<EmbeddedCheckoutEvent>(options.parentOrigin, parentWindow),\n        new IframeEventPoster<EmbeddedCheckoutEvent>('*', parentWindow),\n        { [EmbeddedCheckoutEventType.FrameLoaded]: handleFrameLoadedEvent }\n    );\n}\n","export interface RootCacheKeyMap {\n    maps: ChildCacheKeyMap[];\n}\n\nexport interface IntermediateCacheKeyMap {\n    maps: ChildCacheKeyMap[];\n    parentMap: RootCacheKeyMap | IntermediateCacheKeyMap;\n    usedCount: number;\n    value: any;\n}\n\nexport interface TerminalCacheKeyMap extends IntermediateCacheKeyMap {\n    cacheKey: string;\n}\n\nexport type ChildCacheKeyMap = IntermediateCacheKeyMap | TerminalCacheKeyMap;\n\nexport function isTerminalCacheKeyMap(map: ChildCacheKeyMap): map is TerminalCacheKeyMap {\n    return map.hasOwnProperty('cacheKey');\n}\n\nexport function isRootCacheKeyMap(map: RootCacheKeyMap | ChildCacheKeyMap): map is RootCacheKeyMap {\n    return map.hasOwnProperty('parentMap');\n}\n","import { noop } from 'lodash';\nimport shallowEqual from 'shallowequal';\n\nimport { isRootCacheKeyMap, isTerminalCacheKeyMap, ChildCacheKeyMap, IntermediateCacheKeyMap, RootCacheKeyMap, TerminalCacheKeyMap } from './cache-key-maps';\n\nexport interface CacheKeyResolverOptions {\n    maxSize?: number;\n    onExpire?(key: string): void;\n    isEqual?(valueA: any, valueB: any): boolean;\n}\n\ninterface ResolveResult {\n    index: number;\n    parentMap: RootCacheKeyMap | IntermediateCacheKeyMap;\n    map?: TerminalCacheKeyMap;\n}\n\nexport default class CacheKeyResolver {\n    private _lastId = 0;\n    private _map: RootCacheKeyMap = { maps: [] };\n    private _usedMaps: TerminalCacheKeyMap[] = [];\n    private _options: Required<CacheKeyResolverOptions>;\n\n    constructor(options?: CacheKeyResolverOptions) {\n        this._options = {\n            maxSize: 0,\n            isEqual: shallowEqual,\n            onExpire: noop,\n            ...options,\n        };\n    }\n\n    getKey(...args: any[]): string {\n        const result = this._resolveMap(...args);\n        const { index, parentMap } = result;\n        let { map } = result;\n\n        if (map && map.cacheKey) {\n            map.usedCount++;\n        } else {\n            map = this._generateMap(parentMap, args.slice(index));\n        }\n\n        // Keep track of the least used map so we can remove it if the size of\n        // the stack exceeds the maximum size.\n        this._removeLeastUsedMap(map);\n\n        return map.cacheKey;\n    }\n\n    getUsedCount(...args: any[]): number {\n        const { map } = this._resolveMap(...args);\n\n        return map ? map.usedCount : 0;\n    }\n\n    private _resolveMap(...args: any[]): ResolveResult {\n        let index = 0;\n        let parentMap = this._map;\n\n        // Traverse the tree to find the linked list of maps that match the\n        // arguments of the call. Each intermediate or terminal map contains a\n        // value that could be used to match with the arguments. The last map in\n        // the list (the terminal) should contain a cache key. If it can does\n        // not exist, we will return a falsy value so that the caller could\n        // handle and generate a new cache key.\n        while (parentMap.maps.length) {\n            let isMatched = false;\n\n            for (let mapIndex = 0; mapIndex < parentMap.maps.length; mapIndex++) {\n                const map = parentMap.maps[mapIndex];\n\n                if (!this._options.isEqual(map.value, args[index])) {\n                    continue;\n                }\n\n                // Move the most recently used map to the top of the stack for\n                // quicker access\n                parentMap.maps.unshift(...parentMap.maps.splice(mapIndex, 1));\n\n                if ((args.length === 0 || index === args.length - 1) && isTerminalCacheKeyMap(map)) {\n                    return { index, map, parentMap };\n                }\n\n                isMatched = true;\n                parentMap = map;\n                index++;\n\n                break;\n            }\n\n            if (!isMatched) {\n                break;\n            }\n        }\n\n        return { index, parentMap };\n    }\n\n    private _generateMap(parent: RootCacheKeyMap | IntermediateCacheKeyMap, args: any[]): TerminalCacheKeyMap {\n        let index = 0;\n        let parentMap = parent;\n        let map: IntermediateCacheKeyMap;\n\n        do {\n            map = {\n                maps: [],\n                parentMap,\n                usedCount: 1,\n                value: args[index],\n            };\n\n            // Continue to build the tree of maps so that it could be resolved\n            // next time when the function is called with the same set of\n            // arguments.\n            parentMap.maps.unshift(map);\n\n            parentMap = map;\n            index++;\n        } while (index < args.length);\n\n        const terminalMap = map as TerminalCacheKeyMap;\n\n        terminalMap.cacheKey = `${++this._lastId}`;\n\n        return terminalMap;\n    }\n\n    private _removeLeastUsedMap(recentlyUsedMap: TerminalCacheKeyMap): void {\n        if (!this._options.maxSize) {\n            return;\n        }\n\n        const index = this._usedMaps.indexOf(recentlyUsedMap);\n\n        this._usedMaps.splice(\n            index === -1 ? 0 : index,\n            index === -1 ? 0 : 1,\n            recentlyUsedMap\n        );\n\n        if (this._usedMaps.length <= this._options.maxSize) {\n            return;\n        }\n\n        const map = this._usedMaps.pop();\n\n        if (!map) {\n            return;\n        }\n\n        this._removeMap(map);\n        this._options.onExpire(map.cacheKey);\n    }\n\n    private _removeMap(map: ChildCacheKeyMap): void {\n        if (!map.parentMap) {\n            return;\n        }\n\n        map.parentMap.maps.splice(map.parentMap.maps.indexOf(map), 1);\n\n        if (isRootCacheKeyMap(map.parentMap)) {\n            return;\n        }\n\n        this._removeMap(map.parentMap);\n    }\n}\n","module.exports = require(\"@braintree/browser-detection\");","module.exports = require(\"messageformat\");","import { Response } from '@bigcommerce/request-sender';\n\nimport { PaymentErrorResponseBody } from '../error-response-body';\n\nimport RequestError from './request-error';\n\nexport default function mapFromPaymentErrorResponse(\n    response: Response<PaymentErrorResponseBody>,\n    message?: string\n): RequestError {\n    const { body } = response;\n    const { errors = [] } = body;\n\n    return new RequestError(response, {\n        message: joinErrors(errors) || message,\n        errors,\n    });\n}\n\nfunction joinErrors(errors: Array<{ code: string; message?: string }>): string | undefined {\n    if (!Array.isArray(errors)) {\n        return;\n    }\n\n    return errors.reduce((result: string[], error) => {\n        if (error && error.message) {\n            return [...result, error.message];\n        }\n\n        return result;\n    }, []).join(' ');\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport RequestError from './request-error';\n\n/**\n * Throw this error if a request fails to complete within its required timeframe\n * because of a network issue.\n */\nexport default class TimeoutError<T = any> extends RequestError<T> {\n    constructor(response?: Response<T>) {\n        super(response, {\n            message: 'The request has timed out or aborted.',\n        });\n\n        this.name = 'TimeoutError';\n        this.type = 'timeout';\n    }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { RequestError } from '../../common/error/errors';\n\n/**\n * Throw this error if we are unable to successfully submit a server request\n * using a payment method because the method has invalid configuration or is in\n * an invalid state.\n */\nexport default class PaymentMethodInvalidError<T = any> extends RequestError<T> {\n    constructor(response?: Response<T>) {\n        super(response, { message: 'There is a problem processing your payment. Please try again later.' });\n\n        this.name = 'PaymentMethodInvalidError';\n        this.type = 'payment_method_invalid';\n    }\n}\n","import { createSelector as defaultSelectorCreator } from 'reselect';\n\nimport withMemoizedCombiner from './with-memoized-combiner';\n\n/**\n * This is a decorated version of Reselect's default `createSelector` function.\n * If the return value of the combiner function is a function, it will create a\n * memorized version of that function and return it instead.\n */\nexport default withMemoizedCombiner(defaultSelectorCreator);\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Subscriptions } from './subscriptions';\n\nexport enum SubscriptionsActionType {\n    UpdateSubscriptionsRequested = 'UPDATE_SUBSCRIPTIONS_REQUESTED',\n    UpdateSubscriptionsSucceeded = 'UPDATE_SUBSCRIPTIONS_SUCCEEDED',\n    UpdateSubscriptionsFailed = 'UPDATE_SUBSCRIPTIONS_FAILED',\n}\nexport type UpdateSubscriptionsAction =\n    UpdateSubscriptionsRequestedAction |\n    UpdateSubscriptionsSucceededAction |\n    UpdateSubscriptionsFailedAction;\n\nexport interface UpdateSubscriptionsRequestedAction extends Action {\n    type: SubscriptionsActionType.UpdateSubscriptionsRequested;\n}\n\nexport interface UpdateSubscriptionsSucceededAction extends Action<Subscriptions> {\n    type: SubscriptionsActionType.UpdateSubscriptionsSucceeded;\n}\n\nexport interface UpdateSubscriptionsFailedAction extends Action<Error> {\n    type: SubscriptionsActionType.UpdateSubscriptionsFailed;\n}\n","import { createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { cachableAction, ActionOptions } from '../common/data-store';\nimport { RequestOptions } from '../common/http-request';\n\nimport { ConfigRequestSender } from '.';\nimport { ConfigActionType, LoadConfigAction } from './config-actions';\n\nexport default class ConfigActionCreator {\n    constructor(\n        private _configRequestSender: ConfigRequestSender\n    ) {}\n\n    @cachableAction\n    loadConfig(options?: RequestOptions & ActionOptions): Observable<LoadConfigAction> {\n        return Observable.create((observer: Observer<LoadConfigAction>) => {\n            observer.next(createAction(ConfigActionType.LoadConfigRequested));\n\n            this._configRequestSender.loadConfig(options)\n                .then(response => {\n                    observer.next(createAction(ConfigActionType.LoadConfigSucceeded, response.body));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(ConfigActionType.LoadConfigFailed, response));\n                });\n        });\n    }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, INTERNAL_USE_ONLY, RequestOptions } from '../common/http-request';\n\nimport Config from './config';\n\nexport default class ConfigRequestSender {\n    constructor(\n        private _requestSender: RequestSender\n    ) {}\n\n    loadConfig({ timeout }: RequestOptions = {}): Promise<Response<Config>> {\n        const url = '/api/storefront/checkout-settings';\n\n        return this._requestSender.get(url, {\n            timeout,\n            headers: {\n                Accept: ContentType.JsonV1,\n                'X-API-INTERNAL': INTERNAL_USE_ONLY,\n            },\n        });\n    }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, RequestOptions } from '../common/http-request';\n\nimport { Subscriptions } from './subscriptions';\n\nexport default class SubscriptionsRequestSender {\n    constructor(\n        private _requestSender: RequestSender\n    ) {}\n\n    updateSubscriptions(subscriptions: Subscriptions, { timeout }: RequestOptions = {}): Promise<Response<Subscriptions>> {\n        const url = '/api/storefront/subscriptions';\n        const headers = { Accept: ContentType.JsonV1 };\n\n        return this._requestSender.post(url, { body: subscriptions, headers, timeout });\n    }\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { concat, defer, of, Observable } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { cachableAction, ActionOptions } from '../common/data-store';\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\n\nimport { FormFieldsActionType, LoadFormFieldsAction } from './form-fields-actions';\nimport FormFieldsRequestSender from './form-fields-request-sender';\n\nexport default class FormFieldsActionCreator {\n    constructor(\n        private _formFieldsRequestSender: FormFieldsRequestSender\n    ) {}\n\n    @cachableAction\n    loadFormFields(options?: RequestOptions & ActionOptions): Observable<LoadFormFieldsAction> {\n        return concat(\n            of(createAction(FormFieldsActionType.LoadFormFieldsRequested)),\n            defer(async () => {\n                const { body } = await this._formFieldsRequestSender.loadFields(options);\n\n                return createAction(FormFieldsActionType.LoadFormFieldsSucceeded, body);\n            })\n        ).pipe(\n            catchError(response => throwErrorAction(FormFieldsActionType.LoadFormFieldsFailed, response))\n        );\n    }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, INTERNAL_USE_ONLY, RequestOptions } from '../common/http-request';\n\nimport { FormFields } from './form-field';\n\nexport default class FormFieldsRequestSender {\n    constructor(\n        private _requestSender: RequestSender\n    ) {}\n\n    loadFields({ timeout }: RequestOptions = {}): Promise<Response<FormFields>> {\n        const url = '/api/storefront/form-fields';\n\n        return this._requestSender.get(url, {\n            timeout,\n            headers: {\n                Accept: ContentType.JsonV1,\n                'X-API-INTERNAL': INTERNAL_USE_ONLY,\n            },\n        });\n    }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { AddressRequestBody } from '../address';\nimport { Checkout } from '../checkout';\nimport { ContentType, RequestOptions } from '../common/http-request';\n\nimport { BillingAddressUpdateRequestBody } from './billing-address';\n\nconst DEFAULT_PARAMS = {\n    include: [\n        'cart.lineItems.physicalItems.options',\n        'cart.lineItems.digitalItems.options',\n        'customer',\n        'promotions.banners',\n    ].join(','),\n};\n\nexport default class BillingAddressRequestSender {\n    constructor(\n        private _requestSender: RequestSender\n    ) {}\n\n    createAddress(checkoutId: string, address: Partial<AddressRequestBody>, { timeout }: RequestOptions = {}): Promise<Response<Checkout>> {\n        const url = `/api/storefront/checkouts/${checkoutId}/billing-address`;\n        const headers = { Accept: ContentType.JsonV1 };\n\n        return this._requestSender.post(url, { body: address, params: DEFAULT_PARAMS, headers, timeout });\n    }\n\n    updateAddress(checkoutId: string, address: Partial<BillingAddressUpdateRequestBody>, { timeout }: RequestOptions = {}): Promise<Response<Checkout>> {\n        const { id, ...body } = address;\n        const url = `/api/storefront/checkouts/${checkoutId}/billing-address/${id}`;\n        const headers = { Accept: ContentType.JsonV1 };\n\n        return this._requestSender.put(url, { params: DEFAULT_PARAMS, body, headers, timeout });\n    }\n}\n","import { InvalidArgumentError } from '../error/errors';\n\nexport default class Registry<T, K extends string = string> {\n    private _factories: { [key: string]: Factory<T> };\n    private _instances: { [key: string]: T };\n    private _options: RegistryOptions;\n\n    constructor(options?: RegistryOptions) {\n        this._factories = {};\n        this._instances = {};\n        this._options = { defaultToken: 'default', ...options };\n    }\n\n    get(token?: K, cacheToken?: string): T {\n        try {\n            return this._getInstance(\n                token || this._options.defaultToken,\n                cacheToken || token || this._options.defaultToken\n            );\n        } catch (error) {\n            return this._getInstance(\n                this._options.defaultToken,\n                cacheToken || this._options.defaultToken\n            );\n        }\n    }\n\n    register(token: K, factory: Factory<T>): void {\n        if (this._hasFactory(token)) {\n            throw new InvalidArgumentError(`'${token}' is already registered.`);\n        }\n\n        this._factories[token] = factory;\n    }\n\n    protected _hasFactory(token: string): boolean {\n        return !!this._factories[token];\n    }\n\n    private _hasInstance(token: string): boolean {\n        return !!this._instances[token];\n    }\n\n    private _getInstance(token: string, cacheToken: string): T {\n        if (!this._hasInstance(cacheToken)) {\n            const factory = this._factories[token];\n\n            if (!factory) {\n                throw new InvalidArgumentError(`'${token}' is not registered.`);\n            }\n\n            this._instances[cacheToken] = factory();\n        }\n\n        return this._instances[cacheToken];\n    }\n}\n\nexport type Factory<T> = () => T;\n\nexport interface RegistryOptions {\n    defaultToken: string;\n}\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if we try to call a method that is only a stub and has not\n * been fully implemented.\n */\nexport default class NotImplementedError extends StandardError {\n    constructor(message?: string) {\n        super(message || 'Not implemented.');\n\n        this.name = 'NotImplementedError';\n        this.type = 'not_implemented';\n    }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if we are unable to synchronize the checkout details of a\n * shopper with a hosted / remote checkout provider (i.e.: Amazon).\n */\nexport default class RemoteCheckoutSynchronizationError extends StandardError {\n    constructor(\n        public error?: Error\n    ) {\n        super('Unable to synchronize your checkout details with a third party provider. Please try again later.');\n\n        this.name = 'RemoteCheckoutSynchronizationError';\n        this.type = 'remote_checkout_synchronization';\n    }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport PaymentMethod from '../../payment-method';\n\nimport { BillingAddressFormat, GooglePaymentData, GooglePayInitializer, GooglePayPaymentDataRequestV2, TokenizePayload } from './googlepay';\n\nexport default class GooglePayAdyenV2Initializer implements GooglePayInitializer {\n    initialize(\n        checkout: Checkout,\n        paymentMethod: PaymentMethod,\n        hasShippingAddress: boolean\n    ): Promise<GooglePayPaymentDataRequestV2> {\n        return Promise.resolve(this._getGooglePayPaymentDataRequest(\n            checkout,\n            paymentMethod,\n            hasShippingAddress\n        ));\n    }\n\n    teardown(): Promise<void> {\n        return Promise.resolve();\n    }\n\n    parseResponse(paymentData: GooglePaymentData): Promise<TokenizePayload> {\n        const {\n            paymentMethodData: {\n                type,\n                tokenizationData: { token },\n                info: {\n                    cardNetwork: cardType,\n                    cardDetails: lastFour,\n                },\n            },\n        } = paymentData;\n\n        return Promise.resolve({\n            type,\n            nonce: token,\n            details: {\n                cardType,\n                lastFour,\n            },\n        });\n    }\n\n    private _getGooglePayPaymentDataRequest(\n        checkout: Checkout,\n        paymentMethod: PaymentMethod,\n        hasShippingAddress: boolean\n    ): GooglePayPaymentDataRequestV2 {\n        const {\n            outstandingBalance,\n            cart: {\n                currency: { code: currencyCode },\n            },\n        } = checkout;\n\n        const {\n            initializationData: {\n                gatewayMerchantId,\n                storeCountry: countryCode,\n                googleMerchantName: merchantName,\n                googleMerchantId: merchantId,\n                platformToken: authJwt,\n            },\n            supportedCards,\n        } = paymentMethod;\n\n        return {\n            apiVersion: 2,\n            apiVersionMinor: 0,\n            merchantInfo: {\n                authJwt,\n                merchantId,\n                merchantName,\n            },\n            allowedPaymentMethods: [{\n                type: 'CARD',\n                parameters: {\n                    allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n                    allowedCardNetworks: supportedCards.map(card => card === 'MC' ? 'MASTERCARD' : card),\n                    billingAddressRequired: true,\n                    billingAddressParameters: {\n                        format: BillingAddressFormat.Full,\n                        phoneNumberRequired: true,\n                    },\n                },\n                tokenizationSpecification: {\n                    type: 'PAYMENT_GATEWAY',\n                    parameters: {\n                        gateway: 'adyen',\n                        gatewayMerchantId,\n                    },\n                },\n            }],\n            transactionInfo: {\n                countryCode,\n                currencyCode,\n                totalPriceStatus: 'FINAL',\n                totalPrice: round(outstandingBalance, 2).toFixed(2),\n            },\n            emailRequired: true,\n            shippingAddressRequired: !hasShippingAddress,\n            shippingAddressParameters: {\n                phoneNumberRequired: true,\n            },\n        };\n    }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { Masterpass, MasterpassHostWindow } from './masterpass';\ninterface MasterpassScriptLoaderParams {\n    useMasterpassSrc: boolean;\n    language: string;\n    testMode?: boolean;\n    checkoutId?: string;\n  }\nexport default class MasterpassScriptLoader {\n\n    constructor(\n        private _scriptLoader: ScriptLoader,\n        public _window: MasterpassHostWindow = window\n    ) {}\n\n    async load({ useMasterpassSrc, language, testMode, checkoutId }: MasterpassScriptLoaderParams): Promise<Masterpass> {\n\n        if (useMasterpassSrc) {\n            const subdomain = testMode ? 'sandbox.' : '';\n            const params = [\n                `locale=${language}`,\n                `checkoutid=${checkoutId}`,\n            ];\n\n            const sourceUrl = [\n               `https://${subdomain}src.mastercard.com/srci/integration/merchant.js`,\n               params.join('&'),\n            ].join('?');\n\n            await this._scriptLoader.loadScript(sourceUrl);\n\n            if (!this._window.masterpass) {\n                throw new PaymentMethodClientUnavailableError();\n            }\n\n            return this._window.masterpass;\n\n        }\n\n        await this._scriptLoader.loadScript(`//${testMode ? 'sandbox.' : ''}masterpass.com/integration/merchant.js`);\n\n        if (!this._window.masterpass) {\n            throw new PaymentMethodClientUnavailableError();\n        }\n\n        return this._window.masterpass;\n    }\n}\n","import { round } from 'lodash';\n\nimport { PaymentMethod } from '../..';\nimport { Checkout } from '../../../checkout';\n\nimport { BillingAddressFormat, GooglePaymentData, GooglePayInitializer, GooglePayPaymentDataRequestV2, TokenizationSpecification, TokenizePayload } from './googlepay';\n\nconst baseRequest = {\n    apiVersion: 2,\n    apiVersionMinor: 0,\n};\n\nexport default class GooglePayAuthorizeNetInitializer implements GooglePayInitializer {\n    initialize(\n        checkout: Checkout,\n        paymentMethod: PaymentMethod,\n        hasShippingAddress: boolean\n    ): Promise<GooglePayPaymentDataRequestV2> {\n        return Promise.resolve(\n            this._getGooglePaymentDataRequest(checkout, paymentMethod, hasShippingAddress)\n        );\n    }\n\n    teardown(): Promise<void> {\n        return Promise.resolve();\n    }\n\n    parseResponse(paymentData: GooglePaymentData): Promise<TokenizePayload> {\n        const {\n            paymentMethodData: {\n                type,\n                tokenizationData: { token },\n                info: {\n                    cardNetwork: cardType,\n                    cardDetails: lastFour,\n                },\n            },\n        } = paymentData;\n\n        return Promise.resolve({\n            type,\n            nonce: btoa(token),\n            details: {\n                cardType,\n                lastFour,\n            },\n        });\n    }\n\n    private _getGooglePaymentDataRequest(checkout: Checkout, paymentMethod: PaymentMethod, hasShippingAddress: boolean): GooglePayPaymentDataRequestV2 {\n        const {\n            outstandingBalance,\n            cart: {\n                currency: { code: currencyCode },\n            },\n        } = checkout;\n\n        const {\n            initializationData: {\n                paymentGatewayId: gatewayMerchantId,\n                storeCountry: countryCode,\n                googleMerchantName: merchantName,\n                googleMerchantId: merchantId,\n                platformToken: authJwt,\n            },\n            supportedCards,\n        } = paymentMethod;\n\n        const paymentGatewaySpecification = this._getPaymentGatewaySpecification(gatewayMerchantId);\n        const cardPaymentMethod = this._getCardPaymentMethod(paymentGatewaySpecification, supportedCards);\n\n        return {\n            ...baseRequest,\n            allowedPaymentMethods: [cardPaymentMethod],\n            transactionInfo: {\n                totalPriceStatus: 'FINAL',\n                totalPrice: round(outstandingBalance, 2).toFixed(2),\n                currencyCode,\n                countryCode,\n            },\n            merchantInfo : {\n                merchantName,\n                merchantId,\n                authJwt,\n            },\n            emailRequired: true,\n            shippingAddressRequired: !hasShippingAddress,\n            shippingAddressParameters: {\n                phoneNumberRequired: true,\n            },\n        };\n    }\n\n    private _getPaymentGatewaySpecification(gatewayMerchantId: string) {\n        return {\n            type: 'PAYMENT_GATEWAY',\n            parameters: {\n                gateway: 'authorizenet',\n                gatewayMerchantId,\n            },\n        };\n    }\n\n    private _getCardPaymentMethod(tokenizationSpecification: TokenizationSpecification, supportedCards: string[]) {\n        return {\n            type: 'CARD',\n            parameters: {\n                allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n                allowedCardNetworks: supportedCards.map(card => card === 'MC' ? 'MASTERCARD' : card),\n                billingAddressRequired: true,\n                billingAddressParameters: {\n                    format: BillingAddressFormat.Full,\n                    phoneNumberRequired: true,\n                },\n            },\n            tokenizationSpecification,\n        };\n    }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../../../common/error/errors';\nimport PaymentMethod from '../../payment-method';\nimport { BraintreeSDKCreator, GooglePayBraintreeSDK } from '../braintree';\n\nimport { BillingAddressFormat, GooglePaymentData, GooglePayInitializer, GooglePayPaymentDataRequestV2, TokenizePayload } from './googlepay';\nimport { GooglePayBraintreeDataRequest, GooglePayBraintreePaymentDataRequestV1 } from './googlepay-braintree';\n\nexport default class GooglePayBraintreeInitializer implements GooglePayInitializer {\n    private _googlePaymentInstance!: GooglePayBraintreeSDK;\n\n    constructor(\n        private _braintreeSDKCreator: BraintreeSDKCreator\n    ) {}\n\n    initialize(\n        checkout: Checkout,\n        paymentMethod: PaymentMethod,\n        hasShippingAddress: boolean\n    ): Promise<GooglePayPaymentDataRequestV2> {\n        if (!paymentMethod.clientToken) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        this._braintreeSDKCreator.initialize(paymentMethod.clientToken);\n\n        return this._braintreeSDKCreator.getGooglePaymentComponent()\n            .then(googleBraintreePaymentInstance => {\n                this._googlePaymentInstance = googleBraintreePaymentInstance;\n\n                return this._createGooglePayPayload(\n                    checkout,\n                    paymentMethod.initializationData,\n                    hasShippingAddress\n                );\n            });\n    }\n\n    teardown(): Promise<void> {\n        return this._braintreeSDKCreator.teardown();\n    }\n\n    parseResponse(paymentData: GooglePaymentData): Promise<TokenizePayload> {\n        const payload = JSON.parse(paymentData.paymentMethodData.tokenizationData.token).androidPayCards[0];\n\n        return Promise.resolve({\n            nonce: payload.nonce,\n            type: payload.type,\n            description: payload.description,\n            details: {\n                cardType: payload.details.cardType,\n                lastFour: payload.details.lastFour,\n                lastTwo: payload.details.lastTwo,\n            },\n            binData: payload.binData,\n        });\n    }\n\n    private _createGooglePayPayload(\n        checkout: Checkout,\n        initializationData: any,\n        hasShippingAddress: boolean\n    ): GooglePayPaymentDataRequestV2 {\n        if (!initializationData.platformToken) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        const googlePayBraintreePaymentDataRequest: GooglePayBraintreeDataRequest = {\n            merchantInfo: {\n                authJwt: initializationData.platformToken,\n                merchantName: initializationData.googleMerchantName,\n                merchantId: initializationData.googleMerchantId,\n            },\n            transactionInfo: {\n                currencyCode: checkout.cart.currency.code,\n                totalPriceStatus: 'FINAL',\n                totalPrice: round(checkout.outstandingBalance, 2).toFixed(2),\n            },\n            cardRequirements: {\n                billingAddressRequired: true,\n                billingAddressFormat: 'FULL',\n            },\n            shippingAddressRequired: !hasShippingAddress,\n            emailRequired: true,\n            phoneNumberRequired: true,\n        };\n\n        return this._mapGooglePayBraintreeDataRequestToGooglePayDataRequestV2(\n            this._googlePaymentInstance.createPaymentDataRequest(googlePayBraintreePaymentDataRequest)\n        );\n    }\n\n    private _mapGooglePayBraintreeDataRequestToGooglePayDataRequestV2(googlePayBraintreeDataRequestV1: GooglePayBraintreePaymentDataRequestV1): GooglePayPaymentDataRequestV2 {\n        return {\n            apiVersion: 2,\n            apiVersionMinor: 0,\n            merchantInfo: {\n                authJwt: googlePayBraintreeDataRequestV1.merchantInfo.authJwt,\n                merchantId: googlePayBraintreeDataRequestV1.merchantInfo.merchantId,\n                merchantName: googlePayBraintreeDataRequestV1.merchantInfo.merchantName,\n            },\n            allowedPaymentMethods: [{\n                type: 'CARD',\n                parameters: {\n                    allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n                    allowedCardNetworks: googlePayBraintreeDataRequestV1.cardRequirements.allowedCardNetworks,\n                    billingAddressRequired: true,\n                    billingAddressParameters: {\n                        format: BillingAddressFormat.Full,\n                        phoneNumberRequired: true,\n                    },\n                },\n                tokenizationSpecification: {\n                    type: 'PAYMENT_GATEWAY',\n                    parameters: {\n                        gateway: 'braintree',\n                        'braintree:apiVersion': 'v1',\n                        'braintree:authorizationFingerprint': googlePayBraintreeDataRequestV1.paymentMethodTokenizationParameters.parameters['braintree:authorizationFingerprint'],\n                        'braintree:merchantId': googlePayBraintreeDataRequestV1.paymentMethodTokenizationParameters.parameters['braintree:merchantId'],\n                        'braintree:sdkVersion': googlePayBraintreeDataRequestV1.paymentMethodTokenizationParameters.parameters['braintree:sdkVersion'],\n                    },\n                },\n            }],\n            transactionInfo: googlePayBraintreeDataRequestV1.transactionInfo,\n            emailRequired: true,\n            shippingAddressRequired: googlePayBraintreeDataRequestV1.shippingAddressRequired,\n            shippingAddressParameters: {\n                phoneNumberRequired: googlePayBraintreeDataRequestV1.phoneNumberRequired,\n            },\n        };\n    }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport { InvalidArgumentError } from '../../../common/error/errors';\nimport { ContentType } from '../../../common/http-request';\nimport { PaymentMethodFailedError } from '../../errors';\nimport PaymentMethod from '../../payment-method';\nimport { CheckoutcomGooglePayToken, CheckoutcomToken } from '../checkoutcom';\n\nimport { BillingAddressFormat, GooglePaymentData, GooglePayInitializer, GooglePayPaymentDataRequestV2, TokenizePayload } from './googlepay';\n\nexport default class GooglePayCheckoutcomInitializer implements GooglePayInitializer {\n    private _publishableKey: string = '';\n    private _testMode: boolean = true;\n\n    constructor(\n       private _requestSender: RequestSender\n    ) {}\n\n    async initialize(\n        checkout: Checkout,\n        paymentMethod: PaymentMethod,\n        hasShippingAddress: boolean\n    ): Promise<GooglePayPaymentDataRequestV2> {\n        this._publishableKey = paymentMethod.initializationData.checkoutcomkey;\n        this._testMode = !!paymentMethod.config.testMode;\n\n        return this._mapGooglePayCheckoutcomDataRequestToGooglePayDataRequestV2(\n            checkout,\n            paymentMethod.initializationData,\n            hasShippingAddress\n        );\n    }\n\n    teardown(): Promise<void> {\n        return Promise.resolve();\n    }\n\n    async parseResponse(paymentData: GooglePaymentData): Promise<TokenizePayload> {\n        let token;\n        try {\n            token = JSON.parse(paymentData.paymentMethodData.tokenizationData.token);\n        } catch (err) {\n            throw new InvalidArgumentError('Unable to parse response from Google Pay.');\n        }\n\n        if (!token.signature || !token.protocolVersion || !token.signedMessage) {\n            throw new PaymentMethodFailedError('Unable to parse response from Google Pay.');\n        }\n        const finalToken = await this._convertToken(this._testMode, this._publishableKey, token);\n\n        return {\n            nonce: finalToken,\n            type: 'CreditCard',\n            description: paymentData.paymentMethodData.description,\n            details: {\n                cardType: paymentData.paymentMethodData.info.cardNetwork,\n                lastFour: paymentData.paymentMethodData.info.cardDetails,\n            },\n        };\n    }\n\n    private async _convertToken(testMode: boolean, checkoutcomkey: string, token: CheckoutcomGooglePayToken): Promise<string> {\n        if (!token || !token.protocolVersion) {\n            throw new PaymentMethodFailedError('Unable to parse response from GooglePay.');\n        }\n\n        const checkoutcomToken: CheckoutcomToken = await this._requestCheckoutcomTokenize(testMode, checkoutcomkey, {\n            type: 'googlepay',\n            token_data: token,\n        });\n\n        if (!checkoutcomToken || !checkoutcomToken.token) {\n            throw new PaymentMethodFailedError('Unable to parse response from Checkout.com');\n        }\n\n        return checkoutcomToken.token;\n    }\n\n    private async _requestCheckoutcomTokenize(testMode: boolean, checkoutcomKey: string, data = {}): Promise<CheckoutcomToken> {\n        const TEST_URL: string = 'https://api.sandbox.checkout.com/tokens';\n        const LIVE_URL: string = 'https://api.checkout.com/tokens';\n\n        const url = testMode ? TEST_URL : LIVE_URL;\n\n        const response = await this._requestSender.post(url, {\n            credentials: false,\n            body: data,\n            headers: {\n                'Content-Type': ContentType.Json,\n                Authorization: checkoutcomKey,\n                'X-XSRF-TOKEN': null,\n            },\n        });\n\n        return response.body as CheckoutcomToken;\n    }\n\n    private _mapGooglePayCheckoutcomDataRequestToGooglePayDataRequestV2(\n        checkout: Checkout,\n        initializationData: any,\n        hasShippingAddress: boolean\n    ): GooglePayPaymentDataRequestV2 {\n        return {\n            apiVersion: 2,\n            apiVersionMinor: 0,\n            merchantInfo: {\n                authJwt: initializationData.platformToken,\n                merchantId: initializationData.googleMerchantId,\n                merchantName: initializationData.googleMerchantName,\n            },\n            allowedPaymentMethods: [{\n                type: 'CARD',\n                parameters: {\n                    allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n                    allowedCardNetworks: ['AMEX', 'DISCOVER', 'JCB', 'MASTERCARD', 'VISA'],\n                    billingAddressRequired: true,\n                    billingAddressParameters: {\n                        format: BillingAddressFormat.Full,\n                        phoneNumberRequired: true,\n                    },\n                },\n                tokenizationSpecification: {\n                    type: 'PAYMENT_GATEWAY',\n                    parameters: {\n                        gateway: 'checkoutltd',\n                        gatewayMerchantId: initializationData.checkoutcomkey,\n                    },\n                },\n            }],\n            transactionInfo: {\n                currencyCode: checkout.cart.currency.code,\n                totalPriceStatus: 'FINAL',\n                totalPrice: round(checkout.outstandingBalance, 2).toFixed(2),\n            },\n            emailRequired: true,\n            shippingAddressRequired: !hasShippingAddress,\n            shippingAddressParameters: {\n                phoneNumberRequired: true,\n            },\n        };\n    }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport PaymentMethod from '../../payment-method';\n\nimport { BillingAddressFormat, GooglePaymentData, GooglePayInitializer, GooglePayPaymentDataRequestV2, TokenizePayload } from './googlepay';\n\nexport default class GooglePayCybersourceV2Initializer implements GooglePayInitializer {\n    initialize(\n        checkout: Checkout,\n        paymentMethod: PaymentMethod,\n        hasShippingAddress: boolean\n    ): Promise<GooglePayPaymentDataRequestV2> {\n        return Promise.resolve(this._getGooglePayPaymentDataRequest(\n            checkout,\n            paymentMethod,\n            hasShippingAddress\n        ));\n    }\n\n    teardown(): Promise<void> {\n        return Promise.resolve();\n    }\n\n    parseResponse(paymentData: GooglePaymentData): Promise<TokenizePayload> {\n        const {\n            paymentMethodData: {\n                type,\n                tokenizationData: { token },\n                info: {\n                    cardNetwork: cardType,\n                    cardDetails: lastFour,\n                },\n            },\n        } = paymentData;\n\n        return Promise.resolve({\n            nonce: btoa(token),\n            type,\n            details: {\n                cardType,\n                lastFour,\n            },\n        });\n    }\n\n    private _getGooglePayPaymentDataRequest(\n        checkout: Checkout,\n        paymentMethod: PaymentMethod,\n        hasShippingAddress: boolean\n    ): GooglePayPaymentDataRequestV2 {\n        const {\n            outstandingBalance,\n            cart: {\n                currency: { code: currencyCode },\n            },\n        } = checkout;\n\n        const {\n            initializationData: {\n                gatewayMerchantId,\n                googleMerchantName: merchantName,\n                googleMerchantId: merchantId,\n                platformToken: authJwt,\n            },\n            supportedCards,\n        } = paymentMethod;\n\n        return {\n            apiVersion: 2,\n            apiVersionMinor: 0,\n            merchantInfo: {\n                authJwt,\n                merchantId,\n                merchantName,\n            },\n            allowedPaymentMethods: [{\n                type: 'CARD',\n                parameters: {\n                    allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n                    allowedCardNetworks: supportedCards.map(card => card === 'MC' ? 'MASTERCARD' : card),\n                    billingAddressRequired: true,\n                    billingAddressParameters: {\n                        format: BillingAddressFormat.Full,\n                        phoneNumberRequired: true,\n                    },\n                },\n                tokenizationSpecification: {\n                    type: 'PAYMENT_GATEWAY',\n                    parameters: {\n                        gateway: 'cybersource',\n                        gatewayMerchantId,\n                    },\n                },\n            }],\n            transactionInfo: {\n                currencyCode,\n                totalPriceStatus: 'FINAL',\n                totalPrice: round(outstandingBalance, 2).toFixed(2),\n            },\n            emailRequired: true,\n            shippingAddressRequired: !hasShippingAddress,\n            shippingAddressParameters: {\n                phoneNumberRequired: true,\n            },\n        };\n    }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport { InvalidArgumentError } from '../../../common/error/errors';\nimport PaymentMethod from '../../payment-method';\n\nimport { BillingAddressFormat, GooglePaymentData, GooglePayInitializer, GooglePayPaymentDataRequestV2, TokenizePayload } from './googlepay';\n\nexport default class GooglePayStripeInitializer implements GooglePayInitializer {\n    initialize(\n        checkout: Checkout,\n        paymentMethod: PaymentMethod,\n        hasShippingAddress: boolean\n    ): Promise<GooglePayPaymentDataRequestV2> {\n        return Promise.resolve(this._getGooglePayPaymentDataRequest(\n            checkout,\n            paymentMethod,\n            hasShippingAddress\n        ));\n    }\n\n    teardown(): Promise<void> {\n        return Promise.resolve();\n    }\n\n    parseResponse(paymentData: GooglePaymentData): Promise<TokenizePayload> {\n        try {\n            const payload = JSON.parse(paymentData.paymentMethodData.tokenizationData.token);\n\n            return Promise.resolve({\n                nonce: payload.id,\n                type: payload.type,\n                details: {\n                    cardType: payload.card.brand,\n                    lastFour: payload.card.last4,\n                },\n            });\n        } catch (err) {\n            throw new InvalidArgumentError('Unable to parse response from Google Pay.');\n        }\n    }\n\n    private _getGooglePayPaymentDataRequest(\n        checkout: Checkout,\n        paymentMethod: PaymentMethod,\n        hasShippingAddress: boolean\n    ): GooglePayPaymentDataRequestV2 {\n        const {\n            outstandingBalance,\n            cart: {\n                currency: { code: currencyCode },\n            },\n        } = checkout;\n\n        const {\n            initializationData: {\n                googleMerchantName: merchantName,\n                googleMerchantId: merchantId,\n                platformToken: authJwt,\n                stripeVersion,\n                stripePublishableKey,\n                stripeConnectedAccount,\n            },\n            supportedCards,\n        } = paymentMethod;\n\n        return {\n            apiVersion: 2,\n            apiVersionMinor: 0,\n            merchantInfo: {\n                authJwt,\n                merchantId,\n                merchantName,\n            },\n            allowedPaymentMethods: [{\n                type: 'CARD',\n                parameters: {\n                    allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n                    allowedCardNetworks: supportedCards.map(card => card === 'MC' ? 'MASTERCARD' : card),\n                    billingAddressRequired: true,\n                    billingAddressParameters: {\n                        format: BillingAddressFormat.Full,\n                        phoneNumberRequired: true,\n                    },\n                },\n                tokenizationSpecification: {\n                    type: 'PAYMENT_GATEWAY',\n                    parameters: {\n                        gateway: 'stripe',\n                        'stripe:version': stripeVersion,\n                        'stripe:publishableKey': `${stripePublishableKey}/${stripeConnectedAccount}`,\n                    },\n                },\n            }],\n            transactionInfo: {\n                currencyCode,\n                totalPriceStatus: 'FINAL',\n                totalPrice: round(outstandingBalance, 2).toFixed(2),\n            },\n            emailRequired: true,\n            shippingAddressRequired: !hasShippingAddress,\n            shippingAddressParameters: {\n                phoneNumberRequired: true,\n            },\n        };\n    }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport default class InvalidHostedFormConfigError extends StandardError {\n    constructor(message?: string) {\n        super(message || 'Unable to proceed due to invalid configuration provided for the hosted payment form.');\n\n        this.name = 'InvalidHostedFormConfigError';\n        this.type = 'invalid_hosted_form_config';\n    }\n}\n","import { flatMap, map, values } from 'lodash';\n\nimport { StandardError } from '../../common/error/errors';\nimport { HostedInputValidateErrorDataMap } from '../iframe-content';\n\nexport default class InvalidHostedFormValueError extends StandardError {\n    constructor(\n        public errors: HostedInputValidateErrorDataMap\n    ) {\n        super([\n            'Unable to proceed due to invalid user input values',\n            ...flatMap(values(errors), fieldErrors => map(fieldErrors, ({ message }) => message)),\n        ].join('. '));\n\n        this.name = 'InvalidHostedFormValueError';\n        this.type = 'invalid_hosted_form_value';\n    }\n}\n","import { LoadScriptOptions, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { PaypalHostWindow, PaypalSDK } from './paypal-sdk';\n\nexport default class PaypalScriptLoader {\n    private _window: PaypalHostWindow;\n\n    constructor(\n        private _scriptLoader: ScriptLoader\n    ) {\n        this._window = window;\n    }\n\n    async loadPaypal(merchantId: string = ''): Promise<PaypalSDK> {\n        const scriptSrc = '//www.paypalobjects.com/api/checkout.min.js';\n        const options: LoadScriptOptions = { async: true, attributes: { 'data-merchant-id': merchantId } };\n\n        merchantId\n            ? await this._scriptLoader.loadScript(scriptSrc, options)\n            : await this._scriptLoader.loadScript(scriptSrc);\n\n        if (!this._window.paypal) {\n            throw new PaymentMethodClientUnavailableError();\n        }\n\n        return this._window.paypal;\n    }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { ContentType, INTERNAL_USE_ONLY } from '../../../common/http-request';\n\nimport { OrderData, OrderStatus } from './paypal-commerce-sdk';\n\nexport interface ParamsForProvider {\n    isCredit?: boolean;\n    isCheckout?: boolean;\n    isCreditCard?: boolean;\n    isAPM?: boolean;\n}\n\nexport default class PaypalCommerceRequestSender {\n    constructor(\n        private _requestSender: RequestSender\n    ) {}\n\n    async setupPayment(cartId: string, params: ParamsForProvider = {}): Promise<OrderData> {\n        const { isCredit, isCheckout, isCreditCard, isAPM } = params;\n        let provider = 'paypalcommerce';\n\n        if (isCreditCard) {\n            provider = 'paypalcommercecreditcardscheckout';\n        } else if (isCheckout) {\n            provider = isCredit ? 'paypalcommercecreditcheckout' : 'paypalcommercecheckout';\n        } else if (isCredit) {\n            provider = 'paypalcommercecredit';\n        }\n\n        if (isAPM) {\n            provider = 'paypalcommercealternativemethodscheckout';\n        }\n\n        const url = `/api/storefront/payment/${provider}`;\n        const body = { cartId };\n        const headers = {\n            'X-API-INTERNAL': INTERNAL_USE_ONLY,\n            'Content-Type': ContentType.Json,\n        };\n\n        const res = await this._requestSender.post(url, { headers, body });\n\n        return res.body as OrderData;\n    }\n\n    async getOrderStatus() {\n        const url = '/api/storefront/initialization/paypalcommerce';\n        const headers = {\n            'X-API-INTERNAL': INTERNAL_USE_ONLY,\n            'Content-Type': ContentType.Json,\n        };\n\n        const res = await this._requestSender.get<OrderStatus>(url, {headers});\n\n        return res.body;\n    }\n}\n","import { LoadingIndicatorStyles } from './loading-indicator-styles';\n\nconst DEFAULT_STYLES: LoadingIndicatorStyles = {\n    size: 70,\n    color: '#d9d9d9',\n    backgroundColor: '#ffffff',\n};\n\nconst ROTATION_ANIMATION = 'embedded-checkout-loading-indicator-rotation';\n\nexport default class LoadingIndicator {\n    private _container: HTMLElement;\n    private _indicator: HTMLElement;\n    private _styles: LoadingIndicatorStyles;\n\n    constructor(\n        options?: { styles?: LoadingIndicatorStyles }\n    ) {\n        this._styles = { ...DEFAULT_STYLES, ...options && options.styles };\n\n        this._defineAnimation();\n\n        this._container = this._buildContainer();\n        this._indicator = this._buildIndicator();\n\n        this._container.appendChild(this._indicator);\n    }\n\n    show(parentId?: string): void {\n        if (parentId) {\n            const parent = document.getElementById(parentId);\n\n            if (!parent) {\n                throw new Error('Unable to attach the loading indicator because the parent ID is not valid.');\n            }\n\n            parent.appendChild(this._container);\n        }\n\n        this._container.style.visibility = 'visible';\n        this._container.style.opacity = '1';\n    }\n\n    hide(): void {\n        const handleTransitionEnd = () => {\n            this._container.style.visibility = 'hidden';\n\n            this._container.removeEventListener('transitionend', handleTransitionEnd);\n        };\n\n        this._container.addEventListener('transitionend', handleTransitionEnd);\n\n        this._container.style.opacity = '0';\n    }\n\n    private _buildContainer(): HTMLElement {\n        const container = document.createElement('div');\n\n        container.style.display = 'block';\n        container.style.bottom = '0';\n        container.style.left = '0';\n        container.style.height = '100%';\n        container.style.width = '100%';\n        container.style.position = 'absolute';\n        container.style.right = '0';\n        container.style.top = '0';\n        container.style.transition = 'all 250ms ease-out';\n        container.style.opacity = '0';\n\n        return container;\n    }\n\n    private _buildIndicator(): HTMLElement {\n        const indicator = document.createElement('div');\n\n        indicator.style.display = 'block';\n        indicator.style.width = `${this._styles.size}px`;\n        indicator.style.height = `${this._styles.size}px`;\n        indicator.style.borderRadius = `${this._styles.size}px`;\n        indicator.style.border = 'solid 1px';\n        indicator.style.borderColor = `${this._styles.backgroundColor} ${this._styles.backgroundColor} ${this._styles.color} ${this._styles.color}`;\n        indicator.style.margin = '0 auto';\n        indicator.style.position = 'absolute';\n        indicator.style.left = '0';\n        indicator.style.right = '0';\n        indicator.style.top = '50%';\n        indicator.style.transform = 'translateY(-50%) rotate(0deg)';\n        indicator.style.transformStyle = 'preserve-3d';\n        indicator.style.animation = `${ROTATION_ANIMATION} 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)`;\n\n        return indicator;\n    }\n\n    private _defineAnimation(): void {\n        // In order to define CSS animation, we need to insert a stylesheet into the host frame.\n        // We only have to do it once.\n        if (document.getElementById(ROTATION_ANIMATION)) {\n            return;\n        }\n\n        const style = document.createElement('style');\n\n        style.id = ROTATION_ANIMATION;\n\n        document.head.appendChild(style);\n\n        if (style.sheet instanceof CSSStyleSheet) {\n            // We need to provide the 2nd parameter for IE11, even though it is\n            // 0 by default for all other browsers.\n            style.sheet.insertRule(`\n                @keyframes ${ROTATION_ANIMATION} {\n                    0% { transform: translateY(-50%) rotate(0deg); }\n                    100% { transform: translateY(-50%) rotate(360deg); }\n                }\n            `, 0);\n        }\n    }\n}\n","import { IFrameComponent, IFrameOptions } from 'iframe-resizer';\n\nexport {\n    HeightCalculationMethod,\n    IFrameComponent,\n    IFrameMessageData,\n    IFrameObject,\n    IFrameOptions,\n    IFramePage,\n    IFramePageOptions,\n    IFrameResizedData,\n    IFrameScrollData,\n    PageInfo,\n    WidthCalculationMethod,\n} from 'iframe-resizer';\n\n// The reason why we are wrapping the original `iframeResizer` function imported\n// from the package is because the package sets up event listeners (window\n// resize etc...) as soon as the package is imported. Therefore, to defer the\n// side effect from happening until the function is actually being used, we are\n// importing the package inside this function. To minimise the chance of\n// importing the original package inadvertently, we are also re-exporting all of\n// its public interfaces. The re-exports do not cause any side effect because\n// they are plain TypeScript interfaces; meaning they are only used for type\n// checks rather than for code output.\nexport function iframeResizer(options: IFrameOptions, target: string | HTMLElement): IFrameComponent[] {\n    const { iframeResizer: originalIframeResizer } = require('iframe-resizer');\n\n    return originalIframeResizer(options, target);\n}\n\n// We also need to wrap the original `iframeResizer.contentWindow` because\n// similarly the package sets up event listeners as soon as the package gets\n// imported. Another reason is that if it is imported at the top level using a\n// regular import statement, it will be stripped out by Webpack as it is\n// considered as \"unused\", unless we explicitly mark it as a package that\n// produces side effects.\nexport function setupContentWindowForIframeResizer(): void {\n    /* eslint-disable-next-line import/no-internal-modules */\n    require('iframe-resizer/js/iframeResizer.contentWindow');\n}\n","import { ClearErrorAction, ErrorActionType } from './error-actions';\n\nexport default class ErrorActionCreator {\n    clearError(error: Error): ClearErrorAction {\n        return {\n            type: ErrorActionType.ClearError,\n            payload: error,\n        };\n    }\n}\n","export default function getEnvironment(): string {\n    try {\n        return process.env.NODE_ENV || 'development';\n    } catch (e) {\n        return 'development';\n    }\n}\n","import ConsoleLogger from './console-logger';\nimport Logger from './logger';\nimport NoopLogger from './noop-logger';\n\nexport default function createLogger(isEnabled = true): Logger {\n    if (!isEnabled) {\n        return new NoopLogger();\n    }\n\n    return new ConsoleLogger(console);\n}\n","import Logger from './logger';\n\nexport default class ConsoleLogger implements Logger {\n    constructor(\n        private _console?: Console\n    ) {}\n\n    log(...messages: any[]): void {\n        this._logToConsole('log', ...messages);\n    }\n\n    info(...messages: any[]): void {\n        this._logToConsole('info', ...messages);\n    }\n\n    warn(...messages: any[]): void {\n        this._logToConsole('warn', ...messages);\n    }\n\n    error(...messages: any[]): void {\n        this._logToConsole('error', ...messages);\n    }\n\n    debug(...messages: any[]): void {\n        this._logToConsole('debug', ...messages);\n    }\n\n    private _logToConsole(type: keyof Console, ...messages: any[]): void {\n        if (!this._console || !this._console[type]) {\n            return;\n        }\n\n        this._console[type].call(this._console, ...messages);\n    }\n}\n","import Logger from './logger';\n\nexport default class NoopLogger implements Logger {\n    log(): void {}\n\n    info(): void {}\n\n    warn(): void {}\n\n    error(): void {}\n\n    debug(): void {}\n}\n","import { getEnvironment } from '../utility';\n\nimport createLogger from './create-logger';\nimport Logger from './logger';\n\nconst logger = createLogger(getEnvironment() !== 'test');\n\nexport default function getDefaultLogger(): Logger {\n    return logger;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport { ApplyCouponAction, CouponAction, CouponActionType, RemoveCouponAction } from './coupon-actions';\nimport CouponRequestSender from './coupon-request-sender';\n\nexport default class CouponActionCreator {\n    constructor(\n        private _couponRequestSender: CouponRequestSender\n    ) {}\n\n    applyCoupon(code: string, options?: RequestOptions): ThunkAction<CouponAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<ApplyCouponAction>) => {\n            const state = store.getState();\n            const checkout = state.checkout.getCheckout();\n\n            if (!checkout) {\n                throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n            }\n\n            observer.next(createAction(CouponActionType.ApplyCouponRequested));\n\n            this._couponRequestSender.applyCoupon(checkout.id, code, options)\n                .then(({ body }) => {\n                    observer.next(createAction(CouponActionType.ApplyCouponSucceeded, body));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(CouponActionType.ApplyCouponFailed, response));\n                });\n        });\n    }\n\n    removeCoupon(code: string, options?: RequestOptions): ThunkAction<CouponAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<RemoveCouponAction>) => {\n            const state = store.getState();\n            const checkout = state.checkout.getCheckout();\n\n            if (!checkout) {\n                throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n            }\n\n            observer.next(createAction(CouponActionType.RemoveCouponRequested));\n\n            this._couponRequestSender.removeCoupon(checkout.id, code, options)\n                .then(({ body }) => {\n                    observer.next(createAction(CouponActionType.RemoveCouponSucceeded, body));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(CouponActionType.RemoveCouponFailed, response));\n                });\n        });\n    }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CheckoutIncludes, CHECKOUT_DEFAULT_INCLUDES } from '../checkout';\nimport { joinIncludes, ContentType, RequestOptions } from '../common/http-request';\n\nexport default class CouponRequestSender {\n    constructor(\n        private _requestSender: RequestSender\n    ) {}\n\n    applyCoupon(checkoutId: string, couponCode: string, { timeout }: RequestOptions = {}): Promise<Response<Checkout>> {\n        const url = `/api/storefront/checkouts/${checkoutId}/coupons`;\n        const headers = { Accept: ContentType.JsonV1 };\n\n        return this._requestSender.post(url, {\n            headers,\n            timeout,\n            params: {\n                include: joinIncludes([\n                    ...CHECKOUT_DEFAULT_INCLUDES,\n                    CheckoutIncludes.AvailableShippingOptions,\n                ]),\n            },\n            body: { couponCode },\n        });\n    }\n\n    removeCoupon(checkoutId: string, couponCode: string, { timeout }: RequestOptions = {}): Promise<Response<Checkout>> {\n        const url = `/api/storefront/checkouts/${checkoutId}/coupons/${couponCode}`;\n        const headers = { Accept: ContentType.JsonV1 };\n\n        return this._requestSender.delete(url, {\n            headers,\n            timeout,\n            params: {\n                include: joinIncludes([\n                    ...CHECKOUT_DEFAULT_INCLUDES,\n                    CheckoutIncludes.AvailableShippingOptions,\n                ]),\n            },\n        });\n    }\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable ,  Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport { GiftCertificateRequestSender } from '.';\nimport { ApplyGiftCertificateAction, GiftCertificateActionType, RemoveGiftCertificateAction } from './gift-certificate-actions';\n\nexport default class GiftCertificateActionCreator {\n    constructor(\n        private _giftCertificateRequestSender: GiftCertificateRequestSender\n    ) {}\n\n    applyGiftCertificate(giftCertificate: string, options?: RequestOptions): ThunkAction<ApplyGiftCertificateAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<ApplyGiftCertificateAction>) => {\n            const state = store.getState();\n            const checkout = state.checkout.getCheckout();\n\n            if (!checkout) {\n                throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n            }\n\n            observer.next(createAction(GiftCertificateActionType.ApplyGiftCertificateRequested));\n\n            this._giftCertificateRequestSender.applyGiftCertificate(checkout.id, giftCertificate, options)\n                .then(({ body }) => {\n                    observer.next(createAction(GiftCertificateActionType.ApplyGiftCertificateSucceeded, body));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(GiftCertificateActionType.ApplyGiftCertificateFailed, response));\n                });\n        });\n    }\n\n    removeGiftCertificate(giftCertificate: string, options?: RequestOptions): ThunkAction<RemoveGiftCertificateAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<RemoveGiftCertificateAction>) => {\n            const state = store.getState();\n            const checkout = state.checkout.getCheckout();\n\n            if (!checkout) {\n                throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n            }\n\n            observer.next(createAction(GiftCertificateActionType.RemoveGiftCertificateRequested));\n\n            this._giftCertificateRequestSender.removeGiftCertificate(checkout.id, giftCertificate, options)\n                .then(({ body }) => {\n                    observer.next(createAction(GiftCertificateActionType.RemoveGiftCertificateSucceeded, body));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(GiftCertificateActionType.RemoveGiftCertificateFailed, response));\n                });\n        });\n    }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CHECKOUT_DEFAULT_INCLUDES } from '../checkout';\nimport { joinIncludes, ContentType, RequestOptions } from '../common/http-request';\n\nexport default class GiftCertificateRequestSender {\n    constructor(\n        private _requestSender: RequestSender\n    ) {}\n\n    applyGiftCertificate(checkoutId: string, giftCertificateCode: string, { timeout }: RequestOptions = {}): Promise<Response<Checkout>> {\n        const url = `/api/storefront/checkouts/${checkoutId}/gift-certificates`;\n        const headers = { Accept: ContentType.JsonV1 };\n\n        return this._requestSender.post(url, {\n            headers,\n            timeout,\n            params: {\n                include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n            },\n            body: { giftCertificateCode },\n        });\n    }\n\n    removeGiftCertificate(checkoutId: string, giftCertificateCode: string, { timeout }: RequestOptions = {}): Promise<Response<Checkout>> {\n        const url = `/api/storefront/checkouts/${checkoutId}/gift-certificates/${giftCertificateCode}`;\n        const headers = { Accept: ContentType.JsonV1 };\n\n        return this._requestSender.delete(url, {\n            headers,\n            timeout,\n            params: {\n                include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n            },\n        });\n    }\n}\n","import { ExecuteSucceededAction, SpamProtectionAction } from './spam-protection-actions';\n\nexport default function isSpamProtectionExecuteSucceededAction(action: SpamProtectionAction): action is ExecuteSucceededAction {\n    const succeededAction = action as ExecuteSucceededAction;\n\n    return typeof succeededAction === 'object' &&\n        typeof succeededAction.payload === 'object' &&\n        typeof succeededAction.payload.token === 'string';\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, from, of, Observable } from 'rxjs';\nimport { catchError, switchMap } from 'rxjs/operators';\n\nimport { CheckoutActionCreator, InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\nimport { isSpamProtectionExecuteSucceededAction, SpamProtectionActionCreator } from '../spam-protection';\n\nimport CustomerAccountRequestBody, { CustomerAddressRequestBody } from './customer-account';\nimport { CreateCustomerAction, CreateCustomerAddressAction, CustomerActionType, SignInCustomerAction, SignOutCustomerAction } from './customer-actions';\nimport CustomerCredentials from './customer-credentials';\nimport CustomerRequestSender from './customer-request-sender';\n\nexport default class CustomerActionCreator {\n    constructor(\n        private _customerRequestSender: CustomerRequestSender,\n        private _checkoutActionCreator: CheckoutActionCreator,\n        private _spamProtectionActionCreator: SpamProtectionActionCreator\n    ) {}\n\n    createCustomer(\n        customerAccount: CustomerAccountRequestBody,\n        options?: RequestOptions\n    ): ThunkAction<CreateCustomerAction, InternalCheckoutSelectors> {\n        return store => {\n            const state = store.getState();\n            const config = state.config.getStoreConfigOrThrow();\n            const { isStorefrontSpamProtectionEnabled } = config.checkoutSettings;\n\n            const createCustomer = (token?: string) =>\n                from(this._customerRequestSender.createAccount({ ...customerAccount, token }, options))\n                    .pipe(switchMap(() => concat(\n                        this._checkoutActionCreator.loadCurrentCheckout(options)(store),\n                        of(createAction(CustomerActionType.CreateCustomerSucceeded))\n                    )));\n\n            return concat(\n                of(createAction(CustomerActionType.CreateCustomerRequested)),\n                (isStorefrontSpamProtectionEnabled ?\n                    from(this._spamProtectionActionCreator.execute()(store))\n                        .pipe(switchMap(action => isSpamProtectionExecuteSucceededAction(action) ?\n                                concat(\n                                    of(action),\n                                    createCustomer(action.payload?.token)\n                                ) :\n                                of(action)\n                        )) :\n                    createCustomer()\n                )\n            ).pipe(\n                catchError(error => throwErrorAction(CustomerActionType.CreateCustomerFailed, error))\n            );\n        };\n    }\n\n    createAddress(\n        customerAddress: CustomerAddressRequestBody,\n        options?: RequestOptions\n    ): Observable<CreateCustomerAddressAction> {\n        return concat(\n            of(createAction(CustomerActionType.CreateCustomerAddressRequested)),\n            defer(async () => {\n                const { body } = await this._customerRequestSender.createAddress(customerAddress, options);\n\n                return createAction(CustomerActionType.CreateCustomerAddressSucceeded, body);\n            })\n        ).pipe(\n            catchError(error => throwErrorAction(CustomerActionType.CreateCustomerAddressFailed, error))\n        );\n    }\n\n    signInCustomer(\n        credentials: CustomerCredentials,\n        options?: RequestOptions\n    ): ThunkAction<SignInCustomerAction, InternalCheckoutSelectors> {\n        return store => concat(\n            of(createAction(CustomerActionType.SignInCustomerRequested)),\n            from(this._customerRequestSender.signInCustomer(credentials, options))\n                .pipe(\n                    switchMap(({ body }) => concat(\n                        this._checkoutActionCreator.loadCurrentCheckout(options)(store),\n                        of(createAction(CustomerActionType.SignInCustomerSucceeded, body.data))\n                    ))\n                )\n        ).pipe(\n            catchError(error => throwErrorAction(CustomerActionType.SignInCustomerFailed, error))\n        );\n    }\n\n    signOutCustomer(\n        options?: RequestOptions\n    ): ThunkAction<SignOutCustomerAction, InternalCheckoutSelectors> {\n        return store => concat(\n            of(createAction(CustomerActionType.SignOutCustomerRequested)),\n            from(this._customerRequestSender.signOutCustomer(options))\n                .pipe(\n                    switchMap(({ body }) => concat(\n                        this._checkoutActionCreator.loadCurrentCheckout(options)(store),\n                        of(createAction(CustomerActionType.SignOutCustomerSucceeded, body.data))\n                    ))\n                )\n        ).pipe(\n            catchError(error => throwErrorAction(CustomerActionType.SignOutCustomerFailed, error))\n        );\n    }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions } from '../common/http-request';\n\nimport Customer from './customer';\nimport { CustomerAccountInternalRequestBody, CustomerAddressRequestBody } from './customer-account';\nimport CustomerCredentials from './customer-credentials';\nimport { InternalCustomerResponseBody } from './internal-customer-responses';\n\nexport default class CustomerRequestSender {\n    constructor(\n        private _requestSender: RequestSender\n    ) {}\n\n    createAccount(customerAccount: CustomerAccountInternalRequestBody, { timeout }: RequestOptions = {}): Promise<Response<{}>> {\n        const url = '/api/storefront/customer';\n\n        return this._requestSender.post(url, { timeout, body: customerAccount });\n    }\n\n    createAddress(customerAddress: CustomerAddressRequestBody, { timeout }: RequestOptions = {}): Promise<Response<Customer>> {\n        const url = `/api/storefront/customer-address`;\n\n        return this._requestSender.post<Customer>(url, { timeout, body: customerAddress });\n    }\n\n    signInCustomer(credentials: CustomerCredentials, { timeout }: RequestOptions = {}): Promise<Response<InternalCustomerResponseBody>> {\n        const url = '/internalapi/v1/checkout/customer';\n\n        return this._requestSender.post(url, { timeout, body: credentials });\n    }\n\n    signOutCustomer({ timeout }: RequestOptions = {}): Promise<Response<InternalCustomerResponseBody>> {\n        const url = '/internalapi/v1/checkout/customer';\n\n        return this._requestSender.delete(url, { timeout });\n    }\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { Registry } from '../common/registry';\n\nimport CustomerCredentials from './customer-credentials';\nimport { CustomerInitializeOptions, CustomerRequestOptions } from './customer-request-options';\nimport { CustomerStrategyActionType, CustomerStrategyDeinitializeAction, CustomerStrategyInitializeAction, CustomerStrategySignInAction, CustomerStrategySignOutAction, CustomerStrategyWidgetAction } from './customer-strategy-actions';\nimport { CustomerStrategy } from './strategies';\n\nexport default class CustomerStrategyActionCreator {\n    constructor(\n        private _strategyRegistry: Registry<CustomerStrategy>\n    ) {}\n\n    signIn(credentials: CustomerCredentials, options?: CustomerRequestOptions): Observable<CustomerStrategySignInAction> {\n        return Observable.create((observer: Observer<CustomerStrategySignInAction>) => {\n            const methodId = options && options.methodId;\n            const meta = { methodId };\n\n            observer.next(createAction(CustomerStrategyActionType.SignInRequested, undefined, meta));\n\n            this._strategyRegistry.get(methodId)\n                .signIn(credentials, options)\n                .then(() => {\n                    observer.next(createAction(CustomerStrategyActionType.SignInSucceeded, undefined, meta));\n                    observer.complete();\n                })\n                .catch(error => {\n                    observer.error(createErrorAction(CustomerStrategyActionType.SignInFailed, error, meta));\n                });\n        });\n    }\n\n    signOut(options?: CustomerRequestOptions): Observable<CustomerStrategySignOutAction> {\n        return Observable.create((observer: Observer<CustomerStrategySignOutAction>) => {\n            const methodId = options && options.methodId;\n            const meta = { methodId };\n\n            observer.next(createAction(CustomerStrategyActionType.SignOutRequested, undefined, meta));\n\n            this._strategyRegistry.get(methodId)\n                .signOut(options)\n                .then(() => {\n                    observer.next(createAction(CustomerStrategyActionType.SignOutSucceeded, undefined, meta));\n                    observer.complete();\n                })\n                .catch(error => {\n                    observer.error(createErrorAction(CustomerStrategyActionType.SignOutFailed, error, meta));\n                });\n        });\n    }\n\n    initialize(options?: CustomerInitializeOptions): ThunkAction<CustomerStrategyInitializeAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<CustomerStrategyInitializeAction>) => {\n            const state = store.getState();\n            const methodId = options && options.methodId;\n            const meta = { methodId };\n\n            if (methodId && state.customerStrategies.isInitialized(methodId)) {\n                return observer.complete();\n            }\n\n            observer.next(createAction(CustomerStrategyActionType.InitializeRequested, undefined, meta));\n\n            this._strategyRegistry.get(methodId)\n                .initialize(options)\n                .then(() => {\n                    observer.next(createAction(CustomerStrategyActionType.InitializeSucceeded, undefined, meta));\n                    observer.complete();\n                })\n                .catch(error => {\n                    observer.error(createErrorAction(CustomerStrategyActionType.InitializeFailed, error, meta));\n                });\n        });\n    }\n\n    deinitialize(options?: CustomerRequestOptions): ThunkAction<CustomerStrategyDeinitializeAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<CustomerStrategyDeinitializeAction>) => {\n            const state = store.getState();\n            const methodId = options && options.methodId;\n            const meta = { methodId };\n\n            if (methodId && !state.customerStrategies.isInitialized(methodId)) {\n                return observer.complete();\n            }\n\n            observer.next(createAction(CustomerStrategyActionType.DeinitializeRequested, undefined, meta));\n\n            this._strategyRegistry.get(methodId)\n                .deinitialize(options)\n                .then(() => {\n                    observer.next(createAction(CustomerStrategyActionType.DeinitializeSucceeded, undefined, meta));\n                    observer.complete();\n                })\n                .catch(error => {\n                    observer.error(createErrorAction(CustomerStrategyActionType.DeinitializeFailed, error, meta));\n                });\n        });\n    }\n\n    widgetInteraction(method: () => Promise<any>, options?: CustomerRequestOptions): Observable<CustomerStrategyWidgetAction> {\n        return Observable.create((observer: Observer<CustomerStrategyWidgetAction>) => {\n            const methodId = options && options.methodId;\n            const meta = { methodId };\n\n            observer.next(createAction(CustomerStrategyActionType.WidgetInteractionStarted, undefined, meta));\n\n            method().then(() => {\n                observer.next(createAction(CustomerStrategyActionType.WidgetInteractionFinished, undefined, meta));\n                observer.complete();\n            })\n            .catch(error => {\n                observer.error(createErrorAction(CustomerStrategyActionType.WidgetInteractionFailed, error, meta));\n            });\n        });\n    }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport PaymentMethod from '../../payment-method';\n\nimport AmazonPayWindow from './amazon-pay-window';\n\nexport default class AmazonPayScriptLoader {\n    private _window: AmazonPayWindow;\n\n    constructor(\n        private _scriptLoader: ScriptLoader\n    ) {\n        this._window = window;\n    }\n\n    loadWidget(method: PaymentMethod, onPaymentReady?: () => void): Promise<void> {\n        const {\n            config: { merchantId, testMode },\n            initializationData: { region = 'us' } = {},\n        } = method;\n\n        const url = 'https://' +\n            (region.toLowerCase() !== 'us' ? 'static-eu.' : 'static-na.') +\n            'payments-amazon.com/OffAmazonPayments/' +\n            `${region.toLowerCase()}/` +\n            (testMode ? 'sandbox/' : '') +\n            (region.toLowerCase() !== 'us' ? 'lpa/' : '') +\n            `js/Widgets.js?sellerId=${merchantId}`;\n\n        this._configureWidget(method, onPaymentReady);\n\n        return this._scriptLoader.loadScript(url);\n    }\n\n    private _configureWidget(method: PaymentMethod, onPaymentReady?: () => void): void {\n        const onLoginReady = () => {\n            if (!this._window.amazon) {\n                return;\n            }\n\n            this._window.amazon.Login.setClientId(method.initializationData.clientId);\n            this._window.amazon.Login.setUseCookie(true);\n        };\n\n        if (this._window.amazon && this._window.amazon.Login) {\n            onLoginReady();\n        } else {\n            this._window.onAmazonLoginReady = onLoginReady;\n        }\n\n        if (this._window.OffAmazonPayments && onPaymentReady) {\n            onPaymentReady();\n        } else {\n            this._window.onAmazonPaymentsReady = onPaymentReady;\n        }\n    }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { Address, LegacyAddress } from '../../../address';\n\nimport { BraintreeDataCollector } from './braintree';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport { VisaCheckoutAddress, VisaCheckoutInitOptions, VisaCheckoutPaymentSuccessPayload, VisaCheckoutTokenizedPayload } from './visacheckout';\n\nexport default class BraintreeVisaCheckoutPaymentProcessor {\n    constructor(\n        private _braintreeSDKCreator: BraintreeSDKCreator,\n        private _requestSender: RequestSender\n    ) {}\n\n    initialize(clientToken: string, options: VisaCheckoutInitializeOptions): Promise<VisaCheckoutInitOptions> {\n        this._braintreeSDKCreator.initialize(clientToken);\n\n        return this._braintreeSDKCreator.getVisaCheckout()\n            .then(visaCheckout => visaCheckout.createInitOptions({\n                settings: {\n                    locale: options.locale,\n                    shipping: {\n                        collectShipping: options.collectShipping,\n                    },\n                },\n                paymentRequest: {\n                    currencyCode: options.currencyCode,\n                    subtotal: String(options.subtotal),\n                },\n            }));\n    }\n\n    deinitialize(): Promise<void> {\n        return this._braintreeSDKCreator.teardown();\n    }\n\n    handleSuccess(payment: VisaCheckoutPaymentSuccessPayload, shipping?: Address, billing?: Address): Promise<any> {\n        return this._braintreeSDKCreator.getVisaCheckout()\n            .then(braintreeVisaCheckout => Promise.all([\n                braintreeVisaCheckout.tokenize(payment),\n                this._braintreeSDKCreator.getDataCollector(),\n            ])\n            .then(([tokenizedPayload, dataCollector]) => {\n                const {\n                    shippingAddress = this._toVisaCheckoutAddress(shipping),\n                    billingAddress = this._toVisaCheckoutAddress(billing),\n                } = tokenizedPayload;\n\n                return this._postForm({\n                    ...tokenizedPayload,\n                    shippingAddress,\n                    billingAddress,\n                }, dataCollector);\n            }));\n    }\n\n    private _postForm(paymentData: VisaCheckoutTokenizedPayload, dataCollector: BraintreeDataCollector) {\n        const {\n            userData,\n            billingAddress,\n            shippingAddress,\n            details: cardInformation,\n        } = paymentData;\n        const { userEmail } = userData;\n        const { deviceData } = dataCollector;\n\n        return this._requestSender.post('/checkout.php', {\n            headers: {\n                Accept: 'text/html',\n                'Content-Type': 'application/x-www-form-urlencoded',\n            },\n            body: {\n                payment_type: paymentData.type,\n                nonce: paymentData.nonce,\n                provider: 'braintreevisacheckout',\n                action: 'set_external_checkout',\n                device_data: deviceData,\n                card_information: this._getCardInformation(cardInformation),\n                billing_address: this._getAddress(userEmail, billingAddress),\n                shipping_address: this._getAddress(userEmail, shippingAddress),\n            },\n        });\n    }\n\n    private _toVisaCheckoutAddress(address?: Address): VisaCheckoutAddress {\n        if (!address) {\n            return {};\n        }\n\n        return {\n            firstName: address.firstName,\n            lastName: address.lastName,\n            phoneNumber: address.phone,\n            streetAddress: address.address1,\n            extendedAddress: address.address2,\n            locality: address.city,\n            region: address.stateOrProvinceCode,\n            countryCode: address.countryCode,\n            postalCode: address.postalCode,\n        };\n    }\n\n    private _getAddress(email: string, address: VisaCheckoutAddress = {}): Partial<LegacyAddress> {\n        return {\n            email,\n            first_name: address.firstName,\n            last_name: address.lastName,\n            phone_number: address.phoneNumber,\n            address_line_1: address.streetAddress,\n            address_line_2: address.extendedAddress,\n            city: address.locality,\n            state: address.region,\n            country_code: address.countryCode,\n            postal_code: address.postalCode,\n        };\n    }\n\n    private _getCardInformation(cardInformation: { cardType: string; lastTwo: string }) {\n        return {\n            type: cardInformation.cardType,\n            number: cardInformation.lastTwo,\n        };\n    }\n}\n\nexport interface VisaCheckoutInitializeOptions {\n    locale?: string;\n    collectShipping?: boolean;\n    subtotal?: number;\n    currencyCode?: string;\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport BraintreeVisaCheckoutPaymentProcessor from './braintree-visacheckout-payment-processor';\n\nexport default function createBraintreeVisaCheckoutPaymentProcessor(\n    scriptLoader: ScriptLoader,\n    requestSender: RequestSender\n) {\n    const braintreeScriptLoader = new BraintreeScriptLoader(scriptLoader);\n    const braintreeSDKCreator = new BraintreeSDKCreator(braintreeScriptLoader);\n\n    return new BraintreeVisaCheckoutPaymentProcessor(braintreeSDKCreator, requestSender);\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { VisaCheckoutHostWindow, VisaCheckoutSDK } from './visacheckout';\n\nexport default class VisaCheckoutScriptLoader {\n    constructor(\n        private _scriptLoader: ScriptLoader,\n        private _window: VisaCheckoutHostWindow = window\n    ) {}\n\n    load(testMode?: boolean): Promise<VisaCheckoutSDK> {\n        return this._scriptLoader\n            .loadScript(`//${testMode ? 'sandbox-' : ''}assets.secure.checkout.visa.com/checkout-widget/resources/js/integration/v1/sdk.js`)\n            .then(() => {\n                if (!this._window.V) {\n                    throw new PaymentMethodClientUnavailableError();\n                }\n\n                return this._window.V;\n            });\n    }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { ChasePayHostWindow, JPMC } from './chasepay';\n\nexport default class ChasePayScriptLoader {\n    constructor(\n        private _scriptLoader: ScriptLoader,\n        public _window: ChasePayHostWindow = window\n    ) {}\n\n    load(testMode?: boolean): Promise<JPMC> {\n        return this._scriptLoader\n            .loadScript(`//pwc${testMode ? 'psb' : ''}.chase.com/pwc/checkout/js/v20170521/list.action?type=raw&applId=PWC&channelId=CWC&version=1`)\n            .then(() => {\n                if (!this._window.JPMC) {\n                    throw new PaymentMethodClientUnavailableError();\n                }\n\n                return this._window.JPMC;\n            });\n    }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport PaymentMethod from '../../payment-method';\n\nimport { BillingAddressFormat, GooglePaymentData, GooglePayInitializer, GooglePayPaymentDataRequestV2, TokenizePayload } from './googlepay';\n\nexport default class GooglePayOrbitalInitializer implements GooglePayInitializer {\n    initialize(\n        checkout: Checkout,\n        paymentMethod: PaymentMethod,\n        hasShippingAddress: boolean\n    ): Promise<GooglePayPaymentDataRequestV2> {\n        return Promise.resolve(this._getGooglePayPaymentDataRequest(\n            checkout,\n            paymentMethod,\n            hasShippingAddress\n        ));\n    }\n\n    teardown(): Promise<void> {\n        return Promise.resolve();\n    }\n\n    parseResponse(paymentData: GooglePaymentData): Promise<TokenizePayload> {\n        const {\n            paymentMethodData: {\n                type,\n                tokenizationData: { token },\n                info: {\n                    cardNetwork: cardType,\n                    cardDetails: lastFour,\n                },\n            },\n        } = paymentData;\n\n        return Promise.resolve({\n            nonce: btoa(token),\n            type,\n            details: {\n                cardType,\n                lastFour,\n            },\n        });\n    }\n\n    private _getGooglePayPaymentDataRequest(\n        checkout: Checkout,\n        paymentMethod: PaymentMethod,\n        hasShippingAddress: boolean\n    ): GooglePayPaymentDataRequestV2 {\n        const {\n            outstandingBalance,\n            cart: {\n                currency: { code: currencyCode },\n            },\n        } = checkout;\n\n        const {\n            initializationData: {\n                gatewayMerchantId,\n                googleMerchantName: merchantName,\n                googleMerchantId: merchantId,\n                platformToken: authJwt,\n            },\n            supportedCards,\n        } = paymentMethod;\n\n        return {\n            apiVersion: 2,\n            apiVersionMinor: 0,\n            merchantInfo: {\n                authJwt,\n                merchantId,\n                merchantName,\n            },\n            allowedPaymentMethods: [{\n                type: 'CARD',\n                parameters: {\n                    allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n                    allowedCardNetworks: supportedCards.map(card => card === 'MC' ? 'MASTERCARD' : card),\n                    billingAddressRequired: true,\n                    billingAddressParameters: {\n                        format: BillingAddressFormat.Full,\n                        phoneNumberRequired: true,\n                    },\n                },\n                tokenizationSpecification: {\n                    type: 'PAYMENT_GATEWAY',\n                    parameters: {\n                        gateway: 'chase',\n                        gatewayMerchantId,\n                    },\n                },\n            }],\n            transactionInfo: {\n                currencyCode,\n                totalPriceStatus: 'FINAL',\n                totalPrice: round(outstandingBalance, 2).toFixed(2),\n            },\n            emailRequired: true,\n            shippingAddressRequired: !hasShippingAddress,\n            shippingAddressParameters: {\n                phoneNumberRequired: true,\n            },\n        };\n    }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions } from '../common/http-request';\n\n/**\n * @todo Convert this file into TypeScript properly\n */\nexport default class RemoteCheckoutRequestSender {\n    constructor(\n        private _requestSender: RequestSender\n    ) {}\n\n    initializeBilling(methodName: string, params?: { referenceId: string }, { timeout }: RequestOptions = {}): Promise<Response<any>> {\n        const url = `/remote-checkout/${methodName}/billing`;\n\n        return this._requestSender.get(url, { params, timeout });\n    }\n\n    initializeShipping(methodName: string, params?: { referenceId: string }, { timeout }: RequestOptions = {}): Promise<Response<any>> {\n        const url = `/remote-checkout/${methodName}/shipping`;\n\n        return this._requestSender.get(url, { params, timeout });\n    }\n\n    initializePayment(methodName: string, params?: InitializePaymentOptions, { timeout }: RequestOptions = {}): Promise<Response<any>> {\n        const url = `/remote-checkout/${methodName}/payment`;\n\n        return this._requestSender.get(url, { params, timeout });\n    }\n\n    loadSettings(methodName: string, { timeout }: RequestOptions = {}): Promise<Response<any>> {\n        const url = `/remote-checkout/${methodName}/settings`;\n\n        return this._requestSender.get(url, { timeout });\n    }\n\n    signOut(methodName: string, { timeout }: RequestOptions = {}): Promise<Response<any>> {\n        const url = `/remote-checkout/${methodName}/signout`;\n\n        return this._requestSender.get(url, { timeout });\n    }\n\n    generateToken({ timeout }: RequestOptions = {}): Promise<Response<any>> {\n        const url = '/remote-checkout-token';\n\n        return this._requestSender.get(url, { timeout });\n    }\n\n    trackAuthorizationEvent({ timeout }: RequestOptions = {}): Promise<Response<any>> {\n        const url = '/remote-checkout/events/shopper-checkout-service-provider-authorization-requested';\n\n        return this._requestSender.post(url, { timeout });\n    }\n}\n\nexport interface InitializePaymentOptions {\n    authorizationToken?: string;\n    customerMessage?: string;\n    referenceId?: string;\n    useStoreCredit?: boolean;\n}\n","import { createAction, createErrorAction, Action } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { RequestOptions } from '../common/http-request';\n\nimport { RemoteCheckoutActionType } from './remote-checkout-actions';\nimport RemoteCheckoutRequestSender, { InitializePaymentOptions } from './remote-checkout-request-sender';\nimport { RemoteCheckoutStateData } from './remote-checkout-state';\n\n/**\n * @todo Convert this file into TypeScript properly\n * i.e.: Action<T>\n */\nexport default class RemoteCheckoutActionCreator {\n    constructor(\n        private _remoteCheckoutRequestSender: RemoteCheckoutRequestSender\n    ) {}\n\n    initializeBilling(methodId: string, params?: { referenceId: string }, options?: RequestOptions): Observable<Action> {\n        return Observable.create((observer: Observer<Action>) => {\n            observer.next(createAction(RemoteCheckoutActionType.InitializeRemoteBillingRequested, undefined, { methodId }));\n\n            this._remoteCheckoutRequestSender.initializeBilling(methodId, params, options)\n                .then(({ body = {} }) => {\n                    observer.next(createAction(RemoteCheckoutActionType.InitializeRemoteBillingSucceeded, body, { methodId }));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(RemoteCheckoutActionType.InitializeRemoteBillingFailed, response, { methodId }));\n                });\n        });\n    }\n\n    initializeShipping(methodId: string, params?: { referenceId: string }, options?: RequestOptions): Observable<Action> {\n        return Observable.create((observer: Observer<Action>) => {\n            observer.next(createAction(RemoteCheckoutActionType.InitializeRemoteShippingRequested, undefined, { methodId }));\n\n            this._remoteCheckoutRequestSender.initializeShipping(methodId, params, options)\n                .then(({ body = {} }) => {\n                    observer.next(createAction(RemoteCheckoutActionType.InitializeRemoteShippingSucceeded, body, { methodId }));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(RemoteCheckoutActionType.InitializeRemoteShippingFailed, response, { methodId }));\n                });\n        });\n    }\n\n    initializePayment(methodId: string, params?: InitializePaymentOptions, options?: RequestOptions): Observable<Action> {\n        return Observable.create((observer: Observer<Action>) => {\n            observer.next(createAction(RemoteCheckoutActionType.InitializeRemotePaymentRequested, undefined, { methodId }));\n\n            this._remoteCheckoutRequestSender.initializePayment(methodId, params, options)\n                .then(({ body = {} }) => {\n                    observer.next(createAction(RemoteCheckoutActionType.InitializeRemotePaymentSucceeded, body, { methodId }));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(RemoteCheckoutActionType.InitializeRemotePaymentFailed, response, { methodId }));\n                });\n        });\n    }\n\n    loadSettings(methodId: string, options?: RequestOptions): Observable<Action> {\n        return Observable.create((observer: Observer<Action>) => {\n            observer.next(createAction(RemoteCheckoutActionType.LoadRemoteSettingsRequested, undefined, { methodId }));\n\n            this._remoteCheckoutRequestSender.loadSettings(methodId, options)\n                .then(({ body }) => {\n                    observer.next(createAction(RemoteCheckoutActionType.LoadRemoteSettingsSucceeded, body, { methodId }));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(RemoteCheckoutActionType.LoadRemoteSettingsFailed, response, { methodId }));\n                });\n        });\n    }\n\n    signOut(methodId: string, options?: RequestOptions): Observable<Action> {\n        return Observable.create((observer: Observer<Action>) => {\n            observer.next(createAction(RemoteCheckoutActionType.SignOutRemoteCustomerRequested, undefined, { methodId }));\n\n            this._remoteCheckoutRequestSender.signOut(methodId, options)\n                .then(() => {\n                    observer.next(createAction(RemoteCheckoutActionType.SignOutRemoteCustomerSucceeded, undefined, { methodId }));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(RemoteCheckoutActionType.SignOutRemoteCustomerFailed, response, { methodId }));\n                });\n        });\n    }\n\n    updateCheckout<K extends keyof RemoteCheckoutStateData>(methodId: K, data: Partial<RemoteCheckoutStateData[K]>): Action {\n        return createAction(RemoteCheckoutActionType.UpdateRemoteCheckout, data, { methodId });\n    }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if the shopper chooses not to complete the spam protection\n * challenge (i.e.: they close the reCaptcha window).\n */\nexport default class SpamProtectionChallengeNotCompletedError extends StandardError {\n    constructor() {\n        super('You haven\\'t complete our spam protection challenge. Please try again.');\n\n        this.name = 'SpamProtectionChallengeNotCompletedError';\n        this.type = 'spam_protection_challenge_not_completed';\n    }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if we fail to complete the required spam protection\n * verification due to an unknown reason.\n */\nexport default class SpamProtectionFailedError extends StandardError {\n    constructor() {\n        super('We were not able to complete your spam protection verification. Please try again.');\n\n        this.name = 'SpamProtectionFailedError';\n        this.type = 'spam_protection_failed';\n    }\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, from, of } from 'rxjs';\nimport { catchError, switchMap, take } from 'rxjs/operators';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\n\nimport { SpamProtectionChallengeNotCompletedError, SpamProtectionFailedError } from './errors';\nimport GoogleRecaptcha from './google-recaptcha';\nimport isSpamProtectionExecuteSucceededAction from './is-spam-protection-succeeded-action';\nimport { SpamProtectionAction, SpamProtectionActionType } from './spam-protection-actions';\nimport { SpamProtectionOptions } from './spam-protection-options';\nimport SpamProtectionRequestSender from './spam-protection-request-sender';\n\nexport default class SpamProtectionActionCreator {\n    constructor(\n        private _googleRecaptcha: GoogleRecaptcha,\n        private _requestSender: SpamProtectionRequestSender\n    ) {}\n\n    initialize(options?: SpamProtectionOptions): ThunkAction<SpamProtectionAction, InternalCheckoutSelectors> {\n        return store => concat(\n            of(createAction(SpamProtectionActionType.InitializeRequested, undefined)),\n            defer(async () => {\n                const spamProtectionElementId = options ? options.containerId : 'spamProtectionContainer';\n\n                if (!options && !document.getElementById(spamProtectionElementId)) {\n                    const spamProtectionElement = document.createElement('div');\n                    spamProtectionElement.setAttribute('id', spamProtectionElementId);\n                    document.body.appendChild(spamProtectionElement);\n                }\n\n                const state = store.getState();\n                const storeConfig = state.config.getStoreConfigOrThrow();\n                const recaptchaSitekey = storeConfig.checkoutSettings.googleRecaptchaSitekey;\n\n                await this._googleRecaptcha.load(spamProtectionElementId, recaptchaSitekey);\n\n                return createAction(SpamProtectionActionType.InitializeSucceeded);\n            })\n        ).pipe(\n            catchError(error => throwErrorAction(SpamProtectionActionType.InitializeFailed, error))\n        );\n    }\n\n    verifyCheckoutSpamProtection(): ThunkAction<SpamProtectionAction> {\n        return store => defer(() => {\n            const state = store.getState();\n            const checkout = state.checkout.getCheckout();\n\n            if (!checkout) {\n                throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n            }\n\n            return concat(\n                of(createAction(SpamProtectionActionType.VerifyCheckoutRequested)),\n                from(this.execute()(store))\n                    .pipe(switchMap(action => {\n                        if (!isSpamProtectionExecuteSucceededAction(action) || !action.payload) {\n                            return of(action);\n                        }\n\n                        return from(this._requestSender.validate(checkout.id, action.payload.token))\n                            .pipe(\n                                switchMap(({ body }) => concat(\n                                    of(action),\n                                    of(createAction(SpamProtectionActionType.VerifyCheckoutSucceeded, body))\n                                ))\n                            );\n                        })\n                    )\n            ).pipe(\n                catchError(error => throwErrorAction(SpamProtectionActionType.VerifyCheckoutFailed, error))\n            );\n        });\n    }\n\n    execute(): ThunkAction<SpamProtectionAction, InternalCheckoutSelectors> {\n        return store => concat(\n                of(createAction(SpamProtectionActionType.ExecuteRequested)),\n                this.initialize()(store),\n                this._googleRecaptcha.execute()\n                    .pipe(take(1))\n                    .pipe(switchMap(async ({ error, token }) => {\n                        if (error instanceof SpamProtectionChallengeNotCompletedError) {\n                            throw error;\n                        }\n\n                        if (error || !token) {\n                            throw new SpamProtectionFailedError();\n                        }\n\n                        return createAction(SpamProtectionActionType.ExecuteSucceeded, { token });\n                    }))\n            ).pipe(\n                catchError(error => throwErrorAction(SpamProtectionActionType.ExecuteFailed, error))\n            );\n    }\n}\n","export interface MutationObeserverCreator {\n    prototype: MutationObserver;\n    new(callback: MutationCallback): MutationObserver;\n}\n\nexport interface MutationObserverWindow extends Window {\n    MutationObserver: MutationObeserverCreator;\n}\n\nexport class MutationObserverFactory {\n    constructor(\n        private _window: MutationObserverWindow = window as MutationObserverWindow\n    ) {}\n\n    create(callback: MutationCallback): MutationObserver {\n        return new this._window.MutationObserver(callback);\n    }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if spam protection is not loaded when trying to\n * complete the required spam protection verification.\n */\nexport default class SpamProtectionNotLoadedError extends StandardError {\n    constructor() {\n        super('Spam protection is not loaded. Please try again.');\n\n        this.name = 'SpamProtectionNotLoadedError';\n        this.type = 'spam_protection_failed';\n    }\n}\n","import { memoize } from '@bigcommerce/memoize';\nimport { defer, of, throwError, Observable, Subject } from 'rxjs';\nimport { catchError, delay, retryWhen, switchMap } from 'rxjs/operators';\n\nimport { MutationObserverFactory } from '../common/dom';\nimport { NotInitializedError, NotInitializedErrorType } from '../common/error/errors';\n\nimport { SpamProtectionChallengeNotCompletedError, SpamProtectionFailedError, SpamProtectionNotLoadedError } from './errors';\nimport GoogleRecaptchaScriptLoader from './google-recaptcha-script-loader';\n\nconst TIMEOUT = 7000;\nconst RETRY_INTERVAL = 250;\nconst MAX_RETRIES = TIMEOUT / RETRY_INTERVAL;\n\nexport interface RecaptchaResult {\n    error?: Error;\n    token?: string;\n}\n\nexport default class GoogleRecaptcha {\n    private _event$?: Subject<RecaptchaResult>;\n    private _recaptcha?: ReCaptchaV2.ReCaptcha;\n    private _memoized: (recaptcha: ReCaptchaV2.ReCaptcha, sitekey: string, container: HTMLElement | null) => Subject<RecaptchaResult>;\n    private _widgetId?: number;\n\n    constructor(\n        private googleRecaptchaScriptLoader: GoogleRecaptchaScriptLoader,\n        private mutationObserverFactory: MutationObserverFactory\n    ) {\n        this._memoized = memoize((recaptcha: ReCaptchaV2.ReCaptcha, sitekey: string, container: HTMLElement | null) => {\n            const event$ = new Subject<RecaptchaResult>();\n\n            if (!container) {\n                throw new Error();\n            }\n\n            this._widgetId = recaptcha.render(container.id, {\n                sitekey,\n                size: 'invisible',\n                callback: () => {\n                    event$.next({\n                        token: recaptcha.getResponse(this._widgetId),\n                    });\n                    recaptcha.reset(this._widgetId);\n                },\n                'error-callback': () => {\n                    event$.next({\n                        error: new SpamProtectionFailedError(),\n                    });\n                },\n            });\n\n            return event$;\n        }, { isEqual: (a, b) => a === b });\n    }\n\n    load(containerId: string, sitekey: string): Promise<void> {\n        return this.googleRecaptchaScriptLoader.load()\n            .then(recaptcha => {\n                this._event$ = this._memoized(recaptcha, sitekey, document.getElementById(containerId));\n\n                this._recaptcha = recaptcha;\n            });\n    }\n\n    execute(): Observable<RecaptchaResult> {\n        return defer(() => {\n            const event$ = this._event$;\n            const recaptcha = this._recaptcha;\n\n            if (!event$ || !recaptcha) {\n                throw new NotInitializedError(NotInitializedErrorType.SpamProtectionNotInitialized);\n            }\n\n            return defer(() => {\n                const element = document.querySelector('iframe[src*=\"bframe\"]');\n\n                return element ? of(element) : throwError(new SpamProtectionNotLoadedError());\n            })\n                .pipe(\n                    retryWhen(errors => errors.pipe(\n                        delay(RETRY_INTERVAL),\n                        switchMap((error, index) =>\n                            index < MAX_RETRIES ? of(error) : throwError(error)\n                        )\n                    )),\n                    switchMap(element => {\n                        this._watchRecaptchaChallengeWindow(event$, element);\n                        recaptcha.execute(this._widgetId);\n\n                        return event$;\n                    }),\n                    catchError(error => of({ error }))\n                );\n        });\n    }\n\n    private _watchRecaptchaChallengeWindow(event: Subject<RecaptchaResult>, element: Element) {\n        const iframeContainer = element.parentElement;\n\n        if (!iframeContainer) {\n            throw new SpamProtectionNotLoadedError();\n        }\n\n        const container = iframeContainer.parentElement;\n\n        if (!container) {\n            throw new SpamProtectionNotLoadedError();\n        }\n\n        this.mutationObserverFactory.create(() => {\n            // When customer closes the Google ReCaptcha challenge window, throw SpamProtectionNotCompletedError\n            if (container.style.visibility === 'hidden') {\n                event.next({\n                    error: new SpamProtectionChallengeNotCompletedError(),\n                });\n            }\n        }).observe(container, { attributes: true, attributeFilter: ['style'] });\n    }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nexport default class GoogleRecaptchaScriptLoader {\n    private _loadPromise?: Promise<ReCaptchaV2.ReCaptcha>;\n\n    constructor(\n        private _scriptLoader: ScriptLoader,\n        private _window: GoogleRecaptchaWindow = window\n    ) {}\n\n    load(): Promise<ReCaptchaV2.ReCaptcha> {\n        if (!this._loadPromise) {\n            this._loadPromise = this._loadScript();\n        }\n\n        return this._loadPromise;\n    }\n\n    private _loadScript(): Promise<ReCaptchaV2.ReCaptcha> {\n        const callbackName = 'initRecaptcha';\n        const params = [\n            `onload=${callbackName}`,\n            'render=explicit',\n        ].join('&');\n\n        return new Promise((resolve, reject) => {\n            this._window[callbackName] = () => resolve(this._window.grecaptcha);\n\n            this._scriptLoader.loadScript(`//www.google.com/recaptcha/api.js?${params}`)\n                .catch(error => {\n                    this._loadPromise = undefined;\n                    reject(error);\n                });\n        });\n    }\n}\n\nexport interface GoogleRecaptchaWindow extends Window {\n    grecaptcha?: ReCaptchaV2.ReCaptcha;\n    initRecaptcha?(): void;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { MutationObserverFactory } from '../common/dom';\n\nimport GoogleRecaptcha from './google-recaptcha';\nimport GoogleRecaptchaScriptLoader from './google-recaptcha-script-loader';\n\nexport default function createSpamProtection(scriptLoader: ScriptLoader): GoogleRecaptcha {\n    return new GoogleRecaptcha(\n        new GoogleRecaptchaScriptLoader(scriptLoader),\n        new MutationObserverFactory()\n    );\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout } from '../checkout';\nimport { ContentType, RequestOptions } from '../common/http-request';\n\nexport default class SpamProtectionRequestSender {\n    constructor(\n        private _requestSender: RequestSender\n    ) {}\n\n    validate(checkoutId: string, token: string, { timeout }: RequestOptions = {}): Promise<Response<Checkout>> {\n        const url = `/api/storefront/checkouts/${checkoutId}/spam-protection`;\n        const headers = { Accept: ContentType.JsonV1 };\n\n        return this._requestSender.post(url, { body: { token }, headers, timeout });\n    }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotImplementedError, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport { AmazonPayLoginButton, AmazonPayScriptLoader, AmazonPayWindow } from '../../../payment/strategies/amazon-pay';\nimport { RemoteCheckoutActionCreator, RemoteCheckoutRequestSender } from '../../../remote-checkout';\nimport { CustomerInitializeOptions, CustomerRequestOptions } from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nimport AmazonPayCustomerInitializeOptions from './amazon-pay-customer-initialize-options';\n\nexport default class AmazonPayCustomerStrategy implements CustomerStrategy {\n    private _paymentMethod?: PaymentMethod;\n    private _window: AmazonPayWindow;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n        private _remoteCheckoutRequestSender: RemoteCheckoutRequestSender,\n        private _scriptLoader: AmazonPayScriptLoader\n    ) {\n        this._window = window;\n    }\n\n    initialize(options: CustomerInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { amazon: amazonOptions, methodId } = options;\n\n        if (!amazonOptions || !methodId) {\n            throw new InvalidArgumentError('Unable to proceed because \"options.amazon\" argument is not provided.');\n        }\n\n        return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n            .then(state => new Promise((resolve, reject) => {\n                this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n                if (!this._paymentMethod) {\n                    throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n                }\n\n                const { onError = () => {} } = amazonOptions;\n                const onReady = () => {\n                    this._createSignInButton({\n                        ...amazonOptions,\n                        onError: error => {\n                            reject(error);\n                            onError(error);\n                        },\n                    });\n\n                    resolve();\n                };\n\n                this._scriptLoader.loadWidget(this._paymentMethod, onReady)\n                    .catch(reject);\n            }))\n            .then(() => this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        this._paymentMethod = undefined;\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    signIn(): Promise<InternalCheckoutSelectors> {\n        throw new NotImplementedError(\n            'In order to sign in via AmazonPay, the shopper must click on \"Login with Amazon\" button.'\n        );\n    }\n\n    signOut(options?: CustomerRequestOptions): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n        const payment = state.payment.getPaymentId();\n\n        if (!payment) {\n            return Promise.resolve(this._store.getState());\n        }\n\n        return this._store.dispatch(\n            this._remoteCheckoutActionCreator.signOut(payment.providerId, options)\n        );\n    }\n\n    private _createSignInButton(options: AmazonPayCustomerInitializeOptions): AmazonPayLoginButton {\n        if (!this._paymentMethod || !this._window.OffAmazonPayments) {\n            throw new NotInitializedError(NotInitializedErrorType.CustomerNotInitialized);\n        }\n\n        if (!this._paymentMethod.config.merchantId) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        const { initializationData } = this._paymentMethod;\n\n        return new this._window.OffAmazonPayments.Button(options.container, this._paymentMethod.config.merchantId, {\n            color: options.color || 'Gold',\n            size: options.size || 'small',\n            type: 'PwA',\n            useAmazonAddressBook: true,\n            onError: options.onError,\n            authorization: () => {\n                this._handleAuthorization(initializationData);\n            },\n        });\n    }\n\n    private _handleAuthorization(options: AuthorizationOptions): void {\n        this._remoteCheckoutRequestSender.generateToken()\n            .then(({ body }) => {\n                if (!this._window.amazon) {\n                    throw new NotInitializedError(NotInitializedErrorType.ShippingNotInitialized);\n                }\n\n                this._window.amazon.Login.authorize({\n                    popup: false,\n                    scope: 'payments:shipping_address payments:billing_address payments:widget profile',\n                    state: `${options.tokenPrefix}${body.token}`,\n                }, options.redirectUrl);\n\n                this._remoteCheckoutRequestSender.trackAuthorizationEvent();\n            });\n    }\n}\n\ninterface AuthorizationOptions {\n    redirectUrl: string;\n    tokenPrefix: string;\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotImplementedError } from '../../../common/error/errors';\nimport { PaymentMethodActionCreator } from '../../../payment';\nimport { AmazonPayV2PaymentProcessor, AmazonPayV2PayOptions, AmazonPayV2Placement } from '../../../payment/strategies/amazon-pay-v2';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { getShippableItemsCount } from '../../../shipping';\nimport { CustomerInitializeOptions, CustomerRequestOptions } from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class AmazonPayV2CustomerStrategy implements CustomerStrategy {\n    private _walletButton?: HTMLElement;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n        private _amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor\n    ) {}\n\n    async initialize(options: CustomerInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { methodId, amazonpay } = options;\n\n        if (!methodId || !amazonpay) {\n            throw new InvalidArgumentError('Unable to proceed because \"options.methodId\" or \"options.amazonpay\" argument is not provided.');\n        }\n\n        const state = await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId));\n        const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n        await this._amazonPayV2PaymentProcessor.initialize(paymentMethod);\n        this._walletButton = this._createSignInButton(amazonpay.container, methodId);\n\n        return this._store.getState();\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        if (this._walletButton && this._walletButton.parentNode) {\n            this._walletButton.parentNode.removeChild(this._walletButton);\n            this._walletButton = undefined;\n        }\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    signIn(): Promise<InternalCheckoutSelectors> {\n        throw new NotImplementedError(\n            'In order to sign in via Amazon, the shopper must click on \"Amazon Pay\" button.'\n        );\n    }\n\n    async signOut(options?: CustomerRequestOptions): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n        const payment = state.payment.getPaymentId();\n\n        if (!payment) {\n            return Promise.resolve(this._store.getState());\n        }\n\n        await this._amazonPayV2PaymentProcessor.signout();\n\n        return this._store.dispatch(\n            this._remoteCheckoutActionCreator.signOut(payment.providerId, options)\n        );\n    }\n\n    private _createSignInButton(containerId: string, methodId: string): HTMLElement {\n        const container = document.getElementById(containerId);\n\n        if (!container) {\n            throw new InvalidArgumentError('Unable to create sign-in button without valid container ID.');\n        }\n\n        const state = this._store.getState();\n        const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n        const config = state.config.getStoreConfig();\n        const cart = state.cart.getCart();\n\n        if (!config) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n        }\n\n        if (!paymentMethod) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        const {\n            config: {\n                merchantId,\n                testMode,\n            },\n            initializationData: {\n                checkoutLanguage,\n                ledgerCurrency,\n                checkoutSessionMethod,\n                extractAmazonCheckoutSessionId,\n            },\n        } = paymentMethod;\n\n        if (!merchantId) {\n            throw new InvalidArgumentError('Unable to create sign-in button without valid merchant ID.');\n        }\n\n        const amazonButtonOptions = {\n            merchantId,\n            sandbox: !!testMode,\n            checkoutLanguage,\n            ledgerCurrency,\n            productType: cart && getShippableItemsCount(cart) === 0 ?\n                AmazonPayV2PayOptions.PayOnly :\n                AmazonPayV2PayOptions.PayAndShip,\n            createCheckoutSession: {\n                method: checkoutSessionMethod,\n                url: `${config.storeProfile.shopPath}/remote-checkout/${methodId}/payment-session`,\n                extractAmazonCheckoutSessionId,\n            },\n            placement: AmazonPayV2Placement.Checkout,\n        };\n\n        this._amazonPayV2PaymentProcessor.createButton(`#${containerId}`, amazonButtonOptions);\n\n        return container;\n    }\n}\n","import { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotImplementedError } from '../../../common/error/errors';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport { BraintreeVisaCheckoutPaymentProcessor, VisaCheckoutPaymentSuccessPayload, VisaCheckoutScriptLoader } from '../../../payment/strategies/braintree';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { CustomerInitializeOptions, CustomerRequestOptions } from '../../customer-request-options';\nimport CustomerStrategyActionCreator from '../../customer-strategy-action-creator';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class BraintreeVisaCheckoutCustomerStrategy implements CustomerStrategy {\n    private _paymentMethod?: PaymentMethod;\n    private _buttonClassName: string = 'visa-checkout-wrapper';\n\n    constructor(\n        private _store: CheckoutStore,\n        private _checkoutActionCreator: CheckoutActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _customerStrategyActionCreator: CustomerStrategyActionCreator,\n        private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n        private _braintreeVisaCheckoutPaymentProcessor: BraintreeVisaCheckoutPaymentProcessor,\n        private _visaCheckoutScriptLoader: VisaCheckoutScriptLoader\n    ) {}\n\n    initialize(options: CustomerInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { braintreevisacheckout: visaCheckoutOptions, methodId } = options;\n\n        if (!visaCheckoutOptions || !methodId) {\n            throw new InvalidArgumentError('Unable to proceed because \"options.braintreevisacheckout\" argument is not provided.');\n        }\n\n        return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n            .then(state => {\n                this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n                const checkout = state.checkout.getCheckout();\n                const storeConfig = state.config.getStoreConfig();\n\n                if (!checkout) {\n                    throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n                }\n\n                if (!storeConfig) {\n                    throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n                }\n\n                if (!this._paymentMethod || !this._paymentMethod.clientToken) {\n                    throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n                }\n\n                const {\n                    container,\n                    onError = () => {},\n                } = visaCheckoutOptions;\n\n                const initOptions = {\n                    locale: storeConfig.storeProfile.storeLanguage,\n                    collectShipping: true,\n                    subtotal: checkout.subtotal,\n                    currencyCode: storeConfig.currency.code,\n                };\n\n                return Promise.all([\n                    this._visaCheckoutScriptLoader.load(this._paymentMethod.config.testMode),\n                    this._braintreeVisaCheckoutPaymentProcessor.initialize(this._paymentMethod.clientToken, initOptions),\n                ])\n                .then(([visaCheckout, initOptions]) => {\n                    const signInButton = this._createSignInButton(container, this._buttonClassName);\n\n                    visaCheckout.init(initOptions);\n                    visaCheckout.on('payment.success', (paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) =>\n                        this._paymentInstrumentSelected(paymentSuccessPayload)\n                            .catch(error => onError(error))\n                    );\n                    visaCheckout.on('payment.error', (_, error) => onError(error));\n\n                    return signInButton;\n                })\n                .then(signInButton => { signInButton.style.visibility = 'visible'; });\n            })\n            .then(() => this._store.getState());\n    }\n\n    signIn(): Promise<InternalCheckoutSelectors> {\n        throw new NotImplementedError(\n            'In order to sign in via VisaCheckout, the shopper must click on \"Visa Checkout\" button.'\n        );\n    }\n\n    signOut(options?: CustomerRequestOptions): Promise<InternalCheckoutSelectors> {\n        return this._store.dispatch(\n            this._remoteCheckoutActionCreator.signOut('braintreevisacheckout', options)\n        );\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        this._paymentMethod = undefined;\n\n        return this._braintreeVisaCheckoutPaymentProcessor.deinitialize()\n            .then(() => this._store.getState());\n    }\n\n    private _paymentInstrumentSelected(paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) {\n        const state = this._store.getState();\n\n        if (!this._paymentMethod) {\n            throw new Error('Payment method not initialized');\n        }\n\n        const { id: methodId } = this._paymentMethod;\n\n        return this._store.dispatch(\n            this._customerStrategyActionCreator.widgetInteraction(() => {\n                return this._braintreeVisaCheckoutPaymentProcessor.handleSuccess(\n                    paymentSuccessPayload,\n                    state.shippingAddress.getShippingAddress(),\n                    state.billingAddress.getBillingAddress()\n                )\n                .then(() => this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()));\n        }, { methodId }), { queueId: 'widgetInteraction' });\n    }\n\n    private _createSignInButton(containerId: string, buttonClass: string): HTMLElement {\n        const container = document.querySelector(`#${containerId}`);\n\n        if (!container) {\n            throw new Error('Need a container to place the button');\n        }\n\n        return (container.querySelector('.' + buttonClass) as HTMLElement) ||\n            this._insertVisaCheckoutButton(container, buttonClass);\n    }\n\n    private _insertVisaCheckoutButton(container: Element, buttonClass: string): HTMLElement {\n        const buttonSource = 'https://secure.checkout.visa.com/wallet-services-web/xo/button.png?acceptCanadianVisaDebit=false&cobrand=true&size=154';\n        const buttonTemplate = `\n            <img\n                alt=\"Visa Checkout\"\n                class=\"v-button\"\n                role=\"button\"\n                src=\"${buttonSource}\"\n                />\n            <a class=\"v-learn v-learn-default\" style=\"text-align: right; display: block; font-size: 10px; color: #003366;\" href=\"#\" data-locale=\"en_US\">Tell Me More</a>`;\n\n        const visaCheckoutButton = document.createElement('div');\n        visaCheckoutButton.style.display = 'flex';\n        visaCheckoutButton.style.flexDirection = 'column';\n        visaCheckoutButton.style.visibility = 'hidden';\n        visaCheckoutButton.className = buttonClass;\n        visaCheckoutButton.innerHTML = buttonTemplate;\n\n        container.appendChild(visaCheckoutButton);\n\n        return visaCheckoutButton;\n    }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotImplementedError, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport { ChasePayScriptLoader, ChasePaySuccessPayload } from '../../../payment/strategies/chasepay';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { CustomerInitializeOptions, CustomerRequestOptions } from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class ChasePayCustomerStrategy implements CustomerStrategy {\n    private _paymentMethod?: PaymentMethod;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n        private _chasePayScriptLoader: ChasePayScriptLoader,\n        private _requestSender: RequestSender,\n        private _formPoster: FormPoster\n    ) {}\n\n    initialize(options: CustomerInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { chasepay: chasePayOptions, methodId } = options;\n\n        if (!chasePayOptions || !methodId) {\n            throw new InvalidArgumentError('Unable to proceed because \"options.chasepay\" argument is not provided.');\n        }\n\n        return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n            .then(state => {\n                this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n                const cart = state.cart.getCart();\n                const storeConfig = state.config.getStoreConfig();\n\n                if (!cart) {\n                    throw new MissingDataError(MissingDataErrorType.MissingCart);\n                }\n\n                if (!storeConfig) {\n                    throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n                }\n\n                if (!this._paymentMethod || !this._paymentMethod.initializationData.digitalSessionId) {\n                    throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n                }\n\n                const { container } = chasePayOptions;\n\n                return this._chasePayScriptLoader.load(this._paymentMethod.config.testMode)\n                    .then(JPMC => {\n                        const ChasePay = JPMC.ChasePay;\n\n                        ChasePay.configure({\n                            language: storeConfig.storeProfile.storeLanguage,\n                        });\n\n                        if (ChasePay.isChasePayUp) {\n                            ChasePay.insertButtons({\n                                containers: [container],\n                            });\n                        }\n\n                        ChasePay.on(ChasePay.EventType.START_CHECKOUT, () => {\n                            this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n                                .then(() => {\n                                    const state = this._store.getState();\n                                    const method = state.paymentMethods.getPaymentMethod(methodId);\n                                    const sessionId = method && method.initializationData && method.initializationData.digitalSessionId;\n\n                                    if (sessionId) {\n                                        ChasePay.startCheckout(sessionId);\n                                    }\n                                });\n                        });\n\n                        ChasePay.on(ChasePay.EventType.COMPLETE_CHECKOUT, (payload: ChasePaySuccessPayload) => {\n                            const state = this._store.getState();\n                            const method = state.paymentMethods.getPaymentMethod(methodId);\n                            const requestId = method && method.initializationData && method.initializationData.merchantRequestId;\n\n                            if (requestId) {\n                                this._setExternalCheckoutData(payload, requestId)\n                                    .then(() => {\n                                        this._reloadPage();\n                                });\n                            }\n                        });\n                    });\n            })\n            .then(() => this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n\n    signIn(): Promise<InternalCheckoutSelectors> {\n        throw new NotImplementedError(\n            'In order to sign in via Chase Pay®, the shopper must click on \"Chase Pay®\" button.'\n        );\n    }\n\n    signOut(options?: CustomerRequestOptions): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n        const payment = state.payment.getPaymentId();\n\n        if (!payment) {\n            return Promise.resolve(this._store.getState());\n        }\n\n        return this._store.dispatch(\n            this._remoteCheckoutActionCreator.signOut(payment.providerId, options)\n        );\n    }\n\n    private _setExternalCheckoutData(payload: ChasePaySuccessPayload, requestId: string): Promise<Response<any>> {\n        const url = `checkout.php?provider=chasepay&action=set_external_checkout`;\n        const options = {\n            headers: {\n                Accept: 'text/html',\n                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n            },\n            body: {\n                sessionToken: payload.sessionToken,\n                merchantRequestId: requestId,\n            },\n            method: 'post',\n        };\n\n        return this._requestSender.sendRequest(url, options);\n    }\n\n    private _reloadPage() {\n        this._formPoster.postForm('/checkout.php', {\n            headers: {\n                Accept: 'text/html',\n                'Content-Type': 'application/x-www-form-urlencoded',\n            },\n            params: {\n                fromChasePay: true,\n            },\n        });\n    }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport CustomerActionCreator from '../../customer-action-creator';\nimport CustomerCredentials from '../../customer-credentials';\nimport { CustomerRequestOptions } from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class DefaultCustomerStrategy implements CustomerStrategy {\n    constructor(\n        private _store: CheckoutStore,\n        private _customerActionCreator: CustomerActionCreator\n    ) {}\n\n    signIn(credentials: CustomerCredentials, options?: CustomerRequestOptions): Promise<InternalCheckoutSelectors> {\n        return this._store.dispatch(\n            this._customerActionCreator.signInCustomer(credentials, options)\n        );\n    }\n\n    signOut(options?: CustomerRequestOptions): Promise<InternalCheckoutSelectors> {\n        return this._store.dispatch(\n            this._customerActionCreator.signOutCustomer(options)\n        );\n    }\n\n    initialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotImplementedError } from '../../../common/error/errors';\nimport { bindDecorator as bind } from '../../../common/utility';\nimport { GooglePayPaymentProcessor } from '../../../payment/strategies/googlepay';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { getShippableItemsCount } from '../../../shipping';\nimport { CustomerInitializeOptions, CustomerRequestOptions } from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nimport GooglePayCustomerInitializeOptions from './googlepay-customer-initialize-options';\n\nexport default class GooglePayCustomerStrategy implements CustomerStrategy {\n    private _walletButton?: HTMLElement;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n        private _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n        private _formPoster: FormPoster\n    ) {}\n\n    initialize(options: CustomerInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { methodId }  = options;\n\n        const googlePayOptions = this._getGooglePayOptions(options);\n\n        if (!methodId) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        return this._googlePayPaymentProcessor.initialize(methodId)\n            .then(() => {\n                this._walletButton = this._createSignInButton(googlePayOptions.container, googlePayOptions);\n            })\n            .then(() => this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        if (this._walletButton && this._walletButton.parentNode) {\n            this._walletButton.parentNode.removeChild(this._walletButton);\n            this._walletButton = undefined;\n        }\n\n        return this._googlePayPaymentProcessor.deinitialize()\n            .then(() => this._store.getState());\n    }\n\n    signIn(): Promise<InternalCheckoutSelectors> {\n        throw new NotImplementedError(\n            'In order to sign in via Google Pay, the shopper must click on \"Google Pay\" button.'\n        );\n    }\n\n    signOut(options?: CustomerRequestOptions): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n        const payment = state.payment.getPaymentId();\n\n        if (!payment) {\n            return Promise.resolve(this._store.getState());\n        }\n\n        return this._store.dispatch(\n            this._remoteCheckoutActionCreator.signOut(payment.providerId, options)\n        );\n    }\n\n    private _createSignInButton(containerId: string, buttonOptions: GooglePayCustomerInitializeOptions): HTMLElement {\n        const container = document.querySelector(`#${containerId}`);\n        const { buttonType, buttonColor } = buttonOptions;\n\n        if (!container) {\n            throw new InvalidArgumentError('Unable to create sign-in button without valid container ID.');\n        }\n\n        const button = this._googlePayPaymentProcessor.createButton(this._handleWalletButtonClick, buttonType, buttonColor);\n\n        container.appendChild(button);\n\n        return button;\n    }\n\n    private _getGooglePayOptions(options: CustomerInitializeOptions): GooglePayCustomerInitializeOptions {\n        if (options.methodId === 'googlepayadyenv2' && options.googlepayadyenv2) {\n            return options.googlepayadyenv2;\n        }\n\n        if (options.methodId === 'googlepayauthorizenet' && options.googlepayauthorizenet) {\n            return options.googlepayauthorizenet;\n        }\n\n        if (options.methodId === 'googlepaybraintree' && options.googlepaybraintree) {\n            return options.googlepaybraintree;\n        }\n\n        if (options.methodId === 'googlepaycheckoutcom' && options.googlepaycheckoutcom) {\n            return options.googlepaycheckoutcom;\n        }\n\n        if (options.methodId === 'googlepaycybersourcev2' && options.googlepaycybersourcev2) {\n            return options.googlepaycybersourcev2;\n        }\n\n        if (options.methodId === 'googlepayorbital' && options.googlepayorbital) {\n            return options.googlepayorbital;\n        }\n\n        if (options.methodId === 'googlepaystripe' && options.googlepaystripe) {\n            return options.googlepaystripe;\n        }\n\n        throw new InvalidArgumentError();\n    }\n\n    @bind\n    private async _handleWalletButtonClick(event: Event): Promise<void> {\n        event.preventDefault();\n        const cart = this._store.getState().cart.getCartOrThrow();\n        const hasPhysicalItems = getShippableItemsCount(cart) > 0;\n\n        try {\n            const paymentData = await this._googlePayPaymentProcessor.displayWallet();\n            await this._googlePayPaymentProcessor.handleSuccess(paymentData);\n            if (hasPhysicalItems && paymentData.shippingAddress) {\n                await this._googlePayPaymentProcessor.updateShippingAddress(paymentData.shippingAddress);\n            }\n            await this._onPaymentSelectComplete();\n        } catch (error) {\n            if (error && error.message !== 'CANCELED') {\n                throw error;\n            }\n        }\n    }\n\n    private _onPaymentSelectComplete(): void {\n        this._formPoster.postForm('/checkout.php', {\n            headers: {\n                Accept: 'text/html',\n                'Content-Type': 'application/x-www-form-urlencoded',\n            },\n        });\n    }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotImplementedError } from '../../../common/error/errors';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport { getCallbackUrl, MasterpassScriptLoader } from '../../../payment/strategies/masterpass';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { CustomerInitializeOptions, CustomerRequestOptions } from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class MasterpassCustomerStrategy implements CustomerStrategy {\n    private _signInButton?: HTMLElement;\n    private _paymentMethod?: PaymentMethod;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n        private _masterpassScriptLoader: MasterpassScriptLoader\n    ) {}\n\n    initialize(options: CustomerInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { masterpass: masterpassOptions, methodId } = options;\n\n        if (!masterpassOptions || !methodId) {\n            throw new InvalidArgumentError('Unable to proceed because \"options.masterpass\" argument is not provided.');\n        }\n\n        return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n            .then(state => {\n\n                this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n                if (!this._paymentMethod || !this._paymentMethod.initializationData.checkoutId) {\n                    throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n                }\n\n                const cart = state.cart.getCart();\n                if (!cart) {\n                    throw new MissingDataError(MissingDataErrorType.MissingCart);\n                }\n\n                const storeConfig = state.config.getStoreConfig();\n                if (!storeConfig) {\n                    throw new InvalidArgumentError('Unable to retrieve store configuration');\n                }\n\n                const { container } = masterpassOptions;\n\n                const payload = {\n                    checkoutId: this._paymentMethod.initializationData.checkoutId,\n                    allowedCardTypes: this._paymentMethod.initializationData.allowedCardTypes,\n                    amount: cart.cartAmount.toString(),\n                    currency: cart.currency.code,\n                    cartId: cart.id,\n                    suppressShippingAddress: false,\n                    callbackUrl: getCallbackUrl('checkout'),\n                };\n\n                const masterpassScriptLoaderParams = {\n                    useMasterpassSrc: this._paymentMethod.initializationData.isMasterpassSrcEnabled,\n                    language: storeConfig.storeProfile.storeLanguage,\n                    testMode: this._paymentMethod.config.testMode,\n                    checkoutId: this._paymentMethod.initializationData.checkoutId,\n                };\n\n                return this._masterpassScriptLoader.load(masterpassScriptLoaderParams)\n                    .then(Masterpass => {\n                        this._signInButton = this._createSignInButton(container);\n\n                        this._signInButton.addEventListener('click', () => {\n                            Masterpass.checkout(payload);\n                        });\n                    });\n            })\n            .then(() => this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        this._paymentMethod = undefined;\n\n        if (this._signInButton && this._signInButton.parentNode) {\n            this._signInButton.parentNode.removeChild(this._signInButton);\n            this._signInButton = undefined;\n        }\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    signIn(): Promise<InternalCheckoutSelectors> {\n        throw new NotImplementedError(\n            'In order to sign in via Masterpass, the shopper must click on \"Masterpass\" button.'\n        );\n    }\n\n    signOut(options?: CustomerRequestOptions): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n        const payment = state.payment.getPaymentId();\n\n        if (!payment) {\n            return Promise.resolve(this._store.getState());\n        }\n\n        return this._store.dispatch(\n            this._remoteCheckoutActionCreator.signOut(payment.providerId, options)\n        );\n    }\n\n    private _createSignInButton(containerId: string): HTMLElement {\n        const container = document.querySelector(`#${containerId}`);\n        const state = this._store.getState();\n        const storeConfig = state.config.getStoreConfig();\n\n        if (!this._paymentMethod || !this._paymentMethod.initializationData.checkoutId) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        if (!container) {\n            throw new InvalidArgumentError('Unable to create sign-in button without valid container ID.');\n        }\n\n        if (!storeConfig) {\n            throw new InvalidArgumentError('Unable to retrieve store configuration');\n        }\n\n        const button = document.createElement('input');\n\n        button.type = 'image';\n\n        if (this._paymentMethod.initializationData.isMasterpassSrcEnabled) {\n            const subdomain = this._paymentMethod.config.testMode ? 'sandbox.' : '';\n            const { storeLanguage } = storeConfig.storeProfile;\n            const { checkoutId } = this._paymentMethod.initializationData;\n\n            const params = [\n                `locale=${storeLanguage}`,\n                `paymentmethod=master,visa,amex,discover`,\n                `checkoutid=${checkoutId}`,\n            ];\n\n            button.src = [\n                `https://${subdomain}src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg`,\n                params.join('&'),\n            ].join('?');\n        } else {\n            button.src = 'https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg';\n        }\n        container.appendChild(button);\n\n        return button;\n    }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { NotImplementedError } from '../../../common/error/errors';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { CustomerRequestOptions } from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class SquareCustomerStrategy implements CustomerStrategy {\n\n    constructor(\n        private _store: CheckoutStore,\n        private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator\n    ) {}\n\n    signIn(): Promise<InternalCheckoutSelectors> {\n        throw new NotImplementedError(\n            'In order to sign in via Masterpass, the shopper must click on \"Masterpass\" button.'\n        );\n    }\n\n    signOut(options?: CustomerRequestOptions): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n        const payment = state.payment.getPaymentId();\n\n        if (!payment) {\n            return Promise.resolve(this._store.getState());\n        }\n\n        return this._store.dispatch(\n            this._remoteCheckoutActionCreator.signOut(payment.providerId, options)\n        );\n    }\n\n    initialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n}\n","import { createAction, createErrorAction, Action } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { RequestOptions } from '../common/http-request';\n\nimport Country from './country';\nimport { CountryActionType } from './country-actions';\nimport CountryRequestSender from './country-request-sender';\n\nexport default class CountryActionCreator {\n    constructor(\n        private _countryRequestSender: CountryRequestSender\n    ) {}\n\n    loadCountries(options?: RequestOptions): Observable<Action<Country[]>> {\n        return Observable.create((observer: Observer<Action<Country[]>>) => {\n            observer.next(createAction(CountryActionType.LoadCountriesRequested));\n\n            this._countryRequestSender.loadCountries(options)\n                .then(response => {\n                    observer.next(createAction(CountryActionType.LoadCountriesSucceeded, response.body.data));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(CountryActionType.LoadCountriesFailed, response));\n                });\n        });\n    }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions } from '../common/http-request';\n\nimport { CountryResponseBody } from './country-responses';\n\nexport default class CountryRequestSender {\n    constructor(\n        private _requestSender: RequestSender,\n        private _config: { locale?: string }\n    ) {}\n\n    loadCountries({ timeout }: RequestOptions = {}): Promise<Response<CountryResponseBody>> {\n        const url = '/internalapi/v1/store/countries';\n        const headers = {\n            'Accept-Language': this._config.locale,\n        };\n\n        return this._requestSender.get(url, { headers, timeout });\n    }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\nimport { isNil, omitBy } from 'lodash';\n\nimport { joinIncludes, ContentType, RequestOptions } from '../common/http-request';\n\nimport InternalOrderRequestBody from './internal-order-request-body';\nimport { InternalOrderResponseBody } from './internal-order-responses';\nimport Order from './order';\nimport OrderParams from './order-params';\n\nexport interface SubmitOrderRequestOptions extends RequestOptions {\n    headers?: {\n        checkoutVariant?: string;\n    };\n}\n\nexport default class OrderRequestSender {\n    constructor(\n        private _requestSender: RequestSender\n    ) {}\n\n    loadOrder(orderId: number, { timeout, params }: RequestOptions<OrderParams> = {}): Promise<Response<Order>> {\n        const url = `/api/storefront/orders/${orderId}`;\n        const headers = { Accept: ContentType.JsonV1 };\n        const include = [\n            'payments',\n            'lineItems.physicalItems.socialMedia',\n            'lineItems.physicalItems.options',\n            'lineItems.digitalItems.socialMedia',\n            'lineItems.digitalItems.options',\n        ];\n\n        return this._requestSender.get(url, {\n            params: {\n                include: joinIncludes([\n                    ...include,\n                    ...(params && params.include || []),\n                ]),\n            },\n            headers,\n            timeout,\n        });\n    }\n\n    submitOrder(body: InternalOrderRequestBody, { headers, timeout }: SubmitOrderRequestOptions = {}): Promise<Response<InternalOrderResponseBody>> {\n        const url = '/internalapi/v1/checkout/order';\n\n        return this._requestSender.post(url, {\n            body,\n            headers: omitBy({\n                'X-Checkout-Variant': headers && headers.checkoutVariant,\n                'X-Checkout-SDK-Version': LIBRARY_VERSION,\n            }, isNil),\n            timeout,\n        });\n    }\n\n    finalizeOrder(orderId: number, { timeout }: RequestOptions = {}): Promise<Response<InternalOrderResponseBody>> {\n        const url = `/internalapi/v1/checkout/order/${orderId}`;\n\n        return this._requestSender.post(url, { timeout });\n    }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if the shopper chooses not to complete the spam check.\n */\nexport default class SpamProtectionNotCompletedError extends StandardError {\n    constructor() {\n        super('You haven\\'t complete our spam check. Please try again.');\n\n        this.name = 'SpamProtectionNotCompletedError';\n        this.type = 'spam_protection_not_completed';\n    }\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, from, of, Observable, Observer } from 'rxjs';\nimport { catchError, switchMap } from 'rxjs/operators';\n\nimport { CheckoutValidator, InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { SpamProtectionNotCompletedError } from '../spam-protection/errors';\n\nimport InternalOrderRequestBody from './internal-order-request-body';\nimport { FinalizeOrderAction, LoadOrderAction, LoadOrderPaymentsAction, OrderActionType, SubmitOrderAction } from './order-actions';\nimport OrderRequestBody from './order-request-body';\nimport OrderRequestSender from './order-request-sender';\n\nexport default class OrderActionCreator {\n    constructor(\n        private _orderRequestSender: OrderRequestSender,\n        private _checkoutValidator: CheckoutValidator\n    ) {}\n\n    loadOrder(orderId: number, options?: RequestOptions): Observable<LoadOrderAction> {\n        return new Observable((observer: Observer<LoadOrderAction>) => {\n            observer.next(createAction(OrderActionType.LoadOrderRequested));\n\n            this._orderRequestSender.loadOrder(orderId, options)\n                .then(response => {\n                    observer.next(createAction(OrderActionType.LoadOrderSucceeded, response.body));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(OrderActionType.LoadOrderFailed, response));\n                });\n        });\n    }\n\n    // TODO: Remove when checkout does not contain unrelated order data.\n    loadOrderPayments(orderId: number, options?: RequestOptions): Observable<LoadOrderPaymentsAction> {\n        return new Observable((observer: Observer<LoadOrderPaymentsAction>) => {\n            observer.next(createAction(OrderActionType.LoadOrderPaymentsRequested));\n\n            this._orderRequestSender.loadOrder(orderId, options)\n                .then(response => {\n                    observer.next(createAction(OrderActionType.LoadOrderPaymentsSucceeded, response.body));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(OrderActionType.LoadOrderPaymentsFailed, response));\n                });\n        });\n    }\n\n    loadCurrentOrder(options?: RequestOptions): ThunkAction<LoadOrderAction, InternalCheckoutSelectors> {\n        return store => defer(() => {\n            const orderId = this._getCurrentOrderId(store.getState());\n\n            if (!orderId) {\n                throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n            }\n\n            return this.loadOrder(orderId, options);\n        });\n    }\n\n    submitOrder(payload: OrderRequestBody, options?: RequestOptions): ThunkAction<SubmitOrderAction, InternalCheckoutSelectors> {\n        return store => concat(\n            of(createAction(OrderActionType.SubmitOrderRequested)),\n            defer(() => {\n                const state = store.getState();\n                const externalSource = state.config.getExternalSource();\n                const variantIdentificationToken = state.config.getVariantIdentificationToken();\n                const checkout = state.checkout.getCheckout();\n\n                if (!checkout) {\n                    throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n                }\n\n                if (checkout.shouldExecuteSpamCheck) {\n                    throw new SpamProtectionNotCompletedError();\n                }\n\n                return from(\n                    this._checkoutValidator.validate(checkout, options)\n                        .then(() => this._orderRequestSender.submitOrder(\n                            this._mapToOrderRequestBody(\n                                payload,\n                                checkout.customerMessage,\n                                externalSource\n                            ),\n                            {\n                                ...options,\n                                headers: {\n                                    checkoutVariant: variantIdentificationToken,\n                                },\n                            }))\n                ).pipe(\n                    switchMap(response => concat(\n                        // TODO: Remove once we can submit orders using storefront API\n                        this.loadOrder(response.body.data.order.orderId, options),\n                        of(createAction(OrderActionType.SubmitOrderSucceeded, response.body.data, { ...response.body.meta, token: response.headers.token }))\n                    ))\n                );\n            }).pipe(\n                catchError(error => throwErrorAction(OrderActionType.SubmitOrderFailed, error))\n            )\n        );\n    }\n\n    finalizeOrder(orderId: number, options?: RequestOptions): Observable<FinalizeOrderAction | LoadOrderAction> {\n        return concat(\n            of(createAction(OrderActionType.FinalizeOrderRequested)),\n            from(this._orderRequestSender.finalizeOrder(orderId, options))\n                .pipe(\n                    switchMap(response => concat(\n                        this.loadOrder(orderId, options),\n                        of(createAction(OrderActionType.FinalizeOrderSucceeded, response.body.data))\n                    ))\n                )\n        ).pipe(\n            catchError(error => throwErrorAction(OrderActionType.FinalizeOrderFailed, error))\n        );\n    }\n\n    private _getCurrentOrderId(state: InternalCheckoutSelectors): number | undefined {\n        const order = state.order.getOrder();\n        const checkout = state.checkout.getCheckout();\n\n        return (order && order.orderId) || (checkout && checkout.orderId);\n    }\n\n    private _mapToOrderRequestBody(\n        payload: OrderRequestBody,\n        customerMessage: string,\n        externalSource?: string\n    ): InternalOrderRequestBody {\n        const { payment, ...order } = payload;\n\n        if (!payment) {\n            return {\n                ...order,\n                customerMessage,\n                externalSource,\n            };\n        }\n\n        return {\n            ...order,\n            customerMessage,\n            externalSource,\n            payment: {\n                paymentData: payment.paymentData,\n                name: payment.methodId,\n                gateway: payment.gatewayId,\n            },\n        };\n    }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if we are trying to make an order finalization request for a\n * payment method that does not require such procedure.\n */\nexport default class OrderFinalizationNotRequiredError extends StandardError {\n    constructor() {\n        super('The current order does not need to be finalized at this stage.');\n\n        this.name = 'OrderFinalizationNotRequiredError';\n        this.type = 'order_finalization_not_required';\n    }\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, empty, of, Observable } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { InternalCheckoutSelectors, ReadableCheckoutStore } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { LoadOrderPaymentsAction, OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../order';\nimport { OrderFinalizationNotRequiredError } from '../order/errors';\nimport { SpamProtectionAction, SpamProtectionActionCreator } from '../spam-protection';\n\nimport { PaymentInitializeOptions, PaymentRequestOptions } from './payment-request-options';\nimport { PaymentStrategyActionType, PaymentStrategyDeinitializeAction, PaymentStrategyExecuteAction, PaymentStrategyFinalizeAction, PaymentStrategyInitializeAction, PaymentStrategyWidgetAction } from './payment-strategy-actions';\nimport PaymentStrategyRegistry from './payment-strategy-registry';\nimport PaymentStrategyType from './payment-strategy-type';\nimport { PaymentStrategy } from './strategies';\n\nexport default class PaymentStrategyActionCreator {\n    constructor(\n        private _strategyRegistry: PaymentStrategyRegistry,\n        private _orderActionCreator: OrderActionCreator,\n        private _spamProtectionActionCreator: SpamProtectionActionCreator\n    ) {}\n\n    execute(payload: OrderRequestBody, options?: RequestOptions): ThunkAction<PaymentStrategyExecuteAction | SpamProtectionAction, InternalCheckoutSelectors> {\n        const { payment = {} as OrderPaymentRequestBody, useStoreCredit } = payload;\n        const meta = { methodId: payment.methodId };\n\n        return store => {\n            const { checkout } = store.getState();\n            const { shouldExecuteSpamCheck } = checkout.getCheckoutOrThrow();\n\n            return concat(\n                shouldExecuteSpamCheck ? this._spamProtectionActionCreator.verifyCheckoutSpamProtection()(store) : empty(),\n                of(createAction(PaymentStrategyActionType.ExecuteRequested, undefined, meta)),\n                defer(() => {\n                    const state = store.getState();\n\n                    let strategy: PaymentStrategy;\n\n                    if (state.payment.isPaymentDataRequired(useStoreCredit)) {\n                        const method = state.paymentMethods.getPaymentMethod(payment.methodId, payment.gatewayId);\n\n                        if (!method) {\n                            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n                        }\n\n                        strategy = this._strategyRegistry.getByMethod(method);\n                    } else {\n                        strategy = this._strategyRegistry.get(PaymentStrategyType.NO_PAYMENT_DATA_REQUIRED);\n                    }\n\n                    return strategy\n                        .execute(payload, { ...options, methodId: payment.methodId, gatewayId: payment.gatewayId })\n                        .then(() => createAction(PaymentStrategyActionType.ExecuteSucceeded, undefined, meta));\n                })\n            ).pipe(\n                catchError(error => throwErrorAction(PaymentStrategyActionType.ExecuteFailed, error, meta))\n            );\n        };\n    }\n\n    finalize(options?: RequestOptions): ThunkAction<PaymentStrategyFinalizeAction, InternalCheckoutSelectors> {\n        return store => concat(\n            of(createAction(PaymentStrategyActionType.FinalizeRequested)),\n            this._loadOrderPaymentsIfNeeded(store, options),\n            defer(() => {\n                const state = store.getState();\n                const { providerId = '', gatewayId = '' } = state.payment.getPaymentId() || {};\n                const method = state.paymentMethods.getPaymentMethod(providerId, gatewayId);\n\n                if (!method) {\n                    throw new OrderFinalizationNotRequiredError();\n                }\n\n                return this._strategyRegistry.getByMethod(method)\n                    .finalize({ ...options, methodId: method.id, gatewayId: method.gateway })\n                    .then(() => createAction(PaymentStrategyActionType.FinalizeSucceeded, undefined, { methodId: method.id }));\n            })\n        ).pipe(\n            catchError(error => {\n                const state = store.getState();\n                const payment = state.payment.getPaymentId();\n\n                return throwErrorAction(PaymentStrategyActionType.FinalizeFailed, error, { methodId: payment && payment.providerId });\n            })\n        );\n    }\n\n    initialize(options: PaymentInitializeOptions): ThunkAction<PaymentStrategyInitializeAction, InternalCheckoutSelectors> {\n        const { methodId, gatewayId } = options;\n\n        return store => defer(() => {\n            const state = store.getState();\n            const method = state.paymentMethods.getPaymentMethod(methodId, gatewayId);\n\n            if (!method) {\n                throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n            }\n\n            if (methodId && state.paymentStrategies.isInitialized(methodId)) {\n                return empty();\n            }\n\n            return concat(\n                of(createAction(PaymentStrategyActionType.InitializeRequested, undefined, { methodId })),\n                this._strategyRegistry.getByMethod(method)\n                    .initialize({ ...options, methodId, gatewayId })\n                    .then(() => createAction(PaymentStrategyActionType.InitializeSucceeded, undefined, { methodId }))\n            );\n        }).pipe(\n            catchError(error => throwErrorAction(PaymentStrategyActionType.InitializeFailed, error, { methodId }))\n        );\n    }\n\n    deinitialize(options: PaymentRequestOptions): ThunkAction<PaymentStrategyDeinitializeAction, InternalCheckoutSelectors> {\n        const { methodId, gatewayId } = options;\n\n        return store => defer(() => {\n            const state = store.getState();\n            const method = state.paymentMethods.getPaymentMethod(methodId, gatewayId);\n\n            if (!method) {\n                throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n            }\n\n            if (methodId && !state.paymentStrategies.isInitialized(methodId)) {\n                return empty();\n            }\n\n            return concat(\n                of(createAction(PaymentStrategyActionType.DeinitializeRequested, undefined, { methodId })),\n                this._strategyRegistry.getByMethod(method)\n                    .deinitialize({ ...options, methodId, gatewayId })\n                    .then(() => createAction(PaymentStrategyActionType.DeinitializeSucceeded, undefined, { methodId }))\n            );\n        }).pipe(\n            catchError(error => throwErrorAction(PaymentStrategyActionType.DeinitializeFailed, error, { methodId }))\n        );\n    }\n\n    widgetInteraction(method: () => Promise<any>, options?: PaymentRequestOptions): Observable<PaymentStrategyWidgetAction> {\n        const methodId = options && options.methodId;\n        const meta = { methodId };\n\n        return concat(\n            of(createAction(PaymentStrategyActionType.WidgetInteractionStarted, undefined, meta)),\n            defer(() =>\n                method().then(() => createAction(PaymentStrategyActionType.WidgetInteractionFinished, undefined, meta))\n            )\n        ).pipe(\n            catchError(error => throwErrorAction(PaymentStrategyActionType.WidgetInteractionFailed, error, meta))\n        );\n    }\n\n    private _loadOrderPaymentsIfNeeded(store: ReadableCheckoutStore, options?: RequestOptions): Observable<LoadOrderPaymentsAction> {\n        const state = store.getState();\n        const checkout = state.checkout.getCheckout();\n\n        if (checkout && checkout.orderId) {\n            return this._orderActionCreator.loadOrderPayments(checkout.orderId, options);\n        }\n\n        return empty();\n    }\n}\n","import { isEqual } from 'lodash';\n\nimport { PartialDeep } from '../common/types';\n\nimport Cart from './cart';\n\nexport default class CartComparator {\n    isEqual(cartA: Cart, cartB: Cart): boolean {\n        return isEqual(\n            this._normalize(cartA),\n            this._normalize(cartB)\n        );\n    }\n\n    private _normalize(cart: Cart): PartialDeep<Cart> {\n        return {\n            cartAmount: cart.cartAmount,\n            currency: cart.currency,\n            id: cart.id,\n            lineItems: {\n                digitalItems: cart.lineItems.digitalItems\n                    .slice()\n                    .sort((itemA, itemB) =>\n                        `${itemA.productId}${itemA.variantId}`.localeCompare(`${itemB.productId}${itemB.variantId}`)\n                    )\n                    .map(item => ({\n                        extendedSalePrice: item.extendedSalePrice,\n                        productId: item.productId,\n                        quantity: item.quantity,\n                        variantId: item.variantId,\n                    })),\n                giftCertificates: cart.lineItems.giftCertificates\n                    .slice()\n                    .sort((itemA, itemB) => `${itemA.id}`.localeCompare(`${itemB.id}`))\n                    .map(item => ({\n                        amount: item.amount,\n                        recipient: item.recipient,\n                    })),\n                physicalItems: cart.lineItems.physicalItems\n                    .slice()\n                    .sort((itemA, itemB) =>\n                        `${itemA.productId}${itemA.variantId}`.localeCompare(`${itemB.productId}${itemB.variantId}`)\n                    )\n                    .map(item => ({\n                        extendedSalePrice: item.extendedSalePrice,\n                        productId: item.productId,\n                        quantity: item.quantity,\n                        variantId: item.variantId,\n                        giftWrapping: item.giftWrapping,\n                    })),\n            },\n        };\n    }\n}\n","import { ComparableCheckout } from '../../checkout';\nimport { StandardError } from '../../common/error/errors';\n\nexport default class CartChangedError extends StandardError {\n    /**\n     * @alpha\n     * Please note that this option is currently in an early stage of\n     * development. Therefore the API is unstable and not ready for public\n     * consumption.\n     */\n    data: { previous: ComparableCheckout; updated: ComparableCheckout };\n\n    constructor(\n        previous: ComparableCheckout,\n        updated: ComparableCheckout\n    ) {\n        super('An update to your shopping cart has been detected and your available shipping costs have been updated.');\n\n        this.name = 'CartChangedError';\n        this.type = 'cart_changed';\n        this.data = {\n            previous,\n            updated,\n        };\n    }\n}\n","import { isEqual, map } from 'lodash';\n\nimport { Cart, CartComparator } from '../cart';\nimport { CartChangedError } from '../cart/errors';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { Coupon, GiftCertificate } from '../coupon';\n\nimport Checkout from './checkout';\nimport CheckoutRequestSender from './checkout-request-sender';\nexport type ComparableCheckout = Pick<Checkout, 'outstandingBalance' | 'coupons' | 'giftCertificates'>\n    & {\n        cart: Partial<Cart>;\n    };\n\nexport default class CheckoutValidator {\n    constructor(\n        private _checkoutRequestSender: CheckoutRequestSender\n    ) {}\n\n    validate(checkout?: Checkout, options?: RequestOptions): Promise<void> {\n        if (!checkout) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n        }\n\n        return this._checkoutRequestSender.loadCheckout(checkout.id, options)\n            .then(response => {\n                const comparator = new CartComparator();\n\n                if (checkout.outstandingBalance === response.body.outstandingBalance\n                    && this._compareCoupons(checkout.coupons, response.body.coupons)\n                    && this._compareGiftCertificates(checkout.giftCertificates, response.body.giftCertificates)\n                    && comparator.isEqual(checkout.cart, response.body.cart)\n                ) {\n                    return;\n                }\n\n                throw new CartChangedError(\n                    this._getComparableCheckout(checkout),\n                    this._getComparableCheckout(response.body)\n                );\n            });\n    }\n\n    private _compareCoupons(couponsA: Coupon[], couponsB: Coupon[]): boolean {\n        return isEqual(map(couponsA, 'code'), map(couponsB, 'code'));\n    }\n\n    private _compareGiftCertificates(giftCertificatesA: GiftCertificate[], giftCertificatesB: GiftCertificate[]): boolean {\n        return isEqual(map(giftCertificatesA, 'code'), map(giftCertificatesB, 'code'));\n    }\n\n    private _getComparableCheckout(\n        checkout: Checkout\n    ): ComparableCheckout  {\n        const { cart, coupons, giftCertificates, outstandingBalance } = checkout;\n\n        return {\n            cart: {\n                cartAmount: cart.cartAmount,\n                currency: cart.currency,\n                lineItems: cart.lineItems,\n            },\n            coupons,\n            giftCertificates,\n            outstandingBalance,\n        };\n    }\n}\n","export default class CancellablePromise<T> {\n    promise: Promise<T>;\n    cancel!: (reason?: any) => void;\n\n    constructor(promise: Promise<T>) {\n        const cancellable = new Promise<T>((_, reject) => {\n            this.cancel = reject;\n        });\n\n        this.promise = Promise.race([promise, cancellable]);\n    }\n}\n","import { StandardError } from '../../error/errors';\n\nexport default class UnexpectedDetachmentError extends StandardError {\n    constructor(message?: string) {\n        super(message || 'Unable to proceed because the required element is unexpectedly detached from the page.');\n\n        this.name = 'UnexpectedDetachmentError';\n        this.type = 'unexpected_detachment';\n    }\n}\n","import { CancellablePromise } from '../utility';\n\nimport { UnexpectedDetachmentError } from './errors';\nimport { MutationObserverFactory } from './mutation-observer';\n\nexport default class DetachmentObserver {\n    constructor(\n        private _mutationObserver: MutationObserverFactory\n    ) {}\n\n    async ensurePresence<T>(targets: Node[], promise: Promise<T>): Promise<T> {\n        const cancellable = new CancellablePromise(promise);\n\n        const observer = this._mutationObserver.create(mutationsList => {\n            mutationsList.forEach(mutation => {\n                const removedTargets = Array.from(mutation.removedNodes)\n                    .filter(node =>\n                        targets.some(target =>\n                            node === target || node.contains(target)\n                        )\n                    );\n\n                if (removedTargets.length === 0) {\n                    return;\n                }\n\n                cancellable.cancel(new UnexpectedDetachmentError());\n            });\n        });\n\n        observer.observe(document.body, { childList: true, subtree: true });\n\n        try {\n            const output = await cancellable.promise;\n\n            observer.disconnect();\n\n            return output;\n        } catch (error) {\n            observer.disconnect();\n\n            throw error;\n        }\n    }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if the shopper chooses not to complete the spam protection\n * challenge (i.e.: they close the reCaptcha window).\n */\nexport default class CardingProtectionChallengeNotCompletedError extends StandardError {\n    constructor() {\n        super('Please complete our human verification challenge and try again.');\n\n        this.name = 'CardingProtectionChallengeNotCompletedError';\n        this.type = 'carding_protection_challenge_not_completed';\n    }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if we fail to complete the required spam protection\n * verification due to an unknown reason.\n */\nexport default class CardingProtectionFailedError extends StandardError {\n    constructor() {\n        super('We were not able to verify that you are not a robot. Please try again.');\n\n        this.name = 'CardingProtectionFailedError';\n        this.type = 'carding_protection_failed';\n    }\n}\n","import { switchMap, take } from 'rxjs/operators';\n\nimport { RequestError } from '../common/error/errors';\nimport { PaymentAdditionalAction } from '../payment';\n\nimport { CardingProtectionChallengeNotCompletedError, CardingProtectionFailedError, SpamProtectionChallengeNotCompletedError } from './errors';\nimport GoogleRecaptcha from './google-recaptcha';\n\nexport default class PaymentHumanVerificationHandler {\n\n    constructor(\n        private _googleRecaptcha: GoogleRecaptcha\n    ) {}\n\n    async handle(error: Error): Promise<PaymentAdditionalAction> {\n        if (!this._isPaymentHumanVerificationRequest(error)) {\n            throw error;\n        }\n\n        await this._initialize(error.body.additional_action_required.data.key);\n\n        return this._googleRecaptcha.execute()\n            .pipe(take(1))\n            .pipe(switchMap(async ({ error, token }) => {\n                if (error instanceof SpamProtectionChallengeNotCompletedError) {\n                    throw new CardingProtectionChallengeNotCompletedError();\n                }\n\n                if (error || !token) {\n                    throw new CardingProtectionFailedError();\n                }\n\n                return {\n                    type: 'recaptcha_v2_verification',\n                    data: {\n                        human_verification_token: token,\n                    },\n                };\n            })).toPromise();\n    }\n\n    private _initialize(recaptchaSitekey: string): Promise<void> {\n        const cardingProtectionElementId = 'cardingProtectionContainer';\n\n        let cardingProtectionElement = document.getElementById(cardingProtectionElementId);\n        if (cardingProtectionElement && cardingProtectionElement.parentNode) {\n            cardingProtectionElement.parentNode.removeChild(cardingProtectionElement);\n        }\n\n        cardingProtectionElement = document.createElement('div');\n        cardingProtectionElement.setAttribute('id', cardingProtectionElementId);\n        document.body.appendChild(cardingProtectionElement);\n\n        return this._googleRecaptcha.load(cardingProtectionElementId, recaptchaSitekey);\n    }\n\n    private _isPaymentHumanVerificationRequest(error: Error): error is RequestError {\n        const { additional_action_required, status } = (error as RequestError).body || {};\n\n        return status === 'additional_action_required'\n            && additional_action_required\n            && additional_action_required.type === 'recaptcha_v2_verification';\n    }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport default class InvalidHostedFormError extends StandardError {\n    constructor(message?: string) {\n        super(message || 'Unable to proceed due to an unknown error with the hosted payment form.');\n\n        this.name = 'InvalidHostedFormError';\n        this.type = 'invalid_hosted_form';\n    }\n}\n","import { values } from 'lodash';\nimport { fromEvent } from 'rxjs';\nimport { switchMap, take } from 'rxjs/operators';\n\nimport { DetachmentObserver } from '../common/dom';\nimport { mapFromPaymentErrorResponse } from '../common/error/errors';\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { parseUrl } from '../common/url';\nimport { CardInstrument } from '../payment/instrument';\n\nimport { InvalidHostedFormConfigError, InvalidHostedFormError, InvalidHostedFormValueError } from './errors';\nimport { HostedFieldEvent, HostedFieldEventType } from './hosted-field-events';\nimport HostedFieldType from './hosted-field-type';\nimport { HostedFieldStylesMap } from './hosted-form-options';\nimport HostedFormOrderData from './hosted-form-order-data';\nimport { HostedInputEventMap, HostedInputEventType, HostedInputSubmitErrorEvent, HostedInputValidateEvent } from './iframe-content';\n\nexport const RETRY_INTERVAL = 60 * 1000;\nexport const LAST_RETRY_KEY = 'lastRetry';\n\nexport default class HostedField {\n    private _iframe: HTMLIFrameElement;\n\n    constructor(\n        private _type: HostedFieldType,\n        private _containerId: string,\n        private _placeholder: string,\n        private _accessibilityLabel: string,\n        private _styles: HostedFieldStylesMap,\n        private _eventPoster: IframeEventPoster<HostedFieldEvent>,\n        private _eventListener: IframeEventListener<HostedInputEventMap>,\n        private _detachmentObserver: DetachmentObserver,\n        private _cardInstrument?: CardInstrument\n    ) {\n        this._iframe = document.createElement('iframe');\n\n        this._iframe.src = `/checkout/payment/hosted-field?version=${LIBRARY_VERSION}`;\n        this._iframe.style.border = 'none';\n        this._iframe.style.height = '100%';\n        this._iframe.style.overflow = 'hidden';\n        this._iframe.style.width = '100%';\n    }\n\n    getType(): HostedFieldType {\n        return this._type;\n    }\n\n    async attach(): Promise<void> {\n        const container = document.getElementById(this._containerId);\n\n        if (!container) {\n            throw new InvalidHostedFormConfigError('Unable to proceed because the provided container ID is not valid.');\n        }\n\n        container.appendChild(this._iframe);\n        this._eventListener.listen();\n\n        const promise = fromEvent(this._iframe, 'load')\n            .pipe(\n                switchMap(async ({ target }) => {\n                    const contentWindow = target && (target as HTMLIFrameElement).contentWindow;\n\n                    if (!contentWindow) {\n                        throw new Error('The content window of the iframe cannot be accessed.');\n                    }\n\n                    this._eventPoster.setTarget(contentWindow);\n\n                    await this._eventPoster.post({\n                        type: HostedFieldEventType.AttachRequested,\n                        payload: {\n                            accessibilityLabel: this._accessibilityLabel,\n                            cardInstrument: this._cardInstrument,\n                            fontUrls: this._getFontUrls(),\n                            placeholder: this._placeholder,\n                            styles: this._styles,\n                            origin: document.location.origin,\n                            type: this._type,\n                        },\n                    }, {\n                        successType: HostedInputEventType.AttachSucceeded,\n                        errorType: HostedInputEventType.AttachFailed,\n                    });\n                }),\n                take(1)\n            ).toPromise();\n\n        await this._detachmentObserver.ensurePresence([this._iframe], promise);\n    }\n\n    detach(): void {\n        if (!this._iframe.parentElement) {\n            return;\n        }\n\n        this._iframe.parentElement.removeChild(this._iframe);\n        this._eventListener.stopListen();\n    }\n\n    async submitForm(\n        fields: HostedFieldType[],\n        data: HostedFormOrderData\n    ): Promise<void> {\n        try {\n            const promise = this._eventPoster.post({\n                type: HostedFieldEventType.SubmitRequested,\n                payload: { fields, data },\n            }, {\n                successType: HostedInputEventType.SubmitSucceeded,\n                errorType: HostedInputEventType.SubmitFailed,\n            });\n\n            await this._detachmentObserver.ensurePresence([this._iframe], promise);\n        } catch (event) {\n            if (this._isSubmitErrorEvent(event)) {\n                if (event.payload.error.code === 'hosted_form_error') {\n                    throw new InvalidHostedFormError(event.payload.error.message);\n                }\n\n                if (event.payload.response) {\n                    throw mapFromPaymentErrorResponse(event.payload.response);\n                }\n\n                throw new Error(event.payload.error.message);\n            }\n\n            throw event;\n        }\n    }\n\n    async validateForm(): Promise<void> {\n        const promise = this._eventPoster.post<HostedInputValidateEvent>({\n            type: HostedFieldEventType.ValidateRequested,\n        }, {\n            successType: HostedInputEventType.Validated,\n        });\n\n        const { payload } = await this._detachmentObserver.ensurePresence([this._iframe], promise);\n\n        if (!payload.isValid) {\n            throw new InvalidHostedFormValueError(payload.errors);\n        }\n    }\n\n    private _getFontUrls(): string[] {\n        const hostname = 'fonts.googleapis.com';\n        const links = document.querySelectorAll(`link[href*='${hostname}'][rel='stylesheet']`);\n\n        return Array.prototype.slice.call(links)\n            .filter(link => parseUrl(link.href).hostname === hostname)\n            .filter(link => values(this._styles)\n                .map(style => style && style.fontFamily)\n                .filter((family): family is string => typeof family === 'string')\n                .some(family => family.split(/,\\s/).some(name => link.href.indexOf(name.replace(' ', '+')) !== -1))\n            )\n            .map(link => link.href);\n    }\n\n    private _isSubmitErrorEvent(event: any): event is HostedInputSubmitErrorEvent {\n        return event.type === HostedInputEventType.SubmitFailed;\n    }\n}\n","import { noop, without } from 'lodash';\n\nimport { IframeEventListener } from '../common/iframe';\nimport { OrderPaymentRequestBody } from '../order';\nimport { PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport { InvalidHostedFormConfigError } from './errors';\nimport HostedField from './hosted-field';\nimport HostedFormOptions from './hosted-form-options';\nimport HostedFormOrderDataTransformer from './hosted-form-order-data-transformer';\nimport { HostedInputEnterEvent, HostedInputEventMap, HostedInputEventType } from './iframe-content';\n\ntype HostedFormEventCallbacks = Pick<HostedFormOptions, 'onBlur' | 'onCardTypeChange' | 'onFocus' | 'onEnter' | 'onValidate'>;\n\nexport default class HostedForm {\n    private _bin?: string;\n    private _cardType?: string;\n\n    constructor(\n        private _fields: HostedField[],\n        private _eventListener: IframeEventListener<HostedInputEventMap>,\n        private _payloadTransformer: HostedFormOrderDataTransformer,\n        private _eventCallbacks: HostedFormEventCallbacks,\n        private _paymentHumanVerificationHandler: PaymentHumanVerificationHandler\n    ) {\n        const { onBlur = noop, onCardTypeChange = noop, onFocus = noop, onValidate = noop } = this._eventCallbacks;\n\n        this._eventListener.addListener(HostedInputEventType.Blurred, ({ payload }) => onBlur(payload));\n        this._eventListener.addListener(HostedInputEventType.CardTypeChanged, ({ payload }) => onCardTypeChange(payload));\n        this._eventListener.addListener(HostedInputEventType.Focused, ({ payload }) => onFocus(payload));\n        this._eventListener.addListener(HostedInputEventType.Validated, ({ payload }) => onValidate(payload));\n        this._eventListener.addListener(HostedInputEventType.Entered, this._handleEnter);\n\n        this._eventListener.addListener(HostedInputEventType.CardTypeChanged, ({ payload }) => this._cardType = payload.cardType);\n        this._eventListener.addListener(HostedInputEventType.BinChanged, ({ payload }) => this._bin = payload.bin);\n    }\n\n    getBin(): string | undefined {\n        return this._bin;\n    }\n\n    getCardType(): string | undefined {\n        return this._cardType;\n    }\n\n    async attach(): Promise<void> {\n        this._eventListener.listen();\n\n        const field = this._getFirstField();\n        const otherFields = without(this._fields, field);\n\n        await field.attach();\n        await Promise.all(otherFields.map(otherField => otherField.attach()));\n    }\n\n    detach(): void {\n        this._eventListener.stopListen();\n\n        this._fields.forEach(field => {\n            field.detach();\n        });\n    }\n\n    async submit(payload: OrderPaymentRequestBody): Promise<void> {\n        try {\n            return await this._getFirstField().submitForm(\n                this._fields.map(field => field.getType()),\n                this._payloadTransformer.transform(payload)\n            );\n        } catch (error) {\n            const additionalAction = await this._paymentHumanVerificationHandler.handle(error);\n\n            return await this._getFirstField().submitForm(\n                this._fields.map(field => field.getType()),\n                this._payloadTransformer.transform(payload, additionalAction)\n            );\n        }\n    }\n\n    async validate(): Promise<void> {\n        return await this._getFirstField().validateForm();\n    }\n\n    private _getFirstField(): HostedField {\n        const field = this._fields[0];\n\n        if (!field) {\n            throw new InvalidHostedFormConfigError('Unable to proceed because the payment form has no field defined.');\n        }\n\n        return field;\n    }\n\n    private _handleEnter: (event: HostedInputEnterEvent) => Promise<void> = async ({ payload }) => {\n        try {\n            await this.validate();\n        } catch (error) {\n            // Catch form validation error because we want to trigger `onEnter`\n            // irrespective of the validation result.\n            if (error.name !== 'InvalidHostedFormValueError') {\n                throw error;\n            }\n        }\n\n        const { onEnter = noop } = this._eventCallbacks;\n\n        onEnter(payload);\n    };\n}\n","import { omit } from 'lodash';\n\nimport { ReadableCheckoutStore } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { OrderPaymentRequestBody } from '../order';\nimport { isVaultedInstrument, HostedCreditCardInstrument, PaymentAdditionalAction } from '../payment';\n\nimport HostedFormOrderData from './hosted-form-order-data';\n\nexport default class HostedFormOrderDataTransformer {\n    constructor(\n        private _store: ReadableCheckoutStore\n    ) {}\n\n    transform(payload: OrderPaymentRequestBody, additionalAction?: PaymentAdditionalAction): HostedFormOrderData {\n        const state = this._store.getState();\n        const checkout = state.checkout.getCheckout();\n        const config = state.config.getConfig();\n        const instrumentMeta = state.instruments.getInstrumentsMeta();\n        const order = state.order.getOrder();\n        const orderMeta = state.order.getOrderMeta();\n        const payment = omit(payload.paymentData, 'ccExpiry', 'ccName', 'ccNumber', 'ccCvv') as HostedCreditCardInstrument;\n        const paymentMethod = state.paymentMethods.getPaymentMethod(payload.methodId, payload.gatewayId);\n        const paymentMethodMeta = state.paymentMethods.getPaymentMethodsMeta();\n        const authToken = instrumentMeta && payment && isVaultedInstrument(payment) ?\n            `${state.payment.getPaymentToken()}, ${instrumentMeta.vaultAccessToken}` :\n            state.payment.getPaymentToken();\n\n        if (!authToken) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n        }\n\n        return {\n            additionalAction,\n            authToken,\n            checkout,\n            config,\n            order,\n            orderMeta,\n            payment,\n            paymentMethod,\n            paymentMethodMeta,\n        };\n    }\n}\n","import { createScriptLoader } from '@bigcommerce/script-loader';\nimport { pick } from 'lodash';\n\nimport { ReadableCheckoutStore } from '../checkout';\nimport { DetachmentObserver, MutationObserverFactory } from '../common/dom';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { CardInstrument } from '../payment/instrument';\nimport { createSpamProtection, PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport HostedField from './hosted-field';\nimport HostedFieldType from './hosted-field-type';\nimport HostedForm from './hosted-form';\nimport HostedFormOptions, { HostedCardFieldOptionsMap, HostedStoredCardFieldOptionsMap } from './hosted-form-options';\nimport HostedFormOrderDataTransformer from './hosted-form-order-data-transformer';\n\nexport default class HostedFormFactory {\n    constructor(\n        private _store: ReadableCheckoutStore\n    ) {}\n\n    create(host: string, options: HostedFormOptions): HostedForm {\n        const fieldTypes = Object.keys(options.fields) as HostedFieldType[];\n        const fields = fieldTypes.reduce<HostedField[]>((result, type) => {\n            const fields = options.fields as HostedStoredCardFieldOptionsMap & HostedCardFieldOptionsMap;\n            const fieldOptions = fields[type];\n\n            if (!fieldOptions) {\n                return result;\n            }\n\n            return [\n                ...result,\n                new HostedField(\n                    type,\n                    fieldOptions.containerId,\n                    fieldOptions.placeholder || '',\n                    fieldOptions.accessibilityLabel || '',\n                    options.styles || {},\n                    new IframeEventPoster(host),\n                    new IframeEventListener(host),\n                    new DetachmentObserver(new MutationObserverFactory()),\n                    'instrumentId' in fieldOptions ?\n                        this._getCardInstrument(fieldOptions.instrumentId) :\n                        undefined\n                ),\n            ];\n        }, []);\n\n        return new HostedForm(\n            fields,\n            new IframeEventListener(host),\n            new HostedFormOrderDataTransformer(this._store),\n            pick(options, 'onBlur', 'onEnter', 'onFocus', 'onCardTypeChange', 'onValidate'),\n            new PaymentHumanVerificationHandler(createSpamProtection(createScriptLoader()))\n        );\n    }\n\n    private _getCardInstrument(instrumentId: string): CardInstrument {\n        const { instruments: { getCardInstrument } } = this._store.getState();\n        const instrument = getCardInstrument(instrumentId);\n\n        if (!instrument) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentInstrument);\n        }\n\n        return instrument;\n    }\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport { StoreCreditAction, StoreCreditActionType } from './store-credit-actions';\nimport StoreCreditRequestSender from './store-credit-request-sender';\n\nexport default class StoreCreditActionCreator {\n    constructor(\n        private _storeCreditRequestSender: StoreCreditRequestSender\n    ) {}\n\n    applyStoreCredit(useStoreCredit: boolean, options?: RequestOptions): ThunkAction<StoreCreditAction, InternalCheckoutSelectors> {\n        return store => concat(\n            of(createAction(StoreCreditActionType.ApplyStoreCreditRequested)),\n            defer(async () => {\n                const state = store.getState();\n                const checkout = state.checkout.getCheckout();\n\n                if (!checkout) {\n                    throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n                }\n\n                const { body } = await (useStoreCredit ?\n                    this._storeCreditRequestSender.applyStoreCredit(checkout.id, options) :\n                    this._storeCreditRequestSender.removeStoreCredit(checkout.id, options));\n\n                return createAction(StoreCreditActionType.ApplyStoreCreditSucceeded, body);\n            })\n        ).pipe(\n            catchError(error => throwErrorAction(StoreCreditActionType.ApplyStoreCreditFailed, error))\n        );\n    }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CHECKOUT_DEFAULT_INCLUDES } from '../checkout';\nimport { joinIncludes, ContentType, RequestOptions } from '../common/http-request';\n\nexport default class StoreCreditRequestSender {\n    constructor(\n        private _requestSender: RequestSender\n    ) {}\n\n    applyStoreCredit(checkoutId: string, { timeout }: RequestOptions = {}): Promise<Response<Checkout>> {\n        const url = `/api/storefront/checkouts/${checkoutId}/store-credit`;\n        const headers = { Accept: ContentType.JsonV1 };\n\n        return this._requestSender.post(url, {\n            headers,\n            timeout,\n            params: {\n                include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n            },\n        });\n    }\n\n    removeStoreCredit(checkoutId: string, { timeout }: RequestOptions = {}): Promise<Response<Checkout>> {\n        const url = `/api/storefront/checkouts/${checkoutId}/store-credit`;\n        const headers = { Accept: ContentType.JsonV1 };\n\n        return this._requestSender.delete(url, {\n            headers,\n            timeout,\n            params: {\n                include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n            },\n        });\n    }\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, of } from 'rxjs';\nimport { catchError, switchMap } from 'rxjs/operators';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { OrderActionCreator } from '../order';\nimport { PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport Payment, { FormattedHostedInstrument, FormattedPayload, FormattedVaultedInstrument } from './payment';\nimport { InitializeOffsitePaymentAction, PaymentActionType, SubmitPaymentAction } from './payment-actions';\nimport PaymentRequestSender from './payment-request-sender';\nimport PaymentRequestTransformer from './payment-request-transformer';\n\ninterface InitializeOffsitePaymentSettings {\n    methodId: string;\n    gatewayId?: string;\n    instrumentId?: string;\n    target?: string;\n    promise?: Promise<undefined>;\n    shouldSaveInstrument?: boolean;\n    shouldSetAsDefaultInstrument?: boolean;\n}\n\ntype InitializeOffsitePayment = (settings: InitializeOffsitePaymentSettings)\n    => ThunkAction<InitializeOffsitePaymentAction, InternalCheckoutSelectors>;\n\nexport default class PaymentActionCreator {\n    constructor(\n        private _paymentRequestSender: PaymentRequestSender,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentRequestTransformer: PaymentRequestTransformer,\n        private _paymentHumanVerificationHandler: PaymentHumanVerificationHandler\n    ) {}\n\n    submitPayment(payment: Payment): ThunkAction<SubmitPaymentAction, InternalCheckoutSelectors> {\n        return store => concat(\n            of(createAction(PaymentActionType.SubmitPaymentRequested)),\n            defer(async () => {\n                try {\n                    return await this._paymentRequestSender.submitPayment(\n                        this._paymentRequestTransformer.transform(payment, store.getState())\n                    );\n                } catch (error) {\n                    const additionalAction = await this._paymentHumanVerificationHandler.handle(error);\n\n                    return await this._paymentRequestSender.submitPayment(\n                        this._paymentRequestTransformer.transform({ ...payment, additionalAction }, store.getState())\n                    );\n                }\n            })\n                .pipe(\n                    switchMap(({ body }) => concat(\n                        this._orderActionCreator.loadCurrentOrder()(store),\n                        of(createAction(PaymentActionType.SubmitPaymentSucceeded, body))\n                    ))\n                )\n        ).pipe(\n            catchError(error => throwErrorAction(PaymentActionType.SubmitPaymentFailed, error))\n        );\n    }\n\n    initializeOffsitePayment: InitializeOffsitePayment = ({\n        methodId,\n        gatewayId,\n        instrumentId,\n        target,\n        promise,\n        shouldSaveInstrument,\n        shouldSetAsDefaultInstrument,\n    }) => {\n        return store => {\n            let paymentData: FormattedPayload<FormattedHostedInstrument | FormattedVaultedInstrument> | undefined;\n\n            if (instrumentId) {\n                paymentData = { formattedPayload: { bigpay_token: instrumentId } };\n            } else if (shouldSaveInstrument) {\n                paymentData = {\n                    formattedPayload: {\n                        vault_payment_instrument: shouldSaveInstrument,\n                        set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n                    },\n                };\n            }\n\n            const payload = this._paymentRequestTransformer.transform({ gatewayId, methodId, paymentData }, store.getState());\n\n            return concat(\n                of(createAction(PaymentActionType.InitializeOffsitePaymentRequested)),\n                Promise.race([this._paymentRequestSender.initializeOffsitePayment(payload, target), promise].filter(Boolean))\n                    .then(() => createAction(PaymentActionType.InitializeOffsitePaymentSucceeded))\n            ).pipe(\n                catchError(error => throwErrorAction(PaymentActionType.InitializeOffsitePaymentFailed, error))\n            );\n        };\n    };\n}\n","import PaymentMethod from './payment-method';\nimport PaymentStrategyType from './payment-strategy-type';\n\ntype PPSDKRequiredProperties = 'initializationStrategy';\n\nexport type PPSDKPaymentMethod = PaymentMethod & {\n    type: PaymentStrategyType.PPSDK;\n} & Required<Pick<PaymentMethod, PPSDKRequiredProperties>>;\n\nexport const isPPSDKPaymentMethod = ( paymentMethod: PaymentMethod ): paymentMethod is PPSDKPaymentMethod => {\n    const { type, initializationStrategy } = paymentMethod;\n\n    return (\n        type === PaymentStrategyType.PPSDK &&\n        typeof initializationStrategy?.type === 'string'\n    );\n};\n","import { ReadableDataStore } from '@bigcommerce/data-store';\nimport { some } from 'lodash';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { Registry, RegistryOptions } from '../common/registry';\n\nimport PaymentMethod from './payment-method';\nimport * as paymentMethodTypes from './payment-method-types';\nimport PaymentStrategyType from './payment-strategy-type';\nimport { isPPSDKPaymentMethod } from './ppsdk-payment-method';\nimport { PaymentStrategy } from './strategies';\n\nconst checkoutcomStrategies: {\n    [key: string]: PaymentStrategyType;\n} = {\n    credit_card: PaymentStrategyType.CHECKOUTCOM,\n    sepa: PaymentStrategyType.CHECKOUTCOM_SEPA,\n    ideal: PaymentStrategyType.CHECKOUTCOM_IDEAL,\n    fawry: PaymentStrategyType.CHECKOUTCOM_FAWRY,\n};\nexport default class PaymentStrategyRegistry extends Registry<PaymentStrategy, PaymentStrategyType> {\n    constructor(\n        private _store: ReadableDataStore<InternalCheckoutSelectors>,\n        options?: PaymentStrategyRegistryOptions\n    ) {\n        super(options);\n    }\n\n    getByMethod(paymentMethod?: PaymentMethod): PaymentStrategy {\n        if (!paymentMethod) {\n            return this.get();\n        }\n\n        const token = this._getToken(paymentMethod);\n\n        const cacheToken = [paymentMethod.gateway, paymentMethod.id]\n            .filter(value => value !== undefined && value !== null)\n            .join('-');\n\n        return this.get(token, cacheToken);\n    }\n\n    private _getToken(paymentMethod: PaymentMethod): PaymentStrategyType {\n        const ppsdkFeatureOn =\n            this._store.getState()\n                .config.getStoreConfig()\n                ?.checkoutSettings.features['PAYMENTS-6806.enable_ppsdk_strategy'];\n\n        if (ppsdkFeatureOn && isPPSDKPaymentMethod(paymentMethod)) {\n            return PaymentStrategyType.PPSDK;\n        }\n\n        if (paymentMethod.gateway === 'klarna') {\n            return PaymentStrategyType.KLARNAV2;\n        }\n\n        if (paymentMethod.id === PaymentStrategyType.PAYPAL_COMMERCE_CREDIT) {\n            return PaymentStrategyType.PAYPAL_COMMERCE;\n        }\n\n        if ( paymentMethod.gateway === PaymentStrategyType.PAYPAL_COMMERCE_ALTERNATIVE_METHODS) {\n            return PaymentStrategyType.PAYPAL_COMMERCE_ALTERNATIVE_METHODS;\n        }\n\n        if (paymentMethod.gateway === PaymentStrategyType.CHECKOUTCOM) {\n            return paymentMethod.id in checkoutcomStrategies\n                ? checkoutcomStrategies[paymentMethod.id]\n                : PaymentStrategyType.CHECKOUTCOM_APM;\n        }\n\n        const methodId = paymentMethod.gateway || paymentMethod.id;\n\n        if (this._hasFactoryForMethod(methodId)) {\n            return methodId;\n        }\n\n        if (paymentMethod.type === paymentMethodTypes.OFFLINE) {\n            return PaymentStrategyType.OFFLINE;\n        }\n\n        if (this._isLegacyMethod(paymentMethod)) {\n            return PaymentStrategyType.LEGACY;\n        }\n\n        if (paymentMethod.type === paymentMethodTypes.HOSTED) {\n            return PaymentStrategyType.OFFSITE;\n        }\n\n        return PaymentStrategyType.CREDIT_CARD;\n    }\n\n    private _hasFactoryForMethod(\n        methodId: string\n    ): methodId is PaymentStrategyType {\n        return this._hasFactory(methodId);\n    }\n\n    private _isLegacyMethod(paymentMethod: PaymentMethod): boolean {\n        const config = this._store.getState().config.getStoreConfig();\n\n        if (!config) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n        }\n\n        const { clientSidePaymentProviders } = config.paymentSettings;\n\n        if (!clientSidePaymentProviders || paymentMethod.gateway === 'adyen' || paymentMethod.gateway === 'barclaycard') {\n            return false;\n        }\n\n        return !some(clientSidePaymentProviders, id =>\n            paymentMethod.id === id || paymentMethod.gateway === id\n        );\n    }\n}\n\nexport interface PaymentStrategyRegistryOptions extends RegistryOptions {\n    clientSidePaymentProviders?: string[];\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { ContentType, INTERNAL_USE_ONLY } from '../common/http-request';\n\nexport default class StorefrontPaymentRequestSender {\n    constructor(\n        private _requestSender: RequestSender\n    ) {}\n\n    async saveExternalId(methodId: string, token: string): Promise<void> {\n        const url = `/api/storefront/payment/${methodId}/save-external-id`;\n        const options = {\n            headers: {\n                Accept: ContentType.JsonV1,\n                'X-API-INTERNAL': INTERNAL_USE_ONLY,\n            },\n            body: {\n                externalId: token,\n                provider: methodId,\n            },\n        };\n\n        await this._requestSender.post<void>(url, options);\n    }\n}\n","import BrowserInfo from './browser-info';\n\nexport default function getBrowserInfo(): BrowserInfo {\n    return {\n        color_depth: screen.colorDepth || 24,\n        java_enabled: typeof navigator.javaEnabled === 'function' ? navigator.javaEnabled() : false,\n        language: navigator.language || (navigator as any).userLanguage,\n        screen_height: screen.height,\n        screen_width: screen.width,\n        time_zone_offset: new Date().getTimezoneOffset().toString(),\n    };\n}\n","export enum AdyenActionType {\n    /*\n    * The payment qualifies for 3D Secure 2, and will go through either the frictionless\n    * or the challenge flow.\n    * */\n    ThreeDS2Fingerprint = 'threeDS2Fingerprint',\n\n    /*\n    * The payment qualifies for 3D Secure 2, and the issuer is initiating a challenge flow.\n    * */\n    ThreeDS2Challenge = 'threeDS2Challenge',\n\n    /*\n    * We will initiate a 3D Secure 1 fallback, because the issuer does not support 3D Secure 2.\n    * */\n    Redirect = 'redirect',\n\n    /*\n    * The Component presents the QR code and calls the onAdditionalDetails event.\n    * */\n    QRCode = 'qrCode',\n\n    /*\n    * The Component displays the voucher which the shopper uses to complete the payment.\n    * */\n    Voucher = 'voucher',\n}\n\nexport enum AdyenComponentType {\n    SecuredFields = 'securedfields',\n}\n\nexport enum AdyenPaymentMethodType {\n    ACH = 'ach',\n    AliPay = 'alipay',\n    Bancontact = 'bcmc',\n    CreditCard = 'scheme',\n    Klarna = 'klarna',\n    KlarnaPayNow = 'klarna_paynow',\n    KlarnaAccount = 'klarna_account',\n    iDEAL = 'ideal',\n    GiroPay = 'giropay',\n    GooglePay = 'paywithgoogle',\n    SEPA = 'sepadirectdebit',\n    Sofort = 'directEbanking',\n    Vipps = 'vipps',\n    WeChatPayQR = 'wechatpayQR',\n}\n\nexport enum HTTPMethod {\n    POST = 'POST',\n}\n\nexport enum ResultCode {\n    ChallengeShopper = 'ChallengeShopper',\n    Error = 'Error',\n    IdentifyShopper = 'IdentifyShopper',\n}\n\ninterface AdyenPaymentMethodState {\n    type: string;\n}\n\ninterface CardDataPaymentMethodState {\n    paymentMethod: CardPaymentMethodState;\n}\n\ninterface WechatDataPaymentMethodState {\n    paymentMethod: AdyenPaymentMethodState;\n}\n\ninterface CardPaymentMethodState extends AdyenPaymentMethodState {\n    encryptedCardNumber: string;\n    encryptedExpiryMonth: string;\n    encryptedExpiryYear: string;\n    encryptedSecurityCode: string;\n    holderName?: string;\n}\n\nexport interface AdyenAction {\n    method: HTTPMethod;\n\n    /**\n     * Value that you need to submit in your /payments/details request when handling\n     * the redirect.\n     */\n    paymentData: string;\n\n    paymentMethodType: AdyenPaymentMethodType;\n\n    /*\n     * The Component performs additional front-end actions depending on the action.type.\n     * Your next steps depend on the type of action that the Component performs.\n     */\n    type: AdyenActionType;\n\n    /**\n     * The HTTP request method that you should use. After the shopper completes the payment,\n     * they will be redirected back to your returnURL using the same method.\n     */\n    url: string;\n}\n\nexport interface AdyenAdditionalAction {\n    resultCode: ResultCode;\n    action: string;\n}\n\nexport interface AdyenAdditionalActionCallbacks {\n    /**\n     * A callback that gets called before adyen component is loaded\n     */\n    onBeforeLoad?(shopperInteraction?: boolean): void;\n\n    /**\n     * A callback that gets called when adyen component is loaded\n     */\n    onLoad?(cancel?: () => void): void;\n\n    /**\n     * A callback that gets called when adyen component verification\n     * is completed\n     */\n    onComplete?(): void;\n}\n\nexport interface AdyenAdditionalActionErrorResponse {\n    provider_data: AdyenAdditionalAction;\n    errors: [\n        {\n            code: string;\n        }\n    ];\n}\n\nexport interface AdyenAdditionalActionOptions extends AdyenAdditionalActionCallbacks {\n    /**\n     * The location to insert the additional action component.\n     */\n    containerId: string;\n}\n\nexport interface AdyenAdditionalActionState {\n    data: AdyenAdditionalAction;\n    isValid?: boolean;\n}\n\nexport interface AdyenBaseCardComponentOptions {\n    /**\n     * Array of card brands that will be recognized by the component.\n     *\n     */\n    brands?: string[];\n\n    /**\n     * Set a style object to customize the input fields. See Styling Secured Fields\n     * for a list of supported properties.\n     */\n    styles?: StyleOptions;\n}\n\nexport interface AdyenComponentEvents {\n    /**\n     * Called when the shopper enters data in the card input fields.\n     * Here you have the option to override your main Adyen Checkout configuration.\n     */\n    onChange?(state: AdyenComponentState, component: AdyenComponent): void;\n\n    /**\n     * Called in case of an invalid card number, invalid expiry date, or\n     *  incomplete field. Called again when errors are cleared.\n     */\n    onError?(state: AdyenComponentState, component: AdyenComponent): void;\n}\n\nexport interface AdyenClient {\n    create(type: string, componentOptions?: AdyenComponentOptions): AdyenComponent;\n\n    createFromAction(action: AdyenAction, componentOptions?: ThreeDS2DeviceFingerprintComponentOptions | ThreeDS2ChallengeComponentOptions ): AdyenComponent;\n}\n\nexport interface AdyenComponent {\n    mount(containerId: string): HTMLElement;\n    unmount(): void;\n}\n\nexport interface AdyenConfiguration {\n    /*\n     * Use test, and then change this to live when you're ready to accept live payments.\n     */\n    environment?: string;\n\n    /*\n     * The shopper's locale. This is used to set the language rendered in the Components.\n     */\n    locale?: string;\n\n    /*\n     * The Origin Key of your website.\n     */\n    originKey?: string;\n\n    /*\n     * The Client Key of your Adyen account.\n     */\n    clientKey?: string;\n\n    /*\n     * Supported from Components version 3.0.0 and later. The full paymentMethods response,\n     * returned in step 1. We recommend that you pass this on the AdyenCheckout instance.\n     * Otherwise, you need to pass the specific payment method details separately for each\n     * Component.\n     */\n    paymentMethodsResponse?: PaymentMethodsResponse;\n\n    /*\n     * Specify the function that you created, for example, handleOnChange. If you wish\n     * to override this function, you can also define an onChange event on the Component\n     * level.\n     */\n    onChange?(state: CardState, component?: AdyenComponent): void;\n\n    onAdditionalDetails?(state: CardState, component?: AdyenComponent): void;\n}\n\nexport interface AdyenPlaceholderData {\n    holderName?: string;\n    billingAddress?: {\n        street: string;\n        houseNumberOrName: string;\n        postalCode: string;\n        city: string;\n        stateOrProvince: string;\n        country: string;\n    };\n}\n\nexport interface AdyenCreditCardComponentOptions extends AdyenBaseCardComponentOptions, AdyenComponentEvents {\n    /**\n     * Set an object containing the details array for type: scheme from\n     * the /paymentMethods response.\n     */\n    details?: InputDetail[];\n\n    /**\n     * Set to true to show the checkbox to save card details for the next payment.\n     */\n    enableStoreDetails?: boolean;\n\n    /**\n     * Set to true to request the name of the card holder.\n     */\n    hasHolderName?: boolean;\n\n    /**\n     * Set to true to require the card holder name.\n     */\n    holderNameRequired?: boolean;\n\n    /**\n     * Information to prefill fields.\n     */\n    data?: AdyenPlaceholderData;\n\n    /**\n     * Defaults to ['mc','visa','amex']. Configure supported card types to\n     * facilitate brand recognition used in the Secured Fields onBrand callback.\n     * See list of available card types. If a shopper enters a card type not\n     * specified in the GroupTypes configuration, the onBrand callback will not be invoked.\n     */\n    groupTypes?: string[];\n\n    /**\n     * Specify the sample values you want to appear for card detail input fields.\n     */\n    placeholders?: CreditCardPlaceHolder | SepaPlaceHolder;\n}\n\nexport interface AdyenCustomCardComponentOptions extends AdyenBaseCardComponentOptions, AdyenComponentEvents {\n    /**\n     * Specify aria attributes for the input fields for web accessibility.\n     */\n    ariaLabels?: CustomCardAriaLabels;\n\n    /**\n     * Automatically shift the focus from date field to the CVC field.\n     */\n    autofocus?: boolean;\n}\n\nexport interface AdyenError {\n    errorCode: string;\n    message: string;\n}\n\nexport interface AdyenHostWindow extends Window {\n    AdyenCheckout?: new(configuration: AdyenConfiguration) => AdyenClient;\n}\n\nexport interface AdyenIdealComponentOptions {\n    /**\n     * Optional. Set to **false** to remove the bank logos from the iDEAL form.\n     */\n    showImage?: boolean;\n}\n\nexport interface AdyenStoredPaymentMethod {\n    /**\n     * The brand of the card.\n     */\n    brand?: string;\n\n    /**\n     * The month the card expires.\n     */\n    expiryMonth?: string;\n\n    /**\n     * The year the card expires.\n     */\n    expiryYear?: string;\n\n    /**\n     * The unique payment method code.\n     */\n    holderName?: string;\n\n    /**\n     * A unique identifier of this stored payment method.\n     */\n    id?: string;\n\n    /**\n     * The last four digits of the PAN.\n     */\n    lastFour?: string;\n\n    /**\n     * The display name of the stored payment method.\n     */\n    name: string;\n\n    /**\n     * The shopper’s email address.\n     */\n    shopperEmail?: string;\n\n    /**\n     * The supported shopper interactions for this stored payment method.\n     */\n    supportedShopperInteractions?: string[];\n\n    /**\n     * The type of payment method.\n     */\n    type?: string;\n}\n\nexport interface AdyenThreeDS2Options extends AdyenAdditionalActionCallbacks {\n    /**\n     * Specify Three3DS2Challenge Widget Size\n     *\n     * Values\n     * '01' = 250px x 400px\n     * '02' = 390px x 400px\n     * '03' = 500px x 600px\n     * '04' = 600px x 400px\n     * '05' = 100% x 100%\n     */\n    widgetSize?: string;\n}\n\nexport interface Bank {\n    /**\n     * The bank account number (without separators).\n     */\n    bankAccountNumber?: string;\n\n    /**\n     * The bank city.\n     */\n    bankCity?: string;\n\n    /**\n     * The location id of the bank. The field value is nil in most cases.\n     */\n    bankLocationId?: string;\n\n    /**\n     * The name of the bank.\n     */\n    bankName?: string;\n\n    /**\n     * The Business Identifier Code (BIC) is the SWIFT address assigned to\n     * a bank. The field value is nil in most cases.\n     */\n    bic?: string;\n\n    /**\n     * Country code where the bank is located.\n     * A valid value is an ISO two-character country code (e.g. 'NL').\n     */\n    countryCode?: string;\n\n    /**\n     * The International Bank Account Number (IBAN).\n     */\n    iban?: string;\n\n    /**\n     * The name of the bank account holder. If you submit a name with non-Latin\n     * characters, we automatically replace some of them with corresponding Latin\n     * characters to meet the FATF recommendations. For example:\n     * χ12 is converted to ch12.\n     * üA is converted to euA.\n     * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'.\n     * After replacement, the ownerName must have at least three alphanumeric characters\n     * (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character\n     * (A-Z, a-z). For example:\n     * John17 - allowed.\n     * J17 - allowed.\n     * 171 - not allowed.\n     * John-7 - allowed.\n     */\n    ownerName?: string;\n\n    /**\n     * The bank account holder's tax ID.\n     */\n    taxId?: string;\n}\n\nexport interface Card {\n    /**\n     * The card verification code (1-20 characters). Depending on the card brand, it\n     * is known also as:\n     * CVV2/CVC2 – length: 3 digits\n     * CID – length: 4 digits\n     */\n    cvc?: string;\n\n    /**\n     * The card expiry month. Format: 2 digits, zero-padded for single digits. For example:\n     * 03 = March\n     * 11 = November\n     * Required\n     */\n    expiryMonth: string;\n\n    /**\n     * The card expiry year. Format: 4 digits. For example: 2020\n     * Required\n     */\n    expiryYear: string;\n\n    /**\n     * The name of the cardholder, as printed on the card.\n     * Required\n     */\n    holderName: string;\n\n    /**\n     * The issue number of the card (for some UK debit cards only).\n     */\n    issueNumber?: string;\n\n    /**\n     * The card number (4-19 characters). Do not use any separators. When this value is\n     * returned in a response, only the last 4 digits of the card number are returned.\n     * Required\n     */\n    number: string;\n\n    /**\n     * The month component of the start date (for some UK debit cards only).\n     */\n    startNumber?: string;\n\n    /**\n     * The year component of the start date (for some UK debit cards only).\n     */\n    startYear?: string;\n}\n\nexport interface CardState {\n    data: CardDataPaymentMethodState;\n    isValid?: boolean;\n}\n\nexport interface WechatState {\n    data: WechatDataPaymentMethodState;\n}\n\nexport interface CreditCardPlaceHolder {\n    encryptedCardNumber?: string;\n    encryptedExpiryDate?: string;\n    encryptedSecurityCode: string;\n}\n\ninterface AccountDataPaymentMethodState {\n    paymentMethod: AdyenPaymentMethodState;\n}\n\nexport interface AccountState {\n    data: AccountDataPaymentMethodState;\n}\n\nexport interface CssProperties {\n    background?: string;\n    color?: string;\n    display?: string;\n    font?: string;\n    fontFamily?: string;\n    fontSize?: string;\n    fontSizeAdjust?: string;\n    fontSmoothing?: string;\n    fontStretch?: string;\n    fontStyle?: string;\n    fontVariant?: string;\n    fontVariantAlternates?: string;\n    fontVariantCaps?: string;\n    fontVariantEastAsian?: string;\n    fontVariantLigatures?: string;\n    fontVariantNumeric?: string;\n    fontWeight?: string;\n    letterSpacing?: string;\n    lineHeight?: string;\n    mozOsxFontSmoothing?: string;\n    mozTransition?: string;\n    outline?: string;\n    opacity?: string | number;\n    padding?: string;\n    textAlign?: string;\n    textShadow?: string;\n    transition?: string;\n    webkitFontSmoothing?: string;\n    webkitTransition?: string;\n}\n\nexport interface CustomCardAriaLabel {\n    label?: string;\n    iframeTitle?: string;\n}\n\nexport interface CustomCardAriaLabels {\n    lang?: string;\n    encryptedCardNumber?: CustomCardAriaLabel;\n    encryptedExpiryDate?: CustomCardAriaLabel;\n    encryptedSecurityCode?: CustomCardAriaLabel;\n}\n\nexport interface Group {\n    /**\n     * The name of the group.\n     */\n    name?: string;\n\n    /**\n     * Echo data to be used if the payment method is displayed as part of this group.\n     */\n    paymentMethodData?: string;\n\n    /**\n     * The unique code of the group.\n     */\n    type?: string;\n}\n\nexport interface InputDetail {\n    /**\n     * Configuration parameters for the required input.\n     */\n    configuration?: object;\n\n    /**\n     * Input details can also be provided recursively.\n     */\n    details?: SubInputDetail[];\n\n    /**\n     * In case of a select, the URL from which to query the items.\n     */\n    itemSearchUrl?: string;\n\n    /**\n     * In case of a select, the items to choose from.\n     */\n    items?: Item[];\n\n    /**\n     * The value to provide in the result.\n     */\n    key?: string;\n\n    /**\n     * True if this input value is optional.\n     */\n    optional?: boolean;\n\n    /**\n     * The type of the required input.\n     */\n    type?: string;\n\n    /**\n     * The value can be pre-filled, if available.\n     */\n    value?: string;\n}\n\nexport interface Item {\n    /**\n     * The value to provide in the result.\n     */\n    id?: string;\n\n    /**\n     * The display name.\n     */\n    name?: string;\n}\n\nexport interface PaymentMethod {\n    /**\n     * List of possible brands. For example: visa, mc.\n     */\n    brands?: string[];\n\n    /**\n     * The configuration of the payment method.\n     */\n    configuration?: object;\n\n    /**\n     * All input details to be provided to complete the payment with this payment\n     * method.\n     */\n    details?: InputDetail[];\n\n    /**\n     * The group where this payment method belongs to.\n     */\n    group?: Group;\n\n    /**\n     * The displayable name of this payment method.\n     */\n    name?: string;\n\n    /**\n     * Echo data required to send in next calls.\n     */\n    paymentMethodData?: string;\n\n    /**\n     * Indicates whether this payment method supports tokenization or not.\n     */\n    supportsRecurring?: boolean;\n\n    /**\n     * The unique payment method code.\n     */\n    type?: string;\n}\n\nexport interface PaymentMethodGroup {\n    /**\n     * The type to submit for any payment method in this group.\n     */\n    groupType?: string;\n\n    /**\n     * The human-readable name of this group.\n     */\n    name?: string;\n\n    /**\n     * The types of payment methods that belong in this group.\n     */\n    types?: string[];\n}\n\nexport interface PaymentMethodsResponse {\n    /**\n     * Groups of payment methods.\n     */\n    groups?: PaymentMethodGroup[];\n\n    /**\n     * Detailed list of one-click payment methods.\n     */\n    oneClickPaymentMethods?: RecurringDetail;\n\n    /**\n     * Detailed list of payment methods required to generate payment forms.\n     */\n    paymentMethods?: PaymentMethod[];\n\n    /**\n     * List of all stored payment methods.\n     */\n    storedPaymentMethods?: AdyenStoredPaymentMethod[];\n}\n\nexport interface RecurringDetail extends PaymentMethod {\n    /**\n     * The reference that uniquely identifies the recurring detail.\n     */\n    recurringDetailReference?: string;\n\n    /**\n     * Contains information on previously stored payment details.\n     */\n    storedDetails?: StoredDetails;\n}\n\nexport interface SepaPlaceHolder {\n    ownerName?: string;\n    ibanNumber?: string;\n}\n\nexport interface StoredDetails {\n    /**\n     * The stored bank account.\n     */\n    bank?: Bank;\n\n    /**\n     * The stored card information.\n     */\n    card?: Card;\n\n    /**\n     * The email associated with stored payment details.\n     */\n    emailAddress?: string;\n}\n\nexport interface StyleOptions {\n    /**\n     * Base styling applied to the iframe. All styling extends from this style.\n     */\n    base?: CssProperties;\n\n    /**\n     * Styling applied when a field fails validation.\n     */\n    error?: CssProperties;\n\n    /**\n     * Styling applied to the field's placeholder values.\n     */\n    placeholder?: CssProperties;\n\n    /**\n     * Styling applied once a field passes validation.\n     */\n    validated?: CssProperties;\n}\n\nexport interface SubInputDetail {\n    /**\n     * Configuration parameters for the required input.\n     */\n    configuration?: object;\n\n    /**\n     * In case of a select, the items to choose from.\n     */\n    items?: Item[];\n\n    /**\n     * The value to provide in the result.\n     */\n    key?: string;\n\n    /**\n     * True if this input is optional to provide.\n     */\n    optional?: boolean;\n\n    /**\n     * The type of the required input.\n     */\n    type?: string;\n\n    /**\n     * The value can be pre-filled, if available.\n     */\n    value?: string;\n}\n\nexport interface ThreeDS2ChallengeComponentOptions {\n    size?: string;\n    onAdditionalDetails?(state: AdyenAdditionalActionState, component?: AdyenComponent): void;\n    onError(error: AdyenError): void;\n}\n\nexport interface ThreeDS2DeviceFingerprintComponentOptions {\n    onAdditionalDetails?(state: AdyenAdditionalActionState, component?: AdyenComponent): void;\n    onError(error: AdyenError): void;\n}\n\nexport type AdyenComponentState = (\n    CardState | WechatState\n);\n\nexport type AdyenComponentOptions = (\n    AdyenCreditCardComponentOptions | AdyenIdealComponentOptions | AdyenCustomCardComponentOptions\n);\n\nexport function isCardState(param: any): param is CardState {\n    return param && typeof param.data.paymentMethod.encryptedSecurityCode === 'string' ||\n        typeof param.data.paymentMethod.encryptedExpiryMonth === 'string';\n}\n\nexport function isAccountState(param: any): param is AccountState {\n    const bankSupported = ['ideal', 'sepadirectdebit', 'directEbanking', 'giropay'];\n\n    return bankSupported.indexOf(param.data.paymentMethod.type) !== -1;\n}\n","import { InvalidArgumentError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when we are unable to submit a payment because\n * the caller has not provided all the required fields, i.e.: if an argument is\n * missing or it is not the expected data type.\n */\nexport default class PaymentArgumentInvalidError extends InvalidArgumentError {\n    constructor(invalidFields?: string[]) {\n        let message = 'Unable to submit payment for the order because the payload is invalid.';\n\n        if (invalidFields) {\n            message = `${message} Make sure the following fields are provided correctly: ${invalidFields.join(', ')}.`;\n        }\n\n        super(message);\n\n        this.name = 'PaymentArgumentInvalidError';\n    }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when the payment flow is cancelled. It could be\n * due to a deliberate user interaction, i.e.: the user clicks on a cancel\n * button which dismisses the payment modal.\n */\nexport default class PaymentMethodCancelledError extends StandardError {\n    constructor(message?: string) {\n        super(message || 'Payment process was cancelled.');\n\n        this.name = 'PaymentMethodCancelledError';\n        this.type = 'payment_cancelled';\n    }\n}\n","import { some } from 'lodash';\n\nimport { BillingAddress } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { getBrowserInfo } from '../../../common/browser-info';\nimport { InvalidArgumentError, NotInitializedError, NotInitializedErrorType, RequestError } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport Payment, { HostedInstrument } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { isAccountState, isCardState, AdyenAction, AdyenActionType, AdyenAdditionalAction, AdyenAdditionalActionState, AdyenClient, AdyenComponent, AdyenComponentState, AdyenComponentType, AdyenError, AdyenPaymentMethodType, AdyenPlaceholderData } from './adyenv2';\nimport AdyenV2PaymentInitializeOptions from './adyenv2-initialize-options';\nimport AdyenV2ScriptLoader from './adyenv2-script-loader';\n\nexport default class AdyenV2PaymentStrategy implements PaymentStrategy {\n    private _adyenClient?: AdyenClient;\n    private _cardVerificationComponent?: AdyenComponent;\n    private _componentState?: AdyenComponentState;\n    private _paymentComponent?: AdyenComponent;\n    private _paymentInitializeOptions?: AdyenV2PaymentInitializeOptions;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _orderActionCreator: OrderActionCreator,\n        private _scriptLoader: AdyenV2ScriptLoader\n    ) {}\n\n    async initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { adyenv2 } = options;\n\n        if (!adyenv2) {\n            throw new InvalidArgumentError('Unable to initialize payment because \"options.adyenv2\" argument is not provided.');\n        }\n\n        this._paymentInitializeOptions = adyenv2;\n\n        const paymentMethod = this._store.getState().paymentMethods.getPaymentMethodOrThrow(options.methodId);\n        const clientSideAuthentication = {\n            key: '',\n            value: '',\n        };\n\n        if (paymentMethod.initializationData.originKey) {\n            clientSideAuthentication.key = 'originKey';\n            clientSideAuthentication.value = paymentMethod.initializationData.originKey;\n        } else {\n            clientSideAuthentication.key = 'clientKey';\n            clientSideAuthentication.value = paymentMethod.initializationData.clientKey;\n        }\n\n        this._adyenClient = await this._scriptLoader.load({\n            environment:  paymentMethod.initializationData.environment,\n            locale: navigator.language,\n            [clientSideAuthentication.key]: clientSideAuthentication.value,\n            paymentMethodsResponse: paymentMethod.initializationData.paymentMethodsResponse,\n        });\n\n        this._paymentComponent = await this._mountPaymentComponent(paymentMethod);\n\n        if (paymentMethod.method === AdyenPaymentMethodType.CreditCard ||\n            paymentMethod.method === AdyenPaymentMethodType.Bancontact) {\n            this._cardVerificationComponent = await this._mountCardVerificationComponent();\n        }\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = payload;\n        const paymentData = payment && payment.paymentData;\n        const shouldSaveInstrument = paymentData && (paymentData as HostedInstrument).shouldSaveInstrument;\n        const shouldSetAsDefaultInstrument = paymentData && (paymentData as HostedInstrument).shouldSetAsDefaultInstrument;\n\n        if (!payment) {\n            throw new PaymentArgumentInvalidError(['payment']);\n        }\n\n        return this._store.dispatch(this._orderActionCreator.submitOrder(order, options))\n            .then(() => {\n                const componentState = this._componentState;\n\n                if (!componentState) {\n                    throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n                }\n\n                if (paymentData && isVaultedInstrument(paymentData)) {\n                    let bigpayToken = {};\n                    if (isCardState(componentState)) {\n                        const { encryptedCardNumber, encryptedSecurityCode, encryptedExpiryMonth, encryptedExpiryYear } = componentState.data.paymentMethod;\n\n                        bigpayToken = {\n                            credit_card_number_confirmation: encryptedCardNumber,\n                            expiry_month: encryptedExpiryMonth,\n                            expiry_year: encryptedExpiryYear,\n                            verification_value: encryptedSecurityCode,\n                        };\n                    }\n\n                    if (isCardState(componentState) || isAccountState(componentState)) {\n                        return this._store.dispatch(this._paymentActionCreator.submitPayment({\n                            ...payment,\n                            paymentData: {\n                                formattedPayload: {\n                                    bigpay_token: {\n                                        ...bigpayToken,\n                                        token: paymentData.instrumentId,\n                                    },\n                                    browser_info: getBrowserInfo(),\n                                    set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n                                },\n                            },\n                        }));\n                    }\n                }\n\n                return this._store.dispatch(this._paymentActionCreator.submitPayment({\n                    methodId: payment.methodId,\n                    paymentData: {\n                        formattedPayload: {\n                            credit_card_token: {\n                                token: JSON.stringify({\n                                    ...componentState.data.paymentMethod,\n                                    origin: window.location.origin,\n                                }),\n                            },\n                            browser_info: getBrowserInfo(),\n                            vault_payment_instrument: shouldSaveInstrument || null,\n                            set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n                        },\n                    },\n                }));\n            })\n            .catch(error => this._processAdditionalAction(error, shouldSaveInstrument, shouldSetAsDefaultInstrument));\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        if (this._paymentComponent) {\n            this._paymentComponent.unmount();\n            this._paymentComponent = undefined;\n        }\n\n        if (this._cardVerificationComponent) {\n            this._cardVerificationComponent.unmount();\n            this._cardVerificationComponent = undefined;\n        }\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    private _getAdyenClient(): AdyenClient {\n        if (!this._adyenClient) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        return this._adyenClient;\n    }\n\n    private _getPaymentInitializeOptions(): AdyenV2PaymentInitializeOptions {\n        if (!this._paymentInitializeOptions) {\n            throw new InvalidArgumentError('\"options.adyenv2\" argument was not provided during initialization.');\n        }\n\n        return this._paymentInitializeOptions;\n    }\n\n    private _getThreeDS2ChallengeWidgetSize(): string {\n        const { widgetSize } = this._getPaymentInitializeOptions().threeDS2Options;\n\n        if (!widgetSize) {\n            return '05';\n        }\n\n        return widgetSize;\n    }\n\n    private _handleAction(additionalAction: AdyenAdditionalAction): Promise<Payment> {\n        return new Promise((resolve, reject) => {\n            const { threeDS2ContainerId, additionalActionOptions } = this._getPaymentInitializeOptions();\n            const { onBeforeLoad, containerId, onLoad, onComplete } = additionalActionOptions;\n            const adyenAction: AdyenAction = JSON.parse(additionalAction.action);\n\n            const additionalActionComponent = this._getAdyenClient().createFromAction(adyenAction, {\n                onAdditionalDetails: (additionalActionState: AdyenAdditionalActionState) => {\n                    const paymentPayload = {\n                        methodId: adyenAction.paymentMethodType,\n                        paymentData: {\n                            nonce: JSON.stringify(additionalActionState.data),\n                        },\n                    };\n\n                    if (onComplete) {\n                        onComplete();\n                    }\n\n                    resolve(paymentPayload);\n                },\n                size: this._getThreeDS2ChallengeWidgetSize(),\n                onError: (error: AdyenError) => reject(error),\n            });\n\n            if (onBeforeLoad) {\n                onBeforeLoad(adyenAction.type === AdyenActionType.ThreeDS2Challenge ||\n                    adyenAction.type === AdyenActionType.QRCode);\n            }\n\n            additionalActionComponent.mount(`#${containerId || threeDS2ContainerId}`);\n\n            if (onLoad) {\n                onLoad(() => {\n                    reject(new PaymentMethodCancelledError());\n                    additionalActionComponent.unmount();\n                });\n            }\n        });\n    }\n\n    private _mapAdyenPlaceholderData(billingAddress?: BillingAddress): AdyenPlaceholderData {\n        if (!billingAddress) {\n            return {};\n        }\n\n        const {\n            firstName,\n            lastName,\n            address1: street,\n            address2: houseNumberOrName,\n            postalCode,\n            city,\n            stateOrProvinceCode: stateOrProvince,\n            countryCode: country,\n        } = billingAddress;\n\n        return {\n            holderName: `${firstName} ${lastName}`,\n            billingAddress: {\n                street,\n                houseNumberOrName,\n                postalCode,\n                city,\n                stateOrProvince,\n                country,\n            },\n        };\n    }\n\n    private _mountCardVerificationComponent(): Promise<AdyenComponent> {\n        const adyenv2 = this._getPaymentInitializeOptions();\n        const adyenClient = this._getAdyenClient();\n        let cardVerificationComponent: AdyenComponent;\n\n        return new Promise((resolve, reject) => {\n            if (adyenv2.cardVerificationContainerId) {\n                cardVerificationComponent = adyenClient.create(AdyenComponentType.SecuredFields, {\n                    ...adyenv2.options,\n                    onChange: componentState => this._updateComponentState(componentState),\n                    onError: componentState => this._updateComponentState(componentState),\n                });\n\n                try {\n                    cardVerificationComponent.mount(`#${adyenv2.cardVerificationContainerId}`);\n                } catch (error) {\n                    reject(new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized));\n                }\n            }\n\n            resolve(cardVerificationComponent);\n        });\n    }\n\n    private _mountPaymentComponent(paymentMethod: PaymentMethod): Promise<AdyenComponent> {\n        let paymentComponent: AdyenComponent;\n        const adyenv2 = this._getPaymentInitializeOptions();\n        const adyenClient = this._getAdyenClient();\n\n        return new Promise((resolve, reject) => {\n            switch (paymentMethod.method) {\n                case AdyenPaymentMethodType.CreditCard:\n                case AdyenPaymentMethodType.ACH:\n                case AdyenPaymentMethodType.Bancontact:\n                    const billingAddress = this._store.getState().billingAddress.getBillingAddress();\n\n                    paymentComponent = adyenClient.create(paymentMethod.method, {\n                        ...adyenv2.options,\n                        onChange: componentState => this._updateComponentState(componentState),\n                        data: this._mapAdyenPlaceholderData(billingAddress),\n                    });\n\n                    try {\n                        paymentComponent.mount(`#${adyenv2.containerId}`);\n                    } catch (error) {\n                        reject(new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized));\n                    }\n\n                    break;\n\n                case AdyenPaymentMethodType.iDEAL:\n                case AdyenPaymentMethodType.SEPA:\n                    if (!adyenv2.hasVaultedInstruments) {\n                        paymentComponent = adyenClient.create(paymentMethod.method, {\n                            ...adyenv2.options,\n                            onChange: componentState => this._updateComponentState(componentState),\n                        });\n\n                        try {\n                            paymentComponent.mount(`#${adyenv2.containerId}`);\n                        } catch (error) {\n                            reject(new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized));\n                        }\n\n                    } else {\n                        this._updateComponentState({\n                            data: {\n                                paymentMethod: {\n                                    type: paymentMethod.method,\n                                },\n                            },\n                        });\n                    }\n                    break;\n\n                case AdyenPaymentMethodType.AliPay:\n                case AdyenPaymentMethodType.GiroPay:\n                case AdyenPaymentMethodType.Sofort:\n                case AdyenPaymentMethodType.Klarna:\n                case AdyenPaymentMethodType.KlarnaPayNow:\n                case AdyenPaymentMethodType.KlarnaAccount:\n                case AdyenPaymentMethodType.Vipps:\n                case AdyenPaymentMethodType.WeChatPayQR:\n                    this._updateComponentState({\n                        data: {\n                            paymentMethod: {\n                                type: paymentMethod.method,\n                            },\n                        },\n                    });\n            }\n\n            resolve(paymentComponent);\n        });\n    }\n\n    private async _processAdditionalAction(error: unknown, shouldSaveInstrument?: boolean, shouldSetAsDefaultInstrument?: boolean): Promise<InternalCheckoutSelectors> {\n        if (!(error instanceof RequestError) || !some(error.body.errors, {code: 'additional_action_required'})) {\n            return Promise.reject(error);\n        }\n\n        const payment = await this._handleAction(error.body.provider_data);\n\n        try {\n            return await this._store.dispatch(this._paymentActionCreator.submitPayment({\n                ...payment,\n                paymentData: {\n                    ...payment.paymentData,\n                    shouldSaveInstrument,\n                    shouldSetAsDefaultInstrument,\n                },\n            }));\n        } catch (error) {\n            return this._processAdditionalAction(error, shouldSaveInstrument, shouldSetAsDefaultInstrument);\n        }\n    }\n\n    private _updateComponentState(componentState: AdyenComponentState) {\n        this._componentState = componentState;\n    }\n}\n","export enum OrderIncludes {\n    DigitalItemsCategories = 'lineItems.digitalItems.categories',\n    PhysicalItemsCategories = 'lineItems.physicalItems.categories',\n}\n\nexport default interface OrderParams {\n    include?: OrderIncludes[];\n}\n","import { ScriptLoader, StylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { AdyenClient, AdyenConfiguration, AdyenHostWindow } from './adyenv2';\n\nexport default class AdyenV2ScriptLoader {\n    constructor(\n        private _scriptLoader: ScriptLoader,\n        private _stylesheetLoader: StylesheetLoader,\n        private _window: AdyenHostWindow = window\n    ) { }\n\n    async load(configuration: AdyenConfiguration): Promise<AdyenClient> {\n        await Promise.all([\n            this._stylesheetLoader.loadStylesheet(`https://checkoutshopper-${configuration.environment}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.css`),\n            this._scriptLoader.loadScript(`https://checkoutshopper-${configuration.environment}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.js`),\n        ]);\n\n        if (!this._window.AdyenCheckout) {\n            throw new PaymentMethodClientUnavailableError();\n        }\n\n        return new this._window.AdyenCheckout(configuration);\n    }\n}\n","import { LineItemCategory } from '../../../cart';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { AmountTransformer } from '../../../common/utility';\nimport { Order, OrderActionCreator, OrderIncludes, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { Consignment } from '../../../shipping';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError, PaymentMethodInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { Affirm, AffirmAddress, AffirmDiscount, AffirmFailResponse, AffirmItem, AffirmRequestData, AffirmSuccessResponse } from './affirm';\nimport AffirmScriptLoader from './affirm-script-loader';\n\nexport default class AffirmPaymentStrategy implements PaymentStrategy {\n    private _affirm?: Affirm;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _affirmScriptLoader: AffirmScriptLoader\n    ) { }\n\n    initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(options.methodId))\n            .then(state => {\n                const paymentMethod = state.paymentMethods.getPaymentMethod(options.methodId);\n\n                if (!paymentMethod || !paymentMethod.clientToken) {\n                    throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n                }\n\n                const { config: { testMode }, clientToken: publicKey } = paymentMethod;\n\n                return this._affirmScriptLoader.load(publicKey, testMode);\n            })\n            .then(affirm => {\n                this._affirm = affirm;\n\n                return this._store.getState();\n            });\n    }\n\n    execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const methodId = payload.payment && payload.payment.methodId;\n        const { useStoreCredit } = payload;\n        const { _affirm } = this;\n\n        if (!_affirm) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        if (!methodId) {\n            throw new PaymentArgumentInvalidError(['payment.methodId']);\n        }\n\n        const requestOptions = {\n            ...options,\n            params: {\n                include: [\n                    OrderIncludes.PhysicalItemsCategories,\n                    OrderIncludes.DigitalItemsCategories,\n                ],\n            },\n        };\n\n        return this._store.dispatch(this._orderActionCreator.submitOrder({ useStoreCredit }, requestOptions))\n            .then<AffirmSuccessResponse>(() => {\n                _affirm.checkout(this._getCheckoutInformation());\n\n                return new Promise((resolve, reject) => {\n                    _affirm.checkout.open({\n                        onFail: (failObject: AffirmFailResponse) => {\n                            failObject.reason === 'canceled' ? reject(new PaymentMethodCancelledError()) : reject(new PaymentMethodInvalidError());\n                        },\n                        onSuccess: successObject => { resolve(successObject); },\n                    });\n                    _affirm.ui.error.on('close', () => {\n                        reject(new PaymentMethodCancelledError());\n                    });\n                });\n            })\n            .then(result => {\n                const paymentPayload = {\n                    methodId,\n                    paymentData: { nonce: result.checkout_token },\n                };\n\n                return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n            });\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        if (this._affirm) {\n            this._affirm = undefined;\n        }\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    private _getCheckoutInformation(): AffirmRequestData {\n        const state = this._store.getState();\n        const config = state.config.getStoreConfig();\n        const consignments = state.consignments.getConsignments();\n        const order = state.order.getOrder();\n\n        if (!config) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n        }\n\n        if (!order) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n        }\n\n        const amountTransformer = new AmountTransformer(order.currency.decimalPlaces);\n        const billingAddress = this._getBillingAddress();\n\n        return {\n            merchant: {\n                user_confirmation_url: config.links.checkoutLink,\n                user_cancel_url: config.links.checkoutLink,\n                user_confirmation_url_action: 'POST',\n            },\n            shipping: this._getShippingAddress() || billingAddress,\n            billing: billingAddress,\n            items: this._getItems(amountTransformer, order),\n            metadata: {\n                shipping_type: this._getShippingType(consignments),\n                mode: 'modal',\n                platform_type: 'BigCommerce',\n                platform_version: '',\n                platform_affirm: '',\n            },\n            discounts: this._getDiscounts(amountTransformer, order),\n            order_id: order.orderId ? order.orderId.toString() : '',\n            shipping_amount: amountTransformer.toInteger(order.shippingCostTotal),\n            tax_amount: amountTransformer.toInteger(order.taxTotal),\n            total: amountTransformer.toInteger(order.orderAmount),\n        };\n    }\n\n    private _getShippingType(consignments?: Consignment[]): string {\n        if (!consignments) {\n            return '';\n        }\n\n        const consignment = consignments[0];\n\n        return consignment && consignment.selectedShippingOption ?\n            consignment.selectedShippingOption.type : '';\n    }\n\n    private _getBillingAddress(): AffirmAddress {\n        const state = this._store.getState();\n        const billingAddress = state.billingAddress.getBillingAddress();\n\n        if (!billingAddress) {\n            throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n        }\n\n        const billingInformation = {\n            name: {\n                first: billingAddress.firstName,\n                last: billingAddress.lastName,\n                full: `${billingAddress.firstName} ${billingAddress.lastName}`,\n            },\n            address: {\n                line1: billingAddress.address1,\n                line2: billingAddress.address2,\n                city: billingAddress.city,\n                state: billingAddress.stateOrProvinceCode,\n                zipcode: billingAddress.postalCode,\n                country: billingAddress.countryCode,\n            },\n            phone_number: billingAddress.phone,\n            email: billingAddress.email,\n        };\n\n        return billingInformation;\n    }\n\n    private _getShippingAddress(): AffirmAddress | undefined {\n        const state = this._store.getState();\n        const shippingAddress = state.shippingAddress.getShippingAddress();\n\n        if (!shippingAddress) {\n            return;\n        }\n\n        const shippingInformation = {\n            name: {\n                first: shippingAddress.firstName,\n                last: shippingAddress.lastName,\n                full: `${shippingAddress.firstName} ${shippingAddress.lastName}`,\n            },\n            address: {\n                line1: shippingAddress.address1,\n                line2: shippingAddress.address2,\n                city: shippingAddress.city,\n                state: shippingAddress.stateOrProvinceCode,\n                zipcode: shippingAddress.postalCode,\n                country: shippingAddress.countryCode,\n            },\n            phone_number: shippingAddress.phone,\n        };\n\n        return shippingInformation;\n    }\n\n    private _getItems(amountTransformer: AmountTransformer, order: Order): AffirmItem[] {\n        const items: AffirmItem[] = [];\n\n        for (const item of order.lineItems.physicalItems) {\n            items.push({\n                display_name: item.name,\n                sku: item.sku,\n                unit_price: amountTransformer.toInteger(item.salePrice),\n                qty: item.quantity,\n                item_image_url: item.imageUrl,\n                item_url: item.url,\n                categories: this._getCategories(item.categories),\n            });\n        }\n\n        for (const item of order.lineItems.digitalItems) {\n            items.push({\n                display_name: item.name,\n                sku: item.sku,\n                unit_price: amountTransformer.toInteger(item.salePrice),\n                qty: item.quantity,\n                item_image_url: item.imageUrl,\n                item_url: item.url,\n                categories: this._getCategories(item.categories),\n            });\n        }\n\n        for (const item of order.lineItems.giftCertificates) {\n            items.push({\n                display_name: item.name,\n                sku: '',\n                unit_price: amountTransformer.toInteger(item.amount),\n                qty: 1,\n                item_image_url: '',\n                item_url: '',\n            });\n        }\n\n        if (order.lineItems.customItems) {\n            for (const item of order.lineItems.customItems) {\n                items.push({\n                    display_name: item.name,\n                    sku: item.sku,\n                    unit_price: amountTransformer.toInteger(item.listPrice),\n                    qty: item.quantity,\n                    item_image_url: '',\n                    item_url: '',\n                });\n            }\n        }\n\n        return items;\n    }\n\n    private _getDiscounts(amountTransformer: AmountTransformer, order: Order): AffirmDiscount {\n        const discounts: AffirmDiscount = {};\n\n        for (const line of order.coupons) {\n            if (line.discountedAmount > 0) {\n                discounts[line.code] = {\n                    discount_amount: amountTransformer.toInteger(line.discountedAmount),\n                    discount_display_name: line.displayName,\n                };\n            }\n        }\n\n        if (order.discountAmount > 0) {\n            discounts.DISCOUNTED_AMOUNT = {\n                discount_amount: amountTransformer.toInteger(order.discountAmount),\n                discount_display_name: 'discount',\n            };\n        }\n\n        return discounts;\n    }\n\n    private _getCategories(categories?: LineItemCategory[][]): string[][] {\n        if (!categories) {\n            return[[]];\n        }\n\n        return categories.map(categoryTree => categoryTree.map(category => category.name));\n    }\n}\n","import { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { Affirm, AffirmHostWindow, AffirmScripts } from './affirm';\nimport loadAffirmJS from './affirmJs';\n\nexport default class AffirmScriptLoader {\n    constructor(\n        public _window: AffirmHostWindow = window\n    ) { }\n\n    load(apikey: string = '', testMode?: boolean): Promise<Affirm> {\n        const scriptURI = this._getScriptURI(testMode);\n\n        loadAffirmJS(apikey, scriptURI);\n\n        if (!this._window.affirm) {\n            throw new PaymentMethodClientUnavailableError();\n        }\n\n        return Promise.resolve(this._window.affirm);\n    }\n\n    private _getScriptURI(testMode: boolean = false): string {\n        const SCRIPTS_DEFAULT: AffirmScripts = {\n            PROD: '//cdn1.affirm.com/js/v2/affirm.js',\n            SANDBOX: '//cdn1-sandbox.affirm.com/js/v2/affirm.js',\n        };\n\n        return testMode ? SCRIPTS_DEFAULT.SANDBOX : SCRIPTS_DEFAULT.PROD;\n    }\n}\n","/**\n * Used this approach as Affirm uses snipped for initializing. Please refer to Affirm documentation in: https://docs.affirm.com/Integrate_Affirm/Direct_API#1._Add_Affirm.js\n */\nimport { Affirm, AffirmHostWindow } from './affirm';\n\ninterface AffirmConfig {\n    public_api_key: string;\n    script: string;\n}\n\nexport default function loadAffirmJS(apiKey: string, scriptURL: string) {\n    const _AFFIRM_CONFIG: AffirmConfig = {\n        public_api_key: apiKey,\n        script: scriptURL,\n    };\n\n    (function foo(m: AffirmHostWindow | any, g: AffirmConfig, n: 'affirm', d: 'checkout', a: 'ui', e: 'script', h: 'ready', c: 'jsReady') {\n        const b = m[n] || {};\n        const k = document.createElement(e);\n        const p = document.getElementsByTagName(e)[0];\n        const l = function bar(a: Affirm | any, b: keyof Affirm, c: string) {\n            return function baz() {\n                a[b]._.push([c, arguments]);\n            };\n        };\n        b[d] = l(b, d, 'set');\n        const f = b[d];\n        b[a] = {};\n        b[a]._ = [];\n        f._ = [];\n        b._ = [];\n        b[a][h] = l(b, a, h);\n        b[c] = function qux() {\n            b._.push([h, arguments]);\n        };\n        let a1 = 0;\n        for (\n          const c1 = 'set add save post open empty reset on off trigger ready setProduct'.split(\n            ' '\n          );\n          a1 < c1.length;\n          a1++\n        ) {\n            f[c1[a1]] = l(b, d, c1[a1]);\n        }\n        let a2 = 0;\n        for (const c2 = ['get', 'token', 'url', 'items']; a2 < c2.length; a2++) {\n            f[c2[a2]] = function foobar() {};\n        }\n        k.async = !0;\n        k.src = g[e];\n        if (p.parentNode) {\n            p.parentNode.insertBefore(k, p);\n        }\n        delete g[e];\n        f(g);\n        m[n] = b;\n    })(\n        window,\n        _AFFIRM_CONFIG,\n        'affirm',\n        'checkout',\n        'ui',\n        'script',\n        'ready',\n        'jsReady'\n    );\n}\n","import { CheckoutStore, CheckoutValidator, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport AfterpayScriptLoader from './afterpay-script-loader';\nimport AfterpaySdk from './afterpay-sdk';\n\nexport default class AfterpayPaymentStrategy implements PaymentStrategy {\n    private _afterpaySdk?: AfterpaySdk;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _checkoutValidator: CheckoutValidator,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _storeCreditActionCreator: StoreCreditActionCreator,\n        private _afterpayScriptLoader: AfterpayScriptLoader\n    ) {}\n\n    async initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n        const paymentMethod = state.paymentMethods.getPaymentMethod(options.methodId, options.gatewayId);\n        const config = state.config.getStoreConfig();\n        const storeCountryName = config ? config.storeProfile.storeCountry : '';\n\n        if (!paymentMethod) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        this._afterpaySdk = await this._afterpayScriptLoader.load(paymentMethod, this._mapCountryToISO2(storeCountryName));\n\n        return this._store.getState();\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        if (this._afterpaySdk) {\n            this._afterpaySdk = undefined;\n        }\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const paymentId = payload.payment && payload.payment.gatewayId;\n\n        if (!paymentId) {\n            throw new PaymentArgumentInvalidError(['payment.gatewayId']);\n        }\n\n        let state = this._store.getState();\n        const config = state.config.getStoreConfig();\n        const storeCountryName = config ? config.storeProfile.storeCountry : '';\n        const { useStoreCredit } = payload;\n\n        if (useStoreCredit !== undefined) {\n            state = await this._store.dispatch(\n                this._storeCreditActionCreator.applyStoreCredit(useStoreCredit)\n            );\n        }\n\n        await this._checkoutValidator.validate(state.checkout.getCheckout(), options);\n\n        state = await this._store.dispatch(\n            this._paymentMethodActionCreator.loadPaymentMethod(paymentId, options)\n        );\n\n        await this._redirectToAfterpay(storeCountryName, state.paymentMethods.getPaymentMethod(paymentId));\n\n        // Afterpay will handle the rest of the flow so return a promise that doesn't really resolve\n        return new Promise<never>(() => {});\n    }\n\n    async finalize(options: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n        const payment = state.payment.getPaymentId();\n        const config = state.config.getContextConfig();\n\n        if (!payment) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n        }\n\n        if (!config || !config.payment.token) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n        }\n\n        const paymentPayload = {\n            methodId: payment.providerId,\n            paymentData: { nonce: config.payment.token },\n        };\n\n        await this._store.dispatch(this._orderActionCreator.submitOrder({}, options));\n\n        return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n    }\n\n    private _redirectToAfterpay(countryName: string, paymentMethod?: PaymentMethod): void {\n        if (!this._afterpaySdk || !paymentMethod || !paymentMethod.clientToken) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        this._afterpaySdk.initialize({ countryCode: this._mapCountryToISO2(countryName)});\n        this._afterpaySdk.redirect({ token: paymentMethod.clientToken });\n    }\n\n    private _mapCountryToISO2(countryName: string): string {\n        switch (countryName) {\n        case 'Australia':\n            return 'AU';\n\n        case 'New Zealand':\n            return 'NZ';\n\n        case 'United States':\n            return 'US';\n\n        default:\n            return 'AU';\n        }\n    }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport PaymentMethod from '../../payment-method';\n\nimport AfterpaySdk from './afterpay-sdk';\nimport AfterpayWindow from './afterpay-window';\n\ninterface AfterpayScripts {\n    PROD: string;\n    SANDBOX: string;\n}\n\nconst SCRIPTS_DEFAULT: AfterpayScripts = {\n    PROD: '//portal.afterpay.com/afterpay-async.js',\n    SANDBOX: '//portal-sandbox.afterpay.com/afterpay-async.js',\n};\n\nconst SCRIPTS_US: AfterpayScripts = {\n    PROD: '//portal.afterpay.com/afterpay-async.js',\n    SANDBOX: '//portal.us-sandbox.afterpay.com/afterpay-async.js',\n};\n\n/** Class responsible for loading the Afterpay SDK */\nexport default class AfterpayScriptLoader {\n    constructor(\n        private _scriptLoader: ScriptLoader\n    ) {}\n\n    /**\n     * Loads the appropriate Afterpay SDK depending on the payment method data.\n     * @param method the payment method data\n     */\n    load(method: PaymentMethod, countryCode: string): Promise<AfterpaySdk> {\n        const testMode = method.config.testMode || false;\n        const scriptURI = this._getScriptURI(countryCode, testMode);\n\n        return this._scriptLoader.loadScript(scriptURI)\n            .then(() => (window as unknown as AfterpayWindow).AfterPay);\n    }\n\n    private _getScriptURI(countryCode: string, testMode: boolean): string {\n        if (countryCode === 'US') {\n            return testMode ? SCRIPTS_US.SANDBOX : SCRIPTS_US.PROD;\n        }\n\n        return testMode ? SCRIPTS_DEFAULT.SANDBOX : SCRIPTS_DEFAULT.PROD;\n    }\n\n}\n","import { isEqual } from 'lodash';\n\nimport { omitPrivate } from '../common/utility';\n\nimport InternalAddress from './internal-address';\n\nexport default function isInternalAddressEqual(addressA: Partial<InternalAddress>, addressB: Partial<InternalAddress>): boolean {\n    return isEqual(normalize(addressA), normalize(addressB));\n}\n\nfunction normalize(address: Partial<InternalAddress>): Partial<InternalAddress> {\n    const ignoredKeys = ['id', 'provinceCode'];\n\n    return (Object.keys(omitPrivate(address) || {}) as Array<keyof InternalAddress>)\n        .reduce(\n            (result, key) => ignoredKeys.indexOf(key) === -1 && address[key] ?\n                { ...result, [key]: address[key] } :\n                result,\n            {}\n        );\n}\n","import isPrivate from './is-private';\nimport omitDeep from './omit-deep';\n\nexport default function omitPrivate(object: any): any {\n    return omitDeep(object, (_: any, key: string) => isPrivate(key));\n}\n","import { BillingAddress } from '../billing';\n\nimport Address from './address';\nimport InternalAddress from './internal-address';\n\nexport default function mapFromInternalAddress(address: InternalAddress): Address | BillingAddress {\n    return {\n        id: address.id,\n        firstName: address.firstName,\n        lastName: address.lastName,\n        company: address.company,\n        address1: address.addressLine1,\n        address2: address.addressLine2,\n        city: address.city,\n        stateOrProvince: address.province,\n        stateOrProvinceCode: address.provinceCode,\n        postalCode: address.postCode,\n        country: address.country,\n        countryCode: address.countryCode,\n        phone: address.phone,\n        customFields: address.customFields,\n    };\n}\n","export interface BoltHostWindow extends Window {\n    BoltCheckout?: BoltCheckout;\n}\n\nexport interface BoltCheckout {\n    configure(cart: BoltCart, hints: {}, callbacks?: BoltCallbacks): BoltClient;\n    setClientCustomCallbacks(callbacks: BoltCallbacks): void;\n}\n\nexport interface BoltDeveloperModeParams {\n    developerMode: BoltDeveloperMode;\n    developerDomain: string;\n}\n\nexport enum BoltDeveloperMode {\n    SandboxMode = 'bolt_sandbox',\n    StagingMode = 'bolt_staging',\n    DevelopmentMode = 'bolt_development',\n}\n\nexport interface BoltClient {\n    open(): void;\n}\n\nexport interface BoltCart {\n    orderToken: string;\n}\n\nexport interface BoltCallbacks {\n    check?(): boolean;\n    onCheckoutStart?(): void;\n    onPaymentSubmit?(): void;\n    success(transaction: BoltTransaction, callback: () => void): void;\n    close?(): void;\n}\n\nexport interface BoltTransaction {\n    id: string;\n    type: string;\n    processor: string;\n    date: number;\n    reference: string;\n    status: string;\n    authorization: BoltAuthorization;\n}\n\nexport interface BoltAuthorization {\n    status: string;\n    reason: string;\n}\n","import { noop } from 'lodash';\n\nimport { isInternalAddressEqual, mapFromInternalAddress, mapToInternalAddress } from '../../../address';\nimport { BillingAddressActionCreator } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType, RequestError } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { RemoteCheckoutSynchronizationError } from '../../../remote-checkout/errors';\nimport PaymentMethod from '../../payment-method';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport AmazonPayConfirmationFlow from './amazon-pay-confirmation-flow';\nimport AmazonPayOrderReference from './amazon-pay-order-reference';\nimport AmazonPayPaymentInitializeOptions from './amazon-pay-payment-initialize-options';\nimport AmazonPayScriptLoader from './amazon-pay-script-loader';\nimport AmazonPayWallet, { AmazonPayWalletOptions } from './amazon-pay-wallet';\nimport AmazonPayWindow from './amazon-pay-window';\n\nexport default class AmazonPayPaymentStrategy implements PaymentStrategy {\n    private _paymentMethod?: PaymentMethod;\n    private _walletOptions?: AmazonPayPaymentInitializeOptions;\n    private _window: AmazonPayWindow;\n    private _isPaymentMethodSelected: boolean;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator,\n        private _billingAddressActionCreator: BillingAddressActionCreator,\n        private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n        private _scriptLoader: AmazonPayScriptLoader\n    ) {\n        this._window = window;\n        this._isPaymentMethodSelected = false;\n    }\n\n    initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { amazon: amazonOptions, methodId } = options;\n        const state = this._store.getState();\n        const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n        if (!amazonOptions) {\n            throw new InvalidArgumentError('Unable to initialize payment because \"options.amazon\" argument is not provided.');\n        }\n\n        if (!paymentMethod) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        this._walletOptions = amazonOptions;\n        this._paymentMethod = paymentMethod;\n\n        return new Promise((resolve, reject) => {\n            const onReady = () => {\n                this._createWallet(amazonOptions)\n                    .then(resolve)\n                    .catch(reject);\n            };\n\n            this._scriptLoader.loadWidget(paymentMethod, onReady)\n                .catch(reject);\n        })\n            .then(() => this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        this._walletOptions = undefined;\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const referenceId = this._getOrderReferenceId();\n        const sellerId = this._getMerchantId();\n\n        if (!referenceId || !sellerId) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        if (!payload.payment) {\n            throw new InvalidArgumentError('Unable to proceed because \"payload.payment.methodId\" argument is not provided.');\n        }\n\n        if (!this._isPaymentMethodSelected) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        const { payment: { paymentData, ...paymentPayload }, useStoreCredit } = payload;\n\n        if (options && this._paymentMethod && this._paymentMethod.config.is3dsEnabled) {\n            return this._processPaymentWith3ds(\n                sellerId,\n                referenceId,\n                paymentPayload.methodId,\n                useStoreCredit,\n                options\n            );\n        }\n\n        return this._store.dispatch(\n            this._remoteCheckoutActionCreator.initializePayment(paymentPayload.methodId, { referenceId, useStoreCredit })\n        )\n            .then(() => this._store.dispatch(\n                this._orderActionCreator.submitOrder({\n                    ...payload,\n                    payment: paymentPayload,\n                }, options)\n            ))\n            .catch(error => {\n                if (error instanceof RequestError && error.body.type === 'provider_widget_error' && this._walletOptions) {\n                    return this._createWallet(this._walletOptions)\n                        .then(() => Promise.reject(error));\n                }\n\n                return Promise.reject(error);\n            });\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    private _getMerchantId(): string | undefined {\n        return this._paymentMethod && this._paymentMethod.config.merchantId;\n    }\n\n    private _getOrderReferenceId(): string | undefined {\n        const state = this._store.getState();\n        const amazon = state.remoteCheckout.getCheckout('amazon');\n\n        return amazon ? amazon.referenceId : undefined;\n    }\n\n    private _getOrderReferenceIdFromInitializationData(): string | undefined {\n        return this._paymentMethod ? this._paymentMethod.initializationData.orderReferenceId : undefined;\n    }\n\n    private _createWallet(options: AmazonPayPaymentInitializeOptions): Promise<AmazonPayWallet> {\n        return new Promise((resolve, reject) => {\n            const { container, onError = noop, onPaymentSelect = noop, onReady = noop } = options;\n            const referenceId = this._getOrderReferenceId() || this._getOrderReferenceIdFromInitializationData();\n            const merchantId = this._getMerchantId();\n\n            if (!document.getElementById(container)) {\n                return reject(new InvalidArgumentError('Unable to create AmazonPay Wallet widget without valid container ID.'));\n            }\n\n            if (!this._window.OffAmazonPayments) {\n                return reject(new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized));\n            }\n\n            if (!merchantId) {\n                return reject(new MissingDataError(MissingDataErrorType.MissingPaymentMethod));\n            }\n\n            const walletOptions: AmazonPayWalletOptions = {\n                amazonOrderReferenceId: referenceId,\n                design: { designMode: 'responsive' },\n                scope: 'payments:billing_address payments:shipping_address payments:widget profile',\n                sellerId: merchantId,\n                onError: error => {\n                    reject(error);\n                    onError(error);\n                },\n                onPaymentSelect: orderReference => {\n                    this._synchronizeBillingAddress()\n                        .then(() => {\n                            this._isPaymentMethodSelected = true;\n                            onPaymentSelect(orderReference);\n                        })\n                        .catch(onError);\n                },\n                onReady: orderReference => {\n                    resolve();\n                    onReady(orderReference);\n                },\n            };\n\n            if (!this._getOrderReferenceId()) {\n                walletOptions.onReady = orderReference => {\n                    this._updateOrderReference(orderReference)\n                        .then(() => {\n                            resolve();\n                            onReady(orderReference);\n                        })\n                        .catch(onError);\n                };\n            }\n\n            const widget = new this._window.OffAmazonPayments.Widgets.Wallet(walletOptions);\n\n            widget.bind(container);\n\n            return widget;\n        });\n    }\n\n    private _synchronizeBillingAddress(): Promise<InternalCheckoutSelectors> {\n        const referenceId = this._getOrderReferenceId();\n        const methodId = this._paymentMethod && this._paymentMethod.id;\n\n        if (!methodId || !referenceId) {\n            throw new RemoteCheckoutSynchronizationError();\n        }\n\n        return this._store.dispatch(\n            this._remoteCheckoutActionCreator.initializeBilling(methodId, { referenceId })\n        )\n            .then(state => {\n                const amazon = state.remoteCheckout.getCheckout('amazon');\n                const remoteAddress = amazon && amazon.billing && amazon.billing.address;\n                const billingAddress = state.billingAddress.getBillingAddress();\n                const internalBillingAddress = billingAddress && mapToInternalAddress(billingAddress);\n\n                if (remoteAddress === false) {\n                    throw new RemoteCheckoutSynchronizationError();\n                }\n\n                if (!remoteAddress || isInternalAddressEqual(remoteAddress, internalBillingAddress || {})) {\n                    return this._store.getState();\n                }\n\n                return this._store.dispatch(\n                    this._billingAddressActionCreator.updateAddress(mapFromInternalAddress(remoteAddress))\n                );\n            });\n    }\n\n    private _updateOrderReference(orderReference: AmazonPayOrderReference): Promise<InternalCheckoutSelectors> {\n        return this._store.dispatch(\n            this._remoteCheckoutActionCreator.updateCheckout('amazon', {\n                referenceId: orderReference.getAmazonOrderReferenceId(),\n            })\n        );\n    }\n\n    private _processPaymentWith3ds(sellerId: string, referenceId: string, methodId: string, useStoreCredit: boolean | undefined, options: PaymentRequestOptions): Promise<never> {\n        return new Promise((_, reject) => {\n            if (!this._window.OffAmazonPayments) {\n                return reject(new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized));\n            }\n\n            return this._window.OffAmazonPayments.initConfirmationFlow(\n                sellerId,\n                referenceId,\n                (confirmationFlow: AmazonPayConfirmationFlow) => {\n                    return this._store.dispatch(\n                        this._orderActionCreator.submitOrder({ useStoreCredit }, options)\n                    )\n                        .then(() => this._store.dispatch(\n                            this._remoteCheckoutActionCreator.initializePayment(methodId, {\n                                referenceId,\n                                useStoreCredit,\n                            }))\n                        )\n                        .then(() => {\n                            confirmationFlow.success();\n\n                            return new Promise<never>(() => {});\n                        })\n                        .catch(error => {\n                            confirmationFlow.error();\n\n                            return reject(error);\n                        });\n                }\n            );\n        });\n    }\n}\n","import { noop } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType, RequestError } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { getShippableItemsCount } from '../../../shipping';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategyActionCreator from '../../payment-strategy-action-creator';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { AmazonPayV2ChangeActionType, AmazonPayV2PaymentProcessor, AmazonPayV2PayOptions, AmazonPayV2Placement } from '.';\n\nexport default class AmazonPayV2PaymentStrategy implements PaymentStrategy {\n\n    private _walletButton?: HTMLElement;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor\n    ) { }\n\n    async initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { methodId, amazonpay } = options;\n\n        if (!methodId || !amazonpay) {\n            throw new InvalidArgumentError('Unable to proceed because \"options.amazonpay\" argument is not provided.');\n        }\n\n        const state = await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId));\n        const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n        await this._amazonPayV2PaymentProcessor.initialize(paymentMethod);\n\n        const { paymentToken } = paymentMethod.initializationData;\n        const buttonId = amazonpay.editButtonId;\n\n        if (paymentToken && buttonId) {\n            this._bindEditButton(buttonId, paymentToken, 'changePayment');\n        } else {\n            this._walletButton = this._createSignInButton(paymentMethod);\n        }\n\n        return this._store.getState();\n    }\n\n    async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment } = orderRequest;\n\n        if (!payment) {\n            throw new PaymentArgumentInvalidError(['payment']);\n        }\n\n        const { methodId } = payment;\n\n        const state = await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId));\n        const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n        const { paymentToken } = paymentMethod.initializationData;\n\n        if (paymentToken) {\n            const paymentPayload = {\n                methodId,\n                paymentData: { nonce: paymentToken },\n            };\n\n            await this._store.dispatch(this._orderActionCreator.submitOrder(orderRequest, options));\n\n            try {\n                return await this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n            } catch (error) {\n                if (error instanceof RequestError && error.body.status === 'additional_action_required') {\n                    return new Promise(() => {\n                        window.location.replace(error.body.additional_action_required.data.redirect_url);\n                    });\n                }\n\n                throw error;\n            }\n        }\n\n        if (!this._walletButton) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        this._walletButton.click();\n\n        return new Promise<never>(noop);\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    async deinitialize(_options?: PaymentRequestOptions | undefined): Promise<InternalCheckoutSelectors> {\n        if (this._walletButton && this._walletButton.parentNode) {\n            this._walletButton.parentNode.removeChild(this._walletButton);\n            this._walletButton = undefined;\n        }\n\n        await this._amazonPayV2PaymentProcessor.deinitialize();\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    private _bindEditButton(id: string, sessionId: string, changeAction: AmazonPayV2ChangeActionType): void {\n        const button = document.getElementById(id);\n\n        if (!button || !button.parentNode) {\n            return;\n        }\n\n        const clone = button.cloneNode(true);\n        button.parentNode.replaceChild(clone, button);\n\n        clone.addEventListener('click', () => this._showLoadingSpinner(() => new Promise(noop)));\n\n        this._amazonPayV2PaymentProcessor.bindButton(id, sessionId, changeAction);\n    }\n\n    private _showLoadingSpinner(callback?: () => Promise<void> | Promise<never>): Promise<InternalCheckoutSelectors> {\n        return this._store.dispatch(this._paymentStrategyActionCreator.widgetInteraction(() => {\n\n            if (callback) {\n                return callback();\n            }\n\n            return Promise.reject();\n        }), { queueId: 'widgetInteraction' });\n    }\n\n    private _createContainer(): HTMLDivElement {\n        let container = document.getElementById('AmazonPayButton') as HTMLDivElement;\n\n        if (container) {\n            return container;\n        }\n\n        container = document.createElement('div');\n        container.id = 'AmazonPayButton';\n        container.style.display = 'none';\n\n        return document.body.appendChild(container);\n    }\n\n    private _createSignInButton(paymentMethod: PaymentMethod): HTMLElement {\n        const state = this._store.getState();\n        const cart = state.cart.getCart();\n        const config = state.config.getStoreConfig();\n\n        if (!config) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n        }\n\n        if (!paymentMethod) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        const {\n            config: {\n                merchantId,\n                testMode,\n            },\n            initializationData: {\n                checkoutLanguage,\n                ledgerCurrency,\n                checkoutSessionMethod,\n                extractAmazonCheckoutSessionId,\n            },\n        } = paymentMethod;\n\n        if (!merchantId) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        const amazonButtonOptions = {\n            merchantId,\n            sandbox: !!testMode,\n            checkoutLanguage,\n            ledgerCurrency,\n            productType: cart && getShippableItemsCount(cart) === 0 ?\n                AmazonPayV2PayOptions.PayOnly :\n                AmazonPayV2PayOptions.PayAndShip,\n            createCheckoutSession: {\n                method: checkoutSessionMethod,\n                url: `${config.storeProfile.shopPath}/remote-checkout/${paymentMethod.id}/payment-session`,\n                extractAmazonCheckoutSessionId,\n            },\n            placement: AmazonPayV2Placement.Checkout,\n        };\n\n        const container = this._createContainer();\n        this._amazonPayV2PaymentProcessor.createButton(`#${container.id}`, amazonButtonOptions);\n\n        return container;\n    }\n}\n","import { isNil, values } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { HostedForm, HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nexport default class CreditCardPaymentStrategy implements PaymentStrategy {\n    protected _hostedForm?: HostedForm;\n    protected _shouldRenderHostedForm?: boolean;\n\n    constructor(\n        protected _store: CheckoutStore,\n        protected _orderActionCreator: OrderActionCreator,\n        protected _paymentActionCreator: PaymentActionCreator,\n        protected _hostedFormFactory: HostedFormFactory\n    ) {}\n\n    execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        return this._isHostedPaymentFormEnabled(payload.payment?.methodId, payload.payment?.gatewayId) && this._shouldRenderHostedForm ?\n            this._executeWithHostedForm(payload, options) :\n            this._executeWithoutHostedForm(payload, options);\n    }\n\n    finalize(_options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    initialize(options?: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        if (!this._isHostedPaymentFormEnabled(options?.methodId, options?.gatewayId) || !this._isHostedFieldAvailable(options)) {\n            this._shouldRenderHostedForm = false;\n\n            return Promise.resolve(this._store.getState());\n        }\n\n        const formOptions = options && options.creditCard && options.creditCard.form;\n        const { config } = this._store.getState();\n        const { paymentSettings: { bigpayBaseUrl: host = '' } = {} } = config.getStoreConfig() || {};\n\n        if (!formOptions) {\n            throw new InvalidArgumentError();\n        }\n\n        const form = this._hostedFormFactory.create(host, formOptions);\n\n        return form.attach()\n            .then(() => {\n                this._shouldRenderHostedForm = true;\n                this._hostedForm = form;\n\n                return this._store.getState();\n            });\n    }\n\n    deinitialize(_options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        if (this._hostedForm) {\n            this._hostedForm.detach();\n        }\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    protected _executeWithoutHostedForm(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = payload;\n        const paymentData = payment && payment.paymentData;\n\n        if (!payment || !paymentData) {\n            throw new PaymentArgumentInvalidError(['payment.paymentData']);\n        }\n\n        return this._store.dispatch(this._orderActionCreator.submitOrder(order, options))\n            .then(() =>\n                this._store.dispatch(this._paymentActionCreator.submitPayment({ ...payment, paymentData }))\n            );\n    }\n\n    protected _executeWithHostedForm(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors>  {\n        const { payment, ...order } = payload;\n        const form = this._hostedForm;\n\n        if (!form) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        if (!payment || !payment.methodId) {\n            throw new PaymentArgumentInvalidError(['payment.methodId']);\n        }\n\n        return form.validate()\n            .then(() => this._store.dispatch(this._orderActionCreator.submitOrder(order, options)))\n            .then(() => form.submit(payment))\n            .then(() => this._store.dispatch(this._orderActionCreator.loadCurrentOrder()));\n    }\n\n    protected _isHostedPaymentFormEnabled(methodId?: string, gatewayId?: string): boolean {\n        if (!methodId) {\n            return false;\n        }\n\n        const { paymentMethods: { getPaymentMethodOrThrow } } = this._store.getState();\n        const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n        return paymentMethod.config.isHostedFormEnabled === true;\n    }\n\n    private _isHostedFieldAvailable(options?: PaymentInitializeOptions): boolean {\n        return !(values(options && options.creditCard && options.creditCard.form.fields).every(isNil));\n    }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CardinalThreeDSecureFlowV2 } from '../cardinal';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class BarclaysPaymentStrategy extends CreditCardPaymentStrategy {\n    constructor(\n        store: CheckoutStore,\n        orderActionCreator: OrderActionCreator,\n        paymentActionCreator: PaymentActionCreator,\n        hostedFormFactory: HostedFormFactory,\n        private _threeDSecureFlow: CardinalThreeDSecureFlowV2\n    ) {\n        super(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            hostedFormFactory\n        );\n    }\n\n    async initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        await super.initialize(options);\n\n        const { paymentMethods: { getPaymentMethodOrThrow } } = this._store.getState();\n        const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n        if (paymentMethod.config.is3dsEnabled) {\n            await this._threeDSecureFlow.prepare(paymentMethod);\n        }\n\n        return this._store.getState();\n    }\n\n    async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment: { methodId = '' } = {} } = payload;\n        const { paymentMethods: { getPaymentMethodOrThrow } } = this._store.getState();\n\n        if (getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n            return this._threeDSecureFlow.start(\n                super.execute.bind(this),\n                payload,\n                options,\n                this._hostedForm\n            );\n        }\n\n        return super.execute(payload, options);\n    }\n}\n","import { noop } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { CancellablePromise } from '../../../common/utility';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { BlueSnapV2StyleProps } from './bluesnapv2';\nimport { BlueSnapV2PaymentInitializeOptions } from './bluesnapv2-payment-options';\n\nconst IFRAME_NAME = 'bluesnapv2_hosted_payment_page';\n\nexport default class BlueSnapV2PaymentStrategy implements PaymentStrategy {\n\n    private _initializeOptions?: BlueSnapV2PaymentInitializeOptions;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator\n    ) {}\n\n    async execute(orderRequest: OrderRequestBody, options?: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { payment } = orderRequest;\n\n        if (!payment) {\n            throw new PaymentArgumentInvalidError(['payment']);\n        }\n\n        if (!this._initializeOptions) {\n            throw new NotInitializedError(\n                NotInitializedErrorType.PaymentNotInitialized\n            );\n        }\n\n        await this._store.dispatch(this._orderActionCreator.submitOrder(orderRequest, options));\n\n        const { onLoad, style } = this._initializeOptions;\n        const frame = this._createIframe(IFRAME_NAME, style);\n        const promise = new CancellablePromise<undefined>(new Promise(noop));\n\n        onLoad(frame, () => promise.cancel(new PaymentMethodCancelledError()));\n\n        return this._store.dispatch(this._paymentActionCreator.initializeOffsitePayment({\n            methodId: payment.methodId,\n            gatewayId: payment.gatewayId,\n            shouldSaveInstrument: false,\n            target: frame.name,\n            promise: promise.promise,\n        }));\n    }\n\n    finalize(options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n        const order = state.order.getOrder();\n        const status = state.payment.getPaymentStatus();\n\n        if (order && (status === paymentStatusTypes.ACKNOWLEDGE || status === paymentStatusTypes.FINALIZE)) {\n            return this._store.dispatch(this._orderActionCreator.finalizeOrder(order.orderId, options));\n        }\n\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    initialize(options?: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        this._initializeOptions = options && options.bluesnapv2;\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n\n    private _createIframe(name: string, style?: BlueSnapV2StyleProps): HTMLIFrameElement {\n        const iframe = document.createElement('iframe');\n\n        iframe.name = name;\n\n        if (style) {\n            const { border, height, width } = style;\n\n            iframe.style.border = border as string;\n            iframe.style.height = height as string;\n            iframe.style.width = width as string;\n        }\n\n        return iframe;\n    }\n}\n","import { isNonceLike } from '../..';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport { NonceInstrument } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { BoltCheckout, BoltTransaction } from './bolt';\nimport BoltScriptLoader from './bolt-script-loader';\n\nexport default class BoltPaymentStrategy implements PaymentStrategy {\n    private _boltClient?: BoltCheckout;\n    private _useBoltClient: boolean = false;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _storeCreditActionCreator: StoreCreditActionCreator,\n        private _boltScriptLoader: BoltScriptLoader\n    ) { }\n\n    async initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { bolt, methodId } = options;\n\n        this._useBoltClient = !!(bolt && bolt.useBigCommerceCheckout);\n\n        if (this._useBoltClient) {\n            const state = this._store.getState();\n            const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n            if (!paymentMethod || !paymentMethod.initializationData.publishableKey) {\n                throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n            }\n\n            const { developerConfig, publishableKey } = paymentMethod.initializationData;\n\n            this._boltClient = await this._boltScriptLoader.load(publishableKey, paymentMethod.config.testMode, developerConfig);\n        }\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        this._boltClient = undefined;\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        if (this._useBoltClient) {\n            return this._executeWithBoltClient(payload, options);\n        } else {\n            return this._executeWithBoltCheckout(payload, options);\n        }\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    private async _executeWithBoltClient(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = payload;\n\n        if (!payment) {\n            throw new PaymentArgumentInvalidError(['payment']);\n        }\n\n        if (!this._boltClient) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        const boltClient = this._boltClient;\n\n        await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n        const { isStoreCreditApplied: useStoreCredit } = this._store.getState().checkout.getCheckoutOrThrow();\n\n        if (useStoreCredit !== undefined) {\n            await this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(useStoreCredit));\n        }\n\n        const state = await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(payment.methodId, options));\n        const paymentMethod = state.paymentMethods.getPaymentMethod(payment.methodId);\n\n        if (!paymentMethod || !paymentMethod.clientToken) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        const orderToken = paymentMethod.clientToken;\n\n        const transaction: BoltTransaction = await new Promise((resolve, reject) => {\n            const onSuccess = (transaction: BoltTransaction,  callback: () => void) => {\n                resolve(transaction);\n                callback();\n            };\n\n            const onClose = () => {\n                reject(new PaymentMethodCancelledError());\n            };\n\n            const callbacks = {\n                success: onSuccess,\n                close: onClose,\n            };\n\n            boltClient.configure({ orderToken }, {}, callbacks).open();\n        });\n\n        const { shouldSaveInstrument } = payment.paymentData as NonceInstrument;\n\n        const paymentPayload = {\n            methodId: payment.methodId,\n            paymentData: {\n                nonce: transaction.reference,\n                shouldSaveInstrument,\n            },\n        };\n\n        return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n    }\n\n    private async _executeWithBoltCheckout(payload: OrderRequestBody, _options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = payload;\n\n        if (!payment) {\n            throw new PaymentArgumentInvalidError(['payment']);\n        }\n\n        const { methodId, paymentData } = payment;\n\n        if (!methodId) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        if (!paymentData || !isNonceLike(paymentData)) {\n            throw new MissingDataError(MissingDataErrorType.MissingPayment);\n        }\n\n        await this._store.dispatch(this._orderActionCreator.submitOrder(order, _options));\n\n        return this._store.dispatch(this._paymentActionCreator.submitPayment({\n            methodId,\n            paymentData,\n        }));\n    }\n}\n","import { NonceInstrument, PaymentInstrument } from './payment';\n\nexport default function isNonceLike(instrument: PaymentInstrument): instrument is NonceInstrument {\n    return Boolean((instrument as NonceInstrument).nonce);\n}\n","import { LoadScriptOptions, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { BoltCheckout, BoltDeveloperMode, BoltDeveloperModeParams, BoltHostWindow } from './bolt';\n\nexport default class BoltScriptLoader {\n    constructor(\n        private _scriptLoader: ScriptLoader,\n        public _window: BoltHostWindow = window\n    ) {}\n\n    async load(publishableKey: string, testMode?: boolean, developerModeParams?: BoltDeveloperModeParams): Promise<BoltCheckout> {\n        const options: LoadScriptOptions = {\n            async: true,\n            attributes: {\n                id: 'bolt-connect',\n                'data-publishable-key': publishableKey,\n            },\n        };\n\n        await Promise.all([\n            this._scriptLoader.loadScript(`//${this.getDomainURL(!!testMode, developerModeParams)}/connect-bigcommerce.js`, options),\n            this._scriptLoader.loadScript(`//${this.getDomainURL(!!testMode, developerModeParams)}/track.js`),\n        ]);\n\n        if (!this._window.BoltCheckout) {\n            throw new PaymentMethodClientUnavailableError();\n        }\n\n        return this._window.BoltCheckout;\n    }\n\n    private getDomainURL(testMode: boolean, developerModeParams?: BoltDeveloperModeParams): string {\n\n        if (!testMode) {\n            return 'connect.bolt.com';\n        }\n\n        if (developerModeParams) {\n            switch (developerModeParams.developerMode) {\n                case BoltDeveloperMode.StagingMode:\n                    return 'connect-staging.bolt.com';\n                case BoltDeveloperMode.DevelopmentMode:\n                    return `connect.${developerModeParams.developerDomain}`;\n            }\n        }\n\n        return 'connect-sandbox.bolt.com';\n    }\n}\n","import { BraintreeVerifyPayload } from './braintree';\n\n/**\n * A set of options that are required to initialize the Braintree payment\n * method. You need to provide the options if you want to support 3D Secure\n * authentication flow.\n *\n * ```html\n * <!-- These containers are where the hosted (iframed) credit card fields will be inserted -->\n * <div id=\"card-number\"></div>\n * <div id=\"card-name\"></div>\n * <div id=\"card-expiry\"></div>\n * <div id=\"card-code\"></div>\n * ```\n *\n * ```js\n * service.initializePayment({\n *     methodId: 'braintree',\n *     braintree: {\n *         form: {\n *             fields: {\n *                 cardNumber: { containerId: 'card-number' },\n *                 cardName: { containerId: 'card-name' },\n *                 cardExpiry: { containerId: 'card-expiry' },\n *                 cardCode: { containerId: 'card-code' },\n *             },\n *         },\n *     },\n * });\n * ```\n *\n * Additional options can be passed in to customize the fields and register\n * event callbacks.\n *\n * ```js\n * service.initializePayment({\n *     methodId: 'braintree',\n *     creditCard: {\n *         form: {\n *             fields: {\n *                 cardNumber: { containerId: 'card-number' },\n *                 cardName: { containerId: 'card-name' },\n *                 cardExpiry: { containerId: 'card-expiry' },\n *                 cardCode: { containerId: 'card-code' },\n *             },\n *             styles: {\n *                 default: {\n *                     color: '#000',\n *                 },\n *                 error: {\n *                     color: '#f00',\n *                 },\n *                 focus: {\n *                     color: '#0f0',\n *                 },\n *             },\n *             onBlur({ fieldType }) {\n *                 console.log(fieldType);\n *             },\n *             onFocus({ fieldType }) {\n *                 console.log(fieldType);\n *             },\n *             onEnter({ fieldType }) {\n *                 console.log(fieldType);\n *             },\n *             onCardTypeChange({ cardType }) {\n *                 console.log(cardType);\n *             },\n *             onValidate({ errors, isValid }) {\n *                 console.log(errors);\n *                 console.log(isValid);\n *             },\n *         },\n *     },\n * });\n * ```\n */\nexport interface BraintreePaymentInitializeOptions {\n    threeDSecure?: BraintreeThreeDSecureOptions;\n\n    /**\n     * @alpha\n     * Please note that this option is currently in an early stage of\n     * development. Therefore the API is unstable and not ready for public\n     * consumption.\n     */\n    form?: BraintreeFormOptions;\n}\n\n/**\n * A set of options that are required to support 3D Secure authentication flow.\n *\n * If the customer uses a credit card that has 3D Secure enabled, they will be\n * asked to verify their identity when they pay. The verification is done\n * through a web page via an iframe provided by the card issuer.\n */\nexport interface BraintreeThreeDSecureOptions {\n    /**\n     * A callback that gets called when the iframe is ready to be added to the\n     * current page. It is responsible for determining where the iframe should\n     * be inserted in the DOM.\n     *\n     * @param error - Any error raised during the verification process;\n     * undefined if there is none.\n     * @param iframe - The iframe element containing the verification web page\n     * provided by the card issuer.\n     * @param cancel - A function, when called, will cancel the verification\n     * process and remove the iframe.\n     */\n    addFrame(error: Error | undefined, iframe: HTMLIFrameElement, cancel: () => Promise<BraintreeVerifyPayload> | undefined): void;\n\n    /**\n     * A callback that gets called when the iframe is about to be removed from\n     * the current page.\n     */\n    removeFrame(): void;\n}\n\nexport interface BraintreeFormOptions {\n    fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap;\n    styles?: BraintreeFormFieldStylesMap;\n    onBlur?(data: BraintreeFormFieldBlurEventData): void;\n    onCardTypeChange?(data: BraintreeFormFieldCardTypeChangeEventData): void;\n    onFocus?(data: BraintreeFormFieldFocusEventData): void;\n    onValidate?(data: BraintreeFormFieldValidateEventData): void;\n    onEnter?(data: BraintreeFormFieldEnterEventData): void;\n}\n\nexport enum BraintreeFormFieldType {\n    CardCode = 'cardCode',\n    CardCodeVerification = 'cardCodeVerification',\n    CardExpiry = 'cardExpiry',\n    CardName = 'cardName',\n    CardNumber = 'cardNumber',\n    CardNumberVerification = 'cardNumberVerification',\n}\n\nexport interface BraintreeFormFieldsMap {\n    [BraintreeFormFieldType.CardCode]?: BraintreeFormFieldOptions;\n    [BraintreeFormFieldType.CardExpiry]: BraintreeFormFieldOptions;\n    [BraintreeFormFieldType.CardName]: BraintreeFormFieldOptions;\n    [BraintreeFormFieldType.CardNumber]: BraintreeFormFieldOptions;\n}\n\nexport interface BraintreeStoredCardFieldsMap {\n    [BraintreeFormFieldType.CardCodeVerification]?: BraintreeStoredCardFieldOptions;\n    [BraintreeFormFieldType.CardNumberVerification]?: BraintreeStoredCardFieldOptions;\n}\n\nexport interface BraintreeFormFieldOptions {\n    containerId: string;\n    placeholder?: string;\n}\n\nexport interface BraintreeStoredCardFieldOptions extends BraintreeFormFieldOptions {\n    instrumentId: string;\n}\n\nexport interface BraintreeFormFieldStylesMap {\n    default?: BraintreeFormFieldStyles;\n    error?: BraintreeFormFieldStyles;\n    focus?: BraintreeFormFieldStyles;\n}\n\nexport type BraintreeFormFieldStyles = Partial<Pick<\n    CSSStyleDeclaration,\n    'color' |\n    'fontFamily' |\n    'fontSize' |\n    'fontWeight'\n>>;\n\nexport interface BraintreeFormFieldKeyboardEventData {\n    fieldType: string;\n}\n\nexport type BraintreeFormFieldBlurEventData = BraintreeFormFieldKeyboardEventData;\nexport type BraintreeFormFieldEnterEventData = BraintreeFormFieldKeyboardEventData;\nexport type BraintreeFormFieldFocusEventData = BraintreeFormFieldKeyboardEventData;\n\nexport interface BraintreeFormFieldCardTypeChangeEventData {\n    cardType?: string;\n}\n\nexport interface BraintreeFormFieldValidateEventData {\n    errors: {\n        [BraintreeFormFieldType.CardCode]?: BraintreeFormFieldValidateErrorData[];\n        [BraintreeFormFieldType.CardExpiry]?: BraintreeFormFieldValidateErrorData[];\n        [BraintreeFormFieldType.CardName]?: BraintreeFormFieldValidateErrorData[];\n        [BraintreeFormFieldType.CardNumber]?: BraintreeFormFieldValidateErrorData[];\n        [BraintreeFormFieldType.CardCodeVerification]?: BraintreeFormFieldValidateErrorData[];\n        [BraintreeFormFieldType.CardNumberVerification]?: BraintreeFormFieldValidateErrorData[];\n    };\n    isValid: boolean;\n}\n\nexport interface BraintreeFormFieldValidateErrorData {\n    fieldType: string;\n    message: string;\n    type: string;\n}\n","import getOverlayStyle from './overlay-style';\n\nexport interface OverlayOptions {\n    background?: string;\n    id?: string;\n    transitionDuration?: number;\n    hasCloseButton?: boolean;\n    innerHtml?: HTMLElement | DocumentFragment;\n}\n\nexport interface OverlayShowOptions {\n    onClick?(event: MouseEvent): void;\n    onClickClose?(event: MouseEvent): void;\n}\n\nexport interface Elements {\n    element: HTMLElement;\n    mainElement: HTMLElement;\n    closeElement?: HTMLElement;\n}\n\nexport default class Overlay {\n    private _element: HTMLElement;\n    private _mainElement: HTMLElement;\n    private _closeElement?: HTMLElement;\n    private _unregisterClick?: () => void;\n\n    constructor(options?: OverlayOptions) {\n        const { element, closeElement, mainElement } = this._createElements(options);\n\n        this._element = element;\n        this._closeElement = closeElement;\n        this._mainElement = mainElement;\n    }\n\n    show(options?: OverlayShowOptions): void {\n\n        if (this._mainElement.parentElement) {\n            return;\n        }\n\n        this._registerClick(options);\n\n        document.body.appendChild(this._mainElement);\n\n        // Fade In\n        setTimeout(() => this._element.style.opacity = '1');\n    }\n\n    remove(): void {\n        if (!this._mainElement.parentElement) {\n            return;\n        }\n\n        if (this._unregisterClick) {\n            this._unregisterClick();\n        }\n\n        this._removeAfterTransition();\n\n        setTimeout(() => this._element.style.opacity = '0');\n    }\n\n    private _createElements(options?: OverlayOptions): Elements {\n        const element = document.createElement('div');\n        const {\n            background = 'rgba(0, 0, 0, 0.8)',\n            id = 'checkoutOverlay',\n            transitionDuration = 400,\n            hasCloseButton,\n            innerHtml,\n        } = options || {};\n        let mainElement = element;\n        let closeElement: HTMLElement | undefined;\n        let classLayout: string | undefined;\n        let classClose: string | undefined;\n        let classOverlayText: string | undefined;\n\n        if (id) {\n            element.id = id;\n        }\n\n        if (innerHtml) {\n            const overlayText = document.createElement('div');\n            classOverlayText = `${id}--overlayText`;\n            overlayText.className = classOverlayText;\n            overlayText.appendChild(innerHtml);\n\n            element.appendChild(overlayText);\n        }\n\n        if (hasCloseButton) {\n            classClose = `${id}--close`;\n            closeElement = document.createElement('div');\n            closeElement.className =  classClose;\n\n            classLayout = `${id}--layout`;\n            mainElement = document.createElement('div');\n            mainElement.className = classLayout;\n\n            mainElement.appendChild(element);\n            mainElement.appendChild(closeElement);\n        }\n\n        mainElement.appendChild(getOverlayStyle({ id, background, transitionDuration, classLayout, classOverlayText, classClose }));\n\n        return { element, closeElement, mainElement };\n    }\n\n    private _addEventListener(element?: HTMLElement, onClick?: (event: MouseEvent) => void): void {\n        if (!element || !onClick) {\n           return;\n        }\n\n        element.addEventListener('click', onClick);\n    }\n\n    private _removeEventListener(element?: HTMLElement, onClick?: (event: MouseEvent) => void): void {\n        if (!element || !onClick) {\n            return;\n        }\n\n        element.removeEventListener('click', onClick);\n    }\n\n    private _registerClick(options?: OverlayShowOptions): void {\n        if (this._unregisterClick) {\n            this._unregisterClick();\n        }\n\n        if (options) {\n            const { onClick, onClickClose } = options;\n\n            this._addEventListener(this._element, onClick);\n            this._addEventListener(this._closeElement, onClickClose);\n\n            this._unregisterClick = () => {\n                this._removeEventListener(this._element, onClick);\n                this._removeEventListener(this._closeElement, onClickClose);\n                this._unregisterClick = undefined;\n            };\n        }\n    }\n\n    private _removeAfterTransition(): void {\n        const handleTransition: (event: Event) => void = event => {\n            // NOTE: `event` is not correctly typed in this version of TS\n            if ((event as TransitionEvent).propertyName !== 'opacity') {\n                return;\n            }\n\n            if (this._mainElement.parentElement) {\n                this._mainElement.remove();\n            }\n\n            this._element.removeEventListener('transitionend', handleTransition);\n        };\n\n        this._element.addEventListener('transitionend', handleTransition);\n    }\n}\n","interface OverlayStyleOptions {\n    background?: string;\n    id?: string;\n    transitionDuration?: number;\n    classLayout?: string;\n    classOverlayText?: string;\n    classClose?: string;\n}\n\nexport default function getOverlayStyle(options: OverlayStyleOptions): HTMLElement {\n    const { id, background, transitionDuration, classLayout, classOverlayText, classClose } = options;\n    const styles = document.createElement('style');\n    const addClassLayout = classLayout ? `, .${classLayout}` : '';\n\n    styles.id = `${id}--styles`;\n    styles.type = 'text/css';\n    styles.innerText = `\n        #${id}${addClassLayout} {\n            display: block;\n            height: 100%;\n            width: 100%;\n            left: 0;\n            top: 0;\n            position: fixed;\n            z-index: 2147483647;\n        }\n        #${id} {\n            transition: opacity ${transitionDuration}ms ease-out;\n            background: ${background};\n            opacity: 0;\n        }\n    `;\n\n    if (classOverlayText) {\n        styles.innerText += `\n             #${id} {\n                display: flex;\n                align-items: center;\n                justify-content: center;\n             }\n             #${id} .${classOverlayText} {\n                color: white;\n                max-width: 330px;\n                font-size: 1.2em;\n                text-align: center;\n             }\n        `;\n    }\n\n    if (classClose) {\n        styles.innerText += `\n            #${id} {\n                opacity: 1;\n            }\n            .${classLayout} .${classClose} {\n                position: fixed;\n                right: 16px;\n                top: 16px;\n                width: 16px;\n                height: 16px;\n                opacity: 0.6;\n                cursor: pointer;\n                z-index: 3147483647;\n            }\n            .${classLayout} .${classClose}::after, .${classLayout} .${classClose}::before {\n                position: absolute;\n                left: 8px;\n                content: '';\n                height: 16px;\n                width: 2px;\n                background-color: #fff;\n            }\n            .${classLayout} .${classClose}::after {\n                transform: rotate(-45deg);\n            }\n            .${classLayout} .${classClose}::before {\n                transform: rotate(45deg);\n            }\n        `;\n    }\n\n    return styles;\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport interface PaymentInvalidFormErrorDetails {\n    [key: string]: Array<{ message: string; type: string }>;\n}\n\nexport default class PaymentInvalidFormError extends StandardError {\n    constructor(\n        public details: PaymentInvalidFormErrorDetails,\n        message?: string\n    ) {\n        super(message || 'Unable to proceed because the payment form contains invalid data.');\n\n        this.name = 'PaymentInvalidFormError';\n        this.type = 'payment_invalid_form';\n    }\n}\n","import { InvalidArgumentError } from '../../../common/error/errors';\n\nimport { BraintreeFormFieldOptions, BraintreeFormFieldStyles, BraintreeFormFieldStylesMap } from './braintree-payment-options';\n\nexport default class BraintreeRegularField {\n    private _input: HTMLInputElement;\n\n    constructor(\n        private _options: BraintreeFormFieldOptions,\n        private _styles?: BraintreeFormFieldStylesMap\n    ) {\n        this._input = document.createElement('input');\n        this._input.style.backgroundColor = 'transparent';\n        this._input.style.border = '0';\n        this._input.style.display = 'block';\n        this._input.style.height = '100%';\n        this._input.style.margin = '0';\n        this._input.style.outline = 'none';\n        this._input.style.padding = '0';\n        this._input.style.width = '100%';\n        this._input.placeholder = this._options.placeholder || '';\n\n        this._input.addEventListener('blur', this._handleBlur);\n        this._input.addEventListener('focus', this._handleFocus);\n\n        this._applyStyles(this._styles?.default);\n    }\n\n    getValue(): string {\n        return this._input.value;\n    }\n\n    attach(): void {\n        const container = document.getElementById(this._options.containerId);\n\n        if (!container) {\n            throw new InvalidArgumentError();\n        }\n\n        container.appendChild(this._input);\n    }\n\n    detach(): void {\n        this._input.parentNode?.removeChild(this._input);\n    }\n\n    on(event: string, callback: () => void): void {\n        this._input.addEventListener(event, callback);\n    }\n\n    off(event: string, callback: () => void): void {\n        this._input.removeEventListener(event, callback);\n    }\n\n    private _applyStyles(styles?: BraintreeFormFieldStyles): void {\n        if (!styles) {\n            return;\n        }\n\n        const styleKeys = Object.keys(styles) as Array<keyof BraintreeFormFieldStyles>;\n\n        styleKeys.forEach(key => {\n            this._input.style[key] = styles[key] || '';\n        });\n    }\n\n    private _handleBlur: (event: Event) => void = () => {\n        this._applyStyles(this._styles?.default);\n    };\n\n    private _handleFocus: (event: Event) => void = () => {\n        this._applyStyles(this._styles?.focus);\n    };\n}\n","import { isEmpty, isNil, omitBy, Dictionary } from 'lodash';\n\nimport { Address } from '../../../address';\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { PaymentInvalidFormError, PaymentInvalidFormErrorDetails } from '../../errors';\nimport { NonceInstrument } from '../../payment';\n\nimport { BraintreeBillingAddressRequestData, BraintreeHostedFields, BraintreeHostedFieldsCreatorConfig, BraintreeHostedFieldsState, BraintreeHostedFormError } from './braintree';\nimport { BraintreeFormFieldsMap, BraintreeFormFieldStyles, BraintreeFormFieldStylesMap, BraintreeFormFieldType, BraintreeFormFieldValidateErrorData, BraintreeFormFieldValidateEventData, BraintreeFormOptions, BraintreeStoredCardFieldsMap } from './braintree-payment-options';\nimport BraintreeRegularField from './braintree-regular-field';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport { isBraintreeFormFieldsMap } from './is-braintree-form-fields-map';\n\nenum BraintreeHostedFormType {\n    CreditCard,\n    StoredCardVerification,\n}\n\nexport default class BraintreeHostedForm {\n    private _cardFields?: BraintreeHostedFields;\n    private _cardNameField?: BraintreeRegularField;\n    private _formOptions?: BraintreeFormOptions;\n    private _type?: BraintreeHostedFormType;\n\n    constructor(\n        private _braintreeSDKCreator: BraintreeSDKCreator\n    ) {}\n\n    async initialize(options: BraintreeFormOptions): Promise<boolean> {\n        this._formOptions = options;\n\n        this._type = isBraintreeFormFieldsMap(options.fields) ?\n            BraintreeHostedFormType.CreditCard :\n            BraintreeHostedFormType.StoredCardVerification;\n\n        const fields = this._mapFieldOptions(options.fields);\n\n        if (isEmpty(fields)) {\n            return false;\n        }\n\n        this._cardFields = await this._braintreeSDKCreator.createHostedFields({\n            fields,\n            styles: options.styles && this._mapStyleOptions(options.styles),\n        });\n\n        this._cardFields.on('blur', this._handleBlur);\n        this._cardFields.on('focus', this._handleFocus);\n        this._cardFields.on('cardTypeChange', this._handleCardTypeChange);\n        this._cardFields.on('validityChange', this._handleValidityChange);\n        this._cardFields.on('inputSubmitRequest', this._handleInputSubmitRequest);\n\n        if (isBraintreeFormFieldsMap(options.fields)) {\n            this._cardNameField = new BraintreeRegularField(\n                options.fields.cardName,\n                options.styles\n            );\n            this._cardNameField.on('blur', this._handleNameBlur);\n            this._cardNameField.on('focus', this._handleNameFocus);\n            this._cardNameField.attach();\n        }\n\n        return true;\n    }\n\n    async deinitialize(): Promise<void> {\n        await this._cardFields?.teardown();\n        this._cardNameField?.detach();\n    }\n\n    async tokenize(billingAddress: Address): Promise<NonceInstrument> {\n        if (!this._cardFields) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        try {\n            const { nonce } = await this._cardFields.tokenize(omitBy({\n                billingAddress: billingAddress && this._mapBillingAddress(billingAddress),\n                cardholderName: this._cardNameField?.getValue(),\n            }, isNil));\n\n            this._formOptions?.onValidate?.({\n                isValid: true,\n                errors: {},\n            });\n\n            return { nonce };\n        } catch (error) {\n            const errors = this._mapTokenizeError(error);\n\n            if (errors) {\n                this._formOptions?.onValidate?.({\n                    isValid: false,\n                    errors,\n                });\n\n                throw new PaymentInvalidFormError(errors as PaymentInvalidFormErrorDetails);\n            }\n\n            throw error;\n        }\n    }\n\n    async tokenizeForStoredCardVerification(): Promise<NonceInstrument> {\n        if (!this._cardFields) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        try {\n            const { nonce } = await this._cardFields.tokenize(omitBy({\n                cardholderName: this._cardNameField?.getValue(),\n            }, isNil));\n\n            this._formOptions?.onValidate?.({\n                isValid: true,\n                errors: {},\n            });\n\n            return { nonce };\n        } catch (error) {\n            const errors = this._mapTokenizeError(error);\n\n            if (errors) {\n                this._formOptions?.onValidate?.({\n                    isValid: false,\n                    errors,\n                });\n\n                throw new PaymentInvalidFormError(errors as PaymentInvalidFormErrorDetails);\n            }\n\n            throw error;\n        }\n    }\n\n    private _mapBillingAddress(billingAddress: Address): BraintreeBillingAddressRequestData {\n        return {\n            countryName: billingAddress.country,\n            postalCode: billingAddress.postalCode,\n            streetAddress: billingAddress.address2 ?\n                `${billingAddress.address1} ${billingAddress.address2}` :\n                billingAddress.address1,\n        };\n    }\n\n    private _mapFieldOptions(\n        fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap\n    ): BraintreeHostedFieldsCreatorConfig['fields'] {\n        if (isBraintreeFormFieldsMap(fields)) {\n            return omitBy({\n                number: {\n                    container: `#${fields.cardNumber.containerId}`,\n                    placeholder: fields.cardNumber.placeholder,\n                },\n                expirationDate: {\n                    container: `#${fields.cardExpiry.containerId}`,\n                    placeholder: fields.cardExpiry.placeholder,\n                },\n                cvv: fields.cardCode && {\n                    container: `#${fields.cardCode.containerId}`,\n                    placeholder: fields.cardCode.placeholder,\n                },\n            }, isNil);\n        }\n\n        return omitBy({\n            number: fields.cardNumberVerification && {\n                container: `#${fields.cardNumberVerification.containerId}`,\n                placeholder: fields.cardNumberVerification.placeholder,\n            },\n            cvv: fields.cardCodeVerification && {\n                container: `#${fields.cardCodeVerification.containerId}`,\n                placeholder: fields.cardCodeVerification.placeholder,\n            },\n        }, isNil);\n    }\n\n    private _mapStyleOptions(\n        options: BraintreeFormFieldStylesMap\n    ): BraintreeHostedFieldsCreatorConfig['styles'] {\n        const mapStyles = (styles: BraintreeFormFieldStyles = {}) => omitBy({\n            color: styles.color,\n            'font-family': styles.fontFamily,\n            'font-size': styles.fontSize,\n            'font-weight': styles.fontWeight,\n        }, isNil) as Dictionary<string>;\n\n        return {\n            input: mapStyles(options.default),\n            '.invalid': mapStyles(options.error),\n            ':focus': mapStyles(options.focus),\n        };\n    }\n\n    private _mapFieldType(type: string): BraintreeFormFieldType {\n        switch (type) {\n        case 'number':\n            return this._type === BraintreeHostedFormType.StoredCardVerification ?\n                BraintreeFormFieldType.CardNumberVerification :\n                BraintreeFormFieldType.CardNumber;\n\n        case 'expirationDate':\n            return BraintreeFormFieldType.CardExpiry;\n\n        case 'cvv':\n            return this._type === BraintreeHostedFormType.StoredCardVerification ?\n                BraintreeFormFieldType.CardCodeVerification :\n                BraintreeFormFieldType.CardCode;\n\n        default:\n            throw new Error('Unexpected field type');\n        }\n    }\n\n    private _mapValidationErrors(\n        fields: BraintreeHostedFieldsState['fields']\n    ): BraintreeFormFieldValidateEventData['errors'] {\n        return (Object.keys(fields) as Array<keyof BraintreeHostedFieldsState['fields']>)\n            .reduce((result, fieldKey) => ({\n                ...result,\n                [this._mapFieldType(fieldKey)]: fields[fieldKey]?.isValid ? undefined : [\n                    this._createInvalidError(this._mapFieldType(fieldKey)),\n                ],\n            }), {});\n    }\n\n    private _mapTokenizeError(\n        error: BraintreeHostedFormError\n    ): BraintreeFormFieldValidateEventData['errors'] | undefined {\n        if (error.code === 'HOSTED_FIELDS_FIELDS_EMPTY') {\n            return {\n                [this._mapFieldType('cvv')]: [\n                    this._createRequiredError(this._mapFieldType('cvv')),\n                ],\n                [this._mapFieldType('expirationDate')]: [\n                    this._createRequiredError(this._mapFieldType('expirationDate')),\n                ],\n                [this._mapFieldType('number')]: [\n                    this._createRequiredError(this._mapFieldType('number')),\n                ],\n            };\n        }\n\n        return error?.details?.invalidFieldKeys?.reduce((result, fieldKey) => ({\n            ...result,\n            [this._mapFieldType(fieldKey)]: [\n                this._createInvalidError(this._mapFieldType(fieldKey)),\n            ],\n        }), {});\n    }\n\n    private _createRequiredError(fieldType: BraintreeFormFieldType): BraintreeFormFieldValidateErrorData {\n        switch (fieldType) {\n        case BraintreeFormFieldType.CardCodeVerification:\n        case BraintreeFormFieldType.CardCode:\n            return {\n                fieldType,\n                message: 'CVV is required',\n                type: 'required',\n            };\n\n        case BraintreeFormFieldType.CardNumberVerification:\n        case BraintreeFormFieldType.CardNumber:\n            return {\n                fieldType,\n                message: 'Credit card number is required',\n                type: 'required',\n            };\n\n        case BraintreeFormFieldType.CardExpiry:\n            return {\n                fieldType,\n                message: 'Expiration date is required',\n                type: 'required',\n            };\n\n        case BraintreeFormFieldType.CardName:\n            return {\n                fieldType,\n                message: 'Full name is required',\n                type: 'required',\n            };\n\n        default:\n            return {\n                fieldType,\n                message: 'Field is required',\n                type: 'required',\n            };\n        }\n    }\n\n    private _createInvalidError(fieldType: BraintreeFormFieldType): BraintreeFormFieldValidateErrorData {\n        switch (fieldType) {\n        case BraintreeFormFieldType.CardCodeVerification:\n            return {\n                fieldType,\n                message: 'Invalid card code',\n                type: 'invalid_card_code',\n            };\n\n        case BraintreeFormFieldType.CardNumberVerification:\n            return {\n                fieldType,\n                message: 'Invalid card number',\n                type: 'invalid_card_number',\n            };\n\n        case BraintreeFormFieldType.CardCode:\n            return {\n                fieldType,\n                message: 'Invalid card code',\n                type: 'invalid_card_code',\n            };\n\n        case BraintreeFormFieldType.CardExpiry:\n            return {\n                fieldType,\n                message: 'Invalid card expiry',\n                type: 'invalid_card_expiry',\n            };\n\n        case BraintreeFormFieldType.CardNumber:\n            return {\n                fieldType,\n                message: 'Invalid card number',\n                type: 'invalid_card_number',\n            };\n\n        default:\n            return {\n                fieldType,\n                message: 'Invalid field',\n                type: 'invalid',\n            };\n        }\n    }\n\n    private _handleBlur: (event: BraintreeHostedFieldsState) => void = event => {\n        this._formOptions?.onBlur?.({\n            fieldType: this._mapFieldType(event.emittedBy),\n        });\n    };\n\n    private _handleNameBlur: () => void = () => {\n        this._formOptions?.onBlur?.({\n            fieldType: BraintreeFormFieldType.CardName,\n        });\n    };\n\n    private _handleFocus: (event: BraintreeHostedFieldsState) => void = event => {\n        this._formOptions?.onFocus?.({\n            fieldType: this._mapFieldType(event.emittedBy),\n        });\n    };\n\n    private _handleNameFocus: () => void = () => {\n        this._formOptions?.onFocus?.({\n            fieldType: BraintreeFormFieldType.CardName,\n        });\n    };\n\n    private _handleCardTypeChange: (event: BraintreeHostedFieldsState) => void = event => {\n        this._formOptions?.onCardTypeChange?.({\n            cardType: event.cards.length === 1\n                ? event.cards[0].type.replace(/^master\\-card$/, 'mastercard')\n                : undefined,\n        });\n    };\n\n    private _handleInputSubmitRequest: (event: BraintreeHostedFieldsState) => void = event => {\n        this._formOptions?.onEnter?.({\n            fieldType: this._mapFieldType(event.emittedBy),\n        });\n    };\n\n    private _handleValidityChange: (event: BraintreeHostedFieldsState) => void = event => {\n        this._formOptions?.onValidate?.({\n            isValid: (Object.keys(event.fields) as Array<keyof BraintreeHostedFieldsState['fields']>)\n                .every(key => event.fields[key]?.isValid),\n            errors: this._mapValidationErrors(event.fields),\n        });\n    };\n}\n","import { BraintreeFormFieldsMap, BraintreeStoredCardFieldsMap } from './braintree-payment-options';\n\nexport function isBraintreeFormFieldsMap(\n    fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap\n): fields is BraintreeFormFieldsMap {\n    return !!(fields as BraintreeFormFieldsMap).cardNumber;\n}\n\nexport function isBraintreeStoredCardFieldsMap(\n    fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap\n): fields is BraintreeStoredCardFieldsMap {\n    return !!(\n        (fields as BraintreeStoredCardFieldsMap).cardCodeVerification ||\n        (fields as BraintreeStoredCardFieldsMap).cardNumberVerification\n    );\n}\n","import { ThreeDSecure, ThreeDSecureToken } from '../../payment';\n\nexport const CardinalSignatureValidationErrors = [100004, 1010, 1011, 1020];\n\nexport interface CardinalSDK {\n    configure(params: CardinalConfiguration): void;\n    on(params: CardinalEventType, callback: CardinalEventMap[CardinalEventType]): void;\n    off(params: CardinalEventType): void;\n    setup<K extends keyof CardinalInitializationDataMap>(initializationType: K, initializationData: CardinalInitializationDataMap[K]): void;\n    trigger(event: CardinalTriggerEvents, data?: string): Promise<CardinalBinProcessResponse | void>;\n    continue(paymentBrand: CardinalPaymentBrand, continueObject: CardinalContinue, order: CardinalPartialOrder): void;\n    start(paymentBrand: CardinalPaymentBrand, order: CardinalPartialOrder, jwt?: string): void;\n}\n\nexport interface CardinalWindow extends Window {\n    Cardinal?: CardinalSDK;\n}\n\nexport interface CardinalEventMap {\n    [CardinalEventType.SetupCompleted](setupCompleteData: CardinalSetupCompletedData): void;\n    [CardinalEventType.Validated](data: CardinalValidatedData, jwt?: string): void;\n}\n\nexport type CardinalConfiguration = Partial<{\n    logging: {\n        level: string;\n    };\n    payment: {\n        view: string;\n        framework: string;\n        displayLoading: boolean;\n    };\n}>;\n\nexport interface CardinalSetupCompletedData {\n    sessionId: string;\n    modules: CardinalModuleState[];\n}\n\nexport interface CardinalModuleState {\n    loaded: boolean;\n    module: string;\n}\n\nexport enum CardinalInitializationType {\n    Init = 'init',\n    Complete = 'complete',\n    Confirm = 'confirm',\n}\n\nexport interface CardinalInitializationDataMap {\n    [CardinalInitializationType.Init]: CardinalInitTypeData;\n    [CardinalInitializationType.Complete]: CardinalCompleteTypeData;\n    [CardinalInitializationType.Confirm]: CardinalConfirmTypeData;\n}\n\nexport interface CardinalInitTypeData {\n    jwt: string;\n}\n\nexport interface CardinalCompleteTypeData {\n    Status: string;\n}\n\nexport interface CardinalConfirmTypeData {\n    jwt: string;\n    cardinalResponseJwt: string;\n}\n\nexport interface CardinalValidatedData {\n    ActionCode?: CardinalValidatedAction;\n    ErrorDescription: string;\n    ErrorNumber: number;\n    Validated?: boolean;\n    Payment?: CardinalPayment;\n}\n\nexport interface CardinalPayment {\n    ExtendedData?: CardinalCCAExtendedData;\n    ProcessorTransactionId: string;\n    Type: CardinalPaymentType;\n}\n\nexport interface CardinalBinProcessResponse {\n    Status: boolean;\n}\n\nexport interface CardinalContinue {\n    AcsUrl: string;\n    Payload: string;\n}\n\nexport interface CardinalPartialOrder {\n    OrderDetails: CardinalOrderDetails;\n    Consumer?: CardinalConsumer;\n}\n\nexport interface CardinalConsumer {\n    Email1?: string;\n    Email2?: string;\n    ShippingAddress?: CardinalAddress;\n    BillingAddress?: CardinalAddress;\n    Account?: CardinalAccount;\n}\n\nexport interface CardinalAccount {\n    AccountNumber: number;\n    ExpirationMonth: number;\n    ExpirationYear: number;\n    NameOnAccount: string;\n    CardCode: number;\n}\n\nexport interface CardinalAddress {\n    FullName?: string;\n    FirstName: string;\n    MiddleName?: string;\n    LastName: string;\n    Address1: string;\n    Address2?: string;\n    Address3?: string;\n    City: string;\n    State: string;\n    PostalCode: string;\n    CountryCode: string;\n    Phone1?: string;\n    Phone2?: string;\n}\n\nexport interface CardinalOrderDetails {\n    OrderNumber: string;\n    Amount: number;\n    CurrencyCode: string;\n    OrderDescription?: string;\n    OrderChannel: string;\n    TransactionId?: string;\n}\n\nexport type CardinalCCAExtendedData = Partial<{\n    CAVV: string;\n    ECIFlag: string;\n    PAResStatus: string;\n    SignatureVerification: string;\n    XID: string;\n    UCAFIndicator: string;\n    ChallengeCancel: string;\n}>;\n\nexport enum CardinalEventType {\n    SetupCompleted = 'payments.setupComplete',\n    Validated = 'payments.validated',\n}\n\nexport enum CardinalValidatedAction {\n    Success = 'SUCCESS',\n    NoAction = 'NOACTION',\n    Failure = 'FAILURE',\n    Error = 'ERROR',\n}\n\nexport enum CardinalPaymentType {\n    CCA = 'CCA',\n    Paypal = 'Paypal',\n    Wallet = 'Wallet',\n    VisaCheckout = 'VisaCheckout',\n    ApplePay = 'ApplePay',\n    DiscoverWallet = 'DiscoverWallet',\n}\n\nexport enum CardinalTriggerEvents {\n    BinProcess = 'bin.process',\n}\n\nexport enum CardinalPaymentBrand {\n    CCA = 'cca',\n}\n\nexport enum CardinalSignatureVerification {\n    Yes = 'Y',\n    No = 'N',\n}\n\nexport type CardinalThreeDSecureToken = Pick<ThreeDSecure, 'xid'> | ThreeDSecureToken;\n","import { supportsPopups } from '@braintree/browser-detection';\n\nimport { Address } from '../../../address';\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { Overlay } from '../../../common/overlay';\nimport { CancellablePromise } from '../../../common/utility';\nimport { OrderPaymentRequestBody } from '../../../order';\nimport { PaymentMethodCancelledError } from '../../errors';\nimport { CreditCardInstrument, NonceInstrument } from '../../payment';\n\nimport { BraintreePaypal, BraintreeRequestData, BraintreeShippingAddressOverride, BraintreeThreeDSecure, BraintreeTokenizePayload, BraintreeVerifyPayload } from './braintree';\nimport BraintreeHostedForm from './braintree-hosted-form';\nimport { BraintreeFormOptions, BraintreePaymentInitializeOptions, BraintreeThreeDSecureOptions } from './braintree-payment-options';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\n\nexport interface PaypalConfig {\n    amount: number;\n    currency: string;\n    locale: string;\n    offerCredit?: boolean;\n    shippingAddressOverride?: BraintreeShippingAddressOverride;\n    shouldSaveInstrument?: boolean;\n}\n\nexport default class BraintreePaymentProcessor {\n    private _threeDSecureOptions?: BraintreeThreeDSecureOptions;\n\n    constructor(\n        private _braintreeSDKCreator: BraintreeSDKCreator,\n        private _braintreeHostedForm: BraintreeHostedForm,\n        private _overlay: Overlay\n    ) {}\n\n    initialize(clientToken: string, options?: BraintreePaymentInitializeOptions): void {\n        this._braintreeSDKCreator.initialize(clientToken);\n        this._threeDSecureOptions = options && options.threeDSecure;\n    }\n\n    preloadPaypal(): Promise<BraintreePaypal> {\n        return this._braintreeSDKCreator.getPaypal();\n    }\n\n    async tokenizeCard(payment: OrderPaymentRequestBody, billingAddress: Address): Promise<NonceInstrument> {\n        const requestData = this._mapToCreditCard(payment.paymentData as CreditCardInstrument, billingAddress);\n        const client = await this._braintreeSDKCreator.getClient();\n        const { creditCards } = await client.request(requestData);\n\n        return { nonce: creditCards[0].nonce };\n    }\n\n    async verifyCard(payment: OrderPaymentRequestBody, billingAddress: Address, amount: number): Promise<BraintreeVerifyPayload> {\n        const [{ nonce }, threeDSecure] = await Promise.all([\n            this.tokenizeCard(payment, billingAddress),\n            this._braintreeSDKCreator.get3DS(),\n        ]);\n\n        return this._present3DSChallenge(threeDSecure, amount, nonce);\n    }\n\n    paypal({ shouldSaveInstrument, ...config }: PaypalConfig): Promise<BraintreeTokenizePayload> {\n        const newWindowFlow = supportsPopups();\n\n        return this._braintreeSDKCreator.getPaypal()\n            .then(paypal => {\n                if (newWindowFlow) {\n                    this._overlay.show({\n                        onClick: () => paypal.focusWindow(),\n                    });\n                }\n\n                return paypal.tokenize({\n                    enableShippingAddress: true,\n                    flow: shouldSaveInstrument ? 'vault' : 'checkout',\n                    useraction: 'commit',\n                    ...config,\n                });\n            })\n            .then(response => {\n                this._overlay.remove();\n\n                return response;\n            })\n            .catch(error => {\n                this._overlay.remove();\n\n                throw error;\n            });\n    }\n\n    getSessionId(): Promise<string | undefined> {\n        return this._braintreeSDKCreator.getDataCollector()\n            .then(({ deviceData }) => deviceData);\n    }\n\n    /**\n     * @deprecated Use getSessionId() and combine them in the consumer.\n     */\n    appendSessionId(processedPayment: Promise<NonceInstrument>): Promise<NonceInstrument> {\n        return processedPayment\n            .then(paymentData => Promise.all([paymentData, this._braintreeSDKCreator.getDataCollector()]))\n            .then(([paymentData, { deviceData }]) => ({ ...paymentData, deviceSessionId: deviceData }));\n    }\n\n    deinitialize(): Promise<void> {\n        return this._braintreeSDKCreator.teardown();\n    }\n\n    async initializeHostedForm(options: BraintreeFormOptions): Promise<boolean> {\n        return await this._braintreeHostedForm.initialize(options);\n    }\n\n    async deinitializeHostedForm(): Promise<void> {\n        await this._braintreeHostedForm.deinitialize();\n    }\n\n    tokenizeHostedForm(billingAddress: Address): Promise<NonceInstrument> {\n        return this._braintreeHostedForm.tokenize(billingAddress);\n    }\n\n    tokenizeHostedFormForStoredCardVerification(): Promise<NonceInstrument> {\n        return this._braintreeHostedForm.tokenizeForStoredCardVerification();\n    }\n\n    async verifyCardWithHostedForm(billingAddress: Address, amount: number): Promise<NonceInstrument> {\n        const [{ nonce }, threeDSecure] = await Promise.all([\n            this._braintreeHostedForm.tokenize(billingAddress),\n            this._braintreeSDKCreator.get3DS(),\n        ]);\n\n        return this._present3DSChallenge(threeDSecure, amount, nonce);\n    }\n\n    private _present3DSChallenge(\n        threeDSecure: BraintreeThreeDSecure,\n        amount: number,\n        nonce: string\n    ): Promise<BraintreeVerifyPayload> {\n        if (!this._threeDSecureOptions || !nonce) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        const { addFrame, removeFrame } = this._threeDSecureOptions;\n        const cancelVerifyCard = async () => {\n            const response = await threeDSecure.cancelVerifyCard();\n\n            verification.cancel(new PaymentMethodCancelledError());\n\n            return response;\n        };\n\n        const verification = new CancellablePromise(\n            threeDSecure.verifyCard({\n                addFrame: (error, iframe) => {\n                    addFrame(error, iframe, cancelVerifyCard);\n                },\n                amount,\n                nonce,\n                removeFrame,\n                onLookupComplete: (_data, next) => {\n                    next();\n                },\n            })\n        );\n\n        return verification.promise;\n    }\n\n    private _mapToCreditCard(creditCard: CreditCardInstrument, billingAddress?: Address): BraintreeRequestData {\n        return {\n            data: {\n                creditCard: {\n                    cardholderName: creditCard.ccName,\n                    number: creditCard.ccNumber,\n                    cvv: creditCard.ccCvv,\n                    expirationDate: `${creditCard.ccExpiry.month}/${creditCard.ccExpiry.year}`,\n                    options: {\n                        validate: false,\n                    },\n                    billingAddress: billingAddress && {\n                        countryCodeAlpha2: billingAddress.countryCode,\n                        locality: billingAddress.city,\n                        countryName: billingAddress.country,\n                        postalCode: billingAddress.postalCode,\n                        streetAddress: billingAddress.address2 ?\n                            `${billingAddress.address1} ${billingAddress.address2}` :\n                            billingAddress.address1,\n                    },\n                },\n            },\n            endpoint: 'payment_methods/credit_cards',\n            method: 'post',\n        };\n    }\n}\n","import { pick } from 'lodash';\n\nimport { Address } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodFailedError } from '../../errors';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport { CreditCardInstrument, NonceInstrument, PaymentInstrument, PaymentInstrumentMeta, VaultedInstrumentWithNonceVerification } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport BraintreePaymentProcessor from './braintree-payment-processor';\n\nexport default class BraintreeCreditCardPaymentStrategy implements PaymentStrategy {\n    private _is3dsEnabled?: boolean;\n    private _isHostedFormInitialized?: boolean;\n    private _deviceSessionId?: string;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _braintreePaymentProcessor: BraintreePaymentProcessor\n    ) {}\n\n    async initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const state = await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(options.methodId));\n        const paymentMethod = state.paymentMethods.getPaymentMethod(options.methodId);\n\n        if (!paymentMethod || !paymentMethod.clientToken) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        try {\n            this._braintreePaymentProcessor.initialize(paymentMethod.clientToken, options.braintree);\n\n            if (this._isHostedPaymentFormEnabled(options.methodId, options.gatewayId) && options.braintree?.form) {\n                this._isHostedFormInitialized = await this._braintreePaymentProcessor.initializeHostedForm(options.braintree.form);\n            }\n\n            this._is3dsEnabled = paymentMethod.config.is3dsEnabled;\n            this._deviceSessionId = await this._braintreePaymentProcessor.getSessionId();\n        } catch (error) {\n            this._handleError(error);\n        }\n\n        return this._store.getState();\n    }\n\n    async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = orderRequest;\n\n        if (!payment) {\n            throw new PaymentArgumentInvalidError(['payment']);\n        }\n\n        const state = await this._store.dispatch(\n            this._orderActionCreator.submitOrder(order, options)\n        );\n\n        const {\n            billingAddress: { getBillingAddressOrThrow },\n            order: { getOrderOrThrow },\n            payment: { isPaymentDataRequired },\n        } = state;\n\n        if (!isPaymentDataRequired(order.useStoreCredit)) {\n            return state;\n        }\n\n        try {\n            return this._store.dispatch(this._paymentActionCreator.submitPayment({\n                ...payment,\n                paymentData: this._isHostedFormInitialized ?\n                    await this._prepareHostedPaymentData(\n                        payment,\n                        getBillingAddressOrThrow(),\n                        getOrderOrThrow().orderAmount\n                    ) :\n                    await this._preparePaymentData(\n                        payment,\n                        getBillingAddressOrThrow(),\n                        getOrderOrThrow().orderAmount\n                    ),\n            }));\n        } catch (error) {\n            this._handleError(error);\n        }\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    async deinitialize(): Promise<InternalCheckoutSelectors> {\n        this._isHostedFormInitialized = false;\n\n        await Promise.all([\n            this._braintreePaymentProcessor.deinitialize(),\n            this._braintreePaymentProcessor.deinitializeHostedForm(),\n        ]);\n\n        return this._store.getState();\n    }\n\n    private _handleError(error: Error): never {\n        if (error.name === 'BraintreeError') {\n            throw new PaymentMethodFailedError(error.message);\n        }\n\n        throw error;\n    }\n\n    private async _preparePaymentData(payment: OrderPaymentRequestBody, billingAddress: Address, orderAmount: number): Promise<PaymentInstrument & PaymentInstrumentMeta> {\n        const commonPaymentData = { deviceSessionId: this._deviceSessionId };\n\n        if (this._isSubmittingWithStoredCard(payment) || this._isStoringNewCard(payment)) {\n            return {\n                ...commonPaymentData,\n                ...payment.paymentData,\n            };\n        }\n\n        if (this._shouldPerform3DSVerification(payment)) {\n            return {\n                ...commonPaymentData,\n                ...this._mapToNonceInstrument({\n                    ...payment.paymentData,\n                    ...await this._braintreePaymentProcessor.verifyCard(payment, billingAddress, orderAmount),\n                }),\n            };\n        }\n\n        return {\n            ...commonPaymentData,\n            ...this._mapToNonceInstrument({\n                ...payment.paymentData,\n                ...await this._braintreePaymentProcessor.tokenizeCard(payment, billingAddress),\n            }),\n        };\n    }\n\n    private async _prepareHostedPaymentData(payment: OrderPaymentRequestBody, billingAddress: Address, orderAmount: number): Promise<PaymentInstrument & PaymentInstrumentMeta> {\n        const commonPaymentData = { deviceSessionId: this._deviceSessionId };\n\n        if (this._shouldPerform3DSVerification(payment)) {\n            return {\n                ...commonPaymentData,\n                ...this._mapToNonceInstrument({\n                    ...payment.paymentData,\n                    ...await this._braintreePaymentProcessor.verifyCardWithHostedForm(billingAddress, orderAmount),\n                }),\n            };\n        }\n\n        if (this._isSubmittingWithStoredCard(payment)) {\n            return {\n                ...commonPaymentData,\n                ...this._mapToVaultedInstrumentWithNonceVerification({\n                    ...payment.paymentData,\n                    ...await this._braintreePaymentProcessor.tokenizeHostedFormForStoredCardVerification(),\n                }),\n            };\n        }\n\n        return {\n            ...commonPaymentData,\n            ...this._mapToNonceInstrument({\n                ...payment.paymentData,\n                ...await this._braintreePaymentProcessor.tokenizeHostedForm(billingAddress),\n            }),\n        };\n    }\n\n    private _mapToNonceInstrument(instrument: PaymentInstrument): NonceInstrument {\n        return pick(instrument as NonceInstrument, 'nonce', 'shouldSaveInstrument', 'shouldSetAsDefaultInstrument');\n    }\n\n    private _mapToVaultedInstrumentWithNonceVerification(instrument: PaymentInstrument): VaultedInstrumentWithNonceVerification {\n        return pick(instrument as VaultedInstrumentWithNonceVerification, 'nonce', 'instrumentId');\n    }\n\n    private _isHostedPaymentFormEnabled(methodId?: string, gatewayId?: string): boolean {\n        if (!methodId) {\n            return false;\n        }\n\n        const { paymentMethods: { getPaymentMethodOrThrow } } = this._store.getState();\n        const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n        return paymentMethod.config.isHostedFormEnabled === true;\n    }\n\n    private _isSubmittingWithStoredCard(payment: OrderPaymentRequestBody): boolean {\n        return !!(payment.paymentData && isVaultedInstrument(payment.paymentData));\n    }\n\n    private _isStoringNewCard(payment: OrderPaymentRequestBody): boolean {\n        return !!(payment.paymentData && (payment.paymentData as CreditCardInstrument | NonceInstrument)?.shouldSaveInstrument);\n    }\n\n    private _shouldPerform3DSVerification(payment: OrderPaymentRequestBody): boolean {\n        return !!(this._is3dsEnabled && !this._isSubmittingWithStoredCard(payment));\n    }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError, PaymentMethodFailedError } from '../../errors';\nimport isVaultedInstrument, { isHostedVaultedInstrument } from '../../is-vaulted-instrument';\nimport Payment, { FormattedPayload, PaypalInstrument } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { BraintreePaymentInitializeOptions } from '../../strategies/braintree';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { BraintreeError } from './braintree';\nimport BraintreePaymentProcessor from './braintree-payment-processor';\nimport isBraintreeError from './is-braintree-error';\nimport mapToBraintreeShippingAddressOverride from './map-to-braintree-shipping-address-override';\n\nexport default class BraintreePaypalPaymentStrategy implements PaymentStrategy {\n    private _paymentMethod?: PaymentMethod;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _braintreePaymentProcessor: BraintreePaymentProcessor,\n        private _credit: boolean = false\n    ) {}\n\n    async initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { braintree: braintreeOptions, methodId } = options;\n\n        if (!this._paymentMethod || !this._paymentMethod.nonce) {\n            this._paymentMethod = this._store.getState().paymentMethods.getPaymentMethodOrThrow(methodId);\n        }\n\n        if (this._paymentMethod.clientToken) {\n            return this._loadPaypal(braintreeOptions);\n        }\n\n        const state = await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId));\n        this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n        if (!this._paymentMethod.clientToken) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        return this._loadPaypal(braintreeOptions);\n    }\n\n    execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = orderRequest;\n\n        if (!payment) {\n            throw new PaymentArgumentInvalidError(['payment']);\n        }\n\n        return (payment ? this._preparePaymentData(payment, order.useStoreCredit) : Promise.resolve(payment))\n            .then(payment => Promise.all([payment, this._store.dispatch(this._orderActionCreator.submitOrder(order, options))]))\n            .then(([payment]) => this._store.dispatch(this._paymentActionCreator.submitPayment(payment)))\n            .catch((error: Error) => this._handleError(error));\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        return this._braintreePaymentProcessor.deinitialize()\n            .then(() => this._store.getState());\n    }\n\n    private _handleError(error: BraintreeError | Error): never {\n        if (!isBraintreeError(error)) {\n            throw error;\n        }\n\n        if (error.code === 'PAYPAL_POPUP_CLOSED') {\n            throw new PaymentMethodCancelledError(error.message);\n        }\n\n        throw new PaymentMethodFailedError(error.message);\n    }\n\n    private async _preparePaymentData(payment: OrderPaymentRequestBody, useStoreCredit?: boolean): Promise<Payment> {\n        const state = this._store.getState();\n\n        const grandTotal = state.checkout.getOutstandingBalance(useStoreCredit);\n        const config = state.config.getStoreConfig();\n\n        if (!grandTotal) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n        }\n\n        if (!config) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n        }\n\n        if (!this._paymentMethod) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        const { currency, storeProfile: { storeLanguage } } = config;\n        const { nonce, config: { isVaultingEnabled } } = this._paymentMethod;\n        const { methodId, paymentData = {} } = payment;\n\n        if (nonce) {\n            const state = await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId));\n            this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n            return Promise.resolve({ ...payment, paymentData: this._formattedPayload(nonce) });\n        }\n\n        if (isVaultedInstrument(paymentData) || isHostedVaultedInstrument(paymentData)) {\n            if (!isVaultingEnabled) {\n                throw new InvalidArgumentError('Vaulting is disabled but a vaulted instrument was being used for this transaction');\n            }\n\n            return Promise.resolve(payment);\n        }\n\n        if (paymentData.shouldSaveInstrument && !isVaultingEnabled) {\n            throw new InvalidArgumentError('Vaulting is disabled but shouldSaveInstrument is set to true');\n        }\n\n        const shippingAddress = state.shippingAddress.getShippingAddress();\n\n        const shippingAddressOverride = shippingAddress ? mapToBraintreeShippingAddressOverride(shippingAddress) : undefined;\n\n        return Promise.all([\n            this._braintreePaymentProcessor.paypal({\n                amount: grandTotal,\n                locale: storeLanguage,\n                currency: currency.code,\n                offerCredit: this._credit,\n                shippingAddressOverride,\n                shouldSaveInstrument: paymentData.shouldSaveInstrument || false,\n            }),\n            this._braintreePaymentProcessor.getSessionId(),\n        ]).then(([\n            { nonce, details } = {} as any,\n            sessionId,\n        ]) => ({\n            ...payment,\n            paymentData: this._formattedPayload(nonce, details && details.email, sessionId, paymentData.shouldSaveInstrument, paymentData.shouldSetAsDefaultInstrument),\n        }));\n    }\n\n    private _formattedPayload(token: string, email?: string, sessionId?: string, vaultPaymentInstrument?: boolean, shouldSetAsDefaultInstrument?: boolean): FormattedPayload<PaypalInstrument> {\n        return {\n            formattedPayload: {\n                vault_payment_instrument: vaultPaymentInstrument || null,\n                set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n                device_info: sessionId || null,\n                paypal_account: {\n                    token,\n                    email: email || null,\n                },\n            },\n        };\n    }\n\n    private _loadPaypal(braintreeOptions?: BraintreePaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        if (!this._paymentMethod || !this._paymentMethod.clientToken) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        try {\n            this._braintreePaymentProcessor.initialize(this._paymentMethod.clientToken, braintreeOptions);\n\n            this._braintreePaymentProcessor.preloadPaypal();\n        } catch (error) {\n            this._handleError(error);\n        }\n\n        return Promise.resolve(this._store.getState());\n    }\n}\n","import { BraintreeError } from './braintree';\n\nexport default function isBraintreeError(error: BraintreeError | Error): error is BraintreeError {\n    return error.name === 'BraintreeError';\n}\n","import { Address } from '../../../address';\n\nimport { BraintreeShippingAddressOverride } from './braintree';\n\nexport default function mapToBraintreeShippingAddressOverride(address: Address): BraintreeShippingAddressOverride {\n    return {\n        recipientName: `${address.firstName} ${address.lastName}`,\n        line1: address.address1,\n        line2: address.address2,\n        city: address.city,\n        state: address.stateOrProvinceCode,\n        postalCode: address.postalCode,\n        countryCode: address.countryCode,\n        phone: address.phone,\n    };\n}\n","import { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentMethodFailedError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategyActionCreator from '../../payment-strategy-action-creator';\nimport PaymentStrategy from '../payment-strategy';\n\nimport BraintreeVisaCheckoutPaymentProcessor from './braintree-visacheckout-payment-processor';\nimport { VisaCheckoutPaymentSuccessPayload } from './visacheckout';\nimport VisaCheckoutScriptLoader from './visacheckout-script-loader';\n\nexport default class BraintreeVisaCheckoutPaymentStrategy implements PaymentStrategy {\n    private _paymentMethod?: PaymentMethod;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _checkoutActionCreator: CheckoutActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _orderActionCreator: OrderActionCreator,\n        private _braintreeVisaCheckoutPaymentProcessor: BraintreeVisaCheckoutPaymentProcessor,\n        private _visaCheckoutScriptLoader: VisaCheckoutScriptLoader\n    ) {}\n\n    initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { braintreevisacheckout: visaCheckoutOptions, methodId } = options;\n\n        if (!visaCheckoutOptions) {\n            throw new InvalidArgumentError('Unable to initialize payment because \"options.braintreevisacheckout\" argument is not provided.');\n        }\n\n        return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n            .then(state => {\n                this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n                const checkout = state.checkout.getCheckout();\n                const storeConfig = state.config.getStoreConfig();\n\n                if (!checkout) {\n                    throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n                }\n\n                if (!storeConfig) {\n                    throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n                }\n\n                if (!this._paymentMethod || !this._paymentMethod.clientToken) {\n                    throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n                }\n\n                const {\n                    onError = () => {},\n                    onPaymentSelect = () => {},\n                } = visaCheckoutOptions;\n\n                const initOptions = {\n                    locale: storeConfig.storeProfile.storeLanguage,\n                    collectShipping: false,\n                    subtotal: checkout.subtotal,\n                    currencyCode: storeConfig.currency.code,\n                };\n\n                return Promise.all([\n                    this._visaCheckoutScriptLoader.load(this._paymentMethod.config.testMode),\n                    this._braintreeVisaCheckoutPaymentProcessor.initialize(this._paymentMethod.clientToken, initOptions),\n                ])\n                .then(([visaCheckout, visaInitOptions]) => {\n                    visaCheckout.init(visaInitOptions);\n                    visaCheckout.on('payment.success', (paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) =>\n                        this._paymentInstrumentSelected(paymentSuccessPayload)\n                            .then(() => onPaymentSelect())\n                            .catch(error => onError(error))\n                    );\n                    visaCheckout.on('payment.error', (_, error) => onError(error));\n                });\n            })\n            .then(() => this._store.getState());\n    }\n\n    execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = orderRequest;\n\n        if (!payment) {\n            throw new InvalidArgumentError('Unable to submit payment because \"payload.payment\" argument is not provided.');\n        }\n\n        if (!this._paymentMethod || !this._paymentMethod.initializationData || !this._paymentMethod.initializationData.nonce) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        const { nonce } = this._paymentMethod.initializationData;\n\n        return this._store.dispatch(this._orderActionCreator.submitOrder(order, options))\n            .then(() =>\n                this._store.dispatch(this._paymentActionCreator.submitPayment({ ...payment, paymentData: { nonce } }))\n            )\n            .catch((error: Error) => this._handleError(error));\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        return this._braintreeVisaCheckoutPaymentProcessor.deinitialize()\n            .then(() => this._store.getState());\n    }\n\n    private _paymentInstrumentSelected(paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) {\n        const state = this._store.getState();\n\n        if (!this._paymentMethod) {\n            throw new Error('Payment method not initialized');\n        }\n\n        const { id: methodId } = this._paymentMethod;\n\n        return this._store.dispatch(this._paymentStrategyActionCreator.widgetInteraction(() => {\n            return this._braintreeVisaCheckoutPaymentProcessor.handleSuccess(\n                paymentSuccessPayload,\n                state.shippingAddress.getShippingAddress(),\n                state.billingAddress.getBillingAddress()\n            )\n            .then(() => Promise.all([\n                this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),\n                this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId)),\n            ]));\n        }, { methodId }), { queueId: 'widgetInteraction' });\n    }\n\n    private _handleError(error: Error): never {\n        if (error.name === 'BraintreeError') {\n            throw new PaymentMethodFailedError(error.message);\n        }\n\n        throw error;\n    }\n}\n","import { merge, some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { RequestError } from '../../../common/error/errors';\nimport { HostedForm } from '../../../hosted-form';\nimport { OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { InstrumentSelector } from '../../instrument';\nimport isCreditCardLike from '../../is-credit-card-like';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { CardinalThreeDSecureToken } from './cardinal';\nimport CardinalClient, { CardinalOrderData } from './cardinal-client';\n\nexport default class CardinalThreeDSecureFlowV2 {\n    constructor(\n        private _store: CheckoutStore,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _cardinalClient: CardinalClient\n    ) {}\n\n    async prepare(method: PaymentMethod): Promise<void> {\n        await this._cardinalClient.load(method.id, method.config.testMode);\n    }\n\n    async start(\n        execute: PaymentStrategy['execute'],\n        payload: OrderRequestBody,\n        options?: PaymentRequestOptions,\n        hostedForm?: HostedForm\n    ): Promise<InternalCheckoutSelectors> {\n        const { instruments: { getCardInstrument } } = this._store.getState();\n        const { payment = { methodId: '' } } = payload;\n        const { paymentData = {} } = payment;\n\n        try {\n            return await execute(payload, options);\n        } catch (error) {\n            if (error instanceof RequestError && error.body.status === 'additional_action_required') {\n                const token = error.body.additional_action_required?.data?.token;\n                const xid = error.body.three_ds_result?.payer_auth_request;\n\n                await this._cardinalClient.configure(token);\n\n                const bin = this._getBin(paymentData, getCardInstrument, hostedForm);\n\n                if (bin) {\n                    await this._cardinalClient.runBinProcess(bin);\n                }\n\n                try {\n                    return await this._submitPayment(payment, { xid }, hostedForm);\n                } catch (error) {\n                    if (error instanceof RequestError && some(error.body.errors, {code: 'three_d_secure_required'})) {\n                        const threeDsResult = error.body.three_ds_result;\n                        const token = threeDsResult?.payer_auth_request;\n\n                        await this._cardinalClient.getThreeDSecureData(threeDsResult, this._getOrderData());\n\n                        return await this._submitPayment(payment, { token }, hostedForm);\n                    }\n\n                    throw error;\n                }\n            }\n\n            throw error;\n        }\n    }\n\n    private _getOrderData(): CardinalOrderData {\n        const store = this._store.getState();\n        const billingAddress = store.billingAddress.getBillingAddressOrThrow();\n        const shippingAddress = store.shippingAddress.getShippingAddress();\n        const { cart: { currency: { code: currencyCode }, cartAmount: amount } } = store.checkout.getCheckoutOrThrow();\n        const id = store.order.getOrderOrThrow().orderId.toString();\n\n        return { billingAddress, shippingAddress, currencyCode, id, amount };\n    }\n\n    private async _submitPayment(\n        payment: OrderPaymentRequestBody,\n        threeDSecure: CardinalThreeDSecureToken,\n        hostedForm?: HostedForm\n    ): Promise<InternalCheckoutSelectors> {\n        const paymentPayload = merge({}, payment, { paymentData: { threeDSecure } });\n\n        if (!hostedForm) {\n            return await this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n        }\n\n        await hostedForm.submit(paymentPayload);\n\n        return this._store.getState();\n    }\n\n    private _getBin(\n        paymentData: NonNullable<OrderPaymentRequestBody['paymentData']>,\n        getCardInstrument: InstrumentSelector['getCardInstrument'],\n        hostedForm?: HostedForm\n    ): string {\n        const instrument = isVaultedInstrument(paymentData) && getCardInstrument(paymentData.instrumentId);\n        const ccNumber = isCreditCardLike(paymentData) && paymentData.ccNumber;\n        const bin = instrument ?\n            instrument.iin :\n            hostedForm ?\n                hostedForm?.getBin() :\n                ccNumber;\n\n        return bin || '';\n    }\n}\n","import isVaultedInstrument from './is-vaulted-instrument';\nimport { CreditCardInstrument, PaymentInstrument } from './payment';\n\nexport default function isCreditCardLike(instrument: PaymentInstrument): instrument is CreditCardInstrument {\n    const card = instrument as CreditCardInstrument;\n\n    return !isVaultedInstrument(card) &&\n        typeof card.ccName === 'string' &&\n        typeof card.ccNumber === 'string' &&\n        typeof card.ccExpiry === 'object' &&\n        typeof card.ccExpiry.month === 'string' &&\n        typeof card.ccExpiry.year === 'string';\n    }\n","import { includes } from 'lodash';\n\nimport { Address } from '../../../address';\nimport { BillingAddress } from '../../../billing';\nimport { MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { PaymentMethodFailedError } from '../../errors';\nimport { CreditCardInstrument, ThreeDSecureToken, VaultedInstrument } from '../../payment';\nimport { ThreeDsResult } from '../../payment-response-body';\n\nimport { CardinalAccount, CardinalAddress, CardinalConsumer, CardinalEventType, CardinalInitializationType, CardinalPartialOrder, CardinalPaymentBrand, CardinalSignatureValidationErrors, CardinalSignatureVerification, CardinalSDK, CardinalTriggerEvents, CardinalValidatedAction, CardinalValidatedData } from './cardinal';\nimport CardinalScriptLoader from './cardinal-script-loader';\n\nexport type CardinalSupportedPaymentInstrument = CreditCardInstrument | VaultedInstrument;\n\nexport interface CardinalOrderData {\n    billingAddress: BillingAddress;\n    shippingAddress?: Address;\n    currencyCode: string;\n    id: string;\n    amount: number;\n    paymentData?: CreditCardInstrument;\n}\n\nexport default class CardinalClient {\n    private _provider: string = '';\n    private _testMode: boolean = false;\n    private _sdk?: Promise<CardinalSDK>;\n    private _configurationToken: string = '';\n\n    constructor(\n        private _scriptLoader: CardinalScriptLoader\n    ) {}\n\n    load(provider: string, testMode = false): Promise<void> {\n        this._provider = provider;\n        this._testMode = testMode;\n\n        if (!this._sdk) {\n            this._sdk = this._scriptLoader.load(provider, testMode);\n        }\n\n        return this._sdk.then(() => {});\n    }\n\n    configure(clientToken: string): Promise<void> {\n        if (!!this._configurationToken) {\n            if (this._configurationToken === clientToken) {\n                return Promise.resolve();\n            } else {\n                this._sdk = this._scriptLoader.load(`${this._provider}.${Date.now()}`, this._testMode);\n            }\n        }\n\n        return this._getClientSDK()\n            .then(client => new Promise<void>((resolve, reject) => {\n                client.on(CardinalEventType.SetupCompleted, () => {\n                    client.off(CardinalEventType.SetupCompleted);\n                    client.off(CardinalEventType.Validated);\n\n                    this._configurationToken = clientToken;\n\n                    resolve();\n                });\n\n                client.on(CardinalEventType.Validated, (data: CardinalValidatedData) => {\n                    client.off(CardinalEventType.SetupCompleted);\n                    client.off(CardinalEventType.Validated);\n\n                    switch (data.ActionCode) {\n                        case CardinalValidatedAction.Error:\n                            if (includes(CardinalSignatureValidationErrors, data.ErrorNumber)) {\n                                reject(new MissingDataError(MissingDataErrorType.MissingPaymentMethod));\n                            }\n                            reject(new PaymentMethodFailedError(data.ErrorDescription));\n                            break;\n                    }\n                });\n\n                client.setup(CardinalInitializationType.Init, {\n                    jwt: clientToken,\n                });\n            }));\n    }\n\n    runBinProcess(binNumber: string): Promise<void> {\n        return this._getClientSDK()\n            .then(client => client.trigger(CardinalTriggerEvents.BinProcess, binNumber).catch(() => {}))\n            .then(result => {\n                if (!result || !result.Status) {\n                    throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n                }\n            });\n    }\n\n    getThreeDSecureData(threeDSecureData: ThreeDsResult, orderData: CardinalOrderData): Promise<ThreeDSecureToken> {\n        return this._getClientSDK()\n            .then(client => {\n                return new Promise<ThreeDSecureToken>((resolve, reject) => {\n                    client.on(CardinalEventType.Validated, (data: CardinalValidatedData, jwt?: string) => {\n                        client.off(CardinalEventType.Validated);\n                        if (!jwt) {\n                            return reject(new PaymentMethodFailedError(data.ErrorDescription ? data.ErrorDescription : 'An error was encountered while processing the transaction.'));\n                        }\n\n                        if (!data.ActionCode) {\n                            return resolve({ token: jwt });\n                        }\n\n                        switch (data.ActionCode) {\n                            case CardinalValidatedAction.Success:\n                                return resolve({ token: jwt });\n                            case CardinalValidatedAction.NoAction:\n                                if (data.ErrorNumber > 0) {\n                                    return reject(new PaymentMethodFailedError(data.ErrorDescription));\n                                } else if (!data.Payment || !data.Payment.ExtendedData || data.Payment.ExtendedData.SignatureVerification !== CardinalSignatureVerification.Yes) {\n                                    return reject(new PaymentMethodFailedError('Transaction signature could not be validated.'));\n                                }\n\n                                return resolve({ token: jwt });\n                            case CardinalValidatedAction.Failure:\n                                return reject(new PaymentMethodFailedError('User failed authentication or an error was encountered while processing the transaction.'));\n                            case CardinalValidatedAction.Error:\n                                return reject(new PaymentMethodFailedError(data.ErrorDescription));\n                        }\n                    });\n\n                    const continueObject = {\n                        AcsUrl: threeDSecureData.acs_url,\n                        Payload: threeDSecureData.merchant_data,\n                    };\n\n                    const partialOrder = this._mapToPartialOrder(orderData, threeDSecureData.payer_auth_request);\n\n                    client.continue(CardinalPaymentBrand.CCA, continueObject, partialOrder);\n                });\n            });\n    }\n\n    private _mapToPartialOrder(orderData: CardinalOrderData, transactionId: string): CardinalPartialOrder {\n        const consumer: CardinalConsumer = {\n            BillingAddress: this._mapToCardinalAddress(orderData.billingAddress),\n        };\n\n        if (orderData.paymentData) {\n            consumer.Account = this._mapToCardinalAccount(orderData.paymentData);\n        }\n\n        if (orderData.billingAddress.email) {\n            consumer.Email1 = orderData.billingAddress.email;\n        }\n\n        if (orderData.shippingAddress) {\n            consumer.ShippingAddress = this._mapToCardinalAddress(orderData.shippingAddress);\n        }\n\n        return  {\n            Consumer: consumer,\n            OrderDetails: {\n                OrderNumber: orderData.id,\n                Amount: orderData.amount,\n                CurrencyCode: orderData.currencyCode,\n                OrderChannel: 'S',\n                TransactionId: transactionId,\n            },\n        };\n    }\n\n    private _mapToCardinalAccount(paymentData: CreditCardInstrument): CardinalAccount {\n        return {\n            AccountNumber: Number(paymentData.ccNumber),\n            ExpirationMonth: Number(paymentData.ccExpiry.month),\n            ExpirationYear: Number(paymentData.ccExpiry.year),\n            NameOnAccount: paymentData.ccName,\n            CardCode: Number(paymentData.ccCvv),\n        };\n    }\n\n    private _mapToCardinalAddress(address: Address): CardinalAddress {\n        const cardinalAddress: CardinalAddress = {\n            FirstName: address.firstName,\n            LastName: address.lastName,\n            Address1: address.address1,\n            City: address.city,\n            State: address.stateOrProvince,\n            PostalCode: address.postalCode,\n            CountryCode: address.countryCode,\n        };\n\n        if (address.address2) {\n            cardinalAddress.Address2 = address.address2;\n        }\n\n        if (address.phone) {\n            cardinalAddress.Phone1 = address.phone;\n        }\n\n        return cardinalAddress;\n    }\n\n    private _getClientSDK(): Promise<CardinalSDK> {\n        if (!this._sdk) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        return this._sdk;\n    }\n}\n","export enum ChasePayEventType {\n    StartCheckout = 'startCheckout',\n    CompleteCheckout = 'completeCheckout',\n    CancelCheckout = 'cancelCheckout',\n}\n\nexport interface ChasePayEventMap {\n    [ChasePayEventType.StartCheckout](digitalSessionId: string): void;\n    [ChasePayEventType.CompleteCheckout](payload: ChasePaySuccessPayload): void;\n    [ChasePayEventType.CancelCheckout](): void;\n}\n\nexport interface ChasePayHostWindow extends Window {\n    JPMC?: JPMC;\n}\n\nexport interface JPMC {\n    ChasePay: ChasePay;\n}\n\nexport interface ChasePaySuccessPayload {\n    sessionToken: string;\n}\n\nexport interface ChasePayInsertOptions {\n    color?: string;\n    containers?: string[];\n    height?: number;\n    width?: number;\n}\n\nexport interface ChasePayConfigureOptions {\n    language?: string;\n    zindex?: number;\n    sessionWarningTime?: number;\n    sessionTimeoutTime?: number;\n}\n\nexport interface ChasePay {\n    EventType: {\n        START_CHECKOUT: ChasePayEventType.StartCheckout;\n        COMPLETE_CHECKOUT: ChasePayEventType.CompleteCheckout;\n        CANCEL_CHECKOUT: ChasePayEventType.CancelCheckout;\n    };\n    isChasePayUp: boolean;\n    insertButtons(options: ChasePayInsertOptions): void;\n    insertBrandings(options: ChasePayInsertOptions): void;\n    startCheckout(digitalSessionId?: string): void;\n    showLoadingAnimation(): void;\n    configure(options: ChasePayConfigureOptions): void;\n    on<ChasePayEventType extends keyof ChasePayEventMap>(eventType: ChasePayEventType, callback: ChasePayEventMap[ChasePayEventType]): {};\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { CardinalSDK, CardinalWindow } from './cardinal';\n\nconst SDK_TEST_URL = 'https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js';\nconst SDK_PROD_URL = 'https://songbird.cardinalcommerce.com/edge/v1/songbird.js';\n\nexport default class CardinalScriptLoader {\n    constructor(\n        private _scriptLoader: ScriptLoader,\n        private _window: CardinalWindow = window\n    ) {}\n\n    load(provider: string, testMode?: boolean): Promise<CardinalSDK> {\n        const url = testMode ? SDK_TEST_URL : SDK_PROD_URL;\n\n        return this._scriptLoader\n            .loadScript(url + '?v=' + provider)\n            .then(() => {\n                if (!this._window.Cardinal) {\n                    throw new PaymentMethodClientUnavailableError();\n                }\n\n                return this._window.Cardinal;\n            });\n    }\n}\n","import { merge, some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { RequestError } from '../../../common/error/errors';\nimport { HostedForm } from '../../../hosted-form';\nimport { OrderRequestBody } from '../../../order';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport CardinalClient, { CardinalOrderData } from './cardinal-client';\n\nexport default class CardinalThreeDSecureFlow {\n    constructor(\n        private _store: CheckoutStore,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _cardinalClient: CardinalClient\n    ) {}\n\n    async prepare(method: PaymentMethod): Promise<void> {\n        await this._cardinalClient.load(method.id, method.config.testMode);\n        await this._cardinalClient.configure(await this._getClientToken(method));\n    }\n\n    async start(\n        execute: PaymentStrategy['execute'],\n        payload: OrderRequestBody,\n        options?: PaymentRequestOptions,\n        hostedForm?: HostedForm\n    ): Promise<InternalCheckoutSelectors> {\n        const { instruments: { getCardInstrument }, paymentMethods: { getPaymentMethodOrThrow } } = this._store.getState();\n        const { payment: { methodId = '', paymentData = {} } = {} } = payload;\n        const instrument = isVaultedInstrument(paymentData) && getCardInstrument(paymentData.instrumentId);\n        const bin = instrument ? instrument.iin : hostedForm && hostedForm.getBin();\n\n        if (bin) {\n            await this._cardinalClient.runBinProcess(bin);\n        }\n\n        try {\n            return await execute(merge(payload, {\n                payment: {\n                    paymentData: {\n                        threeDSecure: { token: getPaymentMethodOrThrow(methodId).clientToken },\n                    },\n                },\n            }), options);\n        } catch (error) {\n            if (!(error instanceof RequestError) || !some(error.body.errors, { code: 'three_d_secure_required' })) {\n                throw error;\n            }\n\n            const threeDSecure = await this._cardinalClient.getThreeDSecureData(error.body.three_ds_result, this._getOrderData());\n\n            if (!hostedForm) {\n                return await this._store.dispatch(this._paymentActionCreator.submitPayment(merge(payload.payment, {\n                    paymentData: { threeDSecure },\n                })));\n            }\n\n            await hostedForm.submit(merge(payload.payment, {\n                paymentData: { threeDSecure },\n            }));\n\n            return this._store.getState();\n        }\n    }\n\n    private async _getClientToken(method: PaymentMethod): Promise<string> {\n        if (method.clientToken) {\n            return method.clientToken;\n        }\n\n        const { paymentMethods: { getPaymentMethodOrThrow } } = await this._store.dispatch(\n            this._paymentMethodActionCreator.loadPaymentMethod(method.id)\n        );\n\n        return getPaymentMethodOrThrow(method.id).clientToken || '';\n    }\n\n    private _getOrderData(): CardinalOrderData {\n        const state = this._store.getState();\n        const billingAddress = state.billingAddress.getBillingAddressOrThrow();\n        const shippingAddress = state.shippingAddress.getShippingAddress();\n        const checkout = state.checkout.getCheckoutOrThrow();\n        const order = state.order.getOrderOrThrow();\n\n        return {\n            billingAddress,\n            shippingAddress,\n            currencyCode: checkout.cart.currency.code,\n            id: order.orderId.toString(),\n            amount: checkout.cart.cartAmount,\n        };\n    }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { Subject } from 'rxjs';\nimport { take } from 'rxjs/operators';\n\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { bindDecorator as bind } from '../../../common/utility';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentMethodCancelledError } from '../../errors';\nimport Payment from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategyActionCreator from '../../payment-strategy-action-creator';\nimport PaymentStrategy from '../payment-strategy';\nimport { WepayRiskClient } from '../wepay';\n\nimport { ChasePay, ChasePayEventType, ChasePaySuccessPayload } from './chasepay';\nimport ChasePayInitializeOptions from './chasepay-initialize-options';\nimport ChasePayScriptLoader from './chasepay-script-loader';\n\nexport default class ChasePayPaymentStrategy implements PaymentStrategy {\n    private _chasePayClient?: ChasePay;\n    private _methodId!: string;\n    private _walletButton?: HTMLElement;\n    private _walletEvent$: Subject<{ type: ChasePayEventType }>;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _checkoutActionCreator: CheckoutActionCreator,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n        private _requestSender: RequestSender,\n        private _chasePayScriptLoader: ChasePayScriptLoader,\n        private _wepayRiskClient: WepayRiskClient\n    ) {\n        this._walletEvent$ = new Subject();\n    }\n\n    initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        this._methodId = options.methodId;\n\n        if (!options.chasepay) {\n            throw new InvalidArgumentError('Unable to initialize payment because \"options.chasepay\" argument is not provided.');\n        }\n\n        const walletButton = options.chasepay.walletButton && document.getElementById(options.chasepay.walletButton);\n\n        if (walletButton) {\n            this._walletButton = walletButton;\n            this._walletButton.addEventListener('click', this._handleWalletButtonClick);\n        }\n\n        return this._configureWallet(options.chasepay)\n            .then(() => this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        if (this._walletButton) {\n            this._walletButton.removeEventListener('click', this._handleWalletButtonClick);\n        }\n\n        this._walletButton = undefined;\n        this._chasePayClient = undefined;\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        return this._getPayment()\n            .catch(error => {\n                if (error.subtype === MissingDataErrorType.MissingPayment) {\n                    return this._displayWallet()\n                        .then(() => this._getPayment());\n                }\n\n                throw error;\n            })\n            .then(payment =>\n                this._createOrder(payment, payload.useStoreCredit, options)\n            );\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    private _configureWallet(options: ChasePayInitializeOptions): Promise<void> {\n        const state = this._store.getState();\n        const paymentMethod = state.paymentMethods.getPaymentMethod(this._methodId);\n        const storeConfig = state.config.getStoreConfig();\n\n        if (!paymentMethod) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        if (!storeConfig) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n        }\n\n        return this._chasePayScriptLoader.load(paymentMethod.config.testMode)\n            .then(({ ChasePay }) => {\n                this._chasePayClient = ChasePay;\n\n                if (options.logoContainer && document.getElementById(options.logoContainer)) {\n                    this._chasePayClient.insertBrandings({\n                        color: 'white',\n                        containers: [options.logoContainer],\n                    });\n                }\n\n                this._chasePayClient.configure({\n                    language: storeConfig.storeProfile.storeLanguage,\n                });\n\n                this._chasePayClient.on(ChasePayEventType.CancelCheckout, () => {\n                    this._walletEvent$.next({ type: ChasePayEventType.CancelCheckout });\n\n                    if (options.onCancel) {\n                        options.onCancel();\n                    }\n                });\n\n                this._chasePayClient.on(ChasePayEventType.CompleteCheckout, (payload: ChasePaySuccessPayload) => {\n                    this._setSessionToken(payload.sessionToken)\n                        .then(() => {\n                            this._walletEvent$.next({ type: ChasePayEventType.CompleteCheckout });\n\n                            if (options.onPaymentSelect) {\n                                options.onPaymentSelect();\n                            }\n                        });\n                });\n            });\n    }\n\n    private _displayWallet(): Promise<InternalCheckoutSelectors> {\n        return this._store.dispatch(this._paymentStrategyActionCreator.widgetInteraction(() => {\n            this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(this._methodId))\n                .then(state => {\n                    const paymentMethod = state.paymentMethods.getPaymentMethod(this._methodId);\n\n                    if (!this._chasePayClient) {\n                        throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n                    }\n\n                    if (!paymentMethod) {\n                        throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n                    }\n\n                    this._chasePayClient.showLoadingAnimation();\n                    this._chasePayClient.startCheckout(paymentMethod.initializationData.digitalSessionId);\n                });\n\n            // Wait for payment selection\n            return new Promise((resolve, reject) => {\n                this._walletEvent$\n                    .pipe(take(1))\n                    .subscribe((event: { type: ChasePayEventType }) => {\n                        if (event.type === ChasePayEventType.CancelCheckout) {\n                            reject(new PaymentMethodCancelledError());\n                        } else if (event.type === ChasePayEventType.CompleteCheckout) {\n                            resolve();\n                        }\n                    });\n            });\n        }, { methodId: this._methodId }), { queueId: 'widgetInteraction' });\n    }\n\n    private _setSessionToken(sessionToken: string): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n        const paymentMethod = state.paymentMethods.getPaymentMethod(this._methodId);\n        const merchantRequestId = paymentMethod && paymentMethod.initializationData.merchantRequestId;\n\n        return this._requestSender.post('checkout.php', {\n            headers: {\n                Accept: 'text/html',\n                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n            },\n            body: {\n                action: 'set_external_checkout',\n                provider: this._methodId,\n                sessionToken,\n                merchantRequestId,\n            },\n        })\n            // Re-hydrate checkout data\n            .then(() => Promise.all([\n                this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),\n                this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(this._methodId)),\n            ]))\n            .then(() => this._store.getState());\n    }\n\n    private _getPayment(): Promise<Payment> {\n        return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(this._methodId))\n            .then(() => {\n                if (this._methodId === 'wepay') {\n                    return this._wepayRiskClient.initialize()\n                        .then(client => client.getRiskToken());\n                }\n\n                return '';\n            })\n            .then(riskToken => {\n                const state = this._store.getState();\n                const paymentMethod = state.paymentMethods.getPaymentMethod(this._methodId);\n\n                if (!paymentMethod) {\n                    throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n                }\n\n                if (!paymentMethod.initializationData.paymentCryptogram) {\n                    throw new MissingDataError(MissingDataErrorType.MissingPayment);\n                }\n\n                const paymentData = {\n                    method: this._methodId,\n                    cryptogramId: paymentMethod.initializationData.paymentCryptogram,\n                    eci: paymentMethod.initializationData.eci,\n                    transactionId: btoa(paymentMethod.initializationData.reqTokenId),\n                    ccExpiry: {\n                        month: paymentMethod.initializationData.expDate.toString().substr(0, 2),\n                        year: paymentMethod.initializationData.expDate.toString().substr(2, 2),\n                    },\n                    ccNumber: paymentMethod.initializationData.accountNum,\n                    accountMask: paymentMethod.initializationData.accountMask,\n                    extraData: riskToken ? { riskToken } : undefined,\n                };\n\n                return {\n                    methodId: this._methodId,\n                    paymentData,\n                };\n            });\n    }\n\n    private _createOrder(payment: Payment, useStoreCredit?: boolean, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        return this._store.dispatch(this._orderActionCreator.submitOrder({ useStoreCredit }, options))\n            .then(() => this._store.dispatch(this._paymentActionCreator.submitPayment(payment)));\n    }\n\n    @bind\n    private _handleWalletButtonClick(event: Event): void {\n        event.preventDefault();\n\n        this._displayWallet();\n    }\n}\n","export default interface PaymentResponseBody {\n    status: string;\n    id: string;\n    avs_result: AvsResult | {};\n    cvv_result: CvvResult | {};\n    three_ds_result: ThreeDsResult | {};\n    fraud_review: boolean;\n    transaction_type: string;\n    additional_action_required?: AdditionalActionRequired;\n    errors?: Array<{\n        code: string;\n        message: string;\n    }>;\n}\n\nexport interface AvsResult {\n    code: string;\n    message: string;\n    street_match: string;\n    postal_match: string;\n}\n\nexport interface CvvResult {\n    code: string;\n    message: string;\n}\n\nexport interface ThreeDsResult {\n    acs_url: string;\n    payer_auth_request: string;\n    merchant_data: string;\n    callback_url: string;\n}\n\nexport interface AdditionalActionRequired {\n    type: AdditionalActionType;\n    data: AdditionalRedirectData;\n}\n\nexport interface AdditionalRedirectData {\n    redirect_url: string;\n}\n\nexport enum AdditionalActionType {\n    OffsiteRedirect = 'offsite_redirect',\n}\n","import { InternalCheckoutSelectors } from '../../../checkout';\nimport { NotInitializedError, NotInitializedErrorType, RequestError } from '../../../common/error/errors';\nimport { OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport { AdditionalActionRequired, AdditionalActionType } from '../../payment-response-body';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class CheckoutcomCustomPaymentStrategy extends CreditCardPaymentStrategy {\n\n    finalize(options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n        const order = state.order.getOrder();\n\n        if (order && state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE) {\n            return this._store.dispatch(this._orderActionCreator.finalizeOrder(order.orderId, options));\n        }\n\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    protected async _executeWithHostedForm(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors>  {\n        const { payment, ...order } = payload;\n        const form = this._hostedForm;\n\n        if (!form) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        if (!payment || !payment.methodId) {\n            throw new PaymentArgumentInvalidError(['payment.methodId']);\n        }\n\n        try {\n            await form.validate();\n            await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n            await form.submit(payment);\n        } catch (error) {\n            return this._processResponse(error);\n        }\n\n        return await this._store.dispatch(this._orderActionCreator.loadCurrentOrder());\n    }\n\n    protected _processResponse(error: RequestError): Promise<InternalCheckoutSelectors> {\n        if (!(error instanceof RequestError)) {\n            return Promise.reject(error);\n        }\n\n        const additionalActionRequired: AdditionalActionRequired = error.body.additional_action_required;\n\n        // TODO validate all possible responses and perform respective additional actions\n        if (additionalActionRequired && additionalActionRequired.type === AdditionalActionType.OffsiteRedirect) {\n            return this._performRedirect(additionalActionRequired);\n        }\n\n        return Promise.reject(error);\n    }\n\n    private _performRedirect(additionalActionRequired: AdditionalActionRequired): Promise<InternalCheckoutSelectors> {\n        return new Promise(() => {\n            window.location.replace(additionalActionRequired.data.redirect_url);\n        });\n    }\n}\n","export interface DigitalRiverWindow extends Window {\n    /**\n     * Object to create an instance of the DigitalRiver object. This is called a Digital River publishable API key\n     * This function accepts an optional options object using the following format DigitalRiver(publishableApiKey{, options})\n     * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/digitalriver.js/reference/digital-river-publishable-api-key\n     */\n    DigitalRiver?: DigitalRiverClass;\n}\n\nexport type DigitalRiverClass = new(apiKey: string, options?: DigitalRiverJSOptions) => DigitalRiverJS;\n\nexport default interface DigitalRiverJS {\n    createDropin(configuration: DigitalRiverDropInConfiguration): DigitalRiverDropIn;\n    authenticateSource(data: DigitalRiverAuthenticateSourceRequest): Promise<DigitalRiverAuthenticateSourceResponse>;\n}\n\ninterface DigitalRiverAuthenticateSourceRequest {\n    sessionId: string;\n    sourceId: string;\n    sourceClientSecret: string;\n}\n\nexport interface DigitalRiverAdditionalProviderData {\n    source_id: string;\n    source_client_secret: string;\n}\n\nexport interface DigitalRiverAuthenticateSourceResponse {\n    status: AuthenticationSourceStatus;\n}\n\nexport enum AuthenticationSourceStatus {\n    complete = 'complete',\n    authentication_not_required = 'authentication_not_required',\n    failed = 'failed',\n}\n\nexport interface DigitalRiverJSOptions {\n    /**\n     * The locale used to localize the various display and error strings within DigitalRiver.js\n     * Currently supported locales:\n     * ar-EG, cs-CZ, da-DK, de-AT, de-CH, de-DE, el-GR, en-AU, en-BE, en-CA, en-CH, en-DK, en-FI, en-GB, en-IE, en-IN,\n     * en-MY, en-NL, en-NO, en-NZ, en-PR, en-SE, en-SG, en-US, en-ZA, es-AR, es-CL, es-CO, es-EC, es-ES, es-MX, es-PE,\n     * es-VE, et-EE, fi-FI, fr-BE, fr-CA, fr-CH, fr-FR, hu-HU, it-CH, it-IT, iw-IL, ja-JP, ko-KR, lt-LT, lv-LV, nl-BE,\n     * nl-NL, no-NO, pl-PL, pt-BR, pt-PT, ro-RO, ru-RU, sk-SK, sl-SI, sr-YU, sv-SE, th-TH, tr-TR, zh-CN, zh-HK, zh-TW\n     * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/digitalriver.js/reference/digital-river-publishable-api-key\n     */\n    locale?: string;\n}\n\n/**\n * Create a Configuration object for Drop-in\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#step-5-configure-hydrate\n */\nexport interface DigitalRiverDropInConfiguration {\n    /**\n     * The  payment session identifier returned by Digital River.\n     */\n    sessionId: string;\n\n    /**\n     * you can specify options to trigger different features or functionality\n     */\n    options?: OptionsResponse;\n    billingAddress: {\n        firstName: string;\n        lastName: string;\n        email: string;\n        phoneNumber: string;\n        address: {\n            line1: string;\n            line2?: string;\n            city?: string;\n            state?: string;\n            postalCode: string;\n            country: string;\n        };\n    };\n\n    /**\n     * Additional configuration details for configuration structure (classes, styles etc..)\n     */\n    paymentMethodConfiguration?: BaseElementOptions;\n\n    /**\n     * The function called when the shopper has authorized payment and a payment source has been successfully created.\n     */\n    onSuccess?(data: OnSuccessResponse): void;\n\n    /**\n     * The function called when the shopper cancels the payment process before authorizing payment.\n     */\n    onCancel?(error: OnCancelOrErrorResponse): void;\n\n    /**\n     * The function called when an error has occurred.\n     */\n    onError?(error: OnCancelOrErrorResponse): void;\n\n    /**\n     * The function called when Drop-in is ready for user interaction.\n     */\n    onReady?(data: OnReadyResponse): void;\n}\n\nexport interface OnCancelOrErrorResponse {\n    /**\n     * If an error occurs, Drop-in emits an event that identifies the payment method associated with the error.\n     * Instruct your customer to provide a new method of payment.\n     * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#onerror\n     * Or When your customer chooses to pay with a specific payment method and decides to cancel during the redirect phase,\n     * Drop-in emits an event that identifies the cancelled payment method.\n     * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#oncancel\n     */\n    errors: ErrorData[];\n}\n\nexport interface ErrorData {\n    code: string;\n    message: string;\n}\n\nexport interface OnReadyResponse {\n    /**\n     * When ready, Drop-in will emit an event that contains a \"paymentMethodTypes\" array of the available payment methods.\n     * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#onready\n     */\n    paymentMethodTypes: string[];\n}\n\n/**\n * When creating your Drop-in instance, you can specify options to trigger different features or functionality.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#drop-in-options\n */\nexport interface OptionsResponse {\n    /**\n     * Use this option if you are using Drop-in within a standard checkout flow. Example Value: \"checkout\"\n     */\n    flow?: string;\n\n    /**\n     * When enabled, presents the customer with an option to save their payment details for future use within Drop-in.\n     * Enabling this feature will show the appropriate check boxes and localized disclosure statements and facilitate\n     * any necessary Strong Customer Authentication.\n     * If disabled, Drop-in will not present the customer with an option to save their payment details.\n     */\n    showSavePaymentAgreement?: boolean;\n\n    /**\n     * Will show a localized compliance link section as part of Drop-in. This is an important piece for accessing the Digital River business model.\n     */\n    showComplianceSection?: boolean;\n\n    /**\n     * Use this option to customize the text of the Drop-in button.\n     */\n    button?: ButtonResponse;\n\n    /**\n     * Use this option to specify the future use of a source.\n     */\n    usage?: string;\n\n    /**\n     * Use this option to show the required terms of sale disclosure. These localized terms automatically update if recurring products are purchased.\n     */\n    showTermsOfSaleDisclosure?: boolean;\n\n    /**\n     * Additional configuration details for drop-in.\n     */\n    paymentMethodConfiguration?: BaseElementOptions;\n}\n\nexport interface ButtonResponse {\n    /**\n     * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#customizing-the-text-of-the-drop-in-button\n     * The text of the Drop-in button is customizable. You can either display pre-configured text or you can specify a unique text\n     * Examples type: \"payNow\" || type: \"buyNow\" || type: \"completeOrder\" || type: \"submitOrder\"\n     */\n    type: string;\n}\n\nexport interface OnSuccessResponse {\n    /**\n     * Event that gets triggered after the customer's payment has provided with the necessary details for payment\n     * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#onsuccess\n     */\n    source: {\n        id: string;\n        reusable: boolean;\n        browserInfo?: {\n            browserIp?: string;\n        };\n    };\n\n    /**\n     * Indicates whether the source has been enabled for future use.\n     * Important: If this value is true, it does not mean the customer can use this source multiple times.\n     * This flag identifies whether the necessary downstream actions have been triggered to prepare the source for storage.\n     * You must attach the source to your customer for it to be truly reusable.\n     */\n    readyForStorage: boolean;\n}\n\nexport interface DigitalRiverDropIn {\n    /**\n     * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#step-7-place-drop-in-on-your-checkout-or-customer-page\n     * example \"drop-in\"\n     */\n    mount(dropInId: string): void;\n}\n\ninterface BaseElementOptions {\n    /**\n     * Set custom class names on the container DOM element when the Digital River element is in a particular state.\n     */\n    classes?: DigitalRiverElementClasses;\n\n    /**\n     * Remove specific payment methods when rendering drop-in.\n     */\n    disabledPaymentMethods?: string[];\n}\n\n/**\n * Custom classes\n * You can specify custom classes as part of a Class object included within the Options object when you create or\n * update an element. If you do not provide custom classes, the system uses the default options.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/digitalriver.js/reference/elements#custom-classes\n */\nexport interface DigitalRiverElementClasses {\n    /**\n     * The Element is in its base state. The user either has not entered anything into the input field or is currently typing.\n     */\n    base?: string;\n\n    /**\n     * The Element is in its complete state. The user has input value, and it meets the basic validation requirements of that field.\n     */\n    complete?: string;\n\n    /**\n     * The Element is empty. The Element once had value but is now empty.\n     */\n    empty?: string;\n\n    /**\n     * The Element has focus.\n     */\n    focus?: string;\n\n    /**\n     * The Element has value, but it does not meet the basic validation requirements of the field.\n     */\n    invalid?: string;\n\n    /**\n     * The element has a value that has been automatically filled by the browser.\n     */\n    webkitAutofill?: string;\n}\n\nexport interface DigitalRiverInitializeToken {\n    sessionId: string;\n    checkoutId: string;\n}\n","import { InternalCheckoutSelectors } from '../../../../checkout';\nimport { OrderRequestBody } from '../../../../order';\nimport { PaymentArgumentInvalidError } from '../../../errors';\nimport { PaymentInstrument, WithDocumentInstrument } from '../../../payment';\nimport { PaymentRequestOptions } from '../../../payment-request-options';\nimport CheckoutcomCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst DOCUMENT_SUPPORTED_APMS = ['boleto', 'oxxo', 'qpay', 'ideal'];\nexport default class CheckoutcomAPMPaymentStrategy extends CheckoutcomCustomPaymentStrategy {\n\n    protected async _executeWithoutHostedForm(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = payload;\n        const paymentData = payment?.paymentData;\n\n        if (!payment || !paymentData) {\n            throw new PaymentArgumentInvalidError(['payment.paymentData']);\n        }\n\n        await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n        try {\n            return await this._store.dispatch(this._paymentActionCreator.submitPayment({\n                ...payment,\n                paymentData: {\n                    ...paymentData,\n                    formattedPayload: this._createFormattedPayload(payment.methodId, paymentData),\n                },\n            }));\n        } catch (error) {\n            return this._processResponse(error);\n        }\n    }\n\n    private _createFormattedPayload(methodId: string, paymentData: PaymentInstrument): WithDocumentInstrument {\n        const formattedPayload: WithDocumentInstrument = { ccDocument: '' };\n        const ccDocument = 'ccDocument' in paymentData\n            ? paymentData.ccDocument\n            : '';\n\n        if (DOCUMENT_SUPPORTED_APMS.indexOf(methodId) !== -1 && ccDocument) {\n            formattedPayload.ccDocument = ccDocument;\n        }\n\n        return formattedPayload;\n    }\n}\n","import { InternalCheckoutSelectors } from '../../../../checkout';\nimport { OrderRequestBody } from '../../../../order';\nimport { PaymentArgumentInvalidError } from '../../../errors';\nimport { PaymentInstrument, WithCheckoutcomSEPAInstrument } from '../../../payment';\nimport { PaymentRequestOptions } from '../../../payment-request-options';\nimport CheckoutcomCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst CHECKOUTCOM_SEPA_PAYMENT_METHOD = 'sepa';\nexport default class CheckoutcomSEPAPaymentStrategy extends CheckoutcomCustomPaymentStrategy {\n\n    protected async _executeWithoutHostedForm(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = payload;\n        const paymentData = payment?.paymentData;\n\n        if (!payment || !paymentData) {\n            throw new PaymentArgumentInvalidError(['payment.paymentData']);\n        }\n\n        await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n        try {\n            return await this._store.dispatch(this._paymentActionCreator.submitPayment({\n                ...payment,\n                paymentData: {\n                    ...paymentData,\n                    formattedPayload: this._createFormattedPayload(payment.methodId, paymentData),\n                },\n            }));\n        } catch (error) {\n            return this._processResponse(error);\n        }\n    }\n\n    private _createFormattedPayload(methodId: string, paymentData: PaymentInstrument): WithCheckoutcomSEPAInstrument {\n        const formattedPayload: WithCheckoutcomSEPAInstrument = { iban: '', bic: '' };\n        const { iban, bic } = 'iban' in paymentData ? paymentData : formattedPayload;\n\n        if (methodId === CHECKOUTCOM_SEPA_PAYMENT_METHOD && document) {\n            formattedPayload.iban = iban;\n            formattedPayload.bic = bic;\n        }\n\n        return formattedPayload;\n    }\n}\n","import { InternalCheckoutSelectors } from '../../../../checkout';\nimport { OrderRequestBody } from '../../../../order';\nimport { PaymentArgumentInvalidError } from '../../../errors';\nimport { PaymentInstrument, WithCheckoutcomiDealInstrument } from '../../../payment';\nimport { PaymentRequestOptions } from '../../../payment-request-options';\nimport CheckoutcomCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst CHECKOUTCOM_IDEAL_PAYMENT_METHOD = 'ideal';\nexport default class CheckoutcomiDealPaymentStrategy extends CheckoutcomCustomPaymentStrategy {\n\n    protected async _executeWithoutHostedForm(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = payload;\n        const paymentData = payment?.paymentData;\n\n        if (!payment || !paymentData) {\n            throw new PaymentArgumentInvalidError(['payment.paymentData']);\n        }\n\n        await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n        try {\n            return await this._store.dispatch(this._paymentActionCreator.submitPayment({\n                ...payment,\n                paymentData: {\n                    ...paymentData,\n                    formattedPayload: this._createFormattedPayload(payment.methodId, paymentData),\n                },\n            }));\n        } catch (error) {\n            return this._processResponse(error);\n        }\n    }\n\n    private _createFormattedPayload(methodId: string, paymentData: PaymentInstrument): WithCheckoutcomiDealInstrument | undefined {\n        if (CHECKOUTCOM_IDEAL_PAYMENT_METHOD === methodId && 'bic' in paymentData) {\n            return { bic: paymentData.bic };\n        }\n\n        return;\n    }\n}\n","import { InternalCheckoutSelectors } from '../../../../checkout';\nimport { OrderRequestBody } from '../../../../order';\nimport { PaymentArgumentInvalidError } from '../../../errors';\nimport { PaymentInstrument, WithCheckoutcomFawryInstrument } from '../../../payment';\nimport { PaymentRequestOptions } from '../../../payment-request-options';\nimport CheckoutcomCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst CHECKOUTCOM_FAWRY_PAYMENT_METHOD = 'fawry';\nexport default class CheckoutcomFawryPaymentStrategy extends CheckoutcomCustomPaymentStrategy {\n\n    protected async _executeWithoutHostedForm(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = payload;\n        const paymentData = payment && payment.paymentData;\n\n        if (!payment || !paymentData) {\n            throw new PaymentArgumentInvalidError(['payment.paymentData']);\n        }\n\n        await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n        try {\n            return await this._store.dispatch(this._paymentActionCreator.submitPayment({\n                ...payment,\n                paymentData: {\n                    ...paymentData,\n                    formattedPayload: this._createFormattedPayload(payment.methodId, paymentData),\n                },\n            }));\n        } catch (error) {\n            return this._processResponse(error);\n        }\n    }\n\n    private _createFormattedPayload(methodId: string, paymentData: PaymentInstrument): WithCheckoutcomFawryInstrument | undefined {\n        if (CHECKOUTCOM_FAWRY_PAYMENT_METHOD === methodId && 'customerMobile' in paymentData && 'customerEmail' in paymentData) {\n            return { customerMobile: paymentData.customerMobile, customerEmail: paymentData.customerEmail };\n        }\n\n        return;\n    }\n}\n","import { CheckoutStore, CheckoutValidator, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport ClearpayScriptLoader from './clearpay-script-loader';\nimport ClearpaySdk from './clearpay-sdk';\n\nexport default class ClearpayPaymentStrategy implements PaymentStrategy {\n    private _clearpaySdk?: ClearpaySdk;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _checkoutValidator: CheckoutValidator,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _storeCreditActionCreator: StoreCreditActionCreator,\n        private _clearpayScriptLoader: ClearpayScriptLoader\n    ) {}\n\n    async initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { paymentMethods: { getPaymentMethodOrThrow } } = this._store.getState();\n        const paymentMethod = getPaymentMethodOrThrow(options.methodId, options.gatewayId);\n\n        this._clearpaySdk = await this._clearpayScriptLoader.load(paymentMethod);\n\n        return this._store.getState();\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        this._clearpaySdk = undefined;\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        if (!payload.payment) {\n            throw new PaymentArgumentInvalidError(['payment.gatewayId', 'payment.methodId']);\n        }\n        const { gatewayId, methodId } = payload.payment;\n\n        if (!gatewayId || !methodId) {\n            throw new PaymentArgumentInvalidError(['payment.gatewayId', 'payment.methodId']);\n        }\n\n        const { isStoreCreditApplied: useStoreCredit } = this._store.getState().checkout.getCheckoutOrThrow();\n        let state = this._store.getState();\n\n        if (useStoreCredit !== undefined) {\n            state = await this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(useStoreCredit));\n        }\n\n        await this._checkoutValidator.validate(state.checkout.getCheckout(), options);\n\n        const { countryCode } = this._store.getState().billingAddress.getBillingAddressOrThrow();\n        if (!this._isCountrySupported(countryCode)) {\n            throw new InvalidArgumentError('Unable to proceed because billing country is not supported.');\n        }\n\n        state = await this._store.dispatch(\n            this._paymentMethodActionCreator.loadPaymentMethod(`${gatewayId}?method=${methodId}`)\n        );\n\n        await this._redirectToClearpay(countryCode, state.paymentMethods.getPaymentMethod(methodId));\n\n        // Clearpay will handle the rest of the flow so return a promise that doesn't really resolve\n        return new Promise(() => {});\n    }\n\n    async finalize(options: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n        const payment = state.payment.getPaymentId();\n        const config = state.config.getContextConfig();\n\n        if (!payment) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n        }\n\n        if (!config || !config.payment.token) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n        }\n\n        const paymentPayload = {\n            methodId: payment.providerId,\n            paymentData: { nonce: config.payment.token },\n        };\n\n        await this._store.dispatch(this._orderActionCreator.submitOrder({}, options));\n\n        return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n    }\n\n    private _redirectToClearpay(countryCode: string, paymentMethod?: PaymentMethod): void {\n        if (!this._clearpaySdk || !paymentMethod || !paymentMethod.clientToken) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        this._clearpaySdk.initialize({countryCode});\n        this._clearpaySdk.redirect({ token: paymentMethod.clientToken });\n    }\n\n    private _isCountrySupported( countryCode: string): boolean {\n        return countryCode === 'GB';\n    }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\nimport PaymentMethod from '../../payment-method';\n\nimport ClearpaySdk from './clearpay-sdk';\nimport ClearpayWindow from './clearpay-window';\n\nconst SCRIPTS_DEFAULT = {\n    PROD: '//portal.clearpay.co.uk/afterpay-async.js',\n    SANDBOX: '//portal.sandbox.clearpay.co.uk/afterpay-async.js',\n};\n\nexport default class ClearpayScriptLoader {\n    constructor(\n        private _scriptLoader: ScriptLoader,\n        public _window: ClearpayWindow = window\n    ) { }\n\n    async load(method: PaymentMethod): Promise<ClearpaySdk> {\n        await this._scriptLoader.loadScript(this._getScriptUrl(method.config.testMode));\n\n        if (!this._window.AfterPay) {\n            throw new PaymentMethodClientUnavailableError();\n        }\n\n        return this._window.AfterPay;\n    }\n\n    private _getScriptUrl(testMode?: boolean): string {\n        return testMode ? SCRIPTS_DEFAULT.SANDBOX : SCRIPTS_DEFAULT.PROD;\n    }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { RequestError } from '../../../common/error/errors';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class ConvergePaymentStrategy extends CreditCardPaymentStrategy {\n    constructor(\n        store: CheckoutStore,\n        orderActionCreator: OrderActionCreator,\n        paymentActionCreator: PaymentActionCreator,\n        hostedFormFactory: HostedFormFactory,\n        private _formPoster: FormPoster\n    ) {\n        super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n    }\n\n    execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        return super.execute(payload, options)\n            .catch(error => {\n                if (!(error instanceof RequestError) || !some(error.body.errors, { code: 'three_d_secure_required' })) {\n                    return Promise.reject(error);\n                }\n\n                return new Promise(() => {\n                    this._formPoster.postForm(error.body.three_ds_result.acs_url, {\n                        PaReq: error.body.three_ds_result.payer_auth_request,\n                        TermUrl: error.body.three_ds_result.callback_url,\n                        MD: error.body.three_ds_result.merchant_data,\n                    });\n                });\n            });\n    }\n\n    finalize(options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n        const order = state.order.getOrder();\n\n        if (order && state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE) {\n            return this._store.dispatch(this._orderActionCreator.finalizeOrder(order.orderId, options));\n        }\n\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { NotInitializedError, NotInitializedErrorType, RequestError } from '../../../common/error/errors';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class CreditCardRedirectPaymentStrategy extends CreditCardPaymentStrategy {\n    constructor(\n        protected _store: CheckoutStore,\n        protected _orderActionCreator: OrderActionCreator,\n        protected _paymentActionCreator: PaymentActionCreator,\n        protected _hostedFormFactory: HostedFormFactory,\n        protected _formPoster: FormPoster\n    ) {\n        super(\n            _store,\n            _orderActionCreator,\n            _paymentActionCreator,\n            _hostedFormFactory\n        );\n    }\n\n    finalize(options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n        const order = state.order.getOrder();\n\n        if (order && state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE) {\n            return this._store.dispatch(this._orderActionCreator.finalizeOrder(order.orderId, options));\n        }\n\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    protected async _executeWithoutHostedForm(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = payload;\n        const paymentData = payment && payment.paymentData;\n\n        if (!payment || !paymentData) {\n            throw new PaymentArgumentInvalidError(['payment.paymentData']);\n        }\n\n        await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n        try {\n            return await this._store.dispatch(this._paymentActionCreator.submitPayment({ ...payment, paymentData }));\n        } catch (error) {\n            if (!(error instanceof RequestError) || !some(error.body.errors, { code: 'three_d_secure_required' })) {\n                return Promise.reject(error);\n            }\n\n            return new Promise(() => this._formPoster.postForm(error.body.three_ds_result.acs_url, {\n                PaReq: error.body.three_ds_result.payer_auth_request || null,\n                TermUrl: error.body.three_ds_result.callback_url || null,\n                MD: error.body.three_ds_result.merchant_data || null,\n            }));\n        }\n    }\n\n    protected async _executeWithHostedForm(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors>  {\n        const { payment, ...order } = payload;\n        const form = this._hostedForm;\n\n        if (!form) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        if (!payment || !payment.methodId) {\n            throw new PaymentArgumentInvalidError(['payment.methodId']);\n        }\n\n        try {\n            await form.validate();\n            await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n            await form.submit(payment);\n        } catch (error) {\n            if (!(error instanceof RequestError) || !some(error.body.errors, { code: 'three_d_secure_required' })) {\n                return Promise.reject(error);\n            }\n\n            return new Promise(() => this._formPoster.postForm(error.body.three_ds_result.acs_url, {\n                PaReq: error.body.three_ds_result.payer_auth_request || null,\n                TermUrl: error.body.three_ds_result.callback_url || null,\n                MD: error.body.three_ds_result.merchant_data || null,\n            }));\n        }\n\n        return await this._store.dispatch(this._orderActionCreator.loadCurrentOrder());\n    }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CardinalThreeDSecureFlow } from '../cardinal';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class CyberSourcePaymentStrategy extends CreditCardPaymentStrategy {\n    constructor(\n        store: CheckoutStore,\n        orderActionCreator: OrderActionCreator,\n        paymentActionCreator: PaymentActionCreator,\n        hostedFormFactory: HostedFormFactory,\n        private _threeDSecureFlow: CardinalThreeDSecureFlow\n    ) {\n        super(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            hostedFormFactory\n        );\n    }\n\n    async initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        await super.initialize(options);\n\n        const { paymentMethods: { getPaymentMethodOrThrow } } = this._store.getState();\n        const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n        if (paymentMethod.config.is3dsEnabled) {\n            await this._threeDSecureFlow.prepare(paymentMethod);\n        }\n\n        return this._store.getState();\n    }\n\n    async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment: { methodId = '' } = {} } = payload;\n        const { paymentMethods: { getPaymentMethodOrThrow } } = this._store.getState();\n\n        if (getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n            return this._threeDSecureFlow.start(\n                super.execute.bind(this),\n                payload,\n                options,\n                this._hostedForm\n            );\n        }\n\n        return super.execute(payload, options);\n    }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CardinalThreeDSecureFlowV2 } from '../cardinal';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class CyberSourceV2PaymentStrategy extends CreditCardPaymentStrategy {\n    constructor(\n        store: CheckoutStore,\n        orderActionCreator: OrderActionCreator,\n        paymentActionCreator: PaymentActionCreator,\n        hostedFormFactory: HostedFormFactory,\n        private _threeDSecureFlow: CardinalThreeDSecureFlowV2\n    ) {\n        super(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            hostedFormFactory\n        );\n    }\n\n    async initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        await super.initialize(options);\n\n        const { paymentMethods: { getPaymentMethodOrThrow } } = this._store.getState();\n        const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n        if (paymentMethod.config.is3dsEnabled) {\n            await this._threeDSecureFlow.prepare(paymentMethod);\n        }\n\n        return this._store.getState();\n    }\n\n    async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment: { methodId = '' } = {} } = payload;\n        const { paymentMethods: { getPaymentMethodOrThrow } } = this._store.getState();\n\n        if (getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n            return this._threeDSecureFlow.start(\n                super.execute.bind(this),\n                payload,\n                options,\n                this._hostedForm\n            );\n        }\n\n        return super.execute(payload, options);\n    }\n}\n","import { some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType, RequestError } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport { isVaultedInstrument, HostedInstrument } from '../../index';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport DigitalRiverJS, { AuthenticationSourceStatus, DigitalRiverAdditionalProviderData, DigitalRiverAuthenticateSourceResponse, DigitalRiverDropIn, DigitalRiverInitializeToken, OnCancelOrErrorResponse, OnReadyResponse, OnSuccessResponse } from './digitalriver';\nimport DigitalRiverPaymentInitializeOptions from './digitalriver-payment-initialize-options';\nimport DigitalRiverScriptLoader from './digitalriver-script-loader';\n\nexport default class DigitalRiverPaymentStrategy implements PaymentStrategy {\n    private _digitalRiverJS?: DigitalRiverJS;\n    private _digitalRiverDropComponent?: DigitalRiverDropIn;\n    private _submitFormEvent?: () => void;\n    private _loadSuccessResponse?: OnSuccessResponse;\n    private _digitalRiverCheckoutData?: DigitalRiverInitializeToken;\n    private _unsubscribe?: (() => void);\n    private _digitalRiverInitializeOptions?: DigitalRiverPaymentInitializeOptions;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _storeCreditActionCreator: StoreCreditActionCreator,\n        private _digitalRiverScriptLoader: DigitalRiverScriptLoader\n    ) {}\n\n    async initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        this._digitalRiverInitializeOptions = options.digitalriver;\n        const paymentMethod = this._store.getState().paymentMethods.getPaymentMethodOrThrow(options.methodId);\n        const { publicKey, paymentLanguage: locale } = paymentMethod.initializationData;\n        const { containerId } = this._getDigitalRiverInitializeOptions();\n\n        this._digitalRiverJS = await this._digitalRiverScriptLoader.load(publicKey, locale);\n\n        this._unsubscribe = await this._store.subscribe(\n            async state => {\n                if (state.paymentStrategies.isInitialized(options.methodId)) {\n                    const container = document.getElementById(containerId);\n\n                    if (container) {\n                        container.innerHTML = '';\n\n                        this._digitalRiverJS = await this._digitalRiverScriptLoader.load(publicKey, locale);\n                    }\n\n                    await this._loadWidget(options);\n                }\n            },\n            state => {\n                const checkout = state.checkout.getCheckout();\n\n                return checkout && checkout.outstandingBalance;\n            },\n            state => {\n                const checkout = state.checkout.getCheckout();\n\n                return checkout && checkout.coupons;\n            }\n        );\n\n        return this._loadWidget(options);\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        if (this._unsubscribe) {\n            this._unsubscribe();\n        }\n\n        const { containerId } = this._getDigitalRiverInitializeOptions();\n        const container = document.getElementById(containerId);\n\n        if (container) {\n            container.innerHTML = '';\n        }\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = orderRequest;\n\n        if (!payment || !payment.paymentData) {\n            throw new PaymentArgumentInvalidError(['payment.paymentData']);\n        }\n\n        const { paymentData, methodId } = payment;\n        const { shouldSetAsDefaultInstrument = false } = paymentData as HostedInstrument;\n        const { isStoreCreditApplied: useStoreCredit } = this._store.getState().checkout.getCheckoutOrThrow();\n\n        if (useStoreCredit !== undefined) {\n            await this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(useStoreCredit));\n        }\n\n        await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n        if (!this._digitalRiverCheckoutData) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        if (isVaultedInstrument(paymentData)) {\n            try {\n                return await this._submitVaultedInstrument(methodId, paymentData.instrumentId, this._digitalRiverCheckoutData.checkoutId, shouldSetAsDefaultInstrument, false);\n            } catch (error) {\n                if (!this._isAuthenticateSourceAction(error)) {\n                    throw error;\n                }\n\n                const confirm = await this._authenticateSource(error.body.provider_data);\n\n                return await this._submitVaultedInstrument(methodId, paymentData.instrumentId, this._digitalRiverCheckoutData.checkoutId, shouldSetAsDefaultInstrument, confirm);\n            }\n        } else {\n            if (!this._loadSuccessResponse) {\n                throw new PaymentArgumentInvalidError(['this._loadSuccessResponse']);\n            }\n\n            const paymentPayload = {\n                methodId: payment.methodId,\n                paymentData: {\n                    formattedPayload: {\n                        credit_card_token: {\n                            token: JSON.stringify({\n                                checkoutId: this._digitalRiverCheckoutData.checkoutId,\n                                source: this._loadSuccessResponse,\n                                sessionId: this._digitalRiverCheckoutData.sessionId,\n                            }),\n                        },\n                        vault_payment_instrument: this._loadSuccessResponse.readyForStorage,\n                        set_as_default_stored_instrument: false,\n                    },\n                },\n            };\n\n            return await this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n        }\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    private _getDigitalRiverJs(): DigitalRiverJS {\n        if (!this._digitalRiverJS) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        return this._digitalRiverJS;\n    }\n\n    private _getErrorMessage(error: OnCancelOrErrorResponse): string {\n        const { errors } = error;\n\n        return errors.map(e => 'code: ' + e.code + ' message: ' + e.message).join('\\n');\n    }\n\n    private _onSuccessResponse(data?: OnSuccessResponse): Promise<void> {\n        const error = new InvalidArgumentError('Unable to initialize payment because success argument is not provided.');\n\n        return new Promise((resolve, reject) => {\n            if (data && this._submitFormEvent) {\n                const { browserInfo } = data.source;\n                this._loadSuccessResponse = browserInfo ? {\n                    source: {\n                        id: data.source.id,\n                        reusable: data.source.reusable,\n                        ...browserInfo,\n                    },\n                    readyForStorage: data.readyForStorage,\n                } : {\n                    source: {\n                        id: data.source.id,\n                        reusable: data.source.reusable,\n                    },\n                    readyForStorage: data.readyForStorage,\n                };\n                resolve();\n                this._submitFormEvent();\n            } else {\n                reject(error);\n                this._getDigitalRiverInitializeOptions().onError?.(error);\n            }\n        });\n    }\n\n    private _onReadyResponse(data?: OnReadyResponse): void {\n        if (data) {\n            this._getDigitalRiverInitializeOptions().onRenderButton?.();\n        }\n    }\n\n    private _getDigitalRiverInitializeOptions(): DigitalRiverPaymentInitializeOptions {\n        if (!this._digitalRiverInitializeOptions) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        return this._digitalRiverInitializeOptions;\n    }\n\n    private async _loadWidget(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const state = await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(options.methodId));\n        const billing = state.billingAddress.getBillingAddressOrThrow();\n        const customer = state.customer.getCustomerOrThrow();\n        const { paymentMethodConfiguration } = this._getDigitalRiverInitializeOptions().configuration;\n        const { containerId, configuration } = this._getDigitalRiverInitializeOptions();\n        const { clientToken } = state.paymentMethods.getPaymentMethodOrThrow(options.methodId);\n\n        if (!clientToken) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        this._digitalRiverCheckoutData = JSON.parse(clientToken);\n\n        if (!this._digitalRiverCheckoutData) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        this._submitFormEvent = this._getDigitalRiverInitializeOptions().onSubmitForm;\n        const digitalRiverConfiguration = {\n            sessionId: this._digitalRiverCheckoutData.sessionId,\n            options: { ...configuration, showSavePaymentAgreement: Boolean(customer.email) },\n            billingAddress: {\n                firstName: billing.firstName,\n                lastName: billing.lastName,\n                email: billing.email || customer.email,\n                phoneNumber: billing.phone,\n                address: {\n                    line1: billing.address1,\n                    line2: billing.address2,\n                    city: billing.city,\n                    state: billing.stateOrProvinceCode,\n                    postalCode: billing.postalCode,\n                    country: billing.countryCode,\n                },\n            },\n            paymentMethodConfiguration,\n            onSuccess: (data?: OnSuccessResponse) => {\n                this._onSuccessResponse(data);\n            },\n            onReady: (data?: OnReadyResponse) => {\n                this._onReadyResponse(data);\n            },\n            onError: (error: OnCancelOrErrorResponse) => {\n                const descriptiveError = new Error(this._getErrorMessage(error));\n                this._getDigitalRiverInitializeOptions().onError?.(descriptiveError);\n            },\n        };\n        this._digitalRiverDropComponent = await this._getDigitalRiverJs().createDropin(digitalRiverConfiguration);\n        this._digitalRiverDropComponent.mount(containerId);\n\n        return state;\n    }\n\n    private _isAuthenticateSourceAction(error: unknown): boolean {\n        return  !(!(error instanceof RequestError) || !some(error.body.errors, { code: 'additional_action_required' }));\n    }\n\n    private async _authenticateSource(additionalAction: DigitalRiverAdditionalProviderData): Promise<boolean> {\n        if (!this._digitalRiverCheckoutData) {\n            throw new InvalidArgumentError('Unable to proceed because payload payment argument is not provided.');\n        }\n\n        const authenticateSourceResponse: DigitalRiverAuthenticateSourceResponse = await this._getDigitalRiverJs().authenticateSource({\n            sessionId: this._digitalRiverCheckoutData.sessionId,\n            sourceId: additionalAction.source_id,\n            sourceClientSecret: additionalAction.source_client_secret,\n        });\n\n        if (authenticateSourceResponse.status === AuthenticationSourceStatus.failed) {\n            throw new Error('Source authentication failed, please try again');\n        }\n\n        return authenticateSourceResponse.status === AuthenticationSourceStatus.complete || authenticateSourceResponse.status === AuthenticationSourceStatus.authentication_not_required;\n    }\n\n    private async _submitVaultedInstrument(methodId: string, instrumentId: string, checkoutId: string, shouldSetAsDefaultInstrument: boolean, confirm: boolean): Promise<InternalCheckoutSelectors> {\n        const paymentPayload = {\n            methodId,\n            paymentData: {\n                formattedPayload: {\n                    bigpay_token: {\n                        token: instrumentId,\n                    },\n                    credit_card_token: {\n                        token: JSON.stringify({\n                            checkoutId,\n                        }),\n                    },\n                    confirm,\n                    set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n                },\n            },\n        };\n\n        return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n    }\n}\n","import { each, some } from 'lodash';\n\nimport { PaymentActionCreator } from '../..';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { getBrowserInfo } from '../../../common/browser-info';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType, RequestError } from '../../../common/error/errors';\nimport { HostedForm, HostedFormFactory, HostedFormOptions } from '../../../hosted-form';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport { HostedInstrument } from '../../payment';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { MollieClient, MollieElement } from './mollie';\nimport MolliePaymentInitializeOptions from './mollie-initialize-options';\nimport MollieScriptLoader from './mollie-script-loader';\n\nexport enum MolliePaymentMethodType {\n    creditcard = 'credit_card',\n}\n\nexport default class MolliePaymentStrategy implements PaymentStrategy {\n    private _initializeOptions?: MolliePaymentInitializeOptions;\n    private _mollieClient?: MollieClient;\n    private _cardHolderElement?: MollieElement;\n    private _cardNumberElement?: MollieElement;\n    private _verificationCodeElement?: MollieElement;\n    private _expiryDateElement?: MollieElement;\n\n    private _hostedForm?: HostedForm;\n\n    constructor(\n        private _hostedFormFactory: HostedFormFactory,\n        private _store: CheckoutStore,\n        private _mollieScriptLoader: MollieScriptLoader,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator\n    ) { }\n\n    async initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { mollie, methodId, gatewayId } = options;\n\n        if (!mollie) {\n            throw new InvalidArgumentError('Unable to initialize payment because \"options.mollie\" argument is not provided.');\n        }\n\n        if (!methodId || !gatewayId) {\n            throw new InvalidArgumentError('Unable to initialize payment because \"methodId\" and/or \"gatewayId\" argument is not provided.');\n        }\n\n        const state = this._store.getState();\n        const storeConfig = state.config.getStoreConfig();\n\n        if (!storeConfig) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n        }\n\n        this._initializeOptions = mollie;\n\n        const paymentMethods = state.paymentMethods;\n        const paymentMethod = paymentMethods.getPaymentMethodOrThrow(methodId, gatewayId);\n        const { config: { merchantId, testMode } } = paymentMethod;\n\n        if (!merchantId) {\n            throw new InvalidArgumentError('Unable to initialize payment because \"merchantId\" argument is not provided.');\n        }\n\n        if (this.isCreditCard(methodId) && mollie.form  && this.shouldShowTSVHostedForm(methodId, gatewayId)) {\n            this._hostedForm = await this._mountCardVerificationfields(mollie.form);\n        } else if (this.isCreditCard(methodId)) {\n            this._mollieClient = await this._loadMollieJs(merchantId, storeConfig.storeProfile.storeLanguage, testMode);\n            this._mountElements();\n        }\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment , ...order} = payload;\n        const paymentData = payment?.paymentData;\n\n        if (!payment || !payment.gatewayId || !paymentData) {\n            throw new PaymentArgumentInvalidError([ 'payment', 'gatewayId', 'paymentData' ]);\n        }\n\n        try {\n            await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n            if (isVaultedInstrument(paymentData)) {\n                return await this.executeWithVaulted(payment);\n            }\n\n            if (this.isCreditCard(payment.methodId)) {\n                return await this.executeWithCC(payment);\n            }\n\n            return await this.executeWithAPM(payment);\n        } catch (error) {\n\n            return this._processAdditionalAction(error);\n        }\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        this._mollieClient = undefined;\n\n        this.removeMollieComponents();\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    protected async executeWithCC(payment: OrderPaymentRequestBody): Promise<InternalCheckoutSelectors> {\n        const paymentData = payment.paymentData;\n        const shouldSaveInstrument = (paymentData as HostedInstrument)?.shouldSaveInstrument;\n        const shouldSetAsDefaultInstrument = (paymentData as HostedInstrument)?.shouldSetAsDefaultInstrument;\n\n        const { token, error } = await this._getMollieClient().createToken();\n\n        if (error) {\n            return Promise.reject(error);\n        }\n\n        return await this._store.dispatch(this._paymentActionCreator.submitPayment({\n            ...payment,\n            paymentData: {\n                formattedPayload: {\n                    credit_card_token: {\n                        token,\n                    },\n                    vault_payment_instrument: shouldSaveInstrument,\n                    set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n                    browser_info: getBrowserInfo(),\n                },\n            },\n        }));\n    }\n\n    protected async executeWithVaulted(payment: OrderPaymentRequestBody): Promise<InternalCheckoutSelectors> {\n        if (this._isHostedPaymentFormEnabled(payment.methodId, payment.gatewayId)) {\n            const form = this._hostedForm;\n\n            if (!form) {\n                throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n            }\n\n            await form.validate();\n            await form.submit(payment);\n\n            return await this._store.dispatch(this._orderActionCreator.loadCurrentOrder());\n        } else {\n            return await this._store.dispatch(this._paymentActionCreator.submitPayment(payment));\n        }\n    }\n\n    protected async executeWithAPM(payment: OrderPaymentRequestBody): Promise<InternalCheckoutSelectors> {\n        const paymentData = payment.paymentData;\n        const issuer = paymentData && 'issuer' in paymentData ? paymentData.issuer : '';\n\n        return await this._store.dispatch(this._paymentActionCreator.submitPayment({\n            ...payment,\n            paymentData: {\n                ...paymentData,\n                formattedPayload: {\n                    issuer,\n                },\n            },\n        }));\n    }\n\n    private isCreditCard(methodId: string): boolean {\n        return (methodId === MolliePaymentMethodType.creditcard);\n    }\n\n    private shouldShowTSVHostedForm(methodId: string, gatewayId: string): boolean {\n        return (this._isHostedPaymentFormEnabled(methodId, gatewayId) && this._isHostedFieldAvailable());\n    }\n\n    private _mountCardVerificationfields(formOptions: HostedFormOptions): Promise<HostedForm> {\n        return new Promise(async (resolve , reject) => {\n            try {\n                const { config } = this._store.getState();\n                const bigpayBaseUrl = config.getStoreConfig()?.paymentSettings.bigpayBaseUrl;\n\n                if (!bigpayBaseUrl) {\n                    throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n                }\n\n                const form = this._hostedFormFactory.create(bigpayBaseUrl, formOptions);\n\n                await form.attach();\n\n                resolve(form);\n            } catch (error) {\n                reject(error);\n            }\n        });\n    }\n\n    private _isHostedPaymentFormEnabled(methodId: string, gatewayId?: string): boolean {\n        const { paymentMethods: { getPaymentMethodOrThrow } } = this._store.getState();\n        const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n        return paymentMethod.config.isHostedFormEnabled === true;\n    }\n\n    private _isHostedFieldAvailable(): boolean {\n        const options = this._getInitializeOptions();\n\n        return !!options.form?.fields;\n    }\n\n    private removeMollieComponents(): void {\n        const mollieComponents = document.querySelectorAll('.mollie-component');\n\n        each(mollieComponents, component => component.remove());\n\n        const controllers = document.querySelectorAll('.mollie-components-controller');\n\n        each(controllers, controller => controller.remove());\n    }\n\n    private _processAdditionalAction(error: any): Promise<InternalCheckoutSelectors> {\n        if (!(error instanceof RequestError) || !some(error.body.errors, {code: 'additional_action_required'})) {\n            return Promise.reject(error);\n        }\n        const { additional_action_required: { data : { redirect_url } } } = error.body;\n\n        return new Promise(() => window.location.replace(redirect_url));\n    }\n\n    private _getInitializeOptions(): MolliePaymentInitializeOptions {\n        if (!this._initializeOptions) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        return this._initializeOptions;\n    }\n\n    private _loadMollieJs(merchantId: string, locale: string, testmode: boolean = false): Promise<MollieClient> {\n        if (this._mollieClient) {\n            return Promise.resolve(this._mollieClient);\n        }\n\n        return this._mollieScriptLoader\n            .load(merchantId, locale, testmode);\n    }\n\n    private _getMollieClient(): MollieClient {\n        if (!this._mollieClient) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        return this._mollieClient;\n    }\n\n    /**\n     * ContainerId is use in Mollie for determined either its showing or not the\n     * container, because when Mollie has Vaulted Instruments it gets hide,\n     * and shows an error because can't mount Provider Components\n     *\n     * We had to add a settimeout because Mollie sets de tab index after mounting\n     * each component, but without a setTimeOut Mollie is not able to find the\n     * components as they are hidden so we need to wait until they are shown\n     */\n    private _mountElements() {\n        const { containerId, cardNumberId, cardCvcId, cardExpiryId, cardHolderId, styles } = this._getInitializeOptions();\n        let container: HTMLElement | null;\n\n        if (containerId) {\n            container = document.getElementById(containerId);\n        }\n\n        setTimeout(() => {\n            if (!containerId || container?.style.display !== 'none') {\n                const mollieClient = this._getMollieClient();\n\n                this._cardHolderElement = mollieClient.createComponent('cardHolder', { styles });\n                this._cardHolderElement.mount(`#${cardHolderId}`);\n\n                this._cardNumberElement = mollieClient.createComponent('cardNumber', { styles });\n                this._cardNumberElement.mount(`#${cardNumberId}`);\n\n                this._verificationCodeElement = mollieClient.createComponent('verificationCode', { styles });\n                this._verificationCodeElement.mount(`#${cardCvcId}`);\n\n                this._expiryDateElement = mollieClient.createComponent('expiryDate', { styles });\n                this._expiryDateElement.mount(`#${cardExpiryId}`);\n            }\n        }, 0);\n    }\n}\n","import { ScriptLoader, StylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport DigitalRiverJS, { DigitalRiverWindow } from './digitalriver';\n\nexport default class DigitalRiverScriptLoader {\n    constructor(\n        private _scriptLoader: ScriptLoader,\n        private _stylesheetLoader: StylesheetLoader,\n        private _window: DigitalRiverWindow = window\n    ) {}\n\n    async load(publicKey: string, locale: string): Promise<DigitalRiverJS> {\n        await Promise.all([\n            this._stylesheetLoader.loadStylesheet(`https://js.digitalriverws.com/v1/css/DigitalRiver.css`),\n            this._scriptLoader.loadScript(`https://js.digitalriverws.com/v1/DigitalRiver.js`),\n        ]);\n\n        if (!this._window.DigitalRiver) {\n            throw new PaymentMethodClientUnavailableError();\n        }\n\n        return Promise.resolve(new this._window.DigitalRiver(publicKey, { locale } ));\n    }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { RequestError } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nexport default class ExternalPaymentStrategy implements PaymentStrategy {\n\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _formPoster: FormPoster\n    ) {}\n\n    async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = payload;\n        const paymentData = payment && payment.paymentData;\n\n        if (!payment || !paymentData) {\n            throw new PaymentArgumentInvalidError(['payment.paymentData']);\n        }\n\n        await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n        try {\n            return await this._store.dispatch(this._paymentActionCreator.submitPayment({...payment, paymentData}));\n        } catch (error) {\n            if (!this._isAdditionalActionRequired(error)) {\n                return Promise.reject(error);\n            }\n\n            return new Promise(() => {\n                this._formPoster.postForm(error.body.additional_action_required.data.redirect_url, { });\n            });\n        }\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    initialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n\n    private _isAdditionalActionRequired(error: RequestError): boolean {\n        const { additional_action_required, status } = error.body;\n\n        return status === 'additional_action_required'\n            && additional_action_required\n            && additional_action_required.type === 'offsite_redirect';\n    }\n}\n","import { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { getBrowserInfo } from '../../../common/browser-info';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategyActionCreator from '../../payment-strategy-action-creator';\nimport { AdyenPaymentMethodType } from '../adyenv2';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { GooglePaymentData, PaymentMethodData } from './googlepay';\nimport GooglePayAdyenV2PaymentProcessor from './googlepay-adyenv2-payment-processor';\nimport GooglePayPaymentInitializeOptions from './googlepay-initialize-options';\nimport GooglePayPaymentProcessor from './googlepay-payment-processor';\n\nexport default class GooglePayPaymentStrategy implements PaymentStrategy {\n    private _googlePayOptions?: GooglePayPaymentInitializeOptions;\n    private _walletButton?: HTMLElement;\n    private _paymentMethod?: PaymentMethod;\n    private _buttonClickEventHandler?: (event: Event ) => Promise<InternalCheckoutSelectors>;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _checkoutActionCreator: CheckoutActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _orderActionCreator: OrderActionCreator,\n        private _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n        private _googlePayAdyenV2PaymentProcessor?: GooglePayAdyenV2PaymentProcessor\n    ) {}\n\n    async initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { methodId } = options;\n\n        const state = await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId));\n        this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n        this._googlePayOptions = this._getGooglePayOptions(options);\n\n        this._buttonClickEventHandler = this._handleButtonClickedEvent(methodId);\n\n        if (this._paymentMethod.initializationData.nonce) {\n            return Promise.resolve(this._store.getState());\n        }\n\n        await this._googlePayPaymentProcessor.initialize(methodId);\n\n        if (!this._googlePayOptions.walletButton) {\n            throw new InvalidArgumentError('walletButton argument is missing');\n        }\n\n        const walletButton = document.getElementById(this._googlePayOptions.walletButton);\n\n        if (!walletButton) {\n            throw new InvalidArgumentError('Unable to create wallet, walletButton ID could not be found');\n        }\n\n        this._walletButton = walletButton;\n        this._walletButton.addEventListener('click', this._buttonClickEventHandler);\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        if (this._walletButton && this._buttonClickEventHandler) {\n            this._walletButton.removeEventListener('click', this._buttonClickEventHandler);\n        }\n\n        this._buttonClickEventHandler = undefined;\n        this._walletButton = undefined;\n\n        return this._googlePayPaymentProcessor.deinitialize()\n            .then(() => this._store.getState());\n    }\n\n    async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        if (!this._googlePayOptions) {\n            throw new InvalidArgumentError('Unable to initialize payment because \"options.googlepay\" argument is not provided.');\n        }\n\n        if (!payload.payment) {\n            throw new PaymentArgumentInvalidError(['payment']);\n        }\n\n        const { methodId } = payload.payment;\n\n        if (this._paymentMethod?.initializationData.nonce !== '') {\n            const state = this._store.getState();\n            this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n        }\n\n        let payment = await this._getPayment(methodId);\n\n        if (!payment.paymentData.nonce || !payment.paymentData.cardInformation) {\n            const {\n                onError = () => {},\n                onPaymentSelect = () => {},\n            } = this._googlePayOptions;\n            await this._displayWallet(methodId, onPaymentSelect, onError);\n            payment = await this._getPayment(methodId, true);\n        }\n\n        if (!payment.paymentData.nonce) {\n            throw new MissingDataError(MissingDataErrorType.MissingPayment);\n        }\n\n        try {\n            await this._store.dispatch(this._orderActionCreator.submitOrder({ useStoreCredit: payload.useStoreCredit }, options));\n\n            return await this._store.dispatch(this._paymentActionCreator.submitPayment(payment));\n        } catch (error) {\n            this._googlePayAdyenV2PaymentProcessor?.processAdditionalAction(error);\n            throw error;\n        }\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    private _getGooglePayOptions(options: PaymentInitializeOptions): GooglePayPaymentInitializeOptions {\n        if (options.methodId === 'googlepayadyenv2' && options.googlepayadyenv2) {\n            if (!this._googlePayAdyenV2PaymentProcessor) {\n                throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n            }\n\n            this._googlePayAdyenV2PaymentProcessor.initialize(options);\n\n            return options.googlepayadyenv2;\n        }\n\n        if (options.methodId === 'googlepayauthorizenet' && options.googlepayauthorizenet) {\n            return options.googlepayauthorizenet;\n        }\n\n        if (options.methodId === 'googlepaycheckoutcom' && options.googlepaycheckoutcom) {\n            return options.googlepaycheckoutcom;\n        }\n\n        if (options.methodId === 'googlepaycybersourcev2' && options.googlepaycybersourcev2) {\n            return options.googlepaycybersourcev2;\n        }\n\n        if (options.methodId === 'googlepayorbital' && options.googlepayorbital) {\n            return options.googlepayorbital;\n        }\n\n        if (options.methodId === 'googlepaybraintree' && options.googlepaybraintree) {\n            return options.googlepaybraintree;\n        }\n\n        if (options.methodId === 'googlepaystripe' && options.googlepaystripe) {\n            return options.googlepaystripe;\n        }\n\n        throw new InvalidArgumentError('Unable to initialize payment because \"options.googlepay\" argument is not provided.');\n    }\n\n    private async _getPayment(methodId: string, requireRenewNonce = false): Promise<PaymentMethodData> {\n        if (!methodId || !this._paymentMethod) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        const card_information = this._paymentMethod?.initializationData.card_information;\n        let nonce = this._paymentMethod?.initializationData.nonce;\n\n        if (nonce) {\n            this._paymentMethod = { ...this._paymentMethod,  initializationData: { nonce: ''} };\n        }\n\n        if (requireRenewNonce) {\n            const state = await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId));\n            this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n            nonce = this._paymentMethod?.initializationData.nonce;\n        }\n\n        return {\n            methodId,\n            paymentData: {\n                method: methodId,\n                cardInformation: card_information,\n                nonce: await this._encodeNonce(methodId, nonce),\n            },\n        };\n    }\n\n    private async _encodeNonce(methodId: string, nonce: string) {\n        if (methodId === 'googlepayadyenv2') {\n            return JSON.stringify({\n                type: AdyenPaymentMethodType.GooglePay,\n                googlePayToken: nonce,\n                browser_info: getBrowserInfo(),\n            });\n        }\n\n        return nonce;\n    }\n\n    private async _paymentInstrumentSelected(paymentData: GooglePaymentData, methodId: string) {\n        if (!methodId) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        // TODO: Revisit how we deal with GooglePaymentData after receiving it from Google\n        await this._googlePayPaymentProcessor.handleSuccess(paymentData);\n\n        const state = this._store.getState();\n        this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n        if (this._paymentMethod.initializationData.nonce) {\n            return await Promise.all([\n                this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),\n                this._store.getState(),\n            ]);\n        }\n\n        return await Promise.all([\n            this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),\n            this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId)),\n        ]);\n    }\n\n    private _handleButtonClickedEvent(methodId: string): (event?: Event) => Promise<InternalCheckoutSelectors> {\n\n        return (event?: Event) => {\n            event?.preventDefault();\n\n            if (!methodId || !this._googlePayOptions) {\n                throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n            }\n\n            const {\n                onError = () => {},\n                onPaymentSelect = () => {},\n            } = this._googlePayOptions;\n\n            return this._store.dispatch(\n                this._paymentStrategyActionCreator.widgetInteraction(\n                    async () => await this._displayWallet(methodId, onPaymentSelect, onError),\n                        { methodId }\n                ),\n                { queueId: 'widgetInteraction' }\n            );\n        };\n    }\n\n    private async _displayWallet(methodId: string, onPaymentSelect: () => void, onError: (onError: Error) => void ): Promise<void> {\n        try {\n            const paymentData = await this._googlePayPaymentProcessor.displayWallet();\n            await this._paymentInstrumentSelected(paymentData, methodId);\n\n            return onPaymentSelect();\n        } catch (error) {\n            if (error.statusCode === 'CANCELED') {\n                throw new Error('CANCELED');\n            }\n            onError(error);\n        }\n    }\n}\n","import { some } from 'lodash';\n\nimport { Payment, PaymentActionCreator, PaymentInitializeOptions } from '../..';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType, RequestError } from '../../../common/error/errors';\nimport { PaymentMethodCancelledError } from '../../errors';\nimport { AdyenAction, AdyenAdditionalAction, AdyenAdditionalActionState, AdyenClient, AdyenError, AdyenV2ScriptLoader } from '../adyenv2';\n\nexport default class GooglePayAdyenV2PaymentProcessor {\n    private _adyenClient?: AdyenClient;\n\n    constructor(private _store: CheckoutStore, private _paymentActionCreator: PaymentActionCreator, private _scriptLoader: AdyenV2ScriptLoader) {}\n\n    async initialize(options: PaymentInitializeOptions) {\n        const state = this._store.getState();\n        const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(options.methodId);\n        const storeConfig = state.config.getStoreConfig();\n\n        if (!storeConfig) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n        }\n\n        const clientSideAuthentication = {\n            key: '',\n            value: '',\n        };\n\n        if (paymentMethod.initializationData.originKey) {\n            clientSideAuthentication.key = 'originKey';\n            clientSideAuthentication.value = paymentMethod.initializationData.originKey;\n        } else {\n            clientSideAuthentication.key = 'clientKey';\n            clientSideAuthentication.value = paymentMethod.initializationData.clientKey;\n        }\n\n        this._adyenClient = await this._scriptLoader.load({\n            environment: paymentMethod.config.testMode ? 'TEST' : ' PRODUCTION',\n            locale: storeConfig.storeProfile.storeLanguage,\n            [clientSideAuthentication.key]: clientSideAuthentication.value,\n            paymentMethodsResponse: paymentMethod.initializationData.paymentMethodsResponse,\n        });\n    }\n\n    async processAdditionalAction(error: unknown): Promise<InternalCheckoutSelectors> {\n        if (!(error instanceof RequestError) || !some(error.body.errors, {code: 'additional_action_required'})) {\n            return Promise.reject(error);\n        }\n\n        const payment = await this._handleAction(error.body.provider_data);\n\n        try {\n            return await this._store.dispatch(this._paymentActionCreator.submitPayment({\n                ...payment,\n                paymentData: {\n                    ...payment.paymentData,\n                },\n            }));\n        } catch (error) {\n            return this.processAdditionalAction(error);\n        }\n    }\n\n    private _handleAction(additionalAction: AdyenAdditionalAction): Promise<Payment> {\n        return new Promise((resolve, reject) => {\n            const adyenAction: AdyenAction = JSON.parse(additionalAction.action);\n\n            const additionalActionComponent = this._getAdyenClient().createFromAction(adyenAction, {\n                onAdditionalDetails: (additionalActionState: AdyenAdditionalActionState) => {\n                    const paymentPayload = {\n                        methodId: adyenAction.paymentMethodType,\n                        paymentData: {\n                            nonce: JSON.stringify(additionalActionState.data),\n                        },\n                    };\n\n                    resolve(paymentPayload);\n                },\n                size: '05',\n                onError: (error: AdyenError) => reject(error),\n            });\n\n            additionalActionComponent.mount('body');\n\n            reject(new PaymentMethodCancelledError());\n        });\n    }\n\n    private _getAdyenClient(): AdyenClient {\n        if (!this._adyenClient) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        return this._adyenClient;\n    }\n}\n","export const supportedCountries = ['AT', 'BE', 'CH', 'DE', 'DK', 'ES', 'FI', 'GB', 'IT', 'NL', 'NO', 'NZ', 'SE'];\nexport const supportedCountriesRequiringStates = ['AU'];\n","import { includes } from 'lodash';\n\nimport { Address } from '../../../address';\nimport { BillingAddress } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { PaymentMethodCancelledError, PaymentMethodInvalidError } from '../../errors';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { supportedCountries, supportedCountriesRequiringStates } from '../klarnav2';\nimport PaymentStrategy from '../payment-strategy';\n\nimport KlarnaCredit, { KlarnaAddress, KlarnaLoadResponse, KlarnaUpdateSessionParams } from './klarna-credit';\nimport KlarnaScriptLoader from './klarna-script-loader';\n\nexport default class KlarnaPaymentStrategy implements PaymentStrategy {\n    private _klarnaCredit?: KlarnaCredit;\n    private _unsubscribe?: (() => void);\n\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n        private _klarnaScriptLoader: KlarnaScriptLoader\n    ) {}\n\n    initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        return this._klarnaScriptLoader.load()\n            .then(klarnaCredit => { this._klarnaCredit = klarnaCredit; })\n            .then(() => {\n                this._unsubscribe = this._store.subscribe(\n                    state => {\n                        if (state.paymentStrategies.isInitialized(options.methodId)) {\n                            this._loadWidget(options);\n                        }\n                    },\n                    state => {\n                        const checkout = state.checkout.getCheckout();\n\n                        return checkout && checkout.outstandingBalance;\n                    },\n                    state => {\n                        const checkout = state.checkout.getCheckout();\n\n                        return checkout && checkout.coupons;\n                    }\n                );\n\n                return this._loadWidget(options);\n            })\n            .then(() => this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        if (this._unsubscribe) {\n            this._unsubscribe();\n        }\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        if (!payload.payment) {\n            throw new InvalidArgumentError('Unable to proceed because \"payload.payment\" argument is not provided.');\n        }\n\n        const { payment: { paymentData, ...paymentPayload } } = payload;\n\n        return this._authorize()\n            .then(({ authorization_token: authorizationToken }) => this._store.dispatch(\n                this._remoteCheckoutActionCreator.initializePayment(paymentPayload.methodId, { authorizationToken })\n            ))\n            .then(() => this._store.dispatch(\n                this._orderActionCreator.submitOrder({\n                    ...payload,\n                    payment: paymentPayload,\n                    useStoreCredit: payload.useStoreCredit,\n                }, options)\n            ));\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    private _loadWidget(options: PaymentInitializeOptions): Promise<KlarnaLoadResponse> {\n        if (!options.klarna) {\n            throw new InvalidArgumentError('Unable to load widget because \"options.klarna\" argument is not provided.');\n        }\n\n        const { methodId, klarna: { container, onLoad } } = options;\n\n        return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n            .then(state => new Promise<KlarnaLoadResponse>(resolve => {\n                const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n                if (!paymentMethod) {\n                    throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n                }\n\n                if (!this._klarnaCredit || !paymentMethod.clientToken) {\n                    throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n                }\n\n                this._klarnaCredit.init({ client_token: paymentMethod.clientToken });\n\n                this._klarnaCredit.load({ container }, response => {\n                    if (onLoad) {\n                        onLoad(response);\n                    }\n                    resolve(response);\n                });\n            }));\n    }\n\n    private _getUpdateSessionData(billingAddress: BillingAddress, shippingAddress?: Address): KlarnaUpdateSessionParams {\n        if (!includes([...supportedCountries, ...supportedCountriesRequiringStates], billingAddress.countryCode)) {\n            return {};\n        }\n\n        const data: KlarnaUpdateSessionParams = {\n            billing_address: this._mapToKlarnaAddress(billingAddress, billingAddress.email),\n        };\n\n        if (shippingAddress) {\n            data.shipping_address = this._mapToKlarnaAddress(shippingAddress, billingAddress.email);\n        }\n\n        return data;\n    }\n\n    private _needsStateCode(countryCode: string) {\n        return includes(supportedCountriesRequiringStates, countryCode);\n    }\n\n    private _mapToKlarnaAddress(address: Address, email?: string): KlarnaAddress {\n        const klarnaAddress: KlarnaAddress = {\n            street_address: address.address1,\n            city: address.city,\n            country: address.countryCode,\n            given_name: address.firstName,\n            family_name: address.lastName,\n            postal_code: address.postalCode,\n            region: this._needsStateCode(address.countryCode) ? address.stateOrProvinceCode : address.stateOrProvince,\n            email,\n        };\n\n        if (address.address2) {\n            klarnaAddress.street_address2 = address.address2;\n        }\n\n        if (address.phone) {\n            klarnaAddress.phone = address.phone;\n        }\n\n        return klarnaAddress;\n    }\n\n    private _authorize(): Promise<any> {\n        return new Promise((resolve, reject) => {\n            const billingAddress = this._store.getState().billingAddress.getBillingAddress();\n            const shippingAddress = this._store.getState().shippingAddress.getShippingAddress();\n\n            if (!billingAddress) {\n                throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n            }\n\n            if (!this._klarnaCredit) {\n                throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n            }\n\n            const updateSessionData = this._getUpdateSessionData(billingAddress, shippingAddress);\n\n            this._klarnaCredit.authorize(updateSessionData, res => {\n                if (res.approved) {\n                    return resolve(res);\n                }\n\n                if (res.show_form) {\n                    return reject(new PaymentMethodCancelledError());\n                }\n\n                reject(new PaymentMethodInvalidError());\n            });\n        });\n    }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport KlarnaCredit from './klarna-credit';\nimport KlarnaWindow from './klarna-window';\n\nconst SDK_URL = '//credit.klarnacdn.net/lib/v1/api.js';\n\nexport default class KlarnaScriptLoader {\n    constructor(\n        private _scriptLoader: ScriptLoader\n    ) {}\n\n    load(): Promise<KlarnaCredit> {\n        return this._scriptLoader.loadScript(SDK_URL)\n            .then(() => (window as unknown as KlarnaWindow).Klarna.Credit);\n    }\n}\n","import { includes } from 'lodash';\n\nimport { Address } from '../../../address';\nimport { BillingAddress } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { PaymentMethodCancelledError, PaymentMethodInvalidError } from '../../errors';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport KlarnaPayments, { KlarnaAddress, KlarnaAuthorizationResponse, KlarnaLoadResponse, KlarnaUpdateSessionParams } from './klarna-payments';\nimport { supportedCountries, supportedCountriesRequiringStates } from './klarna-supported-countries';\nimport KlarnaV2ScriptLoader from './klarnav2-script-loader';\n\nexport default class KlarnaV2PaymentStrategy implements PaymentStrategy {\n    private _klarnaPayments?: KlarnaPayments;\n    private _unsubscribe?: (() => void);\n\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n        private _klarnav2ScriptLoader: KlarnaV2ScriptLoader\n    ) {}\n\n    initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        return this._klarnav2ScriptLoader.load()\n            .then(klarnaPayments => { this._klarnaPayments = klarnaPayments; })\n            .then(() => {\n                this._unsubscribe = this._store.subscribe(\n                    state => {\n                        if (state.paymentStrategies.isInitialized(options.methodId)) {\n                            this._loadPaymentsWidget(options);\n                        }\n                    },\n                    state => {\n                        const checkout = state.checkout.getCheckout();\n\n                        return checkout && checkout.outstandingBalance;\n                    },\n                    state => {\n                        const checkout = state.checkout.getCheckout();\n\n                        return checkout && checkout.coupons;\n                    }\n                );\n\n                return this._loadPaymentsWidget(options);\n            })\n            .then(() => this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        if (this._unsubscribe) {\n            this._unsubscribe();\n        }\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        if (!payload.payment) {\n            throw new InvalidArgumentError('Unable to proceed because \"payload.payment\" argument is not provided.');\n        }\n\n        const { payment: { paymentData, ...paymentPayload } } = payload;\n        const { gatewayId } = paymentPayload;\n\n        if (!gatewayId) {\n            throw new InvalidArgumentError('Unable to proceed because \"payload.payment.gatewayId\" argument is not provided.');\n        }\n\n        return this._authorize(paymentPayload.methodId)\n            .then(({ authorization_token: authorizationToken }) => this._store.dispatch(\n                this._remoteCheckoutActionCreator.initializePayment(gatewayId, { authorizationToken })\n            ))\n            .then(() => this._store.dispatch(\n                this._orderActionCreator.submitOrder({\n                    ...payload,\n                    payment: paymentPayload,\n                    useStoreCredit: payload.useStoreCredit,\n                }, options)\n            ));\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    private _loadPaymentsWidget(options: PaymentInitializeOptions): Promise<KlarnaLoadResponse> {\n        if (!options.klarnav2) {\n            throw new InvalidArgumentError('Unable to load widget because \"options.klarnav2\" argument is not provided.');\n        }\n\n        const { methodId, gatewayId, klarnav2: { container, onLoad } } = options;\n        const state = this._store.getState();\n\n        if (!gatewayId) {\n            throw new InvalidArgumentError('Unable to proceed because \"payload.payment.gatewayId\" argument is not provided.');\n        }\n\n        return this._updateOrder(gatewayId).then(() => new Promise<KlarnaLoadResponse>(resolve => {\n            const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n            if (!this._klarnaPayments || !paymentMethod.clientToken) {\n                throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n            }\n\n            this._klarnaPayments.init({ client_token: paymentMethod.clientToken });\n            this._klarnaPayments.load({ container, payment_method_category: paymentMethod.id }, response => {\n                if (onLoad) {\n                    onLoad(response);\n                }\n\n                resolve(response);\n            });\n        }));\n    }\n\n    private _getUpdateSessionData(billingAddress: BillingAddress, shippingAddress?: Address): KlarnaUpdateSessionParams {\n        if (!includes([...supportedCountries, ...supportedCountriesRequiringStates], billingAddress.countryCode)) {\n            return {};\n        }\n\n        const data: KlarnaUpdateSessionParams = {\n            billing_address: this._mapToKlarnaAddress(billingAddress, billingAddress.email),\n        };\n\n        if (shippingAddress) {\n            data.shipping_address = this._mapToKlarnaAddress(shippingAddress, billingAddress.email);\n        }\n\n        return data;\n    }\n\n    private _needsStateCode(countryCode: string) {\n        return includes(supportedCountriesRequiringStates, countryCode);\n    }\n\n    private _mapToKlarnaAddress(address: Address, email?: string): KlarnaAddress {\n        const klarnaAddress: KlarnaAddress = {\n            street_address: address.address1,\n            city: address.city,\n            country: address.countryCode,\n            given_name: address.firstName,\n            family_name: address.lastName,\n            postal_code: address.postalCode,\n            region: this._needsStateCode(address.countryCode) ? address.stateOrProvinceCode : address.stateOrProvince,\n            email,\n        };\n\n        if (address.address2) {\n            klarnaAddress.street_address2 = address.address2;\n        }\n\n        if (address.phone) {\n            klarnaAddress.phone = address.phone;\n        }\n\n        return klarnaAddress;\n    }\n\n    private async _updateOrder(gatewayId: string) {\n        await this._paymentMethodActionCreator.loadPaymentMethod(gatewayId).toPromise();\n    }\n\n    private _authorize(methodId: string): Promise<KlarnaAuthorizationResponse> {\n        return new Promise<KlarnaAuthorizationResponse>((resolve, reject) => {\n            const billingAddress = this._store.getState().billingAddress.getBillingAddress();\n            const shippingAddress = this._store.getState().shippingAddress.getShippingAddress();\n\n            if (!billingAddress) {\n                throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n            }\n\n            const updateSessionData = this._getUpdateSessionData(billingAddress, shippingAddress);\n\n            if (!this._klarnaPayments) {\n                throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n            }\n\n            this._klarnaPayments.authorize({ payment_method_category: methodId }, updateSessionData, res => {\n                if (res.approved) {\n                    return resolve(res);\n                }\n\n                if (res.show_form) {\n                    return reject(new PaymentMethodCancelledError());\n                }\n\n                reject(new PaymentMethodInvalidError());\n            });\n        });\n    }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport KlarnaPayments from './klarna-payments';\nimport KlarnaV2Window from './klarnav2-window';\n\nconst SDK_URL = 'https://x.klarnacdn.net/kp/lib/v1/api.js';\n\nexport default class KlarnaV2ScriptLoader {\n    constructor(\n        private _scriptLoader: ScriptLoader\n    ) {}\n\n    load(): Promise<KlarnaPayments> {\n        return this._scriptLoader.loadScript(SDK_URL)\n            .then(() => (window as unknown as KlarnaV2Window).Klarna.Payments);\n    }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nexport default class LegacyPaymentStrategy implements PaymentStrategy {\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator\n    ) {}\n\n    execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        return this._store.dispatch(this._orderActionCreator.submitOrder(payload, options));\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    initialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType } from '../../../common/error/errors';\nimport { bindDecorator as bind } from '../../../common/utility';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport getCallbackUrl from './get-callback-url';\nimport { Masterpass, MasterpassCheckoutOptions } from './masterpass';\nimport MasterpassScriptLoader from './masterpass-script-loader';\n\nexport default class MasterpassPaymentStrategy implements PaymentStrategy {\n    private _masterpassClient?: Masterpass;\n    private _paymentMethod?: PaymentMethod;\n    private _walletButton?: HTMLElement;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _masterpassScriptLoader: MasterpassScriptLoader\n    ) {}\n\n    initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { methodId } = options;\n        const state = this._store.getState();\n        const storeConfig = state.config.getStoreConfig();\n        this._paymentMethod = this._store.getState().paymentMethods.getPaymentMethod(methodId);\n\n        if (!this._paymentMethod) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        if (!storeConfig) {\n            throw new InvalidArgumentError('Unable to retrieve store configuration');\n        }\n\n        const masterpassScriptLoaderParams = {\n            useMasterpassSrc: this._paymentMethod.initializationData.isMasterpassSrcEnabled,\n            language: storeConfig.storeProfile.storeLanguage,\n            testMode: this._paymentMethod.config.testMode,\n            checkoutId: this._paymentMethod.initializationData.checkoutId,\n        };\n\n        return this._masterpassScriptLoader.load(masterpassScriptLoaderParams)\n            .then(masterpass => {\n                this._masterpassClient = masterpass;\n\n                if (!options.masterpass) {\n                    throw new InvalidArgumentError('Unable to initialize payment because \"options.masterpass\" argument is not provided.');\n                }\n\n                const walletButton  = options.masterpass.walletButton && document.getElementById(options.masterpass.walletButton);\n\n                if (walletButton) {\n                    this._walletButton = walletButton;\n                    this._walletButton.addEventListener('click', this._handleWalletButtonClick);\n                }\n\n                return this._store.getState();\n            });\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        this._paymentMethod = undefined;\n\n        if (this._walletButton) {\n            this._walletButton.removeEventListener('click', this._handleWalletButtonClick);\n        }\n\n        this._walletButton = undefined;\n        this._masterpassClient = undefined;\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment } = payload;\n        const order = { useStoreCredit: payload.useStoreCredit };\n\n        if (!payment) {\n            throw new InvalidArgumentError('Unable to submit payment because \"payload.payment\" argument is not provided.');\n        }\n\n        if (!this._paymentMethod || !this._paymentMethod.initializationData || !this._paymentMethod.initializationData.gateway) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        // TODO: Refactor the API endpoint to return nonce in the right place.\n        const paymentData = this._paymentMethod.initializationData.paymentData;\n\n        // TODO: Redirect to Masterpass if nonce has not been generated yet. And then finalise the order when the shopper is redirected back to the checkout page.\n        if (!paymentData) {\n            throw new InvalidArgumentError('Unable to proceed because \"paymentMethod.initializationData.paymentData\" argument is not provided.');\n        }\n\n        return this._store.dispatch(this._orderActionCreator.submitOrder(order, options))\n            .then(() => this._store.dispatch(this._paymentActionCreator.submitPayment({ ...payment, paymentData })));\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    private _createMasterpassPayload(): MasterpassCheckoutOptions {\n        const state = this._store.getState();\n        const checkout = state.checkout.getCheckout();\n        const storeConfig = state.config.getStoreConfig();\n\n        if (!checkout) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n        }\n\n        if (!storeConfig) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n        }\n\n        if (!this._paymentMethod || !this._paymentMethod.initializationData) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        return {\n            checkoutId: this._paymentMethod.initializationData.checkoutId,\n            allowedCardTypes: this._paymentMethod.initializationData.allowedCardTypes,\n            amount: checkout.subtotal.toFixed(2),\n            currency: storeConfig.currency.code,\n            cartId: checkout.cart.id,\n            callbackUrl: getCallbackUrl('checkout'),\n        };\n    }\n\n    @bind\n    private _handleWalletButtonClick(event: Event) {\n        event.preventDefault();\n\n        if (!this._masterpassClient) {\n            return;\n        }\n\n        const payload = this._createMasterpassPayload();\n        this._masterpassClient.checkout(payload);\n    }\n}\n","import { PaypalFieldsStyleOptions } from './index';\n\n/**\n * A set of options that are required to initialize the PayPal Commerce payment\n * method could be used for PayPal Smart Payment Buttons or PayPal Credit Card methods.\n */\nexport type PaypalCommerceInitializeOptions = PaypalCommercePaymentInitializeOptions | PaypalCommerceCreditCardPaymentInitializeOptions;\n\n/**\n * A set of options that are required to initialize the PayPal Commerce payment\n * method for presenting its PayPal button.\n *\n * Please note that the minimum version of checkout-sdk is 1.100\n *\n * Also, PayPal (also known as PayPal Commerce Platform) requires specific options to initialize the PayPal Smart Payment Button on checkout page that substitutes a standard submit button\n * ```html\n * <!-- This is where the PayPal button will be inserted -->\n * <div id=\"container\"></div>\n * <!-- This is where the PayPal alternative payment methods fields will be inserted.  -->\n * <div id=\"apm-fields-container\"></div>\n * ```\n *\n * ```js\n * service.initializePayment({\n *     methodId: 'paypalcommerce',\n *     paypalcommerce: {\n *         container: '#container',\n *         apmFieldsContainer: '#apm-fields-container',\n *         apmFieldsStyles: {\n *             base: {\n *                   backgroundColor: 'transparent',\n *               },\n *               input: {\n *                   backgroundColor: 'white',\n *                   fontSize: '1rem',\n *                   color: '#333',\n *                   borderColor: '#d9d9d9',\n *                   borderRadius: '4px',\n *                   borderWidth: '1px',\n *                   padding: '1rem',\n *               },\n *               invalid: {\n *                   color: '#ed6a6a',\n *               },\n *               active: {\n *                   color: '#4496f6',\n *               },\n *         },\n *         clientId: 'YOUR_CLIENT_ID',\n * // Callback for submitting payment form that gets called when a buyer approves PayPal payment\n *         submitForm: () => {\n *         // Example function\n *             this.submitOrder(\n *                {\n *                   payment: { methodId: 'paypalcommerce', }\n *               }\n *            );\n *         },\n * // Callback is used to define the state of the payment form, validate if it is applicable for submit.\n *         onValidate: (resolve, reject) => {\n *         // Example function\n *             const isValid = this.validatePaymentForm();\n *             if (isValid) {\n *                 return resolve();\n *             }\n *             return reject();\n *         },\n * // Callback that is called right before render of a Smart Payment Button. It gets called when a buyer is eligible for use of the particular PayPal method. This callback can be used to hide the standard submit button.\n *         onRenderButton: () => {\n *         // Example function\n *             this.hidePaymentSubmitButton();\n *         }\n *     },\n * });\n * ```\n */\nexport interface PaypalCommercePaymentInitializeOptions {\n    /**\n     * The CSS selector of a container where the payment widget should be inserted into.\n     */\n    container: string;\n\n    /**\n     *  The Client ID of the Paypal App\n     */\n    clientId: string;\n\n    /**\n     * The CSS selector of a container where the alternative payment methods fields widget should be inserted into.\n     * It's necessary to specify this parameter when using Alternative Payment Methods.\n     * Without it alternative payment methods will not work.\n     */\n    apmFieldsContainer?: string;\n\n    /**\n     * Object with styles to customize alternative payment methods fields.\n     */\n    apmFieldsStyles?: PaypalFieldsStyleOptions;\n\n    /**\n     * A callback that gets called when a buyer click on Smart Payment Button\n     * and should validate payment form.\n     *\n     * @param resolve - A function, that gets called if form is valid.\n     * @param reject - A function, that gets called if form is not valid.\n     *\n     * @returns reject() or resolve()\n     */\n    onValidate(resolve: () => void, reject: () => void): Promise<void>;\n\n    /**\n     * A callback for submitting payment form that gets called\n     * when buyer approved PayPal account.\n     */\n    submitForm(): void;\n\n    /**\n     * A callback right before render Smart Payment Button that gets called when\n     * Smart Payment Button is eligible. This callback can be used to hide the standard submit button.\n     */\n    onRenderButton?(): void;\n    /**\n     * A callback for displaying error popup. This callback requires error object as parameter.\n     */\n    onError?(error: Error): void;\n}\n\n/**\n * A set of options that are required to initialize the PayPal Commerce payment\n * method for presenting its credit card form.\n *\n * ```html\n * <!-- These containers are where the hosted (iframed) credit card fields will be inserted -->\n * <div id=\"card-number\"></div>\n * <div id=\"card-name\"></div>\n * <div id=\"card-expiry\"></div>\n * <div id=\"card-code\"></div>\n * ```\n *\n * ```js\n * service.initializePayment({\n *     methodId: 'paypalcommerce',\n *     paypalcommerce: {\n *         form: {\n *             fields: {\n *                 cardNumber: { containerId: 'card-number' },\n *                 cardName: { containerId: 'card-name' },\n *                 cardExpiry: { containerId: 'card-expiry' },\n *                 cardCode: { containerId: 'card-code' },\n *             },\n *         },\n *     },\n * });\n * ```\n *\n * Additional options can be passed in to customize the fields and register\n * event callbacks.\n *\n * ```js\n * service.initializePayment({\n *     methodId: 'paypalcommerce',\n *     creditCard: {\n *         form: {\n *             fields: {\n *                 cardNumber: { containerId: 'card-number', placeholder: 'Number of card' },\n *                 cardName: { containerId: 'card-name', placeholder: 'Name of card' },\n *                 cardExpiry: { containerId: 'card-expiry', placeholder: 'Expiry of card' },\n *                 cardCode: { containerId: 'card-code', placeholder: 'Code of card' },\n *             },\n *             styles: {\n *                 default: {\n *                     color: '#000',\n *                 },\n *                 error: {\n *                     color: '#f00',\n *                 },\n *                 focus: {\n *                     color: '#0f0',\n *                 },\n *             },\n *             onBlur({ fieldType }) {\n *                 console.log(fieldType);\n *             },\n *             onFocus({ fieldType }) {\n *                 console.log(fieldType);\n *             },\n *             onEnter({ fieldType }) {\n *                 console.log(fieldType);\n *             },\n *             onCardTypeChange({ cardType }) {\n *                 console.log(cardType);\n *             },\n *             onValidate({ errors, isValid }) {\n *                 console.log(errors);\n *                 console.log(isValid);\n *             },\n *         },\n *     },\n * });\n * ```\n */\nexport interface PaypalCommerceCreditCardPaymentInitializeOptions {\n    /**\n     * The form is data for Credit Card Form\n     */\n    form: PaypalCommerceFormOptions;\n}\n\nexport interface PaypalCommerceFormOptions {\n    /**\n     * Containers for fields can be to present in one set of values\n     *\n     * ```js\n     * { cardNumber: { containerId: 'card-number' },\n     *   cardName: { containerId: 'card-name' },\n     *   cardExpiry: { containerId: 'card-expiry' },\n     *   cardCode: { containerId: 'card-code' }, }\n     * ```\n     *\n     *   Or in another set of values.\n     *\n     * ```js\n     * { cardCodeVerification: { containerId: 'card-number' },\n     *   cardNumberVerification: { containerId: 'card-name' }, }\n     * ```\n     */\n    fields: PaypalCommerceFormFieldsMap | PaypalCommerceStoredCardFieldsMap;\n\n    /**\n     * Styles for inputs. Change the width, height and other styling.\n     *\n     * ```js\n     *  default: { color: '#000' },\n     *  error: { color: '#f00' },\n     *  focus: { color: '#0f0' }\n     * ```\n     */\n    styles?: PaypalCommerceFormFieldStylesMap;\n\n    /**\n     * A callback that gets called when a field loses focus.\n     */\n    onBlur?(data: PaypalCommerceFormFieldBlurEventData): void;\n\n    /**\n     * A callback that gets called when activity within\n     * the number field has changed such that the possible\n     * card type has changed.\n     */\n    onCardTypeChange?(data: PaypalCommerceFormFieldCardTypeChangeEventData): void;\n\n    /**\n     * A callback that gets called when a field gains focus.\n     */\n    onFocus?(data: PaypalCommerceFormFieldFocusEventData): void;\n\n    /**\n     * A callback that gets called when the validity of a field has changed.\n     */\n    onValidate?(data: PaypalCommerceFormFieldValidateEventData): void;\n\n    /**\n     * A callback that gets called when the user requests submission\n     * of an input field, by pressing the Enter or Return key\n     * on their keyboard, or mobile equivalent.\n     */\n    onEnter?(data: PaypalCommerceFormFieldEnterEventData): void;\n}\n\nexport enum PaypalCommerceFormFieldType {\n    CardCode = 'cardCode',\n    CardCodeVerification = 'cardCodeVerification',\n    CardExpiry = 'cardExpiry',\n    CardName = 'cardName',\n    CardNumber = 'cardNumber',\n    CardNumberVerification = 'cardNumberVerification',\n}\n\nexport interface PaypalCommerceFormFieldsMap {\n    [PaypalCommerceFormFieldType.CardCode]?: PaypalCommerceFormFieldOptions;\n    [PaypalCommerceFormFieldType.CardExpiry]: PaypalCommerceFormFieldOptions;\n    [PaypalCommerceFormFieldType.CardName]: PaypalCommerceFormFieldOptions;\n    [PaypalCommerceFormFieldType.CardNumber]: PaypalCommerceFormFieldOptions;\n}\n\nexport interface PaypalCommerceStoredCardFieldsMap {\n    [PaypalCommerceFormFieldType.CardCodeVerification]?: PaypalCommerceStoredCardFieldOptions;\n    [PaypalCommerceFormFieldType.CardNumberVerification]?: PaypalCommerceStoredCardFieldOptions;\n}\n\nexport interface PaypalCommerceFormFieldOptions {\n    containerId: string;\n    placeholder?: string;\n}\n\nexport interface PaypalCommerceStoredCardFieldOptions extends PaypalCommerceFormFieldOptions {\n    instrumentId: string;\n}\n\nexport interface PaypalCommerceFormFieldStylesMap {\n    default?: PaypalCommerceFormFieldStyles;\n    error?: PaypalCommerceFormFieldStyles;\n    focus?: PaypalCommerceFormFieldStyles;\n}\n\nexport type PaypalCommerceFormFieldStyles = Partial<Pick<\n    CSSStyleDeclaration,\n    'color' |\n    'fontFamily' |\n    'fontSize' |\n    'fontWeight'\n    >>;\n\nexport interface PaypalCommerceFormFieldKeyboardEventData {\n    fieldType: string;\n}\n\nexport type PaypalCommerceFormFieldBlurEventData = PaypalCommerceFormFieldKeyboardEventData;\nexport type PaypalCommerceFormFieldEnterEventData = PaypalCommerceFormFieldKeyboardEventData;\nexport type PaypalCommerceFormFieldFocusEventData = PaypalCommerceFormFieldKeyboardEventData;\n\nexport interface PaypalCommerceFormFieldCardTypeChangeEventData {\n    cardType?: string;\n}\n\nexport interface PaypalCommerceFormFieldValidateEventData {\n    errors: {\n        [PaypalCommerceFormFieldType.CardCode]?: PaypalCommerceFormFieldValidateErrorData[];\n        [PaypalCommerceFormFieldType.CardExpiry]?: PaypalCommerceFormFieldValidateErrorData[];\n        [PaypalCommerceFormFieldType.CardName]?: PaypalCommerceFormFieldValidateErrorData[];\n        [PaypalCommerceFormFieldType.CardNumber]?: PaypalCommerceFormFieldValidateErrorData[];\n        [PaypalCommerceFormFieldType.CardCodeVerification]?: PaypalCommerceFormFieldValidateErrorData[];\n        [PaypalCommerceFormFieldType.CardNumberVerification]?: PaypalCommerceFormFieldValidateErrorData[];\n    };\n    isValid: boolean;\n}\n\nexport interface PaypalCommerceFormFieldValidateErrorData {\n    fieldType: string;\n    message: string;\n    type: string;\n}\n","import { isNil, kebabCase, omitBy } from 'lodash';\n\nimport { PaymentInvalidFormError, PaymentInvalidFormErrorDetails, PaymentMethodFailedError } from '../../errors';\n\nimport { PaypalCommerceFormFieldStyles, PaypalCommerceFormFieldStylesMap, PaypalCommerceFormFieldType, PaypalCommerceFormFieldValidateErrorData, PaypalCommerceFormFieldValidateEventData, PaypalCommerceFormOptions, PaypalCommerceHostedFieldsApprove, PaypalCommerceHostedFieldsRenderOptions, PaypalCommerceHostedFieldsState, PaypalCommerceHostedFieldsSubmitOptions, PaypalCommercePaymentProcessor, PaypalCommerceRegularField, PaypalCommerceScriptParams } from './index';\nimport { PaypalCommerceFormFieldsMap, PaypalCommerceStoredCardFieldsMap } from './paypal-commerce-payment-initialize-options';\n\nenum PaypalCommerceHostedFormType {\n    CreditCard,\n    StoredCardVerification,\n}\n\nexport default class PaypalCommerceHostedForm {\n    private _formOptions?: PaypalCommerceFormOptions;\n    private _cardNameField?: PaypalCommerceRegularField;\n    private _type?: PaypalCommerceHostedFormType;\n\n    constructor(\n        private _paypalCommercePaymentProcessor: PaypalCommercePaymentProcessor\n    ) {\n    }\n\n    async initialize(options: PaypalCommerceFormOptions, cartId: string, paramsScript: PaypalCommerceScriptParams) {\n        await this._paypalCommercePaymentProcessor.initialize(paramsScript);\n\n        this._formOptions = options;\n        this._type = this._isPaypalCommerceFormFieldsMap(options.fields) ?\n            PaypalCommerceHostedFormType.CreditCard :\n            PaypalCommerceHostedFormType.StoredCardVerification;\n        const params = {\n            fields: this._mapFieldOptions(options.fields),\n            styles: options.styles && this._mapStyleOptions(options.styles),\n        };\n        const events = {\n            blur: this._handleBlur,\n            focus: this._handleFocus,\n            cardTypeChange: this._handleCardTypeChange,\n            validityChange: this._handleValidityChange,\n            inputSubmitRequest: this._handleInputSubmitRequest,\n        };\n\n        await this._paypalCommercePaymentProcessor.renderHostedFields(cartId, params, events);\n\n        if (this._isPaypalCommerceFormFieldsMap(options.fields)) {\n            this._cardNameField = new PaypalCommerceRegularField(\n                options.fields.cardName,\n                options.styles\n            );\n            this._cardNameField.attach();\n        }\n    }\n\n    async submit(is3dsEnabled?: boolean): Promise<PaypalCommerceHostedFieldsApprove> {\n        this.validate();\n        const options: PaypalCommerceHostedFieldsSubmitOptions = {\n            cardholderName: this._cardNameField?.getValue(),\n            contingencies: is3dsEnabled ? ['3D_SECURE'] : undefined,\n        };\n\n        const result = await this._paypalCommercePaymentProcessor.submitHostedFields(options);\n\n        if (is3dsEnabled && (result.liabilityShift === 'NO' || result.liabilityShift === 'UNKNOWN')) {\n            throw new PaymentMethodFailedError('Failed authentication. Please try to authorize again.');\n        }\n\n        return result;\n    }\n\n    validate(): void {\n        const { isValid, fields } = this._paypalCommercePaymentProcessor.getHostedFieldsValidationState();\n\n        if (isValid) {\n            return;\n        }\n\n        const errors = this._mapValidationErrors(fields);\n\n        this._formOptions?.onValidate?.({\n            errors,\n            isValid: false,\n        });\n\n        throw new PaymentInvalidFormError(errors as PaymentInvalidFormErrorDetails);\n    }\n\n    deinitialize(): void {\n        this._paypalCommercePaymentProcessor.deinitialize();\n    }\n\n    private _mapFieldOptions(fields: PaypalCommerceFormFieldsMap | PaypalCommerceStoredCardFieldsMap): PaypalCommerceHostedFieldsRenderOptions['fields'] {\n        if (this._isPaypalCommerceFormFieldsMap(fields)) {\n            return omitBy({\n                number: {\n                    selector: `#${fields.cardNumber.containerId}`,\n                    placeholder: fields.cardNumber.placeholder,\n                },\n                expirationDate: {\n                    selector: `#${fields.cardExpiry.containerId}`,\n                    placeholder: fields.cardExpiry.placeholder,\n                },\n                cvv: fields.cardCode && {\n                    selector: `#${fields.cardCode.containerId}`,\n                    placeholder: fields.cardCode.placeholder,\n                },\n            }, isNil);\n        }\n\n        return omitBy({\n            number: fields.cardNumberVerification && {\n                selector: `#${fields.cardNumberVerification.containerId}`,\n                placeholder: fields.cardNumberVerification.placeholder,\n            },\n            cvv: fields.cardCodeVerification && {\n                selector: `#${fields.cardCodeVerification.containerId}`,\n                placeholder: fields.cardCodeVerification.placeholder,\n            },\n        }, isNil);\n    }\n\n    private _mapStyleOptions(options: PaypalCommerceFormFieldStylesMap): PaypalCommerceHostedFieldsRenderOptions['styles'] {\n        const mapStyles = (styles: PaypalCommerceFormFieldStyles = {}) => {\n            return (Object.keys(styles) as Array<keyof PaypalCommerceFormFieldStyles>).reduce((updatedStyles, key) =>\n                styles[key] ?  { ...updatedStyles, [kebabCase(key)]: styles[key] } : updatedStyles\n            , {});\n        };\n\n        return {\n            input: mapStyles(options.default),\n            '.invalid': mapStyles(options.error),\n            ':focus': mapStyles(options.focus),\n        };\n    }\n\n    private _isPaypalCommerceFormFieldsMap(fields: PaypalCommerceFormFieldsMap | PaypalCommerceStoredCardFieldsMap): fields is PaypalCommerceFormFieldsMap {\n        return !!(fields as PaypalCommerceFormFieldsMap).cardNumber;\n    }\n\n    private _mapFieldType(type: string): PaypalCommerceFormFieldType {\n        switch (type) {\n            case 'number':\n                return this._type === PaypalCommerceHostedFormType.StoredCardVerification ?\n                    PaypalCommerceFormFieldType.CardNumberVerification :\n                    PaypalCommerceFormFieldType.CardNumber;\n\n            case 'expirationDate':\n                return PaypalCommerceFormFieldType.CardExpiry;\n\n            case 'cvv':\n                return this._type === PaypalCommerceHostedFormType.StoredCardVerification ?\n                    PaypalCommerceFormFieldType.CardCodeVerification :\n                    PaypalCommerceFormFieldType.CardCode;\n\n            default:\n                throw new Error('Unexpected field type');\n        }\n    }\n\n    private _mapValidationErrors(\n        fields: PaypalCommerceHostedFieldsState['fields']\n    ): PaypalCommerceFormFieldValidateEventData['errors'] {\n        return (Object.keys(fields) as Array<keyof PaypalCommerceHostedFieldsState['fields']>)\n            .reduce((result, fieldKey) => ({\n                ...result,\n                [this._mapFieldType(fieldKey)]: fields[fieldKey]?.isValid ? undefined : [\n                    this._createInvalidError(this._mapFieldType(fieldKey)),\n                ],\n            }), {});\n    }\n\n    private _createInvalidError(fieldType: PaypalCommerceFormFieldType): PaypalCommerceFormFieldValidateErrorData {\n        switch (fieldType) {\n            case PaypalCommerceFormFieldType.CardCodeVerification:\n                return {\n                    fieldType,\n                    message: 'Invalid card code',\n                    type: 'invalid_card_code',\n                };\n\n            case PaypalCommerceFormFieldType.CardNumberVerification:\n                return {\n                    fieldType,\n                    message: 'Invalid card number',\n                    type: 'invalid_card_number',\n                };\n\n            case PaypalCommerceFormFieldType.CardCode:\n                return {\n                    fieldType,\n                    message: 'Invalid card code',\n                    type: 'invalid_card_code',\n                };\n\n            case PaypalCommerceFormFieldType.CardExpiry:\n                return {\n                    fieldType,\n                    message: 'Invalid card expiry',\n                    type: 'invalid_card_expiry',\n                };\n\n            case PaypalCommerceFormFieldType.CardNumber:\n                return {\n                    fieldType,\n                    message: 'Invalid card number',\n                    type: 'invalid_card_number',\n                };\n\n            default:\n                return {\n                    fieldType,\n                    message: 'Invalid field',\n                    type: 'invalid',\n                };\n        }\n    }\n\n    private _handleBlur: (event: PaypalCommerceHostedFieldsState) => void = event => {\n        this._formOptions?.onBlur?.({\n            fieldType: this._mapFieldType(event.emittedBy),\n        });\n    };\n\n    private _handleFocus: (event: PaypalCommerceHostedFieldsState) => void = event => {\n        this._formOptions?.onFocus?.({\n            fieldType: this._mapFieldType(event.emittedBy),\n        });\n    };\n\n    private _handleCardTypeChange: (event: PaypalCommerceHostedFieldsState) => void = event => {\n        this._formOptions?.onCardTypeChange?.({\n            cardType: event.cards[0]?.type,\n        });\n    };\n\n    private _handleInputSubmitRequest: (event: PaypalCommerceHostedFieldsState) => void = event => {\n        this._formOptions?.onEnter?.({\n            fieldType: this._mapFieldType(event.emittedBy),\n        });\n    };\n\n    private _handleValidityChange: (event: PaypalCommerceHostedFieldsState) => void = event => {\n        this._formOptions?.onValidate?.({\n            isValid: (Object.keys(event.fields) as Array<keyof PaypalCommerceHostedFieldsState['fields']>)\n                .every(key => event.fields[key]?.isValid),\n            errors: this._mapValidationErrors(event.fields),\n        });\n    };\n\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { MollieClient, MollieHostWindow } from './mollie';\n\nexport default class MollieScriptLoader {\n    constructor(\n        private _scriptLoader: ScriptLoader,\n        private _window: Window = window\n    ) {\n    }\n\n    _isMollieWindow(window: Window): window is MollieHostWindow {\n        const mollieWindow: MollieHostWindow = window as MollieHostWindow;\n\n        return !!mollieWindow.Mollie;\n    }\n\n    async load(merchantId: string, locale: string, testmode: boolean): Promise<MollieClient> {\n        await this._scriptLoader.loadScript('https://js.mollie.com/v1/mollie.js');\n\n        if (!this._isMollieWindow(this._window)) {\n            throw new PaymentMethodClientUnavailableError();\n        }\n\n        return this._window.Mollie(merchantId, {\n            locale,\n            testmode,\n        });\n    }\n}\n","import { map } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError , MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport MonerisStylingProps,  { MoneriesHostedFieldsQueryParams, MonerisInitializationData, MonerisResponseData } from './moneris';\n\nconst IFRAME_NAME = 'moneris-payment-iframe';\nconst RESPONSE_SUCCESS_CODE = '001';\n\nexport default class MonerisPaymentStrategy implements PaymentStrategy {\n    private _iframe?: HTMLIFrameElement;\n    private _windowEventListener?: (response: MessageEvent) => void;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _storeCreditActionCreator: StoreCreditActionCreator\n    ) {}\n\n    initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n\n        const { moneris: monerisOptions } = options;\n        const { config, initializationData } = state.paymentMethods.getPaymentMethodOrThrow(options.methodId);\n\n        if (!monerisOptions) {\n            throw new InvalidArgumentError('Unable to initialize payment because \"options.moneris\" argument is not provided.');\n        }\n\n        if (!initializationData?.profileId) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        if (!this._iframe) {\n            this._iframe = this._createIframe(monerisOptions.containerId, initializationData, !!config.testMode);\n        }\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    async execute(payload: OrderRequestBody, options?: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { payment , ...order } = payload;\n        const { paymentMethods: { getPaymentMethodOrThrow } } = this._store.getState();\n\n        if (!payment) {\n            throw new PaymentArgumentInvalidError(['payment']);\n        }\n\n        const paymentMethod = getPaymentMethodOrThrow(payment.methodId);\n        const testMode = paymentMethod.config.testMode;\n\n        const { isStoreCreditApplied: useStoreCredit } = this._store.getState().checkout.getCheckoutOrThrow();\n\n        if (useStoreCredit !== undefined) {\n            await this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(useStoreCredit));\n        }\n\n        await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n        const nonce = await new Promise<string | undefined>((resolve, reject) => {\n            if (!this._iframe) {\n                throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n            }\n\n            const frameref = this._iframe.contentWindow;\n\n            frameref?.postMessage('tokenize', this._monerisURL(!!testMode));\n\n            this._windowEventListener = (response: MessageEvent) => {\n                try {\n                    resolve(this._handleMonerisResponse(response));\n                } catch (error) {\n                    reject(error);\n                }\n            };\n\n            window.addEventListener('message', this._windowEventListener);\n        });\n\n        if (nonce !== undefined) {\n            return this._store.dispatch(this._paymentActionCreator.submitPayment({\n                methodId: payment.methodId,\n                paymentData: { nonce },\n            }));\n        }\n\n        return this._store.getState();\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        if (this._windowEventListener) {\n            window.removeEventListener('message', this._windowEventListener);\n            this._windowEventListener = undefined;\n        }\n\n        if (this._iframe && this._iframe.parentNode) {\n            this._iframe.parentNode.removeChild(this._iframe);\n            this._iframe = undefined;\n        }\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    private _createIframe(containerId: string, initializationData: MonerisInitializationData, testMode: boolean, style?: MonerisStylingProps): HTMLIFrameElement {\n        const container = document.getElementById(containerId);\n\n        if (!container) {\n            throw new InvalidArgumentError('Unable to create iframe without valid container ID.');\n        }\n\n        const iframe = document.createElement('iframe');\n        const monerisQueryParams: MoneriesHostedFieldsQueryParams = {\n            id: initializationData.profileId,\n            pmmsg: true,\n            display_labels: 1,\n            enable_exp: 1,\n            enable_cvd: 1,\n            css_body: style?.cssBody || 'background:transparent;',\n            css_textbox: style?.cssTextbox || 'border-width:2px;',\n            css_textbox_pan: style?.cssTextboxPan || 'width:140px;',\n            css_textbox_exp: style?.cssTextboxExpiry || 'width:40px;',\n            css_textbox_cvd: style?.csstexboxCvd || 'width:40px',\n            pan_label: initializationData?.creditCardLabel || 'Credit Card Number',\n            exp_label: initializationData?.expiryDateLabel || 'Expiration',\n            cvd_label: initializationData?.cvdLabel || 'CVD',\n        };\n\n        const queryString = map(monerisQueryParams, (value, key) => `${key}=${value}`).join('&');\n\n        iframe.name = IFRAME_NAME;\n        iframe.id = IFRAME_NAME;\n        iframe.style.border = 'none';\n        iframe.src = `${ this._monerisURL(testMode) }?${queryString}`;\n\n        container.appendChild(iframe);\n\n        return iframe;\n    }\n\n    private _handleMonerisResponse(response: MessageEvent): string {\n        const monerisResponse: MonerisResponseData = JSON.parse(response.data);\n\n        if (monerisResponse.responseCode[0] !== RESPONSE_SUCCESS_CODE) {\n            throw new Error(monerisResponse.errorMessage);\n        }\n\n        return monerisResponse.dataKey;\n    }\n\n    private _monerisURL(testMode: boolean): string {\n        return `https://${ testMode ? 'esqa' : 'www3' }.moneris.com/HPPtoken/index.php`;\n    }\n}\n","import { omit } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nexport default class NoPaymentDataRequiredPaymentStrategy implements PaymentStrategy {\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator\n    ) {}\n\n    execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        return this._store.dispatch(\n            this._orderActionCreator.submitOrder(omit(orderRequest, 'payment'), options)\n        );\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    initialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nexport default class OfflinePaymentStrategy implements PaymentStrategy {\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator\n    ) {}\n\n    execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const action = this._orderActionCreator.submitOrder({\n            ...payload,\n            payment: payload.payment ? { methodId: payload.payment.methodId } : undefined,\n        }, options);\n\n        return this._store.dispatch(action);\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    initialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport { HostedInstrument, VaultedInstrument } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport PaymentStrategy from '../payment-strategy';\n\nexport default class OffsitePaymentStrategy implements PaymentStrategy {\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator\n    ) {}\n\n    execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = payload;\n        const orderPayload = this._shouldSubmitFullPayload(payment) ? payload : order;\n        const paymentData = payment && payment.paymentData;\n        const instrumentId = paymentData && (paymentData as VaultedInstrument).instrumentId || undefined;\n        const shouldSaveInstrument = paymentData && (paymentData as HostedInstrument).shouldSaveInstrument || undefined;\n        const shouldSetAsDefaultInstrument = paymentData && (paymentData as HostedInstrument).shouldSetAsDefaultInstrument || undefined;\n\n        if (!payment) {\n            throw new PaymentArgumentInvalidError(['payment']);\n        }\n\n        const { methodId, gatewayId } = payment;\n\n        return this._store.dispatch(this._orderActionCreator.submitOrder(orderPayload, options))\n            .then(() =>\n            this._store.dispatch(this._paymentActionCreator.initializeOffsitePayment({\n                    methodId,\n                    gatewayId,\n                    instrumentId,\n                    shouldSaveInstrument,\n                    shouldSetAsDefaultInstrument,\n                }))\n            );\n    }\n\n    finalize(options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n        const order = state.order.getOrder();\n        const status = state.payment.getPaymentStatus();\n\n        if (order && (status === paymentStatusTypes.ACKNOWLEDGE || status === paymentStatusTypes.FINALIZE)) {\n            return this._store.dispatch(this._orderActionCreator.finalizeOrder(order.orderId, options));\n        }\n\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    initialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n\n    private _shouldSubmitFullPayload(payment?: OrderPaymentRequestBody): boolean {\n        // FIXME: A temporary workaround to support offsite payment methods\n        // where their return URL needs to be provided by the core app.\n        if (!payment) {\n            return false;\n        }\n\n        return payment.gatewayId === 'adyen' || payment.gatewayId === 'barclaycard' || payment.methodId === 'ccavenuemars';\n    }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { ACKNOWLEDGE } from '../../payment-status-types';\nimport { CardinalThreeDSecureFlow } from '../cardinal';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class PaypalProPaymentStrategy extends CreditCardPaymentStrategy {\n    constructor(\n        store: CheckoutStore,\n        orderActionCreator: OrderActionCreator,\n        paymentActionCreator: PaymentActionCreator,\n        hostedFormFactory: HostedFormFactory,\n        private _threeDSecureFlow: CardinalThreeDSecureFlow\n    ) {\n        super(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            hostedFormFactory\n        );\n    }\n\n    async initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        await super.initialize(options);\n\n        const { paymentMethods: { getPaymentMethodOrThrow } } = this._store.getState();\n        const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n        if (paymentMethod.config.is3dsEnabled) {\n            await this._threeDSecureFlow.prepare(paymentMethod);\n        }\n\n        return this._store.getState();\n    }\n\n    execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment: { methodId = '' } = {} } = payload;\n        const { payment: { getPaymentStatus }, paymentMethods: { getPaymentMethodOrThrow } } = this._store.getState();\n\n        if (getPaymentStatus() === ACKNOWLEDGE) {\n            return this._store.dispatch(\n                this._orderActionCreator.submitOrder({\n                    ...payload,\n                    payment: { methodId },\n                }, options)\n            );\n        }\n\n        if (getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n            return this._threeDSecureFlow.start(\n                super.execute.bind(this),\n                payload,\n                options,\n                this._hostedForm\n            );\n        }\n\n        return super.execute(payload, options);\n    }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentMethod from '../../payment-method';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport PaymentStrategy from '../payment-strategy';\n\nimport PaypalScriptLoader from './paypal-script-loader';\nimport { PaypalHostWindow, PaypalSDK } from './paypal-sdk';\n\nexport default class PaypalExpressPaymentStrategy implements PaymentStrategy {\n    private _paypalSdk?: PaypalSDK;\n    private _paymentMethod?: PaymentMethod;\n    private _useRedirectFlow: boolean = false;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator,\n        private _scriptLoader: PaypalScriptLoader,\n        private _window: PaypalHostWindow = window\n    ) {}\n\n    initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n\n        this._paymentMethod = state.paymentMethods.getPaymentMethod(options.methodId);\n        this._useRedirectFlow = (options.paypalexpress && options.paypalexpress.useRedirectFlow) === true;\n\n        if (!this._isInContextEnabled()) {\n            return Promise.resolve(this._store.getState());\n        }\n\n        return this._scriptLoader.loadPaypal()\n            .then(paypal => {\n                this._paypalSdk = paypal;\n\n                if (!this._paymentMethod || !this._paymentMethod.config.merchantId) {\n                    throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n                }\n\n                this._paypalSdk.checkout.setup(this._paymentMethod.config.merchantId, {\n                    button: 'paypal-button',\n                    environment: this._paymentMethod.config.testMode ? 'sandbox' : 'production',\n                });\n            })\n            .then(() => this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        if (this._isInContextEnabled() && this._paypalSdk) {\n            this._paypalSdk.checkout.closeFlow();\n            this._paypalSdk = undefined;\n        }\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const paypal = this._paypalSdk;\n\n        if (this._isAcknowledgedOrFinalized()) {\n            return this._store.dispatch(this._orderActionCreator.submitOrder(payload, options));\n        }\n\n        if (!this._isInContextEnabled() || this._useRedirectFlow) {\n            return this._store.dispatch(this._orderActionCreator.submitOrder(payload, options))\n                .then(state => {\n                    const redirectUrl = state.payment.getPaymentRedirectUrl();\n\n                    if (redirectUrl) {\n                        this._window.top.location.href = redirectUrl;\n                    }\n\n                    // We need to hold execution so the consumer does not redirect us somewhere else\n                    return new Promise<never>(() => {});\n                });\n        }\n\n        if (!paypal) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        paypal.checkout.initXO();\n\n        return this._store.dispatch(this._orderActionCreator.submitOrder(payload, options))\n            .then(state => {\n                const redirectUrl = state.payment.getPaymentRedirectUrl();\n\n                if (redirectUrl) {\n                    paypal.checkout.startFlow(redirectUrl);\n                }\n\n                // We need to hold execution so the consumer does not redirect us somewhere else\n                return new Promise<never>(() => {});\n            })\n            .catch(error => {\n                paypal.checkout.closeFlow();\n\n                return Promise.reject(error);\n            });\n    }\n\n    finalize(options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n        const order = state.order.getOrder();\n\n        if (order && this._isAcknowledgedOrFinalized()) {\n            return this._store.dispatch(this._orderActionCreator.finalizeOrder(order.orderId, options));\n        }\n\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    private _isAcknowledgedOrFinalized(): boolean {\n        const state = this._store.getState();\n\n        return state.payment.getPaymentStatus() === paymentStatusTypes.ACKNOWLEDGE\n            || state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE;\n    }\n\n    private _isInContextEnabled(): boolean {\n        return !!(this._paymentMethod && this._paymentMethod.config.merchantId);\n    }\n}\n","import { Cart } from '../../../cart';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { PaypalCommerceCreditCardPaymentInitializeOptions, PaypalCommerceHostedForm, PaypalCommerceInitializationData, PaypalCommercePaymentInitializeOptions, PaypalCommerceScriptParams } from './index';\n\nexport default class PaypalCommerceCreditCardPaymentStrategy implements PaymentStrategy {\n    constructor(\n        private _store: CheckoutStore,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _paypalCommerceHostedForm: PaypalCommerceHostedForm,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator\n    ) {}\n\n    async initialize({ methodId, paypalcommerce }: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        if (!paypalcommerce || !this._isPaypalCommerceOptionsPayments(paypalcommerce)) {\n            throw new InvalidArgumentError('Unable to proceed because \"options.paypalcommerce.form\" argument is not provided.');\n        }\n\n        const { paymentMethods: { getPaymentMethodOrThrow }, cart: { getCartOrThrow } } = await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId));\n        const { clientToken, initializationData } = getPaymentMethodOrThrow(methodId);\n\n        if (!clientToken) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        const { id: cartId, currency: { code: currencyCode } } = getCartOrThrow();\n        const paramsScript = this._getOptionsScript(initializationData, currencyCode, clientToken);\n\n        await this._paypalCommerceHostedForm.initialize(paypalcommerce.form, cartId, paramsScript);\n\n        return this._store.getState();\n    }\n\n    async execute(payload: OrderRequestBody, options: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = payload;\n\n        if (!payment) {\n            throw new PaymentArgumentInvalidError(['payment']);\n        }\n\n        this._paypalCommerceHostedForm.validate();\n\n        const { paymentMethods: { getPaymentMethodOrThrow } } = await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(payment.methodId));\n        const { orderId } = await this._paypalCommerceHostedForm.submit(getPaymentMethodOrThrow(payment.methodId).config.is3dsEnabled);\n\n        await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n        const paymentData =  {\n            formattedPayload: {\n                vault_payment_instrument: null,\n                set_as_default_stored_instrument: null,\n                device_info: null,\n                paypal_account: {\n                    order_id: orderId,\n                },\n            },\n        };\n\n        return this._store.dispatch(this._paymentActionCreator.submitPayment({ ...payment, paymentData }));\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        this._paypalCommerceHostedForm.deinitialize();\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    private _isPaypalCommerceOptionsPayments(options: PaypalCommercePaymentInitializeOptions | PaypalCommerceCreditCardPaymentInitializeOptions): options is PaypalCommerceCreditCardPaymentInitializeOptions {\n        return !!(options as PaypalCommerceCreditCardPaymentInitializeOptions).form;\n    }\n\n    private _getOptionsScript(initializationData: PaypalCommerceInitializationData, currencyCode: Cart['currency']['code'], clientToken: string): PaypalCommerceScriptParams {\n        const { clientId, intent, merchantId } = initializationData;\n\n        return {\n            'client-id': clientId,\n            'merchant-id': merchantId,\n            'data-client-token': clientToken,\n            components: ['hosted-fields'],\n            commit: true,\n            currency: currencyCode,\n            intent,\n        };\n    }\n}\n","import { InvalidArgumentError } from '../../../common/error/errors';\n\nimport { PaypalCommerceFormFieldOptions, PaypalCommerceFormFieldStyles, PaypalCommerceFormFieldStylesMap } from './index';\n\nexport default class PaypalCommerceRegularField {\n    private _input: HTMLInputElement;\n\n    constructor(\n        private _options: PaypalCommerceFormFieldOptions,\n        private _styles?: PaypalCommerceFormFieldStylesMap\n    ) {\n        this._input = document.createElement('input');\n        this._input.style.backgroundColor = 'transparent';\n        this._input.style.border = '0';\n        this._input.style.display = 'block';\n        this._input.style.height = '100%';\n        this._input.style.margin = '0';\n        this._input.style.outline = 'none';\n        this._input.style.padding = '0';\n        this._input.style.width = '100%';\n        this._input.placeholder = this._options.placeholder || '';\n\n        this._input.addEventListener('blur', this._handleBlur);\n        this._input.addEventListener('focus', this._handleFocus);\n\n        this._applyStyles(this._styles?.default);\n    }\n\n    getValue(): string {\n        return this._input.value;\n    }\n\n    attach(): void {\n        const container = document.getElementById(this._options.containerId);\n\n        if (!container) {\n            throw new InvalidArgumentError();\n        }\n\n        container.appendChild(this._input);\n    }\n\n    detach(): void {\n        this._input.parentNode?.removeChild(this._input);\n    }\n\n    private _applyStyles(styles?: PaypalCommerceFormFieldStyles): void {\n        if (!styles) {\n            return;\n        }\n\n        const styleKeys = Object.keys(styles) as Array<keyof PaypalCommerceFormFieldStyles>;\n\n        styleKeys.forEach(key => {\n            this._input.style[key] = styles[key] || '';\n        });\n    }\n\n    private _handleBlur: (event: Event) => void = () => {\n        this._applyStyles(this._styles?.default);\n    };\n\n    private _handleFocus: (event: Event) => void = () => {\n        this._applyStyles(this._styles?.focus);\n    };\n}\n","export enum PaymentProcessorType {\n    NONE = 'none',\n    UNSUPPORTED = 'unsupported',\n}\n","import { Cart } from '../../../cart';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, TimeoutError } from '../../../common/error/errors';\nimport { LoadingIndicator } from '../../../common/loading-indicator';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodInvalidError } from '../../errors';\nimport { PaymentStrategyType } from '../../index';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { ApproveDataOptions,\n    ButtonsOptions,\n    ComponentsScriptType,\n    PaypalCommerceCreditCardPaymentInitializeOptions,\n    PaypalCommerceFundingKeyResolver,\n    PaypalCommerceInitializationData,\n    PaypalCommercePaymentInitializeOptions,\n    PaypalCommercePaymentProcessor,\n    PaypalCommerceRequestSender,\n    PaypalCommerceScriptParams } from './index';\n\nconst ORDER_STATUS_APPROVED = 'APPROVED';\nconst ORDER_STATUS_CREATED = 'CREATED';\nconst PAYER_ACTION_REQUIRED = 'PAYER_ACTION_REQUIRED';\nconst POLLING_INTERVAL = 3000;\nconst POLLING_MAX_TIME = 600000;\n\nexport default class PaypalCommercePaymentStrategy implements PaymentStrategy {\n    private _orderId?: string;\n    private _isAPM?: boolean;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _paypalCommercePaymentProcessor: PaypalCommercePaymentProcessor,\n        private _paypalCommerceFundingKeyResolver: PaypalCommerceFundingKeyResolver,\n        private _paypalCommerceRequestSender: PaypalCommerceRequestSender,\n        private _loadingIndicator: LoadingIndicator,\n        private _pollingInterval?: number,\n        private _pollingTimer = 0\n    ) {}\n\n    async initialize({ gatewayId, methodId, paypalcommerce }: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const {\n            paymentMethods: { getPaymentMethodOrThrow },\n            cart: { getCartOrThrow },\n            billingAddress: { getBillingAddressOrThrow },\n        } = this._store.getState();\n\n        const { initializationData } = getPaymentMethodOrThrow(methodId, gatewayId);\n        const { orderId, buttonStyle, shouldRenderFields } = initializationData ?? {};\n        this._isAPM = gatewayId === PaymentStrategyType.PAYPAL_COMMERCE_ALTERNATIVE_METHODS;\n\n        if (orderId) {\n            this._orderId = orderId;\n\n            return this._store.getState();\n        }\n\n        if (!paypalcommerce) {\n            throw new InvalidArgumentError('Unable to initialize payment because \"options.paypalcommerce\" argument is not provided.');\n        }\n\n        if (!this._isPaypalCommerceOptionsPayments(paypalcommerce)) {\n            throw new InvalidArgumentError('Unable to initialize payment because \"options.paypalcommerce\" argument should contain \"container\", \"onRenderButton\", \"submitForm\".');\n        }\n\n        const { container, apmFieldsContainer, apmFieldsStyles, onRenderButton, submitForm, onValidate } = paypalcommerce;\n        const { id: cartId, currency: { code: currencyCode } } = getCartOrThrow();\n        const { firstName, lastName, email } = getBillingAddressOrThrow();\n\n        const loadingIndicatorContainerId = container.split('#')[1];\n\n        const paramsScript = this._getOptionsScript(initializationData, currencyCode, this._isAPM ? methodId : undefined);\n        const buttonParams: ButtonsOptions = {\n            style: buttonStyle,\n            onApprove: data => {\n                this._deinitializePollingTimer(gatewayId);\n                this._tokenizePayment(data, submitForm);\n                this._loadingIndicator?.hide();\n\n            },\n            onClick: async (_, actions) => {\n                this._initializePollingMechanism(submitForm, gatewayId, methodId, paypalcommerce);\n\n                const onValidationPassed = () => {\n                    this._loadingIndicator?.show(loadingIndicatorContainerId);\n\n                    return actions.resolve();\n                };\n\n                return onValidate(onValidationPassed, actions.reject);\n            },\n            onCancel: () => {\n                this._deinitializePollingTimer(gatewayId);\n                this._loadingIndicator?.hide();\n            },\n            onError: (e: Error) => {\n                this._deinitializePollingTimer(gatewayId);\n                this._loadingIndicator?.hide();\n                paypalcommerce.onError?.(e);\n            },\n        };\n\n        await this._paypalCommercePaymentProcessor.initialize(paramsScript, undefined, gatewayId);\n\n        const fundingKey = this._paypalCommerceFundingKeyResolver.resolve(methodId, gatewayId);\n\n        if (this._isAPM && shouldRenderFields)  {\n            const fullName = `${firstName} ${lastName}`;\n            if (!apmFieldsContainer) {\n                throw new InvalidArgumentError('Unable to initialize payment because \"options.paypalcommerce\" argument should contain \"apmFieldsContainer\".');\n            }\n            this._paypalCommercePaymentProcessor.renderFields({\n                apmFieldsContainer,\n                fundingKey,\n                apmFieldsStyles,\n                fullName,\n                email,\n            });\n        }\n\n        this._paypalCommercePaymentProcessor.renderButtons(cartId, container, buttonParams, {\n            onRenderButton,\n            fundingKey,\n            paramsForProvider: {isCheckout: true},\n        });\n\n        return this._store.getState();\n    }\n\n    async execute(payload: OrderRequestBody, options: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = payload;\n\n        if (!payment) {\n            throw new PaymentArgumentInvalidError(['payment']);\n        }\n\n        if (!this._orderId) {\n            throw new PaymentMethodInvalidError();\n        }\n\n        const paymentData =  {\n            formattedPayload: {\n                vault_payment_instrument: null,\n                set_as_default_stored_instrument: null,\n                device_info: null,\n                method_id: payment.methodId,\n                paypal_account: {\n                    order_id: this._orderId,\n                },\n            },\n        };\n        await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n        return this._store.dispatch(this._paymentActionCreator.submitPayment({ ...payment, paymentData }));\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    async deinitialize({gatewayId}: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        this._deinitializePollingTimer(gatewayId);\n        this._orderId = undefined;\n        this._paypalCommercePaymentProcessor.deinitialize();\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    private _initializePollingMechanism(submitForm: () => void, gatewayId?: string, methodId?: any, paypalcommerce?: any ) {\n        if (!this._isAPM)  {\n            this._loadingIndicator?.hide();\n\n            return;\n        }\n\n        this._pollingInterval = window.setTimeout(async () => {\n            try {\n                this._pollingTimer += POLLING_INTERVAL;\n\n                const { status } = await this._paypalCommerceRequestSender.getOrderStatus();\n\n                if (status === ORDER_STATUS_APPROVED) {\n                    this._deinitializePollingTimer(gatewayId);\n                    this._tokenizePayment({ orderID: this._paypalCommercePaymentProcessor.getOrderId() }, submitForm);\n                } else if (\n                    (status === ORDER_STATUS_CREATED || status === PAYER_ACTION_REQUIRED) &&\n                    this._pollingTimer < POLLING_MAX_TIME\n                ) {\n                    this._initializePollingMechanism(submitForm, gatewayId, methodId, paypalcommerce);\n                } else {\n                    this._reinitializeButtons({ gatewayId, methodId, paypalcommerce });\n                    this._loadingIndicator?.hide();\n                    throw new TimeoutError();\n                }\n            } catch (e) {\n                this._deinitializePollingTimer(gatewayId);\n                paypalcommerce.onError?.(e);\n            }\n        }, POLLING_INTERVAL);\n    }\n\n    private _reinitializeButtons({ gatewayId, methodId, paypalcommerce }: PaymentInitializeOptions) {\n        this.deinitialize({methodId, gatewayId});\n        this.initialize({ gatewayId, methodId, paypalcommerce });\n    }\n\n    private _deinitializePollingTimer(gatewayId?: string) {\n        if (gatewayId === PaymentStrategyType.PAYPAL_COMMERCE_ALTERNATIVE_METHODS) {\n            clearTimeout(this._pollingInterval);\n            this._pollingTimer = 0;\n        }\n    }\n\n    private _isPaypalCommerceOptionsPayments(options: PaypalCommercePaymentInitializeOptions | PaypalCommerceCreditCardPaymentInitializeOptions): options is PaypalCommercePaymentInitializeOptions {\n        return !!(options as PaypalCommercePaymentInitializeOptions).container;\n    }\n\n    private _tokenizePayment({ orderID }: ApproveDataOptions, submitForm: () => void) {\n        this._orderId = orderID;\n        submitForm();\n    }\n\n    private _getOptionsScript(\n        initializationData: PaypalCommerceInitializationData,\n        currencyCode: Cart['currency']['code'],\n        apmMehodId?: string\n    ): PaypalCommerceScriptParams {\n        const { clientId, intent, merchantId } = initializationData;\n\n        const returnObject = {\n            'client-id': clientId,\n            'merchant-id': merchantId,\n            commit: true,\n            currency: currencyCode,\n            intent,\n            components: ['buttons', 'messages', 'fields', 'funding-eligibility'] as ComponentsScriptType,\n            ...(apmMehodId && { 'enable-funding': apmMehodId}),\n        };\n\n        return returnObject;\n    }\n}\n","import PaymentStrategyType from '../../payment-strategy-type';\n\nimport { PaypalCommerceSDKFunding } from './paypal-commerce-sdk';\n\nexport default class PaypalCommerceFundingKeyResolver {\n    resolve(methodId: string, gatewayId?: string): keyof PaypalCommerceSDKFunding {\n        if (methodId === PaymentStrategyType.PAYPAL_COMMERCE) {\n            return 'PAYPAL';\n        }\n\n        if (methodId === PaymentStrategyType.PAYPAL_COMMERCE_CREDIT) {\n            return 'PAYLATER';\n        }\n\n        if (gatewayId === PaymentStrategyType.PAYPAL_COMMERCE_ALTERNATIVE_METHODS) {\n            switch (methodId) {\n                case 'bancontact':\n                    return 'BANCONTACT';\n                case 'giropay':\n                    return 'GIROPAY';\n                case 'p24':\n                    return 'P24';\n                case 'eps':\n                    return 'EPS';\n                case 'ideal':\n                    return 'IDEAL';\n                case 'mybank':\n                    return 'MYBANK';\n                case 'sofort':\n                    return 'SOFORT';\n                case 'blik':\n                    return 'BLIK';\n                case 'trustly':\n                    return 'TRUSTLY';\n                case 'venmo':\n                    return 'VENMO';\n            }\n        }\n\n        throw new Error('Unable to resolve funding key');\n    }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { overSome } from 'lodash';\n\nimport { PaymentsAPIResponse } from '../../ppsdk-payments-api-response';\n\nimport { handleRedirect, isRedirect, Redirect } from './redirect';\n\nexport type Continue = Redirect;\n\nconst isAnyContinue = overSome(isRedirect);\n\nexport const isContinue = (body: PaymentsAPIResponse['body']): body is Continue => isAnyContinue(body);\n\nexport class ContinueHandler {\n    constructor(\n        private _formPoster: FormPoster\n    ) {}\n\n    handle(body: Continue): Promise<void> {\n        switch (body.code) {\n            case 'redirect':\n                return handleRedirect(body.parameters, this._formPoster);\n        }\n    }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { get, isObject, isString, isUndefined, noop } from 'lodash';\n\nimport { PaymentsAPIResponse } from '../../ppsdk-payments-api-response';\n\ninterface Parameters {\n    url: string;\n    formFields?: Record<string, string | number | boolean>;\n}\n\nexport interface Redirect {\n    type: 'continue';\n    code: 'redirect';\n    parameters: Parameters;\n}\n\nconst isParameters = (x: unknown): x is Parameters => {\n    const formFields = get(x, 'formFields');\n\n    return (\n        isString(get(x, 'url')) &&\n        (isUndefined(formFields) || isObject(formFields))\n    );\n};\n\nexport const isRedirect = (body: PaymentsAPIResponse['body']): body is Redirect => (\n    get(body, 'type') === 'continue' &&\n    get(body, 'code') === 'redirect' &&\n    isParameters(get(body, 'parameters'))\n);\n\nexport const handleRedirect = ({ url, formFields }: Parameters, formPoster: FormPoster): Promise<never> => {\n    if (formFields) {\n        formPoster.postForm(url, formFields);\n    } else {\n        window.location.replace(url);\n    }\n\n    return new Promise(noop);\n};\n","import { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nimport { isContinue, ContinueHandler } from './continue-handler';\nimport { handleError, isError } from './error';\nimport { handleFailed, isFailed } from './failed';\nimport { handleServerError, isServerError } from './server-error';\nimport { handleSuccess, isSuccess } from './success';\nimport { handleUnsupported } from './unsupported';\n\nexport class StepHandler {\n    constructor(\n        private  _continueHandler: ContinueHandler\n    ) {}\n\n    handle(response: PaymentsAPIResponse): Promise<void> {\n        const { body, status } = response;\n\n        if (isServerError(status)) {\n            return handleServerError(response);\n        }\n\n        if (isSuccess(body)) {\n            return handleSuccess();\n        }\n\n        if (isContinue(body)) {\n            return this._continueHandler.handle(body);\n        }\n\n        if (isFailed(response)) {\n            return handleFailed(response);\n        }\n\n        if (isError(response)) {\n            return handleError(response);\n        }\n\n        return handleUnsupported(response);\n    }\n}\n","import { RequestError } from '../../../../common/error/errors';\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nexport const isServerError = (status: number): boolean =>\n    status < 200 || status >= 400;\n\nexport const handleServerError = (response: PaymentsAPIResponse) =>\n    Promise.reject(new RequestError(response));\n","import { get } from 'lodash';\n\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nexport interface Success {\n    type: 'success';\n}\n\nexport const isSuccess = (body: PaymentsAPIResponse['body']): body is Success =>\n    get(body, 'type') === 'success';\n\nexport const handleSuccess = () => Promise.resolve();\n","import { get, isString } from 'lodash';\n\nimport { RequestError } from '../../../../common/error/errors';\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nexport interface FailedResponse extends PaymentsAPIResponse {\n    body: {\n        type: 'failed';\n        code: string;\n    };\n}\n\nexport const isFailed = (response: PaymentsAPIResponse): response is FailedResponse =>\n    get(response.body, 'type') === 'failed' &&\n    isString(get(response.body, 'code'));\n\nconst toRequestErrorFormat = (failedResponse: FailedResponse) => ({\n    ...failedResponse,\n    body: {\n        errors: [\n            { code: failedResponse.body.code },\n        ],\n    },\n});\n\nexport const handleFailed = (response: FailedResponse): Promise<void> =>\n    Promise.reject(new RequestError(toRequestErrorFormat(response)));\n","import { get } from 'lodash';\n\nimport { RequestError } from '../../../../common/error/errors';\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nexport interface ErrorResponse extends PaymentsAPIResponse  {\n    body: {\n        type: 'error';\n    };\n}\n\nexport const isError = (response: PaymentsAPIResponse): response is ErrorResponse =>\n    get(response.body, 'type') === 'error';\n\nexport const handleError = (response: ErrorResponse) =>\n    Promise.reject(new RequestError(response));\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { ContinueHandler } from './continue-handler';\nimport { StepHandler } from './step-handler';\n\nexport const createStepHandler = (formPoster: FormPoster) =>\n    new StepHandler(new ContinueHandler(formPoster));\n","import { CheckoutStore } from '../../../checkout';\nimport { isPPSDKPaymentMethod, PPSDKPaymentMethod } from '../../ppsdk-payment-method';\n\ntype GetPPSDKMethod = (store: CheckoutStore, methodId: string) => PPSDKPaymentMethod | undefined;\n\nexport const getPPSDKMethod: GetPPSDKMethod = (store, methodId) => {\n    const paymentMethod = store.getState().paymentMethods.getPaymentMethod(methodId);\n\n    if (!paymentMethod || !isPPSDKPaymentMethod(paymentMethod)) {\n        return;\n    }\n\n    return paymentMethod;\n};\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { getPPSDKMethod } from './get-ppsdk-payment-method';\nimport { PaymentProcessor } from './ppsdk-payment-processor';\nimport { PaymentProcessorRegistry } from './ppsdk-payment-processor-registry';\nimport { PaymentResumer } from './ppsdk-payment-resumer';\n\nexport class PPSDKStrategy implements PaymentStrategy {\n    private _paymentProcessor?: PaymentProcessor;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentProcessorRegistry: PaymentProcessorRegistry,\n        private _paymentResumer: PaymentResumer\n    ) {}\n\n    async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { bigpayBaseUrl } = this._store.getState().config.getStoreConfigOrThrow().paymentSettings;\n\n        if (!options?.methodId) {\n            throw new InvalidArgumentError('Unable to submit payment because \"options.methodId\" argument is not provided.');\n        }\n\n        const paymentMethod = getPPSDKMethod(this._store, options.methodId);\n\n        const { payment, ...order } = payload;\n        const { _paymentProcessor: paymentProcessor } = this;\n\n        if (!paymentProcessor || !paymentMethod) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n        await paymentProcessor.process({ paymentMethod, payment, bigpayBaseUrl });\n\n        return this._store.getState();\n    }\n\n    async finalize(options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { bigpayBaseUrl } = this._store.getState().config.getStoreConfigOrThrow().paymentSettings;\n\n        if (!options?.methodId) {\n            throw new InvalidArgumentError('Unable to submit payment because \"options.methodId\" argument is not provided.');\n        }\n\n        const paymentId = this._store.getState().order.getPaymentId(options?.methodId);\n\n        if (!paymentId) {\n            throw new OrderFinalizationNotRequiredError();\n        }\n\n        await this._paymentResumer.resume({ paymentId, bigpayBaseUrl });\n\n        return this._store.getState();\n    }\n\n    async initialize(options?: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        if (!options?.methodId) {\n            throw new InvalidArgumentError('Unable to submit payment because \"options.methodId\" argument is not provided.');\n        }\n\n        const paymentMethod = getPPSDKMethod(this._store, options.methodId);\n\n        if (!paymentMethod) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        this._paymentProcessor = this._paymentProcessorRegistry.getByMethod(paymentMethod);\n\n        if (!this._paymentProcessor) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        return this._store.getState();\n    }\n\n    async deinitialize(_options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        return this._store.getState();\n    }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { PaymentProcessor, ProcessorSettings } from '../ppsdk-payment-processor';\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\nimport { StepHandler } from '../step-handler';\n\nexport class NonePaymentProcessor implements PaymentProcessor {\n    constructor(\n        private _requestSender: RequestSender,\n        private _stepHandler: StepHandler\n    ) {}\n\n    process({ paymentMethod, bigpayBaseUrl }: ProcessorSettings) {\n        const paymentMethodId = `${paymentMethod.id}.${paymentMethod.method}`;\n        const body = { payment_method_id: paymentMethodId };\n\n        return this._requestSender.post<PaymentsAPIResponse['body']>(`${bigpayBaseUrl}/payments`, { body })\n            .then(response => this._stepHandler.handle(response));\n    }\n}\n","import { cond, constant, stubTrue } from 'lodash';\n\nimport { Registry } from '../../../common/registry';\nimport { PPSDKPaymentMethod } from '../../ppsdk-payment-method';\n\nimport { isNone } from './initialization-strategies';\nimport { PaymentProcessor } from './ppsdk-payment-processor';\nimport { PaymentProcessorType } from './ppsdk-payment-processor-type';\n\nconst getToken = cond([\n    [isNone, constant(PaymentProcessorType.NONE)],\n    [stubTrue, constant(PaymentProcessorType.UNSUPPORTED)],\n]);\n\nexport class PaymentProcessorRegistry extends Registry<PaymentProcessor | undefined, PaymentProcessorType> {\n    getByMethod(paymentMethod: PPSDKPaymentMethod): PaymentProcessor | undefined {\n        const token = getToken(paymentMethod.initializationStrategy);\n\n        return this.get(token);\n    }\n}\n","export default interface SquarePaymentForm {\n    build(): void;\n    requestCardNonce(): void;\n    setPostalCode(postalCode: string): void;\n}\n\nexport type SquarePaymentFormConstructor = new(options: SquareFormOptions) => SquarePaymentForm;\n\nexport interface SquareFormOptions {\n    applicationId: string;\n    env: string;\n    locationId: string;\n    inputClass?: string;\n    inputStyles?: string[];\n    callbacks?: SquareFormCallbacks;\n    cardNumber: SquareFormElement;\n    cvv: SquareFormElement;\n    expirationDate: SquareFormElement;\n    postalCode: SquareFormElement;\n    masterpass: SquareFormElement;\n}\nexport interface LineItem {\n    label: string;\n    amount: string;\n    pending: boolean;\n}\n\nexport interface SquarePaymentRequest {\n    requestShippingAddress: boolean;\n    requestBillingInfo: boolean;\n    shippingContact?: Contact;\n    countryCode: string;\n    currencyCode: string;\n    lineItems?: LineItem[];\n    total: LineItem;\n}\n\nexport interface NonceGenerationError {\n    type: string;\n    message: string;\n    field: string;\n}\n\nexport interface CardData {\n    card_brand: CardBrand;\n    last_4: number;\n    exp_month: number;\n    exp_year: number;\n    billing_postal_code: string;\n    digital_wallet_type: DigitalWalletType;\n}\n\nexport interface Contact {\n    familyName: string;\n    givenName: string;\n    email: string;\n    country: string;\n    countryName: string;\n    region: string;\n    city: string;\n    addressLines: string[];\n    postalCode: string;\n    phone: string;\n}\n\nexport enum CardBrand {\n    americanExpress = 'AMERICAN_EXPRESS',\n    discover = 'DISCOVER',\n    discoverDiners = 'DISCOVER_DINERS',\n    JCB = 'JCB',\n    masterCard = 'MASTERCARD',\n    unionPay = 'CHINA_UNIONPAY',\n    unknown = 'OTHER_BRAND',\n    visa = 'VISA',\n    squareGift = 'SQUARE_GIFT_CARD',\n}\n\nexport enum DigitalWalletType {\n    applePay = 'APPLEPAY',\n    masterpass = 'MASTERPASS',\n    none = 'NONE',\n}\n\n/**\n * Configures any form element provided by Square payment.\n */\nexport interface SquareFormElement {\n    /**\n     * The ID of the container which the form element should insert into.\n     */\n    elementId: string;\n\n    /**\n     * The placeholder text to use for the form element, if provided.\n     */\n    placeholder?: string;\n}\n\nexport interface SquareFormCallbacks {\n    paymentFormLoaded?(form: SquarePaymentForm): void;\n    unsupportedBrowserDetected?(): void;\n    cardNonceResponseReceived?(\n        errors?: NonceGenerationError[],\n        nonce?: string,\n        cardData?: CardData,\n        billingContact?: Contact,\n        shippingContact?: Contact): void;\n    methodsSupported?(methods: { [key: string]: boolean }): void;\n    createPaymentRequest?(): void;\n}\n\nexport type SquareFormFactory = (options: SquareFormOptions) => SquarePaymentForm;\n","import { InitializationStrategy } from '../../../';\ninterface None {\n    type: 'NONE';\n}\n\nexport const isNone = (strategy: Pick<InitializationStrategy, 'type'>): strategy is None =>\n    strategy.type === 'NONE';\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { NonePaymentProcessor } from './payment-processors';\nimport { PaymentProcessorRegistry } from './ppsdk-payment-processor-registry';\nimport { PaymentProcessorType } from './ppsdk-payment-processor-type';\nimport { StepHandler } from './step-handler';\n\nexport const createPaymentProcessorRegistry = (requestSender: RequestSender, stepHandler: StepHandler) => {\n    const registry = new PaymentProcessorRegistry();\n\n    registry.register(\n        PaymentProcessorType.NONE,\n        () => new NonePaymentProcessor(requestSender, stepHandler)\n    );\n\n    registry.register(\n        PaymentProcessorType.UNSUPPORTED,\n        () => undefined\n    );\n\n    return registry;\n};\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { PaymentsAPIResponse } from './ppsdk-payments-api-response';\nimport { StepHandler } from './step-handler';\n\ninterface ResumeSettings {\n    paymentId: string;\n    bigpayBaseUrl: string;\n}\n\nexport class PaymentResumer {\n    constructor(\n        private _requestSender: RequestSender,\n        private _stepHandler: StepHandler\n    ) {}\n\n    resume({ paymentId, bigpayBaseUrl }: ResumeSettings): Promise<void> {\n        return this._requestSender.get<PaymentsAPIResponse['body']>(`${bigpayBaseUrl}/payments/${paymentId}`)\n            .then(response => this._stepHandler.handle(response));\n    }\n}\n","import { noop } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType, RequestError } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport StorefrontPaymentRequestSender from '../../storefront-payment-request-sender';\nimport PaymentStrategy from '../payment-strategy';\n\nexport default class QuadpayPaymentStrategy implements PaymentStrategy {\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _storeCreditActionCreator: StoreCreditActionCreator,\n        private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n        private _storefrontPaymentRequestSender: StorefrontPaymentRequestSender\n    ) { }\n\n    initialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n\n    async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = payload;\n\n        if (!payment) {\n            throw new PaymentArgumentInvalidError(['payment']);\n        }\n\n        let nonce: string;\n        const { methodId } = payment;\n        const state = await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId, options));\n        const { clientToken = '' } = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n        try {\n            ({ id: nonce } = JSON.parse(clientToken));\n        } catch (error) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        if (!nonce) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n        }\n\n        const paymentPayload = {\n            methodId,\n            paymentData: { nonce },\n        };\n\n        const { isStoreCreditApplied: useStoreCredit } = this._store.getState().checkout.getCheckoutOrThrow();\n\n        await this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(useStoreCredit));\n        await this._store.dispatch(this._remoteCheckoutActionCreator.initializePayment(methodId, { useStoreCredit }));\n        await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n        await this._prepareForReferredRegistration(methodId, nonce);\n\n        try {\n            return await this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n        } catch (error) {\n            if (error instanceof RequestError && error.body.status === 'additional_action_required') {\n                const { redirect_url } = error.body.additional_action_required.data;\n\n                window.location.replace(redirect_url);\n\n                return new Promise(noop);\n            }\n\n            throw error;\n        }\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n\n    private _prepareForReferredRegistration(methodId: string, externalId: string): Promise<void> {\n        return this._storefrontPaymentRequestSender.saveExternalId(methodId, externalId);\n    }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { RequestError } from '../../../common/error/errors';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class SagePayPaymentStrategy extends CreditCardPaymentStrategy {\n    constructor(\n        store: CheckoutStore,\n        orderActionCreator: OrderActionCreator,\n        paymentActionCreator: PaymentActionCreator,\n        hostedFormFactory: HostedFormFactory,\n        private _formPoster: FormPoster\n    ) {\n        super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n    }\n\n    execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        return super.execute(payload, options)\n            .catch((error: Error) => {\n                if (!(error instanceof RequestError) || !some(error.body.errors, { code: 'three_d_secure_required' })) {\n                    return Promise.reject(error);\n                }\n\n                return new Promise(() => {\n                    this._formPoster.postForm(error.body.three_ds_result.acs_url, {\n                        PaReq: error.body.three_ds_result.payer_auth_request,\n                        TermUrl: error.body.three_ds_result.callback_url,\n                        MD: error.body.three_ds_result.merchant_data,\n                    }, undefined, '_top');\n                });\n            });\n    }\n\n    finalize(options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const state = this._store.getState();\n        const order = state.order.getOrder();\n\n        if (order && state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE) {\n            return this._store.dispatch(this._orderActionCreator.finalizeOrder(order.orderId, options));\n        }\n\n        return super.finalize(options);\n    }\n}\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if the shopper is using a browser version that is not\n * supported by us or any third party provider we use.\n */\nexport default class UnsupportedBrowserError extends StandardError {\n    constructor(message?: string) {\n        super(message || 'Unsupported browser error');\n\n        this.name = 'UnsupportedBrowserError';\n        this.type = 'unsupported_browser';\n    }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\nimport { omit } from 'lodash';\nimport { noop } from 'rxjs';\n\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType, TimeoutError, UnsupportedBrowserError } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { NonceInstrument } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategyActionCreator from '../../payment-strategy-action-creator';\nimport PaymentStrategy from '../payment-strategy';\n\nimport SquarePaymentForm, { CardData, Contact, DigitalWalletType, NonceGenerationError, SquareFormElement, SquareFormOptions, SquarePaymentRequest } from './square-form';\nimport SquarePaymentInitializeOptions from './square-payment-initialize-options';\nimport SquareScriptLoader from './square-script-loader';\n\nexport default class SquarePaymentStrategy implements PaymentStrategy {\n    private _deferredRequestNonce?: DeferredPromise;\n    private _paymentForm?: SquarePaymentForm;\n    private _paymentMethod?: PaymentMethod;\n    private _squareOptions?: SquarePaymentInitializeOptions;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _checkoutActionCreator: CheckoutActionCreator,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n        private _requestSender: RequestSender,\n        private _scriptLoader: SquareScriptLoader\n    ) {}\n\n    initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { methodId } = options;\n\n        this._syncPaymentMethod(methodId);\n\n        return this._scriptLoader.load()\n            .then(createSquareForm =>\n                new Promise((resolve, reject) => {\n                    this._paymentForm = createSquareForm(\n                        this._getFormOptions(options, { resolve, reject })\n                    );\n                    this._paymentForm.build();\n                }))\n            .then(() => this._store.getState());\n    }\n\n    execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment } = orderRequest;\n\n        if (!payment || !payment.methodId) {\n            throw new InvalidArgumentError('Unable to submit payment because \"payload.payment.methodId\" argument is not provided.');\n        }\n\n        this._syncPaymentMethod(payment.methodId);\n\n        return this._getNonceInstrument(payment.methodId)\n            .then(paymentData =>\n                this._store.dispatch(this._orderActionCreator.submitOrder(omit(orderRequest, 'payment'), options))\n                .then(() =>\n                    this._store.dispatch(this._paymentActionCreator.submitPayment({ ...payment, paymentData }))\n                ));\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n\n    private _syncPaymentMethod(methodId: string): void {\n        const state = this._store.getState();\n        this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n        if (!this._paymentMethod || !this._paymentMethod.initializationData) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n    }\n\n    private _getCountryCode(countryName: string) {\n        switch (countryName.toUpperCase()) {\n            case 'NEW ZELAND':\n                return 'NZ';\n            case 'AUSTRALIA':\n                return 'AU';\n            default:\n                return 'US';\n        }\n    }\n\n    private _getNonceInstrument(methodId: string): Promise<NonceInstrument> {\n        const state = this._store.getState();\n        const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n        if (paymentMethod) {\n            const { initializationData } = paymentMethod;\n            if (initializationData && initializationData.paymentData.nonce) {\n                return Promise.resolve({ nonce: paymentMethod.initializationData.paymentData.nonce });\n            }\n        }\n\n        return new Promise<NonceInstrument>((resolve, reject) => {\n            if (!this._paymentForm) {\n                throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n            }\n\n            if (this._deferredRequestNonce) {\n                this._deferredRequestNonce.reject(new TimeoutError());\n            }\n\n            this._deferredRequestNonce = { resolve, reject };\n            this._paymentForm.requestCardNonce();\n        });\n    }\n\n    private _getFormOptions(options: PaymentInitializeOptions, deferred: DeferredPromise): SquareFormOptions {\n        const { square: squareOptions } = options;\n\n        if (!squareOptions || !this._paymentMethod) {\n            throw new InvalidArgumentError('Unable to proceed because \"options.square\" argument is not provided.');\n        }\n\n        this._squareOptions = squareOptions;\n\n        return {\n            ...this._squareOptions,\n            ...this._paymentMethod.initializationData,\n            callbacks: {\n                cardNonceResponseReceived: (errors, nonce, cardData, billingContact, shippingContact) => {\n                    if (cardData && cardData.digital_wallet_type !== DigitalWalletType.none) {\n                        this._handleWalletNonceResponse(errors, nonce, cardData, billingContact, shippingContact);\n                    } else {\n                        this._handleCardNonceResponse(errors, nonce);\n                    }\n                },\n                createPaymentRequest: () => this._paymentRequestPayload(),\n                methodsSupported: methods => {\n                    const { masterpass } = squareOptions;\n\n                    if (masterpass) {\n                        this._showPaymentMethods(methods, masterpass);\n                    }\n                },\n                paymentFormLoaded: () => {\n                    deferred.resolve();\n                    this._setPostalCode();\n                },\n                unsupportedBrowserDetected: () => deferred.reject(new UnsupportedBrowserError()),\n            },\n        };\n    }\n\n    private _handleWalletNonceResponse(\n        errors?: NonceGenerationError[],\n        nonce?: string,\n        cardData?: CardData,\n        billingContact?: Contact,\n        shippingContact?: Contact\n    ): void {\n        const onError = this._squareOptions && this._squareOptions.onError || noop;\n        const onPaymentSelect = this._squareOptions && this._squareOptions.onPaymentSelect || noop;\n\n        if (errors) {\n            onError(errors);\n        } else if (nonce && this._paymentMethod) {\n            this._paymentInstrumentSelected(\n                this._paymentMethod.id,\n                nonce,\n                cardData,\n                billingContact,\n                shippingContact\n            )\n                .then(onPaymentSelect)\n                .catch(onError);\n        }\n    }\n\n    private _handleCardNonceResponse(errors?: NonceGenerationError[], nonce?: string): void {\n        if (!this._deferredRequestNonce) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        if (nonce && !errors) {\n            this._deferredRequestNonce.resolve({ nonce });\n\n            return;\n        }\n\n        const onError = this._squareOptions && this._squareOptions.onError || noop;\n\n        onError(errors);\n\n        this._deferredRequestNonce.reject(errors);\n    }\n\n    private _paymentInstrumentSelected(\n        methodId: string,\n        nonce?: string,\n        cardData?: CardData,\n        billingContact?: Contact,\n        shippingContact?: Contact): Promise<InternalCheckoutSelectors> {\n\n        return this._store.dispatch(this._paymentStrategyActionCreator.widgetInteraction(() => {\n            return this._setExternalCheckoutData(nonce, cardData, billingContact, shippingContact)\n            .then(() =>\n                Promise.all([\n                this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),\n                this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId)),\n            ]));\n        }, { methodId }), { queueId: 'widgetInteraction' });\n    }\n\n    private _paymentRequestPayload(): SquarePaymentRequest {\n        const state = this._store.getState();\n        const checkout = state.checkout.getCheckout();\n        const storeConfig = state.config.getStoreConfig();\n\n        if (!checkout) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n        }\n\n        if (!storeConfig) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n        }\n\n        return {\n            requestShippingAddress: true,\n            requestBillingInfo: true,\n            currencyCode: storeConfig.currency.code,\n            countryCode: this._getCountryCode(storeConfig.storeProfile.storeCountry),\n            total: {\n                label: storeConfig.storeProfile.storeName,\n                amount: String(checkout.subtotal),\n                pending: false,\n            },\n        };\n    }\n\n    private _setExternalCheckoutData(nonce?: string, cardData?: CardData, billingContact?: Contact, shippingContact?: Contact): Promise<Response<any>> {\n        return this._requestSender.post('/checkout.php', {\n            headers: {\n                Accept: 'text/html',\n                'Content-Type': 'application/x-www-form-urlencoded',\n            },\n            body: {\n                nonce,\n                provider: 'squarev2',\n                action: 'set_external_checkout',\n                cardData: JSON.stringify(cardData),\n                billingContact: JSON.stringify(billingContact),\n                shippingContact: JSON.stringify(shippingContact),\n            },\n        });\n    }\n\n    private _setPostalCode(): void {\n        const state = this._store.getState();\n        const billingAddress = state.billingAddress.getBillingAddress();\n\n        if (!this._paymentForm) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        if (billingAddress && billingAddress.postalCode) {\n            this._paymentForm.setPostalCode(billingAddress.postalCode);\n        }\n    }\n\n    private _showPaymentMethods(methods: { [key: string]: boolean }, element: SquareFormElement): void {\n        const masterpassBtn = document.getElementById(element.elementId);\n\n        if (masterpassBtn && methods.masterpass) {\n            masterpassBtn.style.display = 'inline-block';\n        }\n    }\n}\n\nexport interface DeferredPromise {\n    resolve(resolution?: NonceInstrument): void;\n    reject(reason?: any): void;\n}\n","interface BaseElementOptions {\n    /**\n     * Customize the appearance of an element using CSS properties passed in a [Style](https://stripe.com/docs/js/appendix/style) object,\n     * which consists of CSS properties nested under objects for each variant.\n     */\n    style?: StripeElementStyle;\n\n    /**\n     * Set custom class names on the container DOM element when the Stripe element is in a particular state.\n     */\n    classes?: StripeElementClasses;\n\n    /**\n     * Applies a disabled state to the Element such that user input is not accepted. Default is false.\n     */\n    disabled?: boolean;\n}\n\nexport interface CreatePaymentMethodCardData extends PaymentMethodCreateParams {\n    card?: StripeElement;\n}\n\nexport interface CreatePaymentMethodIdealData extends PaymentMethodCreateParams {\n    ideal?: StripeElement;\n}\n\nexport interface CreatePaymentMethodSepaData extends PaymentMethodCreateParams {\n    sepa_debit?: StripeElement;\n}\n\n/**\n * The PaymentIntent object.\n */\nexport interface PaymentIntent {\n    /**\n     * Unique identifier for the object.\n     */\n    id: string;\n\n    /**\n     * Status of this PaymentIntent. Read more about each PaymentIntent [status](https://stripe.com/docs/payments/intents#intent-statuses).\n     */\n    status: 'succeeded' | string;\n}\n\n/**\n * The PaymentMethod object\n */\nexport interface PaymentMethod {\n    /**\n     * Unique identifier for the object.\n     */\n    id: string;\n\n    /**\n     * The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value.\n     * It contains additional information specific to the PaymentMethod type.\n     */\n    type: string;\n}\n\nexport interface PaymentMethodCreateParams {\n    /**\n     * Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods.\n     */\n    billing_details?: StripeBillingDetails;\n}\n\nexport interface StripeError {\n    /**\n     * A human-readable message providing more details about the error. For card errors, these messages can be shown to your users.\n     */\n    message?: string;\n}\n\n/**\n * CSS properties supported by Stripe.js.\n */\ninterface StripeElementCSSProperties {\n    /**\n     * The [background-color](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) CSS property.\n     *\n     * This property works best with the `::selection` pseudo-class.\n     * In other cases, consider setting the background color on the element's container instaed.\n     */\n    backgroundColor?: string;\n\n    /**\n     * The [color](https://developer.mozilla.org/en-US/docs/Web/CSS/color) CSS property.\n     */\n    color?: string;\n\n    /**\n     * The [font-family](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family) CSS property.\n     */\n    fontFamily?: string;\n\n    /**\n     * The [font-size](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size) CSS property.\n     */\n    fontSize?: string;\n\n    /**\n     * The [font-smoothing](https://developer.mozilla.org/en-US/docs/Web/CSS/font-smoothing) CSS property.\n     */\n    fontSmoothing?: string;\n\n    /**\n     * The [font-style](https://developer.mozilla.org/en-US/docs/Web/CSS/font-style) CSS property.\n     */\n    fontStyle?: string;\n\n    /**\n     * The [font-variant](https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant) CSS property.\n     */\n    fontVariant?: string;\n\n    /**\n     * The [font-weight](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) CSS property.\n     */\n    fontWeight?: string;\n\n    /**\n     * A custom property, used to set the color of the icons that are rendered in an element.\n     */\n    iconColor?: string;\n\n    /**\n     * The [line-height](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) CSS property.\n     *\n     * To avoid cursors being rendered inconsistently across browsers, consider using a padding on the element's container instead.\n     */\n    lineHeight?: string;\n\n    /**\n     * The [letter-spacing](https://developer.mozilla.org/en-US/docs/Web/CSS/letter-spacing) CSS property.\n     */\n    letterSpacing?: string;\n\n    /**\n     * The [text-align](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) CSS property.\n     *\n     * Available for the `cardNumber`, `cardExpiry`, and `cardCvc` elements.\n     */\n    textAlign?: string;\n\n    /**\n     * The [padding](https://developer.mozilla.org/en-US/docs/Web/CSS/padding) CSS property.\n     *\n     * Available for the `idealBank` element.\n     * Accepts integer `px` values.\n     */\n    padding?: string;\n\n    /**\n     * The [text-decoration](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration) CSS property.\n     */\n    textDecoration?: string;\n\n    /**\n     * The [text-shadow](https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow) CSS property.\n     */\n    textShadow?: string;\n\n    /**\n     * The [text-transform](https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform) CSS property.\n     */\n    textTransform?: string;\n}\n\ninterface StripeElementStyleVariant extends StripeElementCSSProperties {\n    ':hover'?: StripeElementCSSProperties;\n\n    ':focus'?: StripeElementCSSProperties;\n\n    '::placeholder'?: StripeElementCSSProperties;\n\n    '::selection'?: StripeElementCSSProperties;\n\n    ':-webkit-autofill'?: StripeElementCSSProperties;\n\n    /**\n     * Available for all elements except the `paymentRequestButton` element\n     */\n    ':disabled'?: StripeElementCSSProperties;\n\n    /**\n     * Available for the `cardNumber`, `cardExpiry`, and `cardCvc` elements.\n     */\n    '::-ms-clear'?: StripeElementCSSProperties & {display: string};\n}\n\nexport interface CardElementOptions extends BaseElementOptions {\n    /**\n     * A pre-filled set of values to include in the input (e.g., {postalCode: '94110'}).\n     * Note that sensitive card information (card number, CVC, and expiration date)\n     * cannot be pre-filled\n     */\n    value?: string;\n\n    /**\n     * Hide the postal code field. Default is false. If you are already collecting a\n     * full billing address or postal code elsewhere, set this to true.\n     */\n    hidePostalCode?: boolean;\n\n    /**\n     * Appearance of the icon in the Element.\n     */\n    iconStyle?: IconStyle;\n\n    /*\n     * Hides the icon in the Element, Default is false\n     */\n    hideIcon?: boolean;\n\n}\n\ninterface BaseIndividualElementOptions extends BaseElementOptions  {\n    containerId: string;\n}\n\nexport interface CardNumberElementOptions extends BaseIndividualElementOptions {\n    /*\n     * Placeholder\n     */\n    placeholder?: string;\n\n    showIcon?: boolean;\n    /**\n     * Appearance of the icon in the Element. Either `solid` or `default`\n     */\n    iconStyle?: IconStyle;\n}\n\nexport interface CardExpiryElementOptions extends BaseIndividualElementOptions {\n    /*\n     * Placeholder\n     */\n    placeholder?: string;\n}\n\nexport interface CardCvcElementOptions extends BaseIndividualElementOptions {\n    /*\n     * Placeholder\n     */\n    placeholder?: string;\n}\n\nexport interface IbanElementOptions extends BaseElementOptions {\n    /**\n     * Specify the list of countries or country-groups whose IBANs you want to allow.\n     * Must be ['SEPA'].\n     */\n    supportedCountries?: string[];\n\n    /**\n     * Customize the country and format of the placeholder IBAN. Default is DE.\n     */\n    placeholderCountry?: string;\n\n    /**\n     * Appearance of the icon in the Element.\n     */\n    iconStyle?: IconStyle;\n}\n\nexport interface IdealElementOptions extends BaseElementOptions {\n    value?: string;\n\n    /**\n     * Hides the icon in the Element. Default is false.\n     */\n    hideIcon?: boolean;\n}\n\nexport interface ZipCodeElementOptions {\n    containerId: string;\n}\n\nexport enum IconStyle {\n    Solid = 'solid',\n    Default = 'default',\n}\n\nexport interface StripeElementStyle {\n    /**\n     * Base variant—all other variants inherit from these styles.\n     */\n    base?: StripeElementStyleVariant;\n\n    /**\n     * Applied when the element has valid input.\n     */\n    complete?: StripeElementStyleVariant;\n\n    /**\n     * Applied when the element has no customer input.\n     */\n    empty?: StripeElementStyleVariant;\n\n    /**\n     * Applied when the element has invalid input.\n     */\n    invalid?: StripeElementStyleVariant;\n}\n\nexport interface StripeElementClasses {\n    /**\n     * The base class applied to the container. Defaults to StripeElement.\n     */\n    base?: string;\n\n    /**\n     * The class name to apply when the Element is complete. Defaults to StripeElement--complete.\n     */\n    complete?: string;\n\n    /**\n     * The class name to apply when the Element is empty. Defaults to StripeElement--empty.\n     */\n    empty?: string;\n\n    /**\n     * The class name to apply when the Element is focused. Defaults to StripeElement--focus.\n     */\n    focus?: string;\n\n    /**\n     * The class name to apply when the Element is invalid. Defaults to StripeElement--invalid.\n     */\n    invalid?: string;\n\n    /**\n     * The class name to apply when the Element has its value autofilled by the browser\n     * (only on Chrome and Safari). Defaults to StripeElement--webkit-autofill.\n     */\n    webkitAutoFill?: string;\n}\n\nexport interface StripeAddress {\n    /**\n     * City, district, suburb, town, or village.\n     */\n    city?: string;\n\n    /**\n     * Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)).\n     */\n    country?: string;\n\n    /**\n     * Address line 1 (e.g., street, PO Box, or company name).\n     */\n    line1: string;\n\n    /**\n     * Address line 2 (e.g., apartment, suite, unit, or building).\n     */\n    line2?: string;\n\n    /**\n     * ZIP or postal code.\n     */\n    postal_code?: string;\n\n    /**\n     * State, county, province, or region.\n     */\n    state?: string;\n}\n\nexport interface StripeBillingDetails {\n    /**\n     * Billing address.\n     */\n    address?: StripeAddress;\n\n    /**\n     * Email address.\n     */\n    email?: string;\n\n    /**\n     * Full name.\n     */\n    name?: string;\n\n    /**\n     * Billing phone number (including extension).\n     */\n    phone?: string;\n}\n\nexport interface StripeShippingAddress {\n    /**\n     * Shipping Address\n     */\n    address: StripeAddress;\n\n    /**\n     * Recipient name\n     */\n    name: string;\n\n    /**\n     * The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc.\n     */\n    carrier?: string;\n\n    /**\n     * Recipient phone (including extension).\n     */\n    phone?: string;\n\n    /**\n     * The tracking number for a physical product, obtained from the delivery service.\n     * If multiple tracking numbers were generated for this purchase, please separate them with commas.\n     */\n    tracking_number?: string;\n}\n\n/**\n * Data to be sent with a `stripe.confirmAlipayPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmAlipayPaymentData {\n    /**\n     * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n     * is redirect_to_url, this URL will be used on the return path for the redirect.\n     *\n     * @recommended\n     */\n    return_url?: string;\n}\n\n/**\n * Data to be sent with a `stripe.confirmCardPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmCardPaymentData {\n    /*\n     * Either the id of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a\n     * PaymentMethod with. See the use case sections below for details.\n     *\n     * @recommended\n     */\n    payment_method?: CreatePaymentMethodCardData;\n\n    /**\n     * The [shipping details](https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-shipping) for the payment, if collected.\n     *\n     * @recommended\n     */\n    shipping?: StripeShippingAddress;\n\n    /**\n     * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n     * is redirect_to_url, this URL will be used on the return path for the redirect.\n     *\n     * @recommended\n     */\n    return_url?: string;\n\n    /**\n     * Indicates that you intend to make future payments with this PaymentIntent's payment method.\n     *\n     * If present, the payment method used with this PaymentIntent can be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer, even after the transaction completes.\n     *\n     * Use `on_session` if you intend to only reuse the payment method when your customer is present in your checkout flow. Use `off_session` if your customer may or may not be in your checkout flow.\n     */\n    setup_future_usage?: 'off_session' | 'on_session' | null;\n}\n\n/**\n * Data to be sent with a `stripe.confirmIdealPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmIdealPaymentData {\n    /*\n     * Either the id of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a\n     * PaymentMethod with. See the use case sections below for details.\n     *\n     * @recommended\n     */\n    payment_method?: CreatePaymentMethodIdealData;\n\n    /**\n     * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n     * is redirect_to_url, this URL will be used on the return path for the redirect.\n     *\n     * @recommended\n     */\n    return_url?: string;\n}\n\n/**\n * Data to be sent with a `stripe.confirmSEPAPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmSepaPaymentData {\n    /*\n     * Either the id of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a\n     * PaymentMethod with. See the use case sections below for details.\n     *\n     * @recommended\n     */\n    payment_method?: CreatePaymentMethodSepaData;\n}\n\nexport type StripeConfirmPaymentData = StripeConfirmAlipayPaymentData | StripeConfirmCardPaymentData | StripeConfirmIdealPaymentData | StripeConfirmSepaPaymentData | undefined;\n\nexport type StripeElementOptions = CardElementOptions | CardExpiryElementOptions | CardNumberElementOptions | CardCvcElementOptions | IdealElementOptions | IbanElementOptions | ZipCodeElementOptions;\n\nexport interface StripeElement {\n    /**\n     * The `element.mount` method attaches your element to the DOM.\n     */\n    mount(domElement: string | HTMLElement): void;\n\n    /**\n     * Removes the element from the DOM and destroys it.\n     * A destroyed element can not be re-activated or re-mounted to the DOM.\n     */\n    destroy(): void;\n\n    /**\n     * Unmounts the element from the DOM.\n     * Call `element.mount` to re-attach it to the DOM.\n     */\n    unmount(): void;\n}\n\nexport interface StripeElements {\n    /**\n     * Creates a `AlipayElement` | `CardElement` | `CardCvcElement` |`CardExpiryElement` | `CardExpiryElement` | `CardNumberElement` | `IdealBankElement` | `IbanElement`.\n     */\n    create(\n        elementType: StripeElementType,\n        options?: StripeElementOptions\n    ): StripeElement;\n\n    /**\n     * Looks up a previously created `Element` by its type.\n     */\n    getElement(elementType: StripeElementType): StripeElement | null;\n}\n\n/**\n * This object is used to pass custom fonts when creating an [Elements](https://stripe.com/docs/js/elements_object/create) object.\n */\nexport interface CssFontSource {\n    /**\n     * A relative or absolute URL pointing to a CSS file with [@font-face](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face) definitions, for example:\n     * `https://fonts.googleapis.com/css?family=Open+Sans`\n     * Note that if you are using a [content security policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) (CSP),\n     * [additional directives](https://stripe.com/docs/security#content-security-policy) may be necessary.\n     */\n    cssSrc: string;\n}\n\n/**\n * This object is used to pass custom fonts when creating an [Elements](https://stripe.com/docs/js/elements_object/create) object.\n */\nexport interface CustomFontSource {\n    /**\n     * The name to give the font.\n     */\n    family: string;\n\n    /**\n     * A valid [src](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/src) value pointing to your\n     * custom font file. This is usually (though not always) a link to a file with a .woff , .otf, or .svg suffix.\n     */\n    src: string;\n\n    /**\n     * A valid [font-display](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display) value.\n     */\n    display?: string;\n\n    /**\n     * One of normal, italic, oblique. Defaults to normal.\n     */\n    style?: string;\n\n    /**\n     * A valid [unicode-range](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/unicode-range) value.\n     */\n    unicodeRange?: string;\n\n    /**\n     * A valid [font-weight](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight). Note that this is a string, not a number.\n     */\n    weight?: string;\n}\n\nexport type CustomFont = CssFontSource | CustomFontSource;\n\nexport interface StripeElementsOptions {\n    /**\n     * An array of custom fonts, which elements created from the Elements object can use.\n     * Fonts can be specified as [CssFontSource](https://stripe.com/docs/js/appendix/css_font_source_object)\n     * or [CustomFontSource](https://stripe.com/docs/js/appendix/custom_font_source_object) objects.\n     */\n    fonts?: CustomFont[];\n\n    /**\n     * A [locale](https://stripe.com/docs/js/appendix/supported_locales) to display placeholders and\n     * error strings in. Default is auto (Stripe detects the locale of the browser).\n     * Setting the locale does not affect the behavior of postal code validation—a valid postal code\n     * for the billing country of the card is still required.\n     */\n    locale?: string;\n}\n\nexport interface StripeConfirmPaymentOptions {\n    /**\n     * Set this to false if you want to [manually handle the authorization redirect](https://stripe.com/docs/payments/ideal#handle-redirect). Default is true.\n     */\n    handleActions?: boolean;\n}\n\nexport interface StripeV3Client {\n    /**\n     * Create an `Elements` instance, which manages a group of elements.\n     */\n    elements(options?: StripeElementsOptions): StripeElements;\n\n    /**\n     * @docs https://stripe.com/docs/js/payment_intents/confirm_alipay_payment\n     *\n     * Use `stripe.confirmAlipayPayment` in the Alipay payment method creation flow when the customer submits your payment form.\n     * When called, it will confirm the [PaymentIntent](https://stripe.com/docs/api/payment_intents) with data you provide, and it will automatically\n     * redirect the customer to the authorize the transaction. Once authorization is complete, the customer will be redirected\n     * back to your specified `return_url`. When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods).\n     * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you.\n     * If you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data.\n     * These use cases are detailed in the sections that follow.\n     *\n     * @returns\n     * `stripe.confirmAlipayPayment` by default, will trigger a redirect when successful. If there is an error, or when handling\n     * `next_actions` manually by using the `handleActions: false` option, it will return a `Promise` which resolves with a `result` object.\n     * This object has either:\n     *\n     * - result.paymentIntent: the successful PaymentIntent.\n     * - result.error: an error. Refer to the API reference for all possible errors.\n     *\n     * Note that `stripe.confirmAlipayPayment` may take several seconds to complete. During that time, you should disable your\n     * form from being resubmitted and show a waiting indicator like a spinner. If you receive an error result, you should\n     * be sure to show that error to the customer, re-enable the form, and hide the waiting indicator.\n     */\n    confirmAlipayPayment(\n        /**\n         * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n         */\n        clientSecret: string,\n\n        /**\n         * Data to be sent with the request. Refer to the Payment Intents API for a full list of parameters.\n         */\n        data?: StripeConfirmAlipayPaymentData,\n\n        /**\n         * An options object to control the behavior of this method.\n         */\n        options?: StripeConfirmPaymentOptions\n    ): Promise<{paymentIntent?: PaymentIntent; error?: StripeError}>;\n\n    /**\n     * @docs https://stripe.com/docs/js/payment_intents/confirm_card_payment\n     *\n     * Use `stripe.confirmCardPayment` when the customer submits your payment form.\n     * When called, it will confirm the [PaymentIntent](https://stripe.com/docs/api/payment_intents)\n     * with `data` you provide and carry out 3DS or other next actions if they are required.\n     *\n     * If you are using [Dynamic 3D Secure](https://stripe.com/docs/payments/3d-secure#three-ds-radar), `stripe.confirmCardPayment` will\n     * trigger your Radar rules to execute and may open a dialog for your customer to authenticate their payment.\n     *\n     * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods).\n     * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you.\n     * It can also be called with an existing `PaymentMethod`, or if you have already attached a PaymentMethod you can call this\n     * method without needing to provide any additional data. These use cases are detailed in the sections that follow.\n     *\n     * @returns\n     * `stripe.confirmCardPayment` will return a Promise which resolves with a result object.\n     * This object has either:\n     *\n     * - result.paymentIntent: the successful PaymentIntent.\n     * - result.error: an error. Refer to the API reference for all possible errors.\n     *\n     * Note that stripe.confirmCardPayment may take several seconds to complete. During that time, you should disable\n     * your form from being resubmitted and show a waiting indicator like a spinner. If you receive an error result,\n     * you should be sure to show that error to the customer, re-enable the form, and hide the waiting indicator.\n     *\n     * Additionally, `stripe.confirmCardPayment may trigger` a [3D Secure](https://stripe.com/docs/payments/3d-secure) authentication\n     * challenge. This will be shown in a modal dialog and may be confusing for customers using assistive technologies like\n     * screen readers. You should make your form accessible by ensuring that success or error messages are clearly read out\n     * after this method completes.\n     *\n     */\n    confirmCardPayment(\n        /**\n         * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n         */\n        clientSecret: string,\n\n        /**\n         * Data to be sent with the request. Refer to the Payment Intents API for a full list of parameters.\n         */\n        data?: StripeConfirmCardPaymentData,\n\n        /**\n         * An options object to control the behavior of this method.\n         */\n        options?: StripeConfirmPaymentOptions\n    ): Promise<{paymentIntent?: PaymentIntent; error?: StripeError}>;\n\n    /**\n     * @docs https://stripe.com/docs/js/payment_intents/confirm_ideal_payment\n     *\n     * Use `stripe.confirmIdealPayment` in the [iDEAL Payments with Payment Methods](https://stripe.com/docs/payments/ideal)\n     * flow when the customer submits your payment form. When called, it will confirm the `PaymentIntent` with `data` you\n     * provide, and it will automatically redirect the customer to the authorize the transaction.\n     * Once authorization is complete, the customer will be redirected back to your specified `return_url`.\n     *\n     * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods).\n     * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you.\n     * It can also be called with an existing `PaymentMethod`, or if you have already attached a PaymentMethod you can call this\n     * method without needing to provide any additional data. These use cases are detailed in the sections that follow.\n     *\n     * @returns\n     * By default, `stripe.confirmIdealPayment` will trigger a redirect when successful. If there is an error, or when handling\n     * next actions manually by using the `handleActions: false` option, it will return a `Promise` which resolves with a `result`\n     * object. This object has either:\n     *\n     * - result.paymentIntent: the successful PaymentIntent.\n     * - result.error: an error. Refer to the API reference for all possible errors.\n     *\n     * Note that `stripe.confirmIdealPayment` may take several seconds to complete. During that time, you should disable\n     * your form from being resubmitted and show a waiting indicator like a spinner. If you receive an error result,\n     * you should be sure to show that error to the customer, re-enable the form, and hide the waiting indicator.\n     */\n    confirmIdealPayment(\n        /**\n         * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n         */\n        clientSecret: string,\n\n        /**\n         * Data to be sent with the request. Refer to the Payment Intents API for a full list of parameters.\n         */\n        data?: StripeConfirmIdealPaymentData,\n\n        /**\n         * An options object to control the behavior of this method.\n         */\n        options?: StripeConfirmPaymentOptions\n    ): Promise<{paymentIntent?: PaymentIntent; error?: StripeError}>;\n\n    /**\n     *\n     * Use `stripe.confirmSepaDebitPayment` in the [SEPA Direct Debit Payments](https://stripe.com/docs/payments/sepa-debit)\n     * with Payment Methods flow when the customer submits your payment form. When called, it will confirm the\n     * [PaymentIntent](https://stripe.com/docs/api/payment_intents) with `data` you provide. Note that there are some additional\n     * requirements to this flow that are not covered in this reference. Refer to our [integration guide](https://stripe.com/docs/payments/sepa-debit\n     * for more details.\n     *\n     * When you confirm a PaymentIntent, it needs to have an attached PaymentMethod. In addition to confirming the PaymentIntent,\n     * this method can automatically create and attach a new PaymentMethod for you. If you have already attached a\n     * [PaymentMethod](https://stripe.com/docs/api/payment_methods) you can call this method without needing to provide any additional data.\n     * These use cases are detailed in the sections that follow.\n     * @docs https://stripe.com/docs/js/payment_intents/confirm_sepa_debit_payment\n     */\n    confirmSepaDebitPayment(\n        /**\n         * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n         */\n        clientSecret: string,\n\n        /**\n         * Data to be sent with the request. Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n         */\n        data?: StripeConfirmSepaPaymentData\n    ): Promise<{paymentIntent?: PaymentIntent; error?: StripeError}>;\n\n    /**\n     * Use stripe.createPaymentMethod to convert payment information collected by elements into a PaymentMethod\n     * object that you safely pass to your server to use in an API call.\n     * @docs https://stripe.com/docs/js/payment_methods/create_payment_method\n     *\n     * @param type: String, The type of the PaymentMethod to create. Refer to the PaymentMethod API for all possible values.\n     * @param card: StripeElement, A card or cardNumber Element.\n     * @param billing_details: StripeBillingDetails, Billing information associated with the PaymentMethod that\n     * may be used or required by particular types of payment methods.\n     */\n    createPaymentMethod(\n        params: CreatePaymentMethodParams\n    ): Promise<{paymentMethod?: PaymentMethod; error?: StripeError}>;\n\n    /**\n     * Use stripe.handleCardAction in the Payment Intents API manual confirmation flow to handle a PaymentIntent\n     * with the requires_action status. It will throw an error if the PaymentIntent has a different status.\n     * @docs https://stripe.com/docs/js/payment_intents/handle_card_action\n     *\n     * @param paymentIntentClientSecret: String, The client secret of the PaymentIntent to handle.\n     */\n    handleCardAction(\n        paymentIntentClientSecret: string\n    ): Promise<{paymentIntent?: PaymentIntent; error?: StripeError}>;\n}\n\nexport interface CreatePaymentMethodParams {\n    type: StripePaymentMethodType;\n    card: StripeElement;\n    billing_details?: StripeBillingDetails;\n}\n\nexport interface StripeHostWindow extends Window {\n    Stripe?(\n        stripePublishableKey: string,\n        options?: StripeConfigurationOptions\n    ): StripeV3Client;\n}\n\nexport enum StripeElementType {\n    Alipay = 'alipay',\n    CardCvc = 'cardCvc',\n    CardExpiry = 'cardExpiry',\n    CardNumber = 'cardNumber',\n    CreditCard = 'card',\n    iDEAL = 'idealBank',\n    Sepa = 'iban',\n}\n\nexport enum StripePaymentMethodType {\n    Alipay = 'alipay',\n    CreditCard = 'card',\n    iDEAL = 'ideal',\n    Sepa = 'sepa_debit',\n}\n\n/**\n * Initialization options.\n */\nexport interface StripeConfigurationOptions {\n    /**\n     * For usage with [Connect](https://stripe.com/docs/connect) only.\n     * Specifying a connected account ID (e.g., acct_24BFMpJ1svR5A89k) allows you to perform actions on behalf of that account.\n     */\n    stripeAccount: string;\n\n    /**\n     * Override your account's [API version](https://stripe.com/docs/api/versioning)\n     */\n    apiVersion?: string;\n\n    /**\n     * A locale used to globally configure localization in Stripe. Setting the locale here will localize error strings for all Stripe.js methods. It will also configure the locale for Elements and Checkout. Default is auto (Stripe detects the locale of the browser).\n     * Note that Checkout supports a slightly different set of locales than Stripe.js.\n     */\n    locale?: string;\n\n    betas?: string[];\n}\n\nexport interface StripeAdditionalActionData {\n    redirect_url?: string;\n    intent?: string;\n}\n\nexport interface StripeAdditionalAction {\n    type: string;\n    data: StripeAdditionalActionData;\n}\n\nexport interface StripeCardElements {\n    [index: number]: StripeElement;\n}\n\nexport interface IndividualCardElementOptions {\n    cardCvcElementOptions: CardCvcElementOptions;\n    cardExpiryElementOptions: CardExpiryElementOptions;\n    cardNumberElementOptions: CardNumberElementOptions;\n    zipCodeElementOptions?: ZipCodeElementOptions;\n}\n\nexport default function isIndividualCardElementOptions(individualCardElementOptions: unknown): individualCardElementOptions is IndividualCardElementOptions {\n    return Boolean((individualCardElementOptions as IndividualCardElementOptions).cardNumberElementOptions) &&\n        Boolean((individualCardElementOptions as IndividualCardElementOptions).cardCvcElementOptions) &&\n        Boolean((individualCardElementOptions as IndividualCardElementOptions).cardExpiryElementOptions);\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { SquareFormFactory, SquareFormOptions } from './square-form';\nimport SquareWindow from './square-window';\n\nexport default class SquareScriptLoader {\n    constructor(\n        private _scriptLoader: ScriptLoader\n    ) {}\n\n    load(): Promise<SquareFormFactory> {\n        const scriptURI = '//js.squareup.com/v2/paymentform';\n\n        return this._scriptLoader.loadScript(scriptURI)\n            .then(() => (options: SquareFormOptions) =>\n                new (window as unknown as SquareWindow).SqPaymentForm(options)\n            );\n    }\n}\n","import { includes, some } from 'lodash';\n\nimport { Payment } from '../..';\nimport { Address } from '../../../address';\nimport { isBillingAddressLike, BillingAddress } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType, RequestError } from '../../../common/error/errors';\nimport { Customer } from '../../../customer';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { getShippableItemsCount } from '../../../shipping';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport { HostedInstrument } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport isIndividualCardElementOptions, { PaymentIntent, PaymentMethod as StripePaymentMethod, StripeAdditionalAction, StripeAddress, StripeBillingDetails, StripeCardElements, StripeConfirmCardPaymentData, StripeConfirmIdealPaymentData, StripeConfirmPaymentData, StripeConfirmSepaPaymentData, StripeElement, StripeElements, StripeElementOptions, StripeElementType, StripeError, StripePaymentMethodType, StripeShippingAddress, StripeV3Client } from './stripev3';\nimport StripeV3PaymentInitializeOptions from './stripev3-initialize-options';\nimport StripeV3ScriptLoader from './stripev3-script-loader';\n\nconst APM_REDIRECT = [StripeElementType.Alipay, StripeElementType.iDEAL];\n\nexport default class StripeV3PaymentStrategy implements PaymentStrategy {\n    private _initializeOptions?: PaymentInitializeOptions;\n    private _stripeV3Client?: StripeV3Client;\n    private _stripeElements?: StripeElements;\n    private _stripeElement?: StripeElement;\n    private _stripeCardElements?: StripeCardElements;\n    private _useIndividualCardFields?: boolean;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _orderActionCreator: OrderActionCreator,\n        private _stripeScriptLoader: StripeV3ScriptLoader,\n        private _storeCreditActionCreator: StoreCreditActionCreator,\n        private _locale: string\n    ) {}\n\n    async initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        this._initializeOptions = options;\n\n        const paymentMethod = this._store.getState().paymentMethods.getPaymentMethodOrThrow(this._getInitializeOptions().methodId);\n        const { initializationData: { stripePublishableKey, stripeConnectedAccount, useIndividualCardFields } } = paymentMethod;\n\n        this._useIndividualCardFields = useIndividualCardFields;\n        this._stripeV3Client = await this._loadStripeJs(stripePublishableKey, stripeConnectedAccount);\n        this._stripeElement = await this._mountElement(this._getInitializeOptions().methodId);\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = orderRequest;\n        let formattedPayload: { [key: string]: any };\n        let stripeError: StripeError | undefined;\n\n        if (!payment || !payment.paymentData) {\n            throw new PaymentArgumentInvalidError(['payment.paymentData']);\n        }\n\n        const { paymentData, gatewayId, methodId } = payment;\n        const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } = paymentData as HostedInstrument;\n        const shouldSubmitOrderBeforeLoadingAPM = includes(APM_REDIRECT, methodId);\n\n        const { isStoreCreditApplied : useStoreCredit } = this._store.getState().checkout.getCheckoutOrThrow();\n\n        if (useStoreCredit) {\n            await this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(useStoreCredit));\n        }\n\n        if (isVaultedInstrument(paymentData)) {\n            // tslint:disable-next-line: variable-name\n            const { instrumentId: token, ccNumber: credit_card_number_confirmation, ccCvv: verification_value } = paymentData;\n\n            formattedPayload = {\n                bigpay_token: { token },\n                credit_card_number_confirmation,\n                verification_value,\n                confirm: false,\n            };\n        } else {\n            if (shouldSubmitOrderBeforeLoadingAPM) {\n                await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n            }\n            const state = await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(`${gatewayId}?method=${methodId}`));\n            const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n            const result = await this._confirmStripePayment(paymentMethod);\n            const { clientToken, method } = paymentMethod;\n            const { id: token } = result.paymentIntent ?? result.paymentMethod ?? { id: '' };\n            stripeError = result.error;\n\n            formattedPayload = {\n                credit_card_token: { token },\n                vault_payment_instrument: shouldSaveInstrument,\n                confirm: false,\n            };\n\n            if (method === StripeElementType.CreditCard) {\n                formattedPayload.client_token = clientToken;\n            }\n        }\n\n        if (!shouldSubmitOrderBeforeLoadingAPM) {\n            await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n        }\n\n        const paymentPayload = this._buildPaymentPayload(methodId, formattedPayload, shouldSetAsDefaultInstrument);\n\n        try {\n            return await this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n        } catch (error) {\n            return await this._processAdditionalAction(\n                this._handleEmptyPaymentIntentError(error, stripeError),\n                methodId,\n                shouldSaveInstrument,\n                shouldSetAsDefaultInstrument\n            );\n        }\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        this._unmountElement();\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    private _buildPaymentPayload(methodId: string, formattedPayload: { [key: string]: any }, shouldSetAsDefaultInstrument: boolean): Payment {\n        const paymentData = shouldSetAsDefaultInstrument\n            ? { formattedPayload, shouldSetAsDefaultInstrument }\n            : { formattedPayload };\n\n        return { methodId, paymentData };\n    }\n\n    private async _processAdditionalAction(\n        error: Error,\n        methodId: string,\n        shouldSaveInstrument: boolean,\n        shouldSetAsDefaultInstrument: boolean\n    ): Promise<InternalCheckoutSelectors | never> {\n        if (!(error instanceof RequestError)) {\n            throw error;\n        }\n\n        const isAdditionalActionError = some(error.body.errors, { code: 'additional_action_required' });\n        const isThreeDSecureRequiredError = some(error.body.errors, { code: 'three_d_secure_required' });\n\n        if (isAdditionalActionError) {\n            const action: StripeAdditionalAction = error.body.additional_action_required;\n\n            if (action && action.type === 'redirect_to_url') {\n                return new Promise(() => {\n                    if (action.data.redirect_url) {\n                        window.location.replace(action.data.redirect_url);\n                    }\n                });\n            }\n        }\n\n        if (isThreeDSecureRequiredError) {\n            const clientSecret = error.body.three_ds_result.token;\n            const result = await this._getStripeJs().handleCardAction(clientSecret);\n            const { id: token } = result.paymentIntent || { id: '' };\n\n            const formattedPayload = {\n                credit_card_token: { token },\n                vault_payment_instrument: shouldSaveInstrument,\n                confirm: true,\n            };\n\n            const paymentPayload = this._buildPaymentPayload(methodId, formattedPayload, shouldSetAsDefaultInstrument);\n\n            try {\n                return await this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n            } catch (error) {\n                throw this._handleEmptyPaymentIntentError(error, result.error);\n            }\n        }\n\n        throw error;\n    }\n\n    private _handleEmptyPaymentIntentError(\n        error: Error,\n        stripeError: StripeError | undefined\n    ) {\n        if (!(error instanceof RequestError)) {\n            return error;\n        }\n\n        return some(error.body.errors, { code: 'required_field' }) && stripeError\n            ? new Error(stripeError.message)\n            : error;\n    }\n\n    private async _confirmStripePayment(paymentMethod: PaymentMethod): Promise<{\n        paymentIntent?: PaymentIntent | undefined;\n        paymentMethod?: StripePaymentMethod | undefined;\n        error?: StripeError | undefined;\n    }> {\n        const { clientToken: clientSecret, method, returnUrl } = paymentMethod;\n\n        if (!clientSecret) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        switch (method) {\n            case StripeElementType.Alipay:\n                return await this._getStripeJs().confirmAlipayPayment(clientSecret, { return_url: returnUrl }, { handleActions: false } );\n\n            case StripeElementType.CreditCard: {\n                const card = this._useIndividualCardFields ? this._getStripeCardElements()[0] : this._getStripeElement();\n                const billingDetails = this._mapStripeBillingDetails(\n                    this._store.getState().billingAddress.getBillingAddress(),\n                    this._store.getState().customer.getCustomer()\n                );\n\n                return await this._getStripeJs().createPaymentMethod({\n                    type: StripePaymentMethodType.CreditCard,\n                    card,\n                    billing_details: billingDetails,\n                });\n            }\n\n            case StripeElementType.iDEAL: {\n                const data = this._mapStripePaymentData(StripePaymentMethodType.iDEAL, returnUrl);\n\n                return await this._getStripeJs().confirmIdealPayment(clientSecret, data, { handleActions: false });\n            }\n\n            case StripeElementType.Sepa: {\n                const data = this._mapStripePaymentData(StripePaymentMethodType.Sepa);\n\n                return await this._getStripeJs().confirmSepaDebitPayment(clientSecret, data);\n            }\n\n            default:\n                throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n    }\n\n    private _getInitializeOptions(): PaymentInitializeOptions {\n        if (!this._initializeOptions) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        return this._initializeOptions;\n    }\n\n    private _getStripeInitializeOptions(): StripeV3PaymentInitializeOptions {\n        const { stripev3 } = this._getInitializeOptions();\n\n        if (!stripev3) {\n            throw new InvalidArgumentError('Unable to initialize payment because \"options.stripev3\" argument is not provided.');\n        }\n\n        return stripev3;\n    }\n\n    private _getStripeElement(): StripeElement {\n        if (!this._stripeElement) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        return this._stripeElement;\n    }\n\n    private _getStripeCardElements(): StripeCardElements {\n        if (!this._stripeCardElements) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        return this._stripeCardElements;\n    }\n\n    private _getStripeJs(): StripeV3Client {\n        if (!this._stripeV3Client) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        return this._stripeV3Client;\n    }\n\n    private async _loadStripeJs(stripePublishableKey: string, stripeConnectedAccount: string): Promise<StripeV3Client> {\n        if (this._stripeV3Client) { return Promise.resolve(this._stripeV3Client); }\n\n        return await this._stripeScriptLoader.load(\n            stripePublishableKey,\n            stripeConnectedAccount,\n            this._locale\n        );\n    }\n\n    private _mountElement(methodId: string): Promise<StripeElement> {\n        const stripeElementType = methodId as StripeElementType;\n        const { options, containerId } = this._getStripeInitializeOptions();\n\n        let stripeElement: StripeElement;\n\n        return new Promise((resolve, reject) => {\n            if (!this._stripeElements) {\n                this._stripeElements = this._getStripeJs().elements();\n            }\n\n            switch (stripeElementType) {\n                case StripeElementType.CreditCard:\n                    if (this._useIndividualCardFields && isIndividualCardElementOptions(options)) {\n                        const { cardNumberElementOptions, cardExpiryElementOptions, cardCvcElementOptions } = options;\n\n                        const cardNumberElement = this._stripeElements.getElement(StripeElementType.CardNumber) || this._stripeElements.create(StripeElementType.CardNumber, cardNumberElementOptions);\n                        const cardExpiryElement = this._stripeElements.getElement(StripeElementType.CardExpiry) || this._stripeElements.create(StripeElementType.CardExpiry, cardExpiryElementOptions);\n                        const cardCvcElement = this._stripeElements.getElement(StripeElementType.CardCvc) || this._stripeElements.create(StripeElementType.CardCvc, cardCvcElementOptions);\n\n                        this._stripeCardElements = [cardNumberElement, cardExpiryElement, cardCvcElement];\n                        stripeElement = this._stripeCardElements[0];\n\n                        try {\n                            cardNumberElement.mount(`#${cardNumberElementOptions.containerId}`);\n                            cardExpiryElement.mount(`#${cardExpiryElementOptions.containerId}`);\n                            cardCvcElement.mount(`#${cardCvcElementOptions.containerId}`);\n                        } catch (error) {\n                            reject(new InvalidArgumentError('Unable to mount Stripe component without valid container ID.'));\n                        }\n                    } else {\n                        stripeElement = this._stripeElements.getElement(stripeElementType) || this._stripeElements.create(stripeElementType, options as StripeElementOptions);\n\n                        try {\n                            stripeElement.mount(`#${containerId}`);\n                        } catch (error) {\n                            reject(new InvalidArgumentError('Unable to mount Stripe component without valid container ID.'));\n                        }\n                    }\n\n                    break;\n                case StripeElementType.iDEAL:\n                case StripeElementType.Sepa:\n                    stripeElement = this._stripeElements.getElement(stripeElementType) || this._stripeElements.create(stripeElementType, options as StripeElementOptions);\n\n                    try {\n                        stripeElement.mount(`#${containerId}`);\n                    } catch (error) {\n                        reject(new InvalidArgumentError('Unable to mount Stripe component without valid container ID.'));\n                    }\n\n                    break;\n\n                case StripeElementType.Alipay:\n                    break;\n            }\n\n            resolve(stripeElement);\n        });\n    }\n\n    private _mapStripeAddress(address?: Address): StripeAddress {\n        if (address) {\n            const {\n                city,\n                countryCode: country,\n                address1: line1,\n                address2: line2,\n                postalCode,\n                stateOrProvinceCode: state,\n            } = address;\n\n            return { city, country, line1, line2, postal_code: postalCode, state };\n        }\n\n        return { line1: '' };\n    }\n\n    private _mapStripeBillingDetails(billingAddress?: BillingAddress, customer?: Customer): StripeBillingDetails {\n        const { firstName, lastName } = billingAddress || customer || { firstName: 'Guest', lastName: '' };\n        const name = `${firstName} ${lastName}`.trim();\n        const { options } = this._getStripeInitializeOptions();\n\n        if (this._useIndividualCardFields && isIndividualCardElementOptions(options)) {\n            const { zipCodeElementOptions } = options;\n\n            if (zipCodeElementOptions) {\n                const postalCode = document.getElementById(zipCodeElementOptions.containerId) ? (document.getElementById(zipCodeElementOptions.containerId) as HTMLInputElement).value : '';\n\n                if (postalCode && billingAddress) {\n                    billingAddress = { ...billingAddress, postalCode };\n                }\n            }\n        }\n\n        const address = {\n            address:  this._mapStripeAddress(billingAddress),\n        };\n\n        if (customer && customer.addresses[0] && isBillingAddressLike(customer.addresses[0])) {\n            const customerAddress = customer.addresses[0];\n            const { email } = customer;\n            const { phone } = customerAddress;\n\n            return phone ? { ...address, email, name, phone } : { ...address, email, name };\n        }\n\n        if (billingAddress) {\n            const { email, phone } = billingAddress;\n\n            return phone ? { ...address, email, name, phone } : { ...address, email, name };\n        }\n\n        return { ...address, name };\n    }\n\n    private _mapStripePaymentData(element: StripePaymentMethodType.CreditCard, shouldSaveInstrument: boolean): StripeConfirmCardPaymentData;\n    private _mapStripePaymentData(element: StripePaymentMethodType.iDEAL, returnUrl?: string): StripeConfirmIdealPaymentData;\n    private _mapStripePaymentData(element: StripePaymentMethodType.Sepa): StripeConfirmSepaPaymentData;\n    private _mapStripePaymentData(element: StripePaymentMethodType, arg2?: any): StripeConfirmPaymentData {\n        const customer = this._store.getState().customer.getCustomer();\n        const billingAddress = this._store.getState().billingAddress.getBillingAddress();\n        let result: Partial<StripeConfirmPaymentData>;\n\n        result = {\n            payment_method: {\n                [element]: element === StripePaymentMethodType.CreditCard && this._useIndividualCardFields ? this._getStripeCardElements()[0] : this._getStripeElement(),\n                billing_details: this._mapStripeBillingDetails(billingAddress, customer),\n            },\n        };\n\n        switch (element) {\n            case StripePaymentMethodType.CreditCard:\n                const cart = this._store.getState().cart.getCart();\n\n                if (cart && getShippableItemsCount(cart) > 0) {\n                    const shippingAddress = this._store.getState().shippingAddress.getShippingAddress();\n                    result = { ...result, shipping: this._mapStripeShippingAddress(shippingAddress, customer) };\n                }\n\n                return arg2 ? { ...result, setup_future_usage: 'off_session' } : result;\n\n            case StripePaymentMethodType.iDEAL:\n                return { ...result, return_url: arg2 };\n\n        }\n\n        return result;\n    }\n\n    private _mapStripeShippingAddress(shippingAddress?: Address, customer?: Customer): StripeShippingAddress {\n        const { firstName, lastName } = shippingAddress || customer || { firstName: 'Guest', lastName: '' };\n        const name = `${firstName} ${lastName}`.trim();\n\n        const address = {\n            address:  this._mapStripeAddress(shippingAddress),\n        };\n\n        if (customer && customer.addresses[0]) {\n            const customerAddress = customer.addresses[0];\n            const { phone } = customerAddress;\n\n            return { ...address, name, phone };\n        }\n\n        if (shippingAddress) {\n            const { phone } = shippingAddress;\n\n            return {...address, name, phone};\n        }\n\n        return {...address, name};\n    }\n\n    private _unmountElement(): void {\n        if (this._stripeElement) {\n            this._stripeElement.unmount();\n            this._stripeElement = undefined;\n        }\n    }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { StripeHostWindow, StripeV3Client } from './stripev3';\n\nexport default class StripeV3ScriptLoader {\n    constructor(\n        private _scriptLoader: ScriptLoader,\n        private _window: StripeHostWindow = window\n    ) {}\n\n    load(stripePublishableKey: string, stripeAccount: string, locale?: string): Promise<StripeV3Client> {\n        return this._scriptLoader\n            .loadScript('https://js.stripe.com/v3/')\n            .then(() => {\n                if (!this._window.Stripe) {\n                    throw new PaymentMethodClientUnavailableError();\n                }\n\n                return this._window.Stripe(stripePublishableKey, {\n                    stripeAccount,\n                    locale,\n                    betas: ['payment_intent_beta_3', 'alipay_pm_beta_1'],\n                    apiVersion: '2020-03-02;alipay_beta=v1',\n                });\n            });\n    }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\n\nimport WepayRisk from './wepay-risk';\nimport WepayWindow from './wepay-window';\n\nconst SCRIPT_SRC = '//static.wepay.com/min/js/risk.1.latest.js';\n\nexport default class WepayRiskClient {\n    private _riskClient?: WepayRisk;\n\n    constructor(\n        private _scriptLoader: ScriptLoader\n    ) {}\n\n    initialize(): Promise<WepayRiskClient> {\n        return this._scriptLoader\n            .loadScript(SCRIPT_SRC)\n            .then(() => this._riskClient = (window as unknown as WepayWindow).WePay.risk)\n            .then(() => this);\n    }\n\n    getRiskToken(): string {\n        if (!this._riskClient) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        this._riskClient.generate_risk_token();\n\n        return this._riskClient.get_risk_token();\n    }\n}\n","import { merge } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nimport WepayRiskClient from './wepay-risk-client';\n\nexport default class WepayPaymentStrategy extends CreditCardPaymentStrategy {\n    constructor(\n        store: CheckoutStore,\n        orderActionCreator: OrderActionCreator,\n        paymentActionCreator: PaymentActionCreator,\n        hostedFormFactory: HostedFormFactory,\n        private _wepayRiskClient: WepayRiskClient\n    ) {\n        super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n    }\n\n    initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> {\n        this._wepayRiskClient.initialize();\n\n        return super.initialize(options);\n    }\n\n    execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const token = this._wepayRiskClient.getRiskToken();\n        const payloadWithToken = merge({}, payload, {\n            payment: {\n                paymentData: {\n                    deviceSessionId: token,\n                },\n            },\n        });\n\n        return super.execute(payloadWithToken, options);\n    }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if a payment method explicitly returns a declined error and\n * the shopper has to choose a different payment method if they wish to continue\n * their checkout process.\n */\nexport default class PaymentMethodDeclinedError extends StandardError {\n    constructor(message?: string) {\n        super(message || 'The selected payment method was declined. Please select another payment method.');\n\n        this.name = 'PaymentMethodDeclinedError';\n        this.type = 'payment_declined';\n    }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType, RequestError } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentMethodCancelledError, PaymentMethodDeclinedError, PaymentMethodInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport StorefrontPaymentRequestSender from '../../storefront-payment-request-sender';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { Zip, ZipModalEvent } from './zip';\nimport ZipScriptLoader from './zip-script-loader';\n\nexport default class ZipPaymentStrategy implements PaymentStrategy {\n    private _paymentMethod?: PaymentMethod;\n    private _zipClient?: Zip;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentActionCreator: PaymentActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _storeCreditActionCreator: StoreCreditActionCreator,\n        private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n        private _zipScriptLoader: ZipScriptLoader,\n        private _storefrontPaymentRequestSender: StorefrontPaymentRequestSender\n    ) { }\n\n    async initialize(): Promise<InternalCheckoutSelectors> {\n        const zip = await this._zipScriptLoader.load();\n        this._zipClient = zip;\n\n        return this._store.getState();\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        this._paymentMethod = undefined;\n        this._zipClient = undefined;\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> {\n        const { payment, ...order } = payload;\n        const { _zipClient: zipClient } = this;\n\n        if (!payment) {\n            throw new InvalidArgumentError('Unable to submit payment because \"payload.payment\" argument is not provided.');\n        }\n\n        if (!zipClient) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        const { isStoreCreditApplied: useStoreCredit } = this._store.getState().checkout.getCheckoutOrThrow();\n\n        if (useStoreCredit !== undefined) {\n            await this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(useStoreCredit));\n        }\n\n        await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n        await this._store.dispatch(this._remoteCheckoutActionCreator.initializePayment(payment.methodId, { useStoreCredit }));\n\n        const state = await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(payment.methodId, options));\n\n        this._paymentMethod = state.paymentMethods.getPaymentMethod(payment.methodId);\n\n        if (!this._paymentMethod || !this._paymentMethod.clientToken) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        if (this._redirectFlowIsTrue()) {\n            let nonce: { id: string };\n            try {\n                nonce = JSON.parse(this._paymentMethod.clientToken);\n            } catch (error) {\n                throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n            }\n\n            await this._prepareForReferredRegistration(payment.methodId, nonce.id);\n\n            try {\n                return await this._store.dispatch(this._paymentActionCreator.submitPayment({methodId: payment.methodId, paymentData: { nonce: nonce.id }}));\n            } catch (error) {\n                if (error instanceof RequestError && error.body.status === 'additional_action_required') {\n                    return new Promise(() => {\n                        const { redirect_url } = error.body.additional_action_required.data;\n                        window.location.replace(redirect_url);\n                    });\n                }\n                throw error;\n            }\n        }\n\n        const nonce = await new Promise<string | undefined>((resolve, reject) => {\n            zipClient.Checkout.init({\n                onComplete: async ({ checkoutId, state }) => {\n                    if (state === ZipModalEvent.CancelCheckout) {\n                        return reject(new PaymentMethodCancelledError());\n                    }\n\n                    if (state === ZipModalEvent.CheckoutReferred && checkoutId) {\n                        await this._prepareForReferredRegistration(payment.methodId, checkoutId);\n\n                        if (this._paymentMethod?.initializationData?.deferredFlowV2Enabled) {\n                            return resolve(checkoutId);\n                        }\n\n                        return resolve();\n                    }\n\n                    if (state === ZipModalEvent.CheckoutApproved && checkoutId) {\n                        return resolve(checkoutId);\n                    }\n\n                    if (state === ZipModalEvent.CheckoutDeclined) {\n                        return reject(new PaymentMethodDeclinedError('Unfortunately your application was declined. Please select another payment method.'));\n                    }\n\n                    reject(new PaymentMethodInvalidError());\n                },\n                onCheckout: openModal => {\n                    if (!this._paymentMethod || !this._paymentMethod.clientToken) {\n                        throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n                    }\n\n                    openModal(JSON.parse(this._paymentMethod.clientToken));\n                },\n            });\n        });\n\n        if (nonce !== undefined) {\n            return this._store.dispatch(this._paymentActionCreator.submitPayment({\n                methodId: payment.methodId,\n                paymentData: { nonce },\n            }));\n        }\n\n        return this._store.getState();\n    }\n\n    finalize(): Promise<InternalCheckoutSelectors> {\n        return Promise.reject(new OrderFinalizationNotRequiredError());\n    }\n\n    private _redirectFlowIsTrue(): boolean {\n        return this._paymentMethod?.initializationData?.redirectFlowV2Enabled;\n    }\n\n    private _prepareForReferredRegistration(methodId: string, externalId: string): Promise<void> {\n        return this._storefrontPaymentRequestSender.saveExternalId(methodId, externalId);\n    }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\nimport { Zip, ZipHostWindow } from '../zip';\n\nexport default class ZipScriptLoader {\n    constructor(\n        private _scriptLoader: ScriptLoader,\n        public _window: ZipHostWindow = window\n    ) {}\n\n    load(): Promise<Zip> {\n        return this._scriptLoader\n            .loadScript(`//static.zipmoney.com.au/checkout/checkout-v1.min.js`)\n            .then(() => {\n                if (!this._window.Zip) {\n                    throw new PaymentMethodClientUnavailableError();\n                }\n\n                return this._window.Zip;\n            });\n    }\n}\n","import { createAction, createDataStore, Action, DataStore, ReadableDataStore } from '@bigcommerce/data-store';\n\nenum ProjectionActionType {\n    Synchronize = 'SYNCHRONIZE',\n}\n\ninterface SynchronizeAction<TState> extends Action<TState> {\n    type: ProjectionActionType.Synchronize;\n    payload: TState;\n}\n\nexport interface DataStoreProjection<TTransformedState> extends ReadableDataStore<TTransformedState> {\n    notifyState(): void;\n}\n\nexport default function createDataStoreProjection<TState, TTransformedState = TState>(\n    store: DataStore<any, Action, TState>,\n    stateTransformer: (state: TState) => TTransformedState\n): DataStoreProjection<TTransformedState> {\n    const projection = createDataStore<TState | undefined, SynchronizeAction<TState>, TTransformedState>(\n        (state, action) => action.type === ProjectionActionType.Synchronize ?\n            action.payload :\n            state,\n        store.getState(),\n        { stateTransformer }\n    );\n\n    store.subscribe(state => {\n        projection.dispatch(createAction(ProjectionActionType.Synchronize, state) as SynchronizeAction<TState>);\n    }, { initial: false });\n\n    return projection;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { Address } from '../../address';\nimport { InternalCheckoutSelectors, ReadableCheckoutStore } from '../../checkout';\nimport { addMinutes, isFuture } from '../../common/date-time';\nimport { MissingDataError, MissingDataErrorType } from '../../common/error/errors';\n\nimport { SessionContext, VaultAccessToken } from './instrument';\nimport { DeleteInstrumentAction, InstrumentActionType, LoadInstrumentsAction } from './instrument-actions';\nimport InstrumentRequestSender from './instrument-request-sender';\n\nexport default class InstrumentActionCreator {\n    constructor(\n        private _instrumentRequestSender: InstrumentRequestSender\n    ) {}\n\n    loadInstruments(): ThunkAction<LoadInstrumentsAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<LoadInstrumentsAction>) => {\n            observer.next(createAction(InstrumentActionType.LoadInstrumentsRequested));\n\n            const session = this._getSessionContext(store);\n            const token = this._getCurrentAccessToken(store);\n            const shippingAddress = this._getShippingAddress(store);\n\n            return this._getValidAccessToken(token)\n                .then(currentToken =>\n                    this._instrumentRequestSender.loadInstruments({\n                            ...session,\n                            authToken: currentToken.vaultAccessToken,\n                        },\n                        shippingAddress\n                    )\n                        .then(({ body }) => {\n                            observer.next(createAction(\n                                InstrumentActionType.LoadInstrumentsSucceeded,\n                                body,\n                                currentToken\n                            ));\n                            observer.complete();\n                        })\n                )\n                .catch(response => {\n                    observer.error(createErrorAction(InstrumentActionType.LoadInstrumentsFailed, response));\n                });\n        });\n    }\n\n    deleteInstrument(instrumentId: string): ThunkAction<DeleteInstrumentAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<DeleteInstrumentAction>) => {\n            observer.next(createAction(InstrumentActionType.DeleteInstrumentRequested, undefined, { instrumentId }));\n\n            const session = this._getSessionContext(store);\n            const token = this._getCurrentAccessToken(store);\n\n            return this._getValidAccessToken(token)\n                .then(currentToken =>\n                    this._instrumentRequestSender.deleteInstrument({\n                        ...session,\n                        authToken: currentToken.vaultAccessToken,\n                    }, instrumentId)\n                        .then(({ body }) => {\n                            observer.next(createAction(InstrumentActionType.DeleteInstrumentSucceeded, body, {\n                                instrumentId,\n                                ...currentToken,\n                            }));\n                            observer.complete();\n                        })\n                )\n                .catch(response => {\n                    observer.error(createErrorAction(InstrumentActionType.DeleteInstrumentFailed, response, { instrumentId }));\n                });\n        });\n    }\n\n    private _isValidVaultAccessToken(token: VaultAccessToken): boolean {\n        if (!token || !token.vaultAccessToken) {\n            return false;\n        }\n\n        const expiryBuffer = 2;\n        const expiry = addMinutes(new Date(token.vaultAccessExpiry), expiryBuffer);\n\n        return isFuture(expiry);\n    }\n\n    private _getCurrentAccessToken(store: ReadableCheckoutStore): VaultAccessToken | undefined {\n        const { instruments } = store.getState();\n        const meta = instruments.getInstrumentsMeta();\n\n        if (!meta) {\n            return;\n        }\n\n        return {\n            vaultAccessToken: meta.vaultAccessToken,\n            vaultAccessExpiry: meta.vaultAccessExpiry,\n        };\n    }\n\n    private _getValidAccessToken(token?: VaultAccessToken): Promise<VaultAccessToken> {\n        return token && this._isValidVaultAccessToken(token) ?\n            Promise.resolve(token) :\n            this._instrumentRequestSender.getVaultAccessToken().then(({ body }) => body);\n    }\n\n    private _getShippingAddress(store: ReadableCheckoutStore): Address | undefined {\n        const state = store.getState();\n\n        return state.shippingAddress.getShippingAddress();\n    }\n\n    private _getSessionContext(store: ReadableCheckoutStore): SessionContext {\n        const state = store.getState();\n        const config = state.config.getStoreConfig();\n        const cart = state.cart.getCart();\n\n        if (!config) {\n            throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n        }\n\n        if (!cart) {\n            throw new MissingDataError(MissingDataErrorType.MissingCart);\n        }\n\n        const { customerId } = cart;\n        const { storeId } = config.storeProfile;\n        const { code } = config.shopperCurrency.isTransactional ? config.shopperCurrency : config.currency;\n\n        return {\n            customerId,\n            storeId,\n            currencyCode: code,\n        };\n    }\n}\n","export default function isFuture(date: Date): boolean {\n    return date.valueOf() > Date.now();\n}\n","export default function addMinutes(date: Date, amount: number): Date {\n    const newDate = new Date(date.getTime());\n\n    newDate.setMinutes(date.getMinutes() + amount);\n\n    return newDate;\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport PaymentResponse from '../payment-response';\n\nimport PaymentInstrument, { VaultAccessToken } from './instrument';\nimport { BankInternalInstrument, InstrumentsResponseBody, InstrumentErrorResponseBody, InternalInstrument, InternalInstrumentsResponseBody, InternalInstrumentErrorResponseBody, InternalVaultAccessTokenResponseBody, PayPalInternalInstrument } from './instrument-response-body';\nimport { mapToBankInstrument } from './map-to-bank-instrument';\nimport { mapToCardInstrument } from './map-to-card-instrument';\nimport { mapToPayPalInstrument } from './map-to-paypal-instrument';\n\nexport default class InstrumentResponseTransformer {\n    transformResponse(\n        response: PaymentResponse<InternalInstrumentsResponseBody>\n    ): Response<InstrumentsResponseBody> {\n        const { body, ...payload } = this._transformResponse(response);\n\n        return {\n            ...payload,\n            body: {\n                vaultedInstruments: this._transformVaultedInstruments(body.vaulted_instruments),\n            },\n        };\n    }\n\n    transformErrorResponse(\n        response: PaymentResponse<InternalInstrumentErrorResponseBody>\n    ): Response<InstrumentErrorResponseBody> {\n        return this._transformResponse(response);\n    }\n\n    transformVaultAccessResponse(\n        response: Response<InternalVaultAccessTokenResponseBody>\n    ): Response<VaultAccessToken> {\n        return {\n            ...response,\n            body: {\n                vaultAccessToken: response.body.data.token,\n                vaultAccessExpiry: response.body.data.expires_at,\n            },\n        };\n    }\n\n    private _transformVaultedInstruments(vaultedInstruments: InternalInstrument[] = []): PaymentInstrument[] {\n        return vaultedInstruments\n            .map(instrument => {\n                if (this._isPayPalInstrument(instrument)) {\n                    return mapToPayPalInstrument(instrument);\n                }\n\n                if (this._isBankInstrument(instrument)) {\n                    return mapToBankInstrument(instrument);\n                }\n\n                return mapToCardInstrument(instrument);\n            });\n    }\n\n    private _isPayPalInstrument(instrument: InternalInstrument): instrument is PayPalInternalInstrument {\n        return instrument.method_type === 'paypal';\n    }\n\n    private _isBankInstrument(instrument: InternalInstrument): instrument is BankInternalInstrument {\n        return instrument.method_type === 'bank';\n    }\n\n    private _transformResponse<T>(response: PaymentResponse<T>): Response<T> {\n        const { data: body, ...payload } = response;\n\n        return {\n            ...payload,\n            body,\n        };\n    }\n}\n","import { PayPalInstrument } from './instrument';\nimport { PayPalInternalInstrument } from './instrument-response-body';\n\nexport function mapToPayPalInstrument(instrument: PayPalInternalInstrument): PayPalInstrument {\n    return {\n        bigpayToken: instrument.bigpay_token,\n        defaultInstrument: instrument.default_instrument,\n        provider: instrument.provider,\n        externalId: instrument.external_id,\n        trustedShippingAddress: instrument.trusted_shipping_address,\n        method: 'paypal',\n        type: 'account',\n    };\n}\n","import { BankInstrument } from './instrument';\nimport { BankInternalInstrument } from './instrument-response-body';\n\nexport function mapToBankInstrument(instrument: BankInternalInstrument): BankInstrument {\n    return {\n        bigpayToken: instrument.bigpay_token,\n        defaultInstrument: instrument.default_instrument,\n        provider: instrument.provider,\n        externalId: instrument.external_id,\n        trustedShippingAddress: instrument.trusted_shipping_address,\n        accountNumber: instrument.account_number,\n        issuer: instrument.issuer,\n        iban: instrument.iban,\n        method: instrument.method,\n        type: 'bank',\n    };\n}\n","import { CardInstrument } from './instrument';\nimport { CardInternalInstrument } from './instrument-response-body';\n\nexport function mapToCardInstrument(instrument: CardInternalInstrument): CardInstrument {\n    return {\n        bigpayToken: instrument.bigpay_token,\n        defaultInstrument: instrument.default_instrument,\n        provider: instrument.provider,\n        iin: instrument.iin,\n        last4: instrument.last_4,\n        expiryMonth: instrument.expiry_month,\n        expiryYear: instrument.expiry_year,\n        brand: instrument.brand,\n        trustedShippingAddress: instrument.trusted_shipping_address,\n        method: instrument.method,\n        type: 'card',\n    };\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { mapToInternalAddress, Address } from '../../address';\nimport { RequestOptions } from '../../common/http-request';\nimport PaymentResponse from '../payment-response';\n\nimport { InstrumentRequestContext, VaultAccessToken } from './instrument';\nimport { InstrumentsResponseBody, InternalInstrumentsResponseBody, InternalInstrumentErrorResponseBody, InternalVaultAccessTokenResponseBody } from './instrument-response-body';\nimport InstrumentResponseTransformer from './instrument-response-transformer';\n\nexport default class InstrumentRequestSender {\n    private _transformer: InstrumentResponseTransformer;\n\n    constructor(\n        private _client: any,\n        private _requestSender: RequestSender\n    ) {\n        this._transformer = new InstrumentResponseTransformer();\n    }\n\n    getVaultAccessToken(\n        { timeout }: RequestOptions = {}\n    ): Promise<Response<VaultAccessToken>> {\n        const url = '/internalapi/v1/checkout/payments/vault-access-token';\n\n        return this._requestSender.get<InternalVaultAccessTokenResponseBody>(url, { timeout }).then(response => ({\n            ...response,\n            body: {\n                vaultAccessToken: response.body.data.token,\n                vaultAccessExpiry: response.body.data.expires_at,\n            },\n        }));\n    }\n\n    loadInstruments(\n        requestContext: InstrumentRequestContext,\n        shippingAddress?: Address\n    ): Promise<Response<InstrumentsResponseBody>> {\n        return (shippingAddress) ?\n            this._loadInstrumentsWithAddress(requestContext, shippingAddress) :\n            this._loadInstruments(requestContext);\n    }\n\n    deleteInstrument(\n        requestContext: InstrumentRequestContext,\n        instrumentId: string\n    ): Promise<Response<InstrumentsResponseBody>> {\n        const payload = {\n            ...requestContext,\n            instrumentId,\n        };\n\n        return new Promise((resolve, reject) => {\n            this._client.deleteShopperInstrument(\n                payload, (\n                    errorResponse: PaymentResponse<InternalInstrumentErrorResponseBody>,\n                    response: PaymentResponse<InternalInstrumentsResponseBody>\n                ) =>  errorResponse ?\n                    reject(this._transformer.transformErrorResponse(errorResponse)) :\n                    resolve(this._transformer.transformResponse(response))\n            );\n        });\n    }\n\n    private _loadInstruments(\n        requestContext: InstrumentRequestContext\n    ): Promise<Response<InstrumentsResponseBody>> {\n        return new Promise((resolve, reject) => {\n            this._client.loadInstruments(\n                requestContext, (\n                    errorResponse: PaymentResponse<InternalInstrumentErrorResponseBody>,\n                    response: PaymentResponse<InternalInstrumentsResponseBody>\n                ) => errorResponse ?\n                    reject(this._transformer.transformErrorResponse(errorResponse)) :\n                    resolve(this._transformer.transformResponse(response))\n            );\n        });\n    }\n\n    private _loadInstrumentsWithAddress(\n        requestContext: InstrumentRequestContext,\n        shippingAddress: Address\n    ): Promise<Response<InstrumentsResponseBody>> {\n        const payload = {\n            ...requestContext,\n            shippingAddress: mapToInternalAddress(shippingAddress),\n        };\n\n        return new Promise((resolve, reject) => {\n            this._client.loadInstrumentsWithAddress(\n                payload, (\n                    errorResponse: PaymentResponse<InternalInstrumentErrorResponseBody>,\n                    response: PaymentResponse<InternalInstrumentsResponseBody>\n                ) => errorResponse ?\n                    reject(this._transformer.transformErrorResponse(errorResponse)) :\n                    resolve(this._transformer.transformResponse(response))\n            );\n        });\n    }\n}\n","import { createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { RequestOptions } from '../common/http-request';\n\nimport { LoadShippingCountriesAction, ShippingCountryActionType } from './shipping-country-actions';\nimport ShippingCountryRequestSender from './shipping-country-request-sender';\n\nexport default class ShippingCountryActionCreator {\n    constructor(\n        private _shippingCountryRequestSender: ShippingCountryRequestSender\n    ) {}\n\n    loadCountries(options?: RequestOptions): Observable<LoadShippingCountriesAction> {\n        return Observable.create((observer: Observer<LoadShippingCountriesAction>) => {\n            observer.next(createAction(ShippingCountryActionType.LoadShippingCountriesRequested));\n\n            this._shippingCountryRequestSender.loadCountries(options)\n                .then(response => {\n                    observer.next(createAction(ShippingCountryActionType.LoadShippingCountriesSucceeded, response.body.data));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(ShippingCountryActionType.LoadShippingCountriesFailed, response));\n                });\n        });\n    }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions } from '../common/http-request';\nimport { CountryResponseBody } from '../geography';\n\nexport default class ShippingCountryRequestSender {\n    constructor(\n        private _requestSender: RequestSender,\n        private _config: { locale?: string }\n    ) {}\n\n    loadCountries({ timeout }: RequestOptions = {}): Promise<Response<CountryResponseBody>> {\n        const url = '/internalapi/v1/shipping/countries';\n        const headers = {\n            'Accept-Language': this._config.locale,\n        };\n\n        return this._requestSender.get(url, { headers, timeout });\n    }\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { AddressRequestBody } from '../address';\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { Registry } from '../common/registry';\n\nimport { ShippingInitializeOptions, ShippingRequestOptions } from './shipping-request-options';\nimport { ShippingStrategyAction, ShippingStrategyActionType, ShippingStrategyDeinitializeAction, ShippingStrategyInitializeAction, ShippingStrategySelectOptionAction, ShippingStrategyUpdateAddressAction } from './shipping-strategy-actions';\nimport { ShippingStrategy } from './strategies';\n\nexport default class ShippingStrategyActionCreator {\n    constructor(\n        private _strategyRegistry: Registry<ShippingStrategy>\n    ) {}\n\n    updateAddress(address: Partial<AddressRequestBody>, options?: ShippingRequestOptions): ThunkAction<ShippingStrategyUpdateAddressAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<ShippingStrategyUpdateAddressAction>) => {\n            const payment = store.getState().payment.getPaymentId();\n            const methodId = options && options.methodId || payment && payment.providerId;\n\n            observer.next(createAction(ShippingStrategyActionType.UpdateAddressRequested, undefined, { methodId }));\n\n            this._strategyRegistry.get(methodId)\n                .updateAddress(address, { ...options, methodId })\n                .then(() => {\n                    observer.next(createAction(ShippingStrategyActionType.UpdateAddressSucceeded, undefined, { methodId }));\n                    observer.complete();\n                })\n                .catch(error => {\n                    observer.error(createErrorAction(ShippingStrategyActionType.UpdateAddressFailed, error, { methodId }));\n                });\n        });\n    }\n\n    selectOption(shippingOptionId: string, options?: ShippingRequestOptions): ThunkAction<ShippingStrategySelectOptionAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<ShippingStrategySelectOptionAction>) => {\n            const payment = store.getState().payment.getPaymentId();\n            const methodId = options && options.methodId || payment && payment.providerId;\n\n            observer.next(createAction(ShippingStrategyActionType.SelectOptionRequested, undefined, { methodId }));\n\n            this._strategyRegistry.get(methodId)\n                .selectOption(shippingOptionId, { ...options, methodId })\n                .then(() => {\n                    observer.next(createAction(ShippingStrategyActionType.SelectOptionSucceeded, undefined, { methodId }));\n                    observer.complete();\n                })\n                .catch(error => {\n                    observer.error(createErrorAction(ShippingStrategyActionType.SelectOptionFailed, error, { methodId }));\n                });\n        });\n    }\n\n    initialize(options?: ShippingInitializeOptions): ThunkAction<ShippingStrategyInitializeAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<ShippingStrategyInitializeAction>) => {\n            const state = store.getState();\n            const payment = state.payment.getPaymentId();\n            const methodId = options && options.methodId || payment && payment.providerId;\n            const mergedOptions = { ...options, methodId };\n\n            if (methodId && state.shippingStrategies.isInitialized(methodId)) {\n                return observer.complete();\n            }\n\n            observer.next(createAction(ShippingStrategyActionType.InitializeRequested, undefined, { methodId }));\n\n            this._strategyRegistry.get(methodId)\n                .initialize(mergedOptions)\n                .then(() => {\n                    observer.next(createAction(ShippingStrategyActionType.InitializeSucceeded, undefined, { methodId }));\n                    observer.complete();\n                })\n                .catch(error => {\n                    observer.error(createErrorAction(ShippingStrategyActionType.InitializeFailed, error, { methodId }));\n                });\n        });\n    }\n\n    deinitialize(options?: ShippingRequestOptions): ThunkAction<ShippingStrategyDeinitializeAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<ShippingStrategyDeinitializeAction>) => {\n            const state = store.getState();\n            const payment = state.payment.getPaymentId();\n            const methodId = options && options.methodId || payment && payment.providerId;\n\n            if (methodId && !state.shippingStrategies.isInitialized(methodId)) {\n                return observer.complete();\n            }\n\n            observer.next(createAction(ShippingStrategyActionType.DeinitializeRequested, undefined, { methodId }));\n\n            this._strategyRegistry.get(methodId)\n                .deinitialize({ ...options, methodId })\n                .then(() => {\n                    observer.next(createAction(ShippingStrategyActionType.DeinitializeSucceeded, undefined, { methodId }));\n                    observer.complete();\n                })\n                .catch(error => {\n                    observer.error(createErrorAction(ShippingStrategyActionType.DeinitializeFailed, error, { methodId }));\n                });\n        });\n    }\n\n    widgetInteraction(method: () => Promise<any>, options?: ShippingRequestOptions): Observable<ShippingStrategyAction> {\n        return Observable.create((observer: Observer<ShippingStrategyAction>) => {\n            const methodId = options && options.methodId;\n            const meta = { methodId };\n\n            observer.next(createAction(ShippingStrategyActionType.WidgetInteractionStarted, undefined, meta));\n\n            method().then(() => {\n                observer.next(createAction(ShippingStrategyActionType.WidgetInteractionFinished, undefined, meta));\n                observer.complete();\n            })\n            .catch(error => {\n                observer.error(createErrorAction(ShippingStrategyActionType.WidgetInteractionFailed, error, meta));\n            });\n        });\n    }\n}\n","import { createAction, createErrorAction } from '@bigcommerce/data-store';\n\nimport { isInternalAddressEqual, mapFromInternalAddress, AddressRequestBody } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport { AmazonPayAddressBook, AmazonPayOrderReference, AmazonPayScriptLoader, AmazonPayWindow } from '../../../payment/strategies/amazon-pay';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { RemoteCheckoutSynchronizationError } from '../../../remote-checkout/errors';\nimport ConsignmentActionCreator from '../../consignment-action-creator';\nimport { ShippingInitializeOptions, ShippingRequestOptions } from '../../shipping-request-options';\nimport { ShippingStrategyActionType } from '../../shipping-strategy-actions';\nimport ShippingStrategy from '../shipping-strategy';\n\nimport AmazonPayShippingInitializeOptions from './amazon-pay-shipping-initialize-options';\n\nexport default class AmazonPayShippingStrategy implements ShippingStrategy {\n    private _paymentMethod?: PaymentMethod;\n    private _window: AmazonPayWindow;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _consignmentActionCreator: ConsignmentActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n        private _scriptLoader: AmazonPayScriptLoader\n    ) {\n        this._window = window;\n    }\n\n    initialize(options: ShippingInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { amazon: amazonOptions, methodId } = options;\n\n        if (!amazonOptions || !methodId) {\n            throw new InvalidArgumentError('Unable to proceed because \"options.amazon\" argument is not provided.');\n        }\n\n        return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n            .then(state => new Promise((resolve, reject) => {\n                this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n                if (!this._paymentMethod) {\n                    throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n                }\n\n                const onReady = () => {\n                    this._createAddressBook(amazonOptions)\n                        .then(resolve)\n                        .catch(reject);\n                };\n\n                this._scriptLoader.loadWidget(this._paymentMethod, onReady)\n                    .catch(reject);\n            }))\n            .then(() => this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        this._paymentMethod = undefined;\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    updateAddress(address: AddressRequestBody, options?: ShippingRequestOptions): Promise<InternalCheckoutSelectors> {\n        const updateAddressRequestBody = {\n            ...this._store.getState().shippingAddress.getShippingAddress(),\n            customFields: address.customFields,\n        } as AddressRequestBody;\n\n        return this._store.dispatch(\n            this._consignmentActionCreator.updateAddress(updateAddressRequestBody, options)\n        );\n    }\n\n    selectOption(optionId: string, options?: ShippingRequestOptions): Promise<InternalCheckoutSelectors> {\n        return this._store.dispatch(\n            this._consignmentActionCreator.selectShippingOption(optionId, options)\n        );\n    }\n\n    private _createAddressBook(options: AmazonPayShippingInitializeOptions): Promise<AmazonPayAddressBook> {\n        return new Promise((resolve, reject) => {\n            const { container, onAddressSelect = () => {}, onError = () => {}, onReady = () => {} } = options;\n            const merchantId = this._paymentMethod && this._paymentMethod.config.merchantId;\n\n            if (!document.getElementById(container)) {\n                return reject(new InvalidArgumentError('Unable to create AmazonPay AddressBook widget without valid container ID.'));\n            }\n\n            if (!this._window.OffAmazonPayments) {\n                return reject(new NotInitializedError(NotInitializedErrorType.ShippingNotInitialized));\n            }\n\n            if (!merchantId) {\n                return reject(new MissingDataError(MissingDataErrorType.MissingPaymentMethod));\n            }\n\n            const widget = new this._window.OffAmazonPayments.Widgets.AddressBook({\n                design: {\n                    designMode: 'responsive',\n                },\n                scope: 'payments:billing_address payments:shipping_address payments:widget profile',\n                sellerId: merchantId,\n                onAddressSelect: orderReference => {\n                    this._synchronizeShippingAddress()\n                        .then(() => onAddressSelect(orderReference))\n                        .catch(onError);\n                },\n                onError: error => {\n                    reject(error);\n                    onError(error);\n                },\n                onReady: orderReference => {\n                    this._updateOrderReference(orderReference)\n                        .then(() => {\n                            resolve();\n                            onReady(orderReference);\n                        })\n                        .catch(onError);\n                },\n            });\n\n            widget.bind(container);\n\n            return widget;\n        });\n    }\n\n    private _synchronizeShippingAddress(): Promise<InternalCheckoutSelectors> {\n        const methodId = this._paymentMethod && this._paymentMethod.id;\n        const amazon = this._store.getState().remoteCheckout.getCheckout('amazon');\n        const referenceId = amazon ? amazon.referenceId : undefined;\n\n        if (!methodId || !referenceId) {\n            throw new RemoteCheckoutSynchronizationError();\n        }\n\n        return this._store.dispatch(\n            createAction(ShippingStrategyActionType.UpdateAddressRequested, undefined, { methodId })\n        )\n            .then(() => this._store.dispatch(\n                this._remoteCheckoutActionCreator.initializeShipping(methodId, { referenceId })\n            ))\n            .then(state => {\n                const amazon = state.remoteCheckout.getCheckout('amazon');\n                const remoteAddress = amazon && amazon.shipping && amazon.shipping.address;\n                const address = state.shippingAddress.getShippingAddress();\n\n                if (remoteAddress === false) {\n                    throw new RemoteCheckoutSynchronizationError();\n                }\n\n                if (!remoteAddress || isInternalAddressEqual(remoteAddress, address || {})) {\n                    return this._store.getState();\n                }\n\n                return this._store.dispatch(\n                    this._consignmentActionCreator.updateAddress(mapFromInternalAddress(remoteAddress))\n                );\n            })\n            .then(() => this._store.dispatch(\n                createAction(ShippingStrategyActionType.UpdateAddressSucceeded, undefined, { methodId })\n            ))\n            .catch(error => this._store.dispatch(\n                createErrorAction(ShippingStrategyActionType.UpdateAddressFailed, error, { methodId })\n            ));\n    }\n\n    private _updateOrderReference(orderReference: AmazonPayOrderReference): Promise<InternalCheckoutSelectors> {\n        return this._store.dispatch(\n            this._remoteCheckoutActionCreator.updateCheckout('amazon', {\n                referenceId: orderReference.getAmazonOrderReferenceId(),\n            })\n        );\n    }\n}\n","import { noop } from 'rxjs';\n\nimport { ConsignmentActionCreator, ShippingStrategyActionCreator } from '../..';\nimport { AddressRequestBody } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, MissingDataError, MissingDataErrorType } from '../../../common/error/errors';\nimport { PaymentMethodActionCreator } from '../../../payment';\nimport { AmazonPayV2ChangeActionType, AmazonPayV2PaymentProcessor } from '../../../payment/strategies/amazon-pay-v2';\nimport { ShippingInitializeOptions, ShippingRequestOptions } from '../../shipping-request-options';\nimport ShippingStrategy from '../shipping-strategy';\n\nexport default class AmazonPayV2ShippingStrategy implements ShippingStrategy {\n    constructor(\n        private _store: CheckoutStore,\n        private _consignmentActionCreator: ConsignmentActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor,\n        private _shippingStrategyActionCreator: ShippingStrategyActionCreator\n    ) {}\n\n    updateAddress(address: AddressRequestBody, options?: ShippingRequestOptions): Promise<InternalCheckoutSelectors> {\n        const shippingAddress = this._store.getState().shippingAddress.getShippingAddress();\n\n        if (!shippingAddress) {\n            throw new MissingDataError(MissingDataErrorType.MissingShippingAddress);\n        }\n\n        const updateAddressRequestBody = {\n            ...shippingAddress,\n            customFields: address.customFields,\n        };\n\n        return this._store.dispatch(\n            this._consignmentActionCreator.updateAddress(updateAddressRequestBody, options)\n        );\n    }\n\n    selectOption(optionId: string, options?: ShippingRequestOptions): Promise<InternalCheckoutSelectors> {\n        return this._store.dispatch(\n            this._consignmentActionCreator.selectShippingOption(optionId, options)\n        );\n    }\n\n    async initialize(options: ShippingInitializeOptions): Promise<InternalCheckoutSelectors> {\n        const { amazonpay, methodId } = options;\n\n        if (!amazonpay || !methodId) {\n            throw new InvalidArgumentError('Unable to proceed because \"options.amazonpay\" argument is not provided.');\n        }\n\n        const state = await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId));\n        const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n        await this._amazonPayV2PaymentProcessor.initialize(paymentMethod);\n\n        const { paymentToken } = paymentMethod.initializationData;\n        const buttonId = amazonpay.editAddressButtonId;\n\n        if (paymentToken && buttonId) {\n            this._bindEditButton(buttonId, paymentToken, 'changeAddress');\n        }\n\n        return this._store.getState();\n    }\n\n    async deinitialize(): Promise<InternalCheckoutSelectors> {\n        await this._amazonPayV2PaymentProcessor.deinitialize();\n\n        return Promise.resolve(this._store.getState());\n    }\n\n    private _bindEditButton(id: string, sessionId: string, changeAction: AmazonPayV2ChangeActionType): void {\n        const button = document.getElementById(id);\n\n        if (!button || !button.parentNode) {\n            return;\n        }\n\n        const clone = button.cloneNode(true);\n        button.parentNode.replaceChild(clone, button);\n\n        clone.addEventListener('click', () => this._showLoadingSpinner(() => new Promise(noop)));\n\n        this._amazonPayV2PaymentProcessor.bindButton(id, sessionId, changeAction);\n    }\n\n    private _showLoadingSpinner(callback?: () => Promise<void> | Promise<never>): Promise<InternalCheckoutSelectors> {\n        return this._store.dispatch(this._shippingStrategyActionCreator.widgetInteraction(() => {\n\n            if (callback) {\n                return callback();\n            }\n\n            return Promise.reject();\n        }), { queueId: 'widgetInteraction' });\n    }\n}\n","import { AddressRequestBody } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport ConsignmentActionCreator from '../../consignment-action-creator';\nimport { ShippingRequestOptions } from '../../shipping-request-options';\nimport ShippingStrategy from '../shipping-strategy';\n\nexport default class DefaultShippingStrategy implements ShippingStrategy {\n    constructor(\n        private _store: CheckoutStore,\n        private _consignmentActionCreator: ConsignmentActionCreator\n    ) {}\n\n    updateAddress(address: AddressRequestBody, options?: ShippingRequestOptions): Promise<InternalCheckoutSelectors> {\n        return this._store.dispatch(\n            this._consignmentActionCreator.updateAddress(address, options)\n        );\n    }\n\n    selectOption(optionId: string, options?: ShippingRequestOptions): Promise<InternalCheckoutSelectors> {\n        return this._store.dispatch(\n            this._consignmentActionCreator.selectShippingOption(optionId, options)\n        );\n    }\n\n    initialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n\n    deinitialize(): Promise<InternalCheckoutSelectors> {\n        return Promise.resolve(this._store.getState());\n    }\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { concat, defer, of, Observable } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\n\nimport { SignInEmailRequestBody } from './signin-email';\nimport { SendSignInEmailAction, SignInEmailActionType } from './signin-email-actions';\nimport SignInEmailRequestSender from './signin-email-request-sender';\n\nexport default class SignInEmailActionCreator {\n    constructor(\n        private _requestSender: SignInEmailRequestSender\n    ) {}\n\n    sendSignInEmail(\n        emailRequest: SignInEmailRequestBody,\n        options?: RequestOptions\n    ): Observable<SendSignInEmailAction> {\n        return concat(\n            of(createAction(SignInEmailActionType.SendSignInEmailRequested)),\n            defer(async () => {\n                const { body } = await this._requestSender.sendSignInEmail(emailRequest, options);\n\n                return createAction(SignInEmailActionType.SendSignInEmailSucceeded, body);\n            })\n        ).pipe(\n            catchError(error => throwErrorAction(SignInEmailActionType.SendSignInEmailFailed, error))\n        );\n    }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, RequestOptions } from '../common/http-request';\nimport { parseUrl } from '../common/url';\n\nimport { SignInEmail, SignInEmailRequestBody } from './signin-email';\n\nexport default class SignInEmailRequestSender {\n    constructor(\n        private _requestSender: RequestSender\n    ) {}\n\n    sendSignInEmail(\n        {\n            email,\n            redirectUrl,\n        }: SignInEmailRequestBody,\n        {\n            timeout,\n        }: RequestOptions = {}\n    ): Promise<Response<SignInEmail>> {\n        const url = '/login.php?action=passwordless_login';\n        const headers = { Accept: ContentType.JsonV1 };\n\n        return this._requestSender.post(url, { body: {\n            email,\n            redirect_url: redirectUrl || parseUrl(window.top.location.href).pathname,\n        }, headers, timeout });\n    }\n}\n","import { memoize } from 'lodash';\n\nimport isPlainObject from './is-plain-object';\n\nconst cloneDeep = memoize(<T>(input: T): T => {\n    if (Array.isArray(input)) {\n        return input.map((value: T[keyof T]) => (\n            cloneDeepSafe(value)\n        )) as any;\n    }\n\n    if (isPlainObject(input)) {\n        return (Object.keys(input) as Array<keyof T>)\n            .reduce((result, key) => ({\n                ...result,\n                [key]: cloneDeepSafe(input[key]),\n            }), {}) as T;\n    }\n\n    return input;\n});\n\n// Use WeakMap as the MapCache, this allows for better garbage collection\n// There's a deprecated `clear` method in the lodash implementation\n// of MapCache, hence the `any`\ncloneDeep.cache = new WeakMap() as any;\n\n/**\n * This is a wrapper function for `cloneDeep`. We need it because `cloneDeep` is\n * a memoized function using an instance of `WeakMap` as its cache. Without this\n * wrapper, the memoized function will throw an error if it is called with a\n * non-object argument.\n */\nconst cloneDeepSafe = <T>(input: T): T => {\n    return typeof input === 'object' && input !== null ?\n        cloneDeep(input) :\n        input;\n};\n\n/**\n * Clone the return value of a function. If the result is the same as previous\n * calls, return the previous clone instead of cloning it again.\n */\nexport default function cloneResult<T extends Func>(fn: T): T {\n    return ((...args: any[]) => cloneDeepSafe(fn(...args))) as T;\n}\n\nexport type Func = (...args: any[]) => any;\n","import { createSelectorCreator, defaultMemoize } from 'reselect';\nimport shallowEqual from 'shallowequal';\n\nimport withMemoizedCombiner from './with-memoized-combiner';\n\nconst createShallowEqualSelector = createSelectorCreator(\n    defaultMemoize,\n    (a: any, b: any) => shallowEqual(a, b)\n);\n\nexport default withMemoizedCombiner(createShallowEqualSelector);\n","import { createCheckoutStoreErrorSelectorFactory, createCheckoutStoreSelectorFactory, createCheckoutStoreStatusSelectorFactory, CheckoutSelectors, InternalCheckoutSelectors } from '../checkout';\n\nexport type CheckoutSelectorsFactory = (selectors: InternalCheckoutSelectors) => CheckoutSelectors;\n\nexport function createCheckoutSelectorsFactory(): CheckoutSelectorsFactory {\n    const createCheckoutStoreSelector = createCheckoutStoreSelectorFactory();\n    const createCheckoutStoreErrorSelector = createCheckoutStoreErrorSelectorFactory();\n    const createCheckoutStoreStatusSelector = createCheckoutStoreStatusSelectorFactory();\n\n    return (selectors: InternalCheckoutSelectors) => {\n        const data = createCheckoutStoreSelector(selectors);\n        const errors = createCheckoutStoreErrorSelector(selectors);\n        const statuses = createCheckoutStoreStatusSelector(selectors);\n\n        return {\n            data,\n            errors,\n            statuses,\n        };\n    };\n}\n\nexport default function createCheckoutSelectors(selectors: InternalCheckoutSelectors): CheckoutSelectors {\n    return createCheckoutSelectorsFactory()(selectors);\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { omit, values } from 'lodash';\n\nimport { Address } from '../address';\nimport { BillingAddress } from '../billing';\nimport { Cart } from '../cart';\nimport { createSelector } from '../common/selector';\nimport { cloneResult as clone } from '../common/utility';\nimport { FlashMessage, FlashMessageType, StoreConfig } from '../config';\nimport { Coupon, GiftCertificate } from '../coupon';\nimport { Customer } from '../customer';\nimport { FormField } from '../form';\nimport { Country } from '../geography';\nimport { Order } from '../order';\nimport { PaymentMethod } from '../payment';\nimport { CardInstrument, PaymentInstrument } from '../payment/instrument';\nimport { Consignment, ShippingOption } from '../shipping';\nimport { SignInEmail } from '../signin-email';\n\nimport Checkout from './checkout';\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\nexport type Instrument = CardInstrument;\n\n/**\n * Responsible for getting the state of the current checkout.\n *\n * This object has a set of methods that allow you to get a specific piece of\n * checkout information, such as shipping and billing details.\n */\nexport default interface CheckoutStoreSelector {\n    /**\n     * Gets the current checkout.\n     *\n     * @returns The current checkout if it is loaded, otherwise undefined.\n     */\n    getCheckout(): Checkout | undefined;\n\n    /**\n     * Gets the current order.\n     *\n     * @returns The current order if it is loaded, otherwise undefined.\n     */\n    getOrder(): Order | undefined;\n\n    /**\n     * Gets the checkout configuration of a store.\n     *\n     * @returns The configuration object if it is loaded, otherwise undefined.\n     */\n    getConfig(): StoreConfig | undefined;\n\n    /**\n     * Gets the sign-in email.\n     *\n     * @returns The sign-in email object if sent, otherwise undefined\n     */\n    getSignInEmail(): SignInEmail | undefined;\n\n    /**\n     * Gets the shipping address of the current checkout.\n     *\n     * If the address is partially complete, it may not have shipping options\n     * associated with it.\n     *\n     * @returns The shipping address object if it is loaded, otherwise\n     * undefined.\n     */\n    getShippingAddress(): Address | undefined;\n\n    /**\n     * Gets a list of shipping options available for the shipping address.\n     *\n     * If there is no shipping address assigned to the current checkout, the\n     * list of shipping options will be empty.\n     *\n     * @returns The list of shipping options if any, otherwise undefined.\n     */\n    getShippingOptions(): ShippingOption[] | undefined;\n\n    /**\n     * Gets a list of consignments.\n     *\n     * If there are no consignments created for to the current checkout, the\n     * list will be empty.\n     *\n     * @returns The list of consignments if any, otherwise undefined.\n     */\n    getConsignments(): Consignment[] | undefined;\n\n    /**\n     * Gets the selected shipping option for the current checkout.\n     *\n     * @returns The shipping option object if there is a selected option,\n     * otherwise undefined.\n     */\n    getSelectedShippingOption(): ShippingOption | undefined;\n\n    /**\n     * Gets a list of countries available for shipping.\n     *\n     * @returns The list of countries if it is loaded, otherwise undefined.\n     */\n    getShippingCountries(): Country[] | undefined;\n\n    /**\n     * Gets the billing address of an order.\n     *\n     * @returns The billing address object if it is loaded, otherwise undefined.\n     */\n    getBillingAddress(): BillingAddress | undefined;\n\n    /**\n     * Gets a list of countries available for billing.\n     *\n     * @returns The list of countries if it is loaded, otherwise undefined.\n     */\n    getBillingCountries(): Country[] | undefined;\n\n    /**\n     * Gets a list of payment methods available for checkout.\n     *\n     * @returns The list of payment methods if it is loaded, otherwise undefined.\n     */\n    getPaymentMethods(): PaymentMethod[] | undefined;\n\n    /**\n     * Gets a payment method by an id.\n     *\n     * The method returns undefined if unable to find a payment method with the\n     * specified id, either because it is not available for the customer, or it\n     * is not loaded.\n     *\n     * @param methodId - The identifier of the payment method.\n     * @param gatewayId - The identifier of a payment provider providing the\n     * payment method.\n     * @returns The payment method object if loaded and available, otherwise,\n     * undefined.\n     */\n    getPaymentMethod(methodId: string, gatewayId?: string): PaymentMethod | undefined;\n\n    /**\n     * Gets the payment method that is selected for checkout.\n     *\n     * @returns The payment method object if there is a selected method;\n     * undefined if otherwise.\n     */\n    getSelectedPaymentMethod(): PaymentMethod | undefined;\n\n    /**\n     * Gets the available flash messages.\n     *\n     * Flash messages contain messages set by the server,\n     * e.g: when trying to sign in using an invalid email link.\n     *\n     * @param type - The type of flash messages to be returned. Optional\n     * @returns The flash messages if available, otherwise undefined.\n     */\n    getFlashMessages(type?: FlashMessageType): FlashMessage[] | undefined;\n\n    /**\n     * Gets the current cart.\n     *\n     * @returns The current cart object if it is loaded, otherwise undefined.\n     */\n    getCart(): Cart | undefined;\n\n    /**\n     * Gets a list of coupons that are applied to the current checkout.\n     *\n     * @returns The list of applied coupons if there is any, otherwise undefined.\n     */\n    getCoupons(): Coupon[] | undefined;\n\n    /**\n     * Gets a list of gift certificates that are applied to the current checkout.\n     *\n     * @returns The list of applied gift certificates if there is any, otherwise undefined.\n     */\n    getGiftCertificates(): GiftCertificate[] | undefined;\n\n    /**\n     * Gets the current customer.\n     *\n     * @returns The current customer object if it is loaded, otherwise\n     * undefined.\n     */\n    getCustomer(): Customer | undefined;\n\n    /**\n     * Checks if payment data is required or not.\n     *\n     * If payment data is required, customers should be prompted to enter their\n     * payment details.\n     *\n     * ```js\n     * if (state.checkout.isPaymentDataRequired()) {\n     *     // Render payment form\n     * } else {\n     *     // Render \"Payment is not required for this order\" message\n     * }\n     * ```\n     *\n     * @param useStoreCredit - If true, check whether payment data is required\n     * with store credit applied; otherwise, check without store credit.\n     * @returns True if payment data is required, otherwise false.\n     */\n    isPaymentDataRequired(useStoreCredit?: boolean): boolean;\n\n    /**\n     * Checks if payment data is submitted or not.\n     *\n     * If payment data is already submitted using a payment method, customers\n     * should not be prompted to enter their payment details again.\n     *\n     * @param methodId - The identifier of the payment method.\n     * @param gatewayId - The identifier of a payment provider providing the\n     * payment method.\n     * @returns True if payment data is submitted, otherwise false.\n     */\n    isPaymentDataSubmitted(methodId: string, gatewayId?: string): boolean;\n\n    /**\n     * Gets a list of payment instruments associated with the current customer.\n     *\n     * @returns The list of payment instruments if it is loaded, otherwise undefined.\n     */\n    getInstruments(): Instrument[] | undefined;\n    getInstruments(paymentMethod: PaymentMethod): PaymentInstrument[] | undefined;\n\n    /**\n     * Gets a set of form fields that should be presented in order to create a customer.\n     *\n     * @returns The set of customer account form fields if it is loaded,\n     * otherwise undefined.\n     */\n    getCustomerAccountFields(): FormField[];\n\n    /**\n     * Gets a set of form fields that should be presented to customers in order\n     * to capture their billing address for a specific country.\n     *\n     * @param countryCode - A 2-letter country code (ISO 3166-1 alpha-2).\n     * @returns The set of billing address form fields if it is loaded,\n     * otherwise undefined.\n     */\n    getBillingAddressFields(countryCode: string): FormField[];\n\n    /**\n     * Gets a set of form fields that should be presented to customers in order\n     * to capture their shipping address for a specific country.\n     *\n     * @param countryCode - A 2-letter country code (ISO 3166-1 alpha-2).\n     * @returns The set of shipping address form fields if it is loaded,\n     * otherwise undefined.\n     */\n    getShippingAddressFields(countryCode: string): FormField[];\n}\n\nexport type CheckoutStoreSelectorFactory = (state: InternalCheckoutSelectors) => CheckoutStoreSelector;\n\nexport function createCheckoutStoreSelectorFactory(): CheckoutStoreSelectorFactory {\n    const getCheckout = createSelector(\n        ({ checkout }: InternalCheckoutSelectors) => checkout.getCheckout,\n        getCheckout => clone(getCheckout)\n    );\n\n    const getOrder = createSelector(\n        ({ order }: InternalCheckoutSelectors) => order.getOrder,\n        getOrder => clone(getOrder)\n    );\n\n    const getConfig = createSelector(\n        ({ config }: InternalCheckoutSelectors) => config.getStoreConfig,\n        getStoreConfig => clone(getStoreConfig)\n    );\n\n    const getShippingAddress = createSelector(\n        ({ shippingAddress }: InternalCheckoutSelectors) => shippingAddress.getShippingAddress,\n        ({ config }: InternalCheckoutSelectors) => config.getContextConfig,\n        (getShippingAddress, getContextConfig) => clone(() => {\n            const shippingAddress = getShippingAddress();\n            const context = getContextConfig();\n\n            if (!shippingAddress) {\n                if (!context || !context.geoCountryCode) {\n                    return;\n                }\n\n                return {\n                    firstName: '',\n                    lastName: '',\n                    company: '',\n                    address1: '',\n                    address2: '',\n                    city: '',\n                    stateOrProvince: '',\n                    stateOrProvinceCode: '',\n                    postalCode: '',\n                    country: '',\n                    phone: '',\n                    customFields: [],\n                    countryCode: context.geoCountryCode,\n                };\n            }\n\n            return shippingAddress;\n        })\n    );\n\n    const getShippingOptions = createSelector(\n        ({ consignments }: InternalCheckoutSelectors) => consignments.getConsignments,\n        getConsignments => clone(() => {\n            const consignments = getConsignments();\n\n            if (consignments && consignments.length) {\n                return consignments[0].availableShippingOptions;\n            }\n        })\n    );\n\n    const getConsignments = createSelector(\n        ({ consignments }: InternalCheckoutSelectors) => consignments.getConsignments,\n        getConsignments => clone(getConsignments)\n    );\n\n    const getSelectedShippingOption = createSelector(\n        ({ consignments }: InternalCheckoutSelectors) => consignments.getConsignments,\n        getConsignments => clone(() => {\n            const consignments = getConsignments();\n\n            if (!consignments || !consignments.length) {\n                return;\n            }\n\n            return consignments[0].selectedShippingOption;\n        })\n    );\n\n    const getShippingCountries = createSelector(\n        ({ shippingCountries }: InternalCheckoutSelectors) => shippingCountries.getShippingCountries,\n        getShippingCountries => clone(getShippingCountries)\n    );\n\n    const getBillingAddress = createSelector(\n        ({ billingAddress }: InternalCheckoutSelectors) => billingAddress.getBillingAddress,\n        ({ config }: InternalCheckoutSelectors) => config.getContextConfig,\n        (getBillingAddress, getContextConfig) => clone(() => {\n            const billingAddress = getBillingAddress();\n            const context = getContextConfig();\n            const isEmptyBillingAddress = !billingAddress ||\n                values(omit(billingAddress, 'shouldSaveAddress', 'email', 'id'))\n                    .every(val => !val || !val.length);\n\n            if (isEmptyBillingAddress) {\n                if (!context || !context.geoCountryCode) {\n                    return billingAddress;\n                }\n\n                return {\n                    id: billingAddress ? billingAddress.id : '',\n                    firstName: '',\n                    lastName: '',\n                    company: '',\n                    address1: '',\n                    address2: '',\n                    city: '',\n                    email: billingAddress ? billingAddress.email : '',\n                    stateOrProvince: '',\n                    stateOrProvinceCode: '',\n                    postalCode: '',\n                    country: '',\n                    phone: '',\n                    customFields: [],\n                    countryCode: context.geoCountryCode,\n                };\n            }\n\n            return billingAddress;\n        })\n    );\n\n    const getBillingCountries = createSelector(\n        ({ countries }: InternalCheckoutSelectors) => countries.getCountries,\n        getCountries => clone(getCountries)\n    );\n\n    const getPaymentMethods = createSelector(\n        ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethods,\n        getPaymentMethods => clone(getPaymentMethods)\n    );\n\n    const getPaymentMethod = createSelector(\n        ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethod,\n        getPaymentMethod => clone(getPaymentMethod)\n    );\n\n    const getSelectedPaymentMethod = createSelector(\n        ({ payment }: InternalCheckoutSelectors) => payment.getPaymentId,\n        ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethod,\n        (getPaymentId, getPaymentMethod) => clone(() => {\n            const payment = getPaymentId();\n\n            return payment && getPaymentMethod(payment.providerId, payment.gatewayId);\n        })\n    );\n\n    const getCart = createSelector(\n        ({ cart }: InternalCheckoutSelectors) => cart.getCart,\n        getCart => clone(getCart)\n    );\n\n    const getCoupons = createSelector(\n        ({ coupons }: InternalCheckoutSelectors) => coupons.getCoupons,\n        getCoupons => clone(getCoupons)\n    );\n\n    const getGiftCertificates = createSelector(\n        ({ giftCertificates }: InternalCheckoutSelectors) => giftCertificates.getGiftCertificates,\n        getGiftCertificates => clone(getGiftCertificates)\n    );\n\n    const getCustomer = createSelector(\n        ({ customer }: InternalCheckoutSelectors) => customer.getCustomer,\n        getCustomer => clone(getCustomer)\n    );\n\n    const getSignInEmail = createSelector(\n        ({ signInEmail }: InternalCheckoutSelectors) => signInEmail.getEmail,\n        getEmail => clone(getEmail)\n    );\n\n    const isPaymentDataRequired = createSelector(\n        ({ payment }: InternalCheckoutSelectors) => payment.isPaymentDataRequired,\n        isPaymentDataRequired => clone(isPaymentDataRequired)\n    );\n\n    const isPaymentDataSubmitted = createSelector(\n        ({ payment }: InternalCheckoutSelectors) => payment.isPaymentDataSubmitted,\n        ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethod,\n        (isPaymentDataSubmitted, getPaymentMethod) => clone((methodId: string, gatewayId?: string) => {\n            return isPaymentDataSubmitted(getPaymentMethod(methodId, gatewayId));\n        })\n    );\n\n    const getInstruments = createSelector(\n        ({ instruments }: InternalCheckoutSelectors) => instruments.getInstruments,\n        ({ instruments }: InternalCheckoutSelectors) => instruments.getInstrumentsByPaymentMethod,\n        (getInstruments, getInstrumentsByPaymentMethod) => {\n            function getInstrumentsSelector(): Instrument[] | undefined;\n            function getInstrumentsSelector(paymentMethod: PaymentMethod): PaymentInstrument[] | undefined;\n            function getInstrumentsSelector(paymentMethod?: PaymentMethod): PaymentInstrument[] | undefined {\n                return paymentMethod ? getInstrumentsByPaymentMethod(paymentMethod) : getInstruments();\n            }\n\n            return clone(getInstrumentsSelector);\n        }\n    );\n\n    const getCustomerAccountFields = createSelector(\n        ({ form }: InternalCheckoutSelectors) => form.getCustomerAccountFields,\n        getCustomerAccountFields => clone(getCustomerAccountFields)\n    );\n\n    const getBillingAddressFields = createSelector(\n        ({ form }: InternalCheckoutSelectors) => form.getBillingAddressFields,\n        ({ countries }: InternalCheckoutSelectors) => countries.getCountries,\n        (getBillingAddressFields, getCountries) => clone((countryCode: string) => {\n            return getBillingAddressFields(getCountries(), countryCode);\n        })\n    );\n\n    const getShippingAddressFields = createSelector(\n        ({ form }: InternalCheckoutSelectors) => form.getShippingAddressFields,\n        ({ shippingCountries }: InternalCheckoutSelectors) => shippingCountries.getShippingCountries,\n        (getShippingAddressFields, getShippingCountries) => clone((countryCode: string) => {\n            return getShippingAddressFields(getShippingCountries(), countryCode);\n        })\n    );\n\n    const getFlashMessages = createSelector(\n        ({ config }: InternalCheckoutSelectors) => config.getFlashMessages,\n        getFlashMessages => clone(getFlashMessages)\n    );\n\n    return memoizeOne((\n        state: InternalCheckoutSelectors\n    ): CheckoutStoreSelector => {\n        return {\n            getCheckout: getCheckout(state),\n            getOrder: getOrder(state),\n            getConfig: getConfig(state),\n            getFlashMessages: getFlashMessages(state),\n            getShippingAddress: getShippingAddress(state),\n            getShippingOptions: getShippingOptions(state),\n            getConsignments: getConsignments(state),\n            getSelectedShippingOption: getSelectedShippingOption(state),\n            getShippingCountries: getShippingCountries(state),\n            getBillingAddress: getBillingAddress(state),\n            getBillingCountries: getBillingCountries(state),\n            getPaymentMethods: getPaymentMethods(state),\n            getPaymentMethod: getPaymentMethod(state),\n            getSelectedPaymentMethod: getSelectedPaymentMethod(state),\n            getCart: getCart(state),\n            getCoupons: getCoupons(state),\n            getGiftCertificates: getGiftCertificates(state),\n            getCustomer: getCustomer(state),\n            isPaymentDataRequired: isPaymentDataRequired(state),\n            isPaymentDataSubmitted: isPaymentDataSubmitted(state),\n            getSignInEmail: getSignInEmail(state),\n            getInstruments: getInstruments(state),\n            getCustomerAccountFields: getCustomerAccountFields(state),\n            getBillingAddressFields: getBillingAddressFields(state),\n            getShippingAddressFields: getShippingAddressFields(state),\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { CartChangedError } from '../cart/errors';\nimport { RequestError } from '../common/error/errors';\nimport { createSelector, createShallowEqualSelector } from '../common/selector';\nimport { Omit } from '../common/types';\n\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\n/**\n * Responsible for getting the error of any asynchronous checkout action, if\n * there is any.\n *\n * This object has a set of getters that would return an error if an action is\n * not executed successfully. For example, if you are unable to submit an order,\n * you can use this object to retrieve the reason for the failure.\n */\nexport default interface CheckoutStoreErrorSelector {\n    getError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to load the current checkout.\n     *\n     * @returns The error object if unable to load, otherwise undefined.\n     */\n    getLoadCheckoutError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to update the current checkout.\n     *\n     * @returns The error object if unable to update, otherwise undefined.\n     */\n    getUpdateCheckoutError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to submit the current order.\n     *\n     * @returns The error object if unable to submit, otherwise undefined.\n     */\n    getSubmitOrderError(): Error | CartChangedError | undefined;\n\n    /**\n     * Returns an error if unable to finalize the current order.\n     *\n     * @returns The error object if unable to finalize, otherwise undefined.\n     */\n    getFinalizeOrderError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to load the current order.\n     *\n     * @returns The error object if unable to load, otherwise undefined.\n     */\n    getLoadOrderError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to load the current cart.\n     *\n     * @returns The error object if unable to load, otherwise undefined.\n     */\n    getLoadCartError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to load billing countries.\n     *\n     * @returns The error object if unable to load, otherwise undefined.\n     */\n    getLoadBillingCountriesError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to load shipping countries.\n     *\n     * @returns The error object if unable to load, otherwise undefined.\n     */\n    getLoadShippingCountriesError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to load payment methods.\n     *\n     * @returns The error object if unable to load, otherwise undefined.\n     */\n    getLoadPaymentMethodsError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to load a specific payment method.\n     *\n     * @param methodId - The identifier of the payment method to load.\n     * @returns The error object if unable to load, otherwise undefined.\n     */\n    getLoadPaymentMethodError(methodId?: string): Error | undefined;\n\n    /**\n     * Returns an error if unable to initialize a specific payment method.\n     *\n     * @param methodId - The identifier of the payment method to initialize.\n     * @returns The error object if unable to initialize, otherwise undefined.\n     */\n    getInitializePaymentError(methodId?: string): Error | undefined;\n\n    /**\n     * Returns an error if unable to sign in.\n     *\n     * @returns The error object if unable to sign in, otherwise undefined.\n     */\n    getSignInError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to sign out.\n     *\n     * @returns The error object if unable to sign out, otherwise undefined.\n     */\n    getSignOutError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to initialize the customer step of a checkout\n     * process.\n     *\n     * @param methodId - The identifer of the initialization method to execute.\n     * @returns The error object if unable to initialize, otherwise undefined.\n     */\n    getInitializeCustomerError(methodId?: string): Error | undefined;\n\n    /**\n     * Returns an error if unable to load shipping options.\n     *\n     * @returns The error object if unable to load, otherwise undefined.\n     */\n    getLoadShippingOptionsError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to select a shipping option.\n     *\n     * A consignment ID should be provided when checking for an error for a\n     * specific consignment, otherwise it will check for all available consignments.\n     *\n     * @param consignmentId - The identifier of the consignment to be checked.\n     * @returns The error object if unable to select, otherwise undefined.\n     */\n    getSelectShippingOptionError(consignmentId?: string): Error | undefined;\n\n    /**\n     * Returns an error if unable to continue as guest.\n     *\n     * The call could fail in scenarios where guest checkout is not allowed, for example, when existing accounts are required to sign-in.\n     *\n     * In the background, this call tries to set the billing address email using the Storefront API. You could access the Storefront API response status code using `getContinueAsGuestError` error selector.\n     *\n     * ```js\n     * console.log(state.errors.getContinueAsGuestError());\n     * console.log(state.errors.getContinueAsGuestError().status);\n     * ```\n     *\n     * For more information about status codes, check [Checkout Storefront API - Add Checkout Billing Address](https://developer.bigcommerce.com/api-reference/cart-checkout/storefront-checkout-api/checkout-billing-address/checkoutsbillingaddressbycheckoutidpost).\n     *\n     * @returns The error object if unable to continue, otherwise undefined.\n     */\n    getContinueAsGuestError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to update billing address.\n     *\n     * @returns The error object if unable to update, otherwise undefined.\n     */\n    getUpdateBillingAddressError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to update subscriptions.\n     *\n     * @returns The error object if unable to update, otherwise undefined.\n     */\n    getUpdateSubscriptionsError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to update shipping address.\n     *\n     * @returns The error object if unable to update, otherwise undefined.\n     */\n    getUpdateShippingAddressError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to delete a consignment.\n     *\n     * A consignment ID should be provided when checking for an error for a\n     * specific consignment, otherwise it will check for all available consignments.\n     *\n     * @param consignmentId - The identifier of the consignment to be checked.\n     * @returns The error object if unable to delete, otherwise undefined.\n     */\n    getDeleteConsignmentError(consignmentId?: string): Error | undefined;\n\n    /**\n     * Returns an error if unable to update a consignment.\n     *\n     * A consignment ID should be provided when checking for an error for a\n     * specific consignment, otherwise it will check for all available consignments.\n     *\n     * @param consignmentId - The identifier of the consignment to be checked.\n     * @returns The error object if unable to update, otherwise undefined.\n     */\n    getUpdateConsignmentError(consignmentId?: string): Error | undefined;\n\n    /**\n     * Returns an error if unable to create consignments.\n     *\n     * @returns The error object if unable to create, otherwise undefined.\n     */\n    getCreateConsignmentsError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to initialize the shipping step of a checkout\n     * process.\n     *\n     * @param methodId - The identifer of the initialization method to execute.\n     * @returns The error object if unable to initialize, otherwise undefined.\n     */\n    getInitializeShippingError(methodId?: string): Error | undefined;\n\n    /**\n     * Returns an error if unable to apply store credit.\n     *\n     * @returns The error object if unable to apply, otherwise undefined.\n     */\n    getApplyStoreCreditError(): RequestError | undefined;\n\n    /**\n     * Returns an error if unable to apply a coupon code.\n     *\n     * @returns The error object if unable to apply, otherwise undefined.\n     */\n    getApplyCouponError(): RequestError | undefined;\n\n    /**\n     * Returns an error if unable to remove a coupon code.\n     *\n     * @returns The error object if unable to remove, otherwise undefined.\n     */\n    getRemoveCouponError(): RequestError | undefined;\n\n    /**\n     * Returns an error if unable to apply a gift certificate.\n     *\n     * @returns The error object if unable to apply, otherwise undefined.\n     */\n    getApplyGiftCertificateError(): RequestError | undefined;\n\n    /**\n     * Returns an error if unable to remove a gift certificate.\n     *\n     * @returns The error object if unable to remove, otherwise undefined.\n     */\n    getRemoveGiftCertificateError(): RequestError | undefined;\n\n    /**\n     * Returns an error if unable to load payment instruments.\n     *\n     * @returns The error object if unable to load, otherwise undefined.\n     */\n    getLoadInstrumentsError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to delete a payment instrument.\n     *\n     * @param instrumentId - The identifier of the payment instrument to delete.\n     * @returns The error object if unable to delete, otherwise undefined.\n     */\n    getDeleteInstrumentError(instrumentId?: string): Error | undefined;\n\n    /**\n     * Returns an error if unable to load the checkout configuration of a store.\n     *\n     * @returns The error object if unable to load, otherwise undefined.\n     */\n    getLoadConfigError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to send sign-in email.\n     *\n     * @returns The error object if unable to send email, otherwise undefined.\n     */\n    getSignInEmailError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to create customer account.\n     *\n     * @returns The error object if unable to create account, otherwise undefined.\n     */\n    getCreateCustomerAccountError(): Error | undefined;\n\n    /**\n     * Returns an error if unable to create customer address.\n     *\n     * @returns The error object if unable to create address, otherwise undefined.\n     */\n    getCreateCustomerAddressError(): Error | undefined;\n}\n\nexport type CheckoutStoreErrorSelectorFactory = (state: InternalCheckoutSelectors) => CheckoutStoreErrorSelector;\n\nexport function createCheckoutStoreErrorSelectorFactory(): CheckoutStoreErrorSelectorFactory {\n    const getError = createShallowEqualSelector(\n        (selector: Omit<CheckoutStoreErrorSelector, 'getError'>) => selector,\n        selector => () => {\n            for (const key of Object.keys(selector) as Array<keyof Omit<CheckoutStoreErrorSelector, 'getError'>>) {\n                const error = selector[key]();\n\n                if (error) {\n                    return error;\n                }\n            }\n        }\n    );\n\n    const getSelectShippingOptionError = createSelector(\n        ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.getSelectOptionError,\n        ({ consignments }: InternalCheckoutSelectors) => consignments.getUpdateShippingOptionError,\n        (getSelectOptionError, getUpdateShippingOptionError) => (consignmentId?: string) => {\n            return (\n                getSelectOptionError() ||\n                getUpdateShippingOptionError(consignmentId)\n            );\n        }\n    );\n\n    return memoizeOne((\n        state: InternalCheckoutSelectors\n    ): CheckoutStoreErrorSelector => {\n        const selector = {\n            getLoadCheckoutError: state.checkout.getLoadError,\n            getUpdateCheckoutError: state.checkout.getUpdateError,\n            getSubmitOrderError: state.paymentStrategies.getExecuteError,\n            getFinalizeOrderError: state.paymentStrategies.getFinalizeError,\n            getLoadOrderError: state.order.getLoadError,\n            getLoadCartError: state.cart.getLoadError,\n            getLoadBillingCountriesError: state.countries.getLoadError,\n            getLoadShippingCountriesError: state.shippingCountries.getLoadError,\n            getLoadPaymentMethodsError: state.paymentMethods.getLoadError,\n            getLoadPaymentMethodError: state.paymentMethods.getLoadMethodError,\n            getInitializePaymentError: state.paymentStrategies.getInitializeError,\n            getSignInError: state.customerStrategies.getSignInError,\n            getSignOutError: state.customerStrategies.getSignOutError,\n            getInitializeCustomerError: state.customerStrategies.getInitializeError,\n            getLoadShippingOptionsError: state.consignments.getLoadShippingOptionsError,\n            getSelectShippingOptionError: getSelectShippingOptionError(state),\n            getContinueAsGuestError: state.billingAddress.getContinueAsGuestError,\n            getUpdateBillingAddressError: state.billingAddress.getUpdateError,\n            getUpdateSubscriptionsError: state.subscriptions.getUpdateError,\n            getUpdateShippingAddressError: state.shippingStrategies.getUpdateAddressError,\n            getDeleteConsignmentError: state.consignments.getDeleteError,\n            getUpdateConsignmentError: state.consignments.getUpdateError,\n            getCreateConsignmentsError: state.consignments.getCreateError,\n            getInitializeShippingError: state.shippingStrategies.getInitializeError,\n            getApplyStoreCreditError: state.storeCredit.getApplyError,\n            getApplyCouponError: state.coupons.getApplyError,\n            getRemoveCouponError: state.coupons.getRemoveError,\n            getApplyGiftCertificateError: state.giftCertificates.getApplyError,\n            getRemoveGiftCertificateError: state.giftCertificates.getRemoveError,\n            getLoadInstrumentsError: state.instruments.getLoadError,\n            getDeleteInstrumentError: state.instruments.getDeleteError,\n            getLoadConfigError: state.config.getLoadError,\n            getSignInEmailError: state.signInEmail.getSendError,\n            getCreateCustomerAccountError: state.customer.getCreateAccountError,\n            getCreateCustomerAddressError: state.customer.getCreateAddressError,\n        };\n\n        return {\n            getError: getError(selector),\n            ...selector,\n        };\n    });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector, createShallowEqualSelector } from '../common/selector';\nimport { Omit } from '../common/types';\n\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\n/**\n * Responsible for checking the statuses of various asynchronous actions related\n * to checkout.\n *\n * This object has a set of getters that return true if an action is in\n * progress. For example, you can check whether a customer is submitting an\n * order and waiting for the request to complete.\n */\nexport default interface CheckoutStoreStatusSelector {\n    /**\n     * Checks whether any checkout action is pending.\n     *\n     * @returns True if there is a pending action, otherwise false.\n     */\n    isPending(): boolean;\n\n    /**\n     * Checks whether the current checkout is loading.\n     *\n     * @returns True if the current checkout is loading, otherwise false.\n     */\n    isLoadingCheckout(): boolean;\n\n    /**\n     * Checks whether the current checkout is being updated.\n     *\n     * @returns True if the current checkout is being updated, otherwise false.\n     */\n    isUpdatingCheckout(): boolean;\n\n    /**\n     * Checks whether spam check is executing.\n     *\n     * @returns True if the current checkout is being updated, otherwise false.\n     */\n    isExecutingSpamCheck(): boolean;\n\n    /**\n     * Checks whether the current order is submitting.\n     *\n     * @returns True if the current order is submitting, otherwise false.\n     */\n    isSubmittingOrder(): boolean;\n\n    /**\n     * Checks whether the current order is finalizing.\n     *\n     * @returns True if the current order is finalizing, otherwise false.\n     */\n    isFinalizingOrder(): boolean;\n\n    /**\n     * Checks whether the current order is loading.\n     *\n     * @returns True if the current order is loading, otherwise false.\n     */\n    isLoadingOrder(): boolean;\n\n    /**\n     * Checks whether the current cart is loading.\n     *\n     * @returns True if the current cart is loading, otherwise false.\n     */\n    isLoadingCart(): boolean;\n\n    /**\n     * Checks whether billing countries are loading.\n     *\n     * @returns True if billing countries are loading, otherwise false.\n     */\n    isLoadingBillingCountries(): boolean;\n\n    /**\n     * Checks whether shipping countries are loading.\n     *\n     * @returns True if shipping countries are loading, otherwise false.\n     */\n    isLoadingShippingCountries(): boolean;\n\n    /**\n     * Checks whether payment methods are loading.\n     *\n     * @returns True if payment methods are loading, otherwise false.\n     */\n    isLoadingPaymentMethods(): boolean;\n\n    /**\n     * Checks whether a specific or any payment method is loading.\n     *\n     * The method returns true if no ID is provided and at least one payment\n     * method is loading.\n     *\n     * @param methodId - The identifier of the payment method to check.\n     * @returns True if the payment method is loading, otherwise false.\n     */\n    isLoadingPaymentMethod(methodId?: string): boolean;\n\n    /**\n     * Checks whether a specific or any payment method is initializing.\n     *\n     * The method returns true if no ID is provided and at least one payment\n     * method is initializing.\n     *\n     * @param methodId - The identifier of the payment method to check.\n     * @returns True if the payment method is initializing, otherwise false.\n     */\n    isInitializingPayment(methodId?: string): boolean;\n\n    /**\n     * Checks whether the current customer is signing in.\n     *\n     * If an ID is provided, the method also checks whether the customer is\n     * signing in using a specific customer method with the same ID.\n     *\n     * @param methodId - The identifier of the method used for signing in the\n     * current customer.\n     * @returns True if the customer is signing in, otherwise false.\n     */\n    isSigningIn(methodId?: string): boolean;\n\n    /**\n     * Checks whether the current customer is signing out.\n     *\n     * If an ID is provided, the method also checks whether the customer is\n     * signing out using a specific customer method with the same ID.\n     *\n     * @param methodId - The identifier of the method used for signing out the\n     * current customer.\n     * @returns True if the customer is signing out, otherwise false.\n     */\n    isSigningOut(methodId?: string): boolean;\n\n    /**\n     * Checks whether the customer step is initializing.\n     *\n     * If an ID is provided, the method also checks whether the customer step is\n     * initializing using a specific customer method with the same ID.\n     *\n     * @param methodId - The identifier of the method used for initializing the\n     * customer step of checkout.\n     * @returns True if the customer step is initializing, otherwise false.\n     */\n    isInitializingCustomer(methodId?: string): boolean;\n\n    /**\n     * Checks whether shipping options are loading.\n     *\n     * @returns True if shipping options are loading, otherwise false.\n     */\n    isLoadingShippingOptions(): boolean;\n\n    /**\n     * Checks whether a shipping option is being selected.\n     *\n     * A consignment ID should be provided when checking if a shipping option\n     * is being selected for a specific consignment, otherwise it will check\n     * for all consignments.\n     *\n     * @param consignmentId - The identifier of the consignment to be checked.\n     * @returns True if selecting a shipping option, otherwise false.\n     */\n    isSelectingShippingOption(consignmentId?: string): boolean;\n\n    /**\n     * Checks whether the billing address is being updated.\n     *\n     * @returns True if updating their billing address, otherwise false.\n     */\n    isUpdatingBillingAddress(): boolean;\n\n    /**\n     * Checks whether the shopper is continuing out as a guest.\n     *\n     * @returns True if continuing as guest, otherwise false.\n     */\n    isContinuingAsGuest(): boolean;\n\n    /**\n     * Checks the shipping address is being updated.\n     *\n     * @returns True if updating their shipping address, otherwise false.\n     */\n    isUpdatingShippingAddress(): boolean;\n\n    /**\n     * Checks whether a given/any consignment is being updated.\n     *\n     * A consignment ID should be provided when checking for a specific consignment,\n     * otherwise it will check for any consignment.\n     *\n     * @param consignmentId - The identifier of the consignment to be checked.\n     * @returns True if updating consignment(s), otherwise false.\n     */\n    isUpdatingConsignment(consignmentId?: string): boolean;\n\n    /**\n     * Checks whether a given/any consignment is being deleted.\n     *\n     * A consignment ID should be provided when checking for a specific consignment,\n     * otherwise it will check for any consignment.\n     *\n     * @param consignmentId - The identifier of the consignment to be checked.\n     * @returns True if deleting consignment(s), otherwise false.\n     */\n    isDeletingConsignment(consignmentId?: string): boolean;\n\n    /**\n     * Checks whether a given/any consignment is being updated.\n     *\n     * A consignment ID should be provided when checking for a specific consignment,\n     * otherwise it will check for any consignment.\n     *\n     * @returns True if creating consignments, otherwise false.\n     */\n    isCreatingConsignments(): boolean;\n\n    /**\n     * Checks whether the shipping step of a checkout process is initializing.\n     *\n     * If an identifier is provided, the method also checks whether the shipping\n     * step is initializing using a specific shipping method with the same\n     * identifier.\n     *\n     * @param methodId - The identifer of the initialization method to check.\n     * @returns True if the shipping step is initializing, otherwise false.\n     */\n    isInitializingShipping(methodId?: string): boolean;\n\n    /**\n     * Checks whether the current customer is applying a coupon code.\n     *\n     * @returns True if applying a coupon code, otherwise false.\n     */\n    isApplyingCoupon(): boolean;\n\n    /**\n     * Checks whether the current customer is applying store credit.\n     *\n     * @returns True if applying store credit, otherwise false.\n     */\n    isApplyingStoreCredit(): boolean;\n\n    /**\n     * Checks whether the current customer is removing a coupon code.\n     *\n     * @returns True if removing a coupon code, otherwise false.\n     */\n    isRemovingCoupon(): boolean;\n\n    /**\n     * Checks whether a sign-in email is being sent.\n     *\n     * @returns True if sending a sign-in email, otherwise false\n     */\n    isSendingSignInEmail(): boolean;\n\n    /**\n     * Checks whether the current customer is applying a gift certificate.\n     *\n     * @returns True if applying a gift certificate, otherwise false.\n     */\n    isApplyingGiftCertificate(): boolean;\n\n    /**\n     * Checks whether the current customer is removing a gift certificate.\n     *\n     * @returns True if removing a gift certificate, otherwise false.\n     */\n    isRemovingGiftCertificate(): boolean;\n\n    /**\n     * Checks whether the current customer's payment instruments are loading.\n     *\n     * @returns True if payment instruments are loading, otherwise false.\n     */\n    isLoadingInstruments(): boolean;\n\n    /**\n     * Checks whether the current customer is deleting a payment instrument.\n     *\n     * @returns True if deleting a payment instrument, otherwise false.\n     */\n    isDeletingInstrument(instrumentId?: string): boolean;\n\n    /**\n     * Checks whether the checkout configuration of a store is loading.\n     *\n     * @returns True if the configuration is loading, otherwise false.\n     */\n    isLoadingConfig(): boolean;\n\n    /**\n     * Checks whether the customer step of a checkout is in a pending state.\n     *\n     * The customer step is considered to be pending if it is in the process of\n     * initializing, signing in, signing out, and/or interacting with a customer\n     * widget.\n     *\n     * @returns True if the customer step is pending, otherwise false.\n     */\n    isCustomerStepPending(): boolean;\n\n    /**\n     * Checks whether the shipping step of a checkout is in a pending state.\n     *\n     * The shipping step is considered to be pending if it is in the process of\n     * initializing, updating address, selecting a shipping option, and/or\n     * interacting with a shipping widget.\n     *\n     * @returns True if the shipping step is pending, otherwise false.\n     */\n    isShippingStepPending(): boolean;\n\n    /**\n     * Checks whether the payment step of a checkout is in a pending state.\n     *\n     * The payment step is considered to be pending if it is in the process of\n     * initializing, submitting an order, finalizing an order, and/or\n     * interacting with a payment widget.\n     *\n     * @returns True if the payment step is pending, otherwise false.\n     */\n    isPaymentStepPending(): boolean;\n\n    /**\n     * Checks whether the subscriptions are being updated.\n     *\n     * @returns True if updating subscriptions, otherwise false.\n     */\n    isUpdatingSubscriptions(): boolean;\n\n    /**\n     * Checks whether a customer account is being created\n     *\n     * @returns True if creating, otherwise false.\n     */\n    isCreatingCustomerAccount(): boolean;\n\n    /**\n     * Checks whether a customer address is being created\n     *\n     * @returns True if creating, otherwise false.\n     */\n    isCreatingCustomerAddress(): boolean;\n}\n\nexport type CheckoutStoreStatusSelectorFactory = (state: InternalCheckoutSelectors) => CheckoutStoreStatusSelector;\n\nexport function createCheckoutStoreStatusSelectorFactory(): CheckoutStoreStatusSelectorFactory {\n    const isPending = createShallowEqualSelector(\n        (selector: Omit<CheckoutStoreStatusSelector, 'isPending'>) => selector,\n        selector => () => {\n            return (Object.keys(selector) as Array<keyof Omit<CheckoutStoreStatusSelector, 'isPending'>>)\n                .some(key => selector[key]());\n        }\n    );\n\n    const isSelectingShippingOption = createSelector(\n        ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isSelectingOption,\n        ({ consignments }: InternalCheckoutSelectors) => consignments.isUpdatingShippingOption,\n        (isSelectingOption, isUpdatingShippingOption) => (consignmentId?: string) => {\n            return (\n                isSelectingOption() ||\n                isUpdatingShippingOption(consignmentId)\n            );\n        }\n    );\n\n    const isCustomerStepPending = createSelector(\n        ({ customerStrategies }: InternalCheckoutSelectors) => customerStrategies.isInitializing,\n        ({ customerStrategies }: InternalCheckoutSelectors) => customerStrategies.isSigningIn,\n        ({ customerStrategies }: InternalCheckoutSelectors) => customerStrategies.isSigningOut,\n        ({ customerStrategies }: InternalCheckoutSelectors) => customerStrategies.isWidgetInteracting,\n        (isInitializing, isSigningIn, isSigningOut, isWidgetInteracting) => (methodId?: string) => {\n            return (\n                isInitializing(methodId) ||\n                isSigningIn(methodId) ||\n                isSigningOut(methodId) ||\n                isWidgetInteracting(methodId)\n            );\n        }\n    );\n\n    const isShippingStepPending = createSelector(\n        ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isInitializing,\n        ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isUpdatingAddress,\n        ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isSelectingOption,\n        ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isWidgetInteracting,\n        (isInitializing, isUpdatingAddress, isSelectingOption, isWidgetInteracting) => (methodId?: string) => {\n            return (\n                isInitializing(methodId) ||\n                isUpdatingAddress(methodId) ||\n                isSelectingOption(methodId) ||\n                isWidgetInteracting(methodId)\n            );\n        }\n    );\n\n    const isPaymentStepPending = createSelector(\n        ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isInitializing,\n        ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isExecuting,\n        ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isFinalizing,\n        ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isWidgetInteracting,\n        (isInitializing, isExecuting, isFinalizing, isWidgetInteracting) => (methodId?: string) => {\n            return (\n                isInitializing(methodId) ||\n                isExecuting(methodId) ||\n                isFinalizing(methodId) ||\n                isWidgetInteracting(methodId)\n            );\n        }\n    );\n\n    const isSubmittingOrder = createSelector(\n        ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isExecuting,\n        ({ checkout }: InternalCheckoutSelectors) => checkout.isExecutingSpamCheck, // Remove this when CheckoutService#initializeSpamProtection is deprecated\n        (isExecuting, isExecutingSpamCheck) => (methodId?: string) => {\n            return (\n                isExecuting(methodId) ||\n                isExecutingSpamCheck()\n            );\n        }\n    );\n\n    return memoizeOne((\n        state: InternalCheckoutSelectors\n    ): CheckoutStoreStatusSelector => {\n        const selector = {\n            isLoadingCheckout: state.checkout.isLoading,\n            isUpdatingCheckout: state.checkout.isUpdating,\n            isExecutingSpamCheck: state.checkout.isExecutingSpamCheck,\n            isSubmittingOrder: isSubmittingOrder(state),\n            isFinalizingOrder: state.paymentStrategies.isFinalizing,\n            isLoadingOrder: state.order.isLoading,\n            isLoadingCart: state.cart.isLoading,\n            isLoadingBillingCountries: state.countries.isLoading,\n            isLoadingShippingCountries: state.shippingCountries.isLoading,\n            isLoadingPaymentMethods: state.paymentMethods.isLoading,\n            isLoadingPaymentMethod: state.paymentMethods.isLoadingMethod,\n            isInitializingPayment: state.paymentStrategies.isInitializing,\n            isSigningIn: state.customerStrategies.isSigningIn,\n            isSigningOut: state.customerStrategies.isSigningOut,\n            isInitializingCustomer: state.customerStrategies.isInitializing,\n            isLoadingShippingOptions: state.consignments.isLoadingShippingOptions,\n            isSelectingShippingOption: isSelectingShippingOption(state),\n            isUpdatingBillingAddress: state.billingAddress.isUpdating,\n            isUpdatingSubscriptions: state.subscriptions.isUpdating,\n            isCreatingCustomerAccount: state.customer.isCreatingCustomerAccount,\n            isCreatingCustomerAddress: state.customer.isCreatingCustomerAddress,\n            isContinuingAsGuest: state.billingAddress.isContinuingAsGuest,\n            isUpdatingShippingAddress: state.shippingStrategies.isUpdatingAddress,\n            isUpdatingConsignment: state.consignments.isUpdating,\n            isDeletingConsignment: state.consignments.isDeleting,\n            isCreatingConsignments: state.consignments.isCreating,\n            isInitializingShipping: state.shippingStrategies.isInitializing,\n            isApplyingStoreCredit: state.storeCredit.isApplying,\n            isApplyingCoupon: state.coupons.isApplying,\n            isRemovingCoupon: state.coupons.isRemoving,\n            isApplyingGiftCertificate: state.giftCertificates.isApplying,\n            isRemovingGiftCertificate: state.giftCertificates.isRemoving,\n            isLoadingInstruments: state.instruments.isLoading,\n            isDeletingInstrument: state.instruments.isDeleting,\n            isLoadingConfig: state.config.isLoading,\n            isSendingSignInEmail: state.signInEmail.isSending,\n            isCustomerStepPending: isCustomerStepPending(state),\n            isShippingStepPending: isShippingStepPending(state),\n            isPaymentStepPending: isPaymentStepPending(state),\n        };\n\n        return {\n            isPending: isPending(selector),\n            ...selector,\n        };\n    });\n}\n","import { toSingleLine } from '../utility';\n\nexport default class ErrorMessageTransformer<TError extends Error = Error> {\n    constructor(\n        private _messageCustomizer: (type: TError) => string\n    ) {}\n\n    transform(error: TError): TError {\n        error.message = toSingleLine(this._messageCustomizer(error));\n\n        return error;\n    }\n}\n","export default function toSingleLine(input?: string) {\n    if (!input) {\n        return '';\n    }\n\n    return input.split(/(?:\\r\\n|\\n|\\r)/)\n        .map(line => line.replace(/^\\s+/gm, ''))\n        .join(' ')\n        .trim();\n}\n","import { Action, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable } from 'rxjs';\n\nimport { AddressRequestBody } from '../address';\nimport { BillingAddressActionCreator, BillingAddressRequestBody } from '../billing';\nimport { createDataStoreProjection, DataStoreProjection } from '../common/data-store';\nimport { ErrorActionCreator, ErrorMessageTransformer } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\nimport { bindDecorator as bind } from '../common/utility';\nimport { ConfigActionCreator } from '../config';\nimport { CouponActionCreator, GiftCertificateActionCreator } from '../coupon';\nimport { CustomerAccountRequestBody, CustomerActionCreator, CustomerAddressRequestBody, CustomerCredentials, CustomerInitializeOptions, CustomerRequestOptions, CustomerStrategyActionCreator, GuestCredentials } from '../customer';\nimport { FormFieldsActionCreator } from '../form';\nimport { CountryActionCreator } from '../geography';\nimport { OrderActionCreator, OrderRequestBody } from '../order';\nimport { PaymentInitializeOptions, PaymentMethodActionCreator, PaymentRequestOptions, PaymentStrategyActionCreator } from '../payment';\nimport { InstrumentActionCreator } from '../payment/instrument';\nimport { ConsignmentsRequestBody, ConsignmentActionCreator, ConsignmentAssignmentRequestBody, ConsignmentUpdateRequestBody, ShippingCountryActionCreator, ShippingInitializeOptions, ShippingRequestOptions, ShippingStrategyActionCreator } from '../shipping';\nimport { SignInEmailActionCreator, SignInEmailRequestBody } from '../signin-email';\nimport { SpamProtectionActionCreator, SpamProtectionOptions } from '../spam-protection';\nimport { StoreCreditActionCreator } from '../store-credit';\nimport { Subscriptions, SubscriptionsActionCreator } from '../subscription';\n\nimport { CheckoutRequestBody } from './checkout';\nimport CheckoutActionCreator from './checkout-action-creator';\nimport CheckoutParams from './checkout-params';\nimport CheckoutSelectors from './checkout-selectors';\nimport CheckoutStore from './checkout-store';\nimport { createCheckoutSelectorsFactory, CheckoutSelectorsFactory } from './create-checkout-selectors';\nimport createCheckoutServiceErrorTransformer from './create-checkout-service-error-transformer';\n\n/**\n * Responsible for completing the checkout process for the current customer.\n *\n * This object can be used to collect all information that is required for\n * checkout, such as shipping and billing information. It can also be used to\n * retrieve the current checkout state and subscribe to its changes.\n */\n@bind\nexport default class CheckoutService {\n    private _storeProjection: DataStoreProjection<CheckoutSelectors>;\n    private _errorTransformer: ErrorMessageTransformer;\n    private _selectorsFactory: CheckoutSelectorsFactory;\n\n    /**\n     * @internal\n     */\n    constructor(\n        private _store: CheckoutStore,\n        private _billingAddressActionCreator: BillingAddressActionCreator,\n        private _checkoutActionCreator: CheckoutActionCreator,\n        private _configActionCreator: ConfigActionCreator,\n        private _customerActionCreator: CustomerActionCreator,\n        private _consignmentActionCreator: ConsignmentActionCreator,\n        private _countryActionCreator: CountryActionCreator,\n        private _couponActionCreator: CouponActionCreator,\n        private _customerStrategyActionCreator: CustomerStrategyActionCreator,\n        private _errorActionCreator: ErrorActionCreator,\n        private _giftCertificateActionCreator: GiftCertificateActionCreator,\n        private _instrumentActionCreator: InstrumentActionCreator,\n        private _orderActionCreator: OrderActionCreator,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n        private _shippingCountryActionCreator: ShippingCountryActionCreator,\n        private _shippingStrategyActionCreator: ShippingStrategyActionCreator,\n        private _signInEmailActionCreator: SignInEmailActionCreator,\n        private _spamProtectionActionCreator: SpamProtectionActionCreator,\n        private _storeCreditActionCreator: StoreCreditActionCreator,\n        private _subscriptionsActionCreator: SubscriptionsActionCreator,\n        private _formFieldsActionCreator: FormFieldsActionCreator\n    ) {\n        this._errorTransformer = createCheckoutServiceErrorTransformer();\n        this._selectorsFactory = createCheckoutSelectorsFactory();\n        this._storeProjection = createDataStoreProjection(this._store, this._selectorsFactory);\n    }\n\n    /**\n     * Returns a snapshot of the current checkout state.\n     *\n     * The method returns a new instance every time there is a change in the\n     * checkout state. You can query the state by calling any of its getter\n     * methods.\n     *\n     * ```js\n     * const state = service.getState();\n     *\n     * console.log(state.data.getOrder());\n     * console.log(state.errors.getSubmitOrderError());\n     * console.log(state.statuses.isSubmittingOrder());\n     * ```\n     *\n     * @returns The current customer's checkout state\n     */\n    getState(): CheckoutSelectors {\n        return this._storeProjection.getState();\n    }\n\n    /**\n     * Notifies all subscribers with the current state.\n     *\n     * When this method gets called, the subscribers get called regardless if\n     * they have any filters applied.\n     */\n    notifyState(): void {\n        this._storeProjection.notifyState();\n    }\n\n    /**\n     * Subscribes to any changes to the current state.\n     *\n     * The method registers a callback function and executes it every time there\n     * is a change in the checkout state.\n     *\n     * ```js\n     * service.subscribe(state => {\n     *     console.log(state.data.getCart());\n     * });\n     * ```\n     *\n     * The method can be configured to notify subscribers only regarding\n     * relevant changes, by providing a filter function.\n     *\n     * ```js\n     * const filter = state => state.data.getCart();\n     *\n     * // Only trigger the subscriber when the cart changes.\n     * service.subscribe(state => {\n     *     console.log(state.data.getCart())\n     * }, filter);\n     * ```\n     *\n     * @param subscriber - The function to subscribe to state changes.\n     * @param filters - One or more functions to filter out irrelevant state\n     * changes. If more than one function is provided, the subscriber will only\n     * be triggered if all conditions are met.\n     * @returns A function, if called, will unsubscribe the subscriber.\n     */\n    subscribe(\n        subscriber: (state: CheckoutSelectors) => void,\n        ...filters: Array<(state: CheckoutSelectors) => any>\n    ): () => void {\n        return this._storeProjection.subscribe(subscriber, ...filters);\n    }\n\n    /**\n     * Loads the current checkout.\n     *\n     * This method can only be called if there is an active checkout. Also, it\n     * can only retrieve data that belongs to the current customer. When it is\n     * successfully executed, you can retrieve the data by calling\n     * `CheckoutStoreSelector#getCheckout`.\n     *\n     * ```js\n     * const state = await service.loadCheckout('0cfd6c06-57c3-4e29-8d7a-de55cc8a9052');\n     *\n     * console.log(state.data.getCheckout());\n     * ```\n     *\n     * @param id - The identifier of the checkout to load, or the default checkout if not provided.\n     * @param options - Options for loading the current checkout.\n     * @returns A promise that resolves to the current state.\n     */\n    loadCheckout(id?: string, options?: RequestOptions<CheckoutParams>): Promise<CheckoutSelectors> {\n        return this._dispatch(id ?\n            this._checkoutActionCreator.loadCheckout(id, options) :\n            this._checkoutActionCreator.loadDefaultCheckout(options)\n        );\n    }\n\n    /**\n     * Updates specific properties of the current checkout.\n     *\n     * ```js\n     * const state = await service.updateCheckout(checkout);\n     *\n     * console.log(state.data.getCheckout());\n     * ```\n     *\n     * @param payload - The checkout properties to be updated.\n     * @param options - Options for loading the current checkout.\n     * @returns A promise that resolves to the current state.\n     */\n    updateCheckout(payload: CheckoutRequestBody, options?: RequestOptions): Promise<CheckoutSelectors> {\n        const action = this._checkoutActionCreator.updateCheckout(payload, options);\n\n        return this._dispatch(action);\n    }\n\n    /**\n     * Loads an order by an id.\n     *\n     * The method can only retrieve an order if the order belongs to the current\n     * customer. If it is successfully executed, the data can be retrieved by\n     * calling `CheckoutStoreSelector#getOrder`.\n     *\n     * ```js\n     * const state = await service.loadOrder(123);\n     *\n     * console.log(state.data.getOrder());\n     * ```\n     *\n     * @param orderId - The identifier of the order to load.\n     * @param options - Options for loading the order.\n     * @returns A promise that resolves to the current state.\n     */\n    loadOrder(orderId: number, options?: RequestOptions): Promise<CheckoutSelectors> {\n        const loadCheckoutAction = this._orderActionCreator.loadOrder(orderId, options);\n        const formFieldsAction = this._formFieldsActionCreator.loadFormFields(options);\n        const loadConfigAction = this._configActionCreator.loadConfig(options);\n\n        return Promise.all([\n            this._dispatch(loadCheckoutAction),\n            this._dispatch(loadConfigAction, { queueId: 'config' }),\n            this._dispatch(formFieldsAction, { queueId: 'formFields' }),\n        ])\n            .then(() => this.getState());\n    }\n\n    /**\n     * Submits an order, thereby completing a checkout process.\n     *\n     * Before you can submit an order, you must initialize the payment method\n     * chosen by the customer by calling `CheckoutService#initializePayment`.\n     *\n     * ```js\n     * await service.initializePayment({ methodId: 'braintree' });\n     * await service.submitOrder({\n     *     payment: {\n     *         methodId: 'braintree',\n     *         paymentData: {\n     *             ccExpiry: { month: 10, year: 20 },\n     *             ccName: 'BigCommerce',\n     *             ccNumber: '4111111111111111',\n     *             ccCvv: 123,\n     *         },\n     *     },\n     * });\n     * ```\n     *\n     * You are not required to include `paymentData` if the order does not\n     * require additional payment details. For example, the customer has already\n     * entered their payment details on the cart page using one of the hosted\n     * payment methods, such as PayPal. Or the customer has applied a gift\n     * certificate that exceeds the grand total amount.\n     *\n     * If the order is submitted successfully, you can retrieve the newly\n     * created order by calling `CheckoutStoreSelector#getOrder`.\n     *\n     * ```js\n     * const state = await service.submitOrder(payload);\n     *\n     * console.log(state.data.getOrder());\n     * ```\n     *\n     * @param payload - The request payload to submit for the current order.\n     * @param options - Options for submitting the current order.\n     * @returns A promise that resolves to the current state.\n     */\n    submitOrder(payload: OrderRequestBody, options?: RequestOptions): Promise<CheckoutSelectors> {\n        const action = this._paymentStrategyActionCreator.execute(payload, options);\n\n        return this._dispatch(action, { queueId: 'paymentStrategy' });\n    }\n\n    /**\n     * Finalizes the submission process for an order.\n     *\n     * This method is only required for certain hosted payment methods that\n     * require a customer to enter their credit card details on their website.\n     * You need to call this method once the customer has redirected back to\n     * checkout in order to complete the checkout process.\n     *\n     * If the method is called before order finalization is required or for a\n     * payment method that does not require order finalization, an error will be\n     * thrown. Conversely, if the method is called successfully, you should\n     * immediately redirect the customer to the order confirmation page.\n     *\n     * ```js\n     * try {\n     *     await service.finalizeOrderIfNeeded();\n     *\n     *     window.location.assign('/order-confirmation');\n     * } catch (error) {\n     *     if (error.type !== 'order_finalization_not_required') {\n     *         throw error;\n     *     }\n     * }\n     * ```\n     *\n     * @param options - Options for finalizing the current order.\n     * @returns A promise that resolves to the current state.\n     * @throws `OrderFinalizationNotRequiredError` error if order finalization\n     * is not required for the current order at the time of execution.\n     */\n    finalizeOrderIfNeeded(options?: RequestOptions): Promise<CheckoutSelectors> {\n        const action = this._paymentStrategyActionCreator.finalize(options);\n\n        return this._dispatch(action, { queueId: 'paymentStrategy' });\n    }\n\n    /**\n     * Loads a list of payment methods available for checkout.\n     *\n     * If a customer enters their payment details before navigating to the\n     * checkout page (i.e.: using PayPal checkout button on the cart page), only\n     * one payment method will be available for the customer - the selected\n     * payment method. Otherwise, by default, all payment methods configured by\n     * the merchant will be available for the customer.\n     *\n     * Once the method is executed successfully, you can call\n     * `CheckoutStoreSelector#getPaymentMethods` to retrieve the list of payment\n     * methods.\n     *\n     * ```js\n     * const state = service.loadPaymentMethods();\n     *\n     * console.log(state.data.getPaymentMethods());\n     * ```\n     *\n     * @param options - Options for loading the payment methods that are\n     * available to the current customer.\n     * @returns A promise that resolves to the current state.\n     */\n    loadPaymentMethods(options?: RequestOptions): Promise<CheckoutSelectors> {\n        const action = this._paymentMethodActionCreator.loadPaymentMethods(options);\n\n        return this._dispatch(action, { queueId: 'paymentMethods' });\n    }\n\n    /**\n     * Loads a payment method by an id.\n     *\n     * This method does not work with multi-option payment providers. Due to its\n     * limitation, it is deprecated and will be removed in the future.\n     *\n     * @deprecated\n     * @internal\n     * @param methodId - The identifier for the payment method to load.\n     * @param options - Options for loading the payment method.\n     * @returns A promise that resolves to the current state.\n     */\n    loadPaymentMethod(methodId: string, options?: RequestOptions): Promise<CheckoutSelectors> {\n        const action = this._paymentMethodActionCreator.loadPaymentMethod(methodId, options);\n\n        return this._dispatch(action, { queueId: 'paymentMethods' });\n    }\n\n    /**\n     * Initializes the payment step of a checkout process.\n     *\n     * Before a payment method can accept payment details, it must first be\n     * initialized. Some payment methods require you to provide additional\n     * initialization options. For example, Amazon requires a container ID in\n     * order to initialize their payment widget.\n     *\n     * ```js\n     * await service.initializePayment({\n     *     methodId: 'amazon',\n     *     amazon: {\n     *         container: 'walletWidget',\n     *     },\n     * });\n     * ```\n     *\n     * @param options - Options for initializing the payment step of checkout.\n     * @returns A promise that resolves to the current state.\n     */\n    initializePayment(options: PaymentInitializeOptions): Promise<CheckoutSelectors> {\n        const action = this._paymentStrategyActionCreator.initialize(options);\n\n        return this._dispatch(action, { queueId: 'paymentStrategy' });\n    }\n\n    /**\n     * De-initializes the payment step of a checkout process.\n     *\n     * The method should be called once you no longer require a payment method\n     * to be initialized. It can perform any necessary clean-up behind the\n     * scene, i.e.: remove DOM nodes or event handlers that are attached as a\n     * result of payment initialization.\n     *\n     * ```js\n     * await service.deinitializePayment({\n     *     methodId: 'amazon',\n     * });\n     * ```\n     *\n     * @param options - Options for deinitializing the payment step of checkout.\n     * @returns A promise that resolves to the current state.\n     */\n    deinitializePayment(options: PaymentRequestOptions): Promise<CheckoutSelectors> {\n        const action = this._paymentStrategyActionCreator.deinitialize(options);\n\n        return this._dispatch(action, { queueId: 'paymentStrategy' });\n    }\n\n    /**\n     * Loads a list of countries available for billing.\n     *\n     * Once you make a successful request, you will be able to retrieve the list\n     * of countries by calling `CheckoutStoreSelector#getBillingCountries`.\n     *\n     * ```js\n     * const state = await service.loadBillingCountries();\n     *\n     * console.log(state.data.getBillingCountries());\n     * ```\n     *\n     * @param options - Options for loading the available billing countries.\n     * @returns A promise that resolves to the current state.\n     */\n    loadBillingCountries(options?: RequestOptions): Promise<CheckoutSelectors> {\n        const action = this._countryActionCreator.loadCountries(options);\n\n        return this._dispatch(action, { queueId: 'billingCountries' });\n    }\n\n    /**\n     * Loads a list of countries available for shipping.\n     *\n     * The list is determined based on the shipping zones configured by a\n     * merchant. Once you make a successful call, you will be able to retrieve\n     * the list of available shipping countries by calling\n     * `CheckoutStoreSelector#getShippingCountries`.\n     *\n     * ```js\n     * const state = await service.loadShippingCountries();\n     *\n     * console.log(state.data.getShippingCountries());\n     * ```\n     *\n     * @param options - Options for loading the available shipping countries.\n     * @returns A promise that resolves to the current state.\n     */\n    loadShippingCountries(options?: RequestOptions): Promise<CheckoutSelectors> {\n        const action = this._shippingCountryActionCreator.loadCountries(options);\n\n        return this._dispatch(action, { queueId: 'shippingCountries' });\n    }\n\n    /**\n     * Loads a set of form fields that should be presented to customers in order\n     * to capture their billing address.\n     *\n     * Once the method has been executed successfully, you can call\n     * `CheckoutStoreSelector#getBillingAddressFields` to retrieve the set of\n     * form fields.\n     *\n     * ```js\n     * const state = service.loadBillingAddressFields();\n     *\n     * console.log(state.data.getBillingAddressFields('US'));\n     * ```\n     *\n     * @param options - Options for loading the billing address form fields.\n     * @returns A promise that resolves to the current state.\n     */\n    loadBillingAddressFields(options?: RequestOptions): Promise<CheckoutSelectors> {\n        return this.loadBillingCountries(options);\n    }\n\n    /**\n     * Loads a set of form fields that should be presented to customers in order\n     * to capture their shipping address.\n     *\n     * Once the method has been executed successfully, you can call\n     * `CheckoutStoreSelector#getShippingAddressFields` to retrieve the set of\n     * form fields.\n     *\n     * ```js\n     * const state = service.loadShippingAddressFields();\n     *\n     * console.log(state.data.getShippingAddressFields('US'));\n     * ```\n     *\n     * @param options - Options for loading the shipping address form fields.\n     * @returns A promise that resolves to the current state.\n     */\n    loadShippingAddressFields(options?: RequestOptions): Promise<CheckoutSelectors> {\n        return this.loadShippingCountries(options);\n    }\n\n    /**\n     * Initializes the sign-in step of a checkout process.\n     *\n     * Some payment methods, such as Amazon, have their own sign-in flow. In\n     * order to support them, this method must be called.\n     *\n     * ```js\n     * await service.initializeCustomer({\n     *     methodId: 'amazon',\n     *     amazon: {\n     *         container: 'signInButton',\n     *     },\n     * });\n     * ```\n     *\n     * @param options - Options for initializing the customer step of checkout.\n     * @returns A promise that resolves to the current state.\n     */\n    initializeCustomer(options?: CustomerInitializeOptions): Promise<CheckoutSelectors> {\n        const action = this._customerStrategyActionCreator.initialize(options);\n\n        return this._dispatch(action, { queueId: 'customerStrategy' });\n    }\n\n    /**\n     * De-initializes the sign-in step of a checkout process.\n     *\n     * It should be called once you no longer want to prompt customers to sign\n     * in. It can perform any necessary clean-up behind the scene, i.e.: remove\n     * DOM nodes or event handlers that are attached as a result of customer\n     * initialization.\n     *\n     * ```js\n     * await service.deinitializeCustomer({\n     *     methodId: 'amazon',\n     * });\n     * ```\n     *\n     * @param options - Options for deinitializing the customer step of checkout.\n     * @returns A promise that resolves to the current state.\n     */\n    deinitializeCustomer(options?: CustomerRequestOptions): Promise<CheckoutSelectors> {\n        const action = this._customerStrategyActionCreator.deinitialize(options);\n\n        return this._dispatch(action, { queueId: 'customerStrategy' });\n    }\n\n    /**\n     * Sends a email that contains a single-use sign-in link. When a valid links is clicked,\n     * signs in the customer without requiring any password, redirecting them to the account page if no redirectUrl is provided.\n     *\n     *\n     * ```js\n     * checkoutService.sendSignInEmail({ email: 'foo@bar.com', redirectUrl: 'checkout' });\n     * ```\n     *\n     * @param signInEmailRequest - The sign-in email request values.\n     * @param options - Options for the send email request.\n     * @returns A promise that resolves to the current state.\n     */\n    sendSignInEmail(signInEmailRequest: SignInEmailRequestBody, options?: RequestOptions): Promise<CheckoutSelectors> {\n        const action = this._signInEmailActionCreator.sendSignInEmail(signInEmailRequest, options);\n\n        return this._dispatch(action, { queueId: 'signInEmail' });\n    }\n\n    /**\n     * Creates a customer account.\n     *\n     * @remarks\n     * ```js\n     * checkoutService.createCustomerAccount({\n     *   email: 'foo@bar.com',\n     *   firstName: 'Foo',\n     *   lastName: 'Bar',\n     *   password: 'password',\n     *   acceptsMarketingEmails: true,\n     *   customFields: [],\n     * });\n     * ```\n     * Please note that `createCustomerAccount` is currently in an early stage\n     * of development. Therefore the API is unstable and not ready for public\n     * consumption.\n     *\n     * @alpha\n     * @param customerAccount - The customer account data.\n     * @param options - Options for creating customer account.\n     * @returns A promise that resolves to the current state.\n     */\n    createCustomerAccount(customerAccount: CustomerAccountRequestBody, options?: RequestOptions): Promise<CheckoutSelectors> {\n        const action = this._customerActionCreator.createCustomer(customerAccount, options);\n\n        return this._dispatch(action);\n    }\n\n    /**\n     * Creates a customer account address.\n     *\n     * @remarks\n     * ```js\n     * checkoutService.createCustomerAddress({\n     *   firstName: 'Foo',\n     *   lastName: 'Bar',\n     *   address1: '55 Market St',\n     *   stateOrProvinceCode: 'CA',\n     *   countryCode: 'US',\n     *   postalCode: '90110'\n     *   customFields: [],\n     * });\n     * ```\n     * Please note that `createCustomerAccountAddress` is currently in an early stage\n     * of development. Therefore the API is unstable and not ready for public\n     * consumption.\n     *\n     * @alpha\n     * @param customerAddress - The customer account data.\n     * @param options - Options for creating customer account.\n     * @returns A promise that resolves to the current state.\n     */\n    createCustomerAddress(customerAddress: CustomerAddressRequestBody, options?: RequestOptions): Promise<CheckoutSelectors> {\n        const action = this._customerActionCreator.createAddress(customerAddress, options);\n\n        return this._dispatch(action);\n    }\n\n    /**\n     * Updates the subscriptions associated to an email.\n     *\n     * @param subscriptions - The email and associated subscriptions to update.\n     * @param options - Options for continuing as a guest.\n     * @returns A promise that resolves to the current state.\n     */\n    updateSubscriptions(subscriptions: Subscriptions, options?: RequestOptions): Promise<CheckoutSelectors> {\n        const action = this._subscriptionsActionCreator.updateSubscriptions(subscriptions, options);\n\n        return this._dispatch(action, { queueId: 'subscriptions' });\n    }\n\n    /**\n     * Continues to check out as a guest.\n     *\n     * If your Checkout Settings allow it, your customers could continue the checkout as guests (without signing in).\n     * If you have enabled the checkout setting \"Prompt existing accounts to sign in\", this information is\n     * exposed as part of the [Customer](../interfaces/customer.md) object.\n     *\n     * Once they provide their email address, it will be stored as\n     * part of their [billing address](../interfaces/billingaddress.md).\n     *\n     * @param credentials - The guest credentials to use, with optional subscriptions.\n     * @param options - Options for continuing as a guest.\n     * @returns A promise that resolves to the current state.\n     */\n    continueAsGuest(credentials: GuestCredentials, options?: RequestOptions): Promise<CheckoutSelectors> {\n        const action = this._billingAddressActionCreator.continueAsGuest(credentials, options);\n\n        return this._dispatch(action);\n    }\n\n    /**\n     * Signs into a customer's registered account.\n     *\n     * Once the customer is signed in successfully, the checkout state will be\n     * populated with information associated with the customer, such as their\n     * saved addresses. You can call `CheckoutStoreSelector#getCustomer` to\n     * retrieve the data.\n     *\n     * ```js\n     * const state = await service.signInCustomer({\n     *     email: 'foo@bar.com',\n     *     password: 'password123',\n     * });\n     *\n     * console.log(state.data.getCustomer());\n     * ```\n     *\n     * @param credentials - The credentials to be used for signing in the customer.\n     * @param options - Options for signing in the customer.\n     * @returns A promise that resolves to the current state.\n     */\n    signInCustomer(credentials: CustomerCredentials, options?: CustomerRequestOptions): Promise<CheckoutSelectors> {\n        const action = this._customerStrategyActionCreator.signIn(credentials, options);\n\n        return this._dispatch(action, { queueId: 'customerStrategy' });\n    }\n\n    /**\n     * Signs out the current customer if they are previously signed in.\n     *\n     * Once the customer is successfully signed out, the checkout state will be\n     * reset automatically.\n     *\n     * ```js\n     * const state = await service.signOutCustomer();\n     *\n     * // The returned object should not contain information about the previously signed-in customer.\n     * console.log(state.data.getCustomer());\n     * ```\n     *\n     * When a store has \"Allow customers to access their cart across multiple devices\" enabled, signing out\n     * will remove the cart/checkout data from the current session. An error with type=\"checkout_not_available\" will be thrown.\n     *\n     * ```js\n     * try {\n     *   await service.signOutCustomer();\n     * } catch (error) {\n     *   if (error.type === 'checkout_not_available') {\n     *     window.top.location.assign('/');\n     *   }\n     * }\n     * ```\n     *\n     * @param options - Options for signing out the customer.\n     * @returns A promise that resolves to the current state.\n     */\n    signOutCustomer(options?: CustomerRequestOptions): Promise<CheckoutSelectors> {\n        const action = this._customerStrategyActionCreator.signOut(options);\n\n        return this._dispatch(action, { queueId: 'customerStrategy' });\n    }\n\n    /**\n     * Loads a list of shipping options available for checkout.\n     *\n     * Available shipping options can only be determined once a customer\n     * provides their shipping address. If the method is executed successfully,\n     * `CheckoutStoreSelector#getShippingOptions` can be called to retrieve the\n     * list of shipping options.\n     *\n     * ```js\n     * const state = await service.loadShippingOptions();\n     *\n     * console.log(state.data.getShippingOptions());\n     * ```\n     *\n     * @param options - Options for loading the available shipping options.\n     * @returns A promise that resolves to the current state.\n     */\n    loadShippingOptions(options?: RequestOptions): Promise<CheckoutSelectors> {\n        const action = this._consignmentActionCreator.loadShippingOptions(options);\n\n        return this._dispatch(action);\n    }\n\n    /**\n     * Initializes the shipping step of a checkout process.\n     *\n     * Some payment methods, such as Amazon, can provide shipping information to\n     * be used for checkout. In order to support them, this method must be\n     * called.\n     *\n     * ```js\n     * await service.initializeShipping({\n     *     methodId: 'amazon',\n     *     amazon: {\n     *         container: 'addressBook',\n     *     },\n     * });\n     * ```\n     *\n     * @param options - Options for initializing the shipping step of checkout.\n     * @returns A promise that resolves to the current state.\n     */\n    initializeShipping(options?: ShippingInitializeOptions): Promise<CheckoutSelectors> {\n        const action = this._shippingStrategyActionCreator.initialize(options);\n\n        return this._dispatch(action, { queueId: 'shippingStrategy' });\n    }\n\n    /**\n     * De-initializes the shipping step of a checkout process.\n     *\n     * It should be called once you no longer need to collect shipping details.\n     * It can perform any necessary clean-up behind the scene, i.e.: remove DOM\n     * nodes or event handlers that are attached as a result of shipping\n     * initialization.\n     *\n     * ```js\n     * await service.deinitializeShipping({\n     *     methodId: 'amazon',\n     * });\n     * ```\n     *\n     * @param options - Options for deinitializing the shipping step of checkout.\n     * @returns A promise that resolves to the current state.\n     */\n    deinitializeShipping(options?: ShippingRequestOptions): Promise<CheckoutSelectors> {\n        const action = this._shippingStrategyActionCreator.deinitialize(options);\n\n        return this._dispatch(action, { queueId: 'shippingStrategy' });\n    }\n\n    /**\n     * Selects a shipping option for the current address.\n     *\n     * If a shipping option has an additional cost, the quote for the current\n     * order will be adjusted once the option is selected.\n     *\n     * ```js\n     * const state = await service.selectShippingOption('address-id', 'shipping-option-id');\n     *\n     * console.log(state.data.getSelectedShippingOption());\n     * ```\n     *\n     * @param shippingOptionId - The identifier of the shipping option to\n     * select.\n     * @param options - Options for selecting the shipping option.\n     * @returns A promise that resolves to the current state.\n     */\n    selectShippingOption(shippingOptionId: string, options?: ShippingRequestOptions): Promise<CheckoutSelectors> {\n        const action = this._shippingStrategyActionCreator.selectOption(shippingOptionId, options);\n\n        return this._dispatch(action, { queueId: 'shippingStrategy' });\n    }\n\n    /**\n     * Updates the shipping address for the current checkout.\n     *\n     * When a customer updates their shipping address for an order, they will\n     * see an updated list of shipping options and the cost for each option,\n     * unless no options are available. If the update is successful, you can\n     * call `CheckoutStoreSelector#getShippingAddress` to retrieve the address.\n     *\n     * If the shipping address changes and the selected shipping option becomes\n     * unavailable for the updated address, the shipping option will be\n     * deselected.\n     *\n     * You can submit an address that is partially complete. The address does\n     * not get validated until you submit the order.\n     *\n     * ```js\n     * const state = await service.updateShippingAddress(address);\n     *\n     * console.log(state.data.getShippingAddress());\n     * ```\n     *\n     * @param address - The address to be used for shipping.\n     * @param options - Options for updating the shipping address.\n     * @returns A promise that resolves to the current state.\n     */\n    updateShippingAddress(\n        address: Partial<AddressRequestBody>,\n        options?: ShippingRequestOptions<CheckoutParams>\n    ): Promise<CheckoutSelectors> {\n        const action = this._shippingStrategyActionCreator.updateAddress(address, options);\n\n        return this._dispatch(action, { queueId: 'shippingStrategy' });\n    }\n\n    /**\n     * Creates consignments given a list.\n     *\n     * Note: this is used when items need to be shipped to multiple addresses,\n     * for single shipping address, use `CheckoutService#updateShippingAddress`.\n     *\n     * When consignments are created, an updated list of shipping options will\n     * become available for each consignment, unless no options are available.\n     * If the update is successful, you can call\n     * `CheckoutStoreSelector#getConsignments` to retrieve the updated list of\n     * consignments.'\n     *\n     * Beware that if a consignment includes all line items from another\n     * consignment, that consignment will be deleted as a valid consignment must\n     * include at least one valid line item.\n     *\n     * You can submit an address that is partially complete. The address does\n     * not get validated until you submit the order.\n     *\n     * ```js\n     * const state = await service.createConsignments(consignments);\n     *\n     * console.log(state.data.getConsignments());\n     * ```\n     *\n     * @param consignments - The list of consignments to be created.\n     * @param options - Options for updating the shipping address.\n     * @returns A promise that resolves to the current state.\n     */\n    createConsignments(\n        consignments: ConsignmentsRequestBody,\n        options?: RequestOptions\n    ): Promise<CheckoutSelectors> {\n        const action = this._consignmentActionCreator.createConsignments(consignments, options);\n\n        return this._dispatch(action, { queueId: 'shippingStrategy' });\n    }\n\n    /**\n     * Deletes a consignment\n     *\n     * ```js\n     * const state = await service.deleteConsignment('55c96cda6f04c');\n     *\n     * console.log(state.data.getConsignments());\n     * ```\n     *\n     * @param consignmentId - The ID of the consignment to be deleted\n     * @param options - Options for the consignment delete request\n     * @returns A promise that resolves to the current state.\n     */\n    deleteConsignment(\n        consignmentId: string,\n        options?: RequestOptions\n    ): Promise<CheckoutSelectors> {\n        const action = this._consignmentActionCreator.deleteConsignment(consignmentId, options);\n\n        return this._dispatch(action, { queueId: 'shippingStrategy' });\n    }\n\n    /**\n     * Updates a specific consignment.\n     *\n     * Note: this is used when items need to be shipped to multiple addresses,\n     * for single shipping address, use `CheckoutService#selectShippingOption`.\n     *\n     * When a shipping address for a consignment is updated, an updated list of\n     * shipping options will become available for the consignment, unless no\n     * options are available. If the update is successful, you can call\n     * `CheckoutStoreSelector#getConsignments` to retrieve updated list of\n     * consignments.\n     *\n     * Beware that if the updated consignment includes all line items from another\n     * consignment, that consignment will be deleted as a valid consignment must\n     * include at least one valid line item.\n     *\n     * If the shipping address changes and the selected shipping option becomes\n     * unavailable for the updated address, the shipping option will be\n     * deselected.\n     *\n     * You can submit an address that is partially complete. The address does\n     * not get validated until you submit the order.\n     *\n     * ```js\n     * const state = await service.updateConsignment(consignment);\n     *\n     * console.log(state.data.getConsignments());\n     * ```\n     *\n     * @param consignment - The consignment data that will be used.\n     * @param options - Options for updating the shipping address.\n     * @returns A promise that resolves to the current state.\n     */\n    updateConsignment(\n        consignment: ConsignmentUpdateRequestBody,\n        options?: RequestOptions\n    ): Promise<CheckoutSelectors> {\n        const action = this._consignmentActionCreator.updateConsignment(consignment, options);\n\n        return this._dispatch(action, { queueId: 'shippingStrategy' });\n    }\n\n    /**\n     * Convenience method that assigns items to be shipped to a specific address.\n     *\n     * Note: this method finds an existing consignment that matches the provided address\n     * and assigns the provided items. If no consignment matches the address, a new one\n     * will be created.\n     *\n     * @param consignment - The consignment data that will be used.\n     * @param options - Options for the request\n     * @returns A promise that resolves to the current state.\n     */\n    assignItemsToAddress(\n        consignment: ConsignmentAssignmentRequestBody,\n        options?: RequestOptions\n    ): Promise<CheckoutSelectors> {\n        const action = this._consignmentActionCreator.assignItemsByAddress(consignment, options);\n\n        return this._dispatch(action, { queueId: 'shippingStrategy' });\n    }\n\n    /**\n     * Convenience method that unassigns items from a specific shipping address.\n     *\n     * Note: this method finds an existing consignment that matches the provided address\n     * and unassigns the specified items. If the consignment ends up with no line items\n     * after the unassignment, it will be deleted.\n     *\n     * @param consignment - The consignment data that will be used.\n     * @param options - Options for the request\n     * @returns A promise that resolves to the current state.\n     */\n    unassignItemsToAddress(\n        consignment: ConsignmentAssignmentRequestBody,\n        options?: RequestOptions\n    ): Promise<CheckoutSelectors> {\n        const action = this._consignmentActionCreator.unassignItemsByAddress(consignment, options);\n\n        return this._dispatch(action, { queueId: 'shippingStrategy' });\n    }\n\n    /**\n     * Selects a shipping option for a given consignment.\n     *\n     * Note: this is used when items need to be shipped to multiple addresses,\n     * for single shipping address, use `CheckoutService#updateShippingAddress`.\n     *\n     * If a shipping option has an additional cost, the quote for the current\n     * order will be adjusted once the option is selected.\n     *\n     * ```js\n     * const state = await service.selectConsignmentShippingOption(consignmentId, optionId);\n     *\n     * console.log(state.data.getConsignments());\n     * ```\n     *\n     * @param consignmentId - The identified of the consignment to be updated.\n     * @param shippingOptionId - The identifier of the shipping option to\n     * select.\n     * @param options - Options for selecting the shipping option.\n     * @returns A promise that resolves to the current state.\n     */\n    selectConsignmentShippingOption(\n        consignmentId: string,\n        shippingOptionId: string,\n        options?: ShippingRequestOptions\n    ): Promise<CheckoutSelectors> {\n        const action = this._consignmentActionCreator.updateShippingOption({\n            id: consignmentId,\n            shippingOptionId,\n        }, options);\n\n        return this._dispatch(action, { queueId: 'shippingStrategy' });\n    }\n\n    /**\n     * Updates the billing address for the current checkout.\n     *\n     * A customer must provide their billing address before they can proceed to\n     * pay for their order.\n     *\n     * You can submit an address that is partially complete. The address does\n     * not get validated until you submit the order.\n     *\n     * ```js\n     * const state = await service.updateBillingAddress(address);\n     *\n     * console.log(state.data.getBillingAddress());\n     * ```\n     *\n     * @param address - The address to be used for billing.\n     * @param options - Options for updating the billing address.\n     * @returns A promise that resolves to the current state.\n     */\n    updateBillingAddress(address: Partial<BillingAddressRequestBody>, options: RequestOptions = {}): Promise<CheckoutSelectors> {\n        const action = this._billingAddressActionCreator.updateAddress(address, options);\n\n        return this._dispatch(action);\n    }\n\n    /**\n     * Applies or removes customer's store credit code to the current checkout.\n     *\n     * Once the store credit gets applied, the outstanding balance will be adjusted accordingly.\n     *\n     * ```js\n     * const state = await service.applyStoreCredit(true);\n     *\n     * console.log(state.data.getCheckout().outstandingBalance);\n     * ```\n     *\n     * @param options - Options for applying store credit.\n     * @returns A promise that resolves to the current state.\n     */\n    applyStoreCredit(useStoreCredit: boolean, options?: RequestOptions): Promise<CheckoutSelectors> {\n        const action = this._storeCreditActionCreator.applyStoreCredit(useStoreCredit, options);\n\n        return this._dispatch(action);\n    }\n\n    /**\n     * Applies a coupon code to the current checkout.\n     *\n     * Once the coupon code gets applied, the quote for the current checkout will\n     * be adjusted accordingly. The same coupon code cannot be applied more than\n     * once.\n     *\n     * ```js\n     * await service.applyCoupon('COUPON');\n     * ```\n     *\n     * @param code - The coupon code to apply to the current checkout.\n     * @param options - Options for applying the coupon code.\n     * @returns A promise that resolves to the current state.\n     */\n    applyCoupon(code: string, options?: RequestOptions): Promise<CheckoutSelectors> {\n        const action = this._couponActionCreator.applyCoupon(code, options);\n\n        return this._dispatch(action);\n    }\n\n    /**\n     * Removes a coupon code from the current checkout.\n     *\n     * Once the coupon code gets removed, the quote for the current checkout will\n     * be adjusted accordingly.\n     *\n     * ```js\n     * await service.removeCoupon('COUPON');\n     * ```\n     *\n     * @param code - The coupon code to remove from the current checkout.\n     * @param options - Options for removing the coupon code.\n     * @returns A promise that resolves to the current state.\n     */\n    removeCoupon(code: string, options?: RequestOptions): Promise<CheckoutSelectors> {\n        const action = this._couponActionCreator.removeCoupon(code, options);\n\n        return this._dispatch(action);\n    }\n\n    /**\n     * Applies a gift certificate to the current checkout.\n     *\n     * Once the gift certificate gets applied, the quote for the current\n     * checkout will be adjusted accordingly.\n     *\n     * ```js\n     * await service.applyGiftCertificate('GIFT_CERTIFICATE');\n     * ```\n     *\n     * @param code - The gift certificate to apply to the current checkout.\n     * @param options - Options for applying the gift certificate.\n     * @returns A promise that resolves to the current state.\n     */\n    applyGiftCertificate(code: string, options?: RequestOptions): Promise<CheckoutSelectors> {\n        const action = this._giftCertificateActionCreator.applyGiftCertificate(code, options);\n\n        return this._dispatch(action);\n    }\n\n    /**\n     * Removes a gift certificate from an order.\n     *\n     * Once the gift certificate gets removed, the quote for the current\n     * checkout will be adjusted accordingly.\n     *\n     * ```js\n     * await service.removeGiftCertificate('GIFT_CERTIFICATE');\n     * ```\n     *\n     * @param code - The gift certificate to remove from the current checkout.\n     * @param options - Options for removing the gift certificate.\n     * @returns A promise that resolves to the current state.\n     */\n    removeGiftCertificate(code: string, options?: RequestOptions): Promise<CheckoutSelectors> {\n        const action = this._giftCertificateActionCreator.removeGiftCertificate(code, options);\n\n        return this._dispatch(action);\n    }\n\n    /**\n     * Loads a list of payment instruments associated with a customer.\n     *\n     * Once the method has been called successfully, you can retrieve the list\n     * of payment instruments by calling `CheckoutStoreSelector#getInstruments`.\n     * If the customer does not have any payment instruments on record, i.e.:\n     * credit card, you will get an empty list instead.\n     *\n     * ```js\n     * const state = service.loadInstruments();\n     *\n     * console.log(state.data.getInstruments());\n     * ```\n     *\n     * @returns A promise that resolves to the current state.\n     */\n    loadInstruments(): Promise<CheckoutSelectors> {\n        const action = this._instrumentActionCreator.loadInstruments();\n\n        return this._dispatch(action);\n    }\n\n    /**\n     * Deletes a payment instrument by an id.\n     *\n     * Once an instrument gets removed, it can no longer be retrieved using\n     * `CheckoutStoreSelector#getInstruments`.\n     *\n     * ```js\n     * const state = service.deleteInstrument('123');\n     *\n     * console.log(state.data.getInstruments());\n     * ```\n     *\n     * @param instrumentId - The identifier of the payment instrument to delete.\n     * @returns A promise that resolves to the current state.\n     */\n    deleteInstrument(instrumentId: string): Promise<CheckoutSelectors> {\n        const action = this._instrumentActionCreator.deleteInstrument(instrumentId);\n\n        return this._dispatch(action)\n            .then(() => this.loadInstruments());\n    }\n\n    /**\n     * Clear errors that have been collected from previous calls.\n     *\n     * ```js\n     * const state = await service.clearError(error);\n     *\n     * console.log(state.errors.getError());\n     * ```\n     *\n     * @param error - Specific error object to clear\n     * @returns A promise that resolves to the current state.\n     */\n    clearError(error: Error): Promise<CheckoutSelectors> {\n        const action = this._errorActionCreator.clearError(error);\n\n        return this._dispatch(action);\n    }\n\n    /**\n     * Initializes the spam protection for order creation.\n     *\n     * Note: Use `CheckoutService#executeSpamCheck` instead.\n     * You do not need to call this method before calling\n     * `CheckoutService#executeSpamCheck`.\n     *\n     * With spam protection enabled, the customer has to be verified as\n     * a human. The order creation will fail if spam protection\n     * is enabled but verification fails.\n     *\n     * ```js\n     * await service.initializeSpamProtection();\n     * ```\n     *\n     * @param options - Options for initializing spam protection.\n     * @returns A promise that resolves to the current state.\n     * @deprecated - Use CheckoutService#executeSpamCheck instead.\n     */\n    initializeSpamProtection(options: SpamProtectionOptions): Promise<CheckoutSelectors> {\n        const action = this._spamProtectionActionCreator.initialize(options);\n\n        return this._dispatch(action, { queueId: 'spamProtection' });\n    }\n\n    /**\n     * Verifies whether the current checkout is created by a human.\n     *\n     * Note: this method will do the initialization, therefore you do not\n     * need to call `CheckoutService#initializeSpamProtection`\n     * before calling this method.\n     *\n     * With spam protection enabled, the customer has to be verified as\n     * a human. The order creation will fail if spam protection\n     * is enabled but verification fails. You should call this method before\n     * `submitOrder` method is called (i.e.: when the shopper\n     * first gets to the payment step).\n     *\n     * **Note**: You need to enable Google ReCAPTCHA bot protection in your Checkout Settings.\n     *\n     * ```js\n     * await service.executeSpamCheck();\n     * ```\n     *\n     * @returns A promise that resolves to the current state.\n     */\n    executeSpamCheck(): Promise<CheckoutSelectors> {\n        const action = this._spamProtectionActionCreator.verifyCheckoutSpamProtection();\n\n        return this._dispatch(action, { queueId: 'spamProtection' });\n    }\n\n    /**\n     * Dispatches an action through the data store and returns the current state\n     * once the action is dispatched.\n     *\n     * @param action - The action to dispatch.\n     * @returns A promise that resolves to the current state.\n     */\n    private _dispatch(action: Action | Observable<Action> | ThunkAction<Action>, options?: { queueId?: string }): Promise<CheckoutSelectors> {\n        return this._store.dispatch(action, options)\n            .then(() => this.getState())\n            .catch(error => {\n                throw this._errorTransformer.transform(error);\n            });\n    }\n}\n","import { ErrorMessageTransformer } from '../common/error';\nimport { MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType } from '../common/error/errors';\nimport { getEnvironment } from '../common/utility';\n\nexport type CheckoutServiceErrorType = MissingDataError | NotInitializedError;\nexport type CheckoutServiceErrorTransformer = ErrorMessageTransformer<CheckoutServiceErrorType | Error>;\n\nexport default function createCheckoutServiceErrorTransformer(\n    isDevelopment: boolean = getEnvironment() === 'development'\n): CheckoutServiceErrorTransformer {\n    return new ErrorMessageTransformer(error => {\n        if (!isDevelopment || !isCheckoutServiceError(error)) {\n            return error.message;\n        }\n\n        switch (error.subtype || error.type) {\n        case MissingDataErrorType.MissingConsignments:\n            return `\n                ${error.message}\n                The data could be unavailable because no shipping address has been provided.\n                To fix this, create a consignment or update the shipping address before performing\n                the same action again.\n            `;\n\n        case MissingDataErrorType.MissingCart:\n        case MissingDataErrorType.MissingCheckout:\n            return `\n                ${error.message}\n                The data could be unavailable because it has not loaded from the server yet.\n                To fix this issue, you can try calling \\`CheckoutService#loadCheckout\\`\n                before performing the same action again.\n            `;\n\n        case MissingDataErrorType.MissingCheckoutConfig:\n            return `\n                ${error.message}\n                The data could be unavailable because it has not loaded from the server yet.\n                To fix this issue, you need to make sure \\`CheckoutService\\` is initialized\n                properly by calling \\`CheckoutService#loadCheckout\\` before performing any\n                other actions.\n            `;\n\n        case MissingDataErrorType.MissingOrder:\n            return `\n                ${error.message}\n                The data could be unavailable because it has not loaded from the server yet.\n                To fix this issue, you can try calling \\`CheckoutService#loadOrder\\`\n                before performing the same action again.\n            `;\n\n        case MissingDataErrorType.MissingOrderId:\n            return `\n                ${error.message}\n                The data could be unavailable because no order has been created yet. You have\n                to first create the order before you can perform the action.\n            `;\n\n        case MissingDataErrorType.MissingPaymentMethod:\n            return `\n                ${error.message}\n                The data could be unavailable because it has not loaded from the server, or\n                configured by the merchant yet. To fix the former issue, you can try calling\n                \\`CheckoutService#loadPaymentMethods\\` before performing the same action again.\n            `;\n\n        case NotInitializedErrorType.CustomerNotInitialized:\n            return `\n                In order to initialize the customer step of checkout, you need to call\n                \\`CheckoutService#initializeCustomer\\`. Afterwards, you should be able to\n                submit customer details.\n            `;\n\n        case NotInitializedErrorType.PaymentNotInitialized:\n            return `\n                ${error.message}\n                In order to initialize the payment step of checkout, you need to call\n                \\`CheckoutService#initializePayment\\`. Afterwards, you should be able to\n                submit payment details.\n            `;\n\n        case NotInitializedErrorType.ShippingNotInitialized:\n            return `\n                ${error.message}\n                In order to initialize the shipping step of checkout, you need to call\n                \\`CheckoutService#initializeShipping\\`. Afterwards, you should be able to\n                submit shipping details.\n            `;\n\n        default:\n            return error.message;\n        }\n    });\n}\n\nfunction isCheckoutServiceError(error: any): error is CheckoutServiceErrorType {\n    return !!(error.subtype || error.type);\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { ErrorActionCreator } from '../common/error';\nimport { getDefaultLogger } from '../common/log';\nimport { getEnvironment } from '../common/utility';\nimport { ConfigActionCreator, ConfigRequestSender, ConfigState, ConfigWindow } from '../config';\nimport { CouponActionCreator, CouponRequestSender, GiftCertificateActionCreator, GiftCertificateRequestSender } from '../coupon';\nimport { createCustomerStrategyRegistry, CustomerActionCreator, CustomerRequestSender, CustomerStrategyActionCreator } from '../customer';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { CountryActionCreator, CountryRequestSender } from '../geography';\nimport { OrderActionCreator, OrderRequestSender } from '../order';\nimport { createPaymentClient, createPaymentStrategyRegistry, PaymentMethodActionCreator, PaymentMethodRequestSender, PaymentStrategyActionCreator } from '../payment';\nimport { InstrumentActionCreator, InstrumentRequestSender } from '../payment/instrument';\nimport { createShippingStrategyRegistry, ConsignmentActionCreator, ConsignmentRequestSender, ShippingCountryActionCreator, ShippingCountryRequestSender, ShippingStrategyActionCreator } from '../shipping';\nimport { SignInEmailActionCreator, SignInEmailRequestSender } from '../signin-email';\nimport { createSpamProtection, SpamProtectionActionCreator, SpamProtectionRequestSender } from '../spam-protection';\nimport { StoreCreditActionCreator, StoreCreditRequestSender } from '../store-credit';\nimport { SubscriptionsActionCreator, SubscriptionsRequestSender } from '../subscription';\n\nimport CheckoutActionCreator from './checkout-action-creator';\nimport CheckoutRequestSender from './checkout-request-sender';\nimport CheckoutService from './checkout-service';\nimport CheckoutValidator from './checkout-validator';\nimport createCheckoutStore from './create-checkout-store';\n\n/**\n * Creates an instance of `CheckoutService`.\n *\n * @remarks\n * ```js\n * const service = createCheckoutService();\n *\n * service.subscribe(state => {\n *     console.log(state);\n * });\n *\n * service.loadCheckout();\n * ```\n *\n * @param options - A set of construction options.\n * @returns an instance of `CheckoutService`.\n */\nexport default function createCheckoutService(options?: CheckoutServiceOptions): CheckoutService {\n    if (document.location.protocol !== 'https:') {\n        getDefaultLogger().warn('The BigCommerce Checkout SDK should not be used on a non-HTTPS page');\n    }\n\n    if (getEnvironment() !== 'production') {\n        getDefaultLogger().warn('Note that the development build is not optimized. To create a production build, set process.env.NODE_ENV to `production`.');\n    }\n\n    const config: ConfigState = {\n        meta: {\n            externalSource: options && options.externalSource,\n            variantIdentificationToken: (window as ConfigWindow).checkoutVariantIdentificationToken,\n        },\n        errors: {},\n        statuses: {},\n    };\n    const { locale = '', shouldWarnMutation = true } = options || {};\n    const requestSender = createRequestSender({ host: options && options.host });\n    const store = createCheckoutStore({ config }, { shouldWarnMutation });\n    const paymentClient = createPaymentClient(store);\n    const orderRequestSender = new OrderRequestSender(requestSender);\n    const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n    const configActionCreator = new ConfigActionCreator(new ConfigRequestSender(requestSender));\n    const spamProtection = createSpamProtection(createScriptLoader());\n    const spamProtectionRequestSender = new SpamProtectionRequestSender(requestSender);\n    const spamProtectionActionCreator = new SpamProtectionActionCreator(spamProtection, spamProtectionRequestSender);\n    const orderActionCreator = new OrderActionCreator(\n        orderRequestSender,\n        new CheckoutValidator(checkoutRequestSender)\n    );\n    const subscriptionsActionCreator = new SubscriptionsActionCreator(new SubscriptionsRequestSender(requestSender));\n    const formFieldsActionCreator = new FormFieldsActionCreator(new FormFieldsRequestSender(requestSender));\n    const checkoutActionCreator = new CheckoutActionCreator(checkoutRequestSender, configActionCreator, formFieldsActionCreator);\n\n    return new CheckoutService(\n        store,\n        new BillingAddressActionCreator(\n            new BillingAddressRequestSender(requestSender),\n            subscriptionsActionCreator\n        ),\n        checkoutActionCreator,\n        configActionCreator,\n        new CustomerActionCreator(\n            new CustomerRequestSender(requestSender),\n            checkoutActionCreator,\n            spamProtectionActionCreator\n        ),\n        new ConsignmentActionCreator(new ConsignmentRequestSender(requestSender), checkoutRequestSender),\n        new CountryActionCreator(new CountryRequestSender(requestSender, { locale })),\n        new CouponActionCreator(new CouponRequestSender(requestSender)),\n        new CustomerStrategyActionCreator(createCustomerStrategyRegistry(store, requestSender)),\n        new ErrorActionCreator(),\n        new GiftCertificateActionCreator(new GiftCertificateRequestSender(requestSender)),\n        new InstrumentActionCreator(new InstrumentRequestSender(paymentClient, requestSender)),\n        orderActionCreator,\n        new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender)),\n        new PaymentStrategyActionCreator(\n            createPaymentStrategyRegistry(store, paymentClient, requestSender, spamProtection, locale),\n            orderActionCreator,\n            spamProtectionActionCreator\n        ),\n        new ShippingCountryActionCreator(new ShippingCountryRequestSender(requestSender, { locale })),\n        new ShippingStrategyActionCreator(createShippingStrategyRegistry(store, requestSender)),\n        new SignInEmailActionCreator(new SignInEmailRequestSender(requestSender)),\n        spamProtectionActionCreator,\n        new StoreCreditActionCreator(new StoreCreditRequestSender(requestSender)),\n        subscriptionsActionCreator,\n        formFieldsActionCreator\n    );\n}\n\nexport interface CheckoutServiceOptions {\n    locale?: string;\n    host?: string;\n    shouldWarnMutation?: boolean;\n    externalSource?: string;\n}\n","// tslint:disable-next-line:no-reference\n/// <reference path=\"../payment/bigpay-client.d.ts\" />\nimport { createClient as createBigpayClient } from '@bigcommerce/bigpay-client';\n\nimport { CheckoutStore } from '../checkout';\n\nexport default function createPaymentClient(store: CheckoutStore) {\n    const paymentClient = createBigpayClient();\n\n    store.subscribe(\n        state => {\n            const config = state.config.getStoreConfig();\n\n            if (config) {\n                paymentClient.setHost(config.paymentSettings.bigpayBaseUrl);\n            }\n        },\n        state => state.config.getStoreConfig()\n    );\n\n    return paymentClient;\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { CheckoutActionCreator, CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { AmazonPayScriptLoader } from '../payment/strategies/amazon-pay';\nimport { createAmazonPayV2PaymentProcessor } from '../payment/strategies/amazon-pay-v2';\nimport { createBraintreeVisaCheckoutPaymentProcessor, BraintreeScriptLoader, BraintreeSDKCreator, VisaCheckoutScriptLoader } from '../payment/strategies/braintree';\nimport { ChasePayScriptLoader } from '../payment/strategies/chasepay';\nimport { createGooglePayPaymentProcessor, GooglePayAdyenV2Initializer, GooglePayAuthorizeNetInitializer, GooglePayBraintreeInitializer, GooglePayCheckoutcomInitializer, GooglePayCybersourceV2Initializer, GooglePayOrbitalInitializer, GooglePayStripeInitializer } from '../payment/strategies/googlepay';\nimport { MasterpassScriptLoader } from '../payment/strategies/masterpass';\nimport { RemoteCheckoutActionCreator, RemoteCheckoutRequestSender } from '../remote-checkout';\nimport { createSpamProtection, SpamProtectionActionCreator, SpamProtectionRequestSender } from '../spam-protection';\n\nimport CustomerActionCreator from './customer-action-creator';\nimport CustomerRequestSender from './customer-request-sender';\nimport CustomerStrategyActionCreator from './customer-strategy-action-creator';\nimport { CustomerStrategy } from './strategies';\nimport { AmazonPayCustomerStrategy } from './strategies/amazon';\nimport { AmazonPayV2CustomerStrategy } from './strategies/amazon-pay-v2';\nimport { BraintreeVisaCheckoutCustomerStrategy } from './strategies/braintree';\nimport { ChasePayCustomerStrategy } from './strategies/chasepay';\nimport { DefaultCustomerStrategy } from './strategies/default';\nimport { GooglePayCustomerStrategy } from './strategies/googlepay';\nimport { MasterpassCustomerStrategy } from './strategies/masterpass';\nimport { SquareCustomerStrategy } from './strategies/square';\n\nexport default function createCustomerStrategyRegistry(\n    store: CheckoutStore,\n    requestSender: RequestSender\n): Registry<CustomerStrategy> {\n    const registry = new Registry<CustomerStrategy>();\n    const scriptLoader = getScriptLoader();\n    const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n    const checkoutActionCreator = new CheckoutActionCreator(\n        checkoutRequestSender,\n        new ConfigActionCreator(new ConfigRequestSender(requestSender)),\n        new FormFieldsActionCreator(new FormFieldsRequestSender(requestSender))\n    );\n    const formPoster = createFormPoster();\n    const paymentMethodActionCreator = new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender));\n    const remoteCheckoutRequestSender = new RemoteCheckoutRequestSender(requestSender);\n    const remoteCheckoutActionCreator = new RemoteCheckoutActionCreator(remoteCheckoutRequestSender);\n\n    registry.register('googlepayadyenv2', () =>\n        new GooglePayCustomerStrategy(\n            store,\n            remoteCheckoutActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayAdyenV2Initializer()\n            ),\n            formPoster\n        )\n    );\n\n    registry.register('amazon', () =>\n        new AmazonPayCustomerStrategy(\n            store,\n            paymentMethodActionCreator,\n            remoteCheckoutActionCreator,\n            remoteCheckoutRequestSender,\n            new AmazonPayScriptLoader(scriptLoader)\n        )\n    );\n\n    registry.register('amazonpay', () =>\n        new AmazonPayV2CustomerStrategy(\n            store,\n            paymentMethodActionCreator,\n            remoteCheckoutActionCreator,\n            createAmazonPayV2PaymentProcessor()\n        )\n    );\n\n    registry.register('braintreevisacheckout', () =>\n        new BraintreeVisaCheckoutCustomerStrategy(\n            store,\n            checkoutActionCreator,\n            paymentMethodActionCreator,\n            new CustomerStrategyActionCreator(registry),\n            remoteCheckoutActionCreator,\n            createBraintreeVisaCheckoutPaymentProcessor(scriptLoader, requestSender),\n            new VisaCheckoutScriptLoader(scriptLoader)\n        )\n    );\n\n    registry.register('chasepay', () =>\n        new ChasePayCustomerStrategy(\n            store,\n            paymentMethodActionCreator,\n            remoteCheckoutActionCreator,\n            new ChasePayScriptLoader(scriptLoader),\n            requestSender,\n            formPoster\n        )\n    );\n\n    registry.register('squarev2', () =>\n        new SquareCustomerStrategy(\n            store,\n            new RemoteCheckoutActionCreator(remoteCheckoutRequestSender)\n        )\n    );\n\n    registry.register('masterpass', () =>\n        new MasterpassCustomerStrategy(\n            store,\n            paymentMethodActionCreator,\n            remoteCheckoutActionCreator,\n            new MasterpassScriptLoader(scriptLoader)\n        )\n    );\n\n    registry.register('googlepayauthorizenet', () =>\n        new GooglePayCustomerStrategy(\n            store,\n            remoteCheckoutActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayAuthorizeNetInitializer()\n            ),\n            formPoster\n        )\n    );\n\n    registry.register('googlepaybraintree', () =>\n        new GooglePayCustomerStrategy(\n            store,\n            remoteCheckoutActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayBraintreeInitializer(\n                    new BraintreeSDKCreator(\n                        new BraintreeScriptLoader(scriptLoader)\n                    )\n                )\n            ),\n            formPoster\n        )\n    );\n\n    registry.register('googlepaycheckoutcom', () =>\n        new GooglePayCustomerStrategy(\n            store,\n            remoteCheckoutActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayCheckoutcomInitializer(requestSender)\n            ),\n            formPoster\n        )\n    );\n\n    registry.register('googlepaycybersourcev2', () =>\n        new GooglePayCustomerStrategy(\n            store,\n            remoteCheckoutActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayCybersourceV2Initializer()\n            ),\n            formPoster\n        )\n    );\n\n    registry.register('googlepayorbital', () =>\n        new GooglePayCustomerStrategy(\n            store,\n            remoteCheckoutActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayOrbitalInitializer()\n            ),\n            formPoster\n        )\n    );\n\n    registry.register('googlepaystripe', () =>\n        new GooglePayCustomerStrategy(\n            store,\n            remoteCheckoutActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayStripeInitializer()\n            ),\n            formPoster\n        )\n    );\n\n    registry.register('default', () =>\n        new DefaultCustomerStrategy(\n            store,\n            new CustomerActionCreator(\n                new CustomerRequestSender(requestSender),\n                checkoutActionCreator,\n                new SpamProtectionActionCreator(\n                    createSpamProtection(scriptLoader),\n                    new SpamProtectionRequestSender(requestSender)\n                )\n            )\n        )\n    );\n\n    return registry;\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\nimport { createScriptLoader, getScriptLoader, getStylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { CheckoutActionCreator, CheckoutRequestSender, CheckoutStore, CheckoutValidator } from '../checkout';\nimport { LoadingIndicator } from '../common/loading-indicator';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { HostedFormFactory } from '../hosted-form';\nimport { OrderActionCreator, OrderRequestSender } from '../order';\nimport { RemoteCheckoutActionCreator, RemoteCheckoutRequestSender } from '../remote-checkout';\nimport { createSpamProtection, GoogleRecaptcha, PaymentHumanVerificationHandler, SpamProtectionActionCreator, SpamProtectionRequestSender } from '../spam-protection';\nimport { StoreCreditActionCreator, StoreCreditRequestSender } from '../store-credit';\nimport { SubscriptionsActionCreator, SubscriptionsRequestSender } from '../subscription';\n\nimport PaymentActionCreator from './payment-action-creator';\nimport PaymentMethodActionCreator from './payment-method-action-creator';\nimport PaymentMethodRequestSender from './payment-method-request-sender';\nimport PaymentRequestSender from './payment-request-sender';\nimport PaymentRequestTransformer from './payment-request-transformer';\nimport PaymentStrategyActionCreator from './payment-strategy-action-creator';\nimport PaymentStrategyRegistry from './payment-strategy-registry';\nimport PaymentStrategyType from './payment-strategy-type';\nimport StorefrontPaymentRequestSender from './storefront-payment-request-sender';\nimport { AdyenV2PaymentStrategy, AdyenV2ScriptLoader } from './strategies/adyenv2';\nimport { AffirmPaymentStrategy, AffirmScriptLoader } from './strategies/affirm';\nimport { AfterpayPaymentStrategy, AfterpayScriptLoader } from './strategies/afterpay';\nimport { AmazonPayPaymentStrategy, AmazonPayScriptLoader } from './strategies/amazon-pay';\nimport { createAmazonPayV2PaymentProcessor, AmazonPayV2PaymentStrategy } from './strategies/amazon-pay-v2';\nimport { BarclaysPaymentStrategy } from './strategies/barclays';\nimport { BlueSnapV2PaymentStrategy } from './strategies/bluesnapv2';\nimport { BoltPaymentStrategy, BoltScriptLoader } from './strategies/bolt';\nimport { createBraintreePaymentProcessor, createBraintreeVisaCheckoutPaymentProcessor, BraintreeCreditCardPaymentStrategy, BraintreePaypalPaymentStrategy, BraintreeScriptLoader, BraintreeSDKCreator, BraintreeVisaCheckoutPaymentStrategy, VisaCheckoutScriptLoader } from './strategies/braintree';\nimport { CardinalClient, CardinalScriptLoader, CardinalThreeDSecureFlow, CardinalThreeDSecureFlowV2 } from './strategies/cardinal';\nimport { ChasePayPaymentStrategy, ChasePayScriptLoader } from './strategies/chasepay';\nimport { CheckoutcomiDealPaymentStrategy, CheckoutcomAPMPaymentStrategy, CheckoutcomFawryPaymentStrategy, CheckoutcomSEPAPaymentStrategy } from './strategies/checkoutcom-custom';\nimport { ClearpayPaymentStrategy, ClearpayScriptLoader } from './strategies/clearpay';\nimport { ConvergePaymentStrategy } from './strategies/converge';\nimport { CreditCardPaymentStrategy } from './strategies/credit-card';\nimport { CreditCardRedirectPaymentStrategy } from './strategies/credit-card-redirect';\nimport { CyberSourcePaymentStrategy } from './strategies/cybersource/index';\nimport { CyberSourceV2PaymentStrategy } from './strategies/cybersourcev2';\nimport { DigitalRiverPaymentStrategy, DigitalRiverScriptLoader } from './strategies/digitalriver';\nimport { ExternalPaymentStrategy } from './strategies/external';\nimport { createGooglePayPaymentProcessor, GooglePayAdyenV2Initializer, GooglePayAdyenV2PaymentProcessor, GooglePayAuthorizeNetInitializer, GooglePayBraintreeInitializer, GooglePayCheckoutcomInitializer, GooglePayCybersourceV2Initializer, GooglePayOrbitalInitializer,  GooglePayPaymentStrategy, GooglePayStripeInitializer } from './strategies/googlepay';\nimport { KlarnaPaymentStrategy, KlarnaScriptLoader } from './strategies/klarna';\nimport { KlarnaV2PaymentStrategy, KlarnaV2ScriptLoader } from './strategies/klarnav2';\nimport { LegacyPaymentStrategy } from './strategies/legacy';\nimport { MasterpassPaymentStrategy, MasterpassScriptLoader } from './strategies/masterpass';\nimport { MolliePaymentStrategy, MollieScriptLoader } from './strategies/mollie';\nimport { MonerisPaymentStrategy } from './strategies/moneris';\nimport { NoPaymentDataRequiredPaymentStrategy } from './strategies/no-payment';\nimport { OfflinePaymentStrategy } from './strategies/offline';\nimport { OffsitePaymentStrategy } from './strategies/offsite';\nimport { PaypalExpressPaymentStrategy, PaypalProPaymentStrategy, PaypalScriptLoader } from './strategies/paypal';\nimport { createPaypalCommercePaymentProcessor,\n    PaypalCommerceCreditCardPaymentStrategy,\n    PaypalCommerceFundingKeyResolver,\n    PaypalCommerceHostedForm,\n    PaypalCommercePaymentStrategy,\n    PaypalCommerceRequestSender } from './strategies/paypal-commerce';\nimport { createPaymentProcessorRegistry, createStepHandler, PaymentResumer, PPSDKStrategy } from './strategies/ppsdk';\nimport { QuadpayPaymentStrategy } from './strategies/quadpay';\nimport { SagePayPaymentStrategy } from './strategies/sage-pay';\nimport { SquarePaymentStrategy, SquareScriptLoader } from './strategies/square';\nimport { StripeScriptLoader, StripeV3PaymentStrategy } from './strategies/stripev3';\nimport { WepayPaymentStrategy, WepayRiskClient } from './strategies/wepay';\nimport { ZipPaymentStrategy, ZipScriptLoader } from './strategies/zip';\n\nexport default function createPaymentStrategyRegistry(\n    store: CheckoutStore,\n    paymentClient: any,\n    requestSender: RequestSender,\n    spamProtection: GoogleRecaptcha,\n    locale: string\n) {\n    const registry = new PaymentStrategyRegistry(store, { defaultToken: PaymentStrategyType.CREDIT_CARD });\n    const scriptLoader = getScriptLoader();\n    const paymentRequestTransformer = new PaymentRequestTransformer();\n    const paymentRequestSender = new PaymentRequestSender(paymentClient);\n    const billingAddressActionCreator = new BillingAddressActionCreator(\n        new BillingAddressRequestSender(requestSender),\n        new SubscriptionsActionCreator(new SubscriptionsRequestSender(requestSender))\n    );\n    const braintreePaymentProcessor = createBraintreePaymentProcessor(scriptLoader);\n    const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n    const checkoutValidator = new CheckoutValidator(checkoutRequestSender);\n    const spamProtectionActionCreator = new SpamProtectionActionCreator(spamProtection, new SpamProtectionRequestSender(requestSender));\n    const orderActionCreator = new OrderActionCreator(new OrderRequestSender(requestSender), checkoutValidator);\n    const storeCreditActionCreator = new StoreCreditActionCreator(new StoreCreditRequestSender(requestSender));\n    const paymentHumanVerificationHandler = new PaymentHumanVerificationHandler(createSpamProtection(createScriptLoader()));\n    const paymentActionCreator = new PaymentActionCreator(paymentRequestSender, orderActionCreator, paymentRequestTransformer, paymentHumanVerificationHandler);\n    const paymentMethodActionCreator = new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender));\n    const remoteCheckoutActionCreator = new RemoteCheckoutActionCreator(new RemoteCheckoutRequestSender(requestSender));\n    const configActionCreator = new ConfigActionCreator(new ConfigRequestSender(requestSender));\n    const formFieldsActionCreator = new FormFieldsActionCreator(new FormFieldsRequestSender(requestSender));\n    const checkoutActionCreator = new CheckoutActionCreator(checkoutRequestSender, configActionCreator, formFieldsActionCreator);\n    const paymentStrategyActionCreator = new PaymentStrategyActionCreator(registry, orderActionCreator, spamProtectionActionCreator);\n    const formPoster = createFormPoster();\n    const hostedFormFactory = new HostedFormFactory(store);\n    const storefrontPaymentRequestSender = new StorefrontPaymentRequestSender(requestSender);\n    const stepHandler = createStepHandler(formPoster);\n\n    registry.register(PaymentStrategyType.ADYENV2, () =>\n        new AdyenV2PaymentStrategy(\n            store,\n            paymentActionCreator,\n            orderActionCreator,\n            new AdyenV2ScriptLoader(scriptLoader, getStylesheetLoader())\n        )\n    );\n\n    registry.register(PaymentStrategyType.ADYENV2_GOOGLEPAY, () =>\n        new GooglePayPaymentStrategy(\n            store,\n            checkoutActionCreator,\n            paymentMethodActionCreator,\n            paymentStrategyActionCreator,\n            paymentActionCreator,\n            orderActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayAdyenV2Initializer()\n            ),\n            new GooglePayAdyenV2PaymentProcessor(\n                store,\n                paymentActionCreator,\n                new AdyenV2ScriptLoader(scriptLoader, getStylesheetLoader())\n            )\n        )\n    );\n\n    registry.register(PaymentStrategyType.AFFIRM, () =>\n        new AffirmPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            paymentMethodActionCreator,\n            new AffirmScriptLoader()\n        )\n    );\n\n    registry.register(PaymentStrategyType.AFTERPAY, () =>\n        new AfterpayPaymentStrategy(\n            store,\n            checkoutValidator,\n            orderActionCreator,\n            paymentActionCreator,\n            paymentMethodActionCreator,\n            storeCreditActionCreator,\n            new AfterpayScriptLoader(scriptLoader)\n        )\n    );\n\n    registry.register(PaymentStrategyType.AMAZON, () =>\n        new AmazonPayPaymentStrategy(\n            store,\n            orderActionCreator,\n            billingAddressActionCreator,\n            remoteCheckoutActionCreator,\n            new AmazonPayScriptLoader(scriptLoader)\n        )\n    );\n\n    registry.register(PaymentStrategyType.AUTHORIZENET_GOOGLE_PAY, () =>\n        new GooglePayPaymentStrategy(\n            store,\n            checkoutActionCreator,\n            paymentMethodActionCreator,\n            paymentStrategyActionCreator,\n            paymentActionCreator,\n            orderActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayAuthorizeNetInitializer()\n            )\n        )\n    );\n\n    registry.register(PaymentStrategyType.AMAZONPAYV2, () =>\n        new AmazonPayV2PaymentStrategy(\n            store,\n            paymentStrategyActionCreator,\n            paymentMethodActionCreator,\n            orderActionCreator,\n            paymentActionCreator,\n            createAmazonPayV2PaymentProcessor()\n        )\n    );\n\n    registry.register(PaymentStrategyType.BARCLAYS, () =>\n        new BarclaysPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            hostedFormFactory,\n            new CardinalThreeDSecureFlowV2(\n                store,\n                paymentActionCreator,\n                new CardinalClient(new CardinalScriptLoader(scriptLoader))\n            )\n        )\n    );\n\n    registry.register(PaymentStrategyType.BLUESNAPV2, () =>\n        new BlueSnapV2PaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator\n        )\n    );\n\n    registry.register(PaymentStrategyType.CREDIT_CARD, () =>\n        new CreditCardPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            hostedFormFactory\n        )\n    );\n\n    registry.register(PaymentStrategyType.CHECKOUTCOM, () =>\n        new CreditCardRedirectPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            hostedFormFactory,\n            formPoster\n        )\n    );\n\n    registry.register(PaymentStrategyType.CLEARPAY, () =>\n        new ClearpayPaymentStrategy(\n            store,\n            checkoutValidator,\n            orderActionCreator,\n            paymentActionCreator,\n            paymentMethodActionCreator,\n            storeCreditActionCreator,\n            new ClearpayScriptLoader(scriptLoader)\n        )\n    );\n\n    registry.register(PaymentStrategyType.CYBERSOURCE, () =>\n        new CyberSourcePaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            hostedFormFactory,\n            new CardinalThreeDSecureFlow(\n                store,\n                paymentActionCreator,\n                paymentMethodActionCreator,\n                new CardinalClient(new CardinalScriptLoader(scriptLoader))\n            )\n        )\n    );\n\n    registry.register(PaymentStrategyType.CYBERSOURCEV2, () =>\n        new CyberSourceV2PaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            hostedFormFactory,\n            new CardinalThreeDSecureFlowV2(\n                store,\n                paymentActionCreator,\n                new CardinalClient(new CardinalScriptLoader(scriptLoader))\n            )\n        )\n    );\n\n    registry.register(PaymentStrategyType.DIGITALRIVER, () =>\n        new DigitalRiverPaymentStrategy(\n            store,\n            paymentMethodActionCreator,\n            orderActionCreator,\n            paymentActionCreator,\n            storeCreditActionCreator,\n            new DigitalRiverScriptLoader(scriptLoader, getStylesheetLoader())\n        )\n    );\n\n    registry.register(PaymentStrategyType.KLARNA, () =>\n        new KlarnaPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentMethodActionCreator,\n            remoteCheckoutActionCreator,\n            new KlarnaScriptLoader(scriptLoader)\n        )\n    );\n\n    registry.register(PaymentStrategyType.KLARNAV2, () =>\n        new KlarnaV2PaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentMethodActionCreator,\n            remoteCheckoutActionCreator,\n            new KlarnaV2ScriptLoader(scriptLoader)\n        )\n    );\n\n    registry.register(PaymentStrategyType.LEGACY, () =>\n        new LegacyPaymentStrategy(\n            store,\n            orderActionCreator\n        )\n    );\n\n    registry.register(PaymentStrategyType.OFFLINE, () =>\n        new OfflinePaymentStrategy(\n            store,\n            orderActionCreator\n        )\n    );\n\n    registry.register(PaymentStrategyType.OFFSITE, () =>\n        new OffsitePaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator\n        )\n    );\n\n    registry.register(PaymentStrategyType.PAYPAL, () =>\n        new PaypalProPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            hostedFormFactory,\n            new CardinalThreeDSecureFlow(\n                store,\n                paymentActionCreator,\n                paymentMethodActionCreator,\n                new CardinalClient(new CardinalScriptLoader(scriptLoader))\n            )\n        )\n    );\n\n    registry.register(PaymentStrategyType.PAYPAL_EXPRESS, () =>\n        new PaypalExpressPaymentStrategy(\n            store,\n            orderActionCreator,\n            new PaypalScriptLoader(scriptLoader)\n        )\n    );\n\n    registry.register(PaymentStrategyType.PAYPAL_EXPRESS_CREDIT, () =>\n        new PaypalExpressPaymentStrategy(\n            store,\n            orderActionCreator,\n            new PaypalScriptLoader(scriptLoader)\n        )\n    );\n\n    registry.register(PaymentStrategyType.PAYPAL_COMMERCE_CREDIT_CARD, () =>\n        new PaypalCommerceCreditCardPaymentStrategy(\n            store,\n            paymentMethodActionCreator,\n            new PaypalCommerceHostedForm(createPaypalCommercePaymentProcessor(scriptLoader, requestSender)),\n            orderActionCreator,\n            paymentActionCreator\n        )\n    );\n\n    registry.register(PaymentStrategyType.PAYPAL_COMMERCE, () =>\n        new PaypalCommercePaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            createPaypalCommercePaymentProcessor(scriptLoader, requestSender),\n            new PaypalCommerceFundingKeyResolver(),\n            new PaypalCommerceRequestSender(requestSender),\n            new LoadingIndicator({ styles: { backgroundColor: 'black' } })\n        )\n    );\n\n    registry.register(PaymentStrategyType.PAYPAL_COMMERCE_ALTERNATIVE_METHODS, () =>\n        new PaypalCommercePaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            createPaypalCommercePaymentProcessor(scriptLoader, requestSender),\n            new PaypalCommerceFundingKeyResolver(),\n            new PaypalCommerceRequestSender(requestSender),\n            new LoadingIndicator({ styles: { backgroundColor: 'black' } })\n        )\n    );\n\n    registry.register(PaymentStrategyType.PPSDK, () =>\n        new PPSDKStrategy(\n            store,\n            orderActionCreator,\n            createPaymentProcessorRegistry(requestSender, stepHandler),\n            new PaymentResumer(requestSender, stepHandler)\n        )\n    );\n\n    registry.register(PaymentStrategyType.QUADPAY, () =>\n        new QuadpayPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            paymentMethodActionCreator,\n            storeCreditActionCreator,\n            remoteCheckoutActionCreator,\n            storefrontPaymentRequestSender\n        )\n    );\n\n    registry.register(PaymentStrategyType.SAGE_PAY, () =>\n        new SagePayPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            hostedFormFactory,\n            formPoster\n        )\n    );\n\n    registry.register(PaymentStrategyType.SQUARE, () =>\n        new SquarePaymentStrategy(\n            store,\n            checkoutActionCreator,\n            orderActionCreator,\n            paymentActionCreator,\n            paymentMethodActionCreator,\n            paymentStrategyActionCreator,\n            requestSender,\n            new SquareScriptLoader(scriptLoader)\n        )\n    );\n\n    registry.register(PaymentStrategyType.NO_PAYMENT_DATA_REQUIRED, () =>\n        new NoPaymentDataRequiredPaymentStrategy(\n            store,\n            orderActionCreator\n        )\n    );\n\n    registry.register(PaymentStrategyType.BRAINTREE, () =>\n        new BraintreeCreditCardPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            paymentMethodActionCreator,\n            braintreePaymentProcessor\n        )\n    );\n\n    registry.register(PaymentStrategyType.BRAINTREE_PAYPAL, () =>\n        new BraintreePaypalPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            paymentMethodActionCreator,\n            braintreePaymentProcessor\n        )\n    );\n\n    registry.register(PaymentStrategyType.BRAINTREE_PAYPAL_CREDIT, () =>\n        new BraintreePaypalPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            paymentMethodActionCreator,\n            braintreePaymentProcessor,\n            true\n        )\n    );\n\n    registry.register(PaymentStrategyType.BRAINTREE_VISA_CHECKOUT, () =>\n        new BraintreeVisaCheckoutPaymentStrategy(\n            store,\n            checkoutActionCreator,\n            paymentMethodActionCreator,\n            paymentStrategyActionCreator,\n            paymentActionCreator,\n            orderActionCreator,\n            createBraintreeVisaCheckoutPaymentProcessor(scriptLoader, requestSender),\n            new VisaCheckoutScriptLoader(scriptLoader)\n        )\n    );\n\n    registry.register(PaymentStrategyType.CHASE_PAY, () =>\n        new ChasePayPaymentStrategy(\n            store,\n            checkoutActionCreator,\n            orderActionCreator,\n            paymentActionCreator,\n            paymentMethodActionCreator,\n            paymentStrategyActionCreator,\n            requestSender,\n            new ChasePayScriptLoader(scriptLoader),\n            new WepayRiskClient(scriptLoader)\n        )\n    );\n\n    registry.register(PaymentStrategyType.BRAINTREE_GOOGLE_PAY, () =>\n        new GooglePayPaymentStrategy(\n            store,\n            checkoutActionCreator,\n            paymentMethodActionCreator,\n            paymentStrategyActionCreator,\n            paymentActionCreator,\n            orderActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayBraintreeInitializer(\n                    new BraintreeSDKCreator(\n                        new BraintreeScriptLoader(scriptLoader)\n                    )\n                )\n            )\n        )\n    );\n\n    registry.register(PaymentStrategyType.WE_PAY, () =>\n        new WepayPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            hostedFormFactory,\n            new WepayRiskClient(scriptLoader)\n        )\n    );\n\n    registry.register(PaymentStrategyType.MASTERPASS, () =>\n        new MasterpassPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            new MasterpassScriptLoader(scriptLoader)\n        )\n    );\n\n    registry.register(PaymentStrategyType.STRIPE_GOOGLE_PAY, () =>\n        new GooglePayPaymentStrategy(\n            store,\n            checkoutActionCreator,\n            paymentMethodActionCreator,\n            paymentStrategyActionCreator,\n            paymentActionCreator,\n            orderActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayStripeInitializer()\n            )\n        )\n    );\n\n    registry.register(PaymentStrategyType.CYBERSOURCEV2_GOOGLE_PAY, () =>\n        new GooglePayPaymentStrategy(\n            store,\n            checkoutActionCreator,\n            paymentMethodActionCreator,\n            paymentStrategyActionCreator,\n            paymentActionCreator,\n            orderActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayCybersourceV2Initializer()\n            )\n        )\n    );\n\n    registry.register(PaymentStrategyType.ORBITAL_GOOGLE_PAY, () =>\n        new GooglePayPaymentStrategy(\n            store,\n            checkoutActionCreator,\n            paymentMethodActionCreator,\n            paymentStrategyActionCreator,\n            paymentActionCreator,\n            orderActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayOrbitalInitializer()\n            )\n        )\n    );\n\n    registry.register(PaymentStrategyType.CHECKOUTCOM_GOOGLE_PAY, () =>\n        new GooglePayPaymentStrategy(\n            store,\n            checkoutActionCreator,\n            paymentMethodActionCreator,\n            paymentStrategyActionCreator,\n            paymentActionCreator,\n            orderActionCreator,\n            createGooglePayPaymentProcessor(\n                store,\n                new GooglePayCheckoutcomInitializer(requestSender)\n            )\n        )\n    );\n\n    registry.register(PaymentStrategyType.ZIP, () =>\n        new ZipPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            paymentMethodActionCreator,\n            storeCreditActionCreator,\n            remoteCheckoutActionCreator,\n            new ZipScriptLoader(scriptLoader),\n            storefrontPaymentRequestSender\n        )\n    );\n\n    registry.register(PaymentStrategyType.CONVERGE, () =>\n        new ConvergePaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            hostedFormFactory,\n            formPoster\n        )\n    );\n\n    registry.register(PaymentStrategyType.LAYBUY, () =>\n        new ExternalPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            formPoster\n        )\n    );\n\n    registry.register(PaymentStrategyType.SEZZLE, () =>\n        new ExternalPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            formPoster\n        )\n    );\n\n    registry.register(PaymentStrategyType.STRIPEV3, () =>\n        new StripeV3PaymentStrategy(\n            store,\n            paymentMethodActionCreator,\n            paymentActionCreator,\n            orderActionCreator,\n            new StripeScriptLoader(scriptLoader),\n            storeCreditActionCreator,\n            locale\n        )\n    );\n\n    registry.register(PaymentStrategyType.BOLT, () =>\n        new BoltPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            paymentMethodActionCreator,\n            storeCreditActionCreator,\n            new BoltScriptLoader(scriptLoader)\n        )\n    );\n\n    registry.register(PaymentStrategyType.CHECKOUTCOM_APM, () =>\n        new CheckoutcomAPMPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            hostedFormFactory\n        )\n    );\n\n    registry.register(PaymentStrategyType.MOLLIE, () =>\n        new MolliePaymentStrategy(\n            hostedFormFactory,\n            store,\n            new MollieScriptLoader(scriptLoader),\n            orderActionCreator,\n            paymentActionCreator\n        )\n    );\n\n    registry.register(PaymentStrategyType.CHECKOUTCOM_SEPA, () =>\n        new CheckoutcomSEPAPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            hostedFormFactory\n        )\n    );\n\n    registry.register(PaymentStrategyType.CHECKOUTCOM_IDEAL, () =>\n        new CheckoutcomiDealPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            hostedFormFactory\n        )\n    );\n\n    registry.register(PaymentStrategyType.CHECKOUTCOM_FAWRY, () =>\n        new CheckoutcomFawryPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            hostedFormFactory\n        )\n    );\n\n    registry.register(PaymentStrategyType.MONERIS, () =>\n        new MonerisPaymentStrategy(\n            store,\n            orderActionCreator,\n            paymentActionCreator,\n            storeCreditActionCreator\n        )\n    );\n\n    return registry;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { Overlay } from '../../../common/overlay';\n\nimport BraintreeHostedForm from './braintree-hosted-form';\nimport BraintreePaymentProcessor from './braintree-payment-processor';\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\n\nexport default function createBraintreePaymentProcessor(scriptLoader: ScriptLoader) {\n    const braintreeScriptLoader = new BraintreeScriptLoader(scriptLoader);\n    const braintreeSDKCreator = new BraintreeSDKCreator(braintreeScriptLoader);\n    const braintreeHostedForm = new BraintreeHostedForm(braintreeSDKCreator);\n    const overlay = new Overlay();\n\n    return new BraintreePaymentProcessor(\n        braintreeSDKCreator,\n        braintreeHostedForm,\n        overlay\n    );\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { AmazonPayScriptLoader } from '../payment/strategies/amazon-pay';\nimport { createAmazonPayV2PaymentProcessor } from '../payment/strategies/amazon-pay-v2';\nimport { RemoteCheckoutActionCreator, RemoteCheckoutRequestSender } from '../remote-checkout';\n\nimport ConsignmentActionCreator from './consignment-action-creator';\nimport ConsignmentRequestSender from './consignment-request-sender';\nimport ShippingStrategyActionCreator from './shipping-strategy-action-creator';\nimport { ShippingStrategy } from './strategies';\nimport { AmazonPayShippingStrategy } from './strategies/amazon';\nimport { AmazonPayV2ShippingStrategy } from './strategies/amazon-pay-v2';\nimport { DefaultShippingStrategy } from './strategies/default';\n\nexport default function createShippingStrategyRegistry(\n    store: CheckoutStore,\n    requestSender: RequestSender\n): Registry<ShippingStrategy> {\n    const registry = new Registry<ShippingStrategy>();\n    const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n    const consignmentRequestSender = new ConsignmentRequestSender(requestSender);\n    const consignmentActionCreator = new ConsignmentActionCreator(consignmentRequestSender, checkoutRequestSender);\n\n    registry.register('amazon', () =>\n        new AmazonPayShippingStrategy(\n            store,\n            consignmentActionCreator,\n            new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender)),\n            new RemoteCheckoutActionCreator(new RemoteCheckoutRequestSender(requestSender)),\n            new AmazonPayScriptLoader(getScriptLoader())\n        )\n    );\n\n    registry.register('amazonpay', () =>\n        new AmazonPayV2ShippingStrategy(\n            store,\n            consignmentActionCreator,\n            new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender)),\n            createAmazonPayV2PaymentProcessor(),\n            new ShippingStrategyActionCreator(registry)\n        )\n    );\n\n    registry.register('default', () =>\n        new DefaultShippingStrategy(\n            store,\n            consignmentActionCreator\n        )\n    );\n\n    return registry;\n}\n","import { isObject, union } from 'lodash';\nimport MessageFormat from 'messageformat';\n\nimport { Logger } from '../common/log';\nimport { bindDecorator as bind } from '../common/utility';\n\nimport LanguageConfig, { Locales, Translations } from './language-config';\n\nconst DEFAULT_LOCALE = 'en';\nconst KEY_PREFIX = 'optimized_checkout';\n\n/**\n * Responsible for getting language strings.\n *\n * This object can be used to retrieve language strings that are most\n * appropriate for a given locale.\n *\n * The language strings provided to the object should follow [ICU\n * MessageFormat](http://userguide.icu-project.org/formatparse/messages) syntax.\n */\n@bind\nexport default class LanguageService {\n    private _locale: string;\n    private _locales: Locales;\n    private _translations: Translations;\n    private _formatters: { [key: string]: any };\n\n    /**\n     * @internal\n     */\n    constructor(\n        config: Partial<LanguageConfig>,\n        private _logger: Logger\n    ) {\n        const { locale, locales, translations } = this._transformConfig(config);\n\n        this._locale = locale;\n        this._locales = locales;\n        this._translations = translations;\n        this._formatters = {};\n    }\n\n    /**\n     * Remaps a set of language strings with a different set of keys.\n     *\n     * ```js\n     * service.mapKeys({\n     *     'new_key': 'existing_key',\n     * });\n     *\n     * console.log(service.translate('new_key'));\n     * ```\n     *\n     * @param maps - The set of language strings.\n     */\n    mapKeys(maps: { [key: string]: string }): void {\n        Object.keys(maps).forEach(key => {\n            const translationKey = `${KEY_PREFIX}.${maps[key]}`;\n\n            this._translations[`${KEY_PREFIX}.${key}`] = this._translations[translationKey];\n        });\n    }\n\n    /**\n     * Gets the preferred locale of the current customer.\n     *\n     * @returns The preferred locale code.\n     */\n    getLocale(): string {\n        return this._hasTranslations() ? this._locale : DEFAULT_LOCALE;\n    }\n\n    /**\n     * Gets a language string by a key.\n     *\n     * ```js\n     * service.translate('language_key');\n     * ```\n     *\n     * If the language string contains a placeholder, you can replace it by\n     * providing a second argument.\n     *\n     * ```js\n     * service.translate('language_key', { placeholder: 'Hello' });\n     * ```\n     *\n     * @param key - The language key.\n     * @param data - Data for replacing placeholders in the language string.\n     * @returns The translated language string.\n     */\n    translate(key: string, data: TranslationData = {}): string {\n        const prefixedKey = `${KEY_PREFIX}.${key}`;\n\n        if (typeof this._translations[prefixedKey] !== 'string') {\n            this._logger.warn(`Translation key \"${prefixedKey}\" is missing`);\n\n            return prefixedKey;\n        }\n\n        if (!this._formatters[prefixedKey]) {\n            const messageFormat = new MessageFormat(this._locales[prefixedKey]);\n\n            this._formatters[prefixedKey] = messageFormat.compile(this._translations[prefixedKey] || '');\n        }\n\n        return this._formatters[prefixedKey](this._transformData(data));\n    }\n\n    private _transformConfig(config: Partial<LanguageConfig> = {}): LanguageConfig {\n        const output: LanguageConfig = {\n            defaultTranslations: {},\n            translations: {},\n            locales: {},\n            locale: config.locale || DEFAULT_LOCALE,\n        };\n\n        const locales = config.locales || {};\n        const translations = this._flattenObject(config.translations || {});\n        const defaultTranslations = this._flattenObject(config.defaultTranslations || {});\n        const fallbackTranslations = this._flattenObject(config.fallbackTranslations || {});\n        const translationKeys = union(\n            Object.keys(fallbackTranslations),\n            Object.keys(defaultTranslations),\n            Object.keys(translations)\n        );\n\n        translationKeys.forEach(key => {\n            if (translations && translations[key]) {\n                output.translations[key] = translations[key];\n                output.locales[key] = locales[key] || output.locale;\n            } else if (defaultTranslations[key]) {\n                output.translations[key] = defaultTranslations[key];\n                output.locales[key] = config.defaultLocale ?? DEFAULT_LOCALE;\n            } else {\n                output.translations[key] = fallbackTranslations[key];\n                output.locales[key] = config.fallbackLocale ?? DEFAULT_LOCALE;\n            }\n        });\n\n        return output;\n    }\n\n    private _flattenObject(object: Translations, result: Translations = {}, parentKey: string = ''): Translations {\n        try {\n            Object.keys(object).forEach(key => {\n                const value = object[key];\n                const resultKey = parentKey ? `${parentKey}.${key}` : key;\n\n                if (isObject(value)) {\n                    return this._flattenObject(value, result, resultKey);\n                }\n\n                result[resultKey] = value;\n            });\n        } catch (err) {\n            this._logger.warn(`Unable to parse object: ${err}`);\n        }\n\n        return result;\n    }\n\n    private _transformData(data: TranslationData): TranslationData {\n        return Object.keys(data).reduce((result, key) => {\n            const value = data[key];\n\n            result[key] = value === null || value === undefined ? '' : value;\n\n            return result;\n        }, {} as TranslationData);\n    }\n\n    private _hasTranslations(): boolean {\n        return Object.keys(this._locales).map(key => this._locales[key])\n            .filter(code => code.split('-')[0] === this._locale.split('-')[0])\n            .length > 0;\n    }\n}\n\nexport interface TranslationData {\n    [key: string]: string | number;\n}\n","import { getDefaultLogger } from '../common/log';\n\nimport LanguageConfig from './language-config';\nimport LanguageService from './language-service';\n\n/**\n * Creates an instance of `LanguageService`.\n *\n * @remarks\n * ```js\n * const language = {{{langJson 'optimized_checkout'}}}; // `langJson` is a Handlebars helper provided by BigCommerce's Stencil template engine.\n * const service = createLanguageService(language);\n *\n * console.log(service.translate('address.city_label'));\n * ```\n *\n * @param config - A configuration object.\n * @returns An instance of `LanguageService`.\n */\nexport default function createLanguageService(config: Partial<LanguageConfig> = {}): LanguageService {\n    return new LanguageService(\n        config,\n        getDefaultLogger()\n    );\n}\n","import { InvalidArgumentError } from '../common/error/errors';\n\nimport { CurrencyConfig } from './currency';\n\nexport default class CurrencyFormatter {\n    private _decimalPlaces: number;\n    private _symbolLocation: string;\n    private _symbol: string;\n    private _thousandsSeparator: string;\n    private _decimalSeparator: string;\n\n    constructor(\n        currencySettings: CurrencyConfig\n    ) {\n        if (!currencySettings) {\n            throw new Error('Currency settings missing');\n        }\n\n        const {\n            decimalPlaces,\n            symbolLocation,\n            symbol,\n            thousandsSeparator,\n            decimalSeparator,\n        } = currencySettings;\n\n        if (\n            typeof symbolLocation !== 'string' ||\n            typeof symbol !== 'string' ||\n            typeof thousandsSeparator !== 'string' ||\n            typeof decimalSeparator !== 'string' ||\n            typeof decimalPlaces !== 'string'\n        ) {\n            throw new InvalidArgumentError('Invalid currency settings provided');\n        }\n\n        this._decimalPlaces = parseInt(decimalPlaces, 10);\n        this._symbolLocation = symbolLocation;\n        this._symbol = symbol;\n        this._thousandsSeparator = thousandsSeparator;\n        this._decimalSeparator = decimalSeparator;\n    }\n\n    format(amount?: number): string {\n        if (typeof amount !== 'number') {\n            throw new InvalidArgumentError('Invalid amount provided');\n        }\n\n        const formattedNumber = this._formatNumber(amount);\n\n        const formattedCurrency = this._formatCurrency(formattedNumber);\n\n        return amount < 0 ?\n            `-${formattedCurrency}` :\n            formattedCurrency;\n    }\n\n    private _formatNumber(amount: number): string {\n        const positiveAmount = Math.abs(amount);\n        const [ integerAmount, decimalAmount = '' ] = (this._toFixed(positiveAmount, this._decimalPlaces)).split('.');\n        const parsedIntegerAmount = integerAmount.replace(/\\B(?=(\\d{3})+(?!\\d))/g, this._thousandsSeparator);\n\n        if (this._decimalPlaces < 1) {\n            return parsedIntegerAmount;\n        }\n\n        return [\n            parsedIntegerAmount,\n            decimalAmount,\n        ].join(this._decimalSeparator);\n    }\n\n    private _formatCurrency(formattedNumber: string): string {\n        return (this._symbolLocation.toLowerCase() === 'left') ?\n            `${this._symbol}${formattedNumber}` :\n            `${formattedNumber}${this._symbol}`;\n    }\n\n    private _toFixed(value: number, precision: number): string {\n        return (+(Math.round(+(value + 'e' + precision)) + 'e' + -precision)).toFixed(precision);\n    }\n}\n","import { bindDecorator as bind } from '../common/utility';\nimport { StoreConfig } from '../config';\n\nimport CurrencyFormatter from './currency-formatter';\n\n/**\n * Responsible for formatting and converting currencies.\n */\n@bind\nexport default class CurrencyService {\n    private _customerFormatter: CurrencyFormatter;\n    private _storeFormatter: CurrencyFormatter;\n\n    /**\n     * @internal\n     */\n    constructor(\n        private _storeConfig: StoreConfig\n    ) {\n        this._customerFormatter = new CurrencyFormatter(this._storeConfig.shopperCurrency);\n        this._storeFormatter = new CurrencyFormatter(this._storeConfig.currency);\n    }\n\n    toCustomerCurrency(amount: number): string {\n        const exchangeRate = this._storeConfig.shopperCurrency.exchangeRate;\n\n        return this._customerFormatter.format(amount * exchangeRate);\n    }\n\n    toStoreCurrency(amount: number): string {\n        return this._storeFormatter.format(amount);\n    }\n}\n","import { StoreConfig } from '../config';\n\nimport CurrencyService from './currency-service';\n\n/**\n * Creates an instance of `CurrencyService`.\n *\n * @remarks\n * ```js\n * const { data } = checkoutService.getState();\n * const config = data.getConfig();\n * const checkout = data.getCheckout();\n * const currencyService = createCurrencyService(config);\n *\n * currencyService.toStoreCurrency(checkout.grandTotal);\n * currencyService.toCustomerCurrency(checkout.grandTotal);\n * ```\n *\n * @param config - The config object containing the currency configuration\n * @returns an instance of `CurrencyService`.\n */\nexport default function createCurrencyService(\n    config: StoreConfig\n): CurrencyService {\n    return new CurrencyService(config);\n}\n","import { keys } from 'lodash';\n\nimport { LineItemMap } from '../cart';\nimport { Checkout, CheckoutService } from '../checkout';\nimport { InvalidArgumentError } from '../common/error/errors';\nimport { ShopperCurrency, StoreProfile } from '../config';\nimport { Coupon } from '../coupon';\nimport { Order } from '../order';\nimport { ShippingOption } from '../shipping';\n\nimport { AnalyticsTracker } from './analytics-tracker-window';\nimport StepTracker from './step-tracker';\n\nexport interface StepTrackerConfig {\n    checkoutSteps?: AnalyticStepType[];\n}\n\nexport type AnalyticStepType = 'customer' | 'shipping' | 'billing' | 'payment';\n\nconst ORDER_ITEMS_STORAGE_KEY = 'ORDER_ITEMS';\n\nexport enum AnalyticStepId {\n    CUSTOMER = 1,\n    SHIPPING,\n    BILLING,\n    PAYMENT,\n}\n\nconst ANALYTIC_STEPS: { [key: string]: AnalyticStepId } = {\n    customer: AnalyticStepId.CUSTOMER,\n    shipping: AnalyticStepId.SHIPPING,\n    billing: AnalyticStepId.BILLING,\n    payment: AnalyticStepId.PAYMENT,\n};\n\nexport default class AnalyticsStepTracker implements StepTracker {\n    private _checkoutStarted: boolean = false;\n    private _completedSteps: { [key: string]: boolean } = {};\n    private _viewedSteps: { [key in AnalyticStepId]?: boolean; } = {};\n    private _analyticStepOrder: AnalyticStepType[] = [\n        'customer',\n        'shipping',\n        'billing',\n        'payment',\n    ];\n\n    constructor(\n        private checkoutService: CheckoutService,\n        private storage: StorageFallback,\n        private analytics: AnalyticsTracker,\n        { checkoutSteps }: StepTrackerConfig = {}\n    ) {\n        if (checkoutSteps !== undefined) {\n            if (checkoutSteps.some(value => !(value in ANALYTIC_STEPS))) {\n                throw new InvalidArgumentError(\n                    `Invalid checkout steps provided. Valid values are: ${keys(ANALYTIC_STEPS).join(', ')}.`\n                );\n            }\n            this._analyticStepOrder = checkoutSteps;\n\n        }\n    }\n\n    trackCheckoutStarted(): void {\n        if (this._checkoutStarted) {\n            return;\n        }\n\n        const checkout = this.getCheckout();\n\n        if (!checkout) {\n            return;\n        }\n\n        const {\n            coupons,\n            grandTotal,\n            shippingCostTotal,\n            taxTotal,\n            cart: {\n                lineItems,\n                discountAmount,\n                id,\n            },\n        } = checkout;\n\n        const extraItemsData = this.saveExtraItemsData(id, lineItems);\n\n        this.analytics.track('Checkout Started', this.getTrackingPayload({\n            revenue: grandTotal,\n            shipping: shippingCostTotal,\n            tax: taxTotal,\n            discount: discountAmount,\n            coupons,\n            lineItems,\n            extraItemsData,\n        }));\n\n        this._checkoutStarted = true;\n    }\n\n    trackOrderComplete(): void {\n        const order = this.getOrder();\n\n        if (!order) {\n            return;\n        }\n\n        const {\n            isComplete,\n            orderId,\n            orderAmount,\n            shippingCostTotal,\n            taxTotal,\n            discountAmount,\n            coupons,\n            lineItems,\n            cartId,\n        } = order;\n\n        if (!isComplete) {\n            return;\n        }\n\n        const extraItemsData = this.readExtraItemsData(cartId);\n\n        if (extraItemsData === null) {\n            return;\n        }\n\n        const isEcommerceGAEnabled = this.checkoutService.getState().data\n            .getConfig()?.checkoutSettings.features['DATA-6891.missing_orders_within_GA'];\n\n        const payload = this.getTrackingPayload({\n            orderId,\n            revenue: orderAmount,\n            shipping: shippingCostTotal,\n            tax: taxTotal,\n            discount: discountAmount,\n            coupons,\n            extraItemsData,\n            lineItems,\n        });\n\n        if (isEcommerceGAEnabled && this.analytics.hasPayloadLimit(payload)) {\n            this.analytics.hit('transaction', {\n                '&ti': payload.orderId,\n                '&ta': payload.affiliation,\n                '&tr': payload.revenue,\n                '&ts': payload.shipping,\n                '&tt': payload.tax,\n                '&tcc': payload.coupon,\n                '&cu': payload.currency,\n            });\n\n            payload.products.map(product => {\n                this.analytics.hit('item', {\n                    '&ti': payload.orderId,\n                    '&in': product.name,\n                    '&ic': product.sku,\n                    '&iv': `${product.category}`,\n                    '&ip': product.price,\n                    '&iq': product.quantity,\n                });\n            });\n\n            return this.clearExtraItemData(cartId);\n        }\n\n        this.analytics.track('Order Completed', payload);\n\n        this.clearExtraItemData(cartId);\n    }\n\n    trackStepViewed(step: AnalyticStepType): void {\n        const stepId = this.getIdFromStep(step);\n\n        if (!stepId || this.hasStepViewed(stepId)) {\n            return;\n        }\n\n        this.trackViewed(stepId);\n        this.backfill(stepId);\n    }\n\n    trackStepCompleted(step: AnalyticStepType): void {\n        const stepId = this.getIdFromStep(step);\n\n        if (!stepId || this.hasStepCompleted(stepId)) {\n            return;\n        }\n\n        this.backfill(stepId);\n        this.trackCompleted(stepId);\n    }\n\n    private backfill(stepId: AnalyticStepId): void {\n        for (const i of this._analyticStepOrder) {\n            const id = this.getIdFromStep(i);\n\n            if (!id) {\n                break;\n            }\n\n            if (!this.hasStepViewed(id)) {\n                this.trackViewed(id);\n            }\n\n            if (id === stepId) {\n                break;\n            }\n\n            if (!this.hasStepCompleted(id)) {\n                this.trackCompleted(id);\n            }\n        }\n    }\n\n    private trackCompleted(stepId: AnalyticStepId): void {\n        const shippingMethod = this.getSelectedShippingOption();\n        const { code: currency = '' } = this.getShopperCurrency() || {};\n        const paymentMethod = this.getPaymentMethodName();\n\n        const payload: {\n            step: number;\n            currency: string;\n            shippingMethod?: string;\n            paymentMethod?: string;\n        } = {\n            step: stepId,\n            currency,\n        };\n\n        if (shippingMethod) {\n            payload.shippingMethod = shippingMethod.description;\n        }\n\n        if (paymentMethod) {\n            payload.paymentMethod = paymentMethod;\n        }\n\n        // due to an issue with the way the segment library works, we must send at least one of the two\n        // options--otherwise it rejects the track call with no diagnostic messages. however, if we blindly\n        // include both options, it sends a single comma for the value, which is undesireable. by only adding\n        // one of the two (shippingMethod here being arbitrarily chosen), we always have at least one value, but\n        // never send two empty values.\n        if (!payload.shippingMethod && !payload.paymentMethod) {\n            payload.shippingMethod = ' ';\n        }\n\n        this.analytics.track('Checkout Step Completed', payload);\n\n        const shippingMethodId = shippingMethod ? shippingMethod.id : '';\n        const completedStepId = stepId === AnalyticStepId.SHIPPING ?\n            `${stepId}-${shippingMethodId}` :\n            stepId;\n\n        this._completedSteps[completedStepId] = true;\n    }\n\n    private getTrackingPayload({\n        orderId,\n        revenue,\n        shipping,\n        tax,\n        discount,\n        coupons,\n        extraItemsData,\n        lineItems,\n    }: {\n        orderId?: number;\n        revenue: number;\n        shipping: number;\n        tax: number;\n        discount: number;\n        coupons: Coupon[];\n        extraItemsData: ExtraItemsData;\n        lineItems: LineItemMap;\n    }) {\n        const { code = '' } = this.getShopperCurrency() || {};\n        const { storeName = '' } = this.getStoreProfile() || {};\n\n        return {\n            orderId,\n            affiliation: storeName,\n            revenue: this.toShopperCurrency(revenue),\n            shipping: this.toShopperCurrency(shipping),\n            tax: this.toShopperCurrency(tax),\n            discount: this.toShopperCurrency(discount),\n            coupon: (coupons || []).map(coupon => coupon.code.toUpperCase()).join(','),\n            currency: code,\n            products: this.getProducts(extraItemsData, lineItems),\n        };\n    }\n\n    private hasStepCompleted(stepId: AnalyticStepId): boolean {\n        const shippingOption = this.getSelectedShippingOption();\n        const shippingMethodId = shippingOption ? shippingOption.id : '';\n\n        return this._completedSteps.hasOwnProperty(stepId) ||\n            (\n                stepId === AnalyticStepId.SHIPPING &&\n                this._completedSteps.hasOwnProperty(`${stepId}-${shippingMethodId}`)\n            );\n    }\n\n    private hasStepViewed(stepId: AnalyticStepId): boolean {\n        return !!this._viewedSteps[stepId];\n    }\n\n    private getIdFromStep(step: string): AnalyticStepId | null {\n        const name = step.split('.');\n\n        return ANALYTIC_STEPS[name[0]] || null;\n    }\n\n    private trackViewed(stepId: AnalyticStepId): void {\n        const currency = this.getShopperCurrency();\n\n        this.analytics.track('Checkout Step Viewed', {\n            step: stepId,\n            currency: currency ? currency.code : '',\n        });\n\n        this._viewedSteps[stepId] = true;\n    }\n\n    private getOrder(): Order | undefined {\n        const { data: { getOrder } } = this.checkoutService.getState();\n\n        return getOrder();\n    }\n\n    private getCheckout(): Checkout | undefined {\n        const { data: { getCheckout } } = this.checkoutService.getState();\n\n        return getCheckout();\n    }\n\n    private getShopperCurrency(): ShopperCurrency | undefined {\n        const { data: { getConfig } } = this.checkoutService.getState();\n        const config = getConfig();\n\n        return config && config.shopperCurrency;\n    }\n\n    private getStoreProfile(): StoreProfile | undefined {\n        const { data: { getConfig } } = this.checkoutService.getState();\n        const config = getConfig();\n\n        return config && config.storeProfile;\n    }\n\n    private toShopperCurrency(amount: number): number {\n        const { exchangeRate = 1 } = this.getShopperCurrency() || {};\n\n        return Math.round(amount * exchangeRate * 100) / 100;\n    }\n\n    private saveExtraItemsData(id: string, lineItems: LineItemMap): ExtraItemsData {\n        const data = [\n            ...lineItems.physicalItems,\n            ...lineItems.digitalItems,\n        ].reduce((result, item) => {\n            result[item.productId] = {\n                brand: item.brand ? item.brand : '',\n                category: item.categoryNames ? item.categoryNames.join(', ') : '',\n            };\n\n            return result;\n        }, {} as ExtraItemsData);\n\n        try {\n            this.storage.setItem(this.getStorageKey(id), JSON.stringify(data));\n\n            return data;\n        } catch (err) {\n            return {};\n        }\n    }\n\n    private getStorageKey(id: string): string {\n        return id ? `${ORDER_ITEMS_STORAGE_KEY}_${id}` : '';\n    }\n\n    private readExtraItemsData(id: string): ExtraItemsData | null {\n        try {\n            const item = this.storage.getItem(this.getStorageKey(id));\n\n            return item ? JSON.parse(item) : null;\n        } catch (err) {\n            return null;\n        }\n    }\n\n    private clearExtraItemData(id: string): void {\n        try {\n            this.storage.removeItem(this.getStorageKey(id));\n        } catch (err) {\n            // silently ignore the failure\n        }\n    }\n\n    private getSelectedShippingOption(): ShippingOption | null {\n        const { data } = this.checkoutService.getState();\n        const shippingOption = data.getSelectedShippingOption();\n\n        return (shippingOption && shippingOption.id && shippingOption.description) ?\n            shippingOption :\n            null;\n    }\n\n    private getPaymentMethodName(): string {\n        const { data } = this.checkoutService.getState();\n        const paymentMethod = data.getSelectedPaymentMethod();\n\n        return (paymentMethod && paymentMethod.config) ?\n            paymentMethod.config.displayName || '' :\n            '';\n    }\n\n    private getProducts(itemsData: ExtraItemsData, lineItems: LineItemMap): AnalyticsProduct[] {\n        const customItems: AnalyticsProduct[] = (lineItems.customItems || []).map(item => ({\n            product_id: item.id,\n            sku: item.sku,\n            price: item.listPrice,\n            quantity: item.quantity,\n            name: item.name,\n        }));\n\n        const giftCertificateItems: AnalyticsProduct[] = lineItems.giftCertificates.map(item => {\n            return {\n                product_id: item.id,\n                price: this.toShopperCurrency(item.amount),\n                name: item.name,\n                quantity: 1,\n            };\n        });\n\n        const physicalAndDigitalItems: AnalyticsProduct[] = [\n            ...lineItems.physicalItems,\n            ...lineItems.digitalItems,\n        ].map(item => {\n            let itemAttributes;\n\n            if (item.options && item.options.length) {\n                itemAttributes = item.options.map(option => `${option.name}:${option.value}`);\n                itemAttributes.sort();\n            }\n\n            return {\n                product_id: item.productId,\n                sku: item.sku,\n                price: item.salePrice,\n                image_url: item.imageUrl,\n                name: item.name,\n                quantity: item.quantity,\n                brand: itemsData[item.productId] ? itemsData[item.productId].brand : '',\n                category: itemsData[item.productId] ? itemsData[item.productId].category : '',\n                variant: (itemAttributes || []).join(', '),\n            };\n        });\n\n        return [\n            ...customItems,\n            ...physicalAndDigitalItems,\n            ...giftCertificateItems,\n        ];\n    }\n}\n\nexport interface AnalyticsProduct {\n    product_id: string | number;\n    price: number;\n    quantity: number;\n    name: string;\n    sku?: string;\n    image_url?: string;\n    category?: string;\n    variant?: string;\n    brand?: string;\n}\n\nexport interface ExtraItemsData {\n    [productId: string]: {\n        brand: string;\n        category: string;\n    };\n}\n","import StepTracker from './step-tracker';\n\nexport default class NoopStepTracker implements StepTracker {\n    trackCheckoutStarted(): void {\n        return;\n    }\n\n    trackOrderComplete(): void {\n        return;\n    }\n\n    trackStepViewed(): void {\n        return;\n    }\n\n    trackStepCompleted(): void {\n        return;\n    }\n}\n","import localStorageFallback from 'local-storage-fallback';\n\nimport { CheckoutService } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\n\nimport AnalyticsStepTracker, { StepTrackerConfig } from './analytics-step-tracker';\nimport { isAnalyticsTrackerWindow } from './is-analytics-step-tracker-window';\nimport NoopStepTracker from './noop-step-tracker';\nimport StepTracker from './step-tracker';\n\n/**\n * Creates an instance of `StepTracker`.\n *\n * @remarks\n * ```js\n * const checkoutService = createCheckoutService();\n * await checkoutService.loadCheckout();\n * const stepTracker = createStepTracker(checkoutService);\n *\n * stepTracker.trackCheckoutStarted();\n * ```\n *\n * @param CheckoutService - An instance of CheckoutService\n * @param StepTrackerConfig - A step tracker config object\n * @returns an instance of `StepTracker`.\n */\nexport default function createStepTracker(\n    checkoutService: CheckoutService,\n    stepTrackerConfig?: StepTrackerConfig\n): StepTracker {\n    const { data } = checkoutService.getState();\n    const config = data.getConfig();\n\n    if (!config) {\n        throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n    }\n\n    const { isAnalyticsEnabled } = config.checkoutSettings;\n\n    if (isAnalyticsEnabled && isAnalyticsTrackerWindow(window)) {\n        return new AnalyticsStepTracker(\n            checkoutService,\n            localStorageFallback,\n            window.analytics,\n            stepTrackerConfig\n        );\n    }\n\n    return new NoopStepTracker();\n}\n","import AnalyticsTrackerWindow from './analytics-tracker-window';\n\nexport function isAnalyticsTrackerWindow(window: Window): window is AnalyticsTrackerWindow {\n    return Boolean((window as AnalyticsTrackerWindow).analytics);\n}\n","export { createTimeout } from '@bigcommerce/request-sender';\n\nexport { createCheckoutService } from '../checkout';\nexport { createCheckoutButtonInitializer } from '../checkout-buttons';\nexport { embedCheckout } from '../embedded-checkout';\nexport { createEmbeddedCheckoutMessenger } from '../embedded-checkout/iframe-content';\nexport { createLanguageService } from '../locale';\nexport { createCurrencyService } from '../currency';\nexport { createStepTracker } from '../analytics';\n","\nexport interface ApproveDataOptions {\n    orderID?: string;\n}\n\nexport interface ClickDataOptions {\n    fundingSource: string;\n}\n\nexport interface ClickActions {\n    reject(): Promise<void>;\n    resolve(): Promise<void>;\n}\n\nexport interface OrderData {\n    orderId: string;\n    approveUrl: string;\n}\n\nexport interface OrderStatus {\n    status: 'APPROVED' | 'CREATED' | string;\n}\n\nexport enum StyleButtonLabel {\n    paypal = 'paypal',\n    checkout = 'checkout',\n    buynow = 'buynow',\n    pay = 'pay',\n    installment = 'installment',\n}\n\nexport enum StyleButtonLayout {\n    vertical = 'vertical',\n    horizontal = 'horizontal',\n}\n\nexport enum StyleButtonColor {\n    gold = 'gold',\n    blue = 'blue',\n    silver = 'silver',\n    black = 'black',\n    white = 'white',\n}\n\nexport enum StyleButtonShape {\n    pill = 'pill',\n    rect = 'rect' ,\n}\n\nexport interface PaypalButtonStyleOptions {\n    layout?: StyleButtonLayout;\n    color?: StyleButtonColor;\n    shape?: StyleButtonShape;\n    height?: 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55;\n    label?: StyleButtonLabel;\n    tagline?: boolean;\n}\n\nexport interface ButtonsOptions {\n    style?: PaypalButtonStyleOptions;\n    fundingSource?: string;\n    createOrder?(): Promise<string>;\n    onApprove?(data: ApproveDataOptions): void;\n    onClick?(data: ClickDataOptions, actions: ClickActions): void;\n    onCancel?(): void;\n    onError?(error: Error): void;\n}\n\nexport interface PaypalFieldsStyleOptions {\n    base?: {\n        backgroundColor?: string;\n        color?: string;\n        fontSize?: string;\n        fontFamily?: string;\n        lineHeight?: string;\n        letterSpacing?: string;\n    };\n    input?: {\n        backgroundColor?: string;\n        fontSize?: string;\n        color?: string;\n        borderColor?: string;\n        borderRadius?: string;\n        borderWidth?: string;\n        padding?: string;\n    };\n    invalid?: {\n        color?: string;\n    };\n    active?: {\n        color?: string;\n    };\n}\n\nexport interface FieldsOptions {\n    style?: PaypalFieldsStyleOptions;\n    fundingSource: string;\n    fields: { name?: { value?: string }; email?: { value?: string } };\n}\n\nexport interface MessagesOptions {\n    amount: number;\n    placement: string;\n    style?: MessagesStyleOptions;\n    fundingSource?: string;\n}\n\nexport interface MessagesStyleOptions {\n    layout?: string;\n}\n\nexport interface PaypalCommerceHostedFieldOption {\n    selector: string;\n    placeholder?: string;\n}\n\nexport interface PaypalCommerceHostedFieldsRenderOptions {\n    fields?: {\n        number?: PaypalCommerceHostedFieldOption;\n        cvv?: PaypalCommerceHostedFieldOption;\n        expirationDate?: PaypalCommerceHostedFieldOption;\n    };\n    paymentsSDK?: boolean;\n    styles?: {\n        input?: { [key: string]: string };\n        '.invalid'?: { [key: string]: string };\n        '.valid'?: { [key: string]: string };\n        ':focus'?: { [key: string]: string };\n    };\n    createOrder(): Promise<string>;\n}\n\nexport interface PaypalCommerceHostedFieldsSubmitOptions {\n    contingencies?: Array<'3D_SECURE'>;\n    cardholderName?: string;\n}\n\nexport interface PaypalCommerceHostedFieldsApprove {\n    orderId: string;\n    liabilityShift: 'POSSIBLE' | 'NO' | 'UNKNOWN';\n}\n\nexport interface PaypalCommerceHostedFields {\n    submit(options?: PaypalCommerceHostedFieldsSubmitOptions): PaypalCommerceHostedFieldsApprove;\n    getState(): PaypalCommerceHostedFieldsState;\n    on(eventName: string, callback: (event: PaypalCommerceHostedFieldsState) => void): void;\n}\n\nexport interface PaypalCommerceHostedFieldsState {\n    cards: PaypalCommerceHostedFieldsCard[];\n    emittedBy: string;\n    fields: {\n        number?: PaypalCommerceHostedFieldsFieldData;\n        expirationDate?: PaypalCommerceHostedFieldsFieldData;\n        expirationMonth?: PaypalCommerceHostedFieldsFieldData;\n        expirationYear?: PaypalCommerceHostedFieldsFieldData;\n        cvv?: PaypalCommerceHostedFieldsFieldData;\n        postalCode?: PaypalCommerceHostedFieldsFieldData;\n    };\n}\n\nexport interface PaypalCommerceHostedFieldsCard {\n    type: string;\n    niceType: string;\n    code: { name: string; size: number };\n}\n\nexport interface PaypalCommerceHostedFieldsFieldData {\n    container: HTMLElement;\n    isFocused: boolean;\n    isEmpty: boolean;\n    isPotentiallyValid: boolean;\n    isValid: boolean;\n}\n\nexport interface PaypalCommerceButtons {\n    render(id: string): void;\n    close(): void;\n    isEligible(): boolean;\n}\n\nexport interface PaypalCommerceFields {\n    render(id: string): void;\n}\n\nexport interface PaypalCommerceMessages {\n    render(id: string): void;\n}\n\nexport interface PaypalCommerceSDKFunding {\n    PAYPAL: string;\n    CREDIT: string;\n    PAYLATER: string;\n    BANCONTACT: string;\n    GIROPAY: string;\n    P24: string;\n    EPS: string;\n    IDEAL: string;\n    MYBANK: string;\n    SOFORT: string;\n    BLIK: string;\n    TRUSTLY: string;\n    VERKKOPANKKI: string;\n    VENMO: string;\n}\n\nexport interface PaypalCommerceSDK {\n    FUNDING: PaypalCommerceSDKFunding;\n    HostedFields: {\n        isEligible(): boolean;\n        render(data: PaypalCommerceHostedFieldsRenderOptions): Promise<PaypalCommerceHostedFields>;\n    };\n    Buttons(params: ButtonsOptions): PaypalCommerceButtons;\n    Fields(params: FieldsOptions): PaypalCommerceFields;\n    Messages(params: MessagesOptions): PaypalCommerceMessages;\n}\n\nexport interface PaypalCommerceHostWindow extends Window {\n    paypal?: PaypalCommerceSDK;\n    paypalLoadScript?(options: PaypalCommerceScriptParams): Promise<{ paypal: PaypalCommerceSDK }>;\n}\n\nexport interface PaypalCommerceInitializationData {\n    clientId: string;\n    merchantId?: string;\n    buyerCountry?: string;\n    isDeveloperModeApplicable?: boolean;\n    intent?: 'capture' | 'authorize';\n    isPayPalCreditAvailable?: boolean;\n    isProgressiveOnboardingAvailable?: boolean;\n    clientToken?: string;\n    attributionId?: string;\n}\n\nexport type DisableFundingType = Array<'credit' | 'card'>;\n\nexport type ComponentsScriptType = Array<'buttons' | 'messages' | 'hosted-fields' | 'fields'>;\n\nexport interface PaypalCommerceScriptParams  {\n    'client-id': string;\n    'merchant-id'?: string;\n    'buyer-country'?: string;\n    'disable-funding'?: DisableFundingType;\n    'data-client-token'?: string;\n    'data-partner-attribution-id'?: string;\n    currency?: string;\n    commit?: boolean;\n    intent?: 'capture' | 'authorize';\n    components?: ComponentsScriptType;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { InvalidArgumentError } from '../../../common/error/errors';\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { PaypalCommerceHostWindow, PaypalCommerceScriptParams, PaypalCommerceSDK } from './paypal-commerce-sdk';\n\nexport default class PaypalCommerceScriptLoader {\n    private _window: PaypalCommerceHostWindow;\n\n    constructor(\n        private _scriptLoader: ScriptLoader\n    ) {\n        this._window = window;\n    }\n\n    async loadPaypalCommerce(params: PaypalCommerceScriptParams, isProgressiveOnboardingAvailable?: boolean): Promise<PaypalCommerceSDK> {\n        this._validateParams(params, isProgressiveOnboardingAvailable);\n\n        if (!this._window.paypalLoadScript) {\n            const scriptSrc = 'https://unpkg.com/@paypal/paypal-js@1.0.2/dist/paypal.browser.min.js';\n\n            await this._scriptLoader.loadScript(scriptSrc, {async: true, attributes: {}});\n\n            if (!this._window.paypalLoadScript) {\n                throw new PaymentMethodClientUnavailableError();\n            }\n        }\n\n        await this._window.paypalLoadScript(params);\n\n        if (!this._window.paypal) {\n            throw new PaymentMethodClientUnavailableError();\n        }\n\n        return this._window.paypal;\n    }\n\n    _validateParams(options: PaypalCommerceScriptParams, isProgressiveOnboardingAvailable?: boolean): void {\n        const CLIENT_ID = 'client-id';\n        const MERCHANT_ID = 'merchant-id';\n        let param;\n\n        if (!options) {\n            param = 'options';\n        } else if (!options[CLIENT_ID]) {\n            param = CLIENT_ID;\n        } else if (!options[MERCHANT_ID] && !isProgressiveOnboardingAvailable) {\n            param = MERCHANT_ID;\n        }\n\n        if (param) {\n            throw new InvalidArgumentError(`Unable to proceed because \"${param}\" argument in PayPal script is not provided.`);\n        }\n    }\n}\n","import { isNil, omitBy } from 'lodash';\n\nimport { NotImplementedError, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { PaymentMethodClientUnavailableError } from '../../errors';\nimport PaymentStrategyType from '../../payment-strategy-type';\n\nimport { ButtonsOptions, FieldsOptions, ParamsForProvider, PaypalButtonStyleOptions, PaypalCommerceButtons, PaypalCommerceFields, PaypalCommerceHostedFields, PaypalCommerceHostedFieldsApprove, PaypalCommerceHostedFieldsRenderOptions, PaypalCommerceHostedFieldsState, PaypalCommerceHostedFieldsSubmitOptions, PaypalCommerceMessages, PaypalCommerceRequestSender, PaypalCommerceScriptLoader, PaypalCommerceScriptParams, PaypalCommerceSDK, PaypalCommerceSDKFunding, PaypalFieldsStyleOptions, StyleButtonColor, StyleButtonLabel, StyleButtonLayout, StyleButtonShape } from './index';\n\nexport interface OptionalParamsRenderButtons {\n    paramsForProvider?: ParamsForProvider;\n    fundingKey?: keyof PaypalCommerceSDKFunding;\n    onRenderButton?(): void;\n}\n\nexport interface ParamsRenderHostedFields {\n    fields: PaypalCommerceHostedFieldsRenderOptions['fields'];\n    styles?: PaypalCommerceHostedFieldsRenderOptions['styles'];\n}\n\ninterface EventsHostedFields {\n    blur?(event: PaypalCommerceHostedFieldsState): void;\n    focus?(event: PaypalCommerceHostedFieldsState): void;\n    cardTypeChange?(event: PaypalCommerceHostedFieldsState): void;\n    validityChange?(event: PaypalCommerceHostedFieldsState): void;\n    inputSubmitRequest?(event: PaypalCommerceHostedFieldsState): void;\n}\n\nexport interface RenderApmFieldsParams {\n    apmFieldsContainer: string;\n    fundingKey: keyof PaypalCommerceSDKFunding;\n    apmFieldsStyles?: PaypalFieldsStyleOptions;\n    fullName?: string;\n    email?: string;\n}\n\nexport default class PaypalCommercePaymentProcessor {\n    private _paypal?: PaypalCommerceSDK;\n    private _paypalButtons?: PaypalCommerceButtons;\n    private _paypalFields?: PaypalCommerceFields;\n    private _paypalMessages?: PaypalCommerceMessages;\n    private _hostedFields?: PaypalCommerceHostedFields;\n    private _fundingSource?: string;\n    private _orderId?: string;\n    private _gatewayId?: string;\n\n    constructor(\n        private _paypalScriptLoader: PaypalCommerceScriptLoader,\n        private _paypalCommerceRequestSender: PaypalCommerceRequestSender\n    ) {}\n\n    async initialize(paramsScript: PaypalCommerceScriptParams, isProgressiveOnboardingAvailable?: boolean, gatewayId?: string): Promise<PaypalCommerceSDK> {\n        this._paypal = await this._paypalScriptLoader.loadPaypalCommerce(paramsScript, isProgressiveOnboardingAvailable);\n        this._gatewayId = gatewayId;\n\n        return this._paypal;\n    }\n\n    renderButtons(cartId: string, container: string, params: ButtonsOptions = {}, optionalParams: OptionalParamsRenderButtons = {}): PaypalCommerceButtons {\n        if (!this._paypal || !this._paypal.Buttons) {\n            throw new PaymentMethodClientUnavailableError();\n        }\n\n        const { paramsForProvider, fundingKey, onRenderButton } = optionalParams;\n\n        const buttonParams: ButtonsOptions = {\n            ...params,\n            createOrder: () => this._setupPayment(cartId, paramsForProvider),\n\n            onClick: async (data, actions) => {\n                this._fundingSource = data.fundingSource;\n\n                return params.onClick?.(data, actions);\n            },\n        };\n\n        if (params.style) {\n            buttonParams.style = this._validateStyleParams(params.style);\n        }\n\n        if (fundingKey) {\n            this._fundingSource = this._paypal.FUNDING[fundingKey];\n            buttonParams.fundingSource = this._fundingSource;\n        }\n\n        this._paypalButtons = this._paypal.Buttons(buttonParams);\n\n        if (!this._paypalButtons.isEligible()) {\n            this._processNotEligible(buttonParams, fundingKey);\n        }\n\n        onRenderButton?.();\n\n        this._paypalButtons.render(container);\n\n        return this._paypalButtons;\n    }\n\n    renderFields({\n        apmFieldsContainer,\n        fundingKey,\n        apmFieldsStyles,\n        fullName,\n        email,\n    }: RenderApmFieldsParams): PaypalCommerceFields {\n        if (!this._paypal || !this._paypal.Fields) {\n            throw new PaymentMethodClientUnavailableError();\n        }\n\n        const fieldsParams: FieldsOptions = {\n            fundingSource: this._paypal.FUNDING[fundingKey],\n            style: apmFieldsStyles,\n            fields: {\n                name: {\n                    value: fullName,\n                },\n                email: {\n                    value: email,\n                },\n            },\n        };\n\n        this._paypalFields = this._paypal.Fields(fieldsParams);\n\n        const fieldContainerElement = document.querySelector(apmFieldsContainer);\n        if (fieldContainerElement) {\n            fieldContainerElement.innerHTML = '';\n        }\n\n        this._paypalFields.render(apmFieldsContainer);\n\n        return this._paypalFields;\n    }\n\n    getOrderId() {\n        return this._orderId;\n    }\n\n    renderMessages(cartTotal: number, container: string): PaypalCommerceMessages {\n        if (!this._paypal || !this._paypal.Messages) {\n            throw new PaymentMethodClientUnavailableError();\n        }\n        this._paypalMessages = this._paypal.Messages({\n            amount: cartTotal,\n            placement: 'cart',\n            style: {\n                layout: 'text',\n            },\n        });\n        this._paypalMessages.render(container);\n\n        return this._paypalMessages;\n    }\n\n    async renderHostedFields(cartId: string, params: ParamsRenderHostedFields, events?: EventsHostedFields): Promise<void> {\n        if (!this._paypal || !this._paypal.HostedFields) {\n            throw new PaymentMethodClientUnavailableError();\n        }\n\n        const { fields, styles } = params;\n\n        if (!this._paypal.HostedFields.isEligible()) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        this._hostedFields = await this._paypal.HostedFields.render({\n            fields,\n            styles,\n            paymentsSDK: true,\n            createOrder: () => this._setupPayment(cartId, { isCreditCard: true }),\n        });\n\n        if (events) {\n            (Object.keys(events) as Array<keyof EventsHostedFields>).forEach(key => {\n                (this._hostedFields as PaypalCommerceHostedFields).on(key, events[key] as (event: PaypalCommerceHostedFieldsState) => void);\n            });\n        }\n    }\n\n    async submitHostedFields(options?: PaypalCommerceHostedFieldsSubmitOptions): Promise<PaypalCommerceHostedFieldsApprove> {\n        if (!this._hostedFields) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        return this._hostedFields.submit(omitBy(options, isNil));\n    }\n\n    getHostedFieldsValidationState(): { isValid: boolean; fields: PaypalCommerceHostedFieldsState['fields'] } {\n        if (!this._hostedFields) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        const { fields } = this._hostedFields.getState();\n\n        const isValid = (Object.keys(fields) as Array<keyof PaypalCommerceHostedFieldsState['fields']>)\n            .every(key => fields[key]?.isValid);\n\n        return { isValid, fields };\n    }\n\n    deinitialize() {\n        this._paypalButtons?.close?.();\n        this._paypal = undefined;\n        this._paypalButtons = undefined;\n        this._fundingSource = undefined;\n        this._hostedFields = undefined;\n    }\n\n    private async _setupPayment(cartId: string, params: ParamsForProvider = {}): Promise<string> {\n        const paramsForProvider = { ...params, isCredit: this._fundingSource === 'credit' || this._fundingSource === 'paylater' };\n        const isAPM = this._gatewayId === PaymentStrategyType.PAYPAL_COMMERCE_ALTERNATIVE_METHODS;\n        const { orderId } = await this._paypalCommerceRequestSender.setupPayment(cartId, {...paramsForProvider, isAPM});\n        this._orderId = orderId;\n\n        return orderId;\n    }\n\n    private _validateStyleParams = (style: PaypalButtonStyleOptions): PaypalButtonStyleOptions  => {\n        const updatedStyle: PaypalButtonStyleOptions = { ...style };\n        const { label, color, layout, shape, height, tagline } = style;\n\n        if (label && !StyleButtonLabel[label]) {\n            delete updatedStyle.label;\n        }\n\n        if (layout && !StyleButtonLayout[layout]) {\n            delete updatedStyle.layout;\n        }\n\n        if (color && !StyleButtonColor[color]) {\n            delete updatedStyle.color;\n        }\n\n        if (shape && !StyleButtonShape[shape]) {\n            delete updatedStyle.shape;\n        }\n\n        if (typeof height === 'number') {\n            updatedStyle.height = height < 25\n                ? 25\n                : (height > 55 ? 55 : height);\n        } else {\n            delete updatedStyle.height;\n        }\n\n        if (typeof tagline !== 'boolean' || (tagline && updatedStyle.layout !== StyleButtonLayout[StyleButtonLayout.horizontal])) {\n            delete updatedStyle.tagline;\n        }\n\n        return updatedStyle;\n    };\n\n    private _processNotEligible(buttonParams: ButtonsOptions, fundingKey?: keyof PaypalCommerceSDKFunding): void {\n        if (fundingKey === this._paypal?.FUNDING.PAYLATER) {\n            buttonParams.fundingSource = this._paypal?.FUNDING.CREDIT;\n\n            this._paypalButtons = this._paypal?.Buttons(buttonParams);\n\n            if (this._paypalButtons?.isEligible()) {\n                return;\n            }\n        }\n\n        throw new NotImplementedError(`PayPal ${this._fundingSource || ''} is not available for your region. Please use PayPal Checkout instead.`);\n    }\n\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaypalCommercePaymentProcessor, PaypalCommerceRequestSender, PaypalCommerceScriptLoader } from './index';\n\nexport default function createPaypalCommercePaymentProcessor(scriptLoader: ScriptLoader, requestSender: RequestSender) {\n    const paypalScriptLoader = new PaypalCommerceScriptLoader(scriptLoader);\n    const paypalCommerceRequestSender = new PaypalCommerceRequestSender(requestSender);\n\n    return new PaypalCommercePaymentProcessor(paypalScriptLoader, paypalCommerceRequestSender);\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { AddressRequestBody } from '../../../address';\nimport { BillingAddressActionCreator, BillingAddressUpdateRequestBody } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { RemoteCheckoutSynchronizationError } from '../../../remote-checkout/errors';\nimport { ConsignmentActionCreator } from '../../../shipping';\nimport { PaymentMethodInvalidError } from '../../errors';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\n\nimport { ButtonColor, ButtonType, EnvironmentType, GooglePaymentData, GooglePayAddress, GooglePayClient, GooglePayInitializer, GooglePayPaymentDataRequestV2, GooglePaySDK, TokenizePayload } from './googlepay';\nimport GooglePayScriptLoader from './googlepay-script-loader';\n\nexport default class GooglePayPaymentProcessor {\n    private _googlePayClient?: GooglePayClient;\n    private _methodId?: string;\n    private _paymentDataRequest?: GooglePayPaymentDataRequestV2;\n\n    constructor(\n        private _store: CheckoutStore,\n        private _paymentMethodActionCreator: PaymentMethodActionCreator,\n        private _googlePayScriptLoader: GooglePayScriptLoader,\n        private _googlePayInitializer: GooglePayInitializer,\n        private _billingAddressActionCreator: BillingAddressActionCreator,\n        private _consignmentActionCreator: ConsignmentActionCreator,\n        private _requestSender: RequestSender\n    ) {}\n\n    initialize(methodId: string): Promise<void> {\n        this._methodId = methodId;\n\n        return this._configureWallet();\n    }\n\n    deinitialize(): Promise<void> {\n        return this._googlePayInitializer.teardown();\n    }\n\n    createButton(\n        onClick: (event: Event) => Promise<void>,\n        buttonType: ButtonType = ButtonType.Short,\n        buttonColor: ButtonColor = ButtonColor.Default\n    ): HTMLElement {\n        if (!this._googlePayClient) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        return this._googlePayClient.createButton({\n            buttonColor,\n            buttonType,\n            onClick,\n        });\n    }\n\n    displayWallet(): Promise<GooglePaymentData> {\n        if (!this._googlePayClient) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        return this._googlePayClient.loadPaymentData(this._getPaymentDataRequest());\n    }\n\n    handleSuccess(paymentData: GooglePaymentData): Promise<InternalCheckoutSelectors> {\n        return this._googlePayInitializer.parseResponse(paymentData)\n            .then(tokenizePayload => this._postForm(tokenizePayload))\n            .then(() => this._updateBillingAddress(paymentData));\n    }\n\n    updateShippingAddress(shippingAddress: GooglePayAddress): Promise<InternalCheckoutSelectors> {\n        return this._store.dispatch(\n            this._consignmentActionCreator.updateAddress(this._mapGooglePayAddressToShippingAddress(shippingAddress))\n        );\n    }\n\n    private _configureWallet(): Promise<void> {\n        const methodId = this._getMethodId();\n\n        return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n            .then(state => {\n                const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n                const checkout = state.checkout.getCheckout();\n                const hasShippingAddress = !!state.shippingAddress.getShippingAddress();\n\n                if (!paymentMethod) {\n                    throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n                }\n\n                if (!checkout) {\n                    throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n                }\n\n                const { testMode } = paymentMethod.config;\n\n                return Promise.all([\n                    this._googlePayScriptLoader.load(),\n                    this._googlePayInitializer.initialize(checkout, paymentMethod, hasShippingAddress),\n                ]).then(([googlePay, paymentDataRequest]) => {\n                    this._googlePayClient = this._getGooglePayClient(googlePay, testMode);\n                    this._paymentDataRequest = paymentDataRequest;\n\n                    return this._googlePayClient.isReadyToPay({\n                        allowedPaymentMethods: [\n                            {\n                                type: paymentDataRequest.allowedPaymentMethods[0].type,\n                                parameters: {\n                                    allowedAuthMethods: paymentDataRequest.allowedPaymentMethods[0].parameters.allowedAuthMethods,\n                                    allowedCardNetworks: paymentDataRequest.allowedPaymentMethods[0].parameters.allowedCardNetworks,\n                                },\n                            },\n                        ],\n                        apiVersion: paymentDataRequest.apiVersion,\n                        apiVersionMinor: paymentDataRequest.apiVersionMinor,\n                    }).then(response => {\n                        if (response.result) {\n                            return;\n                        }\n\n                        throw new PaymentMethodInvalidError();\n                    });\n                });\n            });\n    }\n\n    private _getCardInformation(cardInformation: { cardType: string; lastFour: string }) {\n        return {\n            type: cardInformation.cardType,\n            number: cardInformation.lastFour,\n        };\n    }\n\n    private _getPaymentDataRequest(): GooglePayPaymentDataRequestV2 {\n        if (!this._paymentDataRequest) {\n            throw new RemoteCheckoutSynchronizationError();\n        }\n\n        return this._paymentDataRequest;\n    }\n\n    private _getGooglePayClient(google: GooglePaySDK, testMode?: boolean): GooglePayClient {\n        if (testMode === undefined) {\n            throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n        }\n\n        const environment: EnvironmentType = testMode ? 'TEST' : 'PRODUCTION';\n\n        return new google.payments.api.PaymentsClient({ environment });\n    }\n\n    private _getMethodId(): string {\n        if (!this._methodId) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        return this._methodId;\n    }\n\n    private _mapGooglePayAddressToBillingAddress(paymentData: GooglePaymentData, id: string): BillingAddressUpdateRequestBody {\n        const firstName = paymentData.paymentMethodData.info.billingAddress.name.split(' ').slice(0, -1).join(' ');\n        const address1 =  paymentData.paymentMethodData.info.billingAddress.address1;\n        const city =  paymentData.paymentMethodData.info.billingAddress.locality;\n        const postalCode =  paymentData.paymentMethodData.info.billingAddress.postalCode;\n        const countryCode =  paymentData.paymentMethodData.info.billingAddress.countryCode;\n\n        if (!firstName || !address1 || !city || !postalCode || !countryCode) {\n            throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n        }\n\n        return {\n            id,\n            firstName,\n            lastName: paymentData.paymentMethodData.info.billingAddress.name.split(' ').slice(-1).join(' '),\n            company: paymentData.paymentMethodData.info.billingAddress.companyName,\n            address1,\n            address2: paymentData.paymentMethodData.info.billingAddress.address2 + paymentData.paymentMethodData.info.billingAddress.address3,\n            city,\n            stateOrProvince: paymentData.paymentMethodData.info.billingAddress.administrativeArea,\n            stateOrProvinceCode: paymentData.paymentMethodData.info.billingAddress.administrativeArea,\n            postalCode,\n            countryCode,\n            phone: paymentData.paymentMethodData.info.billingAddress.phoneNumber,\n            customFields: [],\n            email: paymentData.email,\n        };\n    }\n\n    private _mapGooglePayAddressToShippingAddress(address: GooglePayAddress): AddressRequestBody {\n        return {\n            firstName: address.name.split(' ').slice(0, -1).join(' '),\n            lastName: address.name.split(' ').slice(-1).join(' '),\n            company: address.companyName,\n            address1: address.address1,\n            address2: address.address2 + address.address3,\n            city: address.locality,\n            stateOrProvince: address.administrativeArea,\n            stateOrProvinceCode: address.administrativeArea,\n            postalCode: address.postalCode,\n            countryCode: address.countryCode,\n            phone: address.phoneNumber,\n            customFields: [],\n        };\n    }\n\n    private _postForm(postPaymentData: TokenizePayload): Promise<Response<void>> {\n        const cardInformation = postPaymentData.details;\n\n        return this._requestSender.post('/checkout.php', {\n            headers: {\n                Accept: 'text/html',\n                'Content-Type': 'application/x-www-form-urlencoded',\n            },\n            body: {\n                payment_type: postPaymentData.type,\n                nonce: postPaymentData.nonce,\n                provider: this._getMethodId(),\n                action: 'set_external_checkout',\n                card_information: this._getCardInformation(cardInformation),\n            },\n        });\n    }\n\n    private _updateBillingAddress(paymentData: GooglePaymentData): Promise<InternalCheckoutSelectors> {\n        const remoteBillingAddress = this._store.getState().billingAddress.getBillingAddress();\n\n        if (!remoteBillingAddress) {\n            throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n        }\n\n        const googlePayAddressMapped = this._mapGooglePayAddressToBillingAddress(paymentData, remoteBillingAddress.id);\n\n        return this._store.dispatch(\n            this._billingAddressActionCreator.updateAddress(googlePayAddressMapped)\n        );\n    }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { GooglePayHostWindow, GooglePaySDK } from './googlepay';\n\nexport default class GooglePayScriptLoader {\n    constructor(\n        private _scriptLoader: ScriptLoader,\n        private _window: GooglePayHostWindow = window\n    ) {}\n\n    load(): Promise<GooglePaySDK> {\n        return this._scriptLoader\n            .loadScript('https://pay.google.com/gp/p/js/pay.js')\n            .then(() => {\n                if (!this._window.google) {\n                    throw new PaymentMethodClientUnavailableError();\n                }\n\n                return this._window.google;\n            });\n    }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../../../billing';\nimport { CheckoutRequestSender, CheckoutStore } from '../../../checkout';\nimport { ConsignmentActionCreator, ConsignmentRequestSender } from '../../../shipping';\nimport { SubscriptionsActionCreator, SubscriptionsRequestSender } from '../../../subscription';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport PaymentMethodRequestSender from '../../payment-method-request-sender';\n\nimport { GooglePayInitializer } from './googlepay';\nimport GooglePayPaymentProcessor from './googlepay-payment-processor';\nimport GooglePayScriptLoader from './googlepay-script-loader';\n\nexport default function createGooglePayPaymentProcessor(store: CheckoutStore, initializer: GooglePayInitializer): GooglePayPaymentProcessor {\n    const requestSender = createRequestSender();\n    const scriptLoader = getScriptLoader();\n\n    return new GooglePayPaymentProcessor(\n        store,\n        new PaymentMethodActionCreator(\n            new PaymentMethodRequestSender(requestSender)\n        ),\n        new GooglePayScriptLoader(scriptLoader),\n        initializer,\n        new BillingAddressActionCreator(\n            new BillingAddressRequestSender(requestSender),\n            new SubscriptionsActionCreator(\n                new SubscriptionsRequestSender(requestSender)\n            )\n        ),\n        new ConsignmentActionCreator(\n            new ConsignmentRequestSender(requestSender),\n            new CheckoutRequestSender(requestSender)\n        ),\n        requestSender\n    );\n}\n","import { PaymentMethod } from '../..';\nimport { AmazonPayV2ButtonInitializeOptions } from '../../../checkout-buttons/strategies/amazon-pay-v2';\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\n\nimport { AmazonPayV2ChangeActionType, AmazonPayV2SDK } from './amazon-pay-v2';\nimport AmazonPayV2ScriptLoader from './amazon-pay-v2-script-loader';\n\nexport default class AmazonPayV2PaymentProcessor {\n    private _amazonPayV2SDK?: AmazonPayV2SDK;\n\n    constructor(\n        private _amazonPayV2ScriptLoader: AmazonPayV2ScriptLoader\n    ) { }\n\n    async initialize(paymentMethod: PaymentMethod): Promise<void> {\n        this._amazonPayV2SDK = await this._amazonPayV2ScriptLoader.load(paymentMethod);\n    }\n\n    deinitialize(): Promise<void> {\n        this._amazonPayV2SDK = undefined;\n\n        return Promise.resolve();\n    }\n\n    bindButton(buttonId: string, sessionId: string, changeAction: AmazonPayV2ChangeActionType): void {\n        this._getAmazonPayV2SDK().Pay.bindChangeAction(`#${buttonId}`, {\n            amazonCheckoutSessionId: sessionId,\n            changeAction,\n        });\n    }\n\n    createButton(containerId: string, options: AmazonPayV2ButtonInitializeOptions): HTMLElement {\n        return this._getAmazonPayV2SDK().Pay.renderButton(containerId, options);\n    }\n\n    async signout(): Promise<void> {\n        if (this._amazonPayV2SDK) {\n            this._amazonPayV2SDK.Pay.signout();\n        }\n\n        return Promise.resolve();\n    }\n\n    private _getAmazonPayV2SDK(): AmazonPayV2SDK {\n        if (!this._amazonPayV2SDK) {\n            throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n        }\n\n        return this._amazonPayV2SDK;\n    }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\nimport PaymentMethod from '../../payment-method';\n\nimport { AmazonPayV2HostWindow, AmazonPayV2Regions, AmazonPayV2SDK } from './amazon-pay-v2';\n\nexport default class AmazonPayV2ScriptLoader {\n    constructor(\n        private _scriptLoader: ScriptLoader,\n        private _window: AmazonPayV2HostWindow = window\n    ) {}\n\n    async load(method: PaymentMethod): Promise<AmazonPayV2SDK> {\n        const {\n            initializationData: { region = 'us' } = {},\n        } = method;\n\n        const amazonPayV2Region  = (AmazonPayV2Regions as any)[region];\n\n        await this._scriptLoader.loadScript(`https://static-${amazonPayV2Region}.payments-amazon.com/checkout.js`);\n        if (!this._window.amazon) {\n            throw new PaymentMethodClientUnavailableError();\n        }\n\n        return this._window.amazon;\n    }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport AmazonPayV2PaymentProcessor from './amazon-pay-v2-payment-processor';\nimport AmazonPayV2ScriptLoader from './amazon-pay-v2-script-loader';\n\nexport default function createAmazonPayV2PaymentProcessor(): AmazonPayV2PaymentProcessor {\n    return new AmazonPayV2PaymentProcessor(\n        new AmazonPayV2ScriptLoader(getScriptLoader())\n    );\n}\n","import { Cart } from '../cart';\n\nimport getLineItemsCount from './getLineItemsCount';\n\nexport default function getShippableItemsCount(cart: Cart): number {\n    return getLineItemsCount(cart.lineItems.physicalItems.filter(item => !item.addedByPromotion));\n}\n","import { reduce } from 'lodash';\n\nimport { LineItem } from '../cart';\n\nexport default function getLineItemsCount(lineItems: LineItem[]): number {\n    return reduce(lineItems, (total, item) => total + item.quantity, 0);\n}\n","import { RequestError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when the subscriptions fails to be updated\n */\nexport default class UpdateSubscriptionsError extends RequestError {\n    constructor(response?: Response) {\n        super(response);\n\n        this.name = 'UpdateSubscriptionsError';\n        this.type = 'update_subscriptions';\n    }\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { concat, defer, of, Observable } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\nimport { Subscriptions, SubscriptionsActionType, SubscriptionsRequestSender, UpdateSubscriptionsAction } from '../subscription';\n\nimport { UpdateSubscriptionsError } from './errors';\n\nexport default class SubscriptionsActionCreator {\n    constructor(\n        private _subscriptionsRequestSender: SubscriptionsRequestSender\n    ) {}\n\n    updateSubscriptions(\n        subscriptions: Subscriptions,\n        options?: RequestOptions\n    ): Observable<UpdateSubscriptionsAction> {\n        return concat(\n            of(createAction(SubscriptionsActionType.UpdateSubscriptionsRequested)),\n            defer(async () => {\n                const { body } = await this._subscriptionsRequestSender.updateSubscriptions(subscriptions, options);\n\n                return createAction(SubscriptionsActionType.UpdateSubscriptionsSucceeded, body);\n            })\n        ).pipe(\n            catchError(error => throwErrorAction(\n                SubscriptionsActionType.UpdateSubscriptionsFailed,\n                new UpdateSubscriptionsError(error)\n            ))\n        );\n    }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when a shopper tries to sign in as a guest but\n * they are already signed in as a registered customer.\n */\nexport default class UnableToContinueAsGuestError extends StandardError {\n    constructor(message?: string) {\n        super(message || 'Unable to continue as a guest because the customer is already signed in.');\n\n        this.name = 'UnableToContinueAsGuestError';\n        this.type = 'unable_to_continue_as_guest';\n    }\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Response } from '@bigcommerce/request-sender';\nimport { concat, defer, empty, merge, of, Observable, Observer } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { Checkout, InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { GuestCredentials } from '../customer';\nimport { SubscriptionsActionCreator, UpdateSubscriptionsAction } from '../subscription';\n\nimport { BillingAddressRequestSender } from '.';\nimport { BillingAddressUpdateRequestBody } from './billing-address';\nimport { BillingAddressActionType, ContinueAsGuestAction, UpdateBillingAddressAction } from './billing-address-actions';\nimport { UnableToContinueAsGuestError } from './errors';\n\nexport default class BillingAddressActionCreator {\n    constructor(\n        private _requestSender: BillingAddressRequestSender,\n        private _subscriptionActionCreator: SubscriptionsActionCreator\n    ) {}\n\n    continueAsGuest(\n        credentials: GuestCredentials,\n        options?: RequestOptions\n    ): ThunkAction<ContinueAsGuestAction | UpdateSubscriptionsAction, InternalCheckoutSelectors> {\n        return store => {\n            const state = store.getState();\n            const checkout = state.checkout.getCheckout();\n\n            if (!checkout) {\n                throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n            }\n\n            const customer = state.customer.getCustomer();\n\n            if (customer && !customer.isGuest) {\n                throw new UnableToContinueAsGuestError();\n            }\n\n            const billingAddress = state.billingAddress.getBillingAddress();\n\n            let billingAddressRequestBody: Partial<BillingAddressUpdateRequestBody>;\n\n            if (!billingAddress) {\n                billingAddressRequestBody = credentials;\n            } else {\n                const { country, ...existingBillingAddressRequestBody } = billingAddress;\n\n                billingAddressRequestBody = {\n                    ...existingBillingAddressRequestBody,\n                    ...credentials,\n                };\n            }\n\n            return merge(\n                concat(\n                    of(createAction(BillingAddressActionType.ContinueAsGuestRequested)),\n                    defer(async () => {\n                        const { body } = await this._createOrUpdateBillingAddress(\n                            checkout.id,\n                            billingAddressRequestBody,\n                            options\n                        );\n\n                        return createAction(BillingAddressActionType.ContinueAsGuestSucceeded, body);\n                    })\n                ).pipe(\n                    catchError(error => throwErrorAction(BillingAddressActionType.ContinueAsGuestFailed, error))\n                ),\n                this._updateCustomerConsent(credentials, options)\n            );\n        };\n    }\n\n    updateAddress(\n        address: Partial<BillingAddressUpdateRequestBody>,\n        options?: RequestOptions\n    ): ThunkAction<UpdateBillingAddressAction, InternalCheckoutSelectors> {\n        return store => Observable.create((observer: Observer<UpdateBillingAddressAction>) => {\n            const state = store.getState();\n            const checkout = state.checkout.getCheckout();\n\n            if (!checkout) {\n                throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n            }\n\n            observer.next(createAction(BillingAddressActionType.UpdateBillingAddressRequested));\n\n            const billingAddress = state.billingAddress.getBillingAddress();\n\n            // If email is not present in the address provided by the client, then\n            // fall back to the stored email as it could have been set separately\n            // using a convenience method. We can't rely on billingAddress having\n            // an ID to consider that there's a preexisting email, as billingAddress\n            // object from Order doesn't have an ID.\n            const billingAddressRequestBody = {\n                ...address,\n                email: typeof address.email === 'undefined' && billingAddress ? billingAddress.email : address.email,\n            };\n\n            if (billingAddress && billingAddress.id) {\n                billingAddressRequestBody.id = billingAddress.id;\n            }\n\n            this._createOrUpdateBillingAddress(checkout.id, billingAddressRequestBody, options)\n                .then(({ body }) => {\n                    observer.next(createAction(BillingAddressActionType.UpdateBillingAddressSucceeded, body));\n                    observer.complete();\n                })\n                .catch(response => {\n                    observer.error(createErrorAction(BillingAddressActionType.UpdateBillingAddressFailed, response));\n                });\n        });\n    }\n\n    private _updateCustomerConsent(\n        {\n            email,\n            acceptsAbandonedCartEmails,\n            acceptsMarketingNewsletter,\n        }: GuestCredentials,\n        options?: RequestOptions\n    ): Observable<UpdateSubscriptionsAction> {\n        if ((acceptsAbandonedCartEmails === undefined || acceptsAbandonedCartEmails === null) &&\n            (acceptsMarketingNewsletter === undefined || acceptsMarketingNewsletter === null)) {\n            return empty();\n        }\n\n        return this._subscriptionActionCreator.updateSubscriptions({\n            email,\n            acceptsMarketingNewsletter: acceptsMarketingNewsletter || false,\n            acceptsAbandonedCartEmails: acceptsAbandonedCartEmails || false,\n        }, options);\n    }\n\n    private _createOrUpdateBillingAddress(\n        checkoutId: string,\n        address: Partial<BillingAddressUpdateRequestBody>,\n        options?: RequestOptions\n    ): Promise<Response<Checkout>> {\n        if (!address.id) {\n            return this._requestSender.createAddress(checkoutId, address, options);\n        }\n\n        return this._requestSender.updateAddress(checkoutId, address, options);\n    }\n}\n","export { default as createFormPoster } from './create-form-poster';\nexport { default as FormPoster } from './form-poster';\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OperatorFunction } from '../types';\n\n/**\n * Applies a given `project` function to each value emitted by the source\n * Observable, and emits the resulting values as an Observable.\n *\n * <span class=\"informal\">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),\n * it passes each source value through a transformation function to get\n * corresponding output values.</span>\n *\n * ![](map.png)\n *\n * Similar to the well known `Array.prototype.map` function, this operator\n * applies a projection to each value and emits that projection in the output\n * Observable.\n *\n * ## Example\n * Map every click to the clientX position of that click\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { map } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const positions = clicks.pipe(map(ev => ev.clientX));\n * positions.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link mapTo}\n * @see {@link pluck}\n *\n * @param {function(value: T, index: number): R} project The function to apply\n * to each `value` emitted by the source Observable. The `index` parameter is\n * the number `i` for the i-th emission that has happened since the\n * subscription, starting from the number `0`.\n * @param {any} [thisArg] An optional argument to define what `this` is in the\n * `project` function.\n * @return {Observable<R>} An Observable that emits the values from the source\n * Observable transformed by the given `project` function.\n * @method map\n * @owner Observable\n */\nexport function map<T, R>(project: (value: T, index: number) => R, thisArg?: any): OperatorFunction<T, R> {\n  return function mapOperation(source: Observable<T>): Observable<R> {\n    if (typeof project !== 'function') {\n      throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');\n    }\n    return source.lift(new MapOperator(project, thisArg));\n  };\n}\n\nexport class MapOperator<T, R> implements Operator<T, R> {\n  constructor(private project: (value: T, index: number) => R, private thisArg: any) {\n  }\n\n  call(subscriber: Subscriber<R>, source: any): any {\n    return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass MapSubscriber<T, R> extends Subscriber<T> {\n  count: number = 0;\n  private thisArg: any;\n\n  constructor(destination: Subscriber<R>,\n              private project: (value: T, index: number) => R,\n              thisArg: any) {\n    super(destination);\n    this.thisArg = thisArg || this;\n  }\n\n  // NOTE: This looks unoptimized, but it's actually purposefully NOT\n  // using try/catch optimizations.\n  protected _next(value: T) {\n    let result: R;\n    try {\n      result = this.project.call(this.thisArg, value, this.count++);\n    } catch (err) {\n      this.destination.error(err);\n      return;\n    }\n    this.destination.next(result);\n  }\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\n\n/**\n * The same Observable instance returned by any call to {@link empty} without a\n * `scheduler`. It is preferrable to use this over `empty()`.\n */\nexport const EMPTY = new Observable<never>(subscriber => subscriber.complete());\n\n/**\n * Creates an Observable that emits no items to the Observer and immediately\n * emits a complete notification.\n *\n * <span class=\"informal\">Just emits 'complete', and nothing else.\n * </span>\n *\n * ![](empty.png)\n *\n * This static operator is useful for creating a simple Observable that only\n * emits the complete notification. It can be used for composing with other\n * Observables, such as in a {@link mergeMap}.\n *\n * ## Examples\n * ### Emit the number 7, then complete\n * ```ts\n * import { empty } from 'rxjs';\n * import { startWith } from 'rxjs/operators';\n *\n * const result = empty().pipe(startWith(7));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * ### Map and flatten only odd numbers to the sequence 'a', 'b', 'c'\n * ```ts\n * import { empty, interval, of } from 'rxjs';\n * import { mergeMap } from 'rxjs/operators';\n *\n * const interval$ = interval(1000);\n * const result = interval$.pipe(\n *   mergeMap(x => x % 2 === 1 ? of('a', 'b', 'c') : empty()),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following to the console:\n * // x is equal to the count on the interval eg(0,1,2,3,...)\n * // x will occur every 1000ms\n * // if x % 2 is equal to 1 print abc\n * // if x % 2 is not equal to 1 nothing will be output\n * ```\n *\n * @see {@link Observable}\n * @see {@link never}\n * @see {@link of}\n * @see {@link throwError}\n *\n * @param scheduler A {@link SchedulerLike} to use for scheduling\n * the emission of the complete notification.\n * @return An \"empty\" Observable: emits only the complete\n * notification.\n * @deprecated Deprecated in favor of using {@link EMPTY} constant, or {@link scheduled} (e.g. `scheduled([], scheduler)`)\n */\nexport function empty(scheduler?: SchedulerLike) {\n  return scheduler ? emptyScheduled(scheduler) : EMPTY;\n}\n\nfunction emptyScheduled(scheduler: SchedulerLike) {\n  return new Observable<never>(subscriber => scheduler.schedule(() => subscriber.complete()));\n}\n","import { SchedulerLike } from '../types';\n\nexport function isScheduler(value: any): value is SchedulerLike {\n  return value && typeof (<any>value).schedule === 'function';\n}\n","import { Observable } from '../Observable';\nimport { subscribeTo } from '../util/subscribeTo';\nimport { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';\nimport { scheduled } from '../scheduled/scheduled';\n\nexport function from<O extends ObservableInput<any>>(input: O): Observable<ObservedValueOf<O>>;\n/** @deprecated use {@link scheduled} instead. */\nexport function from<O extends ObservableInput<any>>(input: O, scheduler: SchedulerLike): Observable<ObservedValueOf<O>>;\n\n/**\n * Creates an Observable from an Array, an array-like object, a Promise, an iterable object, or an Observable-like object.\n *\n * <span class=\"informal\">Converts almost anything to an Observable.</span>\n *\n * ![](from.png)\n *\n * `from` converts various other objects and data types into Observables. It also converts a Promise, an array-like, or an\n * <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable\" target=\"_blank\">iterable</a>\n * object into an Observable that emits the items in that promise, array, or iterable. A String, in this context, is treated\n * as an array of characters. Observable-like objects (contains a function named with the ES2015 Symbol for Observable) can also be\n * converted through this operator.\n *\n * ## Examples\n *\n * ### Converts an array to an Observable\n *\n * ```ts\n * import { from } from 'rxjs';\n *\n * const array = [10, 20, 30];\n * const result = from(array);\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 10\n * // 20\n * // 30\n * ```\n *\n * ---\n *\n * ### Convert an infinite iterable (from a generator) to an Observable\n *\n * ```ts\n * import { from } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * function* generateDoubles(seed) {\n *    let i = seed;\n *    while (true) {\n *      yield i;\n *      i = 2 * i; // double it\n *    }\n * }\n *\n * const iterator = generateDoubles(3);\n * const result = from(iterator).pipe(take(10));\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 3\n * // 6\n * // 12\n * // 24\n * // 48\n * // 96\n * // 192\n * // 384\n * // 768\n * // 1536\n * ```\n *\n * ---\n *\n * ### With async scheduler\n *\n * ```ts\n * import { from, asyncScheduler } from 'rxjs';\n *\n * console.log('start');\n *\n * const array = [10, 20, 30];\n * const result = from(array, asyncScheduler);\n *\n * result.subscribe(x => console.log(x));\n *\n * console.log('end');\n *\n * // Logs:\n * // start\n * // end\n * // 10\n * // 20\n * // 30\n * ```\n *\n * @see {@link fromEvent}\n * @see {@link fromEventPattern}\n *\n * @param {ObservableInput<T>} A subscription object, a Promise, an Observable-like,\n * an Array, an iterable, or an array-like object to be converted.\n * @param {SchedulerLike} An optional {@link SchedulerLike} on which to schedule the emission of values.\n * @return {Observable<T>}\n * @name from\n * @owner Observable\n */\nexport function from<T>(input: ObservableInput<T>, scheduler?: SchedulerLike): Observable<T> {\n  if (!scheduler) {\n    if (input instanceof Observable) {\n      return input;\n    }\n    return new Observable<T>(subscribeTo(input));\n  } else {\n    return scheduled(input, scheduler);\n  }\n}\n","export function identity<T>(x: T): T {\n  return x;\n}\n","import { Subscriber } from './Subscriber';\nimport { InnerSubscriber } from './InnerSubscriber';\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class OuterSubscriber<T, R> extends Subscriber<T> {\n  notifyNext(outerValue: T, innerValue: R,\n             outerIndex: number, innerIndex: number,\n             innerSub: InnerSubscriber<T, R>): void {\n    this.destination.next(innerValue);\n  }\n\n  notifyError(error: any, innerSub: InnerSubscriber<T, R>): void {\n    this.destination.error(error);\n  }\n\n  notifyComplete(innerSub: InnerSubscriber<T, R>): void {\n    this.destination.complete();\n  }\n}\n","import { Subscription } from '../Subscription';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { Subscriber } from '../Subscriber';\nimport { subscribeTo } from './subscribeTo';\nimport { Observable } from '../Observable';\n\nexport function subscribeToResult<T, R>(\n  outerSubscriber: OuterSubscriber<T, R>,\n  result: any,\n  outerValue: undefined,\n  outerIndex: undefined,\n  innerSubscriber: InnerSubscriber<T, R>\n): Subscription | undefined;\n\nexport function subscribeToResult<T, R>(\n  outerSubscriber: OuterSubscriber<T, R>,\n  result: any,\n  outerValue?: T,\n  outerIndex?: number\n): Subscription | undefined;\n\nexport function subscribeToResult<T, R>(\n  outerSubscriber: OuterSubscriber<T, R>,\n  result: any,\n  outerValue?: T,\n  outerIndex?: number,\n  innerSubscriber: Subscriber<R> = new InnerSubscriber(outerSubscriber, outerValue, outerIndex)\n): Subscription | undefined {\n  if (innerSubscriber.closed) {\n    return undefined;\n  }\n  if (result instanceof Observable) {\n    return result.subscribe(innerSubscriber);\n  }\n  return subscribeTo(result)(innerSubscriber) as Subscription;\n}\n","/** Symbol.observable or a string \"@@observable\". Used for interop */\nexport const observable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OperatorFunction, MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function filter<T, S extends T>(predicate: (value: T, index: number) => value is S,\n                                       thisArg?: any): OperatorFunction<T, S>;\nexport function filter<T>(predicate: (value: T, index: number) => boolean,\n                          thisArg?: any): MonoTypeOperatorFunction<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Filter items emitted by the source Observable by only emitting those that\n * satisfy a specified predicate.\n *\n * <span class=\"informal\">Like\n * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),\n * it only emits a value from the source if it passes a criterion function.</span>\n *\n * ![](filter.png)\n *\n * Similar to the well-known `Array.prototype.filter` method, this operator\n * takes values from the source Observable, passes them through a `predicate`\n * function and only emits those values that yielded `true`.\n *\n * ## Example\n * Emit only click events whose target was a DIV element\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { filter } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const clicksOnDivs = clicks.pipe(filter(ev => ev.target.tagName === 'DIV'));\n * clicksOnDivs.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link distinct}\n * @see {@link distinctUntilChanged}\n * @see {@link distinctUntilKeyChanged}\n * @see {@link ignoreElements}\n * @see {@link partition}\n * @see {@link skip}\n *\n * @param {function(value: T, index: number): boolean} predicate A function that\n * evaluates each value emitted by the source Observable. If it returns `true`,\n * the value is emitted, if `false` the value is not passed to the output\n * Observable. The `index` parameter is the number `i` for the i-th source\n * emission that has happened since the subscription, starting from the number\n * `0`.\n * @param {any} [thisArg] An optional argument to determine the value of `this`\n * in the `predicate` function.\n * @return {Observable} An Observable of values from the source that were\n * allowed by the `predicate` function.\n * @method filter\n * @owner Observable\n */\nexport function filter<T>(predicate: (value: T, index: number) => boolean,\n                          thisArg?: any): MonoTypeOperatorFunction<T> {\n  return function filterOperatorFunction(source: Observable<T>): Observable<T> {\n    return source.lift(new FilterOperator(predicate, thisArg));\n  };\n}\n\nclass FilterOperator<T> implements Operator<T, T> {\n  constructor(private predicate: (value: T, index: number) => boolean,\n              private thisArg?: any) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass FilterSubscriber<T> extends Subscriber<T> {\n\n  count: number = 0;\n\n  constructor(destination: Subscriber<T>,\n              private predicate: (value: T, index: number) => boolean,\n              private thisArg: any) {\n    super(destination);\n  }\n\n  // the try catch block below is left specifically for\n  // optimization and perf reasons. a tryCatcher is not necessary here.\n  protected _next(value: T) {\n    let result: any;\n    try {\n      result = this.predicate.call(this.thisArg, value, this.count++);\n    } catch (err) {\n      this.destination.error(err);\n      return;\n    }\n    if (result) {\n      this.destination.next(value);\n    }\n  }\n}\n","import { Subject } from '../Subject';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { ConnectableObservable, connectableObservableDescriptor } from '../observable/ConnectableObservable';\nimport { MonoTypeOperatorFunction, OperatorFunction, UnaryFunction, ObservedValueOf, ObservableInput } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function multicast<T>(subject: Subject<T>): UnaryFunction<Observable<T>, ConnectableObservable<T>>;\nexport function multicast<T, O extends ObservableInput<any>>(subject: Subject<T>, selector: (shared: Observable<T>) => O): UnaryFunction<Observable<T>, ConnectableObservable<ObservedValueOf<O>>>;\nexport function multicast<T>(subjectFactory: (this: Observable<T>) => Subject<T>): UnaryFunction<Observable<T>, ConnectableObservable<T>>;\nexport function multicast<T, O extends ObservableInput<any>>(SubjectFactory: (this: Observable<T>) => Subject<T>, selector: (shared: Observable<T>) => O): OperatorFunction<T, ObservedValueOf<O>>;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns an Observable that emits the results of invoking a specified selector on items\n * emitted by a ConnectableObservable that shares a single subscription to the underlying stream.\n *\n * ![](multicast.png)\n *\n * @param {Function|Subject} subjectOrSubjectFactory - Factory function to create an intermediate subject through\n * which the source sequence's elements will be multicast to the selector function\n * or Subject to push source elements into.\n * @param {Function} [selector] - Optional selector function that can use the multicasted source stream\n * as many times as needed, without causing multiple subscriptions to the source stream.\n * Subscribers to the given source will receive all notifications of the source from the\n * time of the subscription forward.\n * @return {Observable} An Observable that emits the results of invoking the selector\n * on the items emitted by a `ConnectableObservable` that shares a single subscription to\n * the underlying stream.\n * @method multicast\n * @owner Observable\n */\nexport function multicast<T, R>(subjectOrSubjectFactory: Subject<T> | (() => Subject<T>),\n                                selector?: (source: Observable<T>) => Observable<R>): OperatorFunction<T, R> {\n  return function multicastOperatorFunction(source: Observable<T>): Observable<R> {\n    let subjectFactory: () => Subject<T>;\n    if (typeof subjectOrSubjectFactory === 'function') {\n      subjectFactory = <() => Subject<T>>subjectOrSubjectFactory;\n    } else {\n      subjectFactory = function subjectFactory() {\n        return <Subject<T>>subjectOrSubjectFactory;\n      };\n    }\n\n    if (typeof selector === 'function') {\n      return source.lift(new MulticastOperator(subjectFactory, selector));\n    }\n\n    const connectable: any = Object.create(source, connectableObservableDescriptor);\n    connectable.source = source;\n    connectable.subjectFactory = subjectFactory;\n\n    return <ConnectableObservable<R>> connectable;\n  };\n}\n\nexport class MulticastOperator<T, R> implements Operator<T, R> {\n  constructor(private subjectFactory: () => Subject<T>,\n              private selector: (source: Observable<T>) => Observable<R>) {\n  }\n  call(subscriber: Subscriber<R>, source: any): any {\n    const { selector } = this;\n    const subject = this.subjectFactory();\n    const subscription = selector(subject).subscribe(subscriber);\n    subscription.add(source.subscribe(subject));\n    return subscription;\n  }\n}\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\n/* global global, define, System, Reflect, Promise */\r\nvar __extends;\r\nvar __assign;\r\nvar __rest;\r\nvar __decorate;\r\nvar __param;\r\nvar __metadata;\r\nvar __awaiter;\r\nvar __generator;\r\nvar __exportStar;\r\nvar __values;\r\nvar __read;\r\nvar __spread;\r\nvar __spreadArrays;\r\nvar __await;\r\nvar __asyncGenerator;\r\nvar __asyncDelegator;\r\nvar __asyncValues;\r\nvar __makeTemplateObject;\r\nvar __importStar;\r\nvar __importDefault;\r\nvar __classPrivateFieldGet;\r\nvar __classPrivateFieldSet;\r\nvar __createBinding;\r\n(function (factory) {\r\n    var root = typeof global === \"object\" ? global : typeof self === \"object\" ? self : typeof this === \"object\" ? this : {};\r\n    if (typeof define === \"function\" && define.amd) {\r\n        define(\"tslib\", [\"exports\"], function (exports) { factory(createExporter(root, createExporter(exports))); });\r\n    }\r\n    else if (typeof module === \"object\" && typeof module.exports === \"object\") {\r\n        factory(createExporter(root, createExporter(module.exports)));\r\n    }\r\n    else {\r\n        factory(createExporter(root));\r\n    }\r\n    function createExporter(exports, previous) {\r\n        if (exports !== root) {\r\n            if (typeof Object.create === \"function\") {\r\n                Object.defineProperty(exports, \"__esModule\", { value: true });\r\n            }\r\n            else {\r\n                exports.__esModule = true;\r\n            }\r\n        }\r\n        return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };\r\n    }\r\n})\r\n(function (exporter) {\r\n    var extendStatics = Object.setPrototypeOf ||\r\n        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n\r\n    __extends = function (d, b) {\r\n        extendStatics(d, b);\r\n        function __() { this.constructor = d; }\r\n        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n    };\r\n\r\n    __assign = Object.assign || function (t) {\r\n        for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n            s = arguments[i];\r\n            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n        }\r\n        return t;\r\n    };\r\n\r\n    __rest = function (s, e) {\r\n        var t = {};\r\n        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n            t[p] = s[p];\r\n        if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n            for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n                if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n                    t[p[i]] = s[p[i]];\r\n            }\r\n        return t;\r\n    };\r\n\r\n    __decorate = function (decorators, target, key, desc) {\r\n        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n        if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n        return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n    };\r\n\r\n    __param = function (paramIndex, decorator) {\r\n        return function (target, key) { decorator(target, key, paramIndex); }\r\n    };\r\n\r\n    __metadata = function (metadataKey, metadataValue) {\r\n        if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n    };\r\n\r\n    __awaiter = function (thisArg, _arguments, P, generator) {\r\n        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n        return new (P || (P = Promise))(function (resolve, reject) {\r\n            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n            function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n            step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n        });\r\n    };\r\n\r\n    __generator = function (thisArg, body) {\r\n        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n        return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n        function verb(n) { return function (v) { return step([n, v]); }; }\r\n        function step(op) {\r\n            if (f) throw new TypeError(\"Generator is already executing.\");\r\n            while (_) try {\r\n                if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n                if (y = 0, t) op = [op[0] & 2, t.value];\r\n                switch (op[0]) {\r\n                    case 0: case 1: t = op; break;\r\n                    case 4: _.label++; return { value: op[1], done: false };\r\n                    case 5: _.label++; y = op[1]; op = [0]; continue;\r\n                    case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n                    default:\r\n                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n                        if (t[2]) _.ops.pop();\r\n                        _.trys.pop(); continue;\r\n                }\r\n                op = body.call(thisArg, _);\r\n            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n        }\r\n    };\r\n\r\n    __createBinding = function(o, m, k, k2) {\r\n        if (k2 === undefined) k2 = k;\r\n        o[k2] = m[k];\r\n    };\r\n\r\n    __exportStar = function (m, exports) {\r\n        for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n    };\r\n\r\n    __values = function (o) {\r\n        var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n        if (m) return m.call(o);\r\n        if (o && typeof o.length === \"number\") return {\r\n            next: function () {\r\n                if (o && i >= o.length) o = void 0;\r\n                return { value: o && o[i++], done: !o };\r\n            }\r\n        };\r\n        throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n    };\r\n\r\n    __read = function (o, n) {\r\n        var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n        if (!m) return o;\r\n        var i = m.call(o), r, ar = [], e;\r\n        try {\r\n            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n        }\r\n        catch (error) { e = { error: error }; }\r\n        finally {\r\n            try {\r\n                if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n            }\r\n            finally { if (e) throw e.error; }\r\n        }\r\n        return ar;\r\n    };\r\n\r\n    __spread = function () {\r\n        for (var ar = [], i = 0; i < arguments.length; i++)\r\n            ar = ar.concat(__read(arguments[i]));\r\n        return ar;\r\n    };\r\n\r\n    __spreadArrays = function () {\r\n        for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n        for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n            for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n                r[k] = a[j];\r\n        return r;\r\n    };\r\n\r\n    __await = function (v) {\r\n        return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n    };\r\n\r\n    __asyncGenerator = function (thisArg, _arguments, generator) {\r\n        if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n        var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n        return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n        function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n        function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n        function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);  }\r\n        function fulfill(value) { resume(\"next\", value); }\r\n        function reject(value) { resume(\"throw\", value); }\r\n        function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n    };\r\n\r\n    __asyncDelegator = function (o) {\r\n        var i, p;\r\n        return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n        function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n    };\r\n\r\n    __asyncValues = function (o) {\r\n        if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n        var m = o[Symbol.asyncIterator], i;\r\n        return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n        function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n        function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n    };\r\n\r\n    __makeTemplateObject = function (cooked, raw) {\r\n        if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n        return cooked;\r\n    };\r\n\r\n    __importStar = function (mod) {\r\n        if (mod && mod.__esModule) return mod;\r\n        var result = {};\r\n        if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n        result[\"default\"] = mod;\r\n        return result;\r\n    };\r\n\r\n    __importDefault = function (mod) {\r\n        return (mod && mod.__esModule) ? mod : { \"default\": mod };\r\n    };\r\n\r\n    __classPrivateFieldGet = function (receiver, privateMap) {\r\n        if (!privateMap.has(receiver)) {\r\n            throw new TypeError(\"attempted to get private field on non-instance\");\r\n        }\r\n        return privateMap.get(receiver);\r\n    };\r\n\r\n    __classPrivateFieldSet = function (receiver, privateMap, value) {\r\n        if (!privateMap.has(receiver)) {\r\n            throw new TypeError(\"attempted to set private field on non-instance\");\r\n        }\r\n        privateMap.set(receiver, value);\r\n        return value;\r\n    };\r\n\r\n    exporter(\"__extends\", __extends);\r\n    exporter(\"__assign\", __assign);\r\n    exporter(\"__rest\", __rest);\r\n    exporter(\"__decorate\", __decorate);\r\n    exporter(\"__param\", __param);\r\n    exporter(\"__metadata\", __metadata);\r\n    exporter(\"__awaiter\", __awaiter);\r\n    exporter(\"__generator\", __generator);\r\n    exporter(\"__exportStar\", __exportStar);\r\n    exporter(\"__createBinding\", __createBinding);\r\n    exporter(\"__values\", __values);\r\n    exporter(\"__read\", __read);\r\n    exporter(\"__spread\", __spread);\r\n    exporter(\"__spreadArrays\", __spreadArrays);\r\n    exporter(\"__await\", __await);\r\n    exporter(\"__asyncGenerator\", __asyncGenerator);\r\n    exporter(\"__asyncDelegator\", __asyncDelegator);\r\n    exporter(\"__asyncValues\", __asyncValues);\r\n    exporter(\"__makeTemplateObject\", __makeTemplateObject);\r\n    exporter(\"__importStar\", __importStar);\r\n    exporter(\"__importDefault\", __importDefault);\r\n    exporter(\"__classPrivateFieldGet\", __classPrivateFieldGet);\r\n    exporter(\"__classPrivateFieldSet\", __classPrivateFieldSet);\r\n});\r\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\n/* global global, define, System, Reflect, Promise */\r\nvar __extends;\r\nvar __assign;\r\nvar __rest;\r\nvar __decorate;\r\nvar __param;\r\nvar __metadata;\r\nvar __awaiter;\r\nvar __generator;\r\nvar __exportStar;\r\nvar __values;\r\nvar __read;\r\nvar __spread;\r\nvar __spreadArrays;\r\nvar __await;\r\nvar __asyncGenerator;\r\nvar __asyncDelegator;\r\nvar __asyncValues;\r\nvar __makeTemplateObject;\r\nvar __importStar;\r\nvar __importDefault;\r\nvar __classPrivateFieldGet;\r\nvar __classPrivateFieldSet;\r\nvar __createBinding;\r\n(function (factory) {\r\n    var root = typeof global === \"object\" ? global : typeof self === \"object\" ? self : typeof this === \"object\" ? this : {};\r\n    if (typeof define === \"function\" && define.amd) {\r\n        define(\"tslib\", [\"exports\"], function (exports) { factory(createExporter(root, createExporter(exports))); });\r\n    }\r\n    else if (typeof module === \"object\" && typeof module.exports === \"object\") {\r\n        factory(createExporter(root, createExporter(module.exports)));\r\n    }\r\n    else {\r\n        factory(createExporter(root));\r\n    }\r\n    function createExporter(exports, previous) {\r\n        if (exports !== root) {\r\n            if (typeof Object.create === \"function\") {\r\n                Object.defineProperty(exports, \"__esModule\", { value: true });\r\n            }\r\n            else {\r\n                exports.__esModule = true;\r\n            }\r\n        }\r\n        return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };\r\n    }\r\n})\r\n(function (exporter) {\r\n    var extendStatics = Object.setPrototypeOf ||\r\n        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n\r\n    __extends = function (d, b) {\r\n        extendStatics(d, b);\r\n        function __() { this.constructor = d; }\r\n        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n    };\r\n\r\n    __assign = Object.assign || function (t) {\r\n        for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n            s = arguments[i];\r\n            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n        }\r\n        return t;\r\n    };\r\n\r\n    __rest = function (s, e) {\r\n        var t = {};\r\n        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n            t[p] = s[p];\r\n        if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n            for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n                if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n                    t[p[i]] = s[p[i]];\r\n            }\r\n        return t;\r\n    };\r\n\r\n    __decorate = function (decorators, target, key, desc) {\r\n        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n        if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n        return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n    };\r\n\r\n    __param = function (paramIndex, decorator) {\r\n        return function (target, key) { decorator(target, key, paramIndex); }\r\n    };\r\n\r\n    __metadata = function (metadataKey, metadataValue) {\r\n        if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n    };\r\n\r\n    __awaiter = function (thisArg, _arguments, P, generator) {\r\n        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n        return new (P || (P = Promise))(function (resolve, reject) {\r\n            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n            function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n            step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n        });\r\n    };\r\n\r\n    __generator = function (thisArg, body) {\r\n        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n        return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n        function verb(n) { return function (v) { return step([n, v]); }; }\r\n        function step(op) {\r\n            if (f) throw new TypeError(\"Generator is already executing.\");\r\n            while (_) try {\r\n                if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n                if (y = 0, t) op = [op[0] & 2, t.value];\r\n                switch (op[0]) {\r\n                    case 0: case 1: t = op; break;\r\n                    case 4: _.label++; return { value: op[1], done: false };\r\n                    case 5: _.label++; y = op[1]; op = [0]; continue;\r\n                    case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n                    default:\r\n                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n                        if (t[2]) _.ops.pop();\r\n                        _.trys.pop(); continue;\r\n                }\r\n                op = body.call(thisArg, _);\r\n            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n        }\r\n    };\r\n\r\n    __createBinding = function(o, m, k, k2) {\r\n        if (k2 === undefined) k2 = k;\r\n        o[k2] = m[k];\r\n    };\r\n\r\n    __exportStar = function (m, exports) {\r\n        for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n    };\r\n\r\n    __values = function (o) {\r\n        var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n        if (m) return m.call(o);\r\n        if (o && typeof o.length === \"number\") return {\r\n            next: function () {\r\n                if (o && i >= o.length) o = void 0;\r\n                return { value: o && o[i++], done: !o };\r\n            }\r\n        };\r\n        throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n    };\r\n\r\n    __read = function (o, n) {\r\n        var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n        if (!m) return o;\r\n        var i = m.call(o), r, ar = [], e;\r\n        try {\r\n            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n        }\r\n        catch (error) { e = { error: error }; }\r\n        finally {\r\n            try {\r\n                if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n            }\r\n            finally { if (e) throw e.error; }\r\n        }\r\n        return ar;\r\n    };\r\n\r\n    __spread = function () {\r\n        for (var ar = [], i = 0; i < arguments.length; i++)\r\n            ar = ar.concat(__read(arguments[i]));\r\n        return ar;\r\n    };\r\n\r\n    __spreadArrays = function () {\r\n        for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n        for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n            for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n                r[k] = a[j];\r\n        return r;\r\n    };\r\n\r\n    __await = function (v) {\r\n        return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n    };\r\n\r\n    __asyncGenerator = function (thisArg, _arguments, generator) {\r\n        if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n        var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n        return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n        function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n        function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n        function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);  }\r\n        function fulfill(value) { resume(\"next\", value); }\r\n        function reject(value) { resume(\"throw\", value); }\r\n        function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n    };\r\n\r\n    __asyncDelegator = function (o) {\r\n        var i, p;\r\n        return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n        function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n    };\r\n\r\n    __asyncValues = function (o) {\r\n        if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n        var m = o[Symbol.asyncIterator], i;\r\n        return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n        function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n        function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n    };\r\n\r\n    __makeTemplateObject = function (cooked, raw) {\r\n        if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n        return cooked;\r\n    };\r\n\r\n    __importStar = function (mod) {\r\n        if (mod && mod.__esModule) return mod;\r\n        var result = {};\r\n        if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n        result[\"default\"] = mod;\r\n        return result;\r\n    };\r\n\r\n    __importDefault = function (mod) {\r\n        return (mod && mod.__esModule) ? mod : { \"default\": mod };\r\n    };\r\n\r\n    __classPrivateFieldGet = function (receiver, privateMap) {\r\n        if (!privateMap.has(receiver)) {\r\n            throw new TypeError(\"attempted to get private field on non-instance\");\r\n        }\r\n        return privateMap.get(receiver);\r\n    };\r\n\r\n    __classPrivateFieldSet = function (receiver, privateMap, value) {\r\n        if (!privateMap.has(receiver)) {\r\n            throw new TypeError(\"attempted to set private field on non-instance\");\r\n        }\r\n        privateMap.set(receiver, value);\r\n        return value;\r\n    };\r\n\r\n    exporter(\"__extends\", __extends);\r\n    exporter(\"__assign\", __assign);\r\n    exporter(\"__rest\", __rest);\r\n    exporter(\"__decorate\", __decorate);\r\n    exporter(\"__param\", __param);\r\n    exporter(\"__metadata\", __metadata);\r\n    exporter(\"__awaiter\", __awaiter);\r\n    exporter(\"__generator\", __generator);\r\n    exporter(\"__exportStar\", __exportStar);\r\n    exporter(\"__createBinding\", __createBinding);\r\n    exporter(\"__values\", __values);\r\n    exporter(\"__read\", __read);\r\n    exporter(\"__spread\", __spread);\r\n    exporter(\"__spreadArrays\", __spreadArrays);\r\n    exporter(\"__await\", __await);\r\n    exporter(\"__asyncGenerator\", __asyncGenerator);\r\n    exporter(\"__asyncDelegator\", __asyncDelegator);\r\n    exporter(\"__asyncValues\", __asyncValues);\r\n    exporter(\"__makeTemplateObject\", __makeTemplateObject);\r\n    exporter(\"__importStar\", __importStar);\r\n    exporter(\"__importDefault\", __importDefault);\r\n    exporter(\"__classPrivateFieldGet\", __classPrivateFieldGet);\r\n    exporter(\"__classPrivateFieldSet\", __classPrivateFieldSet);\r\n});\r\n","export function isFunction(x: any): x is Function {\n  return typeof x === 'function';\n}\n","import { Action } from './Action';\nimport { SchedulerAction } from '../types';\nimport { Subscription } from '../Subscription';\nimport { AsyncScheduler } from './AsyncScheduler';\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class AsyncAction<T> extends Action<T> {\n\n  public id: any;\n  public state: T;\n  public delay: number;\n  protected pending: boolean = false;\n\n  constructor(protected scheduler: AsyncScheduler,\n              protected work: (this: SchedulerAction<T>, state?: T) => void) {\n    super(scheduler, work);\n  }\n\n  public schedule(state?: T, delay: number = 0): Subscription {\n\n    if (this.closed) {\n      return this;\n    }\n\n    // Always replace the current state with the new state.\n    this.state = state;\n\n    const id = this.id;\n    const scheduler = this.scheduler;\n\n    //\n    // Important implementation note:\n    //\n    // Actions only execute once by default, unless rescheduled from within the\n    // scheduled callback. This allows us to implement single and repeat\n    // actions via the same code path, without adding API surface area, as well\n    // as mimic traditional recursion but across asynchronous boundaries.\n    //\n    // However, JS runtimes and timers distinguish between intervals achieved by\n    // serial `setTimeout` calls vs. a single `setInterval` call. An interval of\n    // serial `setTimeout` calls can be individually delayed, which delays\n    // scheduling the next `setTimeout`, and so on. `setInterval` attempts to\n    // guarantee the interval callback will be invoked more precisely to the\n    // interval period, regardless of load.\n    //\n    // Therefore, we use `setInterval` to schedule single and repeat actions.\n    // If the action reschedules itself with the same delay, the interval is not\n    // canceled. If the action doesn't reschedule, or reschedules with a\n    // different delay, the interval will be canceled after scheduled callback\n    // execution.\n    //\n    if (id != null) {\n      this.id = this.recycleAsyncId(scheduler, id, delay);\n    }\n\n    // Set the pending flag indicating that this action has been scheduled, or\n    // has recursively rescheduled itself.\n    this.pending = true;\n\n    this.delay = delay;\n    // If this action has already an async Id, don't request a new one.\n    this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);\n\n    return this;\n  }\n\n  protected requestAsyncId(scheduler: AsyncScheduler, id?: any, delay: number = 0): any {\n    return setInterval(scheduler.flush.bind(scheduler, this), delay);\n  }\n\n  protected recycleAsyncId(scheduler: AsyncScheduler, id: any, delay: number = 0): any {\n    // If this action is rescheduled with the same delay time, don't clear the interval id.\n    if (delay !== null && this.delay === delay && this.pending === false) {\n      return id;\n    }\n    // Otherwise, if the action's delay time is different from the current delay,\n    // or the action has been rescheduled before it's executed, clear the interval id\n    clearInterval(id);\n    return undefined;\n  }\n\n  /**\n   * Immediately executes this action and the `work` it contains.\n   * @return {any}\n   */\n  public execute(state: T, delay: number): any {\n\n    if (this.closed) {\n      return new Error('executing a cancelled action');\n    }\n\n    this.pending = false;\n    const error = this._execute(state, delay);\n    if (error) {\n      return error;\n    } else if (this.pending === false && this.id != null) {\n      // Dequeue if the action didn't reschedule itself. Don't call\n      // unsubscribe(), because the action could reschedule later.\n      // For example:\n      // ```\n      // scheduler.schedule(function doWork(counter) {\n      //   /* ... I'm a busy worker bee ... */\n      //   var originalAction = this;\n      //   /* wait 100ms before rescheduling the action */\n      //   setTimeout(function () {\n      //     originalAction.schedule(counter + 1);\n      //   }, 100);\n      // }, 1000);\n      // ```\n      this.id = this.recycleAsyncId(this.scheduler, this.id, null);\n    }\n  }\n\n  protected _execute(state: T, delay: number): any {\n    let errored: boolean = false;\n    let errorValue: any = undefined;\n    try {\n      this.work(state);\n    } catch (e) {\n      errored = true;\n      errorValue = !!e && e || new Error(e);\n    }\n    if (errored) {\n      this.unsubscribe();\n      return errorValue;\n    }\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _unsubscribe() {\n\n    const id = this.id;\n    const scheduler = this.scheduler;\n    const actions = scheduler.actions;\n    const index = actions.indexOf(this);\n\n    this.work  = null;\n    this.state = null;\n    this.pending = false;\n    this.scheduler = null;\n\n    if (index !== -1) {\n      actions.splice(index, 1);\n    }\n\n    if (id != null) {\n      this.id = this.recycleAsyncId(scheduler, id, null);\n    }\n\n    this.delay = null;\n  }\n}\n","import { Scheduler } from '../Scheduler';\nimport { Action } from './Action';\nimport { AsyncAction } from './AsyncAction';\nimport { SchedulerAction } from '../types';\nimport { Subscription } from '../Subscription';\n\nexport class AsyncScheduler extends Scheduler {\n  public static delegate?: Scheduler;\n  public actions: Array<AsyncAction<any>> = [];\n  /**\n   * A flag to indicate whether the Scheduler is currently executing a batch of\n   * queued actions.\n   * @type {boolean}\n   * @deprecated internal use only\n   */\n  public active: boolean = false;\n  /**\n   * An internal ID used to track the latest asynchronous task such as those\n   * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and\n   * others.\n   * @type {any}\n   * @deprecated internal use only\n   */\n  public scheduled: any = undefined;\n\n  constructor(SchedulerAction: typeof Action,\n              now: () => number = Scheduler.now) {\n    super(SchedulerAction, () => {\n      if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {\n        return AsyncScheduler.delegate.now();\n      } else {\n        return now();\n      }\n    });\n  }\n\n  public schedule<T>(work: (this: SchedulerAction<T>, state?: T) => void, delay: number = 0, state?: T): Subscription {\n    if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {\n      return AsyncScheduler.delegate.schedule(work, delay, state);\n    } else {\n      return super.schedule(work, delay, state);\n    }\n  }\n\n  public flush(action: AsyncAction<any>): void {\n\n    const {actions} = this;\n\n    if (this.active) {\n      actions.push(action);\n      return;\n    }\n\n    let error: any;\n    this.active = true;\n\n    do {\n      if (error = action.execute(action.state, action.delay)) {\n        break;\n      }\n    } while (action = actions.shift()); // exhaust the scheduler queue\n\n    this.active = false;\n\n    if (error) {\n      while (action = actions.shift()) {\n        action.unsubscribe();\n      }\n      throw error;\n    }\n  }\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { subscribeToArray } from '../util/subscribeToArray';\nimport { scheduleArray } from '../scheduled/scheduleArray';\n\nexport function fromArray<T>(input: ArrayLike<T>, scheduler?: SchedulerLike) {\n  if (!scheduler) {\n    return new Observable<T>(subscribeToArray(input));\n  } else {\n    return scheduleArray(input, scheduler);\n  }\n}\n","export interface ArgumentOutOfRangeError extends Error {\n}\n\nexport interface ArgumentOutOfRangeErrorCtor {\n  new(): ArgumentOutOfRangeError;\n}\n\nconst ArgumentOutOfRangeErrorImpl = (() => {\n  function ArgumentOutOfRangeErrorImpl(this: any) {\n    Error.call(this);\n    this.message = 'argument out of range';\n    this.name = 'ArgumentOutOfRangeError';\n    return this;\n  }\n\n  ArgumentOutOfRangeErrorImpl.prototype = Object.create(Error.prototype);\n\n  return ArgumentOutOfRangeErrorImpl;\n})();\n\n/**\n * An error thrown when an element was queried at a certain index of an\n * Observable, but no such index or position exists in that sequence.\n *\n * @see {@link elementAt}\n * @see {@link take}\n * @see {@link takeLast}\n *\n * @class ArgumentOutOfRangeError\n */\nexport const ArgumentOutOfRangeError: ArgumentOutOfRangeErrorCtor = ArgumentOutOfRangeErrorImpl as any;","export interface EmptyError extends Error {\n}\n\nexport interface EmptyErrorCtor {\n  new(): EmptyError;\n}\n\nconst EmptyErrorImpl = (() => {\n  function EmptyErrorImpl(this: any) {\n    Error.call(this);\n    this.message = 'no elements in sequence';\n    this.name = 'EmptyError';\n    return this;\n  }\n\n  EmptyErrorImpl.prototype = Object.create(Error.prototype);\n\n  return EmptyErrorImpl;\n})();\n\n/**\n * An error thrown when an Observable or a sequence was queried but has no\n * elements.\n *\n * @see {@link first}\n * @see {@link last}\n * @see {@link single}\n *\n * @class EmptyError\n */\nexport const EmptyError: EmptyErrorCtor = EmptyErrorImpl as any;","export function getSymbolIterator(): symbol {\n  if (typeof Symbol !== 'function' || !Symbol.iterator) {\n    return '@@iterator' as any;\n  }\n\n  return Symbol.iterator;\n}\n\nexport const iterator = getSymbolIterator();\n\n/**\n * @deprecated use {@link iterator} instead\n */\nexport const $$iterator = iterator;\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction, MonoTypeOperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function defaultIfEmpty<T>(defaultValue?: T): MonoTypeOperatorFunction<T>;\nexport function defaultIfEmpty<T, R>(defaultValue?: R): OperatorFunction<T, T | R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Emits a given value if the source Observable completes without emitting any\n * `next` value, otherwise mirrors the source Observable.\n *\n * <span class=\"informal\">If the source Observable turns out to be empty, then\n * this operator will emit a default value.</span>\n *\n * ![](defaultIfEmpty.png)\n *\n * `defaultIfEmpty` emits the values emitted by the source Observable or a\n * specified default value if the source Observable is empty (completes without\n * having emitted any `next` value).\n *\n * ## Example\n * If no clicks happen in 5 seconds, then emit \"no clicks\"\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { defaultIfEmpty, takeUntil } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const clicksBeforeFive = clicks.pipe(takeUntil(interval(5000)));\n * const result = clicksBeforeFive.pipe(defaultIfEmpty('no clicks'));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link empty}\n * @see {@link last}\n *\n * @param {any} [defaultValue=null] The default value used if the source\n * Observable is empty.\n * @return {Observable} An Observable that emits either the specified\n * `defaultValue` if the source Observable emits no items, or the values emitted\n * by the source Observable.\n * @method defaultIfEmpty\n * @owner Observable\n */\nexport function defaultIfEmpty<T, R>(defaultValue: R = null): OperatorFunction<T, T | R> {\n  return (source: Observable<T>) => source.lift(new DefaultIfEmptyOperator(defaultValue)) as Observable<T | R>;\n}\n\nclass DefaultIfEmptyOperator<T, R> implements Operator<T, T | R> {\n\n  constructor(private defaultValue: R) {\n  }\n\n  call(subscriber: Subscriber<T | R>, source: any): any {\n    return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DefaultIfEmptySubscriber<T, R> extends Subscriber<T> {\n  private isEmpty: boolean = true;\n\n  constructor(destination: Subscriber<T | R>, private defaultValue: R) {\n    super(destination);\n  }\n\n  protected _next(value: T): void {\n    this.isEmpty = false;\n    this.destination.next(value);\n  }\n\n  protected _complete(): void {\n    if (this.isEmpty) {\n      this.destination.next(this.defaultValue);\n    }\n    this.destination.complete();\n  }\n}\n","let _enable_super_gross_mode_that_will_cause_bad_things = false;\n\n/**\n * The global configuration object for RxJS, used to configure things\n * like what Promise contructor should used to create Promises\n */\nexport const config = {\n  /**\n   * The promise constructor used by default for methods such as\n   * {@link toPromise} and {@link forEach}\n   */\n  Promise: undefined as PromiseConstructorLike,\n\n  /**\n   * If true, turns on synchronous error rethrowing, which is a deprecated behavior\n   * in v6 and higher. This behavior enables bad patterns like wrapping a subscribe\n   * call in a try/catch block. It also enables producer interference, a nasty bug\n   * where a multicast can be broken for all observers by a downstream consumer with\n   * an unhandled error. DO NOT USE THIS FLAG UNLESS IT'S NEEDED TO BY TIME\n   * FOR MIGRATION REASONS.\n   */\n  set useDeprecatedSynchronousErrorHandling(value: boolean) {\n    if (value) {\n      const error = new Error();\n      console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \\n' + error.stack);\n    } else if (_enable_super_gross_mode_that_will_cause_bad_things) {\n      console.log('RxJS: Back to a better error behavior. Thank you. <3');\n    }\n    _enable_super_gross_mode_that_will_cause_bad_things = value;\n  },\n\n  get useDeprecatedSynchronousErrorHandling() {\n    return _enable_super_gross_mode_that_will_cause_bad_things;\n  },\n};\n","export interface ObjectUnsubscribedError extends Error {\n}\n\nexport interface ObjectUnsubscribedErrorCtor {\n  new(): ObjectUnsubscribedError;\n}\n\nconst ObjectUnsubscribedErrorImpl = (() => {\n  function ObjectUnsubscribedErrorImpl(this: any) {\n    Error.call(this);\n    this.message = 'object unsubscribed';\n    this.name = 'ObjectUnsubscribedError';\n    return this;\n  }\n\n  ObjectUnsubscribedErrorImpl.prototype = Object.create(Error.prototype);\n\n  return ObjectUnsubscribedErrorImpl;\n})();\n\n/**\n * An error thrown when an action is invalid because the object has been\n * unsubscribed.\n *\n * @see {@link Subject}\n * @see {@link BehaviorSubject}\n *\n * @class ObjectUnsubscribedError\n */\nexport const ObjectUnsubscribedError: ObjectUnsubscribedErrorCtor = ObjectUnsubscribedErrorImpl as any;","import { PartialObserver } from './types';\nimport { Observable } from './Observable';\nimport { empty } from './observable/empty';\nimport { of } from './observable/of';\nimport { throwError } from './observable/throwError';\nimport { deprecate } from 'util';\n\n// TODO: When this enum is removed, replace it with a type alias. See #4556.\n/**\n * @deprecated NotificationKind is deprecated as const enums are not compatible with isolated modules. Use a string literal instead.\n */\nexport enum NotificationKind {\n  NEXT = 'N',\n  ERROR = 'E',\n  COMPLETE = 'C',\n}\n\n/**\n * Represents a push-based event or value that an {@link Observable} can emit.\n * This class is particularly useful for operators that manage notifications,\n * like {@link materialize}, {@link dematerialize}, {@link observeOn}, and\n * others. Besides wrapping the actual delivered value, it also annotates it\n * with metadata of, for instance, what type of push message it is (`next`,\n * `error`, or `complete`).\n *\n * @see {@link materialize}\n * @see {@link dematerialize}\n * @see {@link observeOn}\n *\n * @class Notification<T>\n */\nexport class Notification<T> {\n  hasValue: boolean;\n\n  constructor(public kind: 'N' | 'E' | 'C', public value?: T, public error?: any) {\n    this.hasValue = kind === 'N';\n  }\n\n  /**\n   * Delivers to the given `observer` the value wrapped by this Notification.\n   * @param {Observer} observer\n   * @return\n   */\n  observe(observer: PartialObserver<T>): any {\n    switch (this.kind) {\n      case 'N':\n        return observer.next && observer.next(this.value);\n      case 'E':\n        return observer.error && observer.error(this.error);\n      case 'C':\n        return observer.complete && observer.complete();\n    }\n  }\n\n  /**\n   * Given some {@link Observer} callbacks, deliver the value represented by the\n   * current Notification to the correctly corresponding callback.\n   * @param {function(value: T): void} next An Observer `next` callback.\n   * @param {function(err: any): void} [error] An Observer `error` callback.\n   * @param {function(): void} [complete] An Observer `complete` callback.\n   * @return {any}\n   */\n  do(next: (value: T) => void, error?: (err: any) => void, complete?: () => void): any {\n    const kind = this.kind;\n    switch (kind) {\n      case 'N':\n        return next && next(this.value);\n      case 'E':\n        return error && error(this.error);\n      case 'C':\n        return complete && complete();\n    }\n  }\n\n  /**\n   * Takes an Observer or its individual callback functions, and calls `observe`\n   * or `do` methods accordingly.\n   * @param {Observer|function(value: T): void} nextOrObserver An Observer or\n   * the `next` callback.\n   * @param {function(err: any): void} [error] An Observer `error` callback.\n   * @param {function(): void} [complete] An Observer `complete` callback.\n   * @return {any}\n   */\n  accept(nextOrObserver: PartialObserver<T> | ((value: T) => void), error?: (err: any) => void, complete?: () => void) {\n    if (nextOrObserver && typeof (<PartialObserver<T>>nextOrObserver).next === 'function') {\n      return this.observe(<PartialObserver<T>>nextOrObserver);\n    } else {\n      return this.do(<(value: T) => void>nextOrObserver, error, complete);\n    }\n  }\n\n  /**\n   * Returns a simple Observable that just delivers the notification represented\n   * by this Notification instance.\n   * @return {any}\n   */\n  toObservable(): Observable<T> {\n    const kind = this.kind;\n    switch (kind) {\n      case 'N':\n        return of(this.value);\n      case 'E':\n        return throwError(this.error);\n      case 'C':\n        return empty();\n    }\n    throw new Error('unexpected notification kind value');\n  }\n\n  private static completeNotification: Notification<any> = new Notification('C');\n  private static undefinedValueNotification: Notification<any> = new Notification('N', undefined);\n\n  /**\n   * A shortcut to create a Notification instance of the type `next` from a\n   * given value.\n   * @param {T} value The `next` value.\n   * @return {Notification<T>} The \"next\" Notification representing the\n   * argument.\n   * @nocollapse\n   */\n  static createNext<T>(value: T): Notification<T> {\n    if (typeof value !== 'undefined') {\n      return new Notification('N', value);\n    }\n    return Notification.undefinedValueNotification;\n  }\n\n  /**\n   * A shortcut to create a Notification instance of the type `error` from a\n   * given error.\n   * @param {any} [err] The `error` error.\n   * @return {Notification<T>} The \"error\" Notification representing the\n   * argument.\n   * @nocollapse\n   */\n  static createError<T>(err?: any): Notification<T> {\n    return new Notification('E', undefined, err);\n  }\n\n  /**\n   * A shortcut to create a Notification instance of the type `complete`.\n   * @return {Notification<any>} The valueless \"complete\" Notification.\n   * @nocollapse\n   */\n  static createComplete(): Notification<any> {\n    return Notification.completeNotification;\n  }\n}\n","import { SchedulerLike } from '../types';\nimport { isScheduler } from '../util/isScheduler';\nimport { fromArray } from './fromArray';\nimport { Observable } from '../Observable';\nimport { scheduleArray } from '../scheduled/scheduleArray';\n\n/* tslint:disable:max-line-length */\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T>(a: T, scheduler: SchedulerLike): Observable<T>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2>(a: T, b: T2, scheduler: SchedulerLike): Observable<T | T2>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3>(a: T, b: T2, c: T3, scheduler: SchedulerLike): Observable<T | T2 | T3>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3, T4>(a: T, b: T2, c: T3, d: T4, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3, T4, T5>(a: T, b: T2, c: T3, d: T4, e: T5, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4 | T5>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3, T4, T5, T6>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4 | T5 | T6>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3, T4, T5, T6, T7>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, scheduler: SchedulerLike):\n  Observable<T | T2 | T3 | T4 | T5 | T6 | T7>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3, T4, T5, T6, T7, T8>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8, scheduler: SchedulerLike):\n  Observable<T | T2 | T3 | T4 | T5 | T6 | T7 | T8>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3, T4, T5, T6, T7, T8, T9>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8, i: T9, scheduler: SchedulerLike):\n  Observable<T | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9>;\nexport function of<T>(...args: (T | SchedulerLike)[]): Observable<T>;\n\n// TODO(benlesh): Update the typings for this when we can switch to TS 3.x\nexport function of<T>(a: T): Observable<T>;\nexport function of<T, T2>(a: T, b: T2): Observable<T | T2>;\nexport function of<T, T2, T3>(a: T, b: T2, c: T3): Observable<T | T2 | T3>;\nexport function of<T, T2, T3, T4>(a: T, b: T2, c: T3, d: T4): Observable<T | T2 | T3 | T4>;\nexport function of<T, T2, T3, T4, T5>(a: T, b: T2, c: T3, d: T4, e: T5): Observable<T | T2 | T3 | T4 | T5>;\nexport function of<T, T2, T3, T4, T5, T6>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6): Observable<T | T2 | T3 | T4 | T5 | T6>;\nexport function of<T, T2, T3, T4, T5, T6, T7>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7):\n  Observable<T | T2 | T3 | T4 | T5 | T6 | T7>;\nexport function of<T, T2, T3, T4, T5, T6, T7, T8>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8):\n  Observable<T | T2 | T3 | T4 | T5 | T6 | T7 | T8>;\nexport function of<T, T2, T3, T4, T5, T6, T7, T8, T9>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8, i: T9):\n  Observable<T | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9>;\nexport function of<T>(...args: T[]): Observable<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Converts the arguments to an observable sequence.\n *\n * <span class=\"informal\">Each argument becomes a `next` notification.</span>\n *\n * ![](of.png)\n *\n * Unlike {@link from}, it does not do any flattening and emits each argument in whole\n * as a separate `next` notification.\n *\n * ## Examples\n *\n * Emit the values `10, 20, 30`\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * of(10, 20, 30)\n * .subscribe(\n *   next => console.log('next:', next),\n *   err => console.log('error:', err),\n *   () => console.log('the end'),\n * );\n * // result:\n * // 'next: 10'\n * // 'next: 20'\n * // 'next: 30'\n *\n * ```\n *\n * Emit the array `[1,2,3]`\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * of([1,2,3])\n * .subscribe(\n *   next => console.log('next:', next),\n *   err => console.log('error:', err),\n *   () => console.log('the end'),\n * );\n * // result:\n * // 'next: [1,2,3]'\n * ```\n *\n * @see {@link from}\n * @see {@link range}\n *\n * @param {...T} values A comma separated list of arguments you want to be emitted\n * @return {Observable} An Observable that emits the arguments\n * described above and then completes.\n * @method of\n * @owner Observable\n */\n\nexport function of<T>(...args: Array<T | SchedulerLike>): Observable<T> {\n  let scheduler = args[args.length - 1] as SchedulerLike;\n  if (isScheduler(scheduler)) {\n    args.pop();\n    return scheduleArray(args as T[], scheduler);\n  } else {\n    return fromArray(args as T[]);\n  }\n}\n","import { Subject } from './Subject';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\n\n/**\n * A variant of Subject that only emits a value when it completes. It will emit\n * its latest value to all its observers on completion.\n *\n * @class AsyncSubject<T>\n */\nexport class AsyncSubject<T> extends Subject<T> {\n  private value: T = null;\n  private hasNext: boolean = false;\n  private hasCompleted: boolean = false;\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _subscribe(subscriber: Subscriber<any>): Subscription {\n    if (this.hasError) {\n      subscriber.error(this.thrownError);\n      return Subscription.EMPTY;\n    } else if (this.hasCompleted && this.hasNext) {\n      subscriber.next(this.value);\n      subscriber.complete();\n      return Subscription.EMPTY;\n    }\n    return super._subscribe(subscriber);\n  }\n\n  next(value: T): void {\n    if (!this.hasCompleted) {\n      this.value = value;\n      this.hasNext = true;\n    }\n  }\n\n  error(error: any): void {\n    if (!this.hasCompleted) {\n      super.error(error);\n    }\n  }\n\n  complete(): void {\n    this.hasCompleted = true;\n    if (this.hasNext) {\n      super.next(this.value);\n    }\n    super.complete();\n  }\n}\n","import { ObservableInput } from '../types';\nimport { subscribeToArray } from './subscribeToArray';\nimport { subscribeToPromise } from './subscribeToPromise';\nimport { subscribeToIterable } from './subscribeToIterable';\nimport { subscribeToObservable } from './subscribeToObservable';\nimport { isArrayLike } from './isArrayLike';\nimport { isPromise } from './isPromise';\nimport { isObject } from './isObject';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { Subscription } from '../Subscription';\nimport { Subscriber } from '../Subscriber';\n\nexport const subscribeTo = <T>(result: ObservableInput<T>): (subscriber: Subscriber<T>) => Subscription | void => {\n  if (!!result && typeof result[Symbol_observable] === 'function') {\n    return subscribeToObservable(result as any);\n  } else if (isArrayLike(result)) {\n    return subscribeToArray(result);\n  } else if (isPromise(result)) {\n    return subscribeToPromise(result as Promise<any>);\n  } else if (!!result && typeof result[Symbol_iterator] === 'function') {\n    return subscribeToIterable(result as any);\n  } else {\n    const value = isObject(result) ? 'an invalid object' : `'${result}'`;\n    const msg = `You provided ${value} where a stream was expected.`\n      + ' You can provide an Observable, Promise, Array, or Iterable.';\n    throw new TypeError(msg);\n  }\n};\n","import { Observable } from '../Observable';\nimport { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';\nimport { isScheduler } from '../util/isScheduler';\nimport { of } from './of';\nimport { from } from './from';\nimport { concatAll } from '../operators/concatAll';\n\n/* tslint:disable:max-line-length */\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O1 extends ObservableInput<any>>(v1: O1, scheduler: SchedulerLike): Observable<ObservedValueOf<O1>>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(v1: O1, v2: O2, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2>>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3>>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4>>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4> | ObservedValueOf<O5>>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4> | ObservedValueOf<O5> | ObservedValueOf<O6>>;\n\nexport function concat<O1 extends ObservableInput<any>>(v1: O1): Observable<ObservedValueOf<O1>>;\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(v1: O1, v2: O2): Observable<ObservedValueOf<O1> | ObservedValueOf<O2>>;\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3>>;\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4>>;\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4> | ObservedValueOf<O5>>;\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4> | ObservedValueOf<O5> | ObservedValueOf<O6>>;\nexport function concat<O extends ObservableInput<any>>(...observables: O[]): Observable<ObservedValueOf<O>>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O extends ObservableInput<any>>(...observables: (O | SchedulerLike)[]): Observable<ObservedValueOf<O>>;\nexport function concat<R>(...observables: ObservableInput<any>[]): Observable<R>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<R>(...observables: (ObservableInput<any> | SchedulerLike)[]): Observable<R>;\n/* tslint:enable:max-line-length */\n/**\n * Creates an output Observable which sequentially emits all values from given\n * Observable and then moves on to the next.\n *\n * <span class=\"informal\">Concatenates multiple Observables together by\n * sequentially emitting their values, one Observable after the other.</span>\n *\n * ![](concat.png)\n *\n * `concat` joins multiple Observables together, by subscribing to them one at a time and\n * merging their results into the output Observable. You can pass either an array of\n * Observables, or put them directly as arguments. Passing an empty array will result\n * in Observable that completes immediately.\n *\n * `concat` will subscribe to first input Observable and emit all its values, without\n * changing or affecting them in any way. When that Observable completes, it will\n * subscribe to then next Observable passed and, again, emit its values. This will be\n * repeated, until the operator runs out of Observables. When last input Observable completes,\n * `concat` will complete as well. At any given moment only one Observable passed to operator\n * emits values. If you would like to emit values from passed Observables concurrently, check out\n * {@link merge} instead, especially with optional `concurrent` parameter. As a matter of fact,\n * `concat` is an equivalent of `merge` operator with `concurrent` parameter set to `1`.\n *\n * Note that if some input Observable never completes, `concat` will also never complete\n * and Observables following the one that did not complete will never be subscribed. On the other\n * hand, if some Observable simply completes immediately after it is subscribed, it will be\n * invisible for `concat`, which will just move on to the next Observable.\n *\n * If any Observable in chain errors, instead of passing control to the next Observable,\n * `concat` will error immediately as well. Observables that would be subscribed after\n * the one that emitted error, never will.\n *\n * If you pass to `concat` the same Observable many times, its stream of values\n * will be \"replayed\" on every subscription, which means you can repeat given Observable\n * as many times as you like. If passing the same Observable to `concat` 1000 times becomes tedious,\n * you can always use {@link repeat}.\n *\n * ## Examples\n * ### Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10\n * ```ts\n * import { concat, interval, range } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const timer = interval(1000).pipe(take(4));\n * const sequence = range(1, 10);\n * const result = concat(timer, sequence);\n * result.subscribe(x => console.log(x));\n *\n * // results in:\n * // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10\n * ```\n *\n * ### Concatenate 3 Observables\n * ```ts\n * import { concat, interval } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const timer1 = interval(1000).pipe(take(10));\n * const timer2 = interval(2000).pipe(take(6));\n * const timer3 = interval(500).pipe(take(10));\n *\n * const result = concat(timer1, timer2, timer3);\n * result.subscribe(x => console.log(x));\n *\n * // results in the following:\n * // (Prints to console sequentially)\n * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9\n * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5\n * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9\n * ```\n *\n * ### Concatenate the same Observable to repeat it\n * ```ts\n * import { concat, interval } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const timer = interval(1000).pipe(take(2));\n *\n * concat(timer, timer) // concatenating the same Observable!\n * .subscribe(\n *   value => console.log(value),\n *   err => {},\n *   () => console.log('...and it is done!')\n * );\n *\n * // Logs:\n * // 0 after 1s\n * // 1 after 2s\n * // 0 after 3s\n * // 1 after 4s\n * // \"...and it is done!\" also after 4s\n * ```\n *\n * @see {@link concatAll}\n * @see {@link concatMap}\n * @see {@link concatMapTo}\n * @see {@link startWith}\n * @see {@link endWith}\n *\n * @param {ObservableInput} input1 An input Observable to concatenate with others.\n * @param {ObservableInput} input2 An input Observable to concatenate with others.\n * More than one input Observables may be given as argument.\n * @param {SchedulerLike} [scheduler=null] An optional {@link SchedulerLike} to schedule each\n * Observable subscription on.\n * @return {Observable} All values of each passed Observable merged into a\n * single Observable, in order, in serial fashion.\n * @static true\n * @name concat\n * @owner Observable\n */\nexport function concat<O extends ObservableInput<any>, R>(...observables: Array<O | SchedulerLike>): Observable<ObservedValueOf<O> | R> {\n  return concatAll<R>()(of(...observables));\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { map } from './map';\nimport { from } from '../observable/from';\nimport { SimpleOuterSubscriber, SimpleInnerSubscriber, innerSubscribe } from '../innerSubscribe';\n\n/* tslint:disable:max-line-length */\nexport function mergeMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, concurrent?: number): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function mergeMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: undefined, concurrent?: number): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function mergeMap<T, R, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R, concurrent?: number): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link mergeAll}.</span>\n *\n * ![](mergeMap.png)\n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an Observable, and then merging those resulting Observables and\n * emitting the results of this merger.\n *\n * ## Example\n * Map and flatten each letter to an Observable ticking every 1 second\n * ```ts\n * import { of, interval } from 'rxjs';\n * import { mergeMap, map } from 'rxjs/operators';\n *\n * const letters = of('a', 'b', 'c');\n * const result = letters.pipe(\n *   mergeMap(x => interval(1000).pipe(map(i => x+i))),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // a0\n * // b0\n * // c0\n * // a1\n * // b1\n * // c1\n * // continues to list a,b,c with respective ascending integers\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaustMap}\n * @see {@link merge}\n * @see {@link mergeAll}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n * @see {@link switchMap}\n *\n * @param {function(value: T, ?index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input\n * Observables being subscribed to concurrently.\n * @return {Observable} An Observable that emits the result of applying the\n * projection function (and the optional deprecated `resultSelector`) to each item\n * emitted by the source Observable and merging the results of the Observables\n * obtained from this transformation.\n */\nexport function mergeMap<T, R, O extends ObservableInput<any>>(\n  project: (value: T, index: number) => O,\n  resultSelector?: ((outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R) | number,\n  concurrent: number = Number.POSITIVE_INFINITY\n): OperatorFunction<T, ObservedValueOf<O>|R> {\n  if (typeof resultSelector === 'function') {\n    // DEPRECATED PATH\n    return (source: Observable<T>) => source.pipe(\n      mergeMap((a, i) => from(project(a, i)).pipe(\n        map((b: any, ii: number) => resultSelector(a, b, i, ii)),\n      ), concurrent)\n    );\n  } else if (typeof resultSelector === 'number') {\n    concurrent = resultSelector;\n  }\n  return (source: Observable<T>) => source.lift(new MergeMapOperator(project, concurrent));\n}\n\nexport class MergeMapOperator<T, R> implements Operator<T, R> {\n  constructor(private project: (value: T, index: number) => ObservableInput<R>,\n              private concurrent: number = Number.POSITIVE_INFINITY) {\n  }\n\n  call(observer: Subscriber<R>, source: any): any {\n    return source.subscribe(new MergeMapSubscriber(\n      observer, this.project, this.concurrent\n    ));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class MergeMapSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n  private hasCompleted: boolean = false;\n  private buffer: T[] = [];\n  private active: number = 0;\n  protected index: number = 0;\n\n  constructor(destination: Subscriber<R>,\n              private project: (value: T, index: number) => ObservableInput<R>,\n              private concurrent: number = Number.POSITIVE_INFINITY) {\n    super(destination);\n  }\n\n  protected _next(value: T): void {\n    if (this.active < this.concurrent) {\n      this._tryNext(value);\n    } else {\n      this.buffer.push(value);\n    }\n  }\n\n  protected _tryNext(value: T) {\n    let result: ObservableInput<R>;\n    const index = this.index++;\n    try {\n      result = this.project(value, index);\n    } catch (err) {\n      this.destination.error!(err);\n      return;\n    }\n    this.active++;\n    this._innerSub(result);\n  }\n\n  private _innerSub(ish: ObservableInput<R>): void {\n    const innerSubscriber = new SimpleInnerSubscriber(this);\n    const destination = this.destination as Subscription;\n    destination.add(innerSubscriber);\n    const innerSubscription = innerSubscribe(ish, innerSubscriber);\n    // The returned subscription will usually be the subscriber that was\n    // passed. However, interop subscribers will be wrapped and for\n    // unsubscriptions to chain correctly, the wrapper needs to be added, too.\n    if (innerSubscription !== innerSubscriber) {\n      destination.add(innerSubscription);\n    }\n  }\n\n  protected _complete(): void {\n    this.hasCompleted = true;\n    if (this.active === 0 && this.buffer.length === 0) {\n      this.destination.complete!();\n    }\n    this.unsubscribe();\n  }\n\n  notifyNext(innerValue: R): void {\n    this.destination.next!(innerValue);\n  }\n\n  notifyComplete(): void {\n    const buffer = this.buffer;\n    this.active--;\n    if (buffer.length > 0) {\n      this._next(buffer.shift()!);\n    } else if (this.active === 0 && this.hasCompleted) {\n      this.destination.complete!();\n    }\n  }\n}\n\n/**\n * @deprecated renamed. Use {@link mergeMap}\n */\nexport const flatMap = mergeMap;","import { isArray } from './isArray';\n\nexport function isNumeric(val: any): val is number | string {\n  // parseFloat NaNs numeric-cast false positives (null|true|false|\"\")\n  // ...but misinterprets leading-number strings, particularly hex literals (\"0x...\")\n  // subtraction forces infinities to NaN\n  // adding 1 corrects loss of precision from parseFloat (#15100)\n  return !isArray(val) && (val - parseFloat(val) + 1) >= 0;\n}\n","import { EmptyError } from '../util/EmptyError';\nimport { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { TeardownLogic, MonoTypeOperatorFunction } from '../types';\n\n/**\n * If the source observable completes without emitting a value, it will emit\n * an error. The error will be created at that time by the optional\n * `errorFactory` argument, otherwise, the error will be {@link EmptyError}.\n *\n * ![](throwIfEmpty.png)\n *\n * ## Example\n * ```ts\n * import { fromEvent, timer } from 'rxjs';\n * import { throwIfEmpty, takeUntil } from 'rxjs/operators';\n *\n * const click$ = fromEvent(document, 'click');\n *\n * click$.pipe(\n *   takeUntil(timer(1000)),\n *   throwIfEmpty(\n *     () => new Error('the document was not clicked within 1 second')\n *   ),\n * )\n * .subscribe({\n *   next() { console.log('The button was clicked'); },\n *   error(err) { console.error(err); }\n * });\n * ```\n *\n * @param errorFactory A factory function called to produce the\n * error to be thrown when the source observable completes without emitting a\n * value.\n */\nexport function throwIfEmpty <T>(errorFactory: (() => any) = defaultErrorFactory): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => {\n    return source.lift(new ThrowIfEmptyOperator(errorFactory));\n  };\n}\n\nclass ThrowIfEmptyOperator<T> implements Operator<T, T> {\n  constructor(private errorFactory: () => any) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new ThrowIfEmptySubscriber(subscriber, this.errorFactory));\n  }\n}\n\nclass ThrowIfEmptySubscriber<T> extends Subscriber<T> {\n  private hasValue: boolean = false;\n\n  constructor(destination: Subscriber<T>, private errorFactory: () => any) {\n    super(destination);\n  }\n\n  protected _next(value: T): void {\n    this.hasValue = true;\n    this.destination.next(value);\n  }\n\n  protected _complete() {\n    if (!this.hasValue) {\n      let err: any;\n      try {\n        err = this.errorFactory();\n      } catch (e) {\n        err = e;\n      }\n      this.destination.error(err);\n    } else {\n        return this.destination.complete();\n    }\n  }\n}\n\nfunction defaultErrorFactory() {\n  return new EmptyError();\n}\n","import { Observable } from '../Observable';\nimport { scan } from './scan';\nimport { takeLast } from './takeLast';\nimport { defaultIfEmpty } from './defaultIfEmpty';\nimport { OperatorFunction, MonoTypeOperatorFunction } from '../types';\nimport { pipe } from '../util/pipe';\n\n/* tslint:disable:max-line-length */\nexport function reduce<T, R>(accumulator: (acc: R, value: T, index: number) => R, seed: R): OperatorFunction<T, R>;\nexport function reduce<T>(accumulator: (acc: T, value: T, index: number) => T, seed?: T): MonoTypeOperatorFunction<T>;\nexport function reduce<T, R>(accumulator: (acc: R, value: T, index: number) => R): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Applies an accumulator function over the source Observable, and returns the\n * accumulated result when the source completes, given an optional seed value.\n *\n * <span class=\"informal\">Combines together all values emitted on the source,\n * using an accumulator function that knows how to join a new source value into\n * the accumulation from the past.</span>\n *\n * ![](reduce.png)\n *\n * Like\n * [Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce),\n * `reduce` applies an `accumulator` function against an accumulation and each\n * value of the source Observable (from the past) to reduce it to a single\n * value, emitted on the output Observable. Note that `reduce` will only emit\n * one value, only when the source Observable completes. It is equivalent to\n * applying operator {@link scan} followed by operator {@link last}.\n *\n * Returns an Observable that applies a specified `accumulator` function to each\n * item emitted by the source Observable. If a `seed` value is specified, then\n * that value will be used as the initial value for the accumulator. If no seed\n * value is specified, the first item of the source is used as the seed.\n *\n * ## Example\n * Count the number of click events that happened in 5 seconds\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { reduce, takeUntil, mapTo } from 'rxjs/operators';\n *\n * const clicksInFiveSeconds = fromEvent(document, 'click').pipe(\n *   takeUntil(interval(5000)),\n * );\n * const ones = clicksInFiveSeconds.pipe(mapTo(1));\n * const seed = 0;\n * const count = ones.pipe(reduce((acc, one) => acc + one, seed));\n * count.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link count}\n * @see {@link expand}\n * @see {@link mergeScan}\n * @see {@link scan}\n *\n * @param {function(acc: R, value: T, index: number): R} accumulator The accumulator function\n * called on each source value.\n * @param {R} [seed] The initial accumulation value.\n * @return {Observable<R>} An Observable that emits a single value that is the\n * result of accumulating the values emitted by the source Observable.\n * @method reduce\n * @owner Observable\n */\nexport function reduce<T, R>(accumulator: (acc: T | R, value: T, index?: number) => T | R, seed?: T | R): OperatorFunction<T, T | R> {\n  // providing a seed of `undefined` *should* be valid and trigger\n  // hasSeed! so don't use `seed !== undefined` checks!\n  // For this reason, we have to check it here at the original call site\n  // otherwise inside Operator/Subscriber we won't know if `undefined`\n  // means they didn't provide anything or if they literally provided `undefined`\n  if (arguments.length >= 2) {\n    return function reduceOperatorFunctionWithSeed(source: Observable<T>): Observable<T | R> {\n      return pipe(scan(accumulator, seed), takeLast(1), defaultIfEmpty(seed))(source);\n    };\n  }\n  return function reduceOperatorFunction(source: Observable<T>): Observable<T | R> {\n    return pipe(\n      scan<T, T | R>((acc, value, index) => accumulator(acc, value, index + 1)),\n      takeLast(1),\n    )(source);\n  };\n}\n","import { Subscriber } from '../Subscriber';\nimport { Subject } from '../Subject';\n\n/**\n * Determines whether the ErrorObserver is closed or stopped or has a\n * destination that is closed or stopped - in which case errors will\n * need to be reported via a different mechanism.\n * @param observer the observer\n */\nexport function canReportError(observer: Subscriber<any> | Subject<any>): boolean {\n  while (observer) {\n    const { closed, destination, isStopped } = observer as any;\n    if (closed || isStopped) {\n      return false;\n    } else if (destination && destination instanceof Subscriber) {\n      observer = destination;\n    } else {\n      observer = null;\n    }\n  }\n  return true;\n}\n","/**\n * Throws an error on another job so that it's picked up by the runtime's\n * uncaught error handling mechanism.\n * @param err the error to throw\n */\nexport function hostReportError(err: any) {\n  setTimeout(() => { throw err; }, 0);\n}","export function isObject(x: any): x is Object {\n  return x !== null && typeof x === 'object';\n}\n","/** @deprecated do not use, this is no longer checked by RxJS internals */\nexport const rxSubscriber = (() =>\n  typeof Symbol === 'function'\n    ? Symbol('rxSubscriber')\n    : '@@rxSubscriber_' + Math.random())();\n\n/**\n * @deprecated use rxSubscriber instead\n */\nexport const $$rxSubscriber = rxSubscriber;\n","import { noop } from './noop';\nimport { identity } from './identity';\nimport { UnaryFunction } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function pipe<T>(): UnaryFunction<T, T>;\nexport function pipe<T, A>(fn1: UnaryFunction<T, A>): UnaryFunction<T, A>;\nexport function pipe<T, A, B>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>): UnaryFunction<T, B>;\nexport function pipe<T, A, B, C>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>): UnaryFunction<T, C>;\nexport function pipe<T, A, B, C, D>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>): UnaryFunction<T, D>;\nexport function pipe<T, A, B, C, D, E>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>): UnaryFunction<T, E>;\nexport function pipe<T, A, B, C, D, E, F>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>): UnaryFunction<T, F>;\nexport function pipe<T, A, B, C, D, E, F, G>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>): UnaryFunction<T, G>;\nexport function pipe<T, A, B, C, D, E, F, G, H>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>, fn8: UnaryFunction<G, H>): UnaryFunction<T, H>;\nexport function pipe<T, A, B, C, D, E, F, G, H, I>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>, fn8: UnaryFunction<G, H>, fn9: UnaryFunction<H, I>): UnaryFunction<T, I>;\nexport function pipe<T, A, B, C, D, E, F, G, H, I>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>, fn8: UnaryFunction<G, H>, fn9: UnaryFunction<H, I>, ...fns: UnaryFunction<any, any>[]): UnaryFunction<T, {}>;\n/* tslint:enable:max-line-length */\n\nexport function pipe(...fns: Array<UnaryFunction<any, any>>): UnaryFunction<any, any> {\n  return pipeFromArray(fns);\n}\n\n/** @internal */\nexport function pipeFromArray<T, R>(fns: Array<UnaryFunction<T, R>>): UnaryFunction<T, R> {\n  if (fns.length === 0) {\n    return identity as UnaryFunction<any, any>;\n  }\n\n  if (fns.length === 1) {\n    return fns[0];\n  }\n\n  return function piped(input: T): R {\n    return fns.reduce((prev: any, fn: UnaryFunction<T, R>) => fn(prev), input as any);\n  };\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\nimport { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { Observable } from '../Observable';\n\n/**\n * Make a {@link ConnectableObservable} behave like a ordinary observable and automates the way\n * you can connect to it.\n *\n * Internally it counts the subscriptions to the observable and subscribes (only once) to the source if\n * the number of subscriptions is larger than 0. If the number of subscriptions is smaller than 1, it\n * unsubscribes from the source. This way you can make sure that everything before the *published*\n * refCount has only a single subscription independently of the number of subscribers to the target\n * observable.\n *\n * Note that using the {@link share} operator is exactly the same as using the *publish* operator\n * (making the observable hot) and the *refCount* operator in a sequence.\n *\n * ![](refCount.png)\n *\n * ## Example\n *\n * In the following example there are two intervals turned into connectable observables\n * by using the *publish* operator. The first one uses the *refCount* operator, the\n * second one does not use it. You will notice that a connectable observable does nothing\n * until you call its connect function.\n *\n * ```ts\n * import { interval } from 'rxjs';\n * import { tap, publish, refCount } from 'rxjs/operators';\n *\n * // Turn the interval observable into a ConnectableObservable (hot)\n * const refCountInterval = interval(400).pipe(\n *   tap((num) => console.log(`refCount ${num}`)),\n *   publish(),\n *   refCount()\n * );\n *\n * const publishedInterval = interval(400).pipe(\n *   tap((num) => console.log(`publish ${num}`)),\n *   publish()\n * );\n *\n * refCountInterval.subscribe();\n * refCountInterval.subscribe();\n * // 'refCount 0' -----> 'refCount 1' -----> etc\n * // All subscriptions will receive the same value and the tap (and\n * // every other operator) before the publish operator will be executed\n * // only once per event independently of the number of subscriptions.\n *\n * publishedInterval.subscribe();\n * // Nothing happens until you call .connect() on the observable.\n * ```\n *\n * @see {@link ConnectableObservable}\n * @see {@link share}\n * @see {@link publish}\n */\nexport function refCount<T>(): MonoTypeOperatorFunction<T> {\n  return function refCountOperatorFunction(source: ConnectableObservable<T>): Observable<T> {\n    return source.lift(new RefCountOperator(source));\n  } as MonoTypeOperatorFunction<T>;\n}\n\nclass RefCountOperator<T> implements Operator<T, T> {\n  constructor(private connectable: ConnectableObservable<T>) {\n  }\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n\n    const { connectable } = this;\n    (<any> connectable)._refCount++;\n\n    const refCounter = new RefCountSubscriber(subscriber, connectable);\n    const subscription = source.subscribe(refCounter);\n\n    if (!refCounter.closed) {\n      (<any> refCounter).connection = connectable.connect();\n    }\n\n    return subscription;\n  }\n}\n\nclass RefCountSubscriber<T> extends Subscriber<T> {\n\n  private connection: Subscription;\n\n  constructor(destination: Subscriber<T>,\n              private connectable: ConnectableObservable<T>) {\n    super(destination);\n  }\n\n  protected _unsubscribe() {\n\n    const { connectable } = this;\n    if (!connectable) {\n      this.connection = null;\n      return;\n    }\n\n    this.connectable = null;\n    const refCount = (<any> connectable)._refCount;\n    if (refCount <= 0) {\n      this.connection = null;\n      return;\n    }\n\n    (<any> connectable)._refCount = refCount - 1;\n    if (refCount > 1) {\n      this.connection = null;\n      return;\n    }\n\n    ///\n    // Compare the local RefCountSubscriber's connection Subscription to the\n    // connection Subscription on the shared ConnectableObservable. In cases\n    // where the ConnectableObservable source synchronously emits values, and\n    // the RefCountSubscriber's downstream Observers synchronously unsubscribe,\n    // execution continues to here before the RefCountOperator has a chance to\n    // supply the RefCountSubscriber with the shared connection Subscription.\n    // For example:\n    // ```\n    // range(0, 10).pipe(\n    //   publish(),\n    //   refCount(),\n    //   take(5),\n    // )\n    // .subscribe();\n    // ```\n    // In order to account for this case, RefCountSubscriber should only dispose\n    // the ConnectableObservable's shared connection Subscription if the\n    // connection Subscription exists, *and* either:\n    //   a. RefCountSubscriber doesn't have a reference to the shared connection\n    //      Subscription yet, or,\n    //   b. RefCountSubscriber's connection Subscription reference is identical\n    //      to the shared connection Subscription\n    ///\n    const { connection } = this;\n    const sharedConnection = (<any> connectable)._connection;\n    this.connection = null;\n\n    if (sharedConnection && (!connection || sharedConnection === connection)) {\n      sharedConnection.unsubscribe();\n    }\n  }\n}\n","import { Subject } from './Subject';\nimport { SchedulerLike } from './types';\nimport { queue } from './scheduler/queue';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { ObserveOnSubscriber } from './operators/observeOn';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nimport { SubjectSubscription } from './SubjectSubscription';\n/**\n * A variant of Subject that \"replays\" or emits old values to new subscribers.\n * It buffers a set number of values and will emit those values immediately to\n * any new subscribers in addition to emitting new values to existing subscribers.\n *\n * @class ReplaySubject<T>\n */\nexport class ReplaySubject<T> extends Subject<T> {\n  private _events: (ReplayEvent<T> | T)[] = [];\n  private _bufferSize: number;\n  private _windowTime: number;\n  private _infiniteTimeWindow: boolean = false;\n\n  constructor(bufferSize: number = Number.POSITIVE_INFINITY,\n              windowTime: number = Number.POSITIVE_INFINITY,\n              private scheduler?: SchedulerLike) {\n    super();\n    this._bufferSize = bufferSize < 1 ? 1 : bufferSize;\n    this._windowTime = windowTime < 1 ? 1 : windowTime;\n\n    if (windowTime === Number.POSITIVE_INFINITY) {\n      this._infiniteTimeWindow = true;\n      this.next = this.nextInfiniteTimeWindow;\n    } else {\n      this.next = this.nextTimeWindow;\n    }\n  }\n\n  private nextInfiniteTimeWindow(value: T): void {\n    if (!this.isStopped) {\n      const _events = this._events;\n      _events.push(value);\n      // Since this method is invoked in every next() call than the buffer\n      // can overgrow the max size only by one item\n      if (_events.length > this._bufferSize) {\n        _events.shift();\n      }\n    }\n    super.next(value);\n  }\n\n  private nextTimeWindow(value: T): void {\n    if (!this.isStopped) {\n      this._events.push(new ReplayEvent(this._getNow(), value));\n      this._trimBufferThenGetEvents();\n    }\n    super.next(value);\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _subscribe(subscriber: Subscriber<T>): Subscription {\n    // When `_infiniteTimeWindow === true` then the buffer is already trimmed\n    const _infiniteTimeWindow = this._infiniteTimeWindow;\n    const _events = _infiniteTimeWindow ? this._events : this._trimBufferThenGetEvents();\n    const scheduler = this.scheduler;\n    const len = _events.length;\n    let subscription: Subscription;\n\n    if (this.closed) {\n      throw new ObjectUnsubscribedError();\n    } else if (this.isStopped || this.hasError) {\n      subscription = Subscription.EMPTY;\n    } else {\n      this.observers.push(subscriber);\n      subscription = new SubjectSubscription(this, subscriber);\n    }\n\n    if (scheduler) {\n      subscriber.add(subscriber = new ObserveOnSubscriber<T>(subscriber, scheduler));\n    }\n\n    if (_infiniteTimeWindow) {\n      for (let i = 0; i < len && !subscriber.closed; i++) {\n        subscriber.next(<T>_events[i]);\n      }\n    } else {\n      for (let i = 0; i < len && !subscriber.closed; i++) {\n        subscriber.next((<ReplayEvent<T>>_events[i]).value);\n      }\n    }\n\n    if (this.hasError) {\n      subscriber.error(this.thrownError);\n    } else if (this.isStopped) {\n      subscriber.complete();\n    }\n\n    return subscription;\n  }\n\n  _getNow(): number {\n    return (this.scheduler || queue).now();\n  }\n\n  private _trimBufferThenGetEvents(): ReplayEvent<T>[] {\n    const now = this._getNow();\n    const _bufferSize = this._bufferSize;\n    const _windowTime = this._windowTime;\n    const _events = <ReplayEvent<T>[]>this._events;\n\n    const eventsCount = _events.length;\n    let spliceCount = 0;\n\n    // Trim events that fall out of the time window.\n    // Start at the front of the list. Break early once\n    // we encounter an event that falls within the window.\n    while (spliceCount < eventsCount) {\n      if ((now - _events[spliceCount].time) < _windowTime) {\n        break;\n      }\n      spliceCount++;\n    }\n\n    if (eventsCount > _bufferSize) {\n      spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);\n    }\n\n    if (spliceCount > 0) {\n      _events.splice(0, spliceCount);\n    }\n\n    return _events;\n  }\n\n}\n\nclass ReplayEvent<T> {\n  constructor(public time: number, public value: T) {\n  }\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscription } from '../Subscription';\n\nexport function scheduleArray<T>(input: ArrayLike<T>, scheduler: SchedulerLike) {\n  return new Observable<T>(subscriber => {\n    const sub = new Subscription();\n    let i = 0;\n    sub.add(scheduler.schedule(function () {\n      if (i === input.length) {\n        subscriber.complete();\n        return;\n      }\n      subscriber.next(input[i++]);\n      if (!subscriber.closed) {\n        sub.add(this.schedule());\n      }\n    }));\n    return sub;\n  });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscriber } from '../Subscriber';\n\n/**\n * Creates an Observable that emits no items to the Observer and immediately\n * emits an error notification.\n *\n * <span class=\"informal\">Just emits 'error', and nothing else.\n * </span>\n *\n * ![](throw.png)\n *\n * This static operator is useful for creating a simple Observable that only\n * emits the error notification. It can be used for composing with other\n * Observables, such as in a {@link mergeMap}.\n *\n * ## Examples\n * ### Emit the number 7, then emit an error\n * ```ts\n * import { throwError, concat, of } from 'rxjs';\n *\n * const result = concat(of(7), throwError(new Error('oops!')));\n * result.subscribe(x => console.log(x), e => console.error(e));\n *\n * // Logs:\n * // 7\n * // Error: oops!\n * ```\n *\n * ---\n *\n * ### Map and flatten numbers to the sequence 'a', 'b', 'c', but throw an error for 2\n * ```ts\n * import { throwError, interval, of } from 'rxjs';\n * import { mergeMap } from 'rxjs/operators';\n *\n * interval(1000).pipe(\n *   mergeMap(x => x === 2\n *     ? throwError('Twos are bad')\n *     : of('a', 'b', 'c')\n *   ),\n * ).subscribe(x => console.log(x), e => console.error(e));\n *\n * // Logs:\n * // a\n * // b\n * // c\n * // a\n * // b\n * // c\n * // Twos are bad\n * ```\n *\n * @see {@link Observable}\n * @see {@link empty}\n * @see {@link never}\n * @see {@link of}\n *\n * @param {any} error The particular Error to pass to the error notification.\n * @param {SchedulerLike} [scheduler] A {@link SchedulerLike} to use for scheduling\n * the emission of the error notification.\n * @return {Observable} An error Observable: emits only the error notification\n * using the given error argument.\n * @static true\n * @name throwError\n * @owner Observable\n */\nexport function throwError(error: any, scheduler?: SchedulerLike): Observable<never> {\n  if (!scheduler) {\n    return new Observable(subscriber => subscriber.error(error));\n  } else {\n    return new Observable(subscriber => scheduler.schedule(dispatch, 0, { error, subscriber }));\n  }\n}\n\ninterface DispatchArg {\n  error: any;\n  subscriber: Subscriber<any>;\n}\n\nfunction dispatch({ error, subscriber }: DispatchArg) {\n  subscriber.error(error);\n}\n","/* tslint:disable:no-empty */\nexport function noop() { }\n","import { Observable } from '../Observable';\nimport { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';\nimport { isScheduler  } from '../util/isScheduler';\nimport { isArray  } from '../util/isArray';\nimport { Subscriber } from '../Subscriber';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { Operator } from '../Operator';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { fromArray } from './fromArray';\n\nconst NONE = {};\n\n/* tslint:disable:max-line-length */\n\n// If called with a single array, it \"auto-spreads\" the array, with result selector\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest<O1 extends ObservableInput<any>, R>(sources: [O1], resultSelector: (v1: ObservedValueOf<O1>) => R, scheduler?: SchedulerLike): Observable<R>;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, R>(sources: [O1, O2], resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>) => R, scheduler?: SchedulerLike): Observable<R>;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, R>(sources: [O1, O2, O3], resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>) => R, scheduler?: SchedulerLike): Observable<R>;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, R>(sources: [O1, O2, O3, O4], resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>) => R, scheduler?: SchedulerLike): Observable<R>;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, R>(sources: [O1, O2, O3, O4, O5], resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>, v5: ObservedValueOf<O5>) => R, scheduler?: SchedulerLike): Observable<R>;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>, R>(sources: [O1, O2, O3, O4, O5, O6], resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>, v5: ObservedValueOf<O5>, v6: ObservedValueOf<O6>) => R, scheduler?: SchedulerLike): Observable<R>;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest<O extends ObservableInput<any>, R>(sources: O[], resultSelector: (...args: ObservedValueOf<O>[]) => R, scheduler?: SchedulerLike): Observable<R>;\n\n// standard call, but with a result selector\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest<O1 extends ObservableInput<any>, R>(v1: O1, resultSelector: (v1: ObservedValueOf<O1>) => R, scheduler?: SchedulerLike): Observable<R>;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, R>(v1: O1, v2: O2, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>) => R, scheduler?: SchedulerLike): Observable<R>;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>) => R, scheduler?: SchedulerLike): Observable<R>;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, v4: O4, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>) => R, scheduler?: SchedulerLike): Observable<R>;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>, v5: ObservedValueOf<O5>) => R, scheduler?: SchedulerLike): Observable<R>;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>, v5: ObservedValueOf<O5>, v6: ObservedValueOf<O6>) => R, scheduler?: SchedulerLike): Observable<R>;\n\n// With a scheduler (deprecated)\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest<O1 extends ObservableInput<any>>(sources: [O1], scheduler: SchedulerLike): Observable<[ObservedValueOf<O1>]>;\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(sources: [O1, O2], scheduler: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>]>;\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(sources: [O1, O2, O3], scheduler: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>]>;\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(sources: [O1, O2, O3, O4], scheduler: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>]>;\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(sources: [O1, O2, O3, O4, O5], scheduler: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>]>;\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(sources: [O1, O2, O3, O4, O5, O6], scheduler: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>, ObservedValueOf<O6>]>;\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest<O extends ObservableInput<any>>(sources: O[], scheduler: SchedulerLike): Observable<ObservedValueOf<O>[]>;\n\n// Best case\nexport function combineLatest<O1 extends ObservableInput<any>>(sources: [O1]): Observable<[ObservedValueOf<O1>]>;\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(sources: [O1, O2]): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>]>;\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(sources: [O1, O2, O3]): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>]>;\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(sources: [O1, O2, O3, O4]): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>]>;\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(sources: [O1, O2, O3, O4, O5]): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>]>;\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(sources: [O1, O2, O3, O4, O5, O6]): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>, ObservedValueOf<O6>]>;\nexport function combineLatest<O extends ObservableInput<any>>(sources: O[]): Observable<ObservedValueOf<O>[]>;\n\n// Standard calls\n/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */\nexport function combineLatest<O1 extends ObservableInput<any>>(v1: O1, scheduler?: SchedulerLike): Observable<[ObservedValueOf<O1>]>;\n/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(v1: O1, v2: O2, scheduler?: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>]>;\n/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, scheduler?: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>]>;\n/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, scheduler?: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>]>;\n/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, scheduler?: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>]>;\n/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */\nexport function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6, scheduler?: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>, ObservedValueOf<O6>]>;\n\n/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */\nexport function combineLatest<O extends ObservableInput<any>>(...observables: O[]): Observable<any[]>;\n\n/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */\nexport function combineLatest<O extends ObservableInput<any>, R>(...observables: Array<ObservableInput<any> | ((...values: Array<any>) => R)>): Observable<R>;\n\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest<O extends ObservableInput<any>, R>(array: O[], resultSelector: (...values: ObservedValueOf<O>[]) => R, scheduler?: SchedulerLike): Observable<R>;\n\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest<O extends ObservableInput<any>>(...observables: Array<O | SchedulerLike>): Observable<any[]>;\n\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest<O extends ObservableInput<any>, R>(...observables: Array<O | ((...values: ObservedValueOf<O>[]) => R) | SchedulerLike>): Observable<R>;\n\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest<R>(...observables: Array<ObservableInput<any> | ((...values: Array<any>) => R) | SchedulerLike>): Observable<R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Combines multiple Observables to create an Observable whose values are\n * calculated from the latest values of each of its input Observables.\n *\n * <span class=\"informal\">Whenever any input Observable emits a value, it\n * computes a formula using the latest values from all the inputs, then emits\n * the output of that formula.</span>\n *\n * ![](combineLatest.png)\n *\n * `combineLatest` combines the values from all the Observables passed as\n * arguments. This is done by subscribing to each Observable in order and,\n * whenever any Observable emits, collecting an array of the most recent\n * values from each Observable. So if you pass `n` Observables to operator,\n * returned Observable will always emit an array of `n` values, in order\n * corresponding to order of passed Observables (value from the first Observable\n * on the first place and so on).\n *\n * Static version of `combineLatest` accepts either an array of Observables\n * or each Observable can be put directly as an argument. Note that array of\n * Observables is good choice, if you don't know beforehand how many Observables\n * you will combine. Passing empty array will result in Observable that\n * completes immediately.\n *\n * To ensure output array has always the same length, `combineLatest` will\n * actually wait for all input Observables to emit at least once,\n * before it starts emitting results. This means if some Observable emits\n * values before other Observables started emitting, all these values but the last\n * will be lost. On the other hand, if some Observable does not emit a value but\n * completes, resulting Observable will complete at the same moment without\n * emitting anything, since it will be now impossible to include value from\n * completed Observable in resulting array. Also, if some input Observable does\n * not emit any value and never completes, `combineLatest` will also never emit\n * and never complete, since, again, it will wait for all streams to emit some\n * value.\n *\n * If at least one Observable was passed to `combineLatest` and all passed Observables\n * emitted something, resulting Observable will complete when all combined\n * streams complete. So even if some Observable completes, result of\n * `combineLatest` will still emit values when other Observables do. In case\n * of completed Observable, its value from now on will always be the last\n * emitted value. On the other hand, if any Observable errors, `combineLatest`\n * will error immediately as well, and all other Observables will be unsubscribed.\n *\n * `combineLatest` accepts as optional parameter `project` function, which takes\n * as arguments all values that would normally be emitted by resulting Observable.\n * `project` can return any kind of value, which will be then emitted by Observable\n * instead of default array. Note that `project` does not take as argument that array\n * of values, but values themselves. That means default `project` can be imagined\n * as function that takes all its arguments and puts them into an array.\n *\n * ## Examples\n * ### Combine two timer Observables\n * ```ts\n * import { combineLatest, timer } from 'rxjs';\n *\n * const firstTimer = timer(0, 1000); // emit 0, 1, 2... after every second, starting from now\n * const secondTimer = timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now\n * const combinedTimers = combineLatest(firstTimer, secondTimer);\n * combinedTimers.subscribe(value => console.log(value));\n * // Logs\n * // [0, 0] after 0.5s\n * // [1, 0] after 1s\n * // [1, 1] after 1.5s\n * // [2, 1] after 2s\n * ```\n *\n * ### Combine an array of Observables\n * ```ts\n * import { combineLatest, of } from 'rxjs';\n * import { delay, starWith } from 'rxjs/operators';\n *\n * const observables = [1, 5, 10].map(\n *   n => of(n).pipe(\n *     delay(n * 1000),   // emit 0 and then emit n after n seconds\n *     startWith(0),\n *   )\n * );\n * const combined = combineLatest(observables);\n * combined.subscribe(value => console.log(value));\n * // Logs\n * // [0, 0, 0] immediately\n * // [1, 0, 0] after 1s\n * // [1, 5, 0] after 5s\n * // [1, 5, 10] after 10s\n * ```\n *\n *\n * ### Use project function to dynamically calculate the Body-Mass Index\n * ```ts\n * import { combineLatest, of } from 'rxjs';\n * import { map } from 'rxjs/operators';\n *\n * const weight = of(70, 72, 76, 79, 75);\n * const height = of(1.76, 1.77, 1.78);\n * const bmi = combineLatest(weight, height).pipe(\n *   map(([w, h]) => w / (h * h)),\n * );\n * bmi.subscribe(x => console.log('BMI is ' + x));\n *\n * // With output to console:\n * // BMI is 24.212293388429753\n * // BMI is 23.93948099205209\n * // BMI is 23.671253629592222\n * ```\n *\n * @see {@link combineAll}\n * @see {@link merge}\n * @see {@link withLatestFrom}\n *\n * @param {ObservableInput} observable1 An input Observable to combine with other Observables.\n * @param {ObservableInput} observable2 An input Observable to combine with other Observables.\n * More than one input Observables may be given as arguments\n * or an array of Observables may be given as the first argument.\n * @param {function} [project] An optional function to project the values from\n * the combined latest values into a new value on the output Observable.\n * @param {SchedulerLike} [scheduler=null] The {@link SchedulerLike} to use for subscribing to\n * each input Observable.\n * @return {Observable} An Observable of projected values from the most recent\n * values from each input Observable, or an array of the most recent values from\n * each input Observable.\n */\nexport function combineLatest<O extends ObservableInput<any>, R>(\n  ...observables: (O | ((...values: ObservedValueOf<O>[]) => R) | SchedulerLike)[]\n): Observable<R> {\n  let resultSelector: ((...values: Array<any>) => R) | undefined =  undefined;\n  let scheduler: SchedulerLike|undefined = undefined;\n\n  if (isScheduler(observables[observables.length - 1])) {\n    scheduler = observables.pop() as SchedulerLike;\n  }\n\n  if (typeof observables[observables.length - 1] === 'function') {\n    resultSelector = observables.pop() as (...values: Array<any>) => R;\n  }\n\n  // if the first and only other argument besides the resultSelector is an array\n  // assume it's been called with `combineLatest([obs1, obs2, obs3], resultSelector)`\n  if (observables.length === 1 && isArray(observables[0])) {\n    observables = observables[0] as any;\n  }\n\n  return fromArray(observables, scheduler).lift(new CombineLatestOperator(resultSelector));\n}\n\nexport class CombineLatestOperator<T, R> implements Operator<T, R> {\n  constructor(private resultSelector?: (...values: Array<any>) => R) {\n  }\n\n  call(subscriber: Subscriber<R>, source: any): any {\n    return source.subscribe(new CombineLatestSubscriber(subscriber, this.resultSelector));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class CombineLatestSubscriber<T, R> extends OuterSubscriber<T, R> {\n  private active: number = 0;\n  private values: any[] = [];\n  private observables: any[] = [];\n  private toRespond?: number;\n\n  constructor(destination: Subscriber<R>, private resultSelector?: (...values: Array<any>) => R) {\n    super(destination);\n  }\n\n  protected _next(observable: any) {\n    this.values.push(NONE);\n    this.observables.push(observable);\n  }\n\n  protected _complete() {\n    const observables = this.observables;\n    const len = observables.length;\n    if (len === 0) {\n      this.destination.complete!();\n    } else {\n      this.active = len;\n      this.toRespond = len;\n      for (let i = 0; i < len; i++) {\n        const observable = observables[i];\n        this.add(subscribeToResult(this, observable, undefined, i));\n      }\n    }\n  }\n\n  notifyComplete(unused: Subscriber<R>): void {\n    if ((this.active -= 1) === 0) {\n      this.destination.complete!();\n    }\n  }\n\n  notifyNext(_outerValue: T, innerValue: R,\n             outerIndex: number): void {\n    const values = this.values;\n    const oldVal = values[outerIndex];\n    const toRespond = !this.toRespond\n      ? 0\n      : oldVal === NONE ? --this.toRespond : this.toRespond;\n    values[outerIndex] = innerValue;\n\n    if (toRespond === 0) {\n      if (this.resultSelector) {\n        this._tryResultSelector(values);\n      } else {\n        this.destination.next!(values.slice());\n      }\n    }\n  }\n\n  private _tryResultSelector(values: any[]) {\n    let result: any;\n    try {\n      result = this.resultSelector!.apply(this, values);\n    } catch (err) {\n      this.destination.error!(err);\n      return;\n    }\n    this.destination.next!(result);\n  }\n}\n","\nimport { mergeMap } from './mergeMap';\nimport { identity } from '../util/identity';\nimport { OperatorFunction, ObservableInput } from '../types';\n\n/**\n * Converts a higher-order Observable into a first-order Observable which\n * concurrently delivers all values that are emitted on the inner Observables.\n *\n * <span class=\"informal\">Flattens an Observable-of-Observables.</span>\n *\n * ![](mergeAll.png)\n *\n * `mergeAll` subscribes to an Observable that emits Observables, also known as\n * a higher-order Observable. Each time it observes one of these emitted inner\n * Observables, it subscribes to that and delivers all the values from the\n * inner Observable on the output Observable. The output Observable only\n * completes once all inner Observables have completed. Any error delivered by\n * a inner Observable will be immediately emitted on the output Observable.\n *\n * ## Examples\n * Spawn a new interval Observable for each click event, and blend their outputs as one Observable\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { map, mergeAll } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(map((ev) => interval(1000)));\n * const firstOrder = higherOrder.pipe(mergeAll());\n * firstOrder.subscribe(x => console.log(x));\n * ```\n *\n * Count from 0 to 9 every second for each click, but only allow 2 concurrent timers\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { take, map, mergeAll } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n *   map((ev) => interval(1000).pipe(take(10))),\n * );\n * const firstOrder = higherOrder.pipe(mergeAll(2));\n * firstOrder.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineAll}\n * @see {@link concatAll}\n * @see {@link exhaust}\n * @see {@link merge}\n * @see {@link mergeMap}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link zipAll}\n *\n * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner\n * Observables being subscribed to concurrently.\n * @return {Observable} An Observable that emits values coming from all the\n * inner Observables emitted by the source Observable.\n * @method mergeAll\n * @owner Observable\n */\nexport function mergeAll<T>(concurrent: number = Number.POSITIVE_INFINITY): OperatorFunction<ObservableInput<T>, T> {\n  return mergeMap(identity, concurrent);\n}\n","import { Observable } from '../Observable';\nimport { SubscribableOrPromise, ObservedValueOf, ObservableInput } from '../types';\nimport { from } from './from'; // lol\nimport { empty } from './empty';\n\n/**\n * Creates an Observable that, on subscribe, calls an Observable factory to\n * make an Observable for each new Observer.\n *\n * <span class=\"informal\">Creates the Observable lazily, that is, only when it\n * is subscribed.\n * </span>\n *\n * ![](defer.png)\n *\n * `defer` allows you to create the Observable only when the Observer\n * subscribes, and create a fresh Observable for each Observer. It waits until\n * an Observer subscribes to it, and then it generates an Observable,\n * typically with an Observable factory function. It does this afresh for each\n * subscriber, so although each subscriber may think it is subscribing to the\n * same Observable, in fact each subscriber gets its own individual\n * Observable.\n *\n * ## Example\n * ### Subscribe to either an Observable of clicks or an Observable of interval, at random\n * ```ts\n * import { defer, fromEvent, interval } from 'rxjs';\n *\n * const clicksOrInterval = defer(function () {\n *   return Math.random() > 0.5\n *     ? fromEvent(document, 'click')\n *     : interval(1000);\n * });\n * clicksOrInterval.subscribe(x => console.log(x));\n *\n * // Results in the following behavior:\n * // If the result of Math.random() is greater than 0.5 it will listen\n * // for clicks anywhere on the \"document\"; when document is clicked it\n * // will log a MouseEvent object to the console. If the result is less\n * // than 0.5 it will emit ascending numbers, one every second(1000ms).\n * ```\n *\n * @see {@link Observable}\n *\n * @param {function(): SubscribableOrPromise} observableFactory The Observable\n * factory function to invoke for each Observer that subscribes to the output\n * Observable. May also return a Promise, which will be converted on the fly\n * to an Observable.\n * @return {Observable} An Observable whose Observers' subscriptions trigger\n * an invocation of the given Observable factory function.\n * @static true\n * @name defer\n * @owner Observable\n */\nexport function defer<R extends ObservableInput<any> | void>(observableFactory: () => R): Observable<ObservedValueOf<R>> {\n  return new Observable<ObservedValueOf<R>>(subscriber => {\n    let input: R | void;\n    try {\n      input = observableFactory();\n    } catch (err) {\n      subscriber.error(err);\n      return undefined;\n    }\n    const source = input ? from(input as ObservableInput<ObservedValueOf<R>>) : empty();\n    return source.subscribe(subscriber);\n  });\n}\n","import { Observable } from '../Observable';\nimport { fromArray } from './fromArray';\nimport { isArray } from '../util/isArray';\nimport { Operator } from '../Operator';\nimport { ObservableInput, PartialObserver, ObservedValueOf } from '../types';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { iterator as Symbol_iterator } from '../../internal/symbol/iterator';\nimport { SimpleOuterSubscriber, SimpleInnerSubscriber, innerSubscribe } from '../innerSubscribe';\n\n/* tslint:disable:max-line-length */\n/** @deprecated resultSelector is no longer supported, pipe to map instead */\nexport function zip<O1 extends ObservableInput<any>, R>(v1: O1, resultSelector: (v1: ObservedValueOf<O1>) => R): Observable<R>;\n/** @deprecated resultSelector is no longer supported, pipe to map instead */\nexport function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, R>(v1: O1, v2: O2, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>) => R): Observable<R>;\n/** @deprecated resultSelector is no longer supported, pipe to map instead */\nexport function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>) => R): Observable<R>;\n/** @deprecated resultSelector is no longer supported, pipe to map instead */\nexport function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, v4: O4, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>) => R): Observable<R>;\n/** @deprecated resultSelector is no longer supported, pipe to map instead */\nexport function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>, v5: ObservedValueOf<O5>) => R): Observable<R>;\n/** @deprecated resultSelector is no longer supported, pipe to map instead */\nexport function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>, v5: ObservedValueOf<O5>, v6: ObservedValueOf<O6>) => R): Observable<R>;\n\nexport function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(v1: O1, v2: O2): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>]>;\nexport function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>]>;\nexport function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>]>;\nexport function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>]>;\nexport function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>, ObservedValueOf<O6>]>;\n\nexport function zip<O extends ObservableInput<any>>(array: O[]): Observable<ObservedValueOf<O>[]>;\nexport function zip<R>(array: ObservableInput<any>[]): Observable<R>;\n/** @deprecated resultSelector is no longer supported, pipe to map instead */\nexport function zip<O extends ObservableInput<any>, R>(array: O[], resultSelector: (...values: ObservedValueOf<O>[]) => R): Observable<R>;\n/** @deprecated resultSelector is no longer supported, pipe to map instead */\nexport function zip<R>(array: ObservableInput<any>[], resultSelector: (...values: any[]) => R): Observable<R>;\n\nexport function zip<O extends ObservableInput<any>>(...observables: O[]): Observable<ObservedValueOf<O>[]>;\nexport function zip<O extends ObservableInput<any>, R>(...observables: Array<O | ((...values: ObservedValueOf<O>[]) => R)>): Observable<R>;\nexport function zip<R>(...observables: Array<ObservableInput<any> | ((...values: Array<any>) => R)>): Observable<R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each\n * of its input Observables.\n *\n * If the last parameter is a function, this function is used to compute the created value from the input values.\n * Otherwise, an array of the input values is returned.\n *\n * ## Example\n * Combine age and name from different sources\n * ```ts\n * import { zip, of } from 'rxjs';\n * import { map } from 'rxjs/operators';\n *\n * let age$ = of<number>(27, 25, 29);\n * let name$ = of<string>('Foo', 'Bar', 'Beer');\n * let isDev$ = of<boolean>(true, true, false);\n *\n * zip(age$, name$, isDev$).pipe(\n *   map(([age, name, isDev]) => ({ age, name, isDev })),\n * )\n * .subscribe(x => console.log(x));\n *\n * // outputs\n * // { age: 27, name: 'Foo', isDev: true }\n * // { age: 25, name: 'Bar', isDev: true }\n * // { age: 29, name: 'Beer', isDev: false }\n * ```\n * @param observables\n * @return {Observable<R>}\n * @static true\n * @name zip\n * @owner Observable\n */\nexport function zip<O extends ObservableInput<any>, R>(\n  ...observables: Array<O | ((...values: ObservedValueOf<O>[]) => R)>\n): Observable<ObservedValueOf<O>[]|R> {\n  const resultSelector = <((...ys: Array<any>) => R)> observables[observables.length - 1];\n  if (typeof resultSelector === 'function') {\n    observables.pop();\n  }\n  return fromArray(observables, undefined).lift(new ZipOperator(resultSelector));\n}\n\nexport class ZipOperator<T, R> implements Operator<T, R> {\n\n  resultSelector?: (...values: Array<any>) => R;\n\n  constructor(resultSelector?: (...values: Array<any>) => R) {\n    this.resultSelector = resultSelector;\n  }\n\n  call(subscriber: Subscriber<R>, source: any): any {\n    return source.subscribe(new ZipSubscriber(subscriber, this.resultSelector));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class ZipSubscriber<T, R> extends Subscriber<T> {\n  private iterators: LookAheadIterator<any>[] = [];\n  private active = 0;\n\n  constructor(destination: Subscriber<R>,\n              private resultSelector?: (...values: Array<any>) => R,\n              values: any = Object.create(null)) {\n    super(destination);\n    this.resultSelector = (typeof resultSelector === 'function') ? resultSelector : undefined;\n  }\n\n  protected _next(value: any) {\n    const iterators = this.iterators;\n    if (isArray(value)) {\n      iterators.push(new StaticArrayIterator(value));\n    } else if (typeof value[Symbol_iterator] === 'function') {\n      iterators.push(new StaticIterator(value[Symbol_iterator]()));\n    } else {\n      iterators.push(new ZipBufferIterator(this.destination, this, value));\n    }\n  }\n\n  protected _complete() {\n    const iterators = this.iterators;\n    const len = iterators.length;\n\n    this.unsubscribe();\n\n    if (len === 0) {\n      this.destination.complete!();\n      return;\n    }\n\n    this.active = len;\n    for (let i = 0; i < len; i++) {\n      let iterator: ZipBufferIterator<any, any> = <any>iterators[i];\n      if (iterator.stillUnsubscribed) {\n        const destination = this.destination as Subscription;\n        destination.add(iterator.subscribe());\n      } else {\n        this.active--; // not an observable\n      }\n    }\n  }\n\n  notifyInactive() {\n    this.active--;\n    if (this.active === 0) {\n      this.destination.complete!();\n    }\n  }\n\n  checkIterators() {\n    const iterators = this.iterators;\n    const len = iterators.length;\n    const destination = this.destination;\n\n    // abort if not all of them have values\n    for (let i = 0; i < len; i++) {\n      let iterator = iterators[i];\n      if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {\n        return;\n      }\n    }\n\n    let shouldComplete = false;\n    const args: any[] = [];\n    for (let i = 0; i < len; i++) {\n      let iterator = iterators[i];\n      let result = iterator.next();\n\n      // check to see if it's completed now that you've gotten\n      // the next value.\n      if (iterator.hasCompleted()) {\n        shouldComplete = true;\n      }\n\n      if (result.done) {\n        destination.complete!();\n        return;\n      }\n\n      args.push(result.value);\n    }\n\n    if (this.resultSelector) {\n      this._tryresultSelector(args);\n    } else {\n      destination.next!(args);\n    }\n\n    if (shouldComplete) {\n      destination.complete!();\n    }\n  }\n\n  protected _tryresultSelector(args: any[]) {\n    let result: any;\n    try {\n      result = this.resultSelector!.apply(this, args);\n    } catch (err) {\n      this.destination.error!(err);\n      return;\n    }\n    this.destination.next!(result);\n  }\n}\n\ninterface LookAheadIterator<T> extends Iterator<T> {\n  hasValue(): boolean;\n  hasCompleted(): boolean;\n}\n\nclass StaticIterator<T> implements LookAheadIterator<T> {\n  private nextResult: IteratorResult<T>;\n\n  constructor(private iterator: Iterator<T>) {\n    this.nextResult = iterator.next();\n  }\n\n  hasValue() {\n    return true;\n  }\n\n  next(): IteratorResult<T> {\n    const result = this.nextResult;\n    this.nextResult = this.iterator.next();\n    return result;\n  }\n\n  hasCompleted(): boolean {\n    const nextResult = this.nextResult;\n    return Boolean(nextResult && nextResult.done);\n  }\n}\n\nclass StaticArrayIterator<T> implements LookAheadIterator<T> {\n  private index = 0;\n  private length = 0;\n\n  constructor(private array: T[]) {\n    this.length = array.length;\n  }\n\n  [Symbol_iterator]() {\n    return this;\n  }\n\n  next(value?: any): IteratorResult<T> {\n    const i = this.index++;\n    const array = this.array;\n    return i < this.length ? { value: array[i], done: false } : { value: null, done: true };\n  }\n\n  hasValue() {\n    return this.array.length > this.index;\n  }\n\n  hasCompleted() {\n    return this.array.length === this.index;\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass ZipBufferIterator<T, R> extends SimpleOuterSubscriber<T, R> implements LookAheadIterator<T> {\n  stillUnsubscribed = true;\n  buffer: T[] = [];\n  isComplete = false;\n\n  constructor(destination: PartialObserver<T>,\n              private parent: ZipSubscriber<T, R>,\n              private observable: Observable<T>) {\n    super(destination);\n  }\n\n  [Symbol_iterator]() {\n    return this;\n  }\n\n  // NOTE: there is actually a name collision here with Subscriber.next and Iterator.next\n  //    this is legit because `next()` will never be called by a subscription in this case.\n  next(): IteratorResult<T> {\n    const buffer = this.buffer;\n    if (buffer.length === 0 && this.isComplete) {\n      return { value: null, done: true };\n    } else {\n      return { value: buffer.shift()!, done: false };\n    }\n  }\n\n  hasValue() {\n    return this.buffer.length > 0;\n  }\n\n  hasCompleted() {\n    return this.buffer.length === 0 && this.isComplete;\n  }\n\n  notifyComplete() {\n    if (this.buffer.length > 0) {\n      this.isComplete = true;\n      this.parent.notifyInactive();\n    } else {\n      this.destination.complete!();\n    }\n  }\n\n  notifyNext(innerValue: any): void {\n    this.buffer.push(innerValue);\n    this.parent.checkIterators();\n  }\n\n  subscribe() {\n    return innerSubscribe(this.observable, new SimpleInnerSubscriber(this));\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError';\nimport { empty } from '../observable/empty';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Emits only the first `count` values emitted by the source Observable.\n *\n * <span class=\"informal\">Takes the first `count` values from the source, then\n * completes.</span>\n *\n * ![](take.png)\n *\n * `take` returns an Observable that emits only the first `count` values emitted\n * by the source Observable. If the source emits fewer than `count` values then\n * all of its values are emitted. After that, it completes, regardless if the\n * source completes.\n *\n * ## Example\n * Take the first 5 seconds of an infinite 1-second interval Observable\n * ```ts\n * import { interval } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const intervalCount = interval(1000);\n * const takeFive = intervalCount.pipe(take(5));\n * takeFive.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 0\n * // 1\n * // 2\n * // 3\n * // 4\n * ```\n *\n * @see {@link takeLast}\n * @see {@link takeUntil}\n * @see {@link takeWhile}\n * @see {@link skip}\n *\n * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an\n * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.\n *\n * @param {number} count The maximum number of `next` values to emit.\n * @return {Observable<T>} An Observable that emits only the first `count`\n * values emitted by the source Observable, or all of the values from the source\n * if the source emits fewer than `count` values.\n * @method take\n * @owner Observable\n */\nexport function take<T>(count: number): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => {\n    if (count === 0) {\n      return empty();\n    } else {\n      return source.lift(new TakeOperator(count));\n    }\n  };\n}\n\nclass TakeOperator<T> implements Operator<T, T> {\n  constructor(private total: number) {\n    if (this.total < 0) {\n      throw new ArgumentOutOfRangeError;\n    }\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new TakeSubscriber(subscriber, this.total));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass TakeSubscriber<T> extends Subscriber<T> {\n  private count: number = 0;\n\n  constructor(destination: Subscriber<T>, private total: number) {\n    super(destination);\n  }\n\n  protected _next(value: T): void {\n    const total = this.total;\n    const count = ++this.count;\n    if (count <= total) {\n      this.destination.next(value);\n      if (count === total) {\n        this.destination.complete();\n        this.unsubscribe();\n      }\n    }\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError';\nimport { empty } from '../observable/empty';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Emits only the last `count` values emitted by the source Observable.\n *\n * <span class=\"informal\">Remembers the latest `count` values, then emits those\n * only when the source completes.</span>\n *\n * ![](takeLast.png)\n *\n * `takeLast` returns an Observable that emits at most the last `count` values\n * emitted by the source Observable. If the source emits fewer than `count`\n * values then all of its values are emitted. This operator must wait until the\n * `complete` notification emission from the source in order to emit the `next`\n * values on the output Observable, because otherwise it is impossible to know\n * whether or not more values will be emitted on the source. For this reason,\n * all values are emitted synchronously, followed by the complete notification.\n *\n * ## Example\n * Take the last 3 values of an Observable with many values\n * ```ts\n * import { range } from 'rxjs';\n * import { takeLast } from 'rxjs/operators';\n *\n * const many = range(1, 100);\n * const lastThree = many.pipe(takeLast(3));\n * lastThree.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link take}\n * @see {@link takeUntil}\n * @see {@link takeWhile}\n * @see {@link skip}\n *\n * @throws {ArgumentOutOfRangeError} When using `takeLast(i)`, it delivers an\n * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.\n *\n * @param {number} count The maximum number of values to emit from the end of\n * the sequence of values emitted by the source Observable.\n * @return {Observable<T>} An Observable that emits at most the last count\n * values emitted by the source Observable.\n * @method takeLast\n * @owner Observable\n */\nexport function takeLast<T>(count: number): MonoTypeOperatorFunction<T> {\n  return function takeLastOperatorFunction(source: Observable<T>): Observable<T> {\n    if (count === 0) {\n      return empty();\n    } else {\n      return source.lift(new TakeLastOperator(count));\n    }\n  };\n}\n\nclass TakeLastOperator<T> implements Operator<T, T> {\n  constructor(private total: number) {\n    if (this.total < 0) {\n      throw new ArgumentOutOfRangeError;\n    }\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new TakeLastSubscriber(subscriber, this.total));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass TakeLastSubscriber<T> extends Subscriber<T> {\n  private ring: Array<T> = new Array();\n  private count: number = 0;\n\n  constructor(destination: Subscriber<T>, private total: number) {\n    super(destination);\n  }\n\n  protected _next(value: T): void {\n    const ring = this.ring;\n    const total = this.total;\n    const count = this.count++;\n\n    if (ring.length < total) {\n      ring.push(value);\n    } else {\n      const index = count % total;\n      ring[index] = value;\n    }\n  }\n\n  protected _complete(): void {\n    const destination = this.destination;\n    let count = this.count;\n\n    if (count > 0) {\n      const total = this.count >= this.total ? this.total : this.count;\n      const ring  = this.ring;\n\n      for (let i = 0; i < total; i++) {\n        const idx = (count++) % total;\n        destination.next(ring[idx]);\n      }\n    }\n\n    destination.complete();\n  }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction, MonoTypeOperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function scan<T, R>(accumulator: (acc: R, value: T, index: number) => R, seed: R): OperatorFunction<T, R>;\nexport function scan<T>(accumulator: (acc: T, value: T, index: number) => T, seed?: T): MonoTypeOperatorFunction<T>;\nexport function scan<T, R>(accumulator: (acc: R, value: T, index: number) => R): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Applies an accumulator function over the source Observable, and returns each\n * intermediate result, with an optional seed value.\n *\n * <span class=\"informal\">It's like {@link reduce}, but emits the current\n * accumulation whenever the source emits a value.</span>\n *\n * ![](scan.png)\n *\n * Combines together all values emitted on the source, using an accumulator\n * function that knows how to join a new source value into the accumulation from\n * the past. Is similar to {@link reduce}, but emits the intermediate\n * accumulations.\n *\n * Returns an Observable that applies a specified `accumulator` function to each\n * item emitted by the source Observable. If a `seed` value is specified, then\n * that value will be used as the initial value for the accumulator. If no seed\n * value is specified, the first item of the source is used as the seed.\n *\n * ## Example\n * Count the number of click events\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { scan, mapTo } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const ones = clicks.pipe(mapTo(1));\n * const seed = 0;\n * const count = ones.pipe(scan((acc, one) => acc + one, seed));\n * count.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link expand}\n * @see {@link mergeScan}\n * @see {@link reduce}\n *\n * @param {function(acc: R, value: T, index: number): R} accumulator\n * The accumulator function called on each source value.\n * @param {T|R} [seed] The initial accumulation value.\n * @return {Observable<R>} An observable of the accumulated values.\n * @method scan\n * @owner Observable\n */\nexport function scan<T, R>(accumulator: (acc: R, value: T, index: number) => R, seed?: T | R): OperatorFunction<T, R> {\n  let hasSeed = false;\n  // providing a seed of `undefined` *should* be valid and trigger\n  // hasSeed! so don't use `seed !== undefined` checks!\n  // For this reason, we have to check it here at the original call site\n  // otherwise inside Operator/Subscriber we won't know if `undefined`\n  // means they didn't provide anything or if they literally provided `undefined`\n  if (arguments.length >= 2) {\n    hasSeed = true;\n  }\n\n  return function scanOperatorFunction(source: Observable<T>): Observable<R> {\n    return source.lift(new ScanOperator(accumulator, seed, hasSeed));\n  };\n}\n\nclass ScanOperator<T, R> implements Operator<T, R> {\n  constructor(private accumulator: (acc: R, value: T, index: number) => R, private seed?: T | R, private hasSeed: boolean = false) {}\n\n  call(subscriber: Subscriber<R>, source: any): any {\n    return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass ScanSubscriber<T, R> extends Subscriber<T> {\n  private index: number = 0;\n\n  get seed(): T | R {\n    return this._seed;\n  }\n\n  set seed(value: T | R) {\n    this.hasSeed = true;\n    this._seed = value;\n  }\n\n  constructor(destination: Subscriber<R>, private accumulator: (acc: R, value: T, index: number) => R, private _seed: T | R,\n              private hasSeed: boolean) {\n    super(destination);\n  }\n\n  protected _next(value: T): void {\n    if (!this.hasSeed) {\n      this.seed = value;\n      this.destination.next(value);\n    } else {\n      return this._tryNext(value);\n    }\n  }\n\n  private _tryNext(value: T): void {\n    const index = this.index++;\n    let result: any;\n    try {\n      result = this.accumulator(<R>this.seed, value, index);\n    } catch (err) {\n      this.destination.error(err);\n    }\n    this.seed = result;\n    this.destination.next(result);\n  }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { map } from './map';\nimport { from } from '../observable/from';\nimport { SimpleOuterSubscriber, SimpleInnerSubscriber, innerSubscribe } from '../innerSubscribe';\n\n/* tslint:disable:max-line-length */\nexport function switchMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector is no longer supported, use inner map instead */\nexport function switchMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: undefined): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector is no longer supported, use inner map instead */\nexport function switchMap<T, R, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable, emitting values only from the most recently projected Observable.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables.</span>\n *\n * ![](switchMap.png)\n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an (so-called \"inner\") Observable. Each time it observes one of these\n * inner Observables, the output Observable begins emitting the items emitted by\n * that inner Observable. When a new inner Observable is emitted, `switchMap`\n * stops emitting items from the earlier-emitted inner Observable and begins\n * emitting items from the new one. It continues to behave like this for\n * subsequent inner Observables.\n *\n * ## Example\n * Generate new Observable according to source Observable values\n * ```typescript\n * import { of } from 'rxjs';\n * import { switchMap } from 'rxjs/operators';\n *\n * const switched = of(1, 2, 3).pipe(switchMap((x: number) => of(x, x ** 2, x ** 3)));\n * switched.subscribe(x => console.log(x));\n * // outputs\n * // 1\n * // 1\n * // 1\n * // 2\n * // 4\n * // 8\n * // ... and so on\n * ```\n *\n * Rerun an interval Observable on every click event\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { switchMap } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(switchMap((ev) => interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaustMap}\n * @see {@link mergeMap}\n * @see {@link switchAll}\n * @see {@link switchMapTo}\n *\n * @param {function(value: T, ?index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @return {Observable} An Observable that emits the result of applying the\n * projection function (and the optional deprecated `resultSelector`) to each item\n * emitted by the source Observable and taking only the values from the most recently\n * projected inner Observable.\n * @method switchMap\n * @owner Observable\n */\nexport function switchMap<T, R, O extends ObservableInput<any>>(\n  project: (value: T, index: number) => O,\n  resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R,\n): OperatorFunction<T, ObservedValueOf<O>|R> {\n  if (typeof resultSelector === 'function') {\n    return (source: Observable<T>) => source.pipe(\n      switchMap((a, i) => from(project(a, i)).pipe(\n        map((b, ii) => resultSelector(a, b, i, ii))\n      ))\n    );\n  }\n  return (source: Observable<T>) => source.lift(new SwitchMapOperator(project));\n}\n\nclass SwitchMapOperator<T, R> implements Operator<T, R> {\n  constructor(private project: (value: T, index: number) => ObservableInput<R>) {\n  }\n\n  call(subscriber: Subscriber<R>, source: any): any {\n    return source.subscribe(new SwitchMapSubscriber(subscriber, this.project));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SwitchMapSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n  private index = 0;\n  private innerSubscription?: Subscription;\n\n  constructor(destination: Subscriber<R>,\n              private project: (value: T, index: number) => ObservableInput<R>) {\n    super(destination);\n  }\n\n  protected _next(value: T) {\n    let result: ObservableInput<R>;\n    const index = this.index++;\n    try {\n      result = this.project(value, index);\n    } catch (error) {\n      this.destination.error!(error);\n      return;\n    }\n    this._innerSub(result);\n  }\n\n  private _innerSub(result: ObservableInput<R>) {\n    const innerSubscription = this.innerSubscription;\n    if (innerSubscription) {\n      innerSubscription.unsubscribe();\n    }\n    const innerSubscriber = new SimpleInnerSubscriber(this);\n    const destination = this.destination as Subscription;\n    destination.add(innerSubscriber);\n    this.innerSubscription = innerSubscribe(result, innerSubscriber);\n    // The returned subscription will usually be the subscriber that was\n    // passed. However, interop subscribers will be wrapped and for\n    // unsubscriptions to chain correctly, the wrapper needs to be added, too.\n    if (this.innerSubscription !== innerSubscriber) {\n      destination.add(this.innerSubscription);\n    }\n  }\n\n  protected _complete(): void {\n    const {innerSubscription} = this;\n    if (!innerSubscription || innerSubscription.closed) {\n      super._complete();\n    }\n    this.unsubscribe();\n  }\n\n  protected _unsubscribe() {\n    this.innerSubscription = undefined;\n  }\n\n  notifyComplete(): void {\n    this.innerSubscription = undefined;\n    if (this.isStopped) {\n      super._complete();\n    }\n  }\n\n  notifyNext(innerValue: R): void {\n      this.destination.next!(innerValue);\n  }\n}\n","export default class Timeout {\n    private _promise: Promise<any>;\n    private _resolve: () => void;\n    private _timeoutToken?: number;\n\n    constructor(\n        private _delay?: number\n    ) {\n        // tslint:disable-next-line:no-empty\n        this._resolve = () => {};\n\n        this._promise = new Promise(resolve => {\n            this._resolve = resolve;\n        });\n    }\n\n    onComplete(callback: () => void): void {\n        this._promise.then(callback);\n    }\n\n    complete(): void {\n        this._resolve();\n\n        if (this._timeoutToken) {\n            window.clearTimeout(this._timeoutToken);\n        }\n    }\n\n    start(): void {\n        if (this._delay) {\n            this._timeoutToken = window.setTimeout(() => this.complete(), this._delay);\n        }\n    }\n}\n","/**\n * @param {*} value\n * @returns {boolean}\n */\nexport default function isNil(value) {\n    if (value === null || value === undefined) {\n        return true;\n    }\n\n    return false;\n}\n","import isObject from './is-object';\n\n/**\n * @param {Object} object\n * @param {Function} predicateFn\n * @returns {Object}\n */\nexport default function omitProperty(object, predicateFn) {\n    if (!isObject(object)) {\n        return object;\n    }\n\n    const keys = Object.keys(object);\n\n    return keys.reduce((result, key) => {\n        const value = object[key];\n\n        if (!predicateFn(value)) {\n            result[key] = value;\n        }\n\n        return result;\n    }, {});\n}\n","import { MULTI_OPTION } from '../payment-method-types';\nimport {\n    BRAINTREE,\n    BRAINTREE_GOOGLEPAY,\n    BRAINTREE_PAYPAL,\n    BRAINTREE_PAYPAL_CREDIT,\n    BRAINTREE_VISACHECKOUT,\n    PAYPAL_COMMERCE,\n    PAYPAL_COMMERCE_CREDIT,\n    PAYPAL_COMMERCE_CREDIT_CARDS,\n    PAYPAL_COMMERCE_ALTERNATIVE_METHODS,\n} from '../payment-method-ids';\n\n/**\n * @param {string} id\n * @return {Boolean}\n */\nfunction isBraintreePaymentMethod(id) {\n    switch (id) {\n    case BRAINTREE_PAYPAL:\n    case BRAINTREE_PAYPAL_CREDIT:\n    case BRAINTREE_VISACHECKOUT:\n    case BRAINTREE_GOOGLEPAY:\n        return true;\n    default:\n        return false;\n    }\n}\n\n/**\n * @param {string} id\n * @return {Boolean}\n */\nfunction isPaypalCommercePaymentMethod(id) {\n    switch (id) {\n    case PAYPAL_COMMERCE_CREDIT:\n    case PAYPAL_COMMERCE_CREDIT_CARDS:\n    case PAYPAL_COMMERCE_ALTERNATIVE_METHODS:\n        return true;\n    default:\n        return false;\n    }\n}\n\nexport default class PaymentMethodIdMapper {\n    /**\n     * @returns {PaymentMethodIdMapper}\n     */\n    static create() {\n        return new PaymentMethodIdMapper();\n    }\n\n    /**\n     * @param {PaymentMethod} paymentMethod\n     * @returns {string}\n     */\n    mapToId(paymentMethod) {\n        let { id } = paymentMethod;\n\n        if (paymentMethod.method === MULTI_OPTION) {\n            id = paymentMethod.gateway;\n        }\n\n        if (isBraintreePaymentMethod(id)) {\n            return BRAINTREE;\n        }\n\n        if (isPaypalCommercePaymentMethod(id)) {\n            return PAYPAL_COMMERCE;\n        }\n\n        return id;\n    }\n}\n","export default class UrlHelper {\n    /**\n     * @param {Object} config\n     * @param {string} config.host\n     * @returns {CustomerMapper}\n     */\n    static create(config) {\n        return new UrlHelper(config);\n    }\n\n    /**\n     * @param {Object} config\n     * @param {string} config.host\n     * @returns {void}\n     */\n    constructor(config) {\n        /**\n         * @private\n         * @type {Object}\n         */\n        this.config = config;\n    }\n\n    /**\n     * @private\n     * @returns {string}\n     */\n    get host() {\n        return this.config.host;\n    }\n\n    /**\n     * @returns {string}\n     */\n    getOffsitePaymentUrl() {\n        return `${this.host}/pay/initialize`;\n    }\n\n    /**\n     * @returns {string}\n     */\n    getPaymentUrl() {\n        return `${this.host}/api/public/v1/orders/payments`;\n    }\n\n    /**\n     * @returns {string}\n     */\n    getGenerateClientTokenUrl() {\n        return `${this.host}/api/v2/public/payments/client_tokens`;\n    }\n}\n","import deepAssign from 'deep-assign';\nimport objectAssign from 'object-assign';\nimport { POST } from './method-types';\nimport DEFAULT_OPTIONS from './default-options';\nimport PayloadTransformer from './payload-transformer';\nimport RequestFactory from './request-factory';\n\nexport default class RequestSender {\n    /**\n     * @returns {RequestSender}\n     */\n    static create() {\n        const requestFactory = RequestFactory.create();\n        const payloadTransformer = PayloadTransformer.create();\n\n        return new RequestSender(requestFactory, payloadTransformer);\n    }\n\n    /**\n     * @param {RequestFactory} requestFactory\n     * @param {PayloadTransformer} payloadTransformer\n     */\n    constructor(requestFactory, payloadTransformer) {\n        /**\n         * @private\n         * @type {RequestFactory}\n         */\n        this.requestFactory = requestFactory;\n\n        /**\n         * @private\n         * @type {PayloadTransformer}\n         */\n        this.payloadTransformer = payloadTransformer;\n    }\n\n    /**\n     * @param {string} url\n     * @param {Object} data\n     * @param {Object} [options]\n     * @param {Function} [callback]\n     * @returns {void}\n     */\n    sendRequest(url, data, options, callback) {\n        const mergedOptions = deepAssign({}, DEFAULT_OPTIONS, options);\n\n        const xhr = this.requestFactory.createRequest(url, mergedOptions, (error) => {\n            const response = this.payloadTransformer.fromResponse(xhr);\n\n            if (!callback) {\n                return;\n            }\n\n            if (error || !this.isSuccessfulRequest(xhr)) {\n                callback(response);\n                return;\n            }\n\n            callback(null, response);\n        });\n\n        const payload = this.payloadTransformer.toRequest(data, mergedOptions.headers['Content-Type']);\n\n        xhr.send(payload);\n    }\n\n    /**\n     * @param {string} url\n     * @param {Object} data\n     * @param {Object} [options]\n     * @param {Function} [callback]\n     * @returns {void}\n     */\n    postRequest(url, data, options, callback) {\n        const mergedOptions = objectAssign({}, options, {\n            method: POST,\n        });\n\n        this.sendRequest(url, data, mergedOptions, callback);\n    }\n\n    /**\n     * @private\n     * @param {XMLHttpRequest} xhr\n     * @returns {boolean}\n     */\n    isSuccessfulRequest(xhr) {\n        return xhr.status >= 200 && xhr.status < 300;\n    }\n}\n","export const GET = 'GET';\nexport const POST = 'POST';\nexport const DELETE = 'DELETE';\n","import { merge } from 'lodash';\nimport {\n    defer,\n    from,\n    of,\n    throwError,\n    BehaviorSubject,\n    Observable,\n    Subject,\n    Subscribable,\n    SubscribableOrPromise\n} from 'rxjs';\nimport {\n    catchError,\n    concatMap,\n    distinctUntilChanged,\n    filter,\n    first,\n    map,\n    mergeMap,\n    scan,\n    skip,\n    tap,\n} from 'rxjs/operators';\nimport * as shallowEqual from 'shallowequal';\n\nimport Action from './action';\nimport deepFreeze from './deep-freeze';\nimport DispatchableDataStore, { DispatchableAction, DispatchOptions } from './dispatchable-data-store';\nimport isObservableActionLike from './is-observable-action-like';\nimport noopActionTransformer from './noop-action-transformer';\nimport noopStateTransformer from './noop-state-transformer';\nimport ReadableDataStore, { Filter, Subscriber, SubscribeOptions, Unsubscriber } from './readable-data-store';\nimport Reducer from './reducer';\nimport ThunkAction from './thunk-action';\n\nexport default class DataStore<TState, TAction extends Action = Action, TTransformedState = TState> implements\n    ReadableDataStore<TTransformedState>, DispatchableDataStore<TTransformedState, TAction> {\n    private _reducer: Reducer<TState, TAction>;\n    private _options: DataStoreOptions<TState, TAction, TTransformedState>;\n    private _notification$: Subject<TTransformedState>;\n    private _dispatchers: { [key: string]: Dispatcher<TAction> };\n    private _dispatchQueue$: Subject<Dispatcher<TAction>>;\n    private _state$: BehaviorSubject<TTransformedState>;\n    private _errors: { [key: string]: Subject<Error> };\n\n    constructor(\n        reducer: Reducer<TState, TAction>,\n        initialState: Partial<TState> = {},\n        options?: Partial<DataStoreOptions<TState, TAction, TTransformedState>>\n    ) {\n        this._reducer = reducer;\n        this._options = {\n            actionTransformer: noopActionTransformer,\n            equalityCheck: shallowEqual,\n            shouldWarnMutation: true,\n            stateTransformer: noopStateTransformer,\n            ...options,\n        };\n        this._state$ = new BehaviorSubject(this._options.stateTransformer(initialState as TState));\n        this._notification$ = new Subject();\n        this._dispatchers = {};\n        this._dispatchQueue$ = new Subject();\n        this._errors = {};\n\n        this._dispatchQueue$\n            .pipe(\n                mergeMap(dispatcher$ => dispatcher$.pipe(concatMap(action$ => action$))),\n                filter(action => !!action.type),\n                scan(\n                    (states: StateTuple<TState, TTransformedState>, action: TAction) =>\n                        this._transformStates(states, action),\n                    {\n                        state: initialState as TState,\n                        transformedState: this._state$.getValue(),\n                    }\n                ),\n                distinctUntilChanged(({ state: stateA }, { state: stateB }) =>\n                    this._options.equalityCheck(stateA, stateB)\n                ),\n                map(({ transformedState }) => transformedState)\n            )\n            .subscribe(this._state$);\n\n        this.dispatch({ type: 'INIT' } as TAction);\n    }\n\n    dispatch<TDispatchAction extends TAction>(\n        action: DispatchableAction<TDispatchAction, TTransformedState>,\n        options?: DispatchOptions\n    ): Promise<TTransformedState> {\n        if (isObservableActionLike(action)) {\n            return this._dispatchObservableAction(action, options);\n        }\n\n        if (typeof action === 'function') {\n            return this._dispatchThunkAction(action, options);\n        }\n\n        return this._dispatchAction(action);\n    }\n\n    getState(): TTransformedState {\n        return this._state$.getValue();\n    }\n\n    notifyState(): void {\n        this._notification$.next(this.getState());\n    }\n\n    subscribe(subscriber: Subscriber<TTransformedState>, ...filters: Array<Filter<TTransformedState>>): Unsubscriber;\n    subscribe(subscriber: Subscriber<TTransformedState>, options: SubscribeOptions<TTransformedState>): Unsubscriber;\n    subscribe(subscriber: Subscriber<TTransformedState>, ...args: any[]): Unsubscriber {\n        const options: SubscribeOptions<TTransformedState> = typeof args[0] === 'object' ? args[0] : undefined;\n        const filters: Array<Filter<TTransformedState>> = options ? (options.filters || []) : args;\n\n        let state$: Observable<TTransformedState> = this._state$;\n\n        if (filters.length > 0) {\n            state$ = state$.pipe(\n                distinctUntilChanged((stateA, stateB) =>\n                    filters.every(filterFn =>\n                        this._options.equalityCheck(filterFn(stateA), filterFn(stateB))\n                    )\n                )\n            );\n        }\n\n        if (options && options.initial === false) {\n            state$ = state$.pipe(skip(1));\n        }\n\n        const subscriptions = [\n            state$.subscribe(subscriber),\n            this._notification$.subscribe(subscriber),\n        ];\n\n        return () => subscriptions.forEach(subscription => subscription.unsubscribe());\n    }\n\n    private _transformStates(\n        states: StateTuple<TState, TTransformedState>,\n        action: TAction\n    ): StateTuple<TState, TTransformedState> {\n        try {\n            const newState = this._options.shouldWarnMutation === false ?\n                this._reducer(states.state, action) :\n                deepFreeze(this._reducer(states.state, action), {\n                    equalityCheck: this._options.equalityCheck,\n                    previousValue: states.state,\n                });\n            const transformedState = this._options.stateTransformer(newState);\n\n            return { state: newState, transformedState };\n        } catch (error) {\n            this._getDispatchError(action.meta && action.meta.queueId).next(error);\n\n            return { state: states.state, transformedState: states.transformedState };\n        }\n    }\n\n    private _dispatchAction<TDispatchAction extends TAction>(\n        action: TDispatchAction\n    ): Promise<TTransformedState> {\n        return this._dispatchObservableAction(\n            action.error ? throwError(action) : of(action)\n        );\n    }\n\n    private _dispatchObservableAction<TDispatchAction extends TAction>(\n        action$: SubscribableOrPromise<TDispatchAction>,\n        options: DispatchOptions = {}\n    ): Promise<TTransformedState> {\n        return new Promise((resolve, reject) => {\n            const error$ = this._getDispatchError(options.queueId);\n            const transformedAction$ = this._options.actionTransformer(\n                from(action$).pipe(\n                    map(action =>\n                        options.queueId ?\n                            merge({}, action, { meta: { queueId: options.queueId } }) :\n                            action\n                    )\n                ) as Subscribable<TDispatchAction>\n            );\n\n            this._getDispatcher(options.queueId).next(\n                from(transformedAction$)\n                    .pipe(\n                        map((action, index) => {\n                            if (index === 0) {\n                                error$.pipe(first()).subscribe(reject);\n                            }\n\n                            if (action.error) {\n                                reject(action.payload);\n                            }\n\n                            return action;\n                        }),\n                        catchError(action => {\n                            reject(action instanceof Error ? action : action.payload);\n\n                            return of(action);\n                        }),\n                        tap({\n                            complete: () => {\n                                resolve(this.getState());\n                            },\n                        })\n                    )\n            );\n        });\n    }\n\n    private _dispatchThunkAction<TDispatchAction extends TAction>(\n        thunkAction: ThunkAction<TDispatchAction, TTransformedState>,\n        options: DispatchOptions = {}\n    ): Promise<TTransformedState> {\n        return this._dispatchObservableAction(defer(() => thunkAction(this)), options);\n    }\n\n    private _getDispatcher(queueId: string = 'default'): Dispatcher<TAction> {\n        if (!this._dispatchers[queueId]) {\n            this._dispatchers[queueId] = new Subject();\n\n            this._dispatchQueue$.next(this._dispatchers[queueId]);\n        }\n\n        return this._dispatchers[queueId];\n    }\n\n    private _getDispatchError(queueId: string = 'default'): Subject<Error> {\n        if (!this._errors[queueId]) {\n            this._errors[queueId] = new Subject();\n        }\n\n        return this._errors[queueId];\n    }\n}\n\nexport interface DataStoreOptions<TState, TAction, TTransformedState> {\n    shouldWarnMutation: boolean;\n    actionTransformer(action: Subscribable<TAction>): Subscribable<TAction>;\n    equalityCheck(valueA: any, valueB: any): boolean;\n    stateTransformer(state: TState): TTransformedState;\n}\n\ninterface StateTuple<TState, TTransformedState> {\n    state: TState;\n    transformedState: TTransformedState;\n}\n\ntype Dispatcher<TAction> = Subject<Subscribable<TAction>>;\n","import { isPlainObject } from 'lodash';\nimport * as shallowEqual from 'shallowequal';\n\nexport interface DeepFreezeOptions<T> {\n    previousValue?: T;\n    equalityCheck?(valueA: any, valueB: any): boolean;\n}\n\nexport default function deepFreeze<T>(object: T[], options?: DeepFreezeOptions<T>): ReadonlyArray<T>;\nexport default function deepFreeze<T extends object>(object: T, options?: DeepFreezeOptions<T>): Readonly<T>;\nexport default function deepFreeze<T>(object: T, options?: DeepFreezeOptions<T>): T;\nexport default function deepFreeze<T>(\n    object: T[] | T,\n    options?: DeepFreezeOptions<T>\n): ReadonlyArray<T> | Readonly<T> | T {\n    try {\n        const { equalityCheck = shallowEqual, previousValue = null } = options || {};\n\n        if (equalityCheck(object, previousValue) && Object.isFrozen(previousValue)) {\n            return previousValue as T;\n        }\n\n        if (Object.isFrozen(object) || (!Array.isArray(object) && !isPlainObject(object))) {\n            return object;\n        }\n\n        if (Array.isArray(object)) {\n            return Object.freeze(object.map((value, index) =>\n                deepFreeze(value, {\n                    equalityCheck,\n                    previousValue: Array.isArray(previousValue) ? previousValue[index] : undefined,\n                })\n            ));\n        }\n\n        return Object.freeze(Object.getOwnPropertyNames(object).reduce((result, key) => {\n            result[key as keyof T] = deepFreeze(object[key as keyof T], {\n                equalityCheck,\n                previousValue: previousValue && previousValue.hasOwnProperty(key) ?\n                    (previousValue as any)[key] :\n                    undefined,\n            });\n\n            return result;\n        }, {} as T));\n    } catch (error) {\n        // Browsers that only support ES5 will throw `TypeError` when checking\n        // if a primitive value is frozen or trying to freeze a primitive value.\n        if (error instanceof TypeError) {\n            return object;\n        }\n\n        throw error;\n    }\n}\n","import { assign } from 'lodash';\nimport * as shallowEqual from 'shallowequal';\n\nimport Action from './action';\nimport Reducer from './reducer';\n\nexport default function combineReducers<TState, TAction extends Action = Action>(\n    reducers: ReducerMap<TState, TAction>,\n    options?: CombineReducersOptions\n): Reducer<TState, TAction> {\n    const { equalityCheck = shallowEqual } = options || {};\n\n    return (state, action) =>\n        Object.keys(reducers).reduce((result, key) => {\n            const reducer = reducers[key as keyof TState];\n            const currentState = state ? state[key as keyof TState] : undefined;\n            const newState = reducer(currentState, action);\n\n            if (equalityCheck(currentState, newState) && result) {\n                return result;\n            }\n\n            return assign({}, result, { [key]: newState });\n        }, state || {} as TState);\n}\n\nexport type ReducerMap<TState, TAction extends Action = Action> = {\n    [Key in keyof TState]: Reducer<TState[Key], TAction>;\n};\n\nexport interface CombineReducersOptions {\n    equalityCheck?(valueA: any, valueB: any): boolean;\n}\n","import { omitBy } from 'lodash';\n\nimport Action from './action';\n\nexport default function createAction<TPayload, TMeta, TType extends string>(\n    type: TType,\n    payload?: TPayload,\n    meta?: TMeta\n): Action<TPayload, TMeta, TType> {\n    if (typeof type !== 'string' || type === '') {\n        throw new Error('`type` must be a string');\n    }\n\n    return { type, ...omitBy({ payload, meta }, value => value === undefined) };\n}\n","import { Observer } from './types';\nimport { config } from './config';\nimport { hostReportError } from './util/hostReportError';\n\nexport const empty: Observer<any> = {\n  closed: true,\n  next(value: any): void { /* noop */},\n  error(err: any): void {\n    if (config.useDeprecatedSynchronousErrorHandling) {\n      throw err;\n    } else {\n      hostReportError(err);\n    }\n  },\n  complete(): void { /*noop*/ }\n};\n","export interface UnsubscriptionError extends Error {\n  readonly errors: any[];\n}\n\nexport interface UnsubscriptionErrorCtor {\n  new(errors: any[]): UnsubscriptionError;\n}\n\nconst UnsubscriptionErrorImpl = (() => {\n  function UnsubscriptionErrorImpl(this: any, errors: any[]) {\n    Error.call(this);\n    this.message = errors ?\n      `${errors.length} errors occurred during unsubscription:\n${errors.map((err, i) => `${i + 1}) ${err.toString()}`).join('\\n  ')}` : '';\n    this.name = 'UnsubscriptionError';\n    this.errors = errors;\n    return this;\n  }\n\n  UnsubscriptionErrorImpl.prototype = Object.create(Error.prototype);\n\n  return UnsubscriptionErrorImpl;\n})();\n\n/**\n * An error thrown when one or more errors have occurred during the\n * `unsubscribe` of a {@link Subscription}.\n */\nexport const UnsubscriptionError: UnsubscriptionErrorCtor = UnsubscriptionErrorImpl as any;","import { Subject, SubjectSubscriber } from '../Subject';\nimport { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { TeardownLogic } from '../types';\nimport { refCount as higherOrderRefCount } from '../operators/refCount';\n\n/**\n * @class ConnectableObservable<T>\n */\nexport class ConnectableObservable<T> extends Observable<T> {\n\n  protected _subject: Subject<T>;\n  protected _refCount: number = 0;\n  protected _connection: Subscription;\n  /** @internal */\n  _isComplete = false;\n\n  constructor(public source: Observable<T>,\n              protected subjectFactory: () => Subject<T>) {\n    super();\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _subscribe(subscriber: Subscriber<T>) {\n    return this.getSubject().subscribe(subscriber);\n  }\n\n  protected getSubject(): Subject<T> {\n    const subject = this._subject;\n    if (!subject || subject.isStopped) {\n      this._subject = this.subjectFactory();\n    }\n    return this._subject;\n  }\n\n  connect(): Subscription {\n    let connection = this._connection;\n    if (!connection) {\n      this._isComplete = false;\n      connection = this._connection = new Subscription();\n      connection.add(this.source\n        .subscribe(new ConnectableSubscriber(this.getSubject(), this)));\n      if (connection.closed) {\n        this._connection = null;\n        connection = Subscription.EMPTY;\n      }\n    }\n    return connection;\n  }\n\n  refCount(): Observable<T> {\n    return higherOrderRefCount()(this) as Observable<T>;\n  }\n}\n\nexport const connectableObservableDescriptor: PropertyDescriptorMap = (() => {\n  const connectableProto = <any>ConnectableObservable.prototype;\n  return {\n    operator: { value: null as null },\n    _refCount: { value: 0, writable: true },\n    _subject: { value: null as null, writable: true },\n    _connection: { value: null as null, writable: true },\n    _subscribe: { value: connectableProto._subscribe },\n    _isComplete: { value: connectableProto._isComplete, writable: true },\n    getSubject: { value: connectableProto.getSubject },\n    connect: { value: connectableProto.connect },\n    refCount: { value: connectableProto.refCount }\n  };\n})();\n\nclass ConnectableSubscriber<T> extends SubjectSubscriber<T> {\n  constructor(destination: Subject<T>,\n              private connectable: ConnectableObservable<T>) {\n    super(destination);\n  }\n  protected _error(err: any): void {\n    this._unsubscribe();\n    super._error(err);\n  }\n  protected _complete(): void {\n    this.connectable._isComplete = true;\n    this._unsubscribe();\n    super._complete();\n  }\n  protected _unsubscribe() {\n    const connectable = <any>this.connectable;\n    if (connectable) {\n      this.connectable = null;\n      const connection = connectable._connection;\n      connectable._refCount = 0;\n      connectable._subject = null;\n      connectable._connection = null;\n      if (connection) {\n        connection.unsubscribe();\n      }\n    }\n  }\n}\n\nclass RefCountOperator<T> implements Operator<T, T> {\n  constructor(private connectable: ConnectableObservable<T>) {\n  }\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n\n    const { connectable } = this;\n    (<any> connectable)._refCount++;\n\n    const refCounter = new RefCountSubscriber(subscriber, connectable);\n    const subscription = source.subscribe(refCounter);\n\n    if (!refCounter.closed) {\n      (<any> refCounter).connection = connectable.connect();\n    }\n\n    return subscription;\n  }\n}\n\nclass RefCountSubscriber<T> extends Subscriber<T> {\n\n  private connection: Subscription;\n\n  constructor(destination: Subscriber<T>,\n              private connectable: ConnectableObservable<T>) {\n    super(destination);\n  }\n\n  protected _unsubscribe() {\n\n    const { connectable } = this;\n    if (!connectable) {\n      this.connection = null;\n      return;\n    }\n\n    this.connectable = null;\n    const refCount = (<any> connectable)._refCount;\n    if (refCount <= 0) {\n      this.connection = null;\n      return;\n    }\n\n    (<any> connectable)._refCount = refCount - 1;\n    if (refCount > 1) {\n      this.connection = null;\n      return;\n    }\n\n    ///\n    // Compare the local RefCountSubscriber's connection Subscription to the\n    // connection Subscription on the shared ConnectableObservable. In cases\n    // where the ConnectableObservable source synchronously emits values, and\n    // the RefCountSubscriber's downstream Observers synchronously unsubscribe,\n    // execution continues to here before the RefCountOperator has a chance to\n    // supply the RefCountSubscriber with the shared connection Subscription.\n    // For example:\n    // ```\n    // range(0, 10).pipe(\n    //   publish(),\n    //   refCount(),\n    //   take(5),\n    // ).subscribe();\n    // ```\n    // In order to account for this case, RefCountSubscriber should only dispose\n    // the ConnectableObservable's shared connection Subscription if the\n    // connection Subscription exists, *and* either:\n    //   a. RefCountSubscriber doesn't have a reference to the shared connection\n    //      Subscription yet, or,\n    //   b. RefCountSubscriber's connection Subscription reference is identical\n    //      to the shared connection Subscription\n    ///\n    const { connection } = this;\n    const sharedConnection = (<any> connectable)._connection;\n    this.connection = null;\n\n    if (sharedConnection && (!connection || sharedConnection === connection)) {\n      sharedConnection.unsubscribe();\n    }\n  }\n}\n","import { Subject } from './Subject';\nimport { Observer } from './types';\nimport { Subscription } from './Subscription';\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class SubjectSubscription<T> extends Subscription {\n  closed: boolean = false;\n\n  constructor(public subject: Subject<T>, public subscriber: Observer<T>) {\n    super();\n  }\n\n  unsubscribe() {\n    if (this.closed) {\n      return;\n    }\n\n    this.closed = true;\n\n    const subject = this.subject;\n    const observers = subject.observers;\n\n    this.subject = null;\n\n    if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {\n      return;\n    }\n\n    const subscriberIndex = observers.indexOf(this.subscriber);\n\n    if (subscriberIndex !== -1) {\n      observers.splice(subscriberIndex, 1);\n    }\n  }\n}\n","import { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subject } from '../Subject';\nimport { OperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function groupBy<T, K>(keySelector: (value: T) => K): OperatorFunction<T, GroupedObservable<K, T>>;\nexport function groupBy<T, K>(keySelector: (value: T) => K, elementSelector: void, durationSelector: (grouped: GroupedObservable<K, T>) => Observable<any>): OperatorFunction<T, GroupedObservable<K, T>>;\nexport function groupBy<T, K, R>(keySelector: (value: T) => K, elementSelector?: (value: T) => R, durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>): OperatorFunction<T, GroupedObservable<K, R>>;\nexport function groupBy<T, K, R>(keySelector: (value: T) => K, elementSelector?: (value: T) => R, durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>, subjectSelector?: () => Subject<R>): OperatorFunction<T, GroupedObservable<K, R>>;\n/* tslint:enable:max-line-length */\n\n/**\n * Groups the items emitted by an Observable according to a specified criterion,\n * and emits these grouped items as `GroupedObservables`, one\n * {@link GroupedObservable} per group.\n *\n * ![](groupBy.png)\n *\n * When the Observable emits an item, a key is computed for this item with the keySelector function.\n *\n * If a {@link GroupedObservable} for this key exists, this {@link GroupedObservable} emits. Elsewhere, a new\n * {@link GroupedObservable} for this key is created and emits.\n *\n * A {@link GroupedObservable} represents values belonging to the same group represented by a common key. The common\n * key is available as the key field of a {@link GroupedObservable} instance.\n *\n * The elements emitted by {@link GroupedObservable}s are by default the items emitted by the Observable, or elements\n * returned by the elementSelector function.\n *\n * ## Examples\n *\n * ### Group objects by id and return as array\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { mergeMap, groupBy, reduce } from 'rxjs/operators';\n *\n * of(\n *   {id: 1, name: 'JavaScript'},\n *   {id: 2, name: 'Parcel'},\n *   {id: 2, name: 'webpack'},\n *   {id: 1, name: 'TypeScript'},\n *   {id: 3, name: 'TSLint'}\n * ).pipe(\n *   groupBy(p => p.id),\n *   mergeMap((group$) => group$.pipe(reduce((acc, cur) => [...acc, cur], []))),\n * )\n * .subscribe(p => console.log(p));\n *\n * // displays:\n * // [ { id: 1, name: 'JavaScript'},\n * //   { id: 1, name: 'TypeScript'} ]\n * //\n * // [ { id: 2, name: 'Parcel'},\n * //   { id: 2, name: 'webpack'} ]\n * //\n * // [ { id: 3, name: 'TSLint'} ]\n * ```\n *\n * ### Pivot data on the id field\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { groupBy, map, mergeMap, reduce } from 'rxjs/operators';\n *\n * of(\n *   { id: 1, name: 'JavaScript' },\n *   { id: 2, name: 'Parcel' },\n *   { id: 2, name: 'webpack' },\n *   { id: 1, name: 'TypeScript' },\n *   { id: 3, name: 'TSLint' }\n * )\n *   .pipe(\n *     groupBy(p => p.id, p => p.name),\n *     mergeMap(group$ =>\n *       group$.pipe(reduce((acc, cur) => [...acc, cur], [`${group$.key}`]))\n *     ),\n *     map(arr => ({ id: parseInt(arr[0], 10), values: arr.slice(1) }))\n *  )\n *  .subscribe(p => console.log(p));\n *\n * // displays:\n * // { id: 1, values: [ 'JavaScript', 'TypeScript' ] }\n * // { id: 2, values: [ 'Parcel', 'webpack' ] }\n * // { id: 3, values: [ 'TSLint' ] }\n * ```\n *\n * @param {function(value: T): K} keySelector A function that extracts the key\n * for each item.\n * @param {function(value: T): R} [elementSelector] A function that extracts the\n * return element for each item.\n * @param {function(grouped: GroupedObservable<K,R>): Observable<any>} [durationSelector]\n * A function that returns an Observable to determine how long each group should\n * exist.\n * @return {Observable<GroupedObservable<K,R>>} An Observable that emits\n * GroupedObservables, each of which corresponds to a unique key value and each\n * of which emits those items from the source Observable that share that key\n * value.\n * @method groupBy\n * @owner Observable\n */\nexport function groupBy<T, K, R>(keySelector: (value: T) => K,\n                                 elementSelector?: ((value: T) => R) | void,\n                                 durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>,\n                                 subjectSelector?: () => Subject<R>): OperatorFunction<T, GroupedObservable<K, R>> {\n  return (source: Observable<T>) =>\n    source.lift(new GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector));\n}\n\nexport interface RefCountSubscription {\n  count: number;\n  unsubscribe: () => void;\n  closed: boolean;\n  attemptedToUnsubscribe: boolean;\n}\n\nclass GroupByOperator<T, K, R> implements Operator<T, GroupedObservable<K, R>> {\n  constructor(private keySelector: (value: T) => K,\n              private elementSelector?: ((value: T) => R) | void,\n              private durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>,\n              private subjectSelector?: () => Subject<R>) {\n  }\n\n  call(subscriber: Subscriber<GroupedObservable<K, R>>, source: any): any {\n    return source.subscribe(new GroupBySubscriber(\n      subscriber, this.keySelector, this.elementSelector, this.durationSelector, this.subjectSelector\n    ));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass GroupBySubscriber<T, K, R> extends Subscriber<T> implements RefCountSubscription {\n  private groups: Map<K, Subject<T | R>> = null;\n  public attemptedToUnsubscribe: boolean = false;\n  public count: number = 0;\n\n  constructor(destination: Subscriber<GroupedObservable<K, R>>,\n              private keySelector: (value: T) => K,\n              private elementSelector?: ((value: T) => R) | void,\n              private durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>,\n              private subjectSelector?: () => Subject<R>) {\n    super(destination);\n  }\n\n  protected _next(value: T): void {\n    let key: K;\n    try {\n      key = this.keySelector(value);\n    } catch (err) {\n      this.error(err);\n      return;\n    }\n\n    this._group(value, key);\n  }\n\n  private _group(value: T, key: K) {\n    let groups = this.groups;\n\n    if (!groups) {\n      groups = this.groups = new Map<K, Subject<T | R>>();\n    }\n\n    let group = groups.get(key);\n\n    let element: R;\n    if (this.elementSelector) {\n      try {\n        element = this.elementSelector(value);\n      } catch (err) {\n        this.error(err);\n      }\n    } else {\n      element = <any>value;\n    }\n\n    if (!group) {\n      group = (this.subjectSelector ? this.subjectSelector() : new Subject<R>()) as Subject<T | R>;\n      groups.set(key, group);\n      const groupedObservable = new GroupedObservable(key, group, this);\n      this.destination.next(groupedObservable);\n      if (this.durationSelector) {\n        let duration: any;\n        try {\n          duration = this.durationSelector(new GroupedObservable<K, R>(key, <Subject<R>>group));\n        } catch (err) {\n          this.error(err);\n          return;\n        }\n        this.add(duration.subscribe(new GroupDurationSubscriber(key, group, this)));\n      }\n    }\n\n    if (!group.closed) {\n      group.next(element);\n    }\n  }\n\n  protected _error(err: any): void {\n    const groups = this.groups;\n    if (groups) {\n      groups.forEach((group, key) => {\n        group.error(err);\n      });\n\n      groups.clear();\n    }\n    this.destination.error(err);\n  }\n\n  protected _complete(): void {\n    const groups = this.groups;\n    if (groups) {\n      groups.forEach((group, key) => {\n        group.complete();\n      });\n\n      groups.clear();\n    }\n    this.destination.complete();\n  }\n\n  removeGroup(key: K): void {\n    this.groups.delete(key);\n  }\n\n  unsubscribe() {\n    if (!this.closed) {\n      this.attemptedToUnsubscribe = true;\n      if (this.count === 0) {\n        super.unsubscribe();\n      }\n    }\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass GroupDurationSubscriber<K, T> extends Subscriber<T> {\n  constructor(private key: K,\n              private group: Subject<T>,\n              private parent: GroupBySubscriber<any, K, T | any>) {\n    super(group);\n  }\n\n  protected _next(value: T): void {\n    this.complete();\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _unsubscribe() {\n    const { parent, key } = this;\n    this.key = this.parent = null;\n    if (parent) {\n      parent.removeGroup(key);\n    }\n  }\n}\n\n/**\n * An Observable representing values belonging to the same group represented by\n * a common key. The values emitted by a GroupedObservable come from the source\n * Observable. The common key is available as the field `key` on a\n * GroupedObservable instance.\n *\n * @class GroupedObservable<K, T>\n */\nexport class GroupedObservable<K, T> extends Observable<T> {\n  /** @deprecated Do not construct this type. Internal use only */\n  constructor(public key: K,\n              private groupSubject: Subject<T>,\n              private refCountSubscription?: RefCountSubscription) {\n    super();\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _subscribe(subscriber: Subscriber<T>) {\n    const subscription = new Subscription();\n    const { refCountSubscription, groupSubject } = this;\n    if (refCountSubscription && !refCountSubscription.closed) {\n      subscription.add(new InnerRefCountSubscription(refCountSubscription));\n    }\n    subscription.add(groupSubject.subscribe(subscriber));\n    return subscription;\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass InnerRefCountSubscription extends Subscription {\n  constructor(private parent: RefCountSubscription) {\n    super();\n    parent.count++;\n  }\n\n  unsubscribe() {\n    const parent = this.parent;\n    if (!parent.closed && !this.closed) {\n      super.unsubscribe();\n      parent.count -= 1;\n      if (parent.count === 0 && parent.attemptedToUnsubscribe) {\n        parent.unsubscribe();\n      }\n    }\n  }\n}\n","import { Subject } from './Subject';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { SubscriptionLike } from './types';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\n\n/**\n * A variant of Subject that requires an initial value and emits its current\n * value whenever it is subscribed to.\n *\n * @class BehaviorSubject<T>\n */\nexport class BehaviorSubject<T> extends Subject<T> {\n\n  constructor(private _value: T) {\n    super();\n  }\n\n  get value(): T {\n    return this.getValue();\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _subscribe(subscriber: Subscriber<T>): Subscription {\n    const subscription = super._subscribe(subscriber);\n    if (subscription && !(<SubscriptionLike>subscription).closed) {\n      subscriber.next(this._value);\n    }\n    return subscription;\n  }\n\n  getValue(): T {\n    if (this.hasError) {\n      throw this.thrownError;\n    } else if (this.closed) {\n      throw new ObjectUnsubscribedError();\n    } else {\n      return this._value;\n    }\n  }\n\n  next(value: T): void {\n    super.next(this._value = value);\n  }\n}\n","import { QueueAction } from './QueueAction';\nimport { QueueScheduler } from './QueueScheduler';\n\n/**\n *\n * Queue Scheduler\n *\n * <span class=\"informal\">Put every next task on a queue, instead of executing it immediately</span>\n *\n * `queue` scheduler, when used with delay, behaves the same as {@link asyncScheduler} scheduler.\n *\n * When used without delay, it schedules given task synchronously - executes it right when\n * it is scheduled. However when called recursively, that is when inside the scheduled task,\n * another task is scheduled with queue scheduler, instead of executing immediately as well,\n * that task will be put on a queue and wait for current one to finish.\n *\n * This means that when you execute task with `queue` scheduler, you are sure it will end\n * before any other task scheduled with that scheduler will start.\n *\n * ## Examples\n * Schedule recursively first, then do something\n * ```ts\n * import { queueScheduler } from 'rxjs';\n *\n * queueScheduler.schedule(() => {\n *   queueScheduler.schedule(() => console.log('second')); // will not happen now, but will be put on a queue\n *\n *   console.log('first');\n * });\n *\n * // Logs:\n * // \"first\"\n * // \"second\"\n * ```\n *\n * Reschedule itself recursively\n * ```ts\n * import { queueScheduler } from 'rxjs';\n *\n * queueScheduler.schedule(function(state) {\n *   if (state !== 0) {\n *     console.log('before', state);\n *     this.schedule(state - 1); // `this` references currently executing Action,\n *                               // which we reschedule with new state\n *     console.log('after', state);\n *   }\n * }, 0, 3);\n *\n * // In scheduler that runs recursively, you would expect:\n * // \"before\", 3\n * // \"before\", 2\n * // \"before\", 1\n * // \"after\", 1\n * // \"after\", 2\n * // \"after\", 3\n *\n * // But with queue it logs:\n * // \"before\", 3\n * // \"after\", 3\n * // \"before\", 2\n * // \"after\", 2\n * // \"before\", 1\n * // \"after\", 1\n * ```\n */\nexport const queueScheduler = new QueueScheduler(QueueAction);\n\n/**\n * @deprecated renamed. Use {@link queueScheduler}\n */\nexport const queue = queueScheduler;\n","import { Action } from './scheduler/Action';\nimport { Subscription } from './Subscription';\nimport { SchedulerLike, SchedulerAction } from './types';\n\n/**\n * An execution context and a data structure to order tasks and schedule their\n * execution. Provides a notion of (potentially virtual) time, through the\n * `now()` getter method.\n *\n * Each unit of work in a Scheduler is called an `Action`.\n *\n * ```ts\n * class Scheduler {\n *   now(): number;\n *   schedule(work, delay?, state?): Subscription;\n * }\n * ```\n *\n * @class Scheduler\n * @deprecated Scheduler is an internal implementation detail of RxJS, and\n * should not be used directly. Rather, create your own class and implement\n * {@link SchedulerLike}\n */\nexport class Scheduler implements SchedulerLike {\n\n  /**\n   * Note: the extra arrow function wrapper is to make testing by overriding\n   * Date.now easier.\n   * @nocollapse\n   */\n  public static now: () => number = () => Date.now();\n\n  constructor(private SchedulerAction: typeof Action,\n              now: () => number = Scheduler.now) {\n    this.now = now;\n  }\n\n  /**\n   * A getter method that returns a number representing the current time\n   * (at the time this function was called) according to the scheduler's own\n   * internal clock.\n   * @return {number} A number that represents the current time. May or may not\n   * have a relation to wall-clock time. May or may not refer to a time unit\n   * (e.g. milliseconds).\n   */\n  public now: () => number;\n\n  /**\n   * Schedules a function, `work`, for execution. May happen at some point in\n   * the future, according to the `delay` parameter, if specified. May be passed\n   * some context object, `state`, which will be passed to the `work` function.\n   *\n   * The given arguments will be processed an stored as an Action object in a\n   * queue of actions.\n   *\n   * @param {function(state: ?T): ?Subscription} work A function representing a\n   * task, or some unit of work to be executed by the Scheduler.\n   * @param {number} [delay] Time to wait before executing the work, where the\n   * time unit is implicit and defined by the Scheduler itself.\n   * @param {T} [state] Some contextual data that the `work` function uses when\n   * called by the Scheduler.\n   * @return {Subscription} A subscription in order to be able to unsubscribe\n   * the scheduled work.\n   */\n  public schedule<T>(work: (this: SchedulerAction<T>, state?: T) => void, delay: number = 0, state?: T): Subscription {\n    return new this.SchedulerAction<T>(this, work).schedule(state, delay);\n  }\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { Notification } from '../Notification';\nimport { MonoTypeOperatorFunction, PartialObserver, SchedulerAction, SchedulerLike, TeardownLogic } from '../types';\n\n/**\n *\n * Re-emits all notifications from source Observable with specified scheduler.\n *\n * <span class=\"informal\">Ensure a specific scheduler is used, from outside of an Observable.</span>\n *\n * `observeOn` is an operator that accepts a scheduler as a first parameter, which will be used to reschedule\n * notifications emitted by the source Observable. It might be useful, if you do not have control over\n * internal scheduler of a given Observable, but want to control when its values are emitted nevertheless.\n *\n * Returned Observable emits the same notifications (nexted values, complete and error events) as the source Observable,\n * but rescheduled with provided scheduler. Note that this doesn't mean that source Observables internal\n * scheduler will be replaced in any way. Original scheduler still will be used, but when the source Observable emits\n * notification, it will be immediately scheduled again - this time with scheduler passed to `observeOn`.\n * An anti-pattern would be calling `observeOn` on Observable that emits lots of values synchronously, to split\n * that emissions into asynchronous chunks. For this to happen, scheduler would have to be passed into the source\n * Observable directly (usually into the operator that creates it). `observeOn` simply delays notifications a\n * little bit more, to ensure that they are emitted at expected moments.\n *\n * As a matter of fact, `observeOn` accepts second parameter, which specifies in milliseconds with what delay notifications\n * will be emitted. The main difference between {@link delay} operator and `observeOn` is that `observeOn`\n * will delay all notifications - including error notifications - while `delay` will pass through error\n * from source Observable immediately when it is emitted. In general it is highly recommended to use `delay` operator\n * for any kind of delaying of values in the stream, while using `observeOn` to specify which scheduler should be used\n * for notification emissions in general.\n *\n * ## Example\n * Ensure values in subscribe are called just before browser repaint.\n * ```ts\n * import { interval } from 'rxjs';\n * import { observeOn } from 'rxjs/operators';\n *\n * const intervals = interval(10);                // Intervals are scheduled\n *                                                // with async scheduler by default...\n * intervals.pipe(\n *   observeOn(animationFrameScheduler),          // ...but we will observe on animationFrame\n * )                                              // scheduler to ensure smooth animation.\n * .subscribe(val => {\n *   someDiv.style.height = val + 'px';\n * });\n * ```\n *\n * @see {@link delay}\n *\n * @param {SchedulerLike} scheduler Scheduler that will be used to reschedule notifications from source Observable.\n * @param {number} [delay] Number of milliseconds that states with what delay every notification should be rescheduled.\n * @return {Observable<T>} Observable that emits the same notifications as the source Observable,\n * but with provided scheduler.\n *\n * @method observeOn\n * @owner Observable\n */\nexport function observeOn<T>(scheduler: SchedulerLike, delay: number = 0): MonoTypeOperatorFunction<T> {\n  return function observeOnOperatorFunction(source: Observable<T>): Observable<T> {\n    return source.lift(new ObserveOnOperator(scheduler, delay));\n  };\n}\n\nexport class ObserveOnOperator<T> implements Operator<T, T> {\n  constructor(private scheduler: SchedulerLike, private delay: number = 0) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class ObserveOnSubscriber<T> extends Subscriber<T> {\n  /** @nocollapse */\n  static dispatch(this: SchedulerAction<ObserveOnMessage>, arg: ObserveOnMessage) {\n    const { notification, destination } = arg;\n    notification.observe(destination);\n    this.unsubscribe();\n  }\n\n  constructor(destination: Subscriber<T>,\n              private scheduler: SchedulerLike,\n              private delay: number = 0) {\n    super(destination);\n  }\n\n  private scheduleMessage(notification: Notification<any>): void {\n    const destination = this.destination as Subscription;\n    destination.add(this.scheduler.schedule(\n      ObserveOnSubscriber.dispatch,\n      this.delay,\n      new ObserveOnMessage(notification, this.destination)\n    ));\n  }\n\n  protected _next(value: T): void {\n    this.scheduleMessage(Notification.createNext(value));\n  }\n\n  protected _error(err: any): void {\n    this.scheduleMessage(Notification.createError(err));\n    this.unsubscribe();\n  }\n\n  protected _complete(): void {\n    this.scheduleMessage(Notification.createComplete());\n    this.unsubscribe();\n  }\n}\n\nexport class ObserveOnMessage {\n  constructor(public notification: Notification<any>,\n              public destination: PartialObserver<any>) {\n  }\n}\n","import { Subscriber } from '../Subscriber';\n\n/**\n * Subscribes to an ArrayLike with a subscriber\n * @param array The array or array-like to subscribe to\n */\nexport const subscribeToArray = <T>(array: ArrayLike<T>) => (subscriber: Subscriber<T>) => {\n  for (let i = 0, len = array.length; i < len && !subscriber.closed; i++) {\n    subscriber.next(array[i]);\n  }\n  subscriber.complete();\n};\n","import { AsapAction } from './AsapAction';\nimport { AsapScheduler } from './AsapScheduler';\n\n/**\n *\n * Asap Scheduler\n *\n * <span class=\"informal\">Perform task as fast as it can be performed asynchronously</span>\n *\n * `asap` scheduler behaves the same as {@link asyncScheduler} scheduler when you use it to delay task\n * in time. If however you set delay to `0`, `asap` will wait for current synchronously executing\n * code to end and then it will try to execute given task as fast as possible.\n *\n * `asap` scheduler will do its best to minimize time between end of currently executing code\n * and start of scheduled task. This makes it best candidate for performing so called \"deferring\".\n * Traditionally this was achieved by calling `setTimeout(deferredTask, 0)`, but that technique involves\n * some (although minimal) unwanted delay.\n *\n * Note that using `asap` scheduler does not necessarily mean that your task will be first to process\n * after currently executing code. In particular, if some task was also scheduled with `asap` before,\n * that task will execute first. That being said, if you need to schedule task asynchronously, but\n * as soon as possible, `asap` scheduler is your best bet.\n *\n * ## Example\n * Compare async and asap scheduler<\n * ```ts\n * import { asapScheduler, asyncScheduler } from 'rxjs';\n *\n * asyncScheduler.schedule(() => console.log('async')); // scheduling 'async' first...\n * asapScheduler.schedule(() => console.log('asap'));\n *\n * // Logs:\n * // \"asap\"\n * // \"async\"\n * // ... but 'asap' goes first!\n * ```\n */\nexport const asapScheduler = new AsapScheduler(AsapAction);\n\n/**\n * @deprecated renamed. Use {@link asapScheduler}\n */\nexport const asap = asapScheduler;\n","export interface TimeoutError extends Error {\n}\n\nexport interface TimeoutErrorCtor {\n  new(): TimeoutError;\n}\n\nconst TimeoutErrorImpl = (() => {\n  function TimeoutErrorImpl(this: any) {\n    Error.call(this);\n    this.message = 'Timeout has occurred';\n    this.name = 'TimeoutError';\n    return this;\n  }\n\n  TimeoutErrorImpl.prototype = Object.create(Error.prototype);\n\n  return TimeoutErrorImpl;\n})();\n\n/**\n * An error thrown when duetime elapses.\n *\n * @see {@link operators/timeout}\n *\n * @class TimeoutError\n */\nexport const TimeoutError: TimeoutErrorCtor = TimeoutErrorImpl as any;\n","export const isArrayLike = (<T>(x: any): x is ArrayLike<T> => x && typeof x.length === 'number' && typeof x !== 'function');","/**\n * Tests to see if the object is an ES2015 (ES6) Promise\n * @see {@link https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects}\n * @param value the object to test\n */\nexport function isPromise(value: any): value is PromiseLike<any> {\n  return !!value && typeof (<any>value).subscribe !== 'function' && typeof (value as any).then === 'function';\n}\n","\nimport { mergeAll } from './mergeAll';\nimport { OperatorFunction, ObservableInput } from '../types';\n\nexport function concatAll<T>(): OperatorFunction<ObservableInput<T>, T>;\nexport function concatAll<R>(): OperatorFunction<any, R>;\n\n/**\n * Converts a higher-order Observable into a first-order Observable by\n * concatenating the inner Observables in order.\n *\n * <span class=\"informal\">Flattens an Observable-of-Observables by putting one\n * inner Observable after the other.</span>\n *\n * ![](concatAll.png)\n *\n * Joins every Observable emitted by the source (a higher-order Observable), in\n * a serial fashion. It subscribes to each inner Observable only after the\n * previous inner Observable has completed, and merges all of their values into\n * the returned observable.\n *\n * __Warning:__ If the source Observable emits Observables quickly and\n * endlessly, and the inner Observables it emits generally complete slower than\n * the source emits, you can run into memory issues as the incoming Observables\n * collect in an unbounded buffer.\n *\n * Note: `concatAll` is equivalent to `mergeAll` with concurrency parameter set\n * to `1`.\n *\n * ## Example\n *\n * For each click event, tick every second from 0 to 3, with no concurrency\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { map, take, concatAll } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n *   map(ev => interval(1000).pipe(take(4))),\n * );\n * const firstOrder = higherOrder.pipe(concatAll());\n * firstOrder.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // (results are not concurrent)\n * // For every click on the \"document\" it will emit values 0 to 3 spaced\n * // on a 1000ms interval\n * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3\n * ```\n *\n * @see {@link combineAll}\n * @see {@link concat}\n * @see {@link concatMap}\n * @see {@link concatMapTo}\n * @see {@link exhaust}\n * @see {@link mergeAll}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link zipAll}\n *\n * @return {Observable} An Observable emitting values from all the inner\n * Observables concatenated.\n * @method concatAll\n * @owner Observable\n */\nexport function concatAll<T>(): OperatorFunction<ObservableInput<T>, T> {\n  return mergeAll<T>(1);\n}\n","import { scheduleObservable } from './scheduleObservable';\nimport { schedulePromise } from './schedulePromise';\nimport { scheduleArray } from './scheduleArray';\nimport { scheduleIterable } from './scheduleIterable';\nimport { ObservableInput, SchedulerLike, Observable } from 'rxjs';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isPromise } from '../util/isPromise';\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isIterable } from '../util/isIterable';\n\n/**\n * Converts from a common {@link ObservableInput} type to an observable where subscription and emissions\n * are scheduled on the provided scheduler.\n *\n * @see from\n * @see of\n *\n * @param input The observable, array, promise, iterable, etc you would like to schedule\n * @param scheduler The scheduler to use to schedule the subscription and emissions from\n * the returned observable.\n */\nexport function scheduled<T>(input: ObservableInput<T>, scheduler: SchedulerLike): Observable<T> {\n  if (input != null) {\n    if (isInteropObservable(input)) {\n      return scheduleObservable(input, scheduler);\n    } else if (isPromise(input)) {\n      return schedulePromise(input, scheduler);\n    } else if (isArrayLike(input)) {\n      return scheduleArray(input, scheduler);\n    }  else if (isIterable(input) || typeof input === 'string') {\n      return scheduleIterable(input, scheduler);\n    }\n  }\n\n  throw new TypeError((input !== null && typeof input || input) + ' is not observable');\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput, SchedulerLike} from '../types';\nimport { isScheduler } from '../util/isScheduler';\nimport { mergeAll } from '../operators/mergeAll';\nimport { fromArray } from './fromArray';\n\n/* tslint:disable:max-line-length */\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge<T>(v1: ObservableInput<T>, scheduler: SchedulerLike): Observable<T>;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge<T>(v1: ObservableInput<T>, concurrent: number, scheduler: SchedulerLike): Observable<T>;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge<T, T2>(v1: ObservableInput<T>, v2: ObservableInput<T2>, scheduler: SchedulerLike): Observable<T | T2>;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge<T, T2>(v1: ObservableInput<T>, v2: ObservableInput<T2>, concurrent: number, scheduler: SchedulerLike): Observable<T | T2>;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge<T, T2, T3>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, scheduler: SchedulerLike): Observable<T | T2 | T3>;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge<T, T2, T3>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, concurrent: number, scheduler: SchedulerLike): Observable<T | T2 | T3>;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge<T, T2, T3, T4>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4>;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge<T, T2, T3, T4>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, concurrent: number, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4>;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge<T, T2, T3, T4, T5>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4 | T5>;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge<T, T2, T3, T4, T5>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, concurrent: number, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4 | T5>;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge<T, T2, T3, T4, T5, T6>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4 | T5 | T6>;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge<T, T2, T3, T4, T5, T6>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>, concurrent: number, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4 | T5 | T6>;\n\nexport function merge<T>(v1: ObservableInput<T>): Observable<T>;\nexport function merge<T>(v1: ObservableInput<T>, concurrent?: number): Observable<T>;\nexport function merge<T, T2>(v1: ObservableInput<T>, v2: ObservableInput<T2>): Observable<T | T2>;\nexport function merge<T, T2>(v1: ObservableInput<T>, v2: ObservableInput<T2>, concurrent?: number): Observable<T | T2>;\nexport function merge<T, T2, T3>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>): Observable<T | T2 | T3>;\nexport function merge<T, T2, T3>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, concurrent?: number): Observable<T | T2 | T3>;\nexport function merge<T, T2, T3, T4>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>): Observable<T | T2 | T3 | T4>;\nexport function merge<T, T2, T3, T4>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, concurrent?: number): Observable<T | T2 | T3 | T4>;\nexport function merge<T, T2, T3, T4, T5>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>): Observable<T | T2 | T3 | T4 | T5>;\nexport function merge<T, T2, T3, T4, T5>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, concurrent?: number): Observable<T | T2 | T3 | T4 | T5>;\nexport function merge<T, T2, T3, T4, T5, T6>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>): Observable<T | T2 | T3 | T4 | T5 | T6>;\nexport function merge<T, T2, T3, T4, T5, T6>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>, concurrent?: number): Observable<T | T2 | T3 | T4 | T5 | T6>;\nexport function merge<T>(...observables: (ObservableInput<T> | number)[]): Observable<T>;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge<T>(...observables: (ObservableInput<T> | SchedulerLike | number)[]): Observable<T>;\nexport function merge<T, R>(...observables: (ObservableInput<any> | number)[]): Observable<R>;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge<T, R>(...observables: (ObservableInput<any> | SchedulerLike | number)[]): Observable<R>;\n/* tslint:enable:max-line-length */\n/**\n * Creates an output Observable which concurrently emits all values from every\n * given input Observable.\n *\n * <span class=\"informal\">Flattens multiple Observables together by blending\n * their values into one Observable.</span>\n *\n * ![](merge.png)\n *\n * `merge` subscribes to each given input Observable (as arguments), and simply\n * forwards (without doing any transformation) all the values from all the input\n * Observables to the output Observable. The output Observable only completes\n * once all input Observables have completed. Any error delivered by an input\n * Observable will be immediately emitted on the output Observable.\n *\n * ## Examples\n * ### Merge together two Observables: 1s interval and clicks\n * ```ts\n * import { merge, fromEvent, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const timer = interval(1000);\n * const clicksOrTimer = merge(clicks, timer);\n * clicksOrTimer.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // timer will emit ascending values, one every second(1000ms) to console\n * // clicks logs MouseEvents to console everytime the \"document\" is clicked\n * // Since the two streams are merged you see these happening\n * // as they occur.\n * ```\n *\n * ### Merge together 3 Observables, but only 2 run concurrently\n * ```ts\n * import { merge, interval } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const timer1 = interval(1000).pipe(take(10));\n * const timer2 = interval(2000).pipe(take(6));\n * const timer3 = interval(500).pipe(take(10));\n * const concurrent = 2; // the argument\n * const merged = merge(timer1, timer2, timer3, concurrent);\n * merged.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // - First timer1 and timer2 will run concurrently\n * // - timer1 will emit a value every 1000ms for 10 iterations\n * // - timer2 will emit a value every 2000ms for 6 iterations\n * // - after timer1 hits its max iteration, timer2 will\n * //   continue, and timer3 will start to run concurrently with timer2\n * // - when timer2 hits its max iteration it terminates, and\n * //   timer3 will continue to emit a value every 500ms until it is complete\n * ```\n *\n * @see {@link mergeAll}\n * @see {@link mergeMap}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n *\n * @param {...ObservableInput} observables Input Observables to merge together.\n * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input\n * Observables being subscribed to concurrently.\n * @param {SchedulerLike} [scheduler=null] The {@link SchedulerLike} to use for managing\n * concurrency of input Observables.\n * @return {Observable} an Observable that emits items that are the result of\n * every input Observable.\n * @static true\n * @name merge\n * @owner Observable\n */\nexport function merge<T, R>(...observables: Array<ObservableInput<any> | SchedulerLike | number>): Observable<R> {\n let concurrent = Number.POSITIVE_INFINITY;\n let scheduler: SchedulerLike = null;\n  let last: any = observables[observables.length - 1];\n  if (isScheduler(last)) {\n    scheduler = <SchedulerLike>observables.pop();\n    if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {\n      concurrent = <number>observables.pop();\n    }\n  } else if (typeof last === 'number') {\n    concurrent = <number>observables.pop();\n  }\n\n  if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable) {\n    return <Observable<R>>observables[0];\n  }\n\n  return mergeAll<R>(concurrent)(fromArray<any>(observables, scheduler));\n}\n","import { Observable } from '../Observable';\nimport { noop } from '../util/noop';\n\n/**\n * An Observable that emits no items to the Observer and never completes.\n *\n * ![](never.png)\n *\n * A simple Observable that emits neither values nor errors nor the completion\n * notification. It can be used for testing purposes or for composing with other\n * Observables. Please note that by never emitting a complete notification, this\n * Observable keeps the subscription from being disposed automatically.\n * Subscriptions need to be manually disposed.\n *\n * ##  Example\n * ### Emit the number 7, then never emit anything else (not even complete)\n * ```ts\n * import { NEVER } from 'rxjs';\n * import { startWith } from 'rxjs/operators';\n *\n * function info() {\n *   console.log('Will not be called');\n * }\n * const result = NEVER.pipe(startWith(7));\n * result.subscribe(x => console.log(x), info, info);\n *\n * ```\n *\n * @see {@link Observable}\n * @see {@link index/EMPTY}\n * @see {@link of}\n * @see {@link throwError}\n */\nexport const NEVER = new Observable<never>(noop);\n\n/**\n * @deprecated Deprecated in favor of using {@link NEVER} constant.\n */\nexport function never () {\n  return NEVER;\n}\n","export function not(pred: Function, thisArg: any): Function {\n  function notPred(): any {\n    return !((<any> notPred).pred.apply((<any> notPred).thisArg, arguments));\n  }\n  (<any> notPred).pred = pred;\n  (<any> notPred).thisArg = thisArg;\n  return notPred;\n}","import { Observable } from '../Observable';\nimport { isArray } from '../util/isArray';\nimport { fromArray } from './fromArray';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { TeardownLogic, ObservableInput } from '../types';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\n\n// tslint:disable:max-line-length\nexport function race<A>(arg: [ObservableInput<A>]): Observable<A>;\nexport function race<A, B>(arg: [ObservableInput<A>, ObservableInput<B>]): Observable<A | B>;\nexport function race<A, B, C>(arg: [ObservableInput<A>, ObservableInput<B>, ObservableInput<C>]): Observable<A | B | C>;\nexport function race<A, B, C, D>(arg: [ObservableInput<A>, ObservableInput<B>, ObservableInput<C>, ObservableInput<D>]): Observable<A | B | C | D>;\nexport function race<A, B, C, D, E>(arg: [ObservableInput<A>, ObservableInput<B>, ObservableInput<C>, ObservableInput<D>, ObservableInput<E>]): Observable<A | B | C | D | E>;\nexport function race<T>(arg: ObservableInput<T>[]): Observable<T>;\nexport function race(arg: ObservableInput<any>[]): Observable<{}>;\n\nexport function race<A>(a: ObservableInput<A>): Observable<A>;\nexport function race<A, B>(a: ObservableInput<A>, b: ObservableInput<B>): Observable<A | B>;\nexport function race<A, B, C>(a: ObservableInput<A>, b: ObservableInput<B>, c: ObservableInput<C>): Observable<A | B | C>;\nexport function race<A, B, C, D>(a: ObservableInput<A>, b: ObservableInput<B>, c: ObservableInput<C>, d: ObservableInput<D>): Observable<A | B | C | D>;\nexport function race<A, B, C, D, E>(a: ObservableInput<A>, b: ObservableInput<B>, c: ObservableInput<C>, d: ObservableInput<D>, e: ObservableInput<E>): Observable<A | B | C | D | E>;\n// tslint:enable:max-line-length\n\nexport function race<T>(observables: ObservableInput<T>[]): Observable<T>;\nexport function race(observables: ObservableInput<any>[]): Observable<{}>;\nexport function race<T>(...observables: ObservableInput<T>[]): Observable<T>;\nexport function race(...observables: ObservableInput<any>[]): Observable<{}>;\n\n/**\n * Returns an Observable that mirrors the first source Observable to emit an item.\n *\n * ## Example\n * ### Subscribes to the observable that was the first to start emitting.\n *\n * ```ts\n * import { race, interval } from 'rxjs';\n * import { mapTo } from 'rxjs/operators';\n *\n * const obs1 = interval(1000).pipe(mapTo('fast one'));\n * const obs2 = interval(3000).pipe(mapTo('medium one'));\n * const obs3 = interval(5000).pipe(mapTo('slow one'));\n *\n * race(obs3, obs1, obs2)\n * .subscribe(\n *   winner => console.log(winner)\n * );\n *\n * // result:\n * // a series of 'fast one'\n * ```\n *\n * @param {...Observables} ...observables sources used to race for which Observable emits first.\n * @return {Observable} an Observable that mirrors the output of the first Observable to emit an item.\n * @static true\n * @name race\n * @owner Observable\n */\nexport function race<T>(...observables: ObservableInput<any>[]): Observable<T> {\n  // if the only argument is an array, it was most likely called with\n  // `race([obs1, obs2, ...])`\n  if (observables.length === 1) {\n    if (isArray(observables[0])) {\n      observables = observables[0] as Observable<any>[];\n    } else {\n      return observables[0] as Observable<T>;\n    }\n  }\n\n  return fromArray(observables, undefined).lift(new RaceOperator<T>());\n}\n\nexport class RaceOperator<T> implements Operator<T, T> {\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new RaceSubscriber(subscriber));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class RaceSubscriber<T> extends OuterSubscriber<T, T> {\n  private hasFirst: boolean = false;\n  private observables: Observable<any>[] = [];\n  private subscriptions: Subscription[] = [];\n\n  constructor(destination: Subscriber<T>) {\n    super(destination);\n  }\n\n  protected _next(observable: any): void {\n    this.observables.push(observable);\n  }\n\n  protected _complete() {\n    const observables = this.observables;\n    const len = observables.length;\n\n    if (len === 0) {\n      this.destination.complete!();\n    } else {\n      for (let i = 0; i < len && !this.hasFirst; i++) {\n        const observable = observables[i];\n        const subscription = subscribeToResult(this, observable, undefined, i)!;\n\n        if (this.subscriptions) {\n          this.subscriptions.push(subscription);\n        }\n        this.add(subscription);\n      }\n      this.observables = null!;\n    }\n  }\n\n  notifyNext(_outerValue: T, innerValue: T,\n             outerIndex: number): void {\n    if (!this.hasFirst) {\n      this.hasFirst = true;\n\n      for (let i = 0; i < this.subscriptions.length; i++) {\n        if (i !== outerIndex) {\n          let subscription = this.subscriptions[i];\n\n          subscription.unsubscribe();\n          this.remove(subscription);\n        }\n      }\n\n      this.subscriptions = null!;\n    }\n\n    this.destination.next!(innerValue);\n  }\n}\n","import { Observable } from '../Observable';\nimport { SchedulerAction, SchedulerLike } from '../types';\nimport { async } from '../scheduler/async';\nimport { isNumeric } from '../util/isNumeric';\nimport { isScheduler } from '../util/isScheduler';\nimport { Subscriber } from '../Subscriber';\n\n/**\n * Creates an Observable that starts emitting after an `dueTime` and\n * emits ever increasing numbers after each `period` of time thereafter.\n *\n * <span class=\"informal\">Its like {@link index/interval}, but you can specify when\n * should the emissions start.</span>\n *\n * ![](timer.png)\n *\n * `timer` returns an Observable that emits an infinite sequence of ascending\n * integers, with a constant interval of time, `period` of your choosing\n * between those emissions. The first emission happens after the specified\n * `dueTime`. The initial delay may be a `Date`. By default, this\n * operator uses the {@link asyncScheduler} {@link SchedulerLike} to provide a notion of time, but you\n * may pass any {@link SchedulerLike} to it. If `period` is not specified, the output\n * Observable emits only one value, `0`. Otherwise, it emits an infinite\n * sequence.\n *\n * ## Examples\n * ### Emits ascending numbers, one every second (1000ms), starting after 3 seconds\n * ```ts\n * import { timer } from 'rxjs';\n *\n * const numbers = timer(3000, 1000);\n * numbers.subscribe(x => console.log(x));\n * ```\n *\n * ### Emits one number after five seconds\n * ```ts\n * import { timer } from 'rxjs';\n *\n * const numbers = timer(5000);\n * numbers.subscribe(x => console.log(x));\n * ```\n * @see {@link index/interval}\n * @see {@link delay}\n *\n * @param {number|Date} [dueTime] The initial delay time specified as a Date object or as an integer denoting\n * milliseconds to wait before emitting the first value of 0`.\n * @param {number|SchedulerLike} [periodOrScheduler] The period of time between emissions of the\n * subsequent numbers.\n * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for scheduling\n * the emission of values, and providing a notion of \"time\".\n * @return {Observable} An Observable that emits a `0` after the\n * `dueTime` and ever increasing numbers after each `period` of time\n * thereafter.\n * @static true\n * @name timer\n * @owner Observable\n */\nexport function timer(dueTime: number | Date = 0,\n                      periodOrScheduler?: number | SchedulerLike,\n                      scheduler?: SchedulerLike): Observable<number> {\n  let period = -1;\n  if (isNumeric(periodOrScheduler)) {\n    period = Number(periodOrScheduler) < 1 && 1 || Number(periodOrScheduler);\n  } else if (isScheduler(periodOrScheduler)) {\n    scheduler = periodOrScheduler as any;\n  }\n\n  if (!isScheduler(scheduler)) {\n    scheduler = async;\n  }\n\n  return new Observable(subscriber => {\n    const due = isNumeric(dueTime)\n      ? (dueTime as number)\n      : (+dueTime - scheduler.now());\n\n    return scheduler.schedule(dispatch, due, {\n      index: 0, period, subscriber\n    });\n  });\n}\n\ninterface TimerState {\n  index: number;\n  period: number;\n  subscriber: Subscriber<number>;\n}\n\nfunction dispatch(this: SchedulerAction<TimerState>, state: TimerState) {\n  const { index, period, subscriber } = state;\n  subscriber.next(index);\n\n  if (subscriber.closed) {\n    return;\n  } else if (period === -1) {\n    return subscriber.complete();\n  }\n\n  state.index = index + 1;\n  this.schedule(state, period);\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { MonoTypeOperatorFunction, SubscribableOrPromise, TeardownLogic } from '../types';\nimport { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';\n\n/**\n * Ignores source values for a duration determined by another Observable, then\n * emits the most recent value from the source Observable, then repeats this\n * process.\n *\n * <span class=\"informal\">It's like {@link auditTime}, but the silencing\n * duration is determined by a second Observable.</span>\n *\n * ![](audit.png)\n *\n * `audit` is similar to `throttle`, but emits the last value from the silenced\n * time window, instead of the first value. `audit` emits the most recent value\n * from the source Observable on the output Observable as soon as its internal\n * timer becomes disabled, and ignores source values while the timer is enabled.\n * Initially, the timer is disabled. As soon as the first source value arrives,\n * the timer is enabled by calling the `durationSelector` function with the\n * source value, which returns the \"duration\" Observable. When the duration\n * Observable emits a value or completes, the timer is disabled, then the most\n * recent source value is emitted on the output Observable, and this process\n * repeats for the next source value.\n *\n * ## Example\n *\n * Emit clicks at a rate of at most one click per second\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { audit } from 'rxjs/operators'\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(audit(ev => interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n * @see {@link auditTime}\n * @see {@link debounce}\n * @see {@link delayWhen}\n * @see {@link sample}\n * @see {@link throttle}\n *\n * @param {function(value: T): SubscribableOrPromise} durationSelector A function\n * that receives a value from the source Observable, for computing the silencing\n * duration, returned as an Observable or a Promise.\n * @return {Observable<T>} An Observable that performs rate-limiting of\n * emissions from the source Observable.\n * @method audit\n * @owner Observable\n */\nexport function audit<T>(durationSelector: (value: T) => SubscribableOrPromise<any>): MonoTypeOperatorFunction<T> {\n  return function auditOperatorFunction(source: Observable<T>) {\n    return source.lift(new AuditOperator(durationSelector));\n  };\n}\n\nclass AuditOperator<T> implements Operator<T, T> {\n  constructor(private durationSelector: (value: T) => SubscribableOrPromise<any>) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new AuditSubscriber<T, T>(subscriber, this.durationSelector));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass AuditSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n\n  private value?: T;\n  private hasValue: boolean = false;\n  private throttled?: Subscription;\n\n  constructor(destination: Subscriber<T>,\n              private durationSelector: (value: T) => SubscribableOrPromise<any>) {\n    super(destination);\n  }\n\n  protected _next(value: T): void {\n    this.value = value;\n    this.hasValue = true;\n    if (!this.throttled) {\n      let duration;\n      try {\n        const { durationSelector } = this;\n        duration = durationSelector(value);\n      } catch (err) {\n        return this.destination.error!(err);\n      }\n      const innerSubscription = innerSubscribe(duration, new SimpleInnerSubscriber(this));\n      if (!innerSubscription || innerSubscription.closed) {\n        this.clearThrottle();\n      } else {\n        this.add(this.throttled = innerSubscription);\n      }\n    }\n  }\n\n  clearThrottle() {\n    const { value, hasValue, throttled } = this;\n    if (throttled) {\n      this.remove(throttled);\n      this.throttled = undefined;\n      throttled.unsubscribe();\n    }\n    if (hasValue) {\n      this.value = undefined;\n      this.hasValue = false;\n      this.destination.next!(value);\n    }\n  }\n\n  notifyNext(): void {\n    this.clearThrottle();\n  }\n\n  notifyComplete(): void {\n    this.clearThrottle();\n  }\n}\n","import { mergeMap } from './mergeMap';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function concatMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) =>  O): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function concatMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: undefined): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function concatMap<T, R, O extends ObservableInput<any>>(project: (value: T, index: number) =>  O, resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable, in a serialized fashion waiting for each one to complete before\n * merging the next.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link concatAll}.</span>\n *\n * ![](concatMap.png)\n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an (so-called \"inner\") Observable. Each new inner Observable is\n * concatenated with the previous inner Observable.\n *\n * __Warning:__ if source values arrive endlessly and faster than their\n * corresponding inner Observables can complete, it will result in memory issues\n * as inner Observables amass in an unbounded buffer waiting for their turn to\n * be subscribed to.\n *\n * Note: `concatMap` is equivalent to `mergeMap` with concurrency parameter set\n * to `1`.\n *\n * ## Example\n * For each click event, tick every second from 0 to 3, with no concurrency\n *\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { concatMap, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n *   concatMap(ev => interval(1000).pipe(take(4)))\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // (results are not concurrent)\n * // For every click on the \"document\" it will emit values 0 to 3 spaced\n * // on a 1000ms interval\n * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3\n * ```\n *\n * @see {@link concat}\n * @see {@link concatAll}\n * @see {@link concatMapTo}\n * @see {@link exhaustMap}\n * @see {@link mergeMap}\n * @see {@link switchMap}\n *\n * @param {function(value: T, ?index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @return {Observable} An Observable that emits the result of applying the\n * projection function (and the optional deprecated `resultSelector`) to each item emitted\n * by the source Observable and taking values from each projected inner\n * Observable sequentially.\n * @method concatMap\n * @owner Observable\n */\nexport function concatMap<T, R, O extends ObservableInput<any>>(\n  project: (value: T, index: number) => O,\n  resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, ObservedValueOf<O>|R> {\n  return mergeMap(project, resultSelector, 1);\n}\n","export function isDate(value: any): value is Date {\n  return value instanceof Date && !isNaN(+value);\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function distinctUntilChanged<T>(compare?: (x: T, y: T) => boolean): MonoTypeOperatorFunction<T>;\nexport function distinctUntilChanged<T, K>(compare: (x: K, y: K) => boolean, keySelector: (x: T) => K): MonoTypeOperatorFunction<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.\n *\n * If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted.\n *\n * If a comparator function is not provided, an equality check is used by default.\n *\n * ## Example\n * A simple example with numbers\n * ```ts\n * import { of } from 'rxjs';\n * import { distinctUntilChanged } from 'rxjs/operators';\n *\n * of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4).pipe(\n *     distinctUntilChanged(),\n *   )\n *   .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4\n * ```\n *\n * An example using a compare function\n * ```typescript\n * import { of } from 'rxjs';\n * import { distinctUntilChanged } from 'rxjs/operators';\n *\n * interface Person {\n *    age: number,\n *    name: string\n * }\n *\n * of<Person>(\n *     { age: 4, name: 'Foo'},\n *     { age: 7, name: 'Bar'},\n *     { age: 5, name: 'Foo'},\n *     { age: 6, name: 'Foo'},\n *   ).pipe(\n *     distinctUntilChanged((p: Person, q: Person) => p.name === q.name),\n *   )\n *   .subscribe(x => console.log(x));\n *\n * // displays:\n * // { age: 4, name: 'Foo' }\n * // { age: 7, name: 'Bar' }\n * // { age: 5, name: 'Foo' }\n * ```\n *\n * @see {@link distinct}\n * @see {@link distinctUntilKeyChanged}\n *\n * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.\n * @return {Observable} An Observable that emits items from the source Observable with distinct values.\n * @method distinctUntilChanged\n * @owner Observable\n */\nexport function distinctUntilChanged<T, K>(compare?: (x: K, y: K) => boolean, keySelector?: (x: T) => K): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => source.lift(new DistinctUntilChangedOperator<T, K>(compare, keySelector));\n}\n\nclass DistinctUntilChangedOperator<T, K> implements Operator<T, T> {\n  constructor(private compare: (x: K, y: K) => boolean,\n              private keySelector: (x: T) => K) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DistinctUntilChangedSubscriber<T, K> extends Subscriber<T> {\n  private key: K;\n  private hasKey: boolean = false;\n\n  constructor(destination: Subscriber<T>,\n              compare: (x: K, y: K) => boolean,\n              private keySelector: (x: T) => K) {\n    super(destination);\n    if (typeof compare === 'function') {\n      this.compare = compare;\n    }\n  }\n\n  private compare(x: any, y: any): boolean {\n    return x === y;\n  }\n\n  protected _next(value: T): void {\n    let key: any;\n    try {\n      const { keySelector } = this;\n      key = keySelector ? keySelector(value) : value;\n    } catch (err) {\n      return this.destination.error(err);\n    }\n    let result = false;\n    if (this.hasKey) {\n      try {\n        const { compare } = this;\n        result = compare(this.key, key);\n      } catch (err) {\n        return this.destination.error(err);\n      }\n    } else {\n      this.hasKey = true;\n    }\n    if (!result) {\n      this.key = key;\n      this.destination.next(value);\n    }\n  }\n}\n","import {Observable} from '../Observable';\nimport {Operator} from '../Operator';\nimport {Subscriber} from '../Subscriber';\nimport {OperatorFunction} from '../types';\n\nexport function find<T, S extends T>(predicate: (value: T, index: number, source: Observable<T>) => value is S,\n                                     thisArg?: any): OperatorFunction<T, S | undefined>;\nexport function find<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean,\n                        thisArg?: any): OperatorFunction<T, T | undefined>;\n/**\n * Emits only the first value emitted by the source Observable that meets some\n * condition.\n *\n * <span class=\"informal\">Finds the first value that passes some test and emits\n * that.</span>\n *\n * ![](find.png)\n *\n * `find` searches for the first item in the source Observable that matches the\n * specified condition embodied by the `predicate`, and returns the first\n * occurrence in the source. Unlike {@link first}, the `predicate` is required\n * in `find`, and does not emit an error if a valid value is not found.\n *\n * ## Example\n * Find and emit the first click that happens on a DIV element\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { find } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(find(ev => ev.target.tagName === 'DIV'));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link filter}\n * @see {@link first}\n * @see {@link findIndex}\n * @see {@link take}\n *\n * @param {function(value: T, index: number, source: Observable<T>): boolean} predicate\n * A function called with each item to test for condition matching.\n * @param {any} [thisArg] An optional argument to determine the value of `this`\n * in the `predicate` function.\n * @return {Observable<T>} An Observable of the first item that matches the\n * condition.\n * @method find\n * @owner Observable\n */\nexport function find<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean,\n                        thisArg?: any): OperatorFunction<T, T | undefined> {\n  if (typeof predicate !== 'function') {\n    throw new TypeError('predicate is not a function');\n  }\n  return (source: Observable<T>) => source.lift(new FindValueOperator(predicate, source, false, thisArg)) as Observable<T | undefined>;\n}\n\nexport class FindValueOperator<T> implements Operator<T, T | number | undefined> {\n  constructor(private predicate: (value: T, index: number, source: Observable<T>) => boolean,\n              private source: Observable<T>,\n              private yieldIndex: boolean,\n              private thisArg?: any) {\n  }\n\n  call(observer: Subscriber<T>, source: any): any {\n    return source.subscribe(new FindValueSubscriber(observer, this.predicate, this.source, this.yieldIndex, this.thisArg));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class FindValueSubscriber<T> extends Subscriber<T> {\n  private index: number = 0;\n\n  constructor(destination: Subscriber<T>,\n              private predicate: (value: T, index: number, source: Observable<T>) => boolean,\n              private source: Observable<T>,\n              private yieldIndex: boolean,\n              private thisArg?: any) {\n    super(destination);\n  }\n\n  private notifyComplete(value: any): void {\n    const destination = this.destination;\n\n    destination.next(value);\n    destination.complete();\n    this.unsubscribe();\n  }\n\n  protected _next(value: T): void {\n    const {predicate, thisArg} = this;\n    const index = this.index++;\n    try {\n      const result = predicate.call(thisArg || this, value, index, this.source);\n      if (result) {\n        this.notifyComplete(this.yieldIndex ? index : value);\n      }\n    } catch (err) {\n      this.destination.error(err);\n    }\n  }\n\n  protected _complete(): void {\n    this.notifyComplete(this.yieldIndex ? -1 : undefined);\n  }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\n\nimport { MonoTypeOperatorFunction, SubscribableOrPromise, TeardownLogic } from '../types';\nimport { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';\n\nexport interface ThrottleConfig {\n  leading?: boolean;\n  trailing?: boolean;\n}\n\nexport const defaultThrottleConfig: ThrottleConfig = {\n  leading: true,\n  trailing: false\n};\n\n/**\n * Emits a value from the source Observable, then ignores subsequent source\n * values for a duration determined by another Observable, then repeats this\n * process.\n *\n * <span class=\"informal\">It's like {@link throttleTime}, but the silencing\n * duration is determined by a second Observable.</span>\n *\n * ![](throttle.png)\n *\n * `throttle` emits the source Observable values on the output Observable\n * when its internal timer is disabled, and ignores source values when the timer\n * is enabled. Initially, the timer is disabled. As soon as the first source\n * value arrives, it is forwarded to the output Observable, and then the timer\n * is enabled by calling the `durationSelector` function with the source value,\n * which returns the \"duration\" Observable. When the duration Observable emits a\n * value or completes, the timer is disabled, and this process repeats for the\n * next source value.\n *\n * ## Example\n * Emit clicks at a rate of at most one click per second\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { throttle } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(throttle(ev => interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link audit}\n * @see {@link debounce}\n * @see {@link delayWhen}\n * @see {@link sample}\n * @see {@link throttleTime}\n *\n * @param {function(value: T): SubscribableOrPromise} durationSelector A function\n * that receives a value from the source Observable, for computing the silencing\n * duration for each source value, returned as an Observable or a Promise.\n * @param {Object} config a configuration object to define `leading` and `trailing` behavior. Defaults\n * to `{ leading: true, trailing: false }`.\n * @return {Observable<T>} An Observable that performs the throttle operation to\n * limit the rate of emissions from the source.\n * @method throttle\n * @owner Observable\n */\nexport function throttle<T>(durationSelector: (value: T) => SubscribableOrPromise<any>,\n                            config: ThrottleConfig = defaultThrottleConfig): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => source.lift(new ThrottleOperator(durationSelector, !!config.leading, !!config.trailing));\n}\n\nclass ThrottleOperator<T> implements Operator<T, T> {\n  constructor(private durationSelector: (value: T) => SubscribableOrPromise<any>,\n              private leading: boolean,\n              private trailing: boolean) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(\n      new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing)\n    );\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc\n * @ignore\n * @extends {Ignored}\n */\nclass ThrottleSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n  private _throttled?: Subscription;\n  private _sendValue?: T;\n  private _hasValue = false;\n\n  constructor(protected destination: Subscriber<T>,\n              private durationSelector: (value: T) => SubscribableOrPromise<number>,\n              private _leading: boolean,\n              private _trailing: boolean) {\n    super(destination);\n  }\n\n  protected _next(value: T): void {\n    this._hasValue = true;\n    this._sendValue = value;\n\n    if (!this._throttled) {\n      if (this._leading) {\n        this.send();\n      } else {\n        this.throttle(value);\n      }\n    }\n  }\n\n  private send() {\n    const { _hasValue, _sendValue } = this;\n    if (_hasValue) {\n      this.destination.next(_sendValue);\n      this.throttle(_sendValue!);\n    }\n    this._hasValue = false;\n    this._sendValue = undefined;\n  }\n\n  private throttle(value: T): void {\n    const duration = this.tryDurationSelector(value);\n    if (!!duration) {\n      this.add(this._throttled = innerSubscribe(duration, new SimpleInnerSubscriber(this)));\n    }\n  }\n\n  private tryDurationSelector(value: T): SubscribableOrPromise<any> | null {\n    try {\n      return this.durationSelector(value);\n    } catch (err) {\n      this.destination.error(err);\n      return null;\n    }\n  }\n\n  private throttlingDone() {\n    const { _throttled, _trailing } = this;\n    if (_throttled) {\n      _throttled.unsubscribe();\n    }\n    this._throttled = undefined;\n\n    if (_trailing) {\n      this.send();\n    }\n  }\n\n  notifyNext(): void {\n    this.throttlingDone();\n  }\n\n  notifyComplete(): void {\n    this.throttlingDone();\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { async } from '../scheduler/async';\nimport { Observable } from '../Observable';\nimport { isDate } from '../util/isDate';\nimport { ObservableInput, OperatorFunction, SchedulerAction, SchedulerLike, TeardownLogic } from '../types';\nimport { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';\n\n/* tslint:disable:max-line-length */\nexport function timeoutWith<T, R>(due: number | Date, withObservable: ObservableInput<R>, scheduler?: SchedulerLike): OperatorFunction<T, T | R>;\n/* tslint:enable:max-line-length */\n\n/**\n *\n * Errors if Observable does not emit a value in given time span, in case of which\n * subscribes to the second Observable.\n *\n * <span class=\"informal\">It's a version of `timeout` operator that let's you specify fallback Observable.</span>\n *\n * ![](timeoutWith.png)\n *\n * `timeoutWith` is a variation of `timeout` operator. It behaves exactly the same,\n * still accepting as a first argument either a number or a Date, which control - respectively -\n * when values of source Observable should be emitted or when it should complete.\n *\n * The only difference is that it accepts a second, required parameter. This parameter\n * should be an Observable which will be subscribed when source Observable fails any timeout check.\n * So whenever regular `timeout` would emit an error, `timeoutWith` will instead start re-emitting\n * values from second Observable. Note that this fallback Observable is not checked for timeouts\n * itself, so it can emit values and complete at arbitrary points in time. From the moment of a second\n * subscription, Observable returned from `timeoutWith` simply mirrors fallback stream. When that\n * stream completes, it completes as well.\n *\n * Scheduler, which in case of `timeout` is provided as as second argument, can be still provided\n * here - as a third, optional parameter. It still is used to schedule timeout checks and -\n * as a consequence - when second Observable will be subscribed, since subscription happens\n * immediately after failing check.\n *\n * ## Example\n * Add fallback observable\n * ```ts\n * import { interval } from 'rxjs';\n * import { timeoutWith } from 'rxjs/operators';\n *\n * const seconds = interval(1000);\n * const minutes = interval(60 * 1000);\n *\n * seconds.pipe(timeoutWith(900, minutes))\n *   .subscribe(\n *     value => console.log(value), // After 900ms, will start emitting `minutes`,\n *                                  // since first value of `seconds` will not arrive fast enough.\n *     err => console.log(err),     // Would be called after 900ms in case of `timeout`,\n *                                  // but here will never be called.\n *   );\n * ```\n *\n * @param {number|Date} due Number specifying period within which Observable must emit values\n *                          or Date specifying before when Observable should complete\n * @param {Observable<T>} withObservable Observable which will be subscribed if source fails timeout check.\n * @param {SchedulerLike} [scheduler] Scheduler controlling when timeout checks occur.\n * @return {Observable<T>} Observable that mirrors behaviour of source or, when timeout check fails, of an Observable\n *                          passed as a second parameter.\n * @method timeoutWith\n * @owner Observable\n */\nexport function timeoutWith<T, R>(due: number | Date,\n                                  withObservable: ObservableInput<R>,\n                                  scheduler: SchedulerLike = async): OperatorFunction<T, T | R> {\n  return (source: Observable<T>) => {\n    let absoluteTimeout = isDate(due);\n    let waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(<number>due);\n    return source.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler));\n  };\n}\n\nclass TimeoutWithOperator<T> implements Operator<T, T> {\n  constructor(private waitFor: number,\n              private absoluteTimeout: boolean,\n              private withObservable: ObservableInput<any>,\n              private scheduler: SchedulerLike) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new TimeoutWithSubscriber(\n      subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler\n    ));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass TimeoutWithSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n\n  private action?: SchedulerAction<TimeoutWithSubscriber<T, R>>;\n\n  constructor(destination: Subscriber<T>,\n              private absoluteTimeout: boolean,\n              private waitFor: number,\n              private withObservable: ObservableInput<any>,\n              private scheduler: SchedulerLike) {\n    super(destination);\n    this.scheduleTimeout();\n  }\n\n  private static dispatchTimeout<T, R>(subscriber: TimeoutWithSubscriber<T, R>): void {\n    const { withObservable } = subscriber;\n    subscriber._unsubscribeAndRecycle();\n    subscriber.add(innerSubscribe(withObservable, new SimpleInnerSubscriber(subscriber)));\n  }\n\n  private scheduleTimeout(): void {\n    const { action } = this;\n    if (action) {\n      // Recycle the action if we've already scheduled one. All the production\n      // Scheduler Actions mutate their state/delay time and return themeselves.\n      // VirtualActions are immutable, so they create and return a clone. In this\n      // case, we need to set the action reference to the most recent VirtualAction,\n      // to ensure that's the one we clone from next time.\n      this.action = (<SchedulerAction<TimeoutWithSubscriber<T, R>>> action.schedule(this, this.waitFor));\n    } else {\n      this.add(this.action = (<SchedulerAction<TimeoutWithSubscriber<T, R>>> this.scheduler.schedule<TimeoutWithSubscriber<T, R>>(\n        TimeoutWithSubscriber.dispatchTimeout as any, this.waitFor, this\n      )));\n    }\n  }\n\n  protected _next(value: T): void {\n    if (!this.absoluteTimeout) {\n      this.scheduleTimeout();\n    }\n    super._next(value);\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _unsubscribe() {\n    this.action = undefined;\n    this.scheduler = null!;\n    this.withObservable = null!;\n  }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport BrowserSupport from './browser-support';\n\nexport interface LoadScriptOptions {\n    async: boolean;\n    attributes: ScriptAttributes;\n}\n\nexport interface PreloadScriptOptions {\n    prefetch: boolean;\n}\n\nexport interface ScriptAttributes {\n    [key: string]: string;\n}\n\nexport default class ScriptLoader {\n    private _scripts: { [key: string]: Promise<void> } = {};\n    private _preloadedScripts: { [key: string]: Promise<void> } = {};\n\n    /**\n     * @internal\n     */\n    constructor(\n        private _browserSupport: BrowserSupport,\n        private _requestSender: RequestSender\n    ) {}\n\n    loadScript(src: string, options?: LoadScriptOptions): Promise<void> {\n        if (!this._scripts[src]) {\n            this._scripts[src] = new Promise((resolve, reject) => {\n                const script = document.createElement('script') as LegacyHTMLScriptElement;\n                const { async = false, attributes = {} } = options || {};\n\n                Object.keys(attributes)\n                    .forEach(key => {\n                        script.setAttribute(key, attributes[key]);\n                    });\n\n                script.onload = () => resolve();\n                script.onreadystatechange = () => resolve();\n                script.onerror = event => {\n                    delete this._scripts[src];\n                    reject(event);\n                };\n                script.async = async;\n                script.src = src;\n\n                document.body.appendChild(script);\n            });\n        }\n\n        return this._scripts[src];\n    }\n\n    loadScripts(urls: string[], options?: LoadScriptOptions): Promise<void> {\n        return Promise.all(urls.map(url => this.loadScript(url, options)))\n            .then(() => undefined);\n    }\n\n    preloadScript(url: string, options?: PreloadScriptOptions): Promise<void> {\n        if (!this._preloadedScripts[url]) {\n            this._preloadedScripts[url] = new Promise((resolve, reject) => {\n                const { prefetch = false } = options || {};\n                const rel = prefetch ? 'prefetch' : 'preload';\n\n                if (this._browserSupport.canSupportRel(rel)) {\n                    const preloadedScript = document.createElement('link');\n\n                    preloadedScript.as = 'script';\n                    preloadedScript.rel = rel;\n                    preloadedScript.href = url;\n\n                    preloadedScript.onload = () => {\n                        resolve();\n                    };\n\n                    preloadedScript.onerror = () => {\n                        delete this._preloadedScripts[url];\n                        reject();\n                    };\n\n                    document.head.appendChild(preloadedScript);\n                } else {\n                    this._requestSender.get(url, {\n                        credentials: false,\n                        headers: { Accept: 'application/javascript' },\n                    })\n                        .then(() => resolve())\n                        .catch(reject);\n                }\n            });\n        }\n\n        return this._preloadedScripts[url];\n    }\n\n    preloadScripts(urls: string[], options?: PreloadScriptOptions): Promise<void> {\n        return Promise.all(urls.map(url => this.preloadScript(url, options)))\n            .then(() => undefined);\n    }\n}\n\ninterface LegacyHTMLScriptElement extends HTMLScriptElement {\n    // `onreadystatechange` is needed to support legacy IE\n    onreadystatechange(this: HTMLElement, event: Event): any;\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport BrowserSupport from './browser-support';\nimport ScriptLoader from './script-loader';\n\nexport default function createScriptLoader(): ScriptLoader {\n    return new ScriptLoader(\n        new BrowserSupport(),\n        createRequestSender()\n    );\n}\n","'use strict';\nvar strictUriEncode = require('strict-uri-encode');\nvar objectAssign = require('object-assign');\nvar decodeComponent = require('decode-uri-component');\n\nfunction encoderForArrayFormat(opts) {\n\tswitch (opts.arrayFormat) {\n\t\tcase 'index':\n\t\t\treturn function (key, value, index) {\n\t\t\t\treturn value === null ? [\n\t\t\t\t\tencode(key, opts),\n\t\t\t\t\t'[',\n\t\t\t\t\tindex,\n\t\t\t\t\t']'\n\t\t\t\t].join('') : [\n\t\t\t\t\tencode(key, opts),\n\t\t\t\t\t'[',\n\t\t\t\t\tencode(index, opts),\n\t\t\t\t\t']=',\n\t\t\t\t\tencode(value, opts)\n\t\t\t\t].join('');\n\t\t\t};\n\n\t\tcase 'bracket':\n\t\t\treturn function (key, value) {\n\t\t\t\treturn value === null ? encode(key, opts) : [\n\t\t\t\t\tencode(key, opts),\n\t\t\t\t\t'[]=',\n\t\t\t\t\tencode(value, opts)\n\t\t\t\t].join('');\n\t\t\t};\n\n\t\tdefault:\n\t\t\treturn function (key, value) {\n\t\t\t\treturn value === null ? encode(key, opts) : [\n\t\t\t\t\tencode(key, opts),\n\t\t\t\t\t'=',\n\t\t\t\t\tencode(value, opts)\n\t\t\t\t].join('');\n\t\t\t};\n\t}\n}\n\nfunction parserForArrayFormat(opts) {\n\tvar result;\n\n\tswitch (opts.arrayFormat) {\n\t\tcase 'index':\n\t\t\treturn function (key, value, accumulator) {\n\t\t\t\tresult = /\\[(\\d*)\\]$/.exec(key);\n\n\t\t\t\tkey = key.replace(/\\[\\d*\\]$/, '');\n\n\t\t\t\tif (!result) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = {};\n\t\t\t\t}\n\n\t\t\t\taccumulator[key][result[1]] = value;\n\t\t\t};\n\n\t\tcase 'bracket':\n\t\t\treturn function (key, value, accumulator) {\n\t\t\t\tresult = /(\\[\\])$/.exec(key);\n\t\t\t\tkey = key.replace(/\\[\\]$/, '');\n\n\t\t\t\tif (!result) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t} else if (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = [value];\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], value);\n\t\t\t};\n\n\t\tdefault:\n\t\t\treturn function (key, value, accumulator) {\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], value);\n\t\t\t};\n\t}\n}\n\nfunction encode(value, opts) {\n\tif (opts.encode) {\n\t\treturn opts.strict ? strictUriEncode(value) : encodeURIComponent(value);\n\t}\n\n\treturn value;\n}\n\nfunction keysSorter(input) {\n\tif (Array.isArray(input)) {\n\t\treturn input.sort();\n\t} else if (typeof input === 'object') {\n\t\treturn keysSorter(Object.keys(input)).sort(function (a, b) {\n\t\t\treturn Number(a) - Number(b);\n\t\t}).map(function (key) {\n\t\t\treturn input[key];\n\t\t});\n\t}\n\n\treturn input;\n}\n\nfunction extract(str) {\n\tvar queryStart = str.indexOf('?');\n\tif (queryStart === -1) {\n\t\treturn '';\n\t}\n\treturn str.slice(queryStart + 1);\n}\n\nfunction parse(str, opts) {\n\topts = objectAssign({arrayFormat: 'none'}, opts);\n\n\tvar formatter = parserForArrayFormat(opts);\n\n\t// Create an object with no prototype\n\t// https://github.com/sindresorhus/query-string/issues/47\n\tvar ret = Object.create(null);\n\n\tif (typeof str !== 'string') {\n\t\treturn ret;\n\t}\n\n\tstr = str.trim().replace(/^[?#&]/, '');\n\n\tif (!str) {\n\t\treturn ret;\n\t}\n\n\tstr.split('&').forEach(function (param) {\n\t\tvar parts = param.replace(/\\+/g, ' ').split('=');\n\t\t// Firefox (pre 40) decodes `%3D` to `=`\n\t\t// https://github.com/sindresorhus/query-string/pull/37\n\t\tvar key = parts.shift();\n\t\tvar val = parts.length > 0 ? parts.join('=') : undefined;\n\n\t\t// missing `=` should be `null`:\n\t\t// http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters\n\t\tval = val === undefined ? null : decodeComponent(val);\n\n\t\tformatter(decodeComponent(key), val, ret);\n\t});\n\n\treturn Object.keys(ret).sort().reduce(function (result, key) {\n\t\tvar val = ret[key];\n\t\tif (Boolean(val) && typeof val === 'object' && !Array.isArray(val)) {\n\t\t\t// Sort object keys, not values\n\t\t\tresult[key] = keysSorter(val);\n\t\t} else {\n\t\t\tresult[key] = val;\n\t\t}\n\n\t\treturn result;\n\t}, Object.create(null));\n}\n\nexports.extract = extract;\nexports.parse = parse;\n\nexports.stringify = function (obj, opts) {\n\tvar defaults = {\n\t\tencode: true,\n\t\tstrict: true,\n\t\tarrayFormat: 'none'\n\t};\n\n\topts = objectAssign(defaults, opts);\n\n\tif (opts.sort === false) {\n\t\topts.sort = function () {};\n\t}\n\n\tvar formatter = encoderForArrayFormat(opts);\n\n\treturn obj ? Object.keys(obj).sort(opts.sort).map(function (key) {\n\t\tvar val = obj[key];\n\n\t\tif (val === undefined) {\n\t\t\treturn '';\n\t\t}\n\n\t\tif (val === null) {\n\t\t\treturn encode(key, opts);\n\t\t}\n\n\t\tif (Array.isArray(val)) {\n\t\t\tvar result = [];\n\n\t\t\tval.slice().forEach(function (val2) {\n\t\t\t\tif (val2 === undefined) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tresult.push(formatter(key, val2, result.length));\n\t\t\t});\n\n\t\t\treturn result.join('&');\n\t\t}\n\n\t\treturn encode(key, opts) + '=' + encode(val, opts);\n\t}).filter(function (x) {\n\t\treturn x.length > 0;\n\t}).join('&') : '';\n};\n\nexports.parseUrl = function (str, opts) {\n\treturn {\n\t\turl: str.split('?')[0] || '',\n\t\tquery: parse(extract(str), opts)\n\t};\n};\n","import { CookiesStatic } from 'js-cookie';\nimport merge from 'lodash/merge';\n\nimport Cache, { DefaultCache } from './cache';\nimport isPromise from './is-promise';\nimport PayloadTransformer from './payload-transformer';\nimport RequestFactory from './request-factory';\nimport RequestOptions from './request-options';\nimport RequestSenderOptions from './request-sender-options';\nimport Response from './response';\nimport Timeout from './timeout';\n\nexport default class RequestSender {\n    private _cache: Cache;\n\n    constructor(\n        private _requestFactory: RequestFactory,\n        private _payloadTransformer: PayloadTransformer,\n        private _cookie: CookiesStatic,\n        private _options: RequestSenderOptions = {}\n    ) {\n        this._cache = this._options.cache || new DefaultCache();\n    }\n\n    sendRequest<T = any>(url: string, options?: RequestOptions): Promise<Response<T>> {\n        const requestOptions = this._mergeDefaultOptions(url, options);\n        const cachedRequest = this._getCachedRequest<T>(url, requestOptions);\n\n        if (cachedRequest) {\n            return Promise.resolve(cachedRequest);\n        }\n\n        const request = this._requestFactory.createRequest(this._prependHost(url), requestOptions);\n\n        return new Promise((resolve, reject) => {\n            const requestHandler = () => {\n                const response = this._payloadTransformer.toResponse(request);\n\n                if (response.status >= 200 && response.status < 300) {\n                    this._cacheRequest(url, requestOptions, response);\n                    resolve(response);\n                } else {\n                    reject(response);\n                }\n            };\n\n            request.onload = requestHandler;\n            request.onerror = requestHandler;\n            request.onabort = requestHandler;\n            request.ontimeout = requestHandler;\n\n            if (requestOptions.timeout instanceof Timeout) {\n                requestOptions.timeout.onComplete(() => request.abort());\n                requestOptions.timeout.start();\n            }\n\n            if (isPromise(requestOptions.timeout)) {\n                requestOptions.timeout.then(() => request.abort());\n            }\n\n            request.send(this._payloadTransformer.toRequestBody(requestOptions));\n        });\n    }\n\n    get<T = any>(url: string, options?: RequestOptions): Promise<Response<T>> {\n        return this.sendRequest(url, { ...options, method: 'GET' });\n    }\n\n    post<T = any>(url: string, options?: RequestOptions): Promise<Response<T>> {\n        return this.sendRequest(url, { ...options, method: 'POST' });\n    }\n\n    put<T = any>(url: string, options?: RequestOptions): Promise<Response<T>> {\n        return this.sendRequest(url, { ...options, method: 'PUT' });\n    }\n\n    patch<T = any>(url: string, options?: RequestOptions): Promise<Response<T>> {\n        return this.sendRequest(url, { ...options, method: 'PATCH' });\n    }\n\n    delete<T = any>(url: string, options?: RequestOptions): Promise<Response<T>> {\n        return this.sendRequest(url, { ...options, method: 'DELETE' });\n    }\n\n    private _mergeDefaultOptions(url: string, options?: RequestOptions): RequestOptions {\n        const defaultOptions: Partial<RequestOptions> = {\n            credentials: true,\n            encodeParams: true,\n            headers: {\n                Accept: 'application/json, text/plain, */*',\n            },\n            method: 'GET',\n        };\n\n        const csrfToken = this._cookie.get('XSRF-TOKEN');\n\n        if (csrfToken && defaultOptions.headers && !this._isAssetRequest(url, options)) {\n            defaultOptions.headers['X-XSRF-TOKEN'] = csrfToken;\n        }\n\n        if (options && options.body && defaultOptions.headers) {\n            defaultOptions.headers['Content-Type'] = 'application/json';\n        }\n\n        return merge({}, defaultOptions, options);\n    }\n\n    private _prependHost(url: string): string {\n        if (!this._options.host || /^https?:\\/\\//.test(url)) {\n            return url;\n        }\n\n        return `${this._options.host.replace(/\\/$/, '')}/${url.replace(/^\\//, '')}`;\n    }\n\n    private _shouldCacheRequest(options: RequestOptions): boolean {\n        const method = options.method || 'GET';\n\n        return method.toUpperCase() === 'GET' && Boolean(options.cache);\n    }\n\n    private _getCachedRequest<T>(url: string, options: RequestOptions): Response<T> | null {\n        if (this._shouldCacheRequest(options)) {\n            return this._cache.read<T>(url, options);\n        }\n\n        return null;\n    }\n\n    private _cacheRequest<T>(url: string, options: RequestOptions, response: Response<T>): void {\n        if (this._shouldCacheRequest(options)) {\n            this._cache.write(url, options, response);\n        }\n    }\n\n    private _isAssetRequest(url: string, options?: RequestOptions): boolean {\n        if (options && options.method && options.method.toUpperCase() !== 'GET') {\n            return false;\n        }\n\n        return /\\.(png|gif|jpe?g|css|js|json|svg|html?)$/.test(url.split('?')[0]);\n    }\n}\n","export default class BrowserSupport {\n    canSupportRel(rel: string): boolean {\n        const link = document.createElement('link');\n\n        return !!(\n            link.relList &&\n            link.relList.supports &&\n            link.relList.supports(rel)\n        );\n    }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport BrowserSupport from './browser-support';\n\nexport interface LoadStylesheetOptions {\n    prepend: boolean;\n    attributes?: StylesheetAttributes;\n}\n\nexport interface PreloadStylesheetOptions {\n    prefetch: boolean;\n}\n\nexport interface StylesheetAttributes {\n    [key: string]: string;\n}\n\nexport default class StylesheetLoader {\n    private _stylesheets: { [key: string]: Promise<void> } = {};\n    private _preloadedStylesheets: { [key: string]: Promise<void> } = {};\n\n    /**\n     * @internal\n     */\n    constructor(\n        private _browserSupport: BrowserSupport,\n        private _requestSender: RequestSender\n    ) {}\n\n    loadStylesheet(src: string, options?: LoadStylesheetOptions): Promise<void> {\n        if (!this._stylesheets[src]) {\n            this._stylesheets[src] = new Promise((resolve, reject) => {\n                const stylesheet = document.createElement('link');\n                const { prepend = false, attributes = {} } = options || {};\n\n                Object.keys(attributes)\n                    .forEach(key => {\n                        stylesheet.setAttribute(key, attributes[key]);\n                    });\n\n                stylesheet.onload = () => resolve();\n                stylesheet.onerror = event => {\n                    delete this._stylesheets[src];\n                    reject(event);\n                };\n                stylesheet.rel = 'stylesheet';\n                stylesheet.href = src;\n\n                if (prepend && document.head.children[0]) {\n                    document.head.insertBefore(stylesheet, document.head.children[0]);\n                } else {\n                    document.head.appendChild(stylesheet);\n                }\n            });\n        }\n\n        return this._stylesheets[src];\n    }\n\n    loadStylesheets(urls: string[], options?: LoadStylesheetOptions): Promise<void> {\n        return Promise.all(urls.map(url => this.loadStylesheet(url, options)))\n            .then(() => undefined);\n    }\n\n    preloadStylesheet(url: string, options?: PreloadStylesheetOptions): Promise<void> {\n        if (!this._preloadedStylesheets[url]) {\n            this._preloadedStylesheets[url] = new Promise((resolve, reject) => {\n                const { prefetch = false } = options || {};\n                const rel = prefetch ? 'prefetch' : 'preload';\n\n                if (this._browserSupport.canSupportRel(rel)) {\n                    const preloadedStylesheet = document.createElement('link');\n\n                    preloadedStylesheet.as = 'style';\n                    preloadedStylesheet.rel = prefetch ? 'prefetch' : 'preload';\n                    preloadedStylesheet.href = url;\n\n                    preloadedStylesheet.onload = () => {\n                        resolve();\n                    };\n\n                    preloadedStylesheet.onerror = event => {\n                        delete this._preloadedStylesheets[url];\n                        reject(event);\n                    };\n\n                    document.head.appendChild(preloadedStylesheet);\n                } else {\n                    this._requestSender.get(url, {\n                        credentials: false,\n                        headers: { Accept: 'text/css' },\n                    })\n                        .then(() => resolve())\n                        .catch(reject);\n                }\n            });\n        }\n\n        return this._preloadedStylesheets[url];\n    }\n\n    preloadStylesheets(urls: string[], options?: PreloadStylesheetOptions): Promise<void> {\n        return Promise.all(urls.map(url => this.preloadStylesheet(url, options)))\n            .then(() => undefined);\n    }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport BrowserSupport from './browser-support';\nimport StylesheetLoader from './stylesheet-loader';\n\nexport default function createStylesheetLoader(): StylesheetLoader {\n    return new StylesheetLoader(\n        new BrowserSupport(),\n        createRequestSender()\n    );\n}\n","'use strict';\nvar strictUriEncode = require('strict-uri-encode');\nvar objectAssign = require('object-assign');\nvar decodeComponent = require('decode-uri-component');\n\nfunction encoderForArrayFormat(opts) {\n\tswitch (opts.arrayFormat) {\n\t\tcase 'index':\n\t\t\treturn function (key, value, index) {\n\t\t\t\treturn value === null ? [\n\t\t\t\t\tencode(key, opts),\n\t\t\t\t\t'[',\n\t\t\t\t\tindex,\n\t\t\t\t\t']'\n\t\t\t\t].join('') : [\n\t\t\t\t\tencode(key, opts),\n\t\t\t\t\t'[',\n\t\t\t\t\tencode(index, opts),\n\t\t\t\t\t']=',\n\t\t\t\t\tencode(value, opts)\n\t\t\t\t].join('');\n\t\t\t};\n\n\t\tcase 'bracket':\n\t\t\treturn function (key, value) {\n\t\t\t\treturn value === null ? encode(key, opts) : [\n\t\t\t\t\tencode(key, opts),\n\t\t\t\t\t'[]=',\n\t\t\t\t\tencode(value, opts)\n\t\t\t\t].join('');\n\t\t\t};\n\n\t\tdefault:\n\t\t\treturn function (key, value) {\n\t\t\t\treturn value === null ? encode(key, opts) : [\n\t\t\t\t\tencode(key, opts),\n\t\t\t\t\t'=',\n\t\t\t\t\tencode(value, opts)\n\t\t\t\t].join('');\n\t\t\t};\n\t}\n}\n\nfunction parserForArrayFormat(opts) {\n\tvar result;\n\n\tswitch (opts.arrayFormat) {\n\t\tcase 'index':\n\t\t\treturn function (key, value, accumulator) {\n\t\t\t\tresult = /\\[(\\d*)\\]$/.exec(key);\n\n\t\t\t\tkey = key.replace(/\\[\\d*\\]$/, '');\n\n\t\t\t\tif (!result) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = {};\n\t\t\t\t}\n\n\t\t\t\taccumulator[key][result[1]] = value;\n\t\t\t};\n\n\t\tcase 'bracket':\n\t\t\treturn function (key, value, accumulator) {\n\t\t\t\tresult = /(\\[\\])$/.exec(key);\n\t\t\t\tkey = key.replace(/\\[\\]$/, '');\n\n\t\t\t\tif (!result) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t} else if (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = [value];\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], value);\n\t\t\t};\n\n\t\tdefault:\n\t\t\treturn function (key, value, accumulator) {\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], value);\n\t\t\t};\n\t}\n}\n\nfunction encode(value, opts) {\n\tif (opts.encode) {\n\t\treturn opts.strict ? strictUriEncode(value) : encodeURIComponent(value);\n\t}\n\n\treturn value;\n}\n\nfunction keysSorter(input) {\n\tif (Array.isArray(input)) {\n\t\treturn input.sort();\n\t} else if (typeof input === 'object') {\n\t\treturn keysSorter(Object.keys(input)).sort(function (a, b) {\n\t\t\treturn Number(a) - Number(b);\n\t\t}).map(function (key) {\n\t\t\treturn input[key];\n\t\t});\n\t}\n\n\treturn input;\n}\n\nfunction extract(str) {\n\tvar queryStart = str.indexOf('?');\n\tif (queryStart === -1) {\n\t\treturn '';\n\t}\n\treturn str.slice(queryStart + 1);\n}\n\nfunction parse(str, opts) {\n\topts = objectAssign({arrayFormat: 'none'}, opts);\n\n\tvar formatter = parserForArrayFormat(opts);\n\n\t// Create an object with no prototype\n\t// https://github.com/sindresorhus/query-string/issues/47\n\tvar ret = Object.create(null);\n\n\tif (typeof str !== 'string') {\n\t\treturn ret;\n\t}\n\n\tstr = str.trim().replace(/^[?#&]/, '');\n\n\tif (!str) {\n\t\treturn ret;\n\t}\n\n\tstr.split('&').forEach(function (param) {\n\t\tvar parts = param.replace(/\\+/g, ' ').split('=');\n\t\t// Firefox (pre 40) decodes `%3D` to `=`\n\t\t// https://github.com/sindresorhus/query-string/pull/37\n\t\tvar key = parts.shift();\n\t\tvar val = parts.length > 0 ? parts.join('=') : undefined;\n\n\t\t// missing `=` should be `null`:\n\t\t// http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters\n\t\tval = val === undefined ? null : decodeComponent(val);\n\n\t\tformatter(decodeComponent(key), val, ret);\n\t});\n\n\treturn Object.keys(ret).sort().reduce(function (result, key) {\n\t\tvar val = ret[key];\n\t\tif (Boolean(val) && typeof val === 'object' && !Array.isArray(val)) {\n\t\t\t// Sort object keys, not values\n\t\t\tresult[key] = keysSorter(val);\n\t\t} else {\n\t\t\tresult[key] = val;\n\t\t}\n\n\t\treturn result;\n\t}, Object.create(null));\n}\n\nexports.extract = extract;\nexports.parse = parse;\n\nexports.stringify = function (obj, opts) {\n\tvar defaults = {\n\t\tencode: true,\n\t\tstrict: true,\n\t\tarrayFormat: 'none'\n\t};\n\n\topts = objectAssign(defaults, opts);\n\n\tif (opts.sort === false) {\n\t\topts.sort = function () {};\n\t}\n\n\tvar formatter = encoderForArrayFormat(opts);\n\n\treturn obj ? Object.keys(obj).sort(opts.sort).map(function (key) {\n\t\tvar val = obj[key];\n\n\t\tif (val === undefined) {\n\t\t\treturn '';\n\t\t}\n\n\t\tif (val === null) {\n\t\t\treturn encode(key, opts);\n\t\t}\n\n\t\tif (Array.isArray(val)) {\n\t\t\tvar result = [];\n\n\t\t\tval.slice().forEach(function (val2) {\n\t\t\t\tif (val2 === undefined) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tresult.push(formatter(key, val2, result.length));\n\t\t\t});\n\n\t\t\treturn result.join('&');\n\t\t}\n\n\t\treturn encode(key, opts) + '=' + encode(val, opts);\n\t}).filter(function (x) {\n\t\treturn x.length > 0;\n\t}).join('&') : '';\n};\n\nexports.parseUrl = function (str, opts) {\n\treturn {\n\t\turl: str.split('?')[0] || '',\n\t\tquery: parse(extract(str), opts)\n\t};\n};\n","import FormBuilder from './form-builder';\nimport FormPosterOptions from './form-poster-options';\nimport { isAbsoluteUrl, joinPaths } from './url-utils';\n\nexport default class FormPoster {\n    /**\n     * @internal\n     */\n    constructor(\n        private _formBuilder: FormBuilder,\n        private _options?: FormPosterOptions\n    ) {}\n\n    postForm(url: string, data: { [key: string]: any }, callback?: () => void, target?: string): void {\n        const form = this._formBuilder.build(this._prependHost(url), data, target);\n\n        window.addEventListener('unload', function handleUnload() {\n            window.removeEventListener('unload', handleUnload);\n\n            if (callback) {\n                callback();\n            }\n        });\n\n        // In order to submit the form, the form must be attached to DOM.\n        document.body.appendChild(form);\n        form.submit();\n        document.body.removeChild(form);\n    }\n\n    private _prependHost(url: string): string {\n        if (!this._options || !this._options.host || isAbsoluteUrl(url)) {\n            return url;\n        }\n\n        return joinPaths(this._options.host, url);\n    }\n}\n","export const API = 'PAYMENT_TYPE_API';\nexport const HOSTED = 'PAYMENT_TYPE_HOSTED';\nexport const OFFLINE = 'PAYMENT_TYPE_OFFLINE';\n","/**\n * @param {*} value\n * @returns {boolean}\n */\nexport default function isObject(value) {\n    return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n","export const APPLICATION_JSON = 'application/json';\n","'use strict';\nvar strictUriEncode = require('strict-uri-encode');\nvar objectAssign = require('object-assign');\nvar decodeComponent = require('decode-uri-component');\n\nfunction encoderForArrayFormat(opts) {\n\tswitch (opts.arrayFormat) {\n\t\tcase 'index':\n\t\t\treturn function (key, value, index) {\n\t\t\t\treturn value === null ? [\n\t\t\t\t\tencode(key, opts),\n\t\t\t\t\t'[',\n\t\t\t\t\tindex,\n\t\t\t\t\t']'\n\t\t\t\t].join('') : [\n\t\t\t\t\tencode(key, opts),\n\t\t\t\t\t'[',\n\t\t\t\t\tencode(index, opts),\n\t\t\t\t\t']=',\n\t\t\t\t\tencode(value, opts)\n\t\t\t\t].join('');\n\t\t\t};\n\n\t\tcase 'bracket':\n\t\t\treturn function (key, value) {\n\t\t\t\treturn value === null ? encode(key, opts) : [\n\t\t\t\t\tencode(key, opts),\n\t\t\t\t\t'[]=',\n\t\t\t\t\tencode(value, opts)\n\t\t\t\t].join('');\n\t\t\t};\n\n\t\tdefault:\n\t\t\treturn function (key, value) {\n\t\t\t\treturn value === null ? encode(key, opts) : [\n\t\t\t\t\tencode(key, opts),\n\t\t\t\t\t'=',\n\t\t\t\t\tencode(value, opts)\n\t\t\t\t].join('');\n\t\t\t};\n\t}\n}\n\nfunction parserForArrayFormat(opts) {\n\tvar result;\n\n\tswitch (opts.arrayFormat) {\n\t\tcase 'index':\n\t\t\treturn function (key, value, accumulator) {\n\t\t\t\tresult = /\\[(\\d*)\\]$/.exec(key);\n\n\t\t\t\tkey = key.replace(/\\[\\d*\\]$/, '');\n\n\t\t\t\tif (!result) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = {};\n\t\t\t\t}\n\n\t\t\t\taccumulator[key][result[1]] = value;\n\t\t\t};\n\n\t\tcase 'bracket':\n\t\t\treturn function (key, value, accumulator) {\n\t\t\t\tresult = /(\\[\\])$/.exec(key);\n\t\t\t\tkey = key.replace(/\\[\\]$/, '');\n\n\t\t\t\tif (!result) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t} else if (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = [value];\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], value);\n\t\t\t};\n\n\t\tdefault:\n\t\t\treturn function (key, value, accumulator) {\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], value);\n\t\t\t};\n\t}\n}\n\nfunction encode(value, opts) {\n\tif (opts.encode) {\n\t\treturn opts.strict ? strictUriEncode(value) : encodeURIComponent(value);\n\t}\n\n\treturn value;\n}\n\nfunction keysSorter(input) {\n\tif (Array.isArray(input)) {\n\t\treturn input.sort();\n\t} else if (typeof input === 'object') {\n\t\treturn keysSorter(Object.keys(input)).sort(function (a, b) {\n\t\t\treturn Number(a) - Number(b);\n\t\t}).map(function (key) {\n\t\t\treturn input[key];\n\t\t});\n\t}\n\n\treturn input;\n}\n\nfunction extract(str) {\n\tvar queryStart = str.indexOf('?');\n\tif (queryStart === -1) {\n\t\treturn '';\n\t}\n\treturn str.slice(queryStart + 1);\n}\n\nfunction parse(str, opts) {\n\topts = objectAssign({arrayFormat: 'none'}, opts);\n\n\tvar formatter = parserForArrayFormat(opts);\n\n\t// Create an object with no prototype\n\t// https://github.com/sindresorhus/query-string/issues/47\n\tvar ret = Object.create(null);\n\n\tif (typeof str !== 'string') {\n\t\treturn ret;\n\t}\n\n\tstr = str.trim().replace(/^[?#&]/, '');\n\n\tif (!str) {\n\t\treturn ret;\n\t}\n\n\tstr.split('&').forEach(function (param) {\n\t\tvar parts = param.replace(/\\+/g, ' ').split('=');\n\t\t// Firefox (pre 40) decodes `%3D` to `=`\n\t\t// https://github.com/sindresorhus/query-string/pull/37\n\t\tvar key = parts.shift();\n\t\tvar val = parts.length > 0 ? parts.join('=') : undefined;\n\n\t\t// missing `=` should be `null`:\n\t\t// http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters\n\t\tval = val === undefined ? null : decodeComponent(val);\n\n\t\tformatter(decodeComponent(key), val, ret);\n\t});\n\n\treturn Object.keys(ret).sort().reduce(function (result, key) {\n\t\tvar val = ret[key];\n\t\tif (Boolean(val) && typeof val === 'object' && !Array.isArray(val)) {\n\t\t\t// Sort object keys, not values\n\t\t\tresult[key] = keysSorter(val);\n\t\t} else {\n\t\t\tresult[key] = val;\n\t\t}\n\n\t\treturn result;\n\t}, Object.create(null));\n}\n\nexports.extract = extract;\nexports.parse = parse;\n\nexports.stringify = function (obj, opts) {\n\tvar defaults = {\n\t\tencode: true,\n\t\tstrict: true,\n\t\tarrayFormat: 'none'\n\t};\n\n\topts = objectAssign(defaults, opts);\n\n\tif (opts.sort === false) {\n\t\topts.sort = function () {};\n\t}\n\n\tvar formatter = encoderForArrayFormat(opts);\n\n\treturn obj ? Object.keys(obj).sort(opts.sort).map(function (key) {\n\t\tvar val = obj[key];\n\n\t\tif (val === undefined) {\n\t\t\treturn '';\n\t\t}\n\n\t\tif (val === null) {\n\t\t\treturn encode(key, opts);\n\t\t}\n\n\t\tif (Array.isArray(val)) {\n\t\t\tvar result = [];\n\n\t\t\tval.slice().forEach(function (val2) {\n\t\t\t\tif (val2 === undefined) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tresult.push(formatter(key, val2, result.length));\n\t\t\t});\n\n\t\t\treturn result.join('&');\n\t\t}\n\n\t\treturn encode(key, opts) + '=' + encode(val, opts);\n\t}).filter(function (x) {\n\t\treturn x.length > 0;\n\t}).join('&') : '';\n};\n\nexports.parseUrl = function (str, opts) {\n\treturn {\n\t\turl: str.split('?')[0] || '',\n\t\tquery: parse(extract(str), opts)\n\t};\n};\n","import { Subscribable, SubscribableOrPromise } from 'rxjs';\n\nimport Action from './action';\nimport { DispatchableAction } from './dispatchable-data-store';\n\nexport default function isObservableActionLike<TAction extends Action = Action>(\n    action: DispatchableAction<TAction>\n): action is SubscribableOrPromise<TAction> {\n    return (\n        typeof (action as Subscribable<TAction>).subscribe === 'function' ||\n        typeof (action as PromiseLike<TAction>).then === 'function'\n    );\n}\n","import { Subscribable } from 'rxjs';\n\nimport Action from './action';\n\nexport default function noopActionTransformer<TAction extends Action, TTransformedAction extends Action = TAction>(\n    action: Subscribable<TAction>\n): Subscribable<TTransformedAction> {\n    return action as any as Subscribable<TTransformedAction>;\n}\n","export default function noopStateTransformer<TState, TTransformedState = TState>(\n    state: TState\n): TTransformedState {\n    return state as any as TTransformedState;\n}\n","import { curryRight, flowRight } from 'lodash';\nimport * as shallowEqual from 'shallowequal';\n\nimport Action from './action';\nimport Reducer from './reducer';\n\nexport default function composeReducers<TState, TStateA, TAction extends Action = Action>(\n    reducerA: (state: TStateA, action: TAction) => TState,\n    reducerB: (state: TState, action: TAction) => TStateA,\n    options?: ComposeReducersOptions\n): Reducer<TState, TAction>;\n\nexport default function composeReducers<TState, TStateA, TStateB, TAction extends Action = Action>(\n    reducerA: (state: TStateA, action: TAction) => TState,\n    reducerB: (state: TStateB, action: TAction) => TStateA,\n    reducerC: (state: TState, action: TAction) => TStateB,\n    options?: ComposeReducersOptions\n): Reducer<TState, TAction>;\n\nexport default function composeReducers<TState, TStateA, TStateB, TStateC, TAction extends Action = Action>(\n    reducerA: (state: TStateA, action: TAction) => TState,\n    reducerB: (state: TStateB, action: TAction) => TStateA,\n    reducerC: (state: TStateC, action: TAction) => TStateB,\n    reducerD: (state: TState, action: TAction) => TStateC,\n    options?: ComposeReducersOptions\n): Reducer<TState, TAction>;\n\nexport default function composeReducers<TState, TStateA, TStateB, TStateC, TStateD, TAction extends Action = Action>(\n    reducerA: (state: TStateA, action: TAction) => TState,\n    reducerB: (state: TStateB, action: TAction) => TStateA,\n    reducerC: (state: TStateC, action: TAction) => TStateB,\n    reducerD: (state: TStateD, action: TAction) => TStateC,\n    reducerE: (state: TState, action: TAction) => TStateD,\n    options?: ComposeReducersOptions\n): Reducer<TState, TAction>;\n\nexport default function composeReducers<TState, TAction extends Action = Action>(\n    ...args: any[]\n): Reducer<TState, TAction> {\n    let reducers: Array<Reducer<TState, TAction>> = args;\n    let options: ComposeReducersOptions = {};\n\n    if (typeof args[args.length - 1] === 'object') {\n        reducers = args.slice(0, -1);\n        options = { ...options, ...args[args.length - 1] };\n    }\n\n    const { equalityCheck = shallowEqual } = options;\n\n    return (state, action) => {\n        const newState = flowRight(\n            reducers\n                .filter(reducer => reducer.length === 2)\n                .map(reducer => curryRight(reducer)(action))\n        )(state);\n\n        return equalityCheck(state, newState) ? state : newState;\n    };\n}\n\nexport interface ComposeReducersOptions {\n    equalityCheck?(valueA: any, valueB: any): boolean;\n}\n","import Action from './action';\nimport combineReducers, { ReducerMap } from './combine-reducers';\nimport DataStore, { DataStoreOptions } from './data-store';\nimport Reducer from './reducer';\n\nexport default function createDataStore<TState, TAction extends Action = Action, TTransformedState = TState>(\n    reducer: Reducer<TState, TAction> | ReducerMap<TState, TAction>,\n    initialState?: Partial<TState>,\n    options?: Partial<DataStoreOptions<TState, TAction, TTransformedState>>\n): DataStore<TState, TAction, TTransformedState> {\n    if (typeof reducer === 'function') {\n        return new DataStore(reducer, initialState, options);\n    }\n\n    return new DataStore(\n        combineReducers(reducer, { equalityCheck: options && options.equalityCheck }),\n        initialState,\n        options\n    );\n}\n","import Action from './action';\nimport createAction from './create-action';\n\nexport default function createErrorAction<TPayload, TMeta, TType extends string>(\n    type: TType,\n    payload?: TPayload,\n    meta?: TMeta\n): Action<TPayload, TMeta, TType> {\n    return {\n        ...createAction(type, payload, meta),\n        error: true,\n    };\n}\n","/* Observable */\nexport { Observable } from './internal/Observable';\nexport { ConnectableObservable } from './internal/observable/ConnectableObservable';\nexport { GroupedObservable } from './internal/operators/groupBy';\nexport { Operator } from './internal/Operator';\nexport { observable } from './internal/symbol/observable';\n\n/* Subjects */\nexport { Subject } from './internal/Subject';\nexport { BehaviorSubject } from './internal/BehaviorSubject';\nexport { ReplaySubject } from './internal/ReplaySubject';\nexport { AsyncSubject } from './internal/AsyncSubject';\n\n/* Schedulers */\nexport { asap, asapScheduler } from './internal/scheduler/asap';\nexport { async, asyncScheduler } from './internal/scheduler/async';\nexport { queue, queueScheduler } from './internal/scheduler/queue';\nexport { animationFrame, animationFrameScheduler } from './internal/scheduler/animationFrame';\nexport { VirtualTimeScheduler, VirtualAction } from './internal/scheduler/VirtualTimeScheduler';\nexport { Scheduler } from './internal/Scheduler';\n\n/* Subscription */\nexport { Subscription } from './internal/Subscription';\nexport { Subscriber } from './internal/Subscriber';\n\n/* Notification */\nexport { Notification, NotificationKind } from './internal/Notification';\n\n/* Utils */\nexport { pipe } from './internal/util/pipe';\nexport { noop } from './internal/util/noop';\nexport { identity } from './internal/util/identity';\nexport { isObservable } from './internal/util/isObservable';\n\n/* Error types */\nexport { ArgumentOutOfRangeError } from './internal/util/ArgumentOutOfRangeError';\nexport { EmptyError } from './internal/util/EmptyError';\nexport { ObjectUnsubscribedError } from './internal/util/ObjectUnsubscribedError';\nexport { UnsubscriptionError } from './internal/util/UnsubscriptionError';\nexport { TimeoutError } from './internal/util/TimeoutError';\n\n/* Static observable creation exports */\nexport { bindCallback } from './internal/observable/bindCallback';\nexport { bindNodeCallback } from './internal/observable/bindNodeCallback';\nexport { combineLatest } from './internal/observable/combineLatest';\nexport { concat } from './internal/observable/concat';\nexport { defer } from './internal/observable/defer';\nexport { empty } from './internal/observable/empty';\nexport { forkJoin } from './internal/observable/forkJoin';\nexport { from } from './internal/observable/from';\nexport { fromEvent } from './internal/observable/fromEvent';\nexport { fromEventPattern } from './internal/observable/fromEventPattern';\nexport { generate } from './internal/observable/generate';\nexport { iif } from './internal/observable/iif';\nexport { interval } from './internal/observable/interval';\nexport { merge } from './internal/observable/merge';\nexport { never } from './internal/observable/never';\nexport { of } from './internal/observable/of';\nexport { onErrorResumeNext } from './internal/observable/onErrorResumeNext';\nexport { pairs } from './internal/observable/pairs';\nexport { partition } from './internal/observable/partition';\nexport { race } from './internal/observable/race';\nexport { range } from './internal/observable/range';\nexport { throwError } from './internal/observable/throwError';\nexport { timer } from './internal/observable/timer';\nexport { using } from './internal/observable/using';\nexport { zip } from './internal/observable/zip';\nexport { scheduled } from './internal/scheduled/scheduled';\n\n/* Constants */\nexport { EMPTY } from './internal/observable/empty';\nexport { NEVER } from './internal/observable/never';\n\n/* Types */\nexport * from './internal/types';\n\n/* Config */\nexport { config } from './internal/config';\n","import { Subscriber } from '../Subscriber';\nimport { rxSubscriber as rxSubscriberSymbol } from '../symbol/rxSubscriber';\nimport { empty as emptyObserver } from '../Observer';\nimport { PartialObserver } from '../types';\n\nexport function toSubscriber<T>(\n  nextOrObserver?: PartialObserver<T> | ((value: T) => void),\n  error?: (error: any) => void,\n  complete?: () => void): Subscriber<T> {\n\n  if (nextOrObserver) {\n    if (nextOrObserver instanceof Subscriber) {\n      return (<Subscriber<T>> nextOrObserver);\n    }\n\n    if (nextOrObserver[rxSubscriberSymbol]) {\n      return nextOrObserver[rxSubscriberSymbol]();\n    }\n  }\n\n  if (!nextOrObserver && !error && !complete) {\n    return new Subscriber(emptyObserver);\n  }\n\n  return new Subscriber(nextOrObserver, error, complete);\n}\n","import { AsyncAction } from './AsyncAction';\nimport { Subscription } from '../Subscription';\nimport { QueueScheduler } from './QueueScheduler';\nimport { SchedulerAction } from '../types';\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class QueueAction<T> extends AsyncAction<T> {\n\n  constructor(protected scheduler: QueueScheduler,\n              protected work: (this: SchedulerAction<T>, state?: T) => void) {\n    super(scheduler, work);\n  }\n\n  public schedule(state?: T, delay: number = 0): Subscription {\n    if (delay > 0) {\n      return super.schedule(state, delay);\n    }\n    this.delay = delay;\n    this.state = state;\n    this.scheduler.flush(this);\n    return this;\n  }\n\n  public execute(state: T, delay: number): any {\n    return (delay > 0 || this.closed) ?\n      super.execute(state, delay) :\n      this._execute(state, delay) ;\n  }\n\n  protected requestAsyncId(scheduler: QueueScheduler, id?: any, delay: number = 0): any {\n    // If delay exists and is greater than 0, or if the delay is null (the\n    // action wasn't rescheduled) but was originally scheduled as an async\n    // action, then recycle as an async action.\n    if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {\n      return super.requestAsyncId(scheduler, id, delay);\n    }\n    // Otherwise flush the scheduler starting with this action.\n    return scheduler.flush(this);\n  }\n}\n","import { Scheduler } from '../Scheduler';\nimport { Subscription } from '../Subscription';\nimport { SchedulerAction } from '../types';\n\n/**\n * A unit of work to be executed in a `scheduler`. An action is typically\n * created from within a {@link SchedulerLike} and an RxJS user does not need to concern\n * themselves about creating and manipulating an Action.\n *\n * ```ts\n * class Action<T> extends Subscription {\n *   new (scheduler: Scheduler, work: (state?: T) => void);\n *   schedule(state?: T, delay: number = 0): Subscription;\n * }\n * ```\n *\n * @class Action<T>\n */\nexport class Action<T> extends Subscription {\n  constructor(scheduler: Scheduler, work: (this: SchedulerAction<T>, state?: T) => void) {\n    super();\n  }\n  /**\n   * Schedules this action on its parent {@link SchedulerLike} for execution. May be passed\n   * some context object, `state`. May happen at some point in the future,\n   * according to the `delay` parameter, if specified.\n   * @param {T} [state] Some contextual data that the `work` function uses when\n   * called by the Scheduler.\n   * @param {number} [delay] Time to wait before executing the work, where the\n   * time unit is implicit and defined by the Scheduler.\n   * @return {void}\n   */\n  public schedule(state?: T, delay: number = 0): Subscription {\n    return this;\n  }\n}\n","import { AsyncScheduler } from './AsyncScheduler';\n\nexport class QueueScheduler extends AsyncScheduler {\n}\n","import { Immediate } from '../util/Immediate';\nimport { AsyncAction } from './AsyncAction';\nimport { AsapScheduler } from './AsapScheduler';\nimport { SchedulerAction } from '../types';\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class AsapAction<T> extends AsyncAction<T> {\n\n  constructor(protected scheduler: AsapScheduler,\n              protected work: (this: SchedulerAction<T>, state?: T) => void) {\n    super(scheduler, work);\n  }\n\n  protected requestAsyncId(scheduler: AsapScheduler, id?: any, delay: number = 0): any {\n    // If delay is greater than 0, request as an async action.\n    if (delay !== null && delay > 0) {\n      return super.requestAsyncId(scheduler, id, delay);\n    }\n    // Push the action to the end of the scheduler queue.\n    scheduler.actions.push(this);\n    // If a microtask has already been scheduled, don't schedule another\n    // one. If a microtask hasn't been scheduled yet, schedule one now. Return\n    // the current scheduled microtask id.\n    return scheduler.scheduled || (scheduler.scheduled = Immediate.setImmediate(\n      scheduler.flush.bind(scheduler, null)\n    ));\n  }\n  protected recycleAsyncId(scheduler: AsapScheduler, id?: any, delay: number = 0): any {\n    // If delay exists and is greater than 0, or if the delay is null (the\n    // action wasn't rescheduled) but was originally scheduled as an async\n    // action, then recycle as an async action.\n    if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {\n      return super.recycleAsyncId(scheduler, id, delay);\n    }\n    // If the scheduler queue is empty, cancel the requested microtask and\n    // set the scheduled flag to undefined so the next AsapAction will schedule\n    // its own.\n    if (scheduler.actions.length === 0) {\n      Immediate.clearImmediate(id);\n      scheduler.scheduled = undefined;\n    }\n    // Return undefined so the action knows to request a new async id if it's rescheduled.\n    return undefined;\n  }\n}\n","let nextHandle = 1;\nconst RESOLVED = (() => Promise.resolve())();\nconst activeHandles: { [key: number]: any } = {};\n\n/**\n * Finds the handle in the list of active handles, and removes it.\n * Returns `true` if found, `false` otherwise. Used both to clear\n * Immediate scheduled tasks, and to identify if a task should be scheduled.\n */\nfunction findAndClearHandle(handle: number): boolean {\n  if (handle in activeHandles) {\n    delete activeHandles[handle];\n    return true;\n  }\n  return false;\n}\n\n/**\n * Helper functions to schedule and unschedule microtasks.\n */\nexport const Immediate = {\n  setImmediate(cb: () => void): number {\n    const handle = nextHandle++;\n    activeHandles[handle] = true;\n    RESOLVED.then(() => findAndClearHandle(handle) && cb());\n    return handle;\n  },\n\n  clearImmediate(handle: number): void {\n    findAndClearHandle(handle);\n  },\n};\n\n/**\n * Used for internal testing purposes only. Do not export from library.\n */\nexport const TestTools = {\n  pending() {\n    return Object.keys(activeHandles).length;\n  }\n};\n","import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\nexport class AsapScheduler extends AsyncScheduler {\n  public flush(action?: AsyncAction<any>): void {\n\n    this.active = true;\n    this.scheduled = undefined;\n\n    const {actions} = this;\n    let error: any;\n    let index: number = -1;\n    let count: number = actions.length;\n    action = action || actions.shift();\n\n    do {\n      if (error = action.execute(action.state, action.delay)) {\n        break;\n      }\n    } while (++index < count && (action = actions.shift()));\n\n    this.active = false;\n\n    if (error) {\n      while (++index < count && (action = actions.shift())) {\n        action.unsubscribe();\n      }\n      throw error;\n    }\n  }\n}\n","import { AnimationFrameAction } from './AnimationFrameAction';\nimport { AnimationFrameScheduler } from './AnimationFrameScheduler';\n\n/**\n *\n * Animation Frame Scheduler\n *\n * <span class=\"informal\">Perform task when `window.requestAnimationFrame` would fire</span>\n *\n * When `animationFrame` scheduler is used with delay, it will fall back to {@link asyncScheduler} scheduler\n * behaviour.\n *\n * Without delay, `animationFrame` scheduler can be used to create smooth browser animations.\n * It makes sure scheduled task will happen just before next browser content repaint,\n * thus performing animations as efficiently as possible.\n *\n * ## Example\n * Schedule div height animation\n * ```ts\n * // html: <div style=\"background: #0ff;\"></div>\n * import { animationFrameScheduler } from 'rxjs';\n *\n * const div = document.querySelector('div');\n *\n * animationFrameScheduler.schedule(function(height) {\n *   div.style.height = height + \"px\";\n *\n *   this.schedule(height + 1);  // `this` references currently executing Action,\n *                               // which we reschedule with new state\n * }, 0, 0);\n *\n * // You will see a div element growing in height\n * ```\n */\nexport const animationFrameScheduler = new AnimationFrameScheduler(AnimationFrameAction);\n\n/**\n * @deprecated renamed. Use {@link animationFrameScheduler}\n */\nexport const animationFrame = animationFrameScheduler;\n","import { AsyncAction } from './AsyncAction';\nimport { AnimationFrameScheduler } from './AnimationFrameScheduler';\nimport { SchedulerAction } from '../types';\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class AnimationFrameAction<T> extends AsyncAction<T> {\n\n  constructor(protected scheduler: AnimationFrameScheduler,\n              protected work: (this: SchedulerAction<T>, state?: T) => void) {\n    super(scheduler, work);\n  }\n\n  protected requestAsyncId(scheduler: AnimationFrameScheduler, id?: any, delay: number = 0): any {\n    // If delay is greater than 0, request as an async action.\n    if (delay !== null && delay > 0) {\n      return super.requestAsyncId(scheduler, id, delay);\n    }\n    // Push the action to the end of the scheduler queue.\n    scheduler.actions.push(this);\n    // If an animation frame has already been requested, don't request another\n    // one. If an animation frame hasn't been requested yet, request one. Return\n    // the current animation frame request id.\n    return scheduler.scheduled || (scheduler.scheduled = requestAnimationFrame(\n      () => scheduler.flush(null)));\n  }\n  protected recycleAsyncId(scheduler: AnimationFrameScheduler, id?: any, delay: number = 0): any {\n    // If delay exists and is greater than 0, or if the delay is null (the\n    // action wasn't rescheduled) but was originally scheduled as an async\n    // action, then recycle as an async action.\n    if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {\n      return super.recycleAsyncId(scheduler, id, delay);\n    }\n    // If the scheduler queue is empty, cancel the requested animation frame and\n    // set the scheduled flag to undefined so the next AnimationFrameAction will\n    // request its own.\n    if (scheduler.actions.length === 0) {\n      cancelAnimationFrame(id);\n      scheduler.scheduled = undefined;\n    }\n    // Return undefined so the action knows to request a new async id if it's rescheduled.\n    return undefined;\n  }\n}\n","import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\nexport class AnimationFrameScheduler extends AsyncScheduler {\n  public flush(action?: AsyncAction<any>): void {\n\n    this.active = true;\n    this.scheduled = undefined;\n\n    const {actions} = this;\n    let error: any;\n    let index: number = -1;\n    let count: number = actions.length;\n    action = action || actions.shift();\n\n    do {\n      if (error = action.execute(action.state, action.delay)) {\n        break;\n      }\n    } while (++index < count && (action = actions.shift()));\n\n    this.active = false;\n\n    if (error) {\n      while (++index < count && (action = actions.shift())) {\n        action.unsubscribe();\n      }\n      throw error;\n    }\n  }\n}\n","import { AsyncAction } from './AsyncAction';\nimport { Subscription } from '../Subscription';\nimport { AsyncScheduler } from './AsyncScheduler';\nimport { SchedulerAction } from '../types';\n\nexport class VirtualTimeScheduler extends AsyncScheduler {\n\n  protected static frameTimeFactor: number = 10;\n\n  public frame: number = 0;\n  public index: number = -1;\n\n  constructor(SchedulerAction: typeof AsyncAction = VirtualAction as any,\n              public maxFrames: number = Number.POSITIVE_INFINITY) {\n    super(SchedulerAction, () => this.frame);\n  }\n\n  /**\n   * Prompt the Scheduler to execute all of its queued actions, therefore\n   * clearing its queue.\n   * @return {void}\n   */\n  public flush(): void {\n\n    const {actions, maxFrames} = this;\n    let error: any, action: AsyncAction<any>;\n\n    while ((action = actions[0]) && action.delay <= maxFrames) {\n      actions.shift();\n      this.frame = action.delay;\n\n      if (error = action.execute(action.state, action.delay)) {\n        break;\n      }\n    }\n\n    if (error) {\n      while (action = actions.shift()) {\n        action.unsubscribe();\n      }\n      throw error;\n    }\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @nodoc\n */\nexport class VirtualAction<T> extends AsyncAction<T> {\n\n  protected active: boolean = true;\n\n  constructor(protected scheduler: VirtualTimeScheduler,\n              protected work: (this: SchedulerAction<T>, state?: T) => void,\n              protected index: number = scheduler.index += 1) {\n    super(scheduler, work);\n    this.index = scheduler.index = index;\n  }\n\n  public schedule(state?: T, delay: number = 0): Subscription {\n    if (!this.id) {\n      return super.schedule(state, delay);\n    }\n    this.active = false;\n    // If an action is rescheduled, we save allocations by mutating its state,\n    // pushing it to the end of the scheduler queue, and recycling the action.\n    // But since the VirtualTimeScheduler is used for testing, VirtualActions\n    // must be immutable so they can be inspected later.\n    const action = new VirtualAction(this.scheduler, this.work);\n    this.add(action);\n    return action.schedule(state, delay);\n  }\n\n  protected requestAsyncId(scheduler: VirtualTimeScheduler, id?: any, delay: number = 0): any {\n    this.delay = scheduler.frame + delay;\n    const {actions} = scheduler;\n    actions.push(this);\n    (actions as Array<VirtualAction<T>>).sort(VirtualAction.sortActions);\n    return true;\n  }\n\n  protected recycleAsyncId(scheduler: VirtualTimeScheduler, id?: any, delay: number = 0): any {\n    return undefined;\n  }\n\n  protected _execute(state: T, delay: number): any {\n    if (this.active === true) {\n      return super._execute(state, delay);\n    }\n  }\n\n  public static sortActions<T>(a: VirtualAction<T>, b: VirtualAction<T>) {\n    if (a.delay === b.delay) {\n      if (a.index === b.index) {\n        return 0;\n      } else if (a.index > b.index) {\n        return 1;\n      } else {\n        return -1;\n      }\n    } else if (a.delay > b.delay) {\n      return 1;\n    } else {\n      return -1;\n    }\n  }\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput } from '../types';\n\n/**\n * Tests to see if the object is an RxJS {@link Observable}\n * @param obj the object to test\n */\nexport function isObservable<T>(obj: any): obj is Observable<T> {\n  return !!obj && (obj instanceof Observable || (typeof obj.lift === 'function' && typeof obj.subscribe === 'function'));\n}\n","import { SchedulerLike, SchedulerAction } from '../types';\nimport { Observable } from '../Observable';\nimport { AsyncSubject } from '../AsyncSubject';\nimport { Subscriber } from '../Subscriber';\nimport { map } from '../operators/map';\nimport { canReportError } from '../util/canReportError';\nimport { isArray } from '../util/isArray';\nimport { isScheduler } from '../util/isScheduler';\n\n// tslint:disable:max-line-length\n/** @deprecated resultSelector is no longer supported, use a mapping function. */\nexport function bindCallback(callbackFunc: Function, resultSelector: Function, scheduler?: SchedulerLike): (...args: any[]) => Observable<any>;\n\nexport function bindCallback<R1, R2, R3, R4>(callbackFunc: (callback: (res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): () => Observable<any[]>;\nexport function bindCallback<R1, R2, R3>(callbackFunc: (callback: (res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): () => Observable<[R1, R2, R3]>;\nexport function bindCallback<R1, R2>(callbackFunc: (callback: (res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): () => Observable<[R1, R2]>;\nexport function bindCallback<R1>(callbackFunc: (callback: (res1: R1) => any) => any, scheduler?: SchedulerLike): () => Observable<R1>;\nexport function bindCallback(callbackFunc: (callback: () => any) => any, scheduler?: SchedulerLike): () => Observable<void>;\n\nexport function bindCallback<A1, R1, R2, R3, R4>(callbackFunc: (arg1: A1, callback: (res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<any[]>;\nexport function bindCallback<A1, R1, R2, R3>(callbackFunc: (arg1: A1, callback: (res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<[R1, R2, R3]>;\nexport function bindCallback<A1, R1, R2>(callbackFunc: (arg1: A1, callback: (res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<[R1, R2]>;\nexport function bindCallback<A1, R1>(callbackFunc: (arg1: A1, callback: (res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<R1>;\nexport function bindCallback<A1>(callbackFunc: (arg1: A1, callback: () => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<void>;\n\nexport function bindCallback<A1, A2, R1, R2, R3, R4>(callbackFunc: (arg1: A1, arg2: A2, callback: (res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<any[]>;\nexport function bindCallback<A1, A2, R1, R2, R3>(callbackFunc: (arg1: A1, arg2: A2, callback: (res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<[R1, R2, R3]>;\nexport function bindCallback<A1, A2, R1, R2>(callbackFunc: (arg1: A1, arg2: A2, callback: (res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<[R1, R2]>;\nexport function bindCallback<A1, A2, R1>(callbackFunc: (arg1: A1, arg2: A2, callback: (res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<R1>;\nexport function bindCallback<A1, A2>(callbackFunc: (arg1: A1, arg2: A2, callback: () => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<void>;\n\nexport function bindCallback<A1, A2, A3, R1, R2, R3, R4>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<any[]>;\nexport function bindCallback<A1, A2, A3, R1, R2, R3>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<[R1, R2, R3]>;\nexport function bindCallback<A1, A2, A3, R1, R2>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<[R1, R2]>;\nexport function bindCallback<A1, A2, A3, R1>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<R1>;\nexport function bindCallback<A1, A2, A3>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: () => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<void>;\n\nexport function bindCallback<A1, A2, A3, A4, R1, R2, R3, R4>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<any[]>;\nexport function bindCallback<A1, A2, A3, A4, R1, R2, R3>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<[R1, R2, R3]>;\nexport function bindCallback<A1, A2, A3, A4, R1, R2>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<[R1, R2]>;\nexport function bindCallback<A1, A2, A3, A4, R1>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<R1>;\nexport function bindCallback<A1, A2, A3, A4>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: () => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<void>;\n\nexport function bindCallback<A1, A2, A3, A4, A5, R1, R2, R3, R4>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<any[]>;\nexport function bindCallback<A1, A2, A3, A4, A5, R1, R2, R3>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<[R1, R2, R3]>;\nexport function bindCallback<A1, A2, A3, A4, A5, R1, R2>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<[R1, R2]>;\nexport function bindCallback<A1, A2, A3, A4, A5, R1>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<R1>;\nexport function bindCallback<A1, A2, A3, A4, A5>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: () => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<void>;\n\nexport function bindCallback<A, R>(callbackFunc: (...args: Array<A | ((result: R) => any)>) => any, scheduler?: SchedulerLike): (...args: A[]) => Observable<R>;\nexport function bindCallback<A, R>(callbackFunc: (...args: Array<A | ((...results: R[]) => any)>) => any, scheduler?: SchedulerLike): (...args: A[]) => Observable<R[]>;\n\nexport function bindCallback(callbackFunc: Function, scheduler?: SchedulerLike): (...args: any[]) => Observable<any>;\n\n// tslint:enable:max-line-length\n\n/**\n * Converts a callback API to a function that returns an Observable.\n *\n * <span class=\"informal\">Give it a function `f` of type `f(x, callback)` and\n * it will return a function `g` that when called as `g(x)` will output an\n * Observable.</span>\n *\n * `bindCallback` is not an operator because its input and output are not\n * Observables. The input is a function `func` with some parameters. The\n * last parameter must be a callback function that `func` calls when it is\n * done.\n *\n * The output of `bindCallback` is a function that takes the same parameters\n * as `func`, except the last one (the callback). When the output function\n * is called with arguments it will return an Observable. If function `func`\n * calls its callback with one argument, the Observable will emit that value.\n * If on the other hand the callback is called with multiple values the resulting\n * Observable will emit an array with said values as arguments.\n *\n * It is **very important** to remember that input function `func` is not called\n * when the output function is, but rather when the Observable returned by the output\n * function is subscribed. This means if `func` makes an AJAX request, that request\n * will be made every time someone subscribes to the resulting Observable, but not before.\n *\n * The last optional parameter - `scheduler` - can be used to control when the call\n * to `func` happens after someone subscribes to Observable, as well as when results\n * passed to callback will be emitted. By default, the subscription to an Observable calls `func`\n * synchronously, but using {@link asyncScheduler} as the last parameter will defer the call to `func`,\n * just like wrapping the call in `setTimeout` with a timeout of `0` would. If you were to use the async Scheduler\n * and call `subscribe` on the output Observable, all function calls that are currently executing\n * will end before `func` is invoked.\n *\n * By default, results passed to the callback are emitted immediately after `func` invokes the callback.\n * In particular, if the callback is called synchronously, then the subscription of the resulting Observable\n * will call the `next` function synchronously as well.  If you want to defer that call,\n * you may use {@link asyncScheduler} just as before.  This means that by using `Scheduler.async` you can\n * ensure that `func` always calls its callback asynchronously, thus avoiding terrifying Zalgo.\n *\n * Note that the Observable created by the output function will always emit a single value\n * and then complete immediately. If `func` calls the callback multiple times, values from subsequent\n * calls will not appear in the stream. If you need to listen for multiple calls,\n *  you probably want to use {@link fromEvent} or {@link fromEventPattern} instead.\n *\n * If `func` depends on some context (`this` property) and is not already bound, the context of `func`\n * will be the context that the output function has at call time. In particular, if `func`\n * is called as a method of some objec and if `func` is not already bound, in order to preserve the context\n * it is recommended that the context of the output function is set to that object as well.\n *\n * If the input function calls its callback in the \"node style\" (i.e. first argument to callback is\n * optional error parameter signaling whether the call failed or not), {@link bindNodeCallback}\n * provides convenient error handling and probably is a better choice.\n * `bindCallback` will treat such functions the same as any other and error parameters\n * (whether passed or not) will always be interpreted as regular callback argument.\n *\n * ## Examples\n *\n * ### Convert jQuery's getJSON to an Observable API\n * ```ts\n * import { bindCallback } from 'rxjs';\n * import * as jQuery from 'jquery';\n *\n * // Suppose we have jQuery.getJSON('/my/url', callback)\n * const getJSONAsObservable = bindCallback(jQuery.getJSON);\n * const result = getJSONAsObservable('/my/url');\n * result.subscribe(x => console.log(x), e => console.error(e));\n * ```\n *\n * ### Receive an array of arguments passed to a callback\n * ```ts\n * import { bindCallback } from 'rxjs';\n *\n * const someFunction = (a, b, c) => {\n *   console.log(a); // 5\n *   console.log(b); // 'some string'\n *   console.log(c); // {someProperty: 'someValue'}\n * };\n *\n * const boundSomeFunction = bindCallback(someFunction);\n * boundSomeFunction().subscribe(values => {\n *   console.log(values) // [5, 'some string', {someProperty: 'someValue'}]\n * });\n * ```\n *\n * ### Compare behaviour with and without async Scheduler\n * ```ts\n * import { bindCallback } from 'rxjs';\n *\n * function iCallMyCallbackSynchronously(cb) {\n *   cb();\n * }\n *\n * const boundSyncFn = bindCallback(iCallMyCallbackSynchronously);\n * const boundAsyncFn = bindCallback(iCallMyCallbackSynchronously, null, Rx.Scheduler.async);\n *\n * boundSyncFn().subscribe(() => console.log('I was sync!'));\n * boundAsyncFn().subscribe(() => console.log('I was async!'));\n * console.log('This happened...');\n *\n * // Logs:\n * // I was sync!\n * // This happened...\n * // I was async!\n * ```\n *\n * ### Use bindCallback on an object method\n * ```ts\n * import { bindCallback } from 'rxjs';\n *\n * const boundMethod = bindCallback(someObject.methodWithCallback);\n * boundMethod.call(someObject) // make sure methodWithCallback has access to someObject\n * .subscribe(subscriber);\n * ```\n *\n * @see {@link bindNodeCallback}\n * @see {@link from}\n *\n * @param {function} func A function with a callback as the last parameter.\n * @param {SchedulerLike} [scheduler] The scheduler on which to schedule the\n * callbacks.\n * @return {function(...params: *): Observable} A function which returns the\n * Observable that delivers the same values the callback would deliver.\n * @name bindCallback\n */\nexport function bindCallback<T>(\n  callbackFunc: Function,\n  resultSelector?: Function|SchedulerLike,\n  scheduler?: SchedulerLike\n): (...args: any[]) => Observable<T> {\n  if (resultSelector) {\n    if (isScheduler(resultSelector)) {\n      scheduler = resultSelector;\n    } else {\n      // DEPRECATED PATH\n      return (...args: any[]) => bindCallback(callbackFunc, scheduler)(...args).pipe(\n        map((args) => isArray(args) ? resultSelector(...args) : resultSelector(args)),\n      );\n    }\n  }\n\n  return function (this: any, ...args: any[]): Observable<T> {\n    const context = this;\n    let subject: AsyncSubject<T>;\n    const params = {\n      context,\n      subject,\n      callbackFunc,\n      scheduler,\n    };\n    return new Observable<T>(subscriber => {\n      if (!scheduler) {\n        if (!subject) {\n          subject = new AsyncSubject<T>();\n          const handler = (...innerArgs: any[]) => {\n            subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);\n            subject.complete();\n          };\n\n          try {\n            callbackFunc.apply(context, [...args, handler]);\n          } catch (err) {\n            if (canReportError(subject)) {\n              subject.error(err);\n            } else {\n              console.warn(err);\n            }\n          }\n        }\n        return subject.subscribe(subscriber);\n      } else {\n        const state: DispatchState<T> = {\n          args, subscriber, params,\n        };\n        return scheduler.schedule<DispatchState<T>>(dispatch, 0, state);\n      }\n    });\n  };\n}\n\ninterface DispatchState<T> {\n  args: any[];\n  subscriber: Subscriber<T>;\n  params: ParamsContext<T>;\n}\n\ninterface ParamsContext<T> {\n  callbackFunc: Function;\n  scheduler: SchedulerLike;\n  context: any;\n  subject: AsyncSubject<T>;\n}\n\nfunction dispatch<T>(this: SchedulerAction<DispatchState<T>>, state: DispatchState<T>) {\n  const self = this;\n  const { args, subscriber, params } = state;\n  const { callbackFunc, context, scheduler } = params;\n  let { subject } = params;\n  if (!subject) {\n    subject = params.subject = new AsyncSubject<T>();\n\n    const handler = (...innerArgs: any[]) => {\n      const value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;\n      this.add(scheduler.schedule<NextState<T>>(dispatchNext, 0, { value, subject }));\n    };\n\n    try {\n      callbackFunc.apply(context, [...args, handler]);\n    } catch (err) {\n      subject.error(err);\n    }\n  }\n\n  this.add(subject.subscribe(subscriber));\n}\n\ninterface NextState<T> {\n  subject: AsyncSubject<T>;\n  value: T;\n}\n\nfunction dispatchNext<T>(this: SchedulerAction<NextState<T>>, state: NextState<T>) {\n  const { value, subject } = state;\n  subject.next(value);\n  subject.complete();\n}\n\ninterface ErrorState<T> {\n  subject: AsyncSubject<T>;\n  err: any;\n}\n\nfunction dispatchError<T>(this: SchedulerAction<ErrorState<T>>, state: ErrorState<T>) {\n  const { err, subject } = state;\n  subject.error(err);\n}\n","import { Observable } from '../Observable';\nimport { AsyncSubject } from '../AsyncSubject';\nimport { Subscriber } from '../Subscriber';\nimport { SchedulerAction, SchedulerLike } from '../types';\nimport { map } from '../operators/map';\nimport { canReportError } from '../util/canReportError';\nimport { isScheduler } from '../util/isScheduler';\nimport { isArray } from '../util/isArray';\n\n/* tslint:disable:max-line-length */\n/** @deprecated resultSelector is deprecated, pipe to map instead */\nexport function bindNodeCallback(callbackFunc: Function, resultSelector: Function, scheduler?: SchedulerLike): (...args: any[]) => Observable<any>;\n\nexport function bindNodeCallback<R1, R2, R3, R4>(callbackFunc: (callback: (err: any, res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (...args: any[]) => Observable<any[]>;\nexport function bindNodeCallback<R1, R2, R3>(callbackFunc: (callback: (err: any, res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): () => Observable<[R1, R2, R3]>;\nexport function bindNodeCallback<R1, R2>(callbackFunc: (callback: (err: any, res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): () => Observable<[R1, R2]>;\nexport function bindNodeCallback<R1>(callbackFunc: (callback: (err: any, res1: R1) => any) => any, scheduler?: SchedulerLike): () => Observable<R1>;\nexport function bindNodeCallback(callbackFunc: (callback: (err: any) => any) => any, scheduler?: SchedulerLike): () => Observable<void>;\n\nexport function bindNodeCallback<A1, R1, R2, R3, R4>(callbackFunc: (arg1: A1, callback: (err: any, res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (...args: any[]) => Observable<any[]>;\nexport function bindNodeCallback<A1, R1, R2, R3>(callbackFunc: (arg1: A1, callback: (err: any, res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<[R1, R2, R3]>;\nexport function bindNodeCallback<A1, R1, R2>(callbackFunc: (arg1: A1, callback: (err: any, res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<[R1, R2]>;\nexport function bindNodeCallback<A1, R1>(callbackFunc: (arg1: A1, callback: (err: any, res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<R1>;\nexport function bindNodeCallback<A1>(callbackFunc: (arg1: A1, callback: (err: any) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<void>;\n\nexport function bindNodeCallback<A1, A2, R1, R2, R3, R4>(callbackFunc: (arg1: A1, arg2: A2, callback: (err: any, res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (...args: any[]) => Observable<any[]>;\nexport function bindNodeCallback<A1, A2, R1, R2, R3>(callbackFunc: (arg1: A1, arg2: A2, callback: (err: any, res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<[R1, R2, R3]>;\nexport function bindNodeCallback<A1, A2, R1, R2>(callbackFunc: (arg1: A1, arg2: A2, callback: (err: any, res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<[R1, R2]>;\nexport function bindNodeCallback<A1, A2, R1>(callbackFunc: (arg1: A1, arg2: A2, callback: (err: any, res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<R1>;\nexport function bindNodeCallback<A1, A2>(callbackFunc: (arg1: A1, arg2: A2, callback: (err: any) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<void>;\n\nexport function bindNodeCallback<A1, A2, A3, R1, R2, R3, R4>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (...args: any[]) => Observable<any[]>;\nexport function bindNodeCallback<A1, A2, A3, R1, R2, R3>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<[R1, R2, R3]>;\nexport function bindNodeCallback<A1, A2, A3, R1, R2>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<[R1, R2]>;\nexport function bindNodeCallback<A1, A2, A3, R1>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<R1>;\nexport function bindNodeCallback<A1, A2, A3>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<void>;\n\nexport function bindNodeCallback<A1, A2, A3, A4, R1, R2, R3, R4>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (...args: any[]) => Observable<any[]>;\nexport function bindNodeCallback<A1, A2, A3, A4, R1, R2, R3>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<[R1, R2, R3]>;\nexport function bindNodeCallback<A1, A2, A3, A4, R1, R2>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<[R1, R2]>;\nexport function bindNodeCallback<A1, A2, A3, A4, R1>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<R1>;\nexport function bindNodeCallback<A1, A2, A3, A4>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<void>;\n\nexport function bindNodeCallback<A1, A2, A3, A4, A5, R1, R2, R3, R4>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (...args: any[]) => Observable<any[]>;\nexport function bindNodeCallback<A1, A2, A3, A4, A5, R1, R2, R3>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<[R1, R2, R3]>;\nexport function bindNodeCallback<A1, A2, A3, A4, A5, R1, R2>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<[R1, R2]>;\nexport function bindNodeCallback<A1, A2, A3, A4, A5, R1>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<R1>;\nexport function bindNodeCallback<A1, A2, A3, A4, A5>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<void>; /* tslint:enable:max-line-length */\n\nexport function bindNodeCallback(callbackFunc: Function, scheduler?: SchedulerLike): (...args: any[]) => Observable<any[]>;\n/**\n * Converts a Node.js-style callback API to a function that returns an\n * Observable.\n *\n * <span class=\"informal\">It's just like {@link bindCallback}, but the\n * callback is expected to be of type `callback(error, result)`.</span>\n *\n * `bindNodeCallback` is not an operator because its input and output are not\n * Observables. The input is a function `func` with some parameters, but the\n * last parameter must be a callback function that `func` calls when it is\n * done. The callback function is expected to follow Node.js conventions,\n * where the first argument to the callback is an error object, signaling\n * whether call was successful. If that object is passed to callback, it means\n * something went wrong.\n *\n * The output of `bindNodeCallback` is a function that takes the same\n * parameters as `func`, except the last one (the callback). When the output\n * function is called with arguments, it will return an Observable.\n * If `func` calls its callback with error parameter present, Observable will\n * error with that value as well. If error parameter is not passed, Observable will emit\n * second parameter. If there are more parameters (third and so on),\n * Observable will emit an array with all arguments, except first error argument.\n *\n * Note that `func` will not be called at the same time output function is,\n * but rather whenever resulting Observable is subscribed. By default call to\n * `func` will happen synchronously after subscription, but that can be changed\n * with proper `scheduler` provided as optional third parameter. {@link SchedulerLike}\n * can also control when values from callback will be emitted by Observable.\n * To find out more, check out documentation for {@link bindCallback}, where\n * {@link SchedulerLike} works exactly the same.\n *\n * As in {@link bindCallback}, context (`this` property) of input function will be set to context\n * of returned function, when it is called.\n *\n * After Observable emits value, it will complete immediately. This means\n * even if `func` calls callback again, values from second and consecutive\n * calls will never appear on the stream. If you need to handle functions\n * that call callbacks multiple times, check out {@link fromEvent} or\n * {@link fromEventPattern} instead.\n *\n * Note that `bindNodeCallback` can be used in non-Node.js environments as well.\n * \"Node.js-style\" callbacks are just a convention, so if you write for\n * browsers or any other environment and API you use implements that callback style,\n * `bindNodeCallback` can be safely used on that API functions as well.\n *\n * Remember that Error object passed to callback does not have to be an instance\n * of JavaScript built-in `Error` object. In fact, it does not even have to an object.\n * Error parameter of callback function is interpreted as \"present\", when value\n * of that parameter is truthy. It could be, for example, non-zero number, non-empty\n * string or boolean `true`. In all of these cases resulting Observable would error\n * with that value. This means usually regular style callbacks will fail very often when\n * `bindNodeCallback` is used. If your Observable errors much more often then you\n * would expect, check if callback really is called in Node.js-style and, if not,\n * switch to {@link bindCallback} instead.\n *\n * Note that even if error parameter is technically present in callback, but its value\n * is falsy, it still won't appear in array emitted by Observable.\n *\n * ## Examples\n * ###  Read a file from the filesystem and get the data as an Observable\n * ```ts\n * import * as fs from 'fs';\n * const readFileAsObservable = bindNodeCallback(fs.readFile);\n * const result = readFileAsObservable('./roadNames.txt', 'utf8');\n * result.subscribe(x => console.log(x), e => console.error(e));\n * ```\n *\n * ### Use on function calling callback with multiple arguments\n * ```ts\n * someFunction((err, a, b) => {\n *   console.log(err); // null\n *   console.log(a); // 5\n *   console.log(b); // \"some string\"\n * });\n * const boundSomeFunction = bindNodeCallback(someFunction);\n * boundSomeFunction()\n * .subscribe(value => {\n *   console.log(value); // [5, \"some string\"]\n * });\n * ```\n *\n * ### Use on function calling callback in regular style\n * ```ts\n * someFunction(a => {\n *   console.log(a); // 5\n * });\n * const boundSomeFunction = bindNodeCallback(someFunction);\n * boundSomeFunction()\n * .subscribe(\n *   value => {}             // never gets called\n *   err => console.log(err) // 5\n * );\n * ```\n *\n * @see {@link bindCallback}\n * @see {@link from}\n *\n * @param {function} func Function with a Node.js-style callback as the last parameter.\n * @param {SchedulerLike} [scheduler] The scheduler on which to schedule the\n * callbacks.\n * @return {function(...params: *): Observable} A function which returns the\n * Observable that delivers the same values the Node.js callback would\n * deliver.\n * @name bindNodeCallback\n */\nexport function bindNodeCallback<T>(\n  callbackFunc: Function,\n  resultSelector: Function|SchedulerLike,\n  scheduler?: SchedulerLike\n): (...args: any[]) => Observable<T> {\n\n  if (resultSelector) {\n    if (isScheduler(resultSelector)) {\n      scheduler = resultSelector;\n    } else {\n      // DEPRECATED PATH\n      return (...args: any[]) => bindNodeCallback(callbackFunc, scheduler)(...args).pipe(\n        map(args => isArray(args) ? resultSelector(...args) : resultSelector(args))\n      );\n    }\n  }\n\n  return function(this: any, ...args: any[]): Observable<T> {\n    const params: ParamsState<T> = {\n      subject: undefined,\n      args,\n      callbackFunc,\n      scheduler,\n      context: this,\n    };\n    return new Observable<T>(subscriber => {\n      const { context } = params;\n      let { subject } = params;\n      if (!scheduler) {\n        if (!subject) {\n          subject = params.subject = new AsyncSubject<T>();\n          const handler = (...innerArgs: any[]) => {\n            const err = innerArgs.shift();\n\n            if (err) {\n              subject.error(err);\n              return;\n            }\n\n            subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);\n            subject.complete();\n          };\n\n          try {\n            callbackFunc.apply(context, [...args, handler]);\n          } catch (err) {\n            if (canReportError(subject)) {\n              subject.error(err);\n            } else {\n              console.warn(err);\n            }\n          }\n        }\n        return subject.subscribe(subscriber);\n      } else {\n        return scheduler.schedule<DispatchState<T>>(dispatch, 0, { params, subscriber, context });\n      }\n    });\n  };\n}\n\ninterface DispatchState<T> {\n  subscriber: Subscriber<T>;\n  context: any;\n  params: ParamsState<T>;\n}\n\ninterface ParamsState<T> {\n  callbackFunc: Function;\n  args: any[];\n  scheduler: SchedulerLike;\n  subject: AsyncSubject<T>;\n  context: any;\n}\n\nfunction dispatch<T>(this: SchedulerAction<DispatchState<T>>, state: DispatchState<T>) {\n  const { params, subscriber, context } = state;\n  const { callbackFunc, args, scheduler } = params;\n  let subject = params.subject;\n\n  if (!subject) {\n    subject = params.subject = new AsyncSubject<T>();\n\n    const handler = (...innerArgs: any[]) => {\n      const err = innerArgs.shift();\n      if (err) {\n        this.add(scheduler.schedule<DispatchErrorArg<T>>(dispatchError, 0, { err, subject }));\n      } else {\n        const value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;\n        this.add(scheduler.schedule<DispatchNextArg<T>>(dispatchNext, 0, { value, subject }));\n      }\n    };\n\n    try {\n      callbackFunc.apply(context, [...args, handler]);\n    } catch (err) {\n      this.add(scheduler.schedule<DispatchErrorArg<T>>(dispatchError, 0, { err, subject }));\n    }\n  }\n\n  this.add(subject.subscribe(subscriber));\n}\n\ninterface DispatchNextArg<T> {\n  subject: AsyncSubject<T>;\n  value: T;\n}\n\nfunction dispatchNext<T>(arg: DispatchNextArg<T>) {\n  const { value, subject } = arg;\n  subject.next(value);\n  subject.complete();\n}\n\ninterface DispatchErrorArg<T> {\n  subject: AsyncSubject<T>;\n  err: any;\n}\n\nfunction dispatchError<T>(arg: DispatchErrorArg<T>) {\n  const { err, subject } = arg;\n  subject.error(err);\n}\n","import { Subscriber } from './Subscriber';\nimport { OuterSubscriber } from './OuterSubscriber';\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class InnerSubscriber<T, R> extends Subscriber<R> {\n  private index = 0;\n\n  constructor(private parent: OuterSubscriber<T, R>, public outerValue: T, public outerIndex: number) {\n    super();\n  }\n\n  protected _next(value: R): void {\n    this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);\n  }\n\n  protected _error(error: any): void {\n    this.parent.notifyError(error, this);\n    this.unsubscribe();\n  }\n\n  protected _complete(): void {\n    this.parent.notifyComplete(this);\n    this.unsubscribe();\n  }\n}\n","import { Subscriber } from '../Subscriber';\nimport { hostReportError } from './hostReportError';\n\nexport const subscribeToPromise = <T>(promise: PromiseLike<T>) => (subscriber: Subscriber<T>) => {\n  promise.then(\n    (value) => {\n      if (!subscriber.closed) {\n        subscriber.next(value);\n        subscriber.complete();\n      }\n    },\n    (err: any) => subscriber.error(err)\n  )\n  .then(null, hostReportError);\n  return subscriber;\n};\n","import { Subscriber } from '../Subscriber';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\n\nexport const subscribeToIterable = <T>(iterable: Iterable<T>) => (subscriber: Subscriber<T>) => {\n  const iterator = (iterable as any)[Symbol_iterator]();\n\n  do {\n    let item: IteratorResult<T>;\n    try {\n      item = iterator.next();\n    } catch (err) {\n      subscriber.error(err);\n      return subscriber;\n    }\n    if (item.done) {\n      subscriber.complete();\n      break;\n    }\n    subscriber.next(item.value);\n    if (subscriber.closed) {\n      break;\n    }\n  } while (true);\n\n  // Finalize the iterator if it happens to be a Generator\n  if (typeof iterator.return === 'function') {\n    subscriber.add(() => {\n      if (iterator.return) {\n        iterator.return();\n      }\n    });\n  }\n\n  return subscriber;\n};\n","import { Subscriber } from '../Subscriber';\nimport { observable as Symbol_observable } from '../symbol/observable';\n\n/**\n * Subscribes to an object that implements Symbol.observable with the given\n * Subscriber.\n * @param obj An object that implements Symbol.observable\n */\nexport const subscribeToObservable = <T>(obj: any) => (subscriber: Subscriber<T>) => {\n  const obs = obj[Symbol_observable]();\n  if (typeof obs.subscribe !== 'function') {\n    // Should be caught by observable subscribe function error handling.\n    throw new TypeError('Provided object does not correctly implement Symbol.observable');\n  } else {\n    return obs.subscribe(subscriber);\n  }\n};\n","import { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { InteropObservable, SchedulerLike, Subscribable } from '../types';\n\nexport function scheduleObservable<T>(input: InteropObservable<T>, scheduler: SchedulerLike) {\n  return new Observable<T>(subscriber => {\n    const sub = new Subscription();\n    sub.add(scheduler.schedule(() => {\n      const observable: Subscribable<T> = input[Symbol_observable]();\n      sub.add(observable.subscribe({\n        next(value) { sub.add(scheduler.schedule(() => subscriber.next(value))); },\n        error(err) { sub.add(scheduler.schedule(() => subscriber.error(err))); },\n        complete() { sub.add(scheduler.schedule(() => subscriber.complete())); },\n      }));\n    }));\n    return sub;\n  });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscription } from '../Subscription';\n\nexport function schedulePromise<T>(input: PromiseLike<T>, scheduler: SchedulerLike) {\n  return new Observable<T>(subscriber => {\n    const sub = new Subscription();\n    sub.add(scheduler.schedule(() => input.then(\n      value => {\n        sub.add(scheduler.schedule(() => {\n          subscriber.next(value);\n          sub.add(scheduler.schedule(() => subscriber.complete()));\n        }));\n      },\n      err => {\n        sub.add(scheduler.schedule(() => subscriber.error(err)));\n      }\n    )));\n    return sub;\n  });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscription } from '../Subscription';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\n\nexport function scheduleIterable<T>(input: Iterable<T>, scheduler: SchedulerLike) {\n  if (!input) {\n    throw new Error('Iterable cannot be null');\n  }\n  return new Observable<T>(subscriber => {\n    const sub = new Subscription();\n    let iterator: Iterator<T>;\n    sub.add(() => {\n      // Finalize generators\n      if (iterator && typeof iterator.return === 'function') {\n        iterator.return();\n      }\n    });\n    sub.add(scheduler.schedule(() => {\n      iterator = input[Symbol_iterator]();\n      sub.add(scheduler.schedule(function () {\n        if (subscriber.closed) {\n          return;\n        }\n        let value: T;\n        let done: boolean;\n        try {\n          const result = iterator.next();\n          value = result.value;\n          done = result.done;\n        } catch (err) {\n          subscriber.error(err);\n          return;\n        }\n        if (done) {\n          subscriber.complete();\n        } else {\n          subscriber.next(value);\n          this.schedule();\n        }\n      }));\n    }));\n    return sub;\n  });\n}\n","import { InteropObservable } from '../types';\nimport { observable as Symbol_observable } from '../symbol/observable';\n\n/** Identifies an input as being Observable (but not necessary an Rx Observable) */\nexport function isInteropObservable(input: any): input is InteropObservable<any> {\n  return input && typeof input[Symbol_observable] === 'function';\n}\n","import { iterator as Symbol_iterator } from '../symbol/iterator';\n\n/** Identifies an input as being an Iterable */\nexport function isIterable(input: any): input is Iterable<any> {\n  return input && typeof input[Symbol_iterator] === 'function';\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput, ObservedValuesFromArray, ObservedValueOf, SubscribableOrPromise } from '../types';\nimport { isArray } from '../util/isArray';\nimport { map } from '../operators/map';\nimport { isObject } from '../util/isObject';\nimport { isObservable } from '../util/isObservable';\nimport { from } from './from';\n\n/* tslint:disable:max-line-length */\n\n// forkJoin(a$, b$, c$)\n/** @deprecated Use the version that takes an array of Observables instead */\nexport function forkJoin<T>(v1: SubscribableOrPromise<T>): Observable<[T]>;\n/** @deprecated Use the version that takes an array of Observables instead */\nexport function forkJoin<T, T2>(v1: ObservableInput<T>, v2: ObservableInput<T2>): Observable<[T, T2]>;\n/** @deprecated Use the version that takes an array of Observables instead */\nexport function forkJoin<T, T2, T3>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>): Observable<[T, T2, T3]>;\n/** @deprecated Use the version that takes an array of Observables instead */\nexport function forkJoin<T, T2, T3, T4>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>): Observable<[T, T2, T3, T4]>;\n/** @deprecated Use the version that takes an array of Observables instead */\nexport function forkJoin<T, T2, T3, T4, T5>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>): Observable<[T, T2, T3, T4, T5]>;\n/** @deprecated Use the version that takes an array of Observables instead */\nexport function forkJoin<T, T2, T3, T4, T5, T6>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>): Observable<[T, T2, T3, T4, T5, T6]>;\n\n// forkJoin([a$, b$, c$]);\n// TODO(benlesh): Uncomment for TS 3.0\n// export function forkJoin(sources: []): Observable<never>;\nexport function forkJoin<A>(sources: [ObservableInput<A>]): Observable<[A]>;\nexport function forkJoin<A, B>(sources: [ObservableInput<A>, ObservableInput<B>]): Observable<[A, B]>;\nexport function forkJoin<A, B, C>(sources: [ObservableInput<A>, ObservableInput<B>, ObservableInput<C>]): Observable<[A, B, C]>;\nexport function forkJoin<A, B, C, D>(sources: [ObservableInput<A>, ObservableInput<B>, ObservableInput<C>, ObservableInput<D>]): Observable<[A, B, C, D]>;\nexport function forkJoin<A, B, C, D, E>(sources: [ObservableInput<A>, ObservableInput<B>, ObservableInput<C>, ObservableInput<D>, ObservableInput<E>]): Observable<[A, B, C, D, E]>;\nexport function forkJoin<A, B, C, D, E, F>(sources: [ObservableInput<A>, ObservableInput<B>, ObservableInput<C>, ObservableInput<D>, ObservableInput<E>, ObservableInput<F>]): Observable<[A, B, C, D, E, F]>;\nexport function forkJoin<A extends ObservableInput<any>[]>(sources: A): Observable<ObservedValuesFromArray<A>[]>;\n\n// forkJoin({})\nexport function forkJoin(sourcesObject: {}): Observable<never>;\nexport function forkJoin<T, K extends keyof T>(sourcesObject: T): Observable<{ [K in keyof T]: ObservedValueOf<T[K]> }>;\n\n/** @deprecated resultSelector is deprecated, pipe to map instead */\nexport function forkJoin(...args: Array<ObservableInput<any>|Function>): Observable<any>;\n/** @deprecated Use the version that takes an array of Observables instead */\nexport function forkJoin<T>(...sources: ObservableInput<T>[]): Observable<T[]>;\n/* tslint:enable:max-line-length */\n\n/**\n * Accepts an `Array` of {@link ObservableInput} or a dictionary `Object` of {@link ObservableInput} and returns\n * an {@link Observable} that emits either an array of values in the exact same order as the passed array,\n * or a dictionary of values in the same shape as the passed dictionary.\n *\n * <span class=\"informal\">Wait for Observables to complete and then combine last values they emitted.</span>\n *\n * ![](forkJoin.png)\n *\n * `forkJoin` is an operator that takes any number of input observables which can be passed either as an array\n * or a dictionary of input observables. If no input observables are provided, resulting stream will complete\n * immediately.\n *\n * `forkJoin` will wait for all passed observables to complete and then it will emit an array or an object with last\n * values from corresponding observables.\n *\n * If you pass an array of `n` observables to the operator, resulting\n * array will have `n` values, where first value is the last thing emitted by the first observable,\n * second value is the last thing emitted by the second observable and so on.\n *\n * If you pass a dictionary of observables to the operator, resulting\n * objects will have the same keys as the dictionary passed, with their last values they've emitted\n * located at the corresponding key.\n *\n * That means `forkJoin` will not emit more than once and it will complete after that. If you need to emit combined\n * values not only at the end of lifecycle of passed observables, but also throughout it, try out {@link combineLatest}\n * or {@link zip} instead.\n *\n * In order for resulting array to have the same length as the number of input observables, whenever any of\n * that observables completes without emitting any value, `forkJoin` will complete at that moment as well\n * and it will not emit anything either, even if it already has some last values from other observables.\n * Conversely, if there is an observable that never completes, `forkJoin` will never complete as well,\n * unless at any point some other observable completes without emitting value, which brings us back to\n * the previous case. Overall, in order for `forkJoin` to emit a value, all observables passed as arguments\n * have to emit something at least once and complete.\n *\n * If any input observable errors at some point, `forkJoin` will error as well and all other observables\n * will be immediately unsubscribed.\n *\n * Optionally `forkJoin` accepts project function, that will be called with values which normally\n * would land in emitted array. Whatever is returned by project function, will appear in output\n * observable instead. This means that default project can be thought of as a function that takes\n * all its arguments and puts them into an array. Note that project function will be called only\n * when output observable is supposed to emit a result.\n *\n * ## Examples\n *\n * ### Use forkJoin with a dictionary of observable inputs\n * ```ts\n * import { forkJoin, of, timer } from 'rxjs';\n *\n * const observable = forkJoin({\n *   foo: of(1, 2, 3, 4),\n *   bar: Promise.resolve(8),\n *   baz: timer(4000),\n * });\n * observable.subscribe({\n *  next: value => console.log(value),\n *  complete: () => console.log('This is how it ends!'),\n * });\n *\n * // Logs:\n * // { foo: 4, bar: 8, baz: 0 } after 4 seconds\n * // \"This is how it ends!\" immediately after\n * ```\n *\n * ### Use forkJoin with an array of observable inputs\n * ```ts\n * import { forkJoin, of } from 'rxjs';\n *\n * const observable = forkJoin([\n *   of(1, 2, 3, 4),\n *   Promise.resolve(8),\n *   timer(4000),\n * ]);\n * observable.subscribe({\n *  next: value => console.log(value),\n *  complete: () => console.log('This is how it ends!'),\n * });\n *\n * // Logs:\n * // [4, 8, 0] after 4 seconds\n * // \"This is how it ends!\" immediately after\n * ```\n *\n * @see {@link combineLatest}\n * @see {@link zip}\n *\n * @param {...ObservableInput} sources Any number of Observables provided either as an array or as an arguments\n * passed directly to the operator.\n * @param {function} [project] Function that takes values emitted by input Observables and returns value\n * that will appear in resulting Observable instead of default array.\n * @return {Observable} Observable emitting either an array of last values emitted by passed Observables\n * or value from project function.\n */\nexport function forkJoin(\n  ...sources: any[]\n): Observable<any> {\n  if (sources.length === 1) {\n    const first = sources[0];\n    if (isArray(first)) {\n      return forkJoinInternal(first, null);\n    }\n    // TODO(benlesh): isObservable check will not be necessary when deprecated path is removed.\n    if (isObject(first) && Object.getPrototypeOf(first) === Object.prototype) {\n      const keys = Object.keys(first);\n      return forkJoinInternal(keys.map(key => first[key]), keys);\n    }\n  }\n\n  // DEPRECATED PATHS BELOW HERE\n  if (typeof sources[sources.length - 1] === 'function') {\n    const resultSelector = sources.pop() as Function;\n    sources = (sources.length === 1 && isArray(sources[0])) ? sources[0] : sources;\n    return forkJoinInternal(sources, null).pipe(\n      map((args: any[]) => resultSelector(...args))\n    );\n  }\n\n  return forkJoinInternal(sources, null);\n}\n\nfunction forkJoinInternal(sources: ObservableInput<any>[], keys: string[] | null): Observable<any> {\n  return new Observable(subscriber => {\n    const len = sources.length;\n    if (len === 0) {\n      subscriber.complete();\n      return;\n    }\n    const values = new Array(len);\n    let completed = 0;\n    let emitted = 0;\n    for (let i = 0; i < len; i++) {\n      const source = from(sources[i]);\n      let hasValue = false;\n      subscriber.add(source.subscribe({\n        next: value => {\n          if (!hasValue) {\n            hasValue = true;\n            emitted++;\n          }\n          values[i] = value;\n        },\n        error: err => subscriber.error(err),\n        complete: () => {\n          completed++;\n          if (completed === len || !hasValue) {\n            if (emitted === len) {\n              subscriber.next(keys ?\n                keys.reduce((result, key, i) => (result[key] = values[i], result), {}) :\n                values);\n            }\n            subscriber.complete();\n          }\n        }\n      }));\n    }\n  });\n}\n","import { Observable } from '../Observable';\nimport { isArray } from '../util/isArray';\nimport { isFunction } from '../util/isFunction';\nimport { Subscriber } from '../Subscriber';\nimport { map } from '../operators/map';\n\nconst toString: Function = (() => Object.prototype.toString)();\n\nexport interface NodeStyleEventEmitter {\n  addListener: (eventName: string | symbol, handler: NodeEventHandler) => this;\n  removeListener: (eventName: string | symbol, handler: NodeEventHandler) => this;\n}\n\nexport type NodeEventHandler = (...args: any[]) => void;\n\n// For APIs that implement `addListener` and `removeListener` methods that may\n// not use the same arguments or return EventEmitter values\n// such as React Native\nexport interface NodeCompatibleEventEmitter {\n  addListener: (eventName: string, handler: NodeEventHandler) => void | {};\n  removeListener: (eventName: string, handler: NodeEventHandler) => void | {};\n}\n\nexport interface JQueryStyleEventEmitter {\n  on: (eventName: string, handler: Function) => void;\n  off: (eventName: string, handler: Function) => void;\n}\n\nexport interface HasEventTargetAddRemove<E> {\n  addEventListener(type: string, listener: ((evt: E) => void) | null, options?: boolean | AddEventListenerOptions): void;\n  removeEventListener(type: string, listener?: ((evt: E) => void) | null, options?: EventListenerOptions | boolean): void;\n}\n\nexport type EventTargetLike<T> = HasEventTargetAddRemove<T> | NodeStyleEventEmitter | NodeCompatibleEventEmitter | JQueryStyleEventEmitter;\n\nexport type FromEventTarget<T> = EventTargetLike<T> | ArrayLike<EventTargetLike<T>>;\n\nexport interface EventListenerOptions {\n  capture?: boolean;\n  passive?: boolean;\n  once?: boolean;\n}\n\nexport interface AddEventListenerOptions extends EventListenerOptions {\n  once?: boolean;\n  passive?: boolean;\n}\n\n/* tslint:disable:max-line-length */\nexport function fromEvent<T>(target: FromEventTarget<T>, eventName: string): Observable<T>;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function fromEvent<T>(target: FromEventTarget<T>, eventName: string, resultSelector: (...args: any[]) => T): Observable<T>;\nexport function fromEvent<T>(target: FromEventTarget<T>, eventName: string, options: EventListenerOptions): Observable<T>;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function fromEvent<T>(target: FromEventTarget<T>, eventName: string, options: EventListenerOptions, resultSelector: (...args: any[]) => T): Observable<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Creates an Observable that emits events of a specific type coming from the\n * given event target.\n *\n * <span class=\"informal\">Creates an Observable from DOM events, or Node.js\n * EventEmitter events or others.</span>\n *\n * ![](fromEvent.png)\n *\n * `fromEvent` accepts as a first argument event target, which is an object with methods\n * for registering event handler functions. As a second argument it takes string that indicates\n * type of event we want to listen for. `fromEvent` supports selected types of event targets,\n * which are described in detail below. If your event target does not match any of the ones listed,\n * you should use {@link fromEventPattern}, which can be used on arbitrary APIs.\n * When it comes to APIs supported by `fromEvent`, their methods for adding and removing event\n * handler functions have different names, but they all accept a string describing event type\n * and function itself, which will be called whenever said event happens.\n *\n * Every time resulting Observable is subscribed, event handler function will be registered\n * to event target on given event type. When that event fires, value\n * passed as a first argument to registered function will be emitted by output Observable.\n * When Observable is unsubscribed, function will be unregistered from event target.\n *\n * Note that if event target calls registered function with more than one argument, second\n * and following arguments will not appear in resulting stream. In order to get access to them,\n * you can pass to `fromEvent` optional project function, which will be called with all arguments\n * passed to event handler. Output Observable will then emit value returned by project function,\n * instead of the usual value.\n *\n * Remember that event targets listed below are checked via duck typing. It means that\n * no matter what kind of object you have and no matter what environment you work in,\n * you can safely use `fromEvent` on that object if it exposes described methods (provided\n * of course they behave as was described above). So for example if Node.js library exposes\n * event target which has the same method names as DOM EventTarget, `fromEvent` is still\n * a good choice.\n *\n * If the API you use is more callback then event handler oriented (subscribed\n * callback function fires only once and thus there is no need to manually\n * unregister it), you should use {@link bindCallback} or {@link bindNodeCallback}\n * instead.\n *\n * `fromEvent` supports following types of event targets:\n *\n * **DOM EventTarget**\n *\n * This is an object with `addEventListener` and `removeEventListener` methods.\n *\n * In the browser, `addEventListener` accepts - apart from event type string and event\n * handler function arguments - optional third parameter, which is either an object or boolean,\n * both used for additional configuration how and when passed function will be called. When\n * `fromEvent` is used with event target of that type, you can provide this values\n * as third parameter as well.\n *\n * **Node.js EventEmitter**\n *\n * An object with `addListener` and `removeListener` methods.\n *\n * **JQuery-style event target**\n *\n * An object with `on` and `off` methods\n *\n * **DOM NodeList**\n *\n * List of DOM Nodes, returned for example by `document.querySelectorAll` or `Node.childNodes`.\n *\n * Although this collection is not event target in itself, `fromEvent` will iterate over all Nodes\n * it contains and install event handler function in every of them. When returned Observable\n * is unsubscribed, function will be removed from all Nodes.\n *\n * **DOM HtmlCollection**\n *\n * Just as in case of NodeList it is a collection of DOM nodes. Here as well event handler function is\n * installed and removed in each of elements.\n *\n *\n * ## Examples\n * ### Emits clicks happening on the DOM document\n * ```ts\n * import { fromEvent } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * clicks.subscribe(x => console.log(x));\n *\n * // Results in:\n * // MouseEvent object logged to console every time a click\n * // occurs on the document.\n * ```\n *\n * ### Use addEventListener with capture option\n * ```ts\n * import { fromEvent } from 'rxjs';\n *\n * const clicksInDocument = fromEvent(document, 'click', true); // note optional configuration parameter\n *                                                              // which will be passed to addEventListener\n * const clicksInDiv = fromEvent(someDivInDocument, 'click');\n *\n * clicksInDocument.subscribe(() => console.log('document'));\n * clicksInDiv.subscribe(() => console.log('div'));\n *\n * // By default events bubble UP in DOM tree, so normally\n * // when we would click on div in document\n * // \"div\" would be logged first and then \"document\".\n * // Since we specified optional `capture` option, document\n * // will catch event when it goes DOWN DOM tree, so console\n * // will log \"document\" and then \"div\".\n * ```\n *\n * @see {@link bindCallback}\n * @see {@link bindNodeCallback}\n * @see {@link fromEventPattern}\n *\n * @param {FromEventTarget<T>} target The DOM EventTarget, Node.js\n * EventEmitter, JQuery-like event target, NodeList or HTMLCollection to attach the event handler to.\n * @param {string} eventName The event name of interest, being emitted by the\n * `target`.\n * @param {EventListenerOptions} [options] Options to pass through to addEventListener\n * @return {Observable<T>}\n * @name fromEvent\n */\nexport function fromEvent<T>(\n  target: FromEventTarget<T>,\n  eventName: string,\n  options?: EventListenerOptions | ((...args: any[]) => T),\n  resultSelector?: ((...args: any[]) => T)\n): Observable<T> {\n\n  if (isFunction(options)) {\n    // DEPRECATED PATH\n    resultSelector = options;\n    options = undefined;\n  }\n  if (resultSelector) {\n    // DEPRECATED PATH\n    return fromEvent<T>(target, eventName, <EventListenerOptions | undefined>options).pipe(\n      map(args => isArray(args) ? resultSelector(...args) : resultSelector(args))\n    );\n  }\n\n  return new Observable<T>(subscriber => {\n    function handler(e: T) {\n      if (arguments.length > 1) {\n        subscriber.next(Array.prototype.slice.call(arguments));\n      } else {\n        subscriber.next(e);\n      }\n    }\n    setupSubscription(target, eventName, handler, subscriber, options as EventListenerOptions);\n  });\n}\n\nfunction setupSubscription<T>(sourceObj: FromEventTarget<T>, eventName: string,\n                              handler: (...args: any[]) => void, subscriber: Subscriber<T>,\n                              options?: EventListenerOptions) {\n  let unsubscribe: () => void;\n  if (isEventTarget(sourceObj)) {\n    const source = sourceObj;\n    sourceObj.addEventListener(eventName, handler, options);\n    unsubscribe = () => source.removeEventListener(eventName, handler, options);\n  } else if (isJQueryStyleEventEmitter(sourceObj)) {\n    const source = sourceObj;\n    sourceObj.on(eventName, handler);\n    unsubscribe = () => source.off(eventName, handler);\n  } else if (isNodeStyleEventEmitter(sourceObj)) {\n    const source = sourceObj;\n    sourceObj.addListener(eventName, handler as NodeEventHandler);\n    unsubscribe = () => source.removeListener(eventName, handler as NodeEventHandler);\n  } else if (sourceObj && (sourceObj as any).length) {\n    for (let i = 0, len = (sourceObj as any).length; i < len; i++) {\n      setupSubscription(sourceObj[i], eventName, handler, subscriber, options);\n    }\n  } else {\n    throw new TypeError('Invalid event target');\n  }\n\n  subscriber.add(unsubscribe);\n}\n\nfunction isNodeStyleEventEmitter(sourceObj: any): sourceObj is NodeStyleEventEmitter {\n  return sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';\n}\n\nfunction isJQueryStyleEventEmitter(sourceObj: any): sourceObj is JQueryStyleEventEmitter {\n  return sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';\n}\n\nfunction isEventTarget(sourceObj: any): sourceObj is HasEventTargetAddRemove<any> {\n  return sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';\n}\n","import { Observable } from '../Observable';\nimport { isArray } from '../util/isArray';\nimport { isFunction } from '../util/isFunction';\nimport { NodeEventHandler } from './fromEvent';\nimport { map } from '../operators/map';\n\n/* tslint:disable:max-line-length */\nexport function fromEventPattern<T>(addHandler: (handler: NodeEventHandler) => any, removeHandler?: (handler: NodeEventHandler, signal?: any) => void): Observable<T>;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function fromEventPattern<T>(addHandler: (handler: NodeEventHandler) => any, removeHandler?: (handler: NodeEventHandler, signal?: any) => void, resultSelector?: (...args: any[]) => T): Observable<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Creates an Observable from an arbitrary API for registering event handlers.\n *\n * <span class=\"informal\">When that method for adding event handler was something {@link fromEvent}\n * was not prepared for.</span>\n *\n * ![](fromEventPattern.png)\n *\n * `fromEventPattern` allows you to convert into an Observable any API that supports registering handler functions\n * for events. It is similar to {@link fromEvent}, but far\n * more flexible. In fact, all use cases of {@link fromEvent} could be easily handled by\n * `fromEventPattern` (although in slightly more verbose way).\n *\n * This operator accepts as a first argument an `addHandler` function, which will be injected with\n * handler parameter. That handler is actually an event handler function that you now can pass\n * to API expecting it. `addHandler` will be called whenever Observable\n * returned by the operator is subscribed, so registering handler in API will not\n * necessarily happen when `fromEventPattern` is called.\n *\n * After registration, every time an event that we listen to happens,\n * Observable returned by `fromEventPattern` will emit value that event handler\n * function was called with. Note that if event handler was called with more\n * then one argument, second and following arguments will not appear in the Observable.\n *\n * If API you are using allows to unregister event handlers as well, you can pass to `fromEventPattern`\n * another function - `removeHandler` - as a second parameter. It will be injected\n * with the same handler function as before, which now you can use to unregister\n * it from the API. `removeHandler` will be called when consumer of resulting Observable\n * unsubscribes from it.\n *\n * In some APIs unregistering is actually handled differently. Method registering an event handler\n * returns some kind of token, which is later used to identify which function should\n * be unregistered or it itself has method that unregisters event handler.\n * If that is the case with your API, make sure token returned\n * by registering method is returned by `addHandler`. Then it will be passed\n * as a second argument to `removeHandler`, where you will be able to use it.\n *\n * If you need access to all event handler parameters (not only the first one),\n * or you need to transform them in any way, you can call `fromEventPattern` with optional\n * third parameter - project function which will accept all arguments passed to\n * event handler when it is called. Whatever is returned from project function will appear on\n * resulting stream instead of usual event handlers first argument. This means\n * that default project can be thought of as function that takes its first parameter\n * and ignores the rest.\n *\n * ## Example\n * ### Emits clicks happening on the DOM document\n *\n * ```ts\n * import { fromEventPattern } from 'rxjs';\n *\n * function addClickHandler(handler) {\n *   document.addEventListener('click', handler);\n * }\n *\n * function removeClickHandler(handler) {\n *   document.removeEventListener('click', handler);\n * }\n *\n * const clicks = fromEventPattern(\n *   addClickHandler,\n *   removeClickHandler\n * );\n * clicks.subscribe(x => console.log(x));\n *\n * // Whenever you click anywhere in the browser, DOM MouseEvent\n * // object will be logged.\n * ```\n *\n * ## Example\n * ### Use with API that returns cancellation token\n *\n * ```ts\n * import { fromEventPattern } from 'rxjs';\n *\n * const token = someAPI.registerEventHandler(function() {});\n * someAPI.unregisterEventHandler(token); // this APIs cancellation method accepts\n *                                        // not handler itself, but special token.\n *\n * const someAPIObservable = fromEventPattern(\n *   function(handler) { return someAPI.registerEventHandler(handler); }, // Note that we return the token here...\n *   function(handler, token) { someAPI.unregisterEventHandler(token); }  // ...to then use it here.\n * );\n * ```\n *\n * ## Example\n * ### Use with project function\n *\n * ```ts\n * import { fromEventPattern } from 'rxjs';\n *\n * someAPI.registerEventHandler((eventType, eventMessage) => {\n *   console.log(eventType, eventMessage); // Logs \"EVENT_TYPE\" \"EVENT_MESSAGE\" to console.\n * });\n *\n * const someAPIObservable = fromEventPattern(\n *   handler => someAPI.registerEventHandler(handler),\n *   handler => someAPI.unregisterEventHandler(handler)\n *   (eventType, eventMessage) => eventType + \" --- \" + eventMessage // without that function only \"EVENT_TYPE\"\n * );                                                                // would be emitted by the Observable\n *\n * someAPIObservable.subscribe(value => console.log(value));\n *\n * // Logs:\n * // \"EVENT_TYPE --- EVENT_MESSAGE\"\n * ```\n *\n * @see {@link fromEvent}\n * @see {@link bindCallback}\n * @see {@link bindNodeCallback}\n *\n * @param {function(handler: Function): any} addHandler A function that takes\n * a `handler` function as argument and attaches it somehow to the actual\n * source of events.\n * @param {function(handler: Function, token?: any): void} [removeHandler] A function that\n * takes a `handler` function as an argument and removes it from the event source. If `addHandler`\n * returns some kind of token, `removeHandler` function will have it as a second parameter.\n * @param {function(...args: any): T} [project] A function to\n * transform results. It takes the arguments from the event handler and\n * should return a single value.\n * @return {Observable<T>} Observable which, when an event happens, emits first parameter\n * passed to registered event handler. Alternatively it emits whatever project function returns\n * at that moment.\n * @static true\n * @name fromEventPattern\n * @owner Observable\n */\n\nexport function fromEventPattern<T>(addHandler: (handler: NodeEventHandler) => any,\n                                    removeHandler?: (handler: NodeEventHandler, signal?: any) => void,\n                                    resultSelector?: (...args: any[]) => T): Observable<T | T[]> {\n\n  if (resultSelector) {\n    // DEPRECATED PATH\n    return fromEventPattern<T>(addHandler, removeHandler).pipe(\n      map(args => isArray(args) ? resultSelector(...args) : resultSelector(args))\n    );\n  }\n\n  return new Observable<T | T[]>(subscriber => {\n    const handler = (...e: T[]) => subscriber.next(e.length === 1 ? e[0] : e);\n\n    let retValue: any;\n    try {\n      retValue = addHandler(handler);\n    } catch (err) {\n      subscriber.error(err);\n      return undefined;\n    }\n\n    if (!isFunction(removeHandler)) {\n      return undefined;\n    }\n\n    return () => removeHandler(handler, retValue) ;\n  });\n}\n","import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { identity } from '../util/identity';\nimport { SchedulerAction, SchedulerLike } from '../types';\nimport { isScheduler } from '../util/isScheduler';\n\nexport type ConditionFunc<S> = (state: S) => boolean;\nexport type IterateFunc<S> = (state: S) => S;\nexport type ResultFunc<S, T> = (state: S) => T;\n\ninterface SchedulerState<T, S> {\n  needIterate?: boolean;\n  state: S;\n  subscriber: Subscriber<T>;\n  condition?: ConditionFunc<S>;\n  iterate: IterateFunc<S>;\n  resultSelector: ResultFunc<S, T>;\n}\n\nexport interface GenerateBaseOptions<S> {\n  /**\n   * Initial state.\n   */\n  initialState: S;\n  /**\n   * Condition function that accepts state and returns boolean.\n   * When it returns false, the generator stops.\n   * If not specified, a generator never stops.\n   */\n  condition?: ConditionFunc<S>;\n  /**\n   * Iterate function that accepts state and returns new state.\n   */\n  iterate: IterateFunc<S>;\n  /**\n   * SchedulerLike to use for generation process.\n   * By default, a generator starts immediately.\n   */\n  scheduler?: SchedulerLike;\n}\n\nexport interface GenerateOptions<T, S> extends GenerateBaseOptions<S> {\n  /**\n   * Result selection function that accepts state and returns a value to emit.\n   */\n  resultSelector: ResultFunc<S, T>;\n}\n\n/**\n * Generates an observable sequence by running a state-driven loop\n * producing the sequence's elements, using the specified scheduler\n * to send out observer messages.\n *\n * ![](generate.png)\n *\n * @example <caption>Produces sequence of 0, 1, 2, ... 9, then completes.</caption>\n * const res = generate(0, x => x < 10, x => x + 1, x => x);\n *\n * @example <caption>Using asap scheduler, produces sequence of 2, 3, 5, then completes.</caption>\n * const res = generate(1, x => x < 5, x => x * 2, x => x + 1, asap);\n *\n * @see {@link from}\n * @see {@link Observable}\n *\n * @param {S} initialState Initial state.\n * @param {function (state: S): boolean} condition Condition to terminate generation (upon returning false).\n * @param {function (state: S): S} iterate Iteration step function.\n * @param {function (state: S): T} resultSelector Selector function for results produced in the sequence. (deprecated)\n * @param {SchedulerLike} [scheduler] A {@link SchedulerLike} on which to run the generator loop. If not provided, defaults to emit immediately.\n * @returns {Observable<T>} The generated sequence.\n */\n  export function generate<T, S>(initialState: S,\n                                 condition: ConditionFunc<S>,\n                                 iterate: IterateFunc<S>,\n                                 resultSelector: ResultFunc<S, T>,\n                                 scheduler?: SchedulerLike): Observable<T>;\n\n/**\n * Generates an Observable by running a state-driven loop\n * that emits an element on each iteration.\n *\n * <span class=\"informal\">Use it instead of nexting values in a for loop.</span>\n *\n * <img src=\"./img/generate.png\" width=\"100%\">\n *\n * `generate` allows you to create stream of values generated with a loop very similar to\n * traditional for loop. First argument of `generate` is a beginning value. Second argument\n * is a function that accepts this value and tests if some condition still holds. If it does,\n * loop continues, if not, it stops. Third value is a function which takes previously defined\n * value and modifies it in some way on each iteration. Note how these three parameters\n * are direct equivalents of three expressions in regular for loop: first expression\n * initializes some state (for example numeric index), second tests if loop can make next\n * iteration (for example if index is lower than 10) and third states how defined value\n * will be modified on every step (index will be incremented by one).\n *\n * Return value of a `generate` operator is an Observable that on each loop iteration\n * emits a value. First, condition function is ran. If it returned true, Observable\n * emits currently stored value (initial value at the first iteration) and then updates\n * that value with iterate function. If at some point condition returned false, Observable\n * completes at that moment.\n *\n * Optionally you can pass fourth parameter to `generate` - a result selector function which allows you\n * to immediately map value that would normally be emitted by an Observable.\n *\n * If you find three anonymous functions in `generate` call hard to read, you can provide\n * single object to the operator instead. That object has properties: `initialState`,\n * `condition`, `iterate` and `resultSelector`, which should have respective values that you\n * would normally pass to `generate`. `resultSelector` is still optional, but that form\n * of calling `generate` allows you to omit `condition` as well. If you omit it, that means\n * condition always holds, so output Observable will never complete.\n *\n * Both forms of `generate` can optionally accept a scheduler. In case of multi-parameter call,\n * scheduler simply comes as a last argument (no matter if there is resultSelector\n * function or not). In case of single-parameter call, you can provide it as a\n * `scheduler` property on object passed to the operator. In both cases scheduler decides when\n * next iteration of the loop will happen and therefore when next value will be emitted\n * by the Observable. For example to ensure that each value is pushed to the observer\n * on separate task in event loop, you could use `async` scheduler. Note that\n * by default (when no scheduler is passed) values are simply emitted synchronously.\n *\n *\n * @example <caption>Use with condition and iterate functions.</caption>\n * const generated = generate(0, x => x < 3, x => x + 1);\n *\n * generated.subscribe(\n *   value => console.log(value),\n *   err => {},\n *   () => console.log('Yo!')\n * );\n *\n * // Logs:\n * // 0\n * // 1\n * // 2\n * // \"Yo!\"\n *\n *\n * @example <caption>Use with condition, iterate and resultSelector functions.</caption>\n * const generated = generate(0, x => x < 3, x => x + 1, x => x * 1000);\n *\n * generated.subscribe(\n *   value => console.log(value),\n *   err => {},\n *   () => console.log('Yo!')\n * );\n *\n * // Logs:\n * // 0\n * // 1000\n * // 2000\n * // \"Yo!\"\n *\n *\n * @example <caption>Use with options object.</caption>\n * const generated = generate({\n *   initialState: 0,\n *   condition(value) { return value < 3; },\n *   iterate(value) { return value + 1; },\n *   resultSelector(value) { return value * 1000; }\n * });\n *\n * generated.subscribe(\n *   value => console.log(value),\n *   err => {},\n *   () => console.log('Yo!')\n * );\n *\n * // Logs:\n * // 0\n * // 1000\n * // 2000\n * // \"Yo!\"\n *\n * @example <caption>Use options object without condition function.</caption>\n * const generated = generate({\n *   initialState: 0,\n *   iterate(value) { return value + 1; },\n *   resultSelector(value) { return value * 1000; }\n * });\n *\n * generated.subscribe(\n *   value => console.log(value),\n *   err => {},\n *   () => console.log('Yo!') // This will never run.\n * );\n *\n * // Logs:\n * // 0\n * // 1000\n * // 2000\n * // 3000\n * // ...and never stops.\n *\n *\n * @see {@link from}\n * @see {@link index/Observable.create}\n *\n * @param {S} initialState Initial state.\n * @param {function (state: S): boolean} condition Condition to terminate generation (upon returning false).\n * @param {function (state: S): S} iterate Iteration step function.\n * @param {function (state: S): T} [resultSelector] Selector function for results produced in the sequence.\n * @param {Scheduler} [scheduler] A {@link Scheduler} on which to run the generator loop. If not provided, defaults to emitting immediately.\n * @return {Observable<T>} The generated sequence.\n */\nexport function generate<S>(initialState: S,\n                            condition: ConditionFunc<S>,\n                            iterate: IterateFunc<S>,\n                            scheduler?: SchedulerLike): Observable<S>;\n\n/**\n * Generates an observable sequence by running a state-driven loop\n * producing the sequence's elements, using the specified scheduler\n * to send out observer messages.\n * The overload accepts options object that might contain initial state, iterate,\n * condition and scheduler.\n *\n * ![](generate.png)\n *\n * @example <caption>Produces sequence of 0, 1, 2, ... 9, then completes.</caption>\n * const res = generate({\n *   initialState: 0,\n *   condition: x => x < 10,\n *   iterate: x => x + 1,\n * });\n *\n * @see {@link from}\n * @see {@link Observable}\n *\n * @param {GenerateBaseOptions<S>} options Object that must contain initialState, iterate and might contain condition and scheduler.\n * @returns {Observable<S>} The generated sequence.\n */\nexport function generate<S>(options: GenerateBaseOptions<S>): Observable<S>;\n\n/**\n * Generates an observable sequence by running a state-driven loop\n * producing the sequence's elements, using the specified scheduler\n * to send out observer messages.\n * The overload accepts options object that might contain initial state, iterate,\n * condition, result selector and scheduler.\n *\n * ![](generate.png)\n *\n * @example <caption>Produces sequence of 0, 1, 2, ... 9, then completes.</caption>\n * const res = generate({\n *   initialState: 0,\n *   condition: x => x < 10,\n *   iterate: x => x + 1,\n *   resultSelector: x => x,\n * });\n *\n * @see {@link from}\n * @see {@link Observable}\n *\n * @param {GenerateOptions<T, S>} options Object that must contain initialState, iterate, resultSelector and might contain condition and scheduler.\n * @returns {Observable<T>} The generated sequence.\n */\nexport function generate<T, S>(options: GenerateOptions<T, S>): Observable<T>;\n\nexport function generate<T, S>(initialStateOrOptions: S | GenerateOptions<T, S>,\n                               condition?: ConditionFunc<S>,\n                               iterate?: IterateFunc<S>,\n                               resultSelectorOrObservable?: (ResultFunc<S, T>) | SchedulerLike,\n                               scheduler?: SchedulerLike): Observable<T> {\n\n  let resultSelector: ResultFunc<S, T>;\n  let initialState: S;\n\n  if (arguments.length == 1) {\n    const options = initialStateOrOptions as GenerateOptions<T, S>;\n    initialState = options.initialState;\n    condition = options.condition;\n    iterate = options.iterate;\n    resultSelector = options.resultSelector || identity as ResultFunc<S, T>;\n    scheduler = options.scheduler;\n  } else if (resultSelectorOrObservable === undefined || isScheduler(resultSelectorOrObservable)) {\n    initialState = initialStateOrOptions as S;\n    resultSelector = identity as ResultFunc<S, T>;\n    scheduler = resultSelectorOrObservable as SchedulerLike;\n  } else {\n    initialState = initialStateOrOptions as S;\n    resultSelector = resultSelectorOrObservable as ResultFunc<S, T>;\n  }\n\n  return new Observable<T>(subscriber => {\n    let state = initialState;\n    if (scheduler) {\n      return scheduler.schedule<SchedulerState<T, S>>(dispatch, 0, {\n        subscriber,\n        iterate,\n        condition,\n        resultSelector,\n        state\n      });\n    }\n\n    do {\n      if (condition) {\n        let conditionResult: boolean;\n        try {\n          conditionResult = condition(state);\n        } catch (err) {\n          subscriber.error(err);\n          return undefined;\n        }\n        if (!conditionResult) {\n          subscriber.complete();\n          break;\n        }\n      }\n      let value: T;\n      try {\n        value = resultSelector(state);\n      } catch (err) {\n        subscriber.error(err);\n        return undefined;\n      }\n      subscriber.next(value);\n      if (subscriber.closed) {\n        break;\n      }\n      try {\n        state = iterate(state);\n      } catch (err) {\n        subscriber.error(err);\n        return undefined;\n      }\n    } while (true);\n\n    return undefined;\n  });\n}\n\nfunction dispatch<T, S>(this: SchedulerAction<SchedulerState<T, S>>, state: SchedulerState<T, S>) {\n  const { subscriber, condition } = state;\n  if (subscriber.closed) {\n    return undefined;\n  }\n  if (state.needIterate) {\n    try {\n      state.state = state.iterate(state.state);\n    } catch (err) {\n      subscriber.error(err);\n      return undefined;\n    }\n  } else {\n    state.needIterate = true;\n  }\n  if (condition) {\n    let conditionResult: boolean;\n    try {\n      conditionResult = condition(state.state);\n    } catch (err) {\n      subscriber.error(err);\n      return undefined;\n    }\n    if (!conditionResult) {\n      subscriber.complete();\n      return undefined;\n    }\n    if (subscriber.closed) {\n      return undefined;\n    }\n  }\n  let value: T;\n  try {\n    value = state.resultSelector(state.state);\n  } catch (err) {\n    subscriber.error(err);\n    return undefined;\n  }\n  if (subscriber.closed) {\n    return undefined;\n  }\n  subscriber.next(value);\n  if (subscriber.closed) {\n    return undefined;\n  }\n  return this.schedule(state);\n}\n","import { Observable } from '../Observable';\nimport { defer } from './defer';\nimport { EMPTY } from './empty';\nimport { SubscribableOrPromise } from '../types';\n\n/**\n * Decides at subscription time which Observable will actually be subscribed.\n *\n * <span class=\"informal\">`If` statement for Observables.</span>\n *\n * `iif` accepts a condition function and two Observables. When\n * an Observable returned by the operator is subscribed, condition function will be called.\n * Based on what boolean it returns at that moment, consumer will subscribe either to\n * the first Observable (if condition was true) or to the second (if condition was false). Condition\n * function may also not return anything - in that case condition will be evaluated as false and\n * second Observable will be subscribed.\n *\n * Note that Observables for both cases (true and false) are optional. If condition points to an Observable that\n * was left undefined, resulting stream will simply complete immediately. That allows you to, rather\n * than controlling which Observable will be subscribed, decide at runtime if consumer should have access\n * to given Observable or not.\n *\n * If you have more complex logic that requires decision between more than two Observables, {@link defer}\n * will probably be a better choice. Actually `iif` can be easily implemented with {@link defer}\n * and exists only for convenience and readability reasons.\n *\n *\n * ## Examples\n * ### Change at runtime which Observable will be subscribed\n * ```ts\n * import { iif, of } from 'rxjs';\n *\n * let subscribeToFirst;\n * const firstOrSecond = iif(\n *   () => subscribeToFirst,\n *   of('first'),\n *   of('second'),\n * );\n *\n * subscribeToFirst = true;\n * firstOrSecond.subscribe(value => console.log(value));\n *\n * // Logs:\n * // \"first\"\n *\n * subscribeToFirst = false;\n * firstOrSecond.subscribe(value => console.log(value));\n *\n * // Logs:\n * // \"second\"\n *\n * ```\n *\n * ### Control an access to an Observable\n * ```ts\n * let accessGranted;\n * const observableIfYouHaveAccess = iif(\n *   () => accessGranted,\n *   of('It seems you have an access...'), // Note that only one Observable is passed to the operator.\n * );\n *\n * accessGranted = true;\n * observableIfYouHaveAccess.subscribe(\n *   value => console.log(value),\n *   err => {},\n *   () => console.log('The end'),\n * );\n *\n * // Logs:\n * // \"It seems you have an access...\"\n * // \"The end\"\n *\n * accessGranted = false;\n * observableIfYouHaveAccess.subscribe(\n *   value => console.log(value),\n *   err => {},\n *   () => console.log('The end'),\n * );\n *\n * // Logs:\n * // \"The end\"\n * ```\n *\n * @see {@link defer}\n *\n * @param {function(): boolean} condition Condition which Observable should be chosen.\n * @param {Observable} [trueObservable] An Observable that will be subscribed if condition is true.\n * @param {Observable} [falseObservable] An Observable that will be subscribed if condition is false.\n * @return {Observable} Either first or second Observable, depending on condition.\n * @static true\n * @name iif\n * @owner Observable\n*/\nexport function iif<T = never, F = never>(\n  condition: () => boolean,\n  trueResult: SubscribableOrPromise<T> = EMPTY,\n  falseResult: SubscribableOrPromise<F> = EMPTY\n): Observable<T|F> {\n  return defer(() => condition() ? trueResult : falseResult);\n}\n","import { Observable } from '../Observable';\nimport { async } from '../scheduler/async';\nimport { SchedulerAction, SchedulerLike } from '../types';\nimport { isNumeric } from '../util/isNumeric';\nimport { Subscriber } from '../Subscriber';\n\n/**\n * Creates an Observable that emits sequential numbers every specified\n * interval of time, on a specified {@link SchedulerLike}.\n *\n * <span class=\"informal\">Emits incremental numbers periodically in time.\n * </span>\n *\n * ![](interval.png)\n *\n * `interval` returns an Observable that emits an infinite sequence of\n * ascending integers, with a constant interval of time of your choosing\n * between those emissions. The first emission is not sent immediately, but\n * only after the first period has passed. By default, this operator uses the\n * `async` {@link SchedulerLike} to provide a notion of time, but you may pass any\n * {@link SchedulerLike} to it.\n *\n * ## Example\n * Emits ascending numbers, one every second (1000ms) up to the number 3\n * ```ts\n * import { interval } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const numbers = interval(1000);\n *\n * const takeFourNumbers = numbers.pipe(take(4));\n *\n * takeFourNumbers.subscribe(x => console.log('Next: ', x));\n *\n * // Logs:\n * // Next: 0\n * // Next: 1\n * // Next: 2\n * // Next: 3\n * ```\n *\n * @see {@link timer}\n * @see {@link delay}\n *\n * @param {number} [period=0] The interval size in milliseconds (by default)\n * or the time unit determined by the scheduler's clock.\n * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for scheduling\n * the emission of values, and providing a notion of \"time\".\n * @return {Observable} An Observable that emits a sequential number each time\n * interval.\n * @static true\n * @name interval\n * @owner Observable\n */\nexport function interval(period = 0,\n                         scheduler: SchedulerLike = async): Observable<number> {\n  if (!isNumeric(period) || period < 0) {\n    period = 0;\n  }\n\n  if (!scheduler || typeof scheduler.schedule !== 'function') {\n    scheduler = async;\n  }\n\n  return new Observable<number>(subscriber => {\n    subscriber.add(\n      scheduler.schedule(dispatch, period, { subscriber, counter: 0, period })\n    );\n    return subscriber;\n  });\n}\n\nfunction dispatch(this: SchedulerAction<IntervalState>, state: IntervalState) {\n  const { subscriber, counter, period } = state;\n  subscriber.next(counter);\n  this.schedule({ subscriber, counter: counter + 1, period }, period);\n}\n\ninterface IntervalState {\n  subscriber: Subscriber<number>;\n  counter: number;\n  period: number;\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput } from '../types';\nimport { from } from './from';\nimport { isArray } from '../util/isArray';\nimport { EMPTY } from './empty';\n\n/* tslint:disable:max-line-length */\nexport function onErrorResumeNext<R>(v: ObservableInput<R>): Observable<R>;\nexport function onErrorResumeNext<T2, T3, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>): Observable<R>;\nexport function onErrorResumeNext<T2, T3, T4, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>): Observable<R>;\nexport function onErrorResumeNext<T2, T3, T4, T5, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>): Observable<R>;\nexport function onErrorResumeNext<T2, T3, T4, T5, T6, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>): Observable<R>;\n\nexport function onErrorResumeNext<R>(...observables: Array<ObservableInput<any> | ((...values: Array<any>) => R)>): Observable<R>;\nexport function onErrorResumeNext<R>(array: ObservableInput<any>[]): Observable<R>;\n/* tslint:enable:max-line-length */\n\n/**\n * When any of the provided Observable emits an complete or error notification, it immediately subscribes to the next one\n * that was passed.\n *\n * <span class=\"informal\">Execute series of Observables no matter what, even if it means swallowing errors.</span>\n *\n * ![](onErrorResumeNext.png)\n *\n * `onErrorResumeNext` Will subscribe to each observable source it is provided, in order.\n * If the source it's subscribed to emits an error or completes, it will move to the next source\n * without error.\n *\n * If `onErrorResumeNext` is provided no arguments, or a single, empty array, it will return {@link index/EMPTY}.\n *\n * `onErrorResumeNext` is basically {@link concat}, only it will continue, even if one of its\n * sources emits an error.\n *\n * Note that there is no way to handle any errors thrown by sources via the result of\n * `onErrorResumeNext`. If you want to handle errors thrown in any given source, you can\n * always use the {@link catchError} operator on them before passing them into `onErrorResumeNext`.\n *\n * ## Example\n * Subscribe to the next Observable after map fails</caption>\n * ```ts\n * import { onErrorResumeNext, of } from 'rxjs';\n * import { map } from 'rxjs/operators';\n *\n * onErrorResumeNext(\n *  of(1, 2, 3, 0).pipe(\n *    map(x => {\n *      if (x === 0) throw Error();\n *      return 10 / x;\n *    })\n *  ),\n *  of(1, 2, 3),\n * )\n * .subscribe(\n *   val => console.log(val),\n *   err => console.log(err),          // Will never be called.\n *   () => console.log('done'),\n * );\n *\n * // Logs:\n * // 10\n * // 5\n * // 3.3333333333333335\n * // 1\n * // 2\n * // 3\n * // \"done\"\n * ```\n *\n * @see {@link concat}\n * @see {@link catchError}\n *\n * @param {...ObservableInput} sources Observables (or anything that *is* observable) passed either directly or as an array.\n * @return {Observable} An Observable that concatenates all sources, one after the other,\n * ignoring all errors, such that any error causes it to move on to the next source.\n */\nexport function onErrorResumeNext<T, R>(...sources: Array<ObservableInput<any> |\n                                                              Array<ObservableInput<any>> |\n                                                              ((...values: Array<any>) => R)>): Observable<R> {\n\n  if (sources.length === 0) {\n    return EMPTY;\n  }\n\n  const [ first, ...remainder ] = sources;\n\n  if (sources.length === 1 && isArray(first)) {\n    return onErrorResumeNext(...first);\n  }\n\n  return new Observable(subscriber => {\n    const subNext = () => subscriber.add(\n      onErrorResumeNext(...remainder).subscribe(subscriber)\n    );\n\n    return from(first).subscribe({\n      next(value) { subscriber.next(value); },\n      error: subNext,\n      complete: subNext,\n    });\n  });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerAction, SchedulerLike } from '../types';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\n\n/**\n * Convert an object into an Observable of `[key, value]` pairs.\n *\n * <span class=\"informal\">Turn entries of an object into a stream.</span>\n *\n * <img src=\"./img/pairs.png\" width=\"100%\">\n *\n * `pairs` takes an arbitrary object and returns an Observable that emits arrays. Each\n * emitted array has exactly two elements - the first is a key from the object\n * and the second is a value corresponding to that key. Keys are extracted from\n * an object via `Object.keys` function, which means that they will be only\n * enumerable keys that are present on an object directly - not ones inherited\n * via prototype chain.\n *\n * By default these arrays are emitted synchronously. To change that you can\n * pass a {@link SchedulerLike} as a second argument to `pairs`.\n *\n * @example <caption>Converts a javascript object to an Observable</caption>\n * ```ts\n * import { pairs } from 'rxjs';\n *\n * const obj = {\n *   foo: 42,\n *   bar: 56,\n *   baz: 78\n * };\n *\n * pairs(obj)\n * .subscribe(\n *   value => console.log(value),\n *   err => {},\n *   () => console.log('the end!')\n * );\n *\n * // Logs:\n * // [\"foo\", 42],\n * // [\"bar\", 56],\n * // [\"baz\", 78],\n * // \"the end!\"\n * ```\n *\n * @param {Object} obj The object to inspect and turn into an\n * Observable sequence.\n * @param {Scheduler} [scheduler] An optional IScheduler to schedule\n * when resulting Observable will emit values.\n * @returns {(Observable<Array<string|T>>)} An observable sequence of\n * [key, value] pairs from the object.\n */\nexport function pairs<T>(obj: Object, scheduler?: SchedulerLike): Observable<[string, T]> {\n  if (!scheduler) {\n    return new Observable<[string, T]>(subscriber => {\n      const keys = Object.keys(obj);\n      for (let i = 0; i < keys.length && !subscriber.closed; i++) {\n        const key = keys[i];\n        if (obj.hasOwnProperty(key)) {\n          subscriber.next([key, obj[key]]);\n        }\n      }\n      subscriber.complete();\n    });\n  } else {\n    return new Observable<[string, T]>(subscriber => {\n      const keys = Object.keys(obj);\n      const subscription = new Subscription();\n      subscription.add(\n        scheduler.schedule<{ keys: string[], index: number, subscriber: Subscriber<[string, T]>, subscription: Subscription, obj: Object }>\n          (dispatch, 0, { keys, index: 0, subscriber, subscription, obj }));\n      return subscription;\n    });\n  }\n}\n\n/** @internal */\nexport function dispatch<T>(this: SchedulerAction<any>,\n                            state: { keys: string[], index: number, subscriber: Subscriber<[string, T]>, subscription: Subscription, obj: Object }) {\n  const { keys, index, subscriber, subscription, obj } = state;\n  if (!subscriber.closed) {\n    if (index < keys.length) {\n      const key = keys[index];\n      subscriber.next([key, obj[key]]);\n      subscription.add(this.schedule({ keys, index: index + 1, subscriber, subscription, obj }));\n    } else {\n      subscriber.complete();\n    }\n  }\n}\n","import { not } from '../util/not';\nimport { subscribeTo } from '../util/subscribeTo';\nimport { filter } from '../operators/filter';\nimport { ObservableInput } from '../types';\nimport { Observable } from '../Observable';\n\n/**\n * Splits the source Observable into two, one with values that satisfy a\n * predicate, and another with values that don't satisfy the predicate.\n *\n * <span class=\"informal\">It's like {@link filter}, but returns two Observables:\n * one like the output of {@link filter}, and the other with values that did not\n * pass the condition.</span>\n *\n * ![](partition.png)\n *\n * `partition` outputs an array with two Observables that partition the values\n * from the source Observable through the given `predicate` function. The first\n * Observable in that array emits source values for which the predicate argument\n * returns true. The second Observable emits source values for which the\n * predicate returns false. The first behaves like {@link filter} and the second\n * behaves like {@link filter} with the predicate negated.\n *\n * ## Example\n * Partition a set of numbers into odds and evens observables\n * ```ts\n * import { of, partition } from 'rxjs';\n *\n * const observableValues = of(1, 2, 3, 4, 5, 6);\n * const [evens$, odds$] = partition(observableValues, (value, index) => value % 2 === 0);\n *\n * odds$.subscribe(x => console.log('odds', x));\n * evens$.subscribe(x => console.log('evens', x));\n *\n * // Logs:\n * // odds 1\n * // odds 3\n * // odds 5\n * // evens 2\n * // evens 4\n * // evens 6\n * ```\n *\n * @see {@link filter}\n *\n * @param {function(value: T, index: number): boolean} predicate A function that\n * evaluates each value emitted by the source Observable. If it returns `true`,\n * the value is emitted on the first Observable in the returned array, if\n * `false` the value is emitted on the second Observable in the array. The\n * `index` parameter is the number `i` for the i-th source emission that has\n * happened since the subscription, starting from the number `0`.\n * @param {any} [thisArg] An optional argument to determine the value of `this`\n * in the `predicate` function.\n * @return {[Observable<T>, Observable<T>]} An array with two Observables: one\n * with values that passed the predicate, and another with values that did not\n * pass the predicate.\n */\nexport function partition<T>(\n  source: ObservableInput<T>,\n  predicate: (value: T, index: number) => boolean,\n  thisArg?: any\n): [Observable<T>, Observable<T>] {\n  return [\n    filter(predicate, thisArg)(new Observable<T>(subscribeTo(source))),\n    filter(not(predicate, thisArg) as any)(new Observable<T>(subscribeTo(source)))\n  ] as [Observable<T>, Observable<T>];\n}\n","import { SchedulerAction, SchedulerLike } from '../types';\nimport { Observable } from '../Observable';\n\n/**\n * Creates an Observable that emits a sequence of numbers within a specified\n * range.\n *\n * <span class=\"informal\">Emits a sequence of numbers in a range.</span>\n *\n * ![](range.png)\n *\n * `range` operator emits a range of sequential integers, in order, where you\n * select the `start` of the range and its `length`. By default, uses no\n * {@link SchedulerLike} and just delivers the notifications synchronously, but may use\n * an optional {@link SchedulerLike} to regulate those deliveries.\n *\n * ## Example\n * Emits the numbers 1 to 10</caption>\n * ```ts\n * import { range } from 'rxjs';\n *\n * const numbers = range(1, 10);\n * numbers.subscribe(x => console.log(x));\n * ```\n * @see {@link timer}\n * @see {@link index/interval}\n *\n * @param {number} [start=0] The value of the first integer in the sequence.\n * @param {number} count The number of sequential integers to generate.\n * @param {SchedulerLike} [scheduler] A {@link SchedulerLike} to use for scheduling\n * the emissions of the notifications.\n * @return {Observable} An Observable of numbers that emits a finite range of\n * sequential integers.\n * @static true\n * @name range\n * @owner Observable\n */\nexport function range(start: number = 0,\n                      count?: number,\n                      scheduler?: SchedulerLike): Observable<number> {\n  return new Observable<number>(subscriber => {\n    if (count === undefined) {\n      count = start;\n      start = 0;\n    }\n\n    let index = 0;\n    let current = start;\n\n    if (scheduler) {\n      return scheduler.schedule(dispatch, 0, {\n        index, count, start, subscriber\n      });\n    } else {\n      do {\n        if (index++ >= count) {\n          subscriber.complete();\n          break;\n        }\n        subscriber.next(current++);\n        if (subscriber.closed) {\n          break;\n        }\n      } while (true);\n    }\n\n    return undefined;\n  });\n}\n\n/** @internal */\nexport function dispatch(this: SchedulerAction<any>, state: any) {\n  const { start, index, count, subscriber } = state;\n\n  if (index >= count) {\n    subscriber.complete();\n    return;\n  }\n\n  subscriber.next(start);\n\n  if (subscriber.closed) {\n    return;\n  }\n\n  state.index = index + 1;\n  state.start = start + 1;\n\n  this.schedule(state);\n}\n","import { Observable } from '../Observable';\nimport { Unsubscribable, ObservableInput } from '../types';\nimport { from } from './from'; // from from from! LAWL\nimport { EMPTY } from './empty';\n\n/**\n * Creates an Observable that uses a resource which will be disposed at the same time as the Observable.\n *\n * <span class=\"informal\">Use it when you catch yourself cleaning up after an Observable.</span>\n *\n * `using` is a factory operator, which accepts two functions. First function returns a disposable resource.\n * It can be an arbitrary object that implements `unsubscribe` method. Second function will be injected with\n * that object and should return an Observable. That Observable can use resource object during its execution.\n * Both functions passed to `using` will be called every time someone subscribes - neither an Observable nor\n * resource object will be shared in any way between subscriptions.\n *\n * When Observable returned by `using` is subscribed, Observable returned from the second function will be subscribed\n * as well. All its notifications (nexted values, completion and error events) will be emitted unchanged by the output\n * Observable. If however someone unsubscribes from the Observable or source Observable completes or errors by itself,\n * the `unsubscribe` method on resource object will be called. This can be used to do any necessary clean up, which\n * otherwise would have to be handled by hand. Note that complete or error notifications are not emitted when someone\n * cancels subscription to an Observable via `unsubscribe`, so `using` can be used as a hook, allowing you to make\n * sure that all resources which need to exist during an Observable execution will be disposed at appropriate time.\n *\n * @see {@link defer}\n *\n * @param {function(): ISubscription} resourceFactory A function which creates any resource object\n * that implements `unsubscribe` method.\n * @param {function(resource: ISubscription): Observable<T>} observableFactory A function which\n * creates an Observable, that can use injected resource object.\n * @return {Observable<T>} An Observable that behaves the same as Observable returned by `observableFactory`, but\n * which - when completed, errored or unsubscribed - will also call `unsubscribe` on created resource object.\n */\nexport function using<T>(resourceFactory: () => Unsubscribable | void,\n                         observableFactory: (resource: Unsubscribable | void) => ObservableInput<T> | void): Observable<T> {\n  return new Observable<T>(subscriber => {\n    let resource: Unsubscribable | void;\n\n    try {\n      resource = resourceFactory();\n    } catch (err) {\n      subscriber.error(err);\n      return undefined;\n    }\n\n    let result: ObservableInput<T> | void;\n    try {\n      result = observableFactory(resource);\n    } catch (err) {\n      subscriber.error(err);\n      return undefined;\n    }\n\n    const source = result ? from(result) : EMPTY;\n    const subscription = source.subscribe(subscriber);\n    return () => {\n      subscription.unsubscribe();\n      if (resource) {\n        resource.unsubscribe();\n      }\n    };\n  });\n}\n","import lodashMemoize from 'lodash.memoize'; // tslint:disable-line:match-default-export-name\nimport shallowEqual from 'shallowequal';\n\nimport CacheKeyResolver from './cache-key-resolver';\nimport { Omit } from './types';\n\nexport interface MemoizeOptions {\n    maxSize?: number;\n    isEqual?(valueA: any, valueB: any): boolean;\n}\n\nexport default function memoize<T extends (...args: any[]) => any>(\n    fn: T,\n    options?: MemoizeOptions\n) {\n    const { maxSize, isEqual } = { maxSize: 0, isEqual: shallowEqual, ...options };\n    const cache = new Map();\n    const resolver = new CacheKeyResolver({\n        isEqual,\n        maxSize,\n        onExpire: key => cache.delete(key),\n    });\n    const memoized = lodashMemoize(fn, (...args) => resolver.getKey(...args));\n\n    memoized.cache = cache;\n\n    return memoized;\n}\n\nexport function memoizeOne<T extends (...args: any[]) => any>(\n    fn: T,\n    options?: Omit<MemoizeOptions, 'maxSize'>\n) {\n    return memoize(fn, { ...options, maxSize: 1 });\n}\n","import { noop } from 'lodash';\nimport shallowEqual from 'shallowequal';\n\nimport {\n    isRootCacheKeyMap,\n    isTerminalCacheKeyMap,\n    ChildCacheKeyMap,\n    IntermediateCacheKeyMap,\n    RootCacheKeyMap,\n    TerminalCacheKeyMap\n} from './cache-key-maps';\n\nexport interface CacheKeyResolverOptions {\n    maxSize?: number;\n    onExpire?(key: string): void;\n    isEqual?(valueA: any, valueB: any): boolean;\n}\n\ninterface ResolveResult {\n    index: number;\n    parentMap: RootCacheKeyMap | IntermediateCacheKeyMap;\n    map?: TerminalCacheKeyMap;\n}\n\nexport default class CacheKeyResolver {\n    private _lastId = 0;\n    private _map: RootCacheKeyMap = { maps: [] };\n    private _usedMaps: TerminalCacheKeyMap[] = [];\n    private _options: Required<CacheKeyResolverOptions>;\n\n    constructor(options?: CacheKeyResolverOptions) {\n        this._options = {\n            isEqual: shallowEqual,\n            maxSize: 0,\n            onExpire: noop,\n            ...options,\n        };\n    }\n\n    getKey(...args: any[]): string {\n        const result = this._resolveMap(...args);\n        const { index, parentMap } = result;\n        let { map } = result;\n\n        if (map && map.cacheKey) {\n            map.usedCount++;\n        } else {\n            map = this._generateMap(parentMap, args.slice(index));\n        }\n\n        // Keep track of the least used map so we can remove it if the size of\n        // the stack exceeds the maximum size.\n        this._removeLeastUsedMap(map);\n\n        return map.cacheKey;\n    }\n\n    getUsedCount(...args: any[]): number {\n        const { map } = this._resolveMap(...args);\n\n        return map ? map.usedCount : 0;\n    }\n\n    private _resolveMap(...args: any[]): ResolveResult {\n        let index = 0;\n        let parentMap = this._map;\n\n        // Traverse the tree to find the linked list of maps that match the\n        // arguments of the call. Each intermediate or terminal map contains a\n        // value that could be used to match with the arguments. The last map in\n        // the list (the terminal) should contain a cache key. If it can does\n        // not exist, we will return a falsy value so that the caller could\n        // handle and generate a new cache key.\n        while (parentMap.maps.length) {\n            let isMatched = false;\n\n            for (let mapIndex = 0; mapIndex < parentMap.maps.length; mapIndex++) {\n                const map = parentMap.maps[mapIndex];\n\n                if (!this._options.isEqual(map.value, args[index])) {\n                    continue;\n                }\n\n                // Move the most recently used map to the top of the stack for\n                // quicker access\n                parentMap.maps.unshift(...parentMap.maps.splice(mapIndex, 1));\n\n                if ((args.length === 0 || index === args.length - 1) && isTerminalCacheKeyMap(map)) {\n                    return { index, map, parentMap };\n                }\n\n                isMatched = true;\n                parentMap = map;\n                index++;\n\n                break;\n            }\n\n            if (!isMatched) {\n                break;\n            }\n        }\n\n        return { index, parentMap };\n    }\n\n    private _generateMap(parent: RootCacheKeyMap | IntermediateCacheKeyMap, args: any[]): TerminalCacheKeyMap {\n        let index = 0;\n        let parentMap = parent;\n        let map: IntermediateCacheKeyMap;\n\n        do {\n            map = {\n                maps: [],\n                parentMap,\n                usedCount: 1,\n                value: args[index],\n            };\n\n            // Continue to build the tree of maps so that it could be resolved\n            // next time when the function is called with the same set of\n            // arguments.\n            parentMap.maps.unshift(map);\n\n            parentMap = map;\n            index++;\n        } while (index < args.length);\n\n        const terminalMap = map as TerminalCacheKeyMap;\n\n        terminalMap.cacheKey = `${++this._lastId}`;\n\n        return terminalMap;\n    }\n\n    private _removeLeastUsedMap(recentlyUsedMap: TerminalCacheKeyMap): void {\n        if (!this._options.maxSize) {\n            return;\n        }\n\n        const index = this._usedMaps.indexOf(recentlyUsedMap);\n\n        this._usedMaps.splice(\n            index === -1 ? 0 : index,\n            index === -1 ? 0 : 1,\n            recentlyUsedMap\n        );\n\n        if (this._usedMaps.length <= this._options.maxSize) {\n            return;\n        }\n\n        const map = this._usedMaps.pop();\n\n        if (!map) {\n            return;\n        }\n\n        this._removeMap(map);\n        this._options.onExpire(map.cacheKey);\n    }\n\n    private _removeMap(map: ChildCacheKeyMap): void {\n        if (!map.parentMap) {\n            return;\n        }\n\n        map.parentMap.maps.splice(map.parentMap.maps.indexOf(map), 1);\n\n        if (isRootCacheKeyMap(map.parentMap)) {\n            return;\n        }\n\n        this._removeMap(map.parentMap);\n    }\n}\n","export interface RootCacheKeyMap {\n    maps: ChildCacheKeyMap[];\n}\n\nexport interface IntermediateCacheKeyMap {\n    maps: ChildCacheKeyMap[];\n    parentMap: RootCacheKeyMap | IntermediateCacheKeyMap;\n    usedCount: number;\n    value: any;\n}\n\nexport interface TerminalCacheKeyMap extends IntermediateCacheKeyMap {\n    cacheKey: string;\n}\n\nexport type ChildCacheKeyMap = IntermediateCacheKeyMap | TerminalCacheKeyMap;\n\nexport function isTerminalCacheKeyMap(map: ChildCacheKeyMap): map is TerminalCacheKeyMap {\n    return map.hasOwnProperty('cacheKey');\n}\n\nexport function isRootCacheKeyMap(map: RootCacheKeyMap | ChildCacheKeyMap): map is RootCacheKeyMap {\n    return map.hasOwnProperty('parentMap');\n}\n","\n/* Operator exports */\nexport { audit } from '../internal/operators/audit';\nexport { auditTime } from '../internal/operators/auditTime';\nexport { buffer } from '../internal/operators/buffer';\nexport { bufferCount } from '../internal/operators/bufferCount';\nexport { bufferTime } from '../internal/operators/bufferTime';\nexport { bufferToggle } from '../internal/operators/bufferToggle';\nexport { bufferWhen } from '../internal/operators/bufferWhen';\nexport { catchError } from '../internal/operators/catchError';\nexport { combineAll } from '../internal/operators/combineAll';\nexport { combineLatest } from '../internal/operators/combineLatest';\nexport { concat } from '../internal/operators/concat';\nexport { concatAll } from '../internal/operators/concatAll';\nexport { concatMap } from '../internal/operators/concatMap';\nexport { concatMapTo } from '../internal/operators/concatMapTo';\nexport { count } from '../internal/operators/count';\nexport { debounce } from '../internal/operators/debounce';\nexport { debounceTime } from '../internal/operators/debounceTime';\nexport { defaultIfEmpty } from '../internal/operators/defaultIfEmpty';\nexport { delay } from '../internal/operators/delay';\nexport { delayWhen } from '../internal/operators/delayWhen';\nexport { dematerialize } from '../internal/operators/dematerialize';\nexport { distinct } from '../internal/operators/distinct';\nexport { distinctUntilChanged } from '../internal/operators/distinctUntilChanged';\nexport { distinctUntilKeyChanged } from '../internal/operators/distinctUntilKeyChanged';\nexport { elementAt } from '../internal/operators/elementAt';\nexport { endWith } from '../internal/operators/endWith';\nexport { every } from '../internal/operators/every';\nexport { exhaust } from '../internal/operators/exhaust';\nexport { exhaustMap } from '../internal/operators/exhaustMap';\nexport { expand } from '../internal/operators/expand';\nexport { filter } from '../internal/operators/filter';\nexport { finalize } from '../internal/operators/finalize';\nexport { find } from '../internal/operators/find';\nexport { findIndex } from '../internal/operators/findIndex';\nexport { first } from '../internal/operators/first';\nexport { groupBy } from '../internal/operators/groupBy';\nexport { ignoreElements } from '../internal/operators/ignoreElements';\nexport { isEmpty } from '../internal/operators/isEmpty';\nexport { last } from '../internal/operators/last';\nexport { map } from '../internal/operators/map';\nexport { mapTo } from '../internal/operators/mapTo';\nexport { materialize } from '../internal/operators/materialize';\nexport { max } from '../internal/operators/max';\nexport { merge } from '../internal/operators/merge';\nexport { mergeAll } from '../internal/operators/mergeAll';\nexport { mergeMap, flatMap } from '../internal/operators/mergeMap';\nexport { mergeMapTo } from '../internal/operators/mergeMapTo';\nexport { mergeScan } from '../internal/operators/mergeScan';\nexport { min } from '../internal/operators/min';\nexport { multicast } from '../internal/operators/multicast';\nexport { observeOn } from '../internal/operators/observeOn';\nexport { onErrorResumeNext } from '../internal/operators/onErrorResumeNext';\nexport { pairwise } from '../internal/operators/pairwise';\nexport { partition } from '../internal/operators/partition';\nexport { pluck } from '../internal/operators/pluck';\nexport { publish } from '../internal/operators/publish';\nexport { publishBehavior } from '../internal/operators/publishBehavior';\nexport { publishLast } from '../internal/operators/publishLast';\nexport { publishReplay } from '../internal/operators/publishReplay';\nexport { race } from '../internal/operators/race';\nexport { reduce } from '../internal/operators/reduce';\nexport { repeat } from '../internal/operators/repeat';\nexport { repeatWhen } from '../internal/operators/repeatWhen';\nexport { retry } from '../internal/operators/retry';\nexport { retryWhen } from '../internal/operators/retryWhen';\nexport { refCount } from '../internal/operators/refCount';\nexport { sample } from '../internal/operators/sample';\nexport { sampleTime } from '../internal/operators/sampleTime';\nexport { scan } from '../internal/operators/scan';\nexport { sequenceEqual } from '../internal/operators/sequenceEqual';\nexport { share } from '../internal/operators/share';\nexport { shareReplay } from '../internal/operators/shareReplay';\nexport { single } from '../internal/operators/single';\nexport { skip } from '../internal/operators/skip';\nexport { skipLast } from '../internal/operators/skipLast';\nexport { skipUntil } from '../internal/operators/skipUntil';\nexport { skipWhile } from '../internal/operators/skipWhile';\nexport { startWith } from '../internal/operators/startWith';\nexport { subscribeOn } from '../internal/operators/subscribeOn';\nexport { switchAll } from '../internal/operators/switchAll';\nexport { switchMap } from '../internal/operators/switchMap';\nexport { switchMapTo } from '../internal/operators/switchMapTo';\nexport { take } from '../internal/operators/take';\nexport { takeLast } from '../internal/operators/takeLast';\nexport { takeUntil } from '../internal/operators/takeUntil';\nexport { takeWhile } from '../internal/operators/takeWhile';\nexport { tap } from '../internal/operators/tap';\nexport { throttle } from '../internal/operators/throttle';\nexport { throttleTime } from '../internal/operators/throttleTime';\nexport { throwIfEmpty } from '../internal/operators/throwIfEmpty';\nexport { timeInterval } from '../internal/operators/timeInterval';\nexport { timeout } from '../internal/operators/timeout';\nexport { timeoutWith } from '../internal/operators/timeoutWith';\nexport { timestamp } from '../internal/operators/timestamp';\nexport { toArray } from '../internal/operators/toArray';\nexport { window } from '../internal/operators/window';\nexport { windowCount } from '../internal/operators/windowCount';\nexport { windowTime } from '../internal/operators/windowTime';\nexport { windowToggle } from '../internal/operators/windowToggle';\nexport { windowWhen } from '../internal/operators/windowWhen';\nexport { withLatestFrom } from '../internal/operators/withLatestFrom';\nexport { zip } from '../internal/operators/zip';\nexport { zipAll } from '../internal/operators/zipAll';\n","import { async } from '../scheduler/async';\nimport { audit } from './audit';\nimport { timer } from '../observable/timer';\nimport { MonoTypeOperatorFunction, SchedulerLike } from '../types';\n\n/**\n * Ignores source values for `duration` milliseconds, then emits the most recent\n * value from the source Observable, then repeats this process.\n *\n * <span class=\"informal\">When it sees a source value, it ignores that plus\n * the next ones for `duration` milliseconds, and then it emits the most recent\n * value from the source.</span>\n *\n * ![](auditTime.png)\n *\n * `auditTime` is similar to `throttleTime`, but emits the last value from the\n * silenced time window, instead of the first value. `auditTime` emits the most\n * recent value from the source Observable on the output Observable as soon as\n * its internal timer becomes disabled, and ignores source values while the\n * timer is enabled. Initially, the timer is disabled. As soon as the first\n * source value arrives, the timer is enabled. After `duration` milliseconds (or\n * the time unit determined internally by the optional `scheduler`) has passed,\n * the timer is disabled, then the most recent source value is emitted on the\n * output Observable, and this process repeats for the next source value.\n * Optionally takes a {@link SchedulerLike} for managing timers.\n *\n * ## Example\n *\n * Emit clicks at a rate of at most one click per second\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { auditTime } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(auditTime(1000));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link audit}\n * @see {@link debounceTime}\n * @see {@link delay}\n * @see {@link sampleTime}\n * @see {@link throttleTime}\n *\n * @param {number} duration Time to wait before emitting the most recent source\n * value, measured in milliseconds or the time unit determined internally\n * by the optional `scheduler`.\n * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for\n * managing the timers that handle the rate-limiting behavior.\n * @return {Observable<T>} An Observable that performs rate-limiting of\n * emissions from the source Observable.\n * @method auditTime\n * @owner Observable\n */\nexport function auditTime<T>(duration: number, scheduler: SchedulerLike = async): MonoTypeOperatorFunction<T> {\n  return audit(() => timer(duration, scheduler));\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OperatorFunction } from '../types';\nimport { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';\n\n/**\n * Buffers the source Observable values until `closingNotifier` emits.\n *\n * <span class=\"informal\">Collects values from the past as an array, and emits\n * that array only when another Observable emits.</span>\n *\n * ![](buffer.png)\n *\n * Buffers the incoming Observable values until the given `closingNotifier`\n * Observable emits a value, at which point it emits the buffer on the output\n * Observable and starts a new buffer internally, awaiting the next time\n * `closingNotifier` emits.\n *\n * ## Example\n *\n * On every click, emit array of most recent interval events\n *\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { buffer } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const intervalEvents = interval(1000);\n * const buffered = intervalEvents.pipe(buffer(clicks));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link bufferCount}\n * @see {@link bufferTime}\n * @see {@link bufferToggle}\n * @see {@link bufferWhen}\n * @see {@link window}\n *\n * @param {Observable<any>} closingNotifier An Observable that signals the\n * buffer to be emitted on the output Observable.\n * @return {Observable<T[]>} An Observable of buffers, which are arrays of\n * values.\n * @method buffer\n * @owner Observable\n */\nexport function buffer<T>(closingNotifier: Observable<any>): OperatorFunction<T, T[]> {\n  return function bufferOperatorFunction(source: Observable<T>) {\n    return source.lift(new BufferOperator<T>(closingNotifier));\n  };\n}\n\nclass BufferOperator<T> implements Operator<T, T[]> {\n\n  constructor(private closingNotifier: Observable<any>) {\n  }\n\n  call(subscriber: Subscriber<T[]>, source: any): any {\n    return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass BufferSubscriber<T> extends SimpleOuterSubscriber<T, any> {\n  private buffer: T[] = [];\n\n  constructor(destination: Subscriber<T[]>, closingNotifier: Observable<any>) {\n    super(destination);\n    this.add(innerSubscribe(closingNotifier, new SimpleInnerSubscriber(this)));\n  }\n\n  protected _next(value: T) {\n    this.buffer.push(value);\n  }\n\n  notifyNext(): void {\n    const buffer = this.buffer;\n    this.buffer = [];\n    this.destination.next!(buffer);\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Buffers the source Observable values until the size hits the maximum\n * `bufferSize` given.\n *\n * <span class=\"informal\">Collects values from the past as an array, and emits\n * that array only when its size reaches `bufferSize`.</span>\n *\n * ![](bufferCount.png)\n *\n * Buffers a number of values from the source Observable by `bufferSize` then\n * emits the buffer and clears it, and starts a new buffer each\n * `startBufferEvery` values. If `startBufferEvery` is not provided or is\n * `null`, then new buffers are started immediately at the start of the source\n * and when each buffer closes and is emitted.\n *\n * ## Examples\n *\n * Emit the last two click events as an array\n *\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { bufferCount } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(bufferCount(2));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * On every click, emit the last two click events as an array\n *\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { bufferCount } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(bufferCount(2, 1));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link buffer}\n * @see {@link bufferTime}\n * @see {@link bufferToggle}\n * @see {@link bufferWhen}\n * @see {@link pairwise}\n * @see {@link windowCount}\n *\n * @param {number} bufferSize The maximum size of the buffer emitted.\n * @param {number} [startBufferEvery] Interval at which to start a new buffer.\n * For example if `startBufferEvery` is `2`, then a new buffer will be started\n * on every other value from the source. A new buffer is started at the\n * beginning of the source by default.\n * @return {Observable<T[]>} An Observable of arrays of buffered values.\n * @method bufferCount\n * @owner Observable\n */\nexport function bufferCount<T>(bufferSize: number, startBufferEvery: number = null): OperatorFunction<T, T[]> {\n  return function bufferCountOperatorFunction(source: Observable<T>) {\n    return source.lift(new BufferCountOperator<T>(bufferSize, startBufferEvery));\n  };\n}\n\nclass BufferCountOperator<T> implements Operator<T, T[]> {\n  private subscriberClass: any;\n\n  constructor(private bufferSize: number, private startBufferEvery: number) {\n    if (!startBufferEvery || bufferSize === startBufferEvery) {\n      this.subscriberClass = BufferCountSubscriber;\n    } else {\n      this.subscriberClass = BufferSkipCountSubscriber;\n    }\n  }\n\n  call(subscriber: Subscriber<T[]>, source: any): TeardownLogic {\n    return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass BufferCountSubscriber<T> extends Subscriber<T> {\n  private buffer: T[] = [];\n\n  constructor(destination: Subscriber<T[]>, private bufferSize: number) {\n    super(destination);\n  }\n\n  protected _next(value: T): void {\n    const buffer = this.buffer;\n\n    buffer.push(value);\n\n    if (buffer.length == this.bufferSize) {\n      this.destination.next(buffer);\n      this.buffer = [];\n    }\n  }\n\n  protected _complete(): void {\n    const buffer = this.buffer;\n    if (buffer.length > 0) {\n      this.destination.next(buffer);\n    }\n    super._complete();\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass BufferSkipCountSubscriber<T> extends Subscriber<T> {\n  private buffers: Array<T[]> = [];\n  private count: number = 0;\n\n  constructor(destination: Subscriber<T[]>, private bufferSize: number, private startBufferEvery: number) {\n    super(destination);\n  }\n\n  protected _next(value: T): void {\n    const { bufferSize, startBufferEvery, buffers, count } = this;\n\n    this.count++;\n    if (count % startBufferEvery === 0) {\n      buffers.push([]);\n    }\n\n    for (let i = buffers.length; i--; ) {\n      const buffer = buffers[i];\n      buffer.push(value);\n      if (buffer.length === bufferSize) {\n        buffers.splice(i, 1);\n        this.destination.next(buffer);\n      }\n    }\n  }\n\n  protected _complete(): void {\n    const { buffers, destination } = this;\n\n    while (buffers.length > 0) {\n      let buffer = buffers.shift();\n      if (buffer.length > 0) {\n        destination.next(buffer);\n      }\n    }\n    super._complete();\n  }\n\n}\n","import { Operator } from '../Operator';\nimport { async } from '../scheduler/async';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { isScheduler } from '../util/isScheduler';\nimport { OperatorFunction, SchedulerAction, SchedulerLike } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function bufferTime<T>(bufferTimeSpan: number, scheduler?: SchedulerLike): OperatorFunction<T, T[]>;\nexport function bufferTime<T>(bufferTimeSpan: number, bufferCreationInterval: number | null | undefined, scheduler?: SchedulerLike): OperatorFunction<T, T[]>;\nexport function bufferTime<T>(bufferTimeSpan: number, bufferCreationInterval: number | null | undefined, maxBufferSize: number, scheduler?: SchedulerLike): OperatorFunction<T, T[]>;\n/* tslint:enable:max-line-length */\n\n/**\n * Buffers the source Observable values for a specific time period.\n *\n * <span class=\"informal\">Collects values from the past as an array, and emits\n * those arrays periodically in time.</span>\n *\n * ![](bufferTime.png)\n *\n * Buffers values from the source for a specific time duration `bufferTimeSpan`.\n * Unless the optional argument `bufferCreationInterval` is given, it emits and\n * resets the buffer every `bufferTimeSpan` milliseconds. If\n * `bufferCreationInterval` is given, this operator opens the buffer every\n * `bufferCreationInterval` milliseconds and closes (emits and resets) the\n * buffer every `bufferTimeSpan` milliseconds. When the optional argument\n * `maxBufferSize` is specified, the buffer will be closed either after\n * `bufferTimeSpan` milliseconds or when it contains `maxBufferSize` elements.\n *\n * ## Examples\n *\n * Every second, emit an array of the recent click events\n *\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { bufferTime } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(bufferTime(1000));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * Every 5 seconds, emit the click events from the next 2 seconds\n *\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { bufferTime } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(bufferTime(2000, 5000));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link buffer}\n * @see {@link bufferCount}\n * @see {@link bufferToggle}\n * @see {@link bufferWhen}\n * @see {@link windowTime}\n *\n * @param {number} bufferTimeSpan The amount of time to fill each buffer array.\n * @param {number} [bufferCreationInterval] The interval at which to start new\n * buffers.\n * @param {number} [maxBufferSize] The maximum buffer size.\n * @param {SchedulerLike} [scheduler=async] The scheduler on which to schedule the\n * intervals that determine buffer boundaries.\n * @return {Observable<T[]>} An observable of arrays of buffered values.\n * @method bufferTime\n * @owner Observable\n */\nexport function bufferTime<T>(bufferTimeSpan: number): OperatorFunction<T, T[]> {\n  let length: number = arguments.length;\n\n  let scheduler: SchedulerLike = async;\n  if (isScheduler(arguments[arguments.length - 1])) {\n    scheduler = arguments[arguments.length - 1];\n    length--;\n  }\n\n  let bufferCreationInterval: number = null;\n  if (length >= 2) {\n    bufferCreationInterval = arguments[1];\n  }\n\n  let maxBufferSize: number = Number.POSITIVE_INFINITY;\n  if (length >= 3) {\n    maxBufferSize = arguments[2];\n  }\n\n  return function bufferTimeOperatorFunction(source: Observable<T>) {\n    return source.lift(new BufferTimeOperator<T>(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler));\n  };\n}\n\nclass BufferTimeOperator<T> implements Operator<T, T[]> {\n  constructor(private bufferTimeSpan: number,\n              private bufferCreationInterval: number,\n              private maxBufferSize: number,\n              private scheduler: SchedulerLike) {\n  }\n\n  call(subscriber: Subscriber<T[]>, source: any): any {\n    return source.subscribe(new BufferTimeSubscriber(\n      subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler\n    ));\n  }\n}\n\nclass Context<T> {\n  buffer: T[] = [];\n  closeAction: Subscription;\n}\n\ninterface DispatchCreateArg<T> {\n  bufferTimeSpan: number;\n  bufferCreationInterval: number;\n  subscriber: BufferTimeSubscriber<T>;\n  scheduler: SchedulerLike;\n}\n\ninterface DispatchCloseArg<T> {\n  subscriber: BufferTimeSubscriber<T>;\n  context: Context<T>;\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass BufferTimeSubscriber<T> extends Subscriber<T> {\n  private contexts: Array<Context<T>> = [];\n  private timespanOnly: boolean;\n\n  constructor(destination: Subscriber<T[]>,\n              private bufferTimeSpan: number,\n              private bufferCreationInterval: number,\n              private maxBufferSize: number,\n              private scheduler: SchedulerLike) {\n    super(destination);\n    const context = this.openContext();\n    this.timespanOnly = bufferCreationInterval == null || bufferCreationInterval < 0;\n    if (this.timespanOnly) {\n      const timeSpanOnlyState = { subscriber: this, context, bufferTimeSpan };\n      this.add(context.closeAction = scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));\n    } else {\n      const closeState = { subscriber: this, context };\n      const creationState: DispatchCreateArg<T> = { bufferTimeSpan, bufferCreationInterval, subscriber: this, scheduler };\n      this.add(context.closeAction = scheduler.schedule<DispatchCloseArg<T>>(dispatchBufferClose, bufferTimeSpan, closeState));\n      this.add(scheduler.schedule<DispatchCreateArg<T>>(dispatchBufferCreation, bufferCreationInterval, creationState));\n    }\n  }\n\n  protected _next(value: T) {\n    const contexts = this.contexts;\n    const len = contexts.length;\n    let filledBufferContext: Context<T>;\n    for (let i = 0; i < len; i++) {\n      const context = contexts[i];\n      const buffer = context.buffer;\n      buffer.push(value);\n      if (buffer.length == this.maxBufferSize) {\n        filledBufferContext = context;\n      }\n    }\n\n    if (filledBufferContext) {\n      this.onBufferFull(filledBufferContext);\n    }\n  }\n\n  protected _error(err: any) {\n    this.contexts.length = 0;\n    super._error(err);\n  }\n\n  protected _complete() {\n    const { contexts, destination } = this;\n    while (contexts.length > 0) {\n      const context = contexts.shift();\n      destination.next(context.buffer);\n    }\n    super._complete();\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _unsubscribe() {\n    this.contexts = null;\n  }\n\n  protected onBufferFull(context: Context<T>) {\n    this.closeContext(context);\n    const closeAction = context.closeAction;\n    closeAction.unsubscribe();\n    this.remove(closeAction);\n\n    if (!this.closed && this.timespanOnly) {\n      context = this.openContext();\n      const bufferTimeSpan = this.bufferTimeSpan;\n      const timeSpanOnlyState = { subscriber: this, context, bufferTimeSpan };\n      this.add(context.closeAction = this.scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));\n    }\n  }\n\n  openContext(): Context<T> {\n    const context: Context<T> = new Context<T>();\n    this.contexts.push(context);\n    return context;\n  }\n\n  closeContext(context: Context<T>) {\n    this.destination.next(context.buffer);\n    const contexts = this.contexts;\n\n    const spliceIndex = contexts ? contexts.indexOf(context) : -1;\n    if (spliceIndex >= 0) {\n      contexts.splice(contexts.indexOf(context), 1);\n    }\n  }\n}\n\nfunction dispatchBufferTimeSpanOnly(this: SchedulerAction<any>, state: any) {\n  const subscriber: BufferTimeSubscriber<any> = state.subscriber;\n\n  const prevContext = state.context;\n  if (prevContext) {\n    subscriber.closeContext(prevContext);\n  }\n\n  if (!subscriber.closed) {\n    state.context = subscriber.openContext();\n    state.context.closeAction = this.schedule(state, state.bufferTimeSpan);\n  }\n}\n\nfunction dispatchBufferCreation<T>(this: SchedulerAction<DispatchCreateArg<T>>, state: DispatchCreateArg<T>) {\n  const { bufferCreationInterval, bufferTimeSpan, subscriber, scheduler } = state;\n  const context = subscriber.openContext();\n  const action = <SchedulerAction<DispatchCreateArg<T>>>this;\n  if (!subscriber.closed) {\n    subscriber.add(context.closeAction = scheduler.schedule<DispatchCloseArg<T>>(dispatchBufferClose, bufferTimeSpan, { subscriber, context }));\n    action.schedule(state, bufferCreationInterval);\n  }\n}\n\nfunction dispatchBufferClose<T>(arg: DispatchCloseArg<T>) {\n  const { subscriber, context } = arg;\n  subscriber.closeContext(context);\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { OperatorFunction, SubscribableOrPromise } from '../types';\n\n/**\n * Buffers the source Observable values starting from an emission from\n * `openings` and ending when the output of `closingSelector` emits.\n *\n * <span class=\"informal\">Collects values from the past as an array. Starts\n * collecting only when `opening` emits, and calls the `closingSelector`\n * function to get an Observable that tells when to close the buffer.</span>\n *\n * ![](bufferToggle.png)\n *\n * Buffers values from the source by opening the buffer via signals from an\n * Observable provided to `openings`, and closing and sending the buffers when\n * a Subscribable or Promise returned by the `closingSelector` function emits.\n *\n * ## Example\n *\n * Every other second, emit the click events from the next 500ms\n *\n * ```ts\n * import { fromEvent, interval, EMPTY } from 'rxjs';\n * import { bufferToggle } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const openings = interval(1000);\n * const buffered = clicks.pipe(bufferToggle(openings, i =>\n *   i % 2 ? interval(500) : EMPTY\n * ));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link buffer}\n * @see {@link bufferCount}\n * @see {@link bufferTime}\n * @see {@link bufferWhen}\n * @see {@link windowToggle}\n *\n * @param {SubscribableOrPromise<O>} openings A Subscribable or Promise of notifications to start new\n * buffers.\n * @param {function(value: O): SubscribableOrPromise} closingSelector A function that takes\n * the value emitted by the `openings` observable and returns a Subscribable or Promise,\n * which, when it emits, signals that the associated buffer should be emitted\n * and cleared.\n * @return {Observable<T[]>} An observable of arrays of buffered values.\n * @method bufferToggle\n * @owner Observable\n */\nexport function bufferToggle<T, O>(\n  openings: SubscribableOrPromise<O>,\n  closingSelector: (value: O) => SubscribableOrPromise<any>\n): OperatorFunction<T, T[]> {\n  return function bufferToggleOperatorFunction(source: Observable<T>) {\n    return source.lift(new BufferToggleOperator<T, O>(openings, closingSelector));\n  };\n}\n\nclass BufferToggleOperator<T, O> implements Operator<T, T[]> {\n\n  constructor(private openings: SubscribableOrPromise<O>,\n              private closingSelector: (value: O) => SubscribableOrPromise<any>) {\n  }\n\n  call(subscriber: Subscriber<T[]>, source: any): any {\n    return source.subscribe(new BufferToggleSubscriber(subscriber, this.openings, this.closingSelector));\n  }\n}\n\ninterface BufferContext<T> {\n  buffer: T[];\n  subscription: Subscription;\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass BufferToggleSubscriber<T, O> extends OuterSubscriber<T, O> {\n  private contexts: Array<BufferContext<T>> = [];\n\n  constructor(destination: Subscriber<T[]>,\n              openings: SubscribableOrPromise<O>,\n              private closingSelector: (value: O) => SubscribableOrPromise<any> | void) {\n    super(destination);\n    this.add(subscribeToResult(this, openings));\n  }\n\n  protected _next(value: T): void {\n    const contexts = this.contexts;\n    const len = contexts.length;\n    for (let i = 0; i < len; i++) {\n      contexts[i].buffer.push(value);\n    }\n  }\n\n  protected _error(err: any): void {\n    const contexts = this.contexts;\n    while (contexts.length > 0) {\n      const context = contexts.shift()!;\n      context.subscription.unsubscribe();\n      context.buffer = null!;\n      context.subscription = null!;\n    }\n    this.contexts = null!;\n    super._error(err);\n  }\n\n  protected _complete(): void {\n    const contexts = this.contexts;\n    while (contexts.length > 0) {\n      const context = contexts.shift()!;\n      this.destination.next!(context.buffer);\n      context.subscription.unsubscribe();\n      context.buffer = null!;\n      context.subscription = null!;\n    }\n    this.contexts = null!;\n    super._complete();\n  }\n\n  notifyNext(outerValue: any, innerValue: O): void {\n    outerValue ? this.closeBuffer(outerValue) : this.openBuffer(innerValue);\n  }\n\n  notifyComplete(innerSub: InnerSubscriber<T, O>): void {\n    this.closeBuffer((<any> innerSub).context);\n  }\n\n  private openBuffer(value: O): void {\n    try {\n      const closingSelector = this.closingSelector;\n      const closingNotifier = closingSelector.call(this, value);\n      if (closingNotifier) {\n        this.trySubscribe(closingNotifier);\n      }\n    } catch (err) {\n      this._error(err);\n    }\n  }\n\n  private closeBuffer(context: BufferContext<T>): void {\n    const contexts = this.contexts;\n\n    if (contexts && context) {\n      const { buffer, subscription } = context;\n      this.destination.next!(buffer);\n      contexts.splice(contexts.indexOf(context), 1);\n      this.remove(subscription);\n      subscription.unsubscribe();\n    }\n  }\n\n  private trySubscribe(closingNotifier: any): void {\n    const contexts = this.contexts;\n\n    const buffer: Array<T> = [];\n    const subscription = new Subscription();\n    const context = { buffer, subscription };\n    contexts.push(context);\n\n    const innerSubscription = subscribeToResult(this, closingNotifier, context as any);\n\n    if (!innerSubscription || innerSubscription.closed) {\n      this.closeBuffer(context);\n    } else {\n      (innerSubscription as any).context = context;\n\n      this.add(innerSubscription);\n      subscription.add(innerSubscription);\n    }\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { OperatorFunction } from '../types';\nimport { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';\n\n/**\n * Buffers the source Observable values, using a factory function of closing\n * Observables to determine when to close, emit, and reset the buffer.\n *\n * <span class=\"informal\">Collects values from the past as an array. When it\n * starts collecting values, it calls a function that returns an Observable that\n * tells when to close the buffer and restart collecting.</span>\n *\n * ![](bufferWhen.png)\n *\n * Opens a buffer immediately, then closes the buffer when the observable\n * returned by calling `closingSelector` function emits a value. When it closes\n * the buffer, it immediately opens a new buffer and repeats the process.\n *\n * ## Example\n *\n * Emit an array of the last clicks every [1-5] random seconds\n *\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { bufferWhen } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(bufferWhen(() =>\n *   interval(1000 + Math.random() * 4000)\n * ));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n *\n * @see {@link buffer}\n * @see {@link bufferCount}\n * @see {@link bufferTime}\n * @see {@link bufferToggle}\n * @see {@link windowWhen}\n *\n * @param {function(): Observable} closingSelector A function that takes no\n * arguments and returns an Observable that signals buffer closure.\n * @return {Observable<T[]>} An observable of arrays of buffered values.\n * @method bufferWhen\n * @owner Observable\n */\nexport function bufferWhen<T>(closingSelector: () => Observable<any>): OperatorFunction<T, T[]> {\n  return function (source: Observable<T>) {\n    return source.lift(new BufferWhenOperator(closingSelector));\n  };\n}\n\nclass BufferWhenOperator<T> implements Operator<T, T[]> {\n\n  constructor(private closingSelector: () => Observable<any>) {\n  }\n\n  call(subscriber: Subscriber<T[]>, source: any): any {\n    return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass BufferWhenSubscriber<T> extends SimpleOuterSubscriber<T, any> {\n  private buffer?: T[];\n  private subscribing: boolean = false;\n  private closingSubscription?: Subscription;\n\n  constructor(destination: Subscriber<T[]>, private closingSelector: () => Observable<any>) {\n    super(destination);\n    this.openBuffer();\n  }\n\n  protected _next(value: T) {\n    this.buffer!.push(value);\n  }\n\n  protected _complete() {\n    const buffer = this.buffer;\n    if (buffer) {\n      this.destination.next!(buffer);\n    }\n    super._complete();\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _unsubscribe() {\n    this.buffer = undefined;\n    this.subscribing = false;\n  }\n\n  notifyNext(): void {\n    this.openBuffer();\n  }\n\n  notifyComplete(): void {\n    if (this.subscribing) {\n      this.complete();\n    } else {\n      this.openBuffer();\n    }\n  }\n\n  openBuffer() {\n    let { closingSubscription } = this;\n\n    if (closingSubscription) {\n      this.remove(closingSubscription);\n      closingSubscription.unsubscribe();\n    }\n\n    const buffer = this.buffer;\n    if (this.buffer) {\n      this.destination.next!(buffer);\n    }\n\n    this.buffer = [];\n\n    let closingNotifier;\n    try {\n      const { closingSelector } = this;\n      closingNotifier = closingSelector();\n    } catch (err) {\n      return this.error(err);\n    }\n    closingSubscription = new Subscription();\n    this.closingSubscription = closingSubscription;\n    this.add(closingSubscription);\n    this.subscribing = true;\n    closingSubscription.add(innerSubscribe(closingNotifier, new SimpleInnerSubscriber(this)));\n    this.subscribing = false;\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\n\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { SimpleOuterSubscriber, SimpleInnerSubscriber, innerSubscribe } from '../innerSubscribe';\n\n/* tslint:disable:max-line-length */\nexport function catchError<T, O extends ObservableInput<any>>(selector: (err: any, caught: Observable<T>) => O): OperatorFunction<T, T | ObservedValueOf<O>>;\n/* tslint:enable:max-line-length */\n\n/**\n * Catches errors on the observable to be handled by returning a new observable or throwing an error.\n *\n * ![](catch.png)\n *\n * ## Examples\n * Continues with a different Observable when there's an error\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { map, catchError } from 'rxjs/operators';\n *\n * of(1, 2, 3, 4, 5).pipe(\n *     map(n => {\n *   \t   if (n === 4) {\n * \t       throw 'four!';\n *       }\n *\t     return n;\n *     }),\n *     catchError(err => of('I', 'II', 'III', 'IV', 'V')),\n *   )\n *   .subscribe(x => console.log(x));\n *   // 1, 2, 3, I, II, III, IV, V\n * ```\n *\n * Retries the caught source Observable again in case of error, similar to retry() operator\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { map, catchError, take } from 'rxjs/operators';\n *\n * of(1, 2, 3, 4, 5).pipe(\n *     map(n => {\n *   \t   if (n === 4) {\n *   \t     throw 'four!';\n *       }\n * \t     return n;\n *     }),\n *     catchError((err, caught) => caught),\n *     take(30),\n *   )\n *   .subscribe(x => console.log(x));\n *   // 1, 2, 3, 1, 2, 3, ...\n * ```\n *\n * Throws a new error when the source Observable throws an error\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { map, catchError } from 'rxjs/operators';\n *\n * of(1, 2, 3, 4, 5).pipe(\n *     map(n => {\n *       if (n === 4) {\n *         throw 'four!';\n *       }\n *       return n;\n *     }),\n *     catchError(err => {\n *       throw 'error in source. Details: ' + err;\n *     }),\n *   )\n *   .subscribe(\n *     x => console.log(x),\n *     err => console.log(err)\n *   );\n *   // 1, 2, 3, error in source. Details: four!\n * ```\n *\n *  @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which\n *  is the source observable, in case you'd like to \"retry\" that observable by returning it again. Whatever observable\n *  is returned by the `selector` will be used to continue the observable chain.\n * @return {Observable} An observable that originates from either the source or the observable returned by the\n *  catch `selector` function.\n * @name catchError\n */\nexport function catchError<T, O extends ObservableInput<any>>(\n  selector: (err: any, caught: Observable<T>) => O\n): OperatorFunction<T, T | ObservedValueOf<O>> {\n  return function catchErrorOperatorFunction(source: Observable<T>): Observable<T | ObservedValueOf<O>> {\n    const operator = new CatchOperator(selector);\n    const caught = source.lift(operator);\n    return (operator.caught = caught as Observable<T>);\n  };\n}\n\nclass CatchOperator<T, R> implements Operator<T, T | R> {\n  caught: Observable<T>;\n\n  constructor(private selector: (err: any, caught: Observable<T>) => ObservableInput<T | R>) {\n  }\n\n  call(subscriber: Subscriber<R>, source: any): any {\n    return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass CatchSubscriber<T, R> extends SimpleOuterSubscriber<T, T | R> {\n  constructor(destination: Subscriber<any>,\n              private selector: (err: any, caught: Observable<T>) => ObservableInput<T | R>,\n              private caught: Observable<T>) {\n    super(destination);\n  }\n\n  // NOTE: overriding `error` instead of `_error` because we don't want\n  // to have this flag this subscriber as `isStopped`. We can mimic the\n  // behavior of the RetrySubscriber (from the `retry` operator), where\n  // we unsubscribe from our source chain, reset our Subscriber flags,\n  // then subscribe to the selector result.\n  error(err: any) {\n    if (!this.isStopped) {\n      let result: any;\n      try {\n        result = this.selector(err, this.caught);\n      } catch (err2) {\n        super.error(err2);\n        return;\n      }\n      this._unsubscribeAndRecycle();\n      const innerSubscriber = new SimpleInnerSubscriber(this);\n      this.add(innerSubscriber);\n      const innerSubscription = innerSubscribe(result, innerSubscriber);\n      // The returned subscription will usually be the subscriber that was\n      // passed. However, interop subscribers will be wrapped and for\n      // unsubscriptions to chain correctly, the wrapper needs to be added, too.\n      if (innerSubscription !== innerSubscriber) {\n        this.add(innerSubscription);\n      }\n    }\n  }\n}\n","import { CombineLatestOperator } from '../observable/combineLatest';\nimport { Observable } from '../Observable';\nimport { OperatorFunction, ObservableInput } from '../types';\n\nexport function combineAll<T>(): OperatorFunction<ObservableInput<T>, T[]>;\nexport function combineAll<T>(): OperatorFunction<any, T[]>;\nexport function combineAll<T, R>(project: (...values: T[]) => R): OperatorFunction<ObservableInput<T>, R>;\nexport function combineAll<R>(project: (...values: Array<any>) => R): OperatorFunction<any, R>;\n/**\n * Flattens an Observable-of-Observables by applying {@link combineLatest} when the Observable-of-Observables completes.\n *\n * ![](combineAll.png)\n *\n * `combineAll` takes an Observable of Observables, and collects all Observables from it. Once the outer Observable completes,\n * it subscribes to all collected Observables and combines their values using the {@link combineLatest}</a> strategy, such that:\n *\n * * Every time an inner Observable emits, the output Observable emits\n * * When the returned observable emits, it emits all of the latest values by:\n *    * If a `project` function is provided, it is called with each recent value from each inner Observable in whatever order they\n *      arrived, and the result of the `project` function is what is emitted by the output Observable.\n *    * If there is no `project` function, an array of all the most recent values is emitted by the output Observable.\n *\n * ---\n *\n * ## Examples\n *\n * ### Map two click events to a finite interval Observable, then apply `combineAll`\n *\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { map, combineAll, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n *   map(ev =>\n *      interval(Math.random() * 2000).pipe(take(3))\n *   ),\n *   take(2)\n * );\n * const result = higherOrder.pipe(\n *   combineAll()\n * );\n *\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineLatest}\n * @see {@link mergeAll}\n *\n * @param {function(...values: Array<any>)} An optional function to map the most recent values from each inner Observable into a new result.\n * Takes each of the most recent values from each collected inner Observable as arguments, in order.\n * @return {Observable<T>}\n * @name combineAll\n */\nexport function combineAll<T, R>(project?: (...values: Array<any>) => R): OperatorFunction<T, R> {\n  return (source: Observable<T>) => source.lift(new CombineLatestOperator(project));\n}\n","\nimport { isArray } from '../util/isArray';\nimport { CombineLatestOperator } from '../observable/combineLatest';\nimport { from } from '../observable/from';\nimport { Observable } from '../Observable';\nimport { ObservableInput, OperatorFunction } from '../types';\n\nconst none = {};\n\n/* tslint:disable:max-line-length */\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest<T, R>(project: (v1: T) => R): OperatorFunction<T, R>;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest<T, T2, R>(v2: ObservableInput<T2>, project: (v1: T, v2: T2) => R): OperatorFunction<T, R>;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest<T, T2, T3, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, project: (v1: T, v2: T2, v3: T3) => R): OperatorFunction<T, R>;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest<T, T2, T3, T4, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, project: (v1: T, v2: T2, v3: T3, v4: T4) => R): OperatorFunction<T, R>;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest<T, T2, T3, T4, T5, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, project: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => R): OperatorFunction<T, R>;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest<T, T2, T3, T4, T5, T6, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>, project: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5, v6: T6) => R): OperatorFunction<T, R> ;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest<T, T2>(v2: ObservableInput<T2>): OperatorFunction<T, [T, T2]>;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest<T, T2, T3>(v2: ObservableInput<T2>, v3: ObservableInput<T3>): OperatorFunction<T, [T, T2, T3]>;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest<T, T2, T3, T4>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>): OperatorFunction<T, [T, T2, T3, T4]>;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest<T, T2, T3, T4, T5>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>): OperatorFunction<T, [T, T2, T3, T4, T5]>;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest<T, T2, T3, T4, T5, T6>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>): OperatorFunction<T, [T, T2, T3, T4, T5, T6]> ;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest<T, R>(...observables: Array<ObservableInput<T> | ((...values: Array<T>) => R)>): OperatorFunction<T, R>;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest<T, R>(array: ObservableInput<T>[]): OperatorFunction<T, Array<T>>;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest<T, TOther, R>(array: ObservableInput<TOther>[], project: (v1: T, ...values: Array<TOther>) => R): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * @deprecated Deprecated in favor of static {@link combineLatest}.\n */\nexport function combineLatest<T, R>(...observables: Array<ObservableInput<any> |\n                                                    Array<ObservableInput<any>> |\n                                                    ((...values: Array<any>) => R)>): OperatorFunction<T, R> {\n  let project: (...values: Array<any>) => R = null;\n  if (typeof observables[observables.length - 1] === 'function') {\n    project = <(...values: Array<any>) => R>observables.pop();\n  }\n\n  // if the first and only other argument besides the resultSelector is an array\n  // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`\n  if (observables.length === 1 && isArray(observables[0])) {\n    observables = (<any>observables[0]).slice();\n  }\n\n  return (source: Observable<T>) => source.lift.call(from([source, ...observables]), new CombineLatestOperator(project));\n}\n","import {  concat as concatStatic } from '../observable/concat';\nimport { Observable } from '../Observable';\nimport { ObservableInput, OperatorFunction, MonoTypeOperatorFunction, SchedulerLike } from '../types';\n\n/* tslint:disable:max-line-length */\n/** @deprecated Deprecated in favor of static concat. */\nexport function concat<T>(scheduler?: SchedulerLike): MonoTypeOperatorFunction<T>;\n/** @deprecated Deprecated in favor of static concat. */\nexport function concat<T, T2>(v2: ObservableInput<T2>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2>;\n/** @deprecated Deprecated in favor of static concat. */\nexport function concat<T, T2, T3>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3>;\n/** @deprecated Deprecated in favor of static concat. */\nexport function concat<T, T2, T3, T4>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3 | T4>;\n/** @deprecated Deprecated in favor of static concat. */\nexport function concat<T, T2, T3, T4, T5>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3 | T4 | T5>;\n/** @deprecated Deprecated in favor of static concat. */\nexport function concat<T, T2, T3, T4, T5, T6>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3 | T4 | T5 | T6>;\n/** @deprecated Deprecated in favor of static concat. */\nexport function concat<T>(...observables: Array<ObservableInput<T> | SchedulerLike>): MonoTypeOperatorFunction<T>;\n/** @deprecated Deprecated in favor of static concat. */\nexport function concat<T, R>(...observables: Array<ObservableInput<any> | SchedulerLike>): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * @deprecated Deprecated in favor of static {@link concat}.\n */\nexport function concat<T, R>(...observables: Array<ObservableInput<any> | SchedulerLike>): OperatorFunction<T, R> {\n  return (source: Observable<T>) => source.lift.call(concatStatic(source, ...observables));\n}\n","import { concatMap } from './concatMap';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function concatMapTo<T, O extends ObservableInput<any>>(observable: O): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated */\nexport function concatMapTo<T, O extends ObservableInput<any>>(observable: O, resultSelector: undefined): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated */\nexport function concatMapTo<T, R, O extends ObservableInput<any>>(observable: O, resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to the same Observable which is merged multiple\n * times in a serialized fashion on the output Observable.\n *\n * <span class=\"informal\">It's like {@link concatMap}, but maps each value\n * always to the same inner Observable.</span>\n *\n * ![](concatMapTo.png)\n *\n * Maps each source value to the given Observable `innerObservable` regardless\n * of the source value, and then flattens those resulting Observables into one\n * single Observable, which is the output Observable. Each new `innerObservable`\n * instance emitted on the output Observable is concatenated with the previous\n * `innerObservable` instance.\n *\n * __Warning:__ if source values arrive endlessly and faster than their\n * corresponding inner Observables can complete, it will result in memory issues\n * as inner Observables amass in an unbounded buffer waiting for their turn to\n * be subscribed to.\n *\n * Note: `concatMapTo` is equivalent to `mergeMapTo` with concurrency parameter\n * set to `1`.\n *\n * ## Example\n * For each click event, tick every second from 0 to 3, with no concurrency\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { concatMapTo, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n *   concatMapTo(interval(1000).pipe(take(4))),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // (results are not concurrent)\n * // For every click on the \"document\" it will emit values 0 to 3 spaced\n * // on a 1000ms interval\n * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3\n * ```\n *\n * @see {@link concat}\n * @see {@link concatAll}\n * @see {@link concatMap}\n * @see {@link mergeMapTo}\n * @see {@link switchMapTo}\n *\n * @param {ObservableInput} innerObservable An Observable to replace each value from\n * the source Observable.\n * @return {Observable} An observable of values merged together by joining the\n * passed observable with itself, one after the other, for each value emitted\n * from the source.\n * @method concatMapTo\n * @owner Observable\n */\nexport function concatMapTo<T, R, O extends ObservableInput<any>>(\n  innerObservable: O,\n  resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, ObservedValueOf<O>|R> {\n  return concatMap(() => innerObservable, resultSelector);\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Observer, OperatorFunction } from '../types';\nimport { Subscriber } from '../Subscriber';\n/**\n * Counts the number of emissions on the source and emits that number when the\n * source completes.\n *\n * <span class=\"informal\">Tells how many values were emitted, when the source\n * completes.</span>\n *\n * ![](count.png)\n *\n * `count` transforms an Observable that emits values into an Observable that\n * emits a single value that represents the number of values emitted by the\n * source Observable. If the source Observable terminates with an error, `count`\n * will pass this error notification along without emitting a value first. If\n * the source Observable does not terminate at all, `count` will neither emit\n * a value nor terminate. This operator takes an optional `predicate` function\n * as argument, in which case the output emission will represent the number of\n * source values that matched `true` with the `predicate`.\n *\n * ## Examples\n *\n * Counts how many seconds have passed before the first click happened\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { count, takeUntil } from 'rxjs/operators';\n *\n * const seconds = interval(1000);\n * const clicks = fromEvent(document, 'click');\n * const secondsBeforeClick = seconds.pipe(takeUntil(clicks));\n * const result = secondsBeforeClick.pipe(count());\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Counts how many odd numbers are there between 1 and 7\n * ```ts\n * import { range } from 'rxjs';\n * import { count } from 'rxjs/operators';\n *\n * const numbers = range(1, 7);\n * const result = numbers.pipe(count(i => i % 2 === 1));\n * result.subscribe(x => console.log(x));\n * // Results in:\n * // 4\n * ```\n *\n * @see {@link max}\n * @see {@link min}\n * @see {@link reduce}\n *\n * @param {function(value: T, i: number, source: Observable<T>): boolean} [predicate] A\n * boolean function to select what values are to be counted. It is provided with\n * arguments of:\n * - `value`: the value from the source Observable.\n * - `index`: the (zero-based) \"index\" of the value from the source Observable.\n * - `source`: the source Observable instance itself.\n * @return {Observable} An Observable of one number that represents the count as\n * described above.\n * @method count\n * @owner Observable\n */\n\nexport function count<T>(predicate?: (value: T, index: number, source: Observable<T>) => boolean): OperatorFunction<T, number> {\n  return (source: Observable<T>) => source.lift(new CountOperator(predicate, source));\n}\n\nclass CountOperator<T> implements Operator<T, number> {\n  constructor(private predicate?: (value: T, index: number, source: Observable<T>) => boolean,\n              private source?: Observable<T>) {\n  }\n\n  call(subscriber: Subscriber<number>, source: any): any {\n    return source.subscribe(new CountSubscriber(subscriber, this.predicate, this.source));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass CountSubscriber<T> extends Subscriber<T> {\n  private count: number = 0;\n  private index: number = 0;\n\n  constructor(destination: Observer<number>,\n              private predicate?: (value: T, index: number, source: Observable<T>) => boolean,\n              private source?: Observable<T>) {\n    super(destination);\n  }\n\n  protected _next(value: T): void {\n    if (this.predicate) {\n      this._tryPredicate(value);\n    } else {\n      this.count++;\n    }\n  }\n\n  private _tryPredicate(value: T) {\n    let result: any;\n\n    try {\n      result = this.predicate(value, this.index++, this.source);\n    } catch (err) {\n      this.destination.error(err);\n      return;\n    }\n\n    if (result) {\n      this.count++;\n    }\n  }\n\n  protected _complete(): void {\n    this.destination.next(this.count);\n    this.destination.complete();\n  }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { MonoTypeOperatorFunction, SubscribableOrPromise, TeardownLogic } from '../types';\nimport { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';\n\n/**\n * Emits a value from the source Observable only after a particular time span\n * determined by another Observable has passed without another source emission.\n *\n * <span class=\"informal\">It's like {@link debounceTime}, but the time span of\n * emission silence is determined by a second Observable.</span>\n *\n * ![](debounce.png)\n *\n * `debounce` delays values emitted by the source Observable, but drops previous\n * pending delayed emissions if a new value arrives on the source Observable.\n * This operator keeps track of the most recent value from the source\n * Observable, and spawns a duration Observable by calling the\n * `durationSelector` function. The value is emitted only when the duration\n * Observable emits a value or completes, and if no other value was emitted on\n * the source Observable since the duration Observable was spawned. If a new\n * value appears before the duration Observable emits, the previous value will\n * be dropped and will not be emitted on the output Observable.\n *\n * Like {@link debounceTime}, this is a rate-limiting operator, and also a\n * delay-like operator since output emissions do not necessarily occur at the\n * same time as they did on the source Observable.\n *\n * ## Example\n * Emit the most recent click after a burst of clicks\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { debounce } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(debounce(() => interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link audit}\n * @see {@link debounceTime}\n * @see {@link delayWhen}\n * @see {@link throttle}\n *\n * @param {function(value: T): SubscribableOrPromise} durationSelector A function\n * that receives a value from the source Observable, for computing the timeout\n * duration for each source value, returned as an Observable or a Promise.\n * @return {Observable} An Observable that delays the emissions of the source\n * Observable by the specified duration Observable returned by\n * `durationSelector`, and may drop some values if they occur too frequently.\n * @method debounce\n * @owner Observable\n */\nexport function debounce<T>(durationSelector: (value: T) => SubscribableOrPromise<any>): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => source.lift(new DebounceOperator(durationSelector));\n}\n\nclass DebounceOperator<T> implements Operator<T, T> {\n  constructor(private durationSelector: (value: T) => SubscribableOrPromise<any>) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new DebounceSubscriber(subscriber, this.durationSelector));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DebounceSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n  private value?: T;\n  private hasValue = false;\n  private durationSubscription?: Subscription;\n\n  constructor(destination: Subscriber<R>,\n              private durationSelector: (value: T) => SubscribableOrPromise<any>) {\n    super(destination);\n  }\n\n  protected _next(value: T): void {\n    try {\n      const result = this.durationSelector.call(this, value);\n\n      if (result) {\n        this._tryNext(value, result);\n      }\n    } catch (err) {\n      this.destination.error!(err);\n    }\n  }\n\n  protected _complete(): void {\n    this.emitValue();\n    this.destination.complete!();\n  }\n\n  private _tryNext(value: T, duration: SubscribableOrPromise<any>): void {\n    let subscription = this.durationSubscription;\n    this.value = value;\n    this.hasValue = true;\n    if (subscription) {\n      subscription.unsubscribe();\n      this.remove(subscription);\n    }\n\n    subscription = innerSubscribe(duration, new SimpleInnerSubscriber(this));\n    if (subscription && !subscription.closed) {\n      this.add(this.durationSubscription = subscription);\n    }\n  }\n\n  notifyNext(): void {\n    this.emitValue();\n  }\n\n  notifyComplete(): void {\n    this.emitValue();\n  }\n\n  emitValue(): void {\n    if (this.hasValue) {\n      const value = this.value;\n      const subscription = this.durationSubscription;\n      if (subscription) {\n        this.durationSubscription = undefined;\n        subscription.unsubscribe();\n        this.remove(subscription);\n      }\n      // This must be done *before* passing the value\n      // along to the destination because it's possible for\n      // the value to synchronously re-enter this operator\n      // recursively if the duration selector Observable\n      // emits synchronously\n      this.value = undefined;\n      this.hasValue = false;\n      super._next(value!);\n    }\n  }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { async } from '../scheduler/async';\nimport { MonoTypeOperatorFunction, SchedulerLike, TeardownLogic } from '../types';\n\n/**\n * Emits a value from the source Observable only after a particular time span\n * has passed without another source emission.\n *\n * <span class=\"informal\">It's like {@link delay}, but passes only the most\n * recent value from each burst of emissions.</span>\n *\n * ![](debounceTime.png)\n *\n * `debounceTime` delays values emitted by the source Observable, but drops\n * previous pending delayed emissions if a new value arrives on the source\n * Observable. This operator keeps track of the most recent value from the\n * source Observable, and emits that only when `dueTime` enough time has passed\n * without any other value appearing on the source Observable. If a new value\n * appears before `dueTime` silence occurs, the previous value will be dropped\n * and will not be emitted on the output Observable.\n *\n * This is a rate-limiting operator, because it is impossible for more than one\n * value to be emitted in any time window of duration `dueTime`, but it is also\n * a delay-like operator since output emissions do not occur at the same time as\n * they did on the source Observable. Optionally takes a {@link SchedulerLike} for\n * managing timers.\n *\n * ## Example\n * Emit the most recent click after a burst of clicks\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { debounceTime } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(debounceTime(1000));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link auditTime}\n * @see {@link debounce}\n * @see {@link delay}\n * @see {@link sampleTime}\n * @see {@link throttleTime}\n *\n * @param {number} dueTime The timeout duration in milliseconds (or the time\n * unit determined internally by the optional `scheduler`) for the window of\n * time required to wait for emission silence before emitting the most recent\n * source value.\n * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for\n * managing the timers that handle the timeout for each value.\n * @return {Observable} An Observable that delays the emissions of the source\n * Observable by the specified `dueTime`, and may drop some values if they occur\n * too frequently.\n * @method debounceTime\n * @owner Observable\n */\nexport function debounceTime<T>(dueTime: number, scheduler: SchedulerLike = async): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => source.lift(new DebounceTimeOperator(dueTime, scheduler));\n}\n\nclass DebounceTimeOperator<T> implements Operator<T, T> {\n  constructor(private dueTime: number, private scheduler: SchedulerLike) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DebounceTimeSubscriber<T> extends Subscriber<T> {\n  private debouncedSubscription: Subscription = null;\n  private lastValue: T = null;\n  private hasValue: boolean = false;\n\n  constructor(destination: Subscriber<T>,\n              private dueTime: number,\n              private scheduler: SchedulerLike) {\n    super(destination);\n  }\n\n  protected _next(value: T) {\n    this.clearDebounce();\n    this.lastValue = value;\n    this.hasValue = true;\n    this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));\n  }\n\n  protected _complete() {\n    this.debouncedNext();\n    this.destination.complete();\n  }\n\n  debouncedNext(): void {\n    this.clearDebounce();\n\n    if (this.hasValue) {\n      const { lastValue } = this;\n      // This must be done *before* passing the value\n      // along to the destination because it's possible for\n      // the value to synchronously re-enter this operator\n      // recursively when scheduled with things like\n      // VirtualScheduler/TestScheduler.\n      this.lastValue = null;\n      this.hasValue = false;\n      this.destination.next(lastValue);\n    }\n  }\n\n  private clearDebounce(): void {\n    const debouncedSubscription = this.debouncedSubscription;\n\n    if (debouncedSubscription !== null) {\n      this.remove(debouncedSubscription);\n      debouncedSubscription.unsubscribe();\n      this.debouncedSubscription = null;\n    }\n  }\n}\n\nfunction dispatchNext(subscriber: DebounceTimeSubscriber<any>) {\n  subscriber.debouncedNext();\n}\n","import { async } from '../scheduler/async';\nimport { isDate } from '../util/isDate';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { Notification } from '../Notification';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, PartialObserver, SchedulerAction, SchedulerLike, TeardownLogic } from '../types';\n\n/**\n * Delays the emission of items from the source Observable by a given timeout or\n * until a given Date.\n *\n * <span class=\"informal\">Time shifts each item by some specified amount of\n * milliseconds.</span>\n *\n * ![](delay.png)\n *\n * If the delay argument is a Number, this operator time shifts the source\n * Observable by that amount of time expressed in milliseconds. The relative\n * time intervals between the values are preserved.\n *\n * If the delay argument is a Date, this operator time shifts the start of the\n * Observable execution until the given date occurs.\n *\n * ## Examples\n * Delay each click by one second\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { delay } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const delayedClicks = clicks.pipe(delay(1000)); // each click emitted after 1 second\n * delayedClicks.subscribe(x => console.log(x));\n * ```\n *\n * Delay all clicks until a future date happens\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { delay } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const date = new Date('March 15, 2050 12:00:00'); // in the future\n * const delayedClicks = clicks.pipe(delay(date)); // click emitted only after that date\n * delayedClicks.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link debounceTime}\n * @see {@link delayWhen}\n *\n * @param {number|Date} delay The delay duration in milliseconds (a `number`) or\n * a `Date` until which the emission of the source items is delayed.\n * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for\n * managing the timers that handle the time-shift for each item.\n * @return {Observable} An Observable that delays the emissions of the source\n * Observable by the specified timeout or Date.\n * @method delay\n * @owner Observable\n */\nexport function delay<T>(delay: number|Date,\n                         scheduler: SchedulerLike = async): MonoTypeOperatorFunction<T> {\n  const absoluteDelay = isDate(delay);\n  const delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(<number>delay);\n  return (source: Observable<T>) => source.lift(new DelayOperator(delayFor, scheduler));\n}\n\nclass DelayOperator<T> implements Operator<T, T> {\n  constructor(private delay: number,\n              private scheduler: SchedulerLike) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));\n  }\n}\n\ninterface DelayState<T> {\n  source: DelaySubscriber<T>;\n  destination: PartialObserver<T>;\n  scheduler: SchedulerLike;\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DelaySubscriber<T> extends Subscriber<T> {\n  private queue: Array<DelayMessage<T>> = [];\n  private active: boolean = false;\n  private errored: boolean = false;\n\n  private static dispatch<T>(this: SchedulerAction<DelayState<T>>, state: DelayState<T>): void {\n    const source = state.source;\n    const queue = source.queue;\n    const scheduler = state.scheduler;\n    const destination = state.destination;\n\n    while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {\n      queue.shift().notification.observe(destination);\n    }\n\n    if (queue.length > 0) {\n      const delay = Math.max(0, queue[0].time - scheduler.now());\n      this.schedule(state, delay);\n    } else {\n      this.unsubscribe();\n      source.active = false;\n    }\n  }\n\n  constructor(destination: Subscriber<T>,\n              private delay: number,\n              private scheduler: SchedulerLike) {\n    super(destination);\n  }\n\n  private _schedule(scheduler: SchedulerLike): void {\n    this.active = true;\n    const destination = this.destination as Subscription;\n    destination.add(scheduler.schedule<DelayState<T>>(DelaySubscriber.dispatch, this.delay, {\n      source: this, destination: this.destination, scheduler: scheduler\n    }));\n  }\n\n  private scheduleNotification(notification: Notification<T>): void {\n    if (this.errored === true) {\n      return;\n    }\n\n    const scheduler = this.scheduler;\n    const message = new DelayMessage(scheduler.now() + this.delay, notification);\n    this.queue.push(message);\n\n    if (this.active === false) {\n      this._schedule(scheduler);\n    }\n  }\n\n  protected _next(value: T) {\n    this.scheduleNotification(Notification.createNext(value));\n  }\n\n  protected _error(err: any) {\n    this.errored = true;\n    this.queue = [];\n    this.destination.error(err);\n    this.unsubscribe();\n  }\n\n  protected _complete() {\n    this.scheduleNotification(Notification.createComplete());\n    this.unsubscribe();\n  }\n}\n\nclass DelayMessage<T> {\n  constructor(public readonly time: number,\n              public readonly notification: Notification<T>) {\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/* tslint:disable:max-line-length */\n/** @deprecated In future versions, empty notifiers will no longer re-emit the source value on the output observable. */\nexport function delayWhen<T>(delayDurationSelector: (value: T, index: number) => Observable<never>, subscriptionDelay?: Observable<any>): MonoTypeOperatorFunction<T>;\nexport function delayWhen<T>(delayDurationSelector: (value: T, index: number) => Observable<any>, subscriptionDelay?: Observable<any>): MonoTypeOperatorFunction<T>;\n/* tslint:disable:max-line-length */\n\n/**\n * Delays the emission of items from the source Observable by a given time span\n * determined by the emissions of another Observable.\n *\n * <span class=\"informal\">It's like {@link delay}, but the time span of the\n * delay duration is determined by a second Observable.</span>\n *\n * ![](delayWhen.png)\n *\n * `delayWhen` time shifts each emitted value from the source Observable by a\n * time span determined by another Observable. When the source emits a value,\n * the `delayDurationSelector` function is called with the source value as\n * argument, and should return an Observable, called the \"duration\" Observable.\n * The source value is emitted on the output Observable only when the duration\n * Observable emits a value or completes.\n * The completion of the notifier triggering the emission of the source value\n * is deprecated behavior and will be removed in future versions.\n *\n * Optionally, `delayWhen` takes a second argument, `subscriptionDelay`, which\n * is an Observable. When `subscriptionDelay` emits its first value or\n * completes, the source Observable is subscribed to and starts behaving like\n * described in the previous paragraph. If `subscriptionDelay` is not provided,\n * `delayWhen` will subscribe to the source Observable as soon as the output\n * Observable is subscribed.\n *\n * ## Example\n * Delay each click by a random amount of time, between 0 and 5 seconds\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { delayWhen } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const delayedClicks = clicks.pipe(\n *   delayWhen(event => interval(Math.random() * 5000)),\n * );\n * delayedClicks.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link delay}\n * @see {@link throttle}\n * @see {@link throttleTime}\n * @see {@link debounce}\n * @see {@link debounceTime}\n * @see {@link sample}\n * @see {@link sampleTime}\n * @see {@link audit}\n * @see {@link auditTime}\n *\n * @param {function(value: T, index: number): Observable} delayDurationSelector A function that\n * returns an Observable for each value emitted by the source Observable, which\n * is then used to delay the emission of that item on the output Observable\n * until the Observable returned from this function emits a value.\n * @param {Observable} subscriptionDelay An Observable that triggers the\n * subscription to the source Observable once it emits any value.\n * @return {Observable} An Observable that delays the emissions of the source\n * Observable by an amount of time specified by the Observable returned by\n * `delayDurationSelector`.\n * @method delayWhen\n * @owner Observable\n */\nexport function delayWhen<T>(delayDurationSelector: (value: T, index: number) => Observable<any>,\n                             subscriptionDelay?: Observable<any>): MonoTypeOperatorFunction<T> {\n  if (subscriptionDelay) {\n    return (source: Observable<T>) =>\n      new SubscriptionDelayObservable(source, subscriptionDelay)\n        .lift(new DelayWhenOperator(delayDurationSelector));\n  }\n  return (source: Observable<T>) => source.lift(new DelayWhenOperator(delayDurationSelector));\n}\n\nclass DelayWhenOperator<T> implements Operator<T, T> {\n  constructor(private delayDurationSelector: (value: T, index: number) => Observable<any>) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new DelayWhenSubscriber(subscriber, this.delayDurationSelector));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DelayWhenSubscriber<T, R> extends OuterSubscriber<T, R> {\n  private completed: boolean = false;\n  private delayNotifierSubscriptions: Array<Subscription> = [];\n  private index: number = 0;\n\n  constructor(destination: Subscriber<T>,\n              private delayDurationSelector: (value: T, index: number) => Observable<any>) {\n    super(destination);\n  }\n\n  notifyNext(outerValue: T, _innerValue: any,\n             _outerIndex: number, _innerIndex: number,\n             innerSub: InnerSubscriber<T, R>): void {\n    this.destination.next!(outerValue);\n    this.removeSubscription(innerSub);\n    this.tryComplete();\n  }\n\n  notifyError(error: any, innerSub: InnerSubscriber<T, R>): void {\n    this._error(error);\n  }\n\n  notifyComplete(innerSub: InnerSubscriber<T, R>): void {\n    const value = this.removeSubscription(innerSub);\n    if (value) {\n      this.destination.next!(value);\n    }\n    this.tryComplete();\n  }\n\n  protected _next(value: T): void {\n    const index = this.index++;\n    try {\n      const delayNotifier = this.delayDurationSelector(value, index);\n      if (delayNotifier) {\n        this.tryDelay(delayNotifier, value);\n      }\n    } catch (err) {\n      this.destination.error!(err);\n    }\n  }\n\n  protected _complete(): void {\n    this.completed = true;\n    this.tryComplete();\n    this.unsubscribe();\n  }\n\n  private removeSubscription(subscription: InnerSubscriber<T, R>): T {\n    subscription.unsubscribe();\n\n    const subscriptionIdx = this.delayNotifierSubscriptions.indexOf(subscription);\n    if (subscriptionIdx !== -1) {\n      this.delayNotifierSubscriptions.splice(subscriptionIdx, 1);\n    }\n\n    return subscription.outerValue;\n  }\n\n  private tryDelay(delayNotifier: Observable<any>, value: T): void {\n    const notifierSubscription = subscribeToResult(this, delayNotifier, value);\n\n    if (notifierSubscription && !notifierSubscription.closed) {\n      const destination = this.destination as Subscription;\n      destination.add(notifierSubscription);\n      this.delayNotifierSubscriptions.push(notifierSubscription);\n    }\n  }\n\n  private tryComplete(): void {\n    if (this.completed && this.delayNotifierSubscriptions.length === 0) {\n      this.destination.complete!();\n    }\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SubscriptionDelayObservable<T> extends Observable<T> {\n  constructor(public source: Observable<T>, private subscriptionDelay: Observable<any>) {\n    super();\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _subscribe(subscriber: Subscriber<T>) {\n    this.subscriptionDelay.subscribe(new SubscriptionDelaySubscriber(subscriber, this.source));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SubscriptionDelaySubscriber<T> extends Subscriber<T> {\n  private sourceSubscribed: boolean = false;\n\n  constructor(private parent: Subscriber<T>, private source: Observable<T>) {\n    super();\n  }\n\n  protected _next(unused: any) {\n    this.subscribeToSource();\n  }\n\n  protected _error(err: any) {\n    this.unsubscribe();\n    this.parent.error(err);\n  }\n\n  protected _complete() {\n    this.unsubscribe();\n    this.subscribeToSource();\n  }\n\n  private subscribeToSource(): void {\n    if (!this.sourceSubscribed) {\n      this.sourceSubscribed = true;\n      this.unsubscribe();\n      this.source.subscribe(this.parent);\n    }\n  }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Notification } from '../Notification';\nimport { OperatorFunction } from '../types';\n\n/**\n * Converts an Observable of {@link Notification} objects into the emissions\n * that they represent.\n *\n * <span class=\"informal\">Unwraps {@link Notification} objects as actual `next`,\n * `error` and `complete` emissions. The opposite of {@link materialize}.</span>\n *\n * ![](dematerialize.png)\n *\n * `dematerialize` is assumed to operate an Observable that only emits\n * {@link Notification} objects as `next` emissions, and does not emit any\n * `error`. Such Observable is the output of a `materialize` operation. Those\n * notifications are then unwrapped using the metadata they contain, and emitted\n * as `next`, `error`, and `complete` on the output Observable.\n *\n * Use this operator in conjunction with {@link materialize}.\n *\n * ## Example\n * Convert an Observable of Notifications to an actual Observable\n * ```ts\n * import { of, Notification } from 'rxjs';\n * import { dematerialize } from 'rxjs/operators';\n *\n * const notifA = new Notification('N', 'A');\n * const notifB = new Notification('N', 'B');\n * const notifE = new Notification('E', undefined,\n *   new TypeError('x.toUpperCase is not a function')\n * );\n * const materialized = of(notifA, notifB, notifE);\n * const upperCase = materialized.pipe(dematerialize());\n * upperCase.subscribe(x => console.log(x), e => console.error(e));\n *\n * // Results in:\n * // A\n * // B\n * // TypeError: x.toUpperCase is not a function\n * ```\n *\n * @see {@link Notification}\n * @see {@link materialize}\n *\n * @return {Observable} An Observable that emits items and notifications\n * embedded in Notification objects emitted by the source Observable.\n * @method dematerialize\n * @owner Observable\n */\nexport function dematerialize<T>(): OperatorFunction<Notification<T>, T> {\n  return function dematerializeOperatorFunction(source: Observable<Notification<T>>) {\n    return source.lift(new DeMaterializeOperator());\n  };\n}\n\nclass DeMaterializeOperator<T extends Notification<any>, R> implements Operator<T, R> {\n  call(subscriber: Subscriber<any>, source: any): any {\n    return source.subscribe(new DeMaterializeSubscriber(subscriber));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DeMaterializeSubscriber<T extends Notification<any>> extends Subscriber<T> {\n  constructor(destination: Subscriber<any>) {\n    super(destination);\n  }\n\n  protected _next(value: T) {\n    value.observe(this.destination);\n  }\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\nimport { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';\n\n/**\n * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.\n *\n * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will\n * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the\n * source observable directly with an equality check against previous values.\n *\n * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.\n *\n * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the\n * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`\n * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so\n * that the internal `Set` can be \"flushed\", basically clearing it of values.\n *\n * ## Examples\n * A simple example with numbers\n * ```ts\n * import { of } from 'rxjs';\n * import { distinct } from 'rxjs/operators';\n *\n * of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1).pipe(\n *     distinct(),\n *   )\n *   .subscribe(x => console.log(x)); // 1, 2, 3, 4\n * ```\n *\n * An example using a keySelector function\n * ```typescript\n * import { of } from 'rxjs';\n * import { distinct } from 'rxjs/operators';\n *\n * interface Person {\n *    age: number,\n *    name: string\n * }\n *\n * of<Person>(\n *     { age: 4, name: 'Foo'},\n *     { age: 7, name: 'Bar'},\n *     { age: 5, name: 'Foo'},\n *   ).pipe(\n *     distinct((p: Person) => p.name),\n *   )\n *   .subscribe(x => console.log(x));\n *\n * // displays:\n * // { age: 4, name: 'Foo' }\n * // { age: 7, name: 'Bar' }\n * ```\n * @see {@link distinctUntilChanged}\n * @see {@link distinctUntilKeyChanged}\n *\n * @param {function} [keySelector] Optional function to select which value you want to check as distinct.\n * @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator.\n * @return {Observable} An Observable that emits items from the source Observable with distinct values.\n * @method distinct\n * @owner Observable\n */\nexport function distinct<T, K>(keySelector?: (value: T) => K,\n                               flushes?: Observable<any>): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => source.lift(new DistinctOperator(keySelector, flushes));\n}\n\nclass DistinctOperator<T, K> implements Operator<T, T> {\n  constructor(private keySelector?: (value: T) => K, private flushes?: Observable<any>) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class DistinctSubscriber<T, K> extends SimpleOuterSubscriber<T, T> {\n  private values = new Set<K>();\n\n  constructor(destination: Subscriber<T>, private keySelector?: (value: T) => K, flushes?: Observable<any>) {\n    super(destination);\n\n    if (flushes) {\n      this.add(innerSubscribe(flushes, new SimpleInnerSubscriber(this)));\n    }\n  }\n\n  notifyNext(): void {\n    this.values.clear();\n  }\n\n  notifyError(error: any): void {\n    this._error(error);\n  }\n\n  protected _next(value: T): void {\n    if (this.keySelector) {\n      this._useKeySelector(value);\n    } else {\n      this._finalizeNext(value, value);\n    }\n  }\n\n  private _useKeySelector(value: T): void {\n    let key: K;\n    const { destination } = this;\n    try {\n      key = this.keySelector!(value);\n    } catch (err) {\n      destination.error!(err);\n      return;\n    }\n    this._finalizeNext(key, value);\n  }\n\n  private _finalizeNext(key: K|T, value: T) {\n    const { values } = this;\n    if (!values.has(<K>key)) {\n      values.add(<K>key);\n      this.destination.next!(value);\n    }\n  }\n\n}\n","import { distinctUntilChanged } from './distinctUntilChanged';\nimport { MonoTypeOperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function distinctUntilKeyChanged<T>(key: keyof T): MonoTypeOperatorFunction<T>;\nexport function distinctUntilKeyChanged<T, K extends keyof T>(key: K, compare: (x: T[K], y: T[K]) => boolean): MonoTypeOperatorFunction<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item,\n * using a property accessed by using the key provided to check if the two items are distinct.\n *\n * If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted.\n *\n * If a comparator function is not provided, an equality check is used by default.\n *\n * ## Examples\n * An example comparing the name of persons\n * ```typescript\n * import { of } from 'rxjs';\n * import { distinctUntilKeyChanged } from 'rxjs/operators';\n *\n *  interface Person {\n *     age: number,\n *     name: string\n *  }\n *\n * of<Person>(\n *     { age: 4, name: 'Foo'},\n *     { age: 7, name: 'Bar'},\n *     { age: 5, name: 'Foo'},\n *     { age: 6, name: 'Foo'},\n *   ).pipe(\n *     distinctUntilKeyChanged('name'),\n *   )\n *   .subscribe(x => console.log(x));\n *\n * // displays:\n * // { age: 4, name: 'Foo' }\n * // { age: 7, name: 'Bar' }\n * // { age: 5, name: 'Foo' }\n * ```\n *\n * An example comparing the first letters of the name\n * ```typescript\n * import { of } from 'rxjs';\n * import { distinctUntilKeyChanged } from 'rxjs/operators';\n *\n * interface Person {\n *     age: number,\n *     name: string\n *  }\n *\n * of<Person>(\n *     { age: 4, name: 'Foo1'},\n *     { age: 7, name: 'Bar'},\n *     { age: 5, name: 'Foo2'},\n *     { age: 6, name: 'Foo3'},\n *   ).pipe(\n *     distinctUntilKeyChanged('name', (x: string, y: string) => x.substring(0, 3) === y.substring(0, 3)),\n *   )\n *   .subscribe(x => console.log(x));\n *\n * // displays:\n * // { age: 4, name: 'Foo1' }\n * // { age: 7, name: 'Bar' }\n * // { age: 5, name: 'Foo2' }\n * ```\n *\n * @see {@link distinct}\n * @see {@link distinctUntilChanged}\n *\n * @param {string} key String key for object property lookup on each item.\n * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.\n * @return {Observable} An Observable that emits items from the source Observable with distinct values based on the key specified.\n * @method distinctUntilKeyChanged\n * @owner Observable\n */\nexport function distinctUntilKeyChanged<T, K extends keyof T>(key: K, compare?: (x: T[K], y: T[K]) => boolean): MonoTypeOperatorFunction<T> {\n  return distinctUntilChanged((x: T, y: T) => compare ? compare(x[key], y[key]) : x[key] === y[key]);\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\nimport { filter } from './filter';\nimport { throwIfEmpty } from './throwIfEmpty';\nimport { defaultIfEmpty } from './defaultIfEmpty';\nimport { take } from './take';\n\n/**\n * Emits the single value at the specified `index` in a sequence of emissions\n * from the source Observable.\n *\n * <span class=\"informal\">Emits only the i-th value, then completes.</span>\n *\n * ![](elementAt.png)\n *\n * `elementAt` returns an Observable that emits the item at the specified\n * `index` in the source Observable, or a default value if that `index` is out\n * of range and the `default` argument is provided. If the `default` argument is\n * not given and the `index` is out of range, the output Observable will emit an\n * `ArgumentOutOfRangeError` error.\n *\n * ## Example\n * Emit only the third click event\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { elementAt } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(elementAt(2));\n * result.subscribe(x => console.log(x));\n *\n * // Results in:\n * // click 1 = nothing\n * // click 2 = nothing\n * // click 3 = MouseEvent object logged to console\n * ```\n *\n * @see {@link first}\n * @see {@link last}\n * @see {@link skip}\n * @see {@link single}\n * @see {@link take}\n *\n * @throws {ArgumentOutOfRangeError} When using `elementAt(i)`, it delivers an\n * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0` or the\n * Observable has completed before emitting the i-th `next` notification.\n *\n * @param {number} index Is the number `i` for the i-th source emission that has\n * happened since the subscription, starting from the number `0`.\n * @param {T} [defaultValue] The default value returned for missing indices.\n * @return {Observable} An Observable that emits a single item, if it is found.\n * Otherwise, will emit the default value if given. If not, then emits an error.\n * @method elementAt\n * @owner Observable\n */\nexport function elementAt<T>(index: number, defaultValue?: T): MonoTypeOperatorFunction<T> {\n  if (index < 0) { throw new ArgumentOutOfRangeError(); }\n  const hasDefaultValue = arguments.length >= 2;\n  return (source: Observable<T>) => source.pipe(\n    filter((v, i) => i === index),\n    take(1),\n    hasDefaultValue\n      ? defaultIfEmpty(defaultValue)\n      : throwIfEmpty(() => new ArgumentOutOfRangeError()),\n  );\n}\n","import { Observable } from '../Observable';\nimport { concat } from '../observable/concat';\nimport { of } from '../observable/of';\nimport { MonoTypeOperatorFunction, SchedulerLike, OperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */\nexport function endWith<T>(scheduler: SchedulerLike): MonoTypeOperatorFunction<T>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */\nexport function endWith<T, A>(v1: A, scheduler: SchedulerLike): OperatorFunction<T, T | A>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */\nexport function endWith<T, A, B>(v1: A, v2: B, scheduler: SchedulerLike): OperatorFunction<T, T | A | B>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */\nexport function endWith<T, A, B, C>(v1: A, v2: B, v3: C, scheduler: SchedulerLike): OperatorFunction<T, T | A | B | C>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */\nexport function endWith<T, A, B, C, D>(v1: A, v2: B, v3: C, v4: D, scheduler: SchedulerLike): OperatorFunction<T, T | A | B | C | D>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */\nexport function endWith<T, A, B, C, D, E>(v1: A, v2: B, v3: C, v4: D, v5: E, scheduler: SchedulerLike): OperatorFunction<T, T | A | B | C | D | E>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */\nexport function endWith<T, A, B, C, D, E, F>(v1: A, v2: B, v3: C, v4: D, v5: E, v6: F, scheduler: SchedulerLike): OperatorFunction<T, T | A | B | C | D | E | F>;\n\nexport function endWith<T, A>(v1: A): OperatorFunction<T, T | A>;\nexport function endWith<T, A, B>(v1: A, v2: B): OperatorFunction<T, T | A | B>;\nexport function endWith<T, A, B, C>(v1: A, v2: B, v3: C): OperatorFunction<T, T | A | B | C>;\nexport function endWith<T, A, B, C, D>(v1: A, v2: B, v3: C, v4: D): OperatorFunction<T, T | A | B | C | D>;\nexport function endWith<T, A, B, C, D, E>(v1: A, v2: B, v3: C, v4: D, v5: E): OperatorFunction<T, T | A | B | C | D | E>;\nexport function endWith<T, A, B, C, D, E, F>(v1: A, v2: B, v3: C, v4: D, v5: E, v6: F): OperatorFunction<T, T | A | B | C | D | E | F>;\nexport function endWith<T, Z = T>(...array: Z[]): OperatorFunction<T, T | Z>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */\nexport function endWith<T, Z = T>(...array: Array<Z | SchedulerLike>): OperatorFunction<T, T | Z>;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns an Observable that emits the items you specify as arguments after it finishes emitting\n * items emitted by the source Observable.\n *\n * ![](endWith.png)\n *\n * ## Example\n * ### After the source observable completes, appends an emission and then completes too.\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { endWith } from 'rxjs/operators';\n *\n * of('hi', 'how are you?', 'sorry, I have to go now').pipe(\n *   endWith('goodbye!'),\n * )\n * .subscribe(word => console.log(word));\n * // result:\n * // 'hi'\n * // 'how are you?'\n * // 'sorry, I have to go now'\n * // 'goodbye!'\n * ```\n *\n * @param {...T} values - Items you want the modified Observable to emit last.\n * @param {SchedulerLike} [scheduler] - A {@link SchedulerLike} to use for scheduling\n * the emissions of the `next` notifications.\n * @return {Observable} An Observable that emits the items emitted by the source Observable\n *  and then emits the items in the specified Iterable.\n * @method endWith\n * @owner Observable\n */\nexport function endWith<T>(...array: Array<T | SchedulerLike>): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => concat(source, of(...array)) as Observable<T>;\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Observer, OperatorFunction } from '../types';\n\n/**\n * Returns an Observable that emits whether or not every item of the source satisfies the condition specified.\n *\n * ## Example\n * A simple example emitting true if all elements are less than 5, false otherwise\n * ```ts\n * import { of } from 'rxjs';\n * import { every } from 'rxjs/operators';\n *\n *  of(1, 2, 3, 4, 5, 6).pipe(\n *     every(x => x < 5),\n * )\n * .subscribe(x => console.log(x)); // -> false\n * ```\n *\n * @param {function} predicate A function for determining if an item meets a specified condition.\n * @param {any} [thisArg] Optional object to use for `this` in the callback.\n * @return {Observable} An Observable of booleans that determines if all items of the source Observable meet the condition specified.\n * @method every\n * @owner Observable\n */\nexport function every<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean,\n                         thisArg?: any): OperatorFunction<T, boolean> {\n  return (source: Observable<T>) => source.lift(new EveryOperator(predicate, thisArg, source));\n}\n\nclass EveryOperator<T> implements Operator<T, boolean> {\n  constructor(private predicate: (value: T, index: number, source: Observable<T>) => boolean,\n              private thisArg?: any,\n              private source?: Observable<T>) {\n  }\n\n  call(observer: Subscriber<boolean>, source: any): any {\n    return source.subscribe(new EverySubscriber(observer, this.predicate, this.thisArg, this.source));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass EverySubscriber<T> extends Subscriber<T> {\n  private index: number = 0;\n\n  constructor(destination: Observer<boolean>,\n              private predicate: (value: T, index: number, source: Observable<T>) => boolean,\n              private thisArg: any,\n              private source?: Observable<T>) {\n    super(destination);\n    this.thisArg = thisArg || this;\n  }\n\n  private notifyComplete(everyValueMatch: boolean): void {\n    this.destination.next(everyValueMatch);\n    this.destination.complete();\n  }\n\n  protected _next(value: T): void {\n    let result = false;\n    try {\n      result = this.predicate.call(this.thisArg, value, this.index++, this.source);\n    } catch (err) {\n      this.destination.error(err);\n      return;\n    }\n\n    if (!result) {\n      this.notifyComplete(false);\n    }\n  }\n\n  protected _complete(): void {\n    this.notifyComplete(true);\n  }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { ObservableInput, OperatorFunction, TeardownLogic } from '../types';\nimport { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';\n\nexport function exhaust<T>(): OperatorFunction<ObservableInput<T>, T>;\nexport function exhaust<R>(): OperatorFunction<any, R>;\n\n/**\n * Converts a higher-order Observable into a first-order Observable by dropping\n * inner Observables while the previous inner Observable has not yet completed.\n *\n * <span class=\"informal\">Flattens an Observable-of-Observables by dropping the\n * next inner Observables while the current inner is still executing.</span>\n *\n * ![](exhaust.png)\n *\n * `exhaust` subscribes to an Observable that emits Observables, also known as a\n * higher-order Observable. Each time it observes one of these emitted inner\n * Observables, the output Observable begins emitting the items emitted by that\n * inner Observable. So far, it behaves like {@link mergeAll}. However,\n * `exhaust` ignores every new inner Observable if the previous Observable has\n * not yet completed. Once that one completes, it will accept and flatten the\n * next inner Observable and repeat this process.\n *\n * ## Example\n * Run a finite timer for each click, only if there is no currently active timer\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { exhaust, map, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n *   map((ev) => interval(1000).pipe(take(5))),\n * );\n * const result = higherOrder.pipe(exhaust());\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineAll}\n * @see {@link concatAll}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link mergeAll}\n * @see {@link exhaustMap}\n * @see {@link zipAll}\n *\n * @return {Observable} An Observable that takes a source of Observables and propagates the first observable\n * exclusively until it completes before subscribing to the next.\n * @method exhaust\n * @owner Observable\n */\nexport function exhaust<T>(): OperatorFunction<any, T> {\n  return (source: Observable<T>) => source.lift(new SwitchFirstOperator<T>());\n}\n\nclass SwitchFirstOperator<T> implements Operator<T, T> {\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new SwitchFirstSubscriber(subscriber));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SwitchFirstSubscriber<T> extends SimpleOuterSubscriber<T, T> {\n  private hasCompleted: boolean = false;\n  private hasSubscription: boolean = false;\n\n  constructor(destination: Subscriber<T>) {\n    super(destination);\n  }\n\n  protected _next(value: T): void {\n    if (!this.hasSubscription) {\n      this.hasSubscription = true;\n      this.add(innerSubscribe(value, new SimpleInnerSubscriber(this)));\n    }\n  }\n\n  protected _complete(): void {\n    this.hasCompleted = true;\n    if (!this.hasSubscription) {\n      this.destination.complete!();\n    }\n  }\n\n  notifyComplete(): void {\n    this.hasSubscription = false;\n    if (this.hasCompleted) {\n      this.destination.complete!();\n    }\n  }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { map } from './map';\nimport { from } from '../observable/from';\nimport { SimpleOuterSubscriber, SimpleInnerSubscriber, innerSubscribe } from '../innerSubscribe';\n\n/* tslint:disable:max-line-length */\nexport function exhaustMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector is no longer supported. Use inner map instead. */\nexport function exhaustMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: undefined): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector is no longer supported. Use inner map instead. */\nexport function exhaustMap<T, I, R>(project: (value: T, index: number) => ObservableInput<I>, resultSelector: (outerValue: T, innerValue: I, outerIndex: number, innerIndex: number) => R): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable only if the previous projected Observable has completed.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link exhaust}.</span>\n *\n * ![](exhaustMap.png)\n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an (so-called \"inner\") Observable. When it projects a source value to\n * an Observable, the output Observable begins emitting the items emitted by\n * that projected Observable. However, `exhaustMap` ignores every new projected\n * Observable if the previous projected Observable has not yet completed. Once\n * that one completes, it will accept and flatten the next projected Observable\n * and repeat this process.\n *\n * ## Example\n * Run a finite timer for each click, only if there is no currently active timer\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { exhaustMap, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n *   exhaustMap(ev => interval(1000).pipe(take(5)))\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaust}\n * @see {@link mergeMap}\n * @see {@link switchMap}\n *\n * @param {function(value: T, ?index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @return {Observable} An Observable containing projected Observables\n * of each item of the source, ignoring projected Observables that start before\n * their preceding Observable has completed.\n * @method exhaustMap\n * @owner Observable\n */\nexport function exhaustMap<T, R, O extends ObservableInput<any>>(\n  project: (value: T, index: number) => O,\n  resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R,\n): OperatorFunction<T, ObservedValueOf<O>|R> {\n  if (resultSelector) {\n    // DEPRECATED PATH\n    return (source: Observable<T>) => source.pipe(\n      exhaustMap((a, i) => from(project(a, i)).pipe(\n        map((b: any, ii: any) => resultSelector(a, b, i, ii)),\n      )),\n    );\n  }\n  return (source: Observable<T>) =>\n    source.lift(new ExhaustMapOperator(project));\n}\n\nclass ExhaustMapOperator<T, R> implements Operator<T, R> {\n  constructor(private project: (value: T, index: number) => ObservableInput<R>) {\n  }\n\n  call(subscriber: Subscriber<R>, source: any): any {\n    return source.subscribe(new ExhaustMapSubscriber(subscriber, this.project));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass ExhaustMapSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n  private hasSubscription = false;\n  private hasCompleted = false;\n  private index = 0;\n\n  constructor(destination: Subscriber<R>,\n              private project: (value: T, index: number) => ObservableInput<R>) {\n    super(destination);\n  }\n\n  protected _next(value: T): void {\n    if (!this.hasSubscription) {\n      this.tryNext(value);\n    }\n  }\n\n  private tryNext(value: T): void {\n    let result: ObservableInput<R>;\n    const index = this.index++;\n    try {\n      result = this.project(value, index);\n    } catch (err) {\n      this.destination.error!(err);\n      return;\n    }\n    this.hasSubscription = true;\n    this._innerSub(result);\n  }\n\n  private _innerSub(result: ObservableInput<R>): void {\n    const innerSubscriber = new SimpleInnerSubscriber(this);\n    const destination = this.destination as Subscription;\n    destination.add(innerSubscriber);\n    const innerSubscription = innerSubscribe(result, innerSubscriber);\n    // The returned subscription will usually be the subscriber that was\n    // passed. However, interop subscribers will be wrapped and for\n    // unsubscriptions to chain correctly, the wrapper needs to be added, too.\n    if (innerSubscription !== innerSubscriber) {\n      destination.add(innerSubscription);\n    }\n  }\n\n  protected _complete(): void {\n    this.hasCompleted = true;\n    if (!this.hasSubscription) {\n      this.destination.complete!();\n    }\n    this.unsubscribe();\n  }\n\n  notifyNext(innerValue: R): void {\n    this.destination.next!(innerValue);\n  }\n\n  notifyError(err: any): void {\n    this.destination.error!(err);\n  }\n\n  notifyComplete(): void {\n    this.hasSubscription = false;\n    if (this.hasCompleted) {\n      this.destination.complete!();\n    }\n  }\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { MonoTypeOperatorFunction, OperatorFunction, ObservableInput, SchedulerLike } from '../types';\nimport { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';\n\n/* tslint:disable:max-line-length */\nexport function expand<T, R>(project: (value: T, index: number) => ObservableInput<R>, concurrent?: number, scheduler?: SchedulerLike): OperatorFunction<T, R>;\nexport function expand<T>(project: (value: T, index: number) => ObservableInput<T>, concurrent?: number, scheduler?: SchedulerLike): MonoTypeOperatorFunction<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Recursively projects each source value to an Observable which is merged in\n * the output Observable.\n *\n * <span class=\"informal\">It's similar to {@link mergeMap}, but applies the\n * projection function to every source value as well as every output value.\n * It's recursive.</span>\n *\n * ![](expand.png)\n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an Observable, and then merging those resulting Observables and\n * emitting the results of this merger. *Expand* will re-emit on the output\n * Observable every source value. Then, each output value is given to the\n * `project` function which returns an inner Observable to be merged on the\n * output Observable. Those output values resulting from the projection are also\n * given to the `project` function to produce new output values. This is how\n * *expand* behaves recursively.\n *\n * ## Example\n * Start emitting the powers of two on every click, at most 10 of them\n * ```ts\n * import { fromEvent, of } from 'rxjs';\n * import { expand, mapTo, delay, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const powersOfTwo = clicks.pipe(\n *   mapTo(1),\n *   expand(x => of(2 * x).pipe(delay(1000))),\n *   take(10),\n * );\n * powersOfTwo.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link mergeMap}\n * @see {@link mergeScan}\n *\n * @param {function(value: T, index: number) => Observable} project A function\n * that, when applied to an item emitted by the source or the output Observable,\n * returns an Observable.\n * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input\n * Observables being subscribed to concurrently.\n * @param {SchedulerLike} [scheduler=null] The {@link SchedulerLike} to use for subscribing to\n * each projected inner Observable.\n * @return {Observable} An Observable that emits the source values and also\n * result of applying the projection function to each value emitted on the\n * output Observable and and merging the results of the Observables obtained\n * from this transformation.\n * @method expand\n * @owner Observable\n */\nexport function expand<T, R>(project: (value: T, index: number) => ObservableInput<R>,\n                             concurrent: number = Number.POSITIVE_INFINITY,\n                             scheduler?: SchedulerLike): OperatorFunction<T, R> {\n  concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;\n\n  return (source: Observable<T>) => source.lift(new ExpandOperator(project, concurrent, scheduler));\n}\n\nexport class ExpandOperator<T, R> implements Operator<T, R> {\n  constructor(private project: (value: T, index: number) => ObservableInput<R>,\n              private concurrent: number,\n              private scheduler?: SchedulerLike) {\n  }\n\n  call(subscriber: Subscriber<R>, source: any): any {\n    return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));\n  }\n}\n\ninterface DispatchArg<T, R> {\n  subscriber: ExpandSubscriber<T, R>;\n  result: ObservableInput<R>;\n  value: any;\n  index: number;\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class ExpandSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n  private index: number = 0;\n  private active: number = 0;\n  private hasCompleted: boolean = false;\n  private buffer?: any[];\n\n  constructor(destination: Subscriber<R>,\n              private project: (value: T, index: number) => ObservableInput<R>,\n              private concurrent: number,\n              private scheduler?: SchedulerLike) {\n    super(destination);\n    if (concurrent < Number.POSITIVE_INFINITY) {\n      this.buffer = [];\n    }\n  }\n\n  private static dispatch<T, R>(arg: DispatchArg<T, R>): void {\n    const {subscriber, result, value, index} = arg;\n    subscriber.subscribeToProjection(result, value, index);\n  }\n\n  protected _next(value: any): void {\n    const destination = this.destination;\n\n    if (destination.closed) {\n      this._complete();\n      return;\n    }\n\n    const index = this.index++;\n    if (this.active < this.concurrent) {\n      destination.next!(value);\n      try {\n        const { project } = this;\n        const result = project(value, index);\n        if (!this.scheduler) {\n          this.subscribeToProjection(result, value, index);\n        } else {\n          const state: DispatchArg<T, R> = { subscriber: this, result, value, index };\n          const destination = this.destination as Subscription;\n          destination.add(this.scheduler.schedule<DispatchArg<T, R>>(ExpandSubscriber.dispatch as any, 0, state));\n        }\n      } catch (e) {\n        destination.error!(e);\n      }\n    } else {\n      this.buffer!.push(value);\n    }\n  }\n\n  private subscribeToProjection(result: any, value: T, index: number): void {\n    this.active++;\n    const destination = this.destination as Subscription;\n    destination.add(innerSubscribe(result, new SimpleInnerSubscriber(this)));\n  }\n\n  protected _complete(): void {\n    this.hasCompleted = true;\n    if (this.hasCompleted && this.active === 0) {\n      this.destination.complete!();\n    }\n    this.unsubscribe();\n  }\n\n  notifyNext(innerValue: R): void {\n    this._next(innerValue);\n  }\n\n  notifyComplete(): void {\n    const buffer = this.buffer;\n    this.active--;\n    if (buffer && buffer.length > 0) {\n      this._next(buffer.shift());\n    }\n    if (this.hasCompleted && this.active === 0) {\n      this.destination.complete!();\n    }\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Returns an Observable that mirrors the source Observable, but will call a specified function when\n * the source terminates on complete or error.\n * @param {function} callback Function to be called when source terminates.\n * @return {Observable} An Observable that mirrors the source, but will call the specified function on termination.\n * @method finally\n * @owner Observable\n */\nexport function finalize<T>(callback: () => void): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => source.lift(new FinallyOperator(callback));\n}\n\nclass FinallyOperator<T> implements Operator<T, T> {\n  constructor(private callback: () => void) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new FinallySubscriber(subscriber, this.callback));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass FinallySubscriber<T> extends Subscriber<T> {\n  constructor(destination: Subscriber<T>, callback: () => void) {\n    super(destination);\n    this.add(new Subscription(callback));\n  }\n}\n","import { Observable } from '../Observable';\nimport { FindValueOperator } from '../operators/find';\nimport { OperatorFunction } from '../types';\n/**\n * Emits only the index of the first value emitted by the source Observable that\n * meets some condition.\n *\n * <span class=\"informal\">It's like {@link find}, but emits the index of the\n * found value, not the value itself.</span>\n *\n * ![](findIndex.png)\n *\n * `findIndex` searches for the first item in the source Observable that matches\n * the specified condition embodied by the `predicate`, and returns the\n * (zero-based) index of the first occurrence in the source. Unlike\n * {@link first}, the `predicate` is required in `findIndex`, and does not emit\n * an error if a valid value is not found.\n *\n * ## Example\n * Emit the index of first click that happens on a DIV element\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { findIndex } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(findIndex(ev => ev.target.tagName === 'DIV'));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link filter}\n * @see {@link find}\n * @see {@link first}\n * @see {@link take}\n *\n * @param {function(value: T, index: number, source: Observable<T>): boolean} predicate\n * A function called with each item to test for condition matching.\n * @param {any} [thisArg] An optional argument to determine the value of `this`\n * in the `predicate` function.\n * @return {Observable} An Observable of the index of the first item that\n * matches the condition.\n * @method find\n * @owner Observable\n */\nexport function findIndex<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean,\n                             thisArg?: any): OperatorFunction<T, number> {\n  return (source: Observable<T>) => source.lift(new FindValueOperator(predicate, source, true, thisArg)) as Observable<any>;\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { EmptyError } from '../util/EmptyError';\nimport { OperatorFunction } from '../../internal/types';\nimport { filter } from './filter';\nimport { take } from './take';\nimport { defaultIfEmpty } from './defaultIfEmpty';\nimport { throwIfEmpty } from './throwIfEmpty';\nimport { identity } from '../util/identity';\n\n/* tslint:disable:max-line-length */\nexport function first<T, D = T>(\n  predicate?: null,\n  defaultValue?: D\n): OperatorFunction<T, T | D>;\nexport function first<T, S extends T>(\n  predicate: (value: T, index: number, source: Observable<T>) => value is S,\n  defaultValue?: S\n): OperatorFunction<T, S>;\nexport function first<T, D = T>(\n  predicate: (value: T, index: number, source: Observable<T>) => boolean,\n  defaultValue?: D\n): OperatorFunction<T, T | D>;\n/* tslint:enable:max-line-length */\n\n/**\n * Emits only the first value (or the first value that meets some condition)\n * emitted by the source Observable.\n *\n * <span class=\"informal\">Emits only the first value. Or emits only the first\n * value that passes some test.</span>\n *\n * ![](first.png)\n *\n * If called with no arguments, `first` emits the first value of the source\n * Observable, then completes. If called with a `predicate` function, `first`\n * emits the first value of the source that matches the specified condition. It\n * may also take a deprecated `resultSelector` function to produce the output\n * value from the input value, and a `defaultValue` to emit in case the source\n * completes before it is able to emit a valid value. Throws an error if\n * `defaultValue` was not provided and a matching element is not found.\n *\n * ## Examples\n * Emit only the first click that happens on the DOM\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { first } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(first());\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Emits the first click that happens on a DIV\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { first } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(first(ev => ev.target.tagName === 'DIV'));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link filter}\n * @see {@link find}\n * @see {@link take}\n *\n * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`\n * callback if the Observable completes before any `next` notification was sent.\n *\n * @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]\n * An optional function called with each item to test for condition matching.\n * @param {R} [defaultValue] The default value emitted in case no valid value\n * was found on the source.\n * @return {Observable<T|R>} An Observable of the first item that matches the\n * condition.\n * @method first\n * @owner Observable\n */\nexport function first<T, D>(\n  predicate?: ((value: T, index: number, source: Observable<T>) => boolean) | null,\n  defaultValue?: D\n): OperatorFunction<T, T | D> {\n  const hasDefaultValue = arguments.length >= 2;\n  return (source: Observable<T>) => source.pipe(\n    predicate ? filter((v, i) => predicate(v, i, source)) : identity,\n    take(1),\n    hasDefaultValue ? defaultIfEmpty<T | D>(defaultValue) : throwIfEmpty(() => new EmptyError()),\n  );\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction } from '../types';\n\n/**\n * Ignores all items emitted by the source Observable and only passes calls of `complete` or `error`.\n *\n * ![](ignoreElements.png)\n *\n * ## Examples\n * ### Ignores emitted values, reacts to observable's completion.\n * ```ts\n * import { of } from 'rxjs';\n * import { ignoreElements } from 'rxjs/operators';\n *\n * of('you', 'talking', 'to', 'me').pipe(\n *   ignoreElements(),\n * )\n * .subscribe(\n *   word => console.log(word),\n *   err => console.log('error:', err),\n *   () => console.log('the end'),\n * );\n * // result:\n * // 'the end'\n * ```\n * @return {Observable} An empty Observable that only calls `complete`\n * or `error`, based on which one is called by the source Observable.\n * @method ignoreElements\n * @owner Observable\n */\nexport function ignoreElements(): OperatorFunction<any, never> {\n  return function ignoreElementsOperatorFunction(source: Observable<any>) {\n    return source.lift(new IgnoreElementsOperator());\n  };\n}\n\nclass IgnoreElementsOperator<T, R> implements Operator<T, R> {\n  call(subscriber: Subscriber<R>, source: any): any {\n    return source.subscribe(new IgnoreElementsSubscriber(subscriber));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass IgnoreElementsSubscriber<T> extends Subscriber<T> {\n  protected _next(unused: T): void {\n    // Do nothing\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OperatorFunction } from '../types';\n\n/**\n * Emits false if the input observable emits any values, or emits true if the\n * input observable completes without emitting any values.\n *\n * <span class=\"informal\">Tells whether any values are emitted by an observable</span>\n *\n * ![](isEmpty.png)\n *\n * `isEmpty` transforms an Observable that emits values into an Observable that\n * emits a single boolean value representing whether or not any values were\n * emitted by the source Observable. As soon as the source Observable emits a\n * value, `isEmpty` will emit a `false` and complete.  If the source Observable\n * completes having not emitted anything, `isEmpty` will emit a `true` and\n * complete.\n *\n * A similar effect could be achieved with {@link count}, but `isEmpty` can emit\n * a `false` value sooner.\n *\n * ## Examples\n *\n * Emit `false` for a non-empty Observable\n * ```javascript\n * import { Subject } from 'rxjs';\n * import { isEmpty } from 'rxjs/operators';\n *\n * const source = new Subject<string>();\n * const result = source.pipe(isEmpty());\n * source.subscribe(x => console.log(x));\n * result.subscribe(x => console.log(x));\n * source.next('a');\n * source.next('b');\n * source.next('c');\n * source.complete();\n *\n * // Results in:\n * // a\n * // false\n * // b\n * // c\n * ```\n *\n * Emit `true` for an empty Observable\n * ```javascript\n * import { EMPTY } from 'rxjs';\n * import { isEmpty } from 'rxjs/operators';\n *\n * const result = EMPTY.pipe(isEmpty());\n * result.subscribe(x => console.log(x));\n * // Results in:\n * // true\n * ```\n *\n * @see {@link count}\n * @see {@link EMPTY}\n *\n * @return {OperatorFunction<T, boolean>} An Observable of a boolean value indicating whether observable was empty or not\n * @method isEmpty\n * @owner Observable\n */\n\nexport function isEmpty<T>(): OperatorFunction<T, boolean> {\n  return (source: Observable<T>) => source.lift(new IsEmptyOperator());\n}\n\nclass IsEmptyOperator implements Operator<any, boolean> {\n  call (observer: Subscriber<boolean>, source: any): any {\n    return source.subscribe(new IsEmptySubscriber(observer));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass IsEmptySubscriber extends Subscriber<any> {\n  constructor(destination: Subscriber<boolean>) {\n    super(destination);\n  }\n\n  private notifyComplete(isEmpty: boolean): void {\n    const destination = this.destination;\n\n    destination.next(isEmpty);\n    destination.complete();\n  }\n\n  protected _next(value: boolean) {\n    this.notifyComplete(false);\n  }\n\n  protected _complete() {\n    this.notifyComplete(true);\n  }\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { EmptyError } from '../util/EmptyError';\nimport { OperatorFunction } from '../../internal/types';\nimport { filter } from './filter';\nimport { takeLast } from './takeLast';\nimport { throwIfEmpty } from './throwIfEmpty';\nimport { defaultIfEmpty } from './defaultIfEmpty';\nimport { identity } from '../util/identity';\n\n/* tslint:disable:max-line-length */\nexport function last<T, D = T>(\n  predicate?: null,\n  defaultValue?: D\n): OperatorFunction<T, T | D>;\nexport function last<T, S extends T>(\n  predicate: (value: T, index: number, source: Observable<T>) => value is S,\n  defaultValue?: S\n): OperatorFunction<T, S>;\nexport function last<T, D = T>(\n  predicate: (value: T, index: number, source: Observable<T>) => boolean,\n  defaultValue?: D\n): OperatorFunction<T, T | D>;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns an Observable that emits only the last item emitted by the source Observable.\n * It optionally takes a predicate function as a parameter, in which case, rather than emitting\n * the last item from the source Observable, the resulting Observable will emit the last item\n * from the source Observable that satisfies the predicate.\n *\n * ![](last.png)\n *\n * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`\n * callback if the Observable completes before any `next` notification was sent.\n * @param {function} [predicate] - The condition any source emitted item has to satisfy.\n * @param {any} [defaultValue] - An optional default value to provide if last\n * predicate isn't met or no values were emitted.\n * @return {Observable} An Observable that emits only the last item satisfying the given condition\n * from the source, or an NoSuchElementException if no such items are emitted.\n * @throws - Throws if no items that match the predicate are emitted by the source Observable.\n */\nexport function last<T, D>(\n  predicate?: ((value: T, index: number, source: Observable<T>) => boolean) | null,\n  defaultValue?: D\n): OperatorFunction<T, T | D> {\n  const hasDefaultValue = arguments.length >= 2;\n  return (source: Observable<T>) => source.pipe(\n    predicate ? filter((v, i) => predicate(v, i, source)) : identity,\n    takeLast(1),\n    hasDefaultValue ? defaultIfEmpty<T | D>(defaultValue) : throwIfEmpty(() => new EmptyError()),\n  );\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OperatorFunction } from '../types';\n\n/**\n * Emits the given constant value on the output Observable every time the source\n * Observable emits a value.\n *\n * <span class=\"informal\">Like {@link map}, but it maps every source value to\n * the same output value every time.</span>\n *\n * ![](mapTo.png)\n *\n * Takes a constant `value` as argument, and emits that whenever the source\n * Observable emits a value. In other words, ignores the actual source value,\n * and simply uses the emission moment to know when to emit the given `value`.\n *\n * ## Example\n * Map every click to the string 'Hi'\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { mapTo } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const greetings = clicks.pipe(mapTo('Hi'));\n * greetings.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link map}\n *\n * @param {any} value The value to map each source value to.\n * @return {Observable} An Observable that emits the given `value` every time\n * the source Observable emits something.\n * @method mapTo\n * @owner Observable\n */\nexport function mapTo<T, R>(value: R): OperatorFunction<T, R> {\n  return (source: Observable<T>) => source.lift(new MapToOperator(value));\n}\n\nclass MapToOperator<T, R> implements Operator<T, R> {\n\n  value: R;\n\n  constructor(value: R) {\n    this.value = value;\n  }\n\n  call(subscriber: Subscriber<R>, source: any): any {\n    return source.subscribe(new MapToSubscriber(subscriber, this.value));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass MapToSubscriber<T, R> extends Subscriber<T> {\n\n  value: R;\n\n  constructor(destination: Subscriber<R>, value: R) {\n    super(destination);\n    this.value = value;\n  }\n\n  protected _next(x: T) {\n    this.destination.next(this.value);\n  }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Notification } from '../Notification';\nimport { OperatorFunction } from '../types';\n\n/**\n * Represents all of the notifications from the source Observable as `next`\n * emissions marked with their original types within {@link Notification}\n * objects.\n *\n * <span class=\"informal\">Wraps `next`, `error` and `complete` emissions in\n * {@link Notification} objects, emitted as `next` on the output Observable.\n * </span>\n *\n * ![](materialize.png)\n *\n * `materialize` returns an Observable that emits a `next` notification for each\n * `next`, `error`, or `complete` emission of the source Observable. When the\n * source Observable emits `complete`, the output Observable will emit `next` as\n * a Notification of type \"complete\", and then it will emit `complete` as well.\n * When the source Observable emits `error`, the output will emit `next` as a\n * Notification of type \"error\", and then `complete`.\n *\n * This operator is useful for producing metadata of the source Observable, to\n * be consumed as `next` emissions. Use it in conjunction with\n * {@link dematerialize}.\n *\n * ## Example\n * Convert a faulty Observable to an Observable of Notifications\n * ```ts\n * import { of } from 'rxjs';\n * import { materialize, map } from 'rxjs/operators';\n *\n * const letters = of('a', 'b', 13, 'd');\n * const upperCase = letters.pipe(map(x => x.toUpperCase()));\n * const materialized = upperCase.pipe(materialize());\n * materialized.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // - Notification {kind: \"N\", value: \"A\", error: undefined, hasValue: true}\n * // - Notification {kind: \"N\", value: \"B\", error: undefined, hasValue: true}\n * // - Notification {kind: \"E\", value: undefined, error: TypeError:\n * //   x.toUpperCase is not a function at MapSubscriber.letters.map.x\n * //   [as project] (http://1…, hasValue: false}\n * ```\n *\n * @see {@link Notification}\n * @see {@link dematerialize}\n *\n * @return {Observable<Notification<T>>} An Observable that emits\n * {@link Notification} objects that wrap the original emissions from the source\n * Observable with metadata.\n * @method materialize\n * @owner Observable\n */\nexport function materialize<T>(): OperatorFunction<T, Notification<T>> {\n  return function materializeOperatorFunction(source: Observable<T>) {\n    return source.lift(new MaterializeOperator());\n  };\n}\n\nclass MaterializeOperator<T> implements Operator<T, Notification<T>> {\n  call(subscriber: Subscriber<Notification<T>>, source: any): any {\n    return source.subscribe(new MaterializeSubscriber(subscriber));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass MaterializeSubscriber<T> extends Subscriber<T> {\n  constructor(destination: Subscriber<Notification<T>>) {\n    super(destination);\n  }\n\n  protected _next(value: T) {\n    this.destination.next(Notification.createNext(value));\n  }\n\n  protected _error(err: any) {\n    const destination = this.destination;\n    destination.next(Notification.createError(err));\n    destination.complete();\n  }\n\n  protected _complete() {\n    const destination = this.destination;\n    destination.next(Notification.createComplete());\n    destination.complete();\n  }\n}\n","import { reduce } from './reduce';\nimport { MonoTypeOperatorFunction } from '../types';\n\n/**\n * The Max operator operates on an Observable that emits numbers (or items that can be compared with a provided function),\n * and when source Observable completes it emits a single item: the item with the largest value.\n *\n * ![](max.png)\n *\n * ## Examples\n * Get the maximal value of a series of numbers\n * ```ts\n * import { of } from 'rxjs';\n * import { max } from 'rxjs/operators';\n *\n * of(5, 4, 7, 2, 8).pipe(\n *   max(),\n * )\n * .subscribe(x => console.log(x)); // -> 8\n * ```\n *\n * Use a comparer function to get the maximal item\n * ```typescript\n * import { of } from 'rxjs';\n * import { max } from 'rxjs/operators';\n *\n * interface Person {\n *   age: number,\n *   name: string\n * }\n * of<Person>(\n *   {age: 7, name: 'Foo'},\n *   {age: 5, name: 'Bar'},\n *   {age: 9, name: 'Beer'},\n * ).pipe(\n *   max<Person>((a: Person, b: Person) => a.age < b.age ? -1 : 1),\n * )\n * .subscribe((x: Person) => console.log(x.name)); // -> 'Beer'\n * ```\n *\n * @see {@link min}\n *\n * @param {Function} [comparer] - Optional comparer function that it will use instead of its default to compare the\n * value of two items.\n * @return {Observable} An Observable that emits item with the largest value.\n * @method max\n * @owner Observable\n */\nexport function max<T>(comparer?: (x: T, y: T) => number): MonoTypeOperatorFunction<T> {\n  const max: (x: T, y: T) => T = (typeof comparer === 'function')\n    ? (x, y) => comparer(x, y) > 0 ? x : y\n    : (x, y) => x > y ? x : y;\n\n  return reduce(max);\n}\n","import { merge as mergeStatic } from '../observable/merge';\nimport { Observable } from '../Observable';\nimport { ObservableInput, OperatorFunction, MonoTypeOperatorFunction, SchedulerLike } from '../types';\n\n/* tslint:disable:max-line-length */\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge<T>(scheduler?: SchedulerLike): MonoTypeOperatorFunction<T>;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge<T>(concurrent?: number, scheduler?: SchedulerLike): MonoTypeOperatorFunction<T>;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge<T, T2>(v2: ObservableInput<T2>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2>;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge<T, T2>(v2: ObservableInput<T2>, concurrent?: number, scheduler?: SchedulerLike): OperatorFunction<T, T | T2>;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge<T, T2, T3>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3>;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge<T, T2, T3>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, concurrent?: number, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3>;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge<T, T2, T3, T4>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3 | T4>;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge<T, T2, T3, T4>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, concurrent?: number, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3 | T4>;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge<T, T2, T3, T4, T5>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3 | T4 | T5>;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge<T, T2, T3, T4, T5>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, concurrent?: number, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3 | T4 | T5>;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge<T, T2, T3, T4, T5, T6>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3 | T4 | T5 | T6>;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge<T, T2, T3, T4, T5, T6>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>, concurrent?: number, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3 | T4 | T5 | T6>;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge<T>(...observables: Array<ObservableInput<T> | SchedulerLike | number>): MonoTypeOperatorFunction<T>;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge<T, R>(...observables: Array<ObservableInput<any> | SchedulerLike | number>): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * @deprecated Deprecated in favor of static {@link merge}.\n */\nexport function merge<T, R>(...observables: Array<ObservableInput<any> | SchedulerLike | number>): OperatorFunction<T, R> {\n  return (source: Observable<T>) => source.lift.call(mergeStatic(source, ...observables));\n}\n","import { Observable } from '../Observable';\nimport { OperatorFunction, ObservedValueOf } from '../../internal/types';\nimport { mergeMap } from './mergeMap';\nimport { ObservableInput } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function mergeMapTo<T, O extends ObservableInput<any>>(innerObservable: O, concurrent?: number): OperatorFunction<any, ObservedValueOf<O>>;\n/** @deprecated */\nexport function mergeMapTo<T, R, O extends ObservableInput<any>>(innerObservable: O, resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R, concurrent?: number): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to the same Observable which is merged multiple\n * times in the output Observable.\n *\n * <span class=\"informal\">It's like {@link mergeMap}, but maps each value always\n * to the same inner Observable.</span>\n *\n * ![](mergeMapTo.png)\n *\n * Maps each source value to the given Observable `innerObservable` regardless\n * of the source value, and then merges those resulting Observables into one\n * single Observable, which is the output Observable.\n *\n * ## Example\n * For each click event, start an interval Observable ticking every 1 second\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { mergeMapTo } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(mergeMapTo(interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMapTo}\n * @see {@link merge}\n * @see {@link mergeAll}\n * @see {@link mergeMap}\n * @see {@link mergeScan}\n * @see {@link switchMapTo}\n *\n * @param {ObservableInput} innerObservable An Observable to replace each value from\n * the source Observable.\n * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input\n * Observables being subscribed to concurrently.\n * @return {Observable} An Observable that emits items from the given\n * `innerObservable`\n * @method mergeMapTo\n * @owner Observable\n */\nexport function mergeMapTo<T, R, O extends ObservableInput<any>>(\n  innerObservable: O,\n  resultSelector?: ((outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R) | number,\n  concurrent: number = Number.POSITIVE_INFINITY\n): OperatorFunction<T, ObservedValueOf<O>|R> {\n  if (typeof resultSelector === 'function') {\n    return mergeMap(() => innerObservable, resultSelector, concurrent);\n  }\n  if (typeof resultSelector === 'number') {\n    concurrent = resultSelector;\n  }\n  return mergeMap(() => innerObservable, concurrent);\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { ObservableInput, OperatorFunction } from '../types';\nimport { SimpleOuterSubscriber, SimpleInnerSubscriber, innerSubscribe } from '../innerSubscribe';\n\n/**\n * Applies an accumulator function over the source Observable where the\n * accumulator function itself returns an Observable, then each intermediate\n * Observable returned is merged into the output Observable.\n *\n * <span class=\"informal\">It's like {@link scan}, but the Observables returned\n * by the accumulator are merged into the outer Observable.</span>\n *\n * ## Example\n * Count the number of click events\n * ```ts\n * import { fromEvent, of } from 'rxjs';\n * import { mapTo, mergeScan } from 'rxjs/operators';\n *\n * const click$ = fromEvent(document, 'click');\n * const one$ = click$.pipe(mapTo(1));\n * const seed = 0;\n * const count$ = one$.pipe(\n *   mergeScan((acc, one) => of(acc + one), seed),\n * );\n * count$.subscribe(x => console.log(x));\n *\n * // Results:\n * // 1\n * // 2\n * // 3\n * // 4\n * // ...and so on for each click\n * ```\n *\n * @param {function(acc: R, value: T): Observable<R>} accumulator\n * The accumulator function called on each source value.\n * @param seed The initial accumulation value.\n * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of\n * input Observables being subscribed to concurrently.\n * @return {Observable<R>} An observable of the accumulated values.\n * @method mergeScan\n * @owner Observable\n */\nexport function mergeScan<T, R>(accumulator: (acc: R, value: T, index: number) => ObservableInput<R>,\n                                seed: R,\n                                concurrent: number = Number.POSITIVE_INFINITY): OperatorFunction<T, R> {\n  return (source: Observable<T>) => source.lift(new MergeScanOperator(accumulator, seed, concurrent));\n}\n\nexport class MergeScanOperator<T, R> implements Operator<T, R> {\n  constructor(private accumulator: (acc: R, value: T, index: number) => ObservableInput<R>,\n              private seed: R,\n              private concurrent: number) {\n  }\n\n  call(subscriber: Subscriber<R>, source: any): any {\n    return source.subscribe(new MergeScanSubscriber(\n      subscriber, this.accumulator, this.seed, this.concurrent\n    ));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class MergeScanSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n  private hasValue: boolean = false;\n  private hasCompleted: boolean = false;\n  private buffer: Observable<any>[] = [];\n  private active: number = 0;\n  protected index: number = 0;\n\n  constructor(destination: Subscriber<R>,\n              private accumulator: (acc: R, value: T, index: number) => ObservableInput<R>,\n              private acc: R,\n              private concurrent: number) {\n    super(destination);\n  }\n\n  protected _next(value: any): void {\n    if (this.active < this.concurrent) {\n      const index = this.index++;\n      const destination = this.destination;\n      let ish;\n      try {\n        const { accumulator } = this;\n        ish = accumulator(this.acc, value, index);\n      } catch (e) {\n        return destination.error!(e);\n      }\n      this.active++;\n      this._innerSub(ish);\n    } else {\n      this.buffer.push(value);\n    }\n  }\n\n  private _innerSub(ish: any): void {\n    const innerSubscriber = new SimpleInnerSubscriber(this);\n    const destination = this.destination as Subscription;\n    destination.add(innerSubscriber);\n    const innerSubscription = innerSubscribe(ish, innerSubscriber);\n    // The returned subscription will usually be the subscriber that was\n    // passed. However, interop subscribers will be wrapped and for\n    // unsubscriptions to chain correctly, the wrapper needs to be added, too.\n    if (innerSubscription !== innerSubscriber) {\n      destination.add(innerSubscription);\n    }\n  }\n\n  protected _complete(): void {\n    this.hasCompleted = true;\n    if (this.active === 0 && this.buffer.length === 0) {\n      if (this.hasValue === false) {\n        this.destination.next!(this.acc);\n      }\n      this.destination.complete!();\n    }\n    this.unsubscribe();\n  }\n\n  notifyNext(innerValue: R): void {\n    const { destination } = this;\n    this.acc = innerValue;\n    this.hasValue = true;\n    destination.next!(innerValue);\n  }\n\n  notifyComplete(): void {\n    const buffer = this.buffer;\n    this.active--;\n    if (buffer.length > 0) {\n      this._next(buffer.shift());\n    } else if (this.active === 0 && this.hasCompleted) {\n      if (this.hasValue === false) {\n        this.destination.next!(this.acc);\n      }\n      this.destination.complete!();\n    }\n  }\n}\n","import { reduce } from './reduce';\nimport { MonoTypeOperatorFunction } from '../types';\n\n/**\n * The Min operator operates on an Observable that emits numbers (or items that can be compared with a provided function),\n * and when source Observable completes it emits a single item: the item with the smallest value.\n *\n * ![](min.png)\n *\n * ## Examples\n * Get the minimal value of a series of numbers\n * ```ts\n * import { of } from 'rxjs';\n * import { min } from 'rxjs/operators';\n *\n * of(5, 4, 7, 2, 8).pipe(\n *   min(),\n * )\n * .subscribe(x => console.log(x)); // -> 2\n * ```\n *\n * Use a comparer function to get the minimal item\n * ```typescript\n * import { of } from 'rxjs';\n * import { min } from 'rxjs/operators';\n *\n * interface Person {\n *   age: number,\n *   name: string\n * }\n * of<Person>(\n *   {age: 7, name: 'Foo'},\n *   {age: 5, name: 'Bar'},\n *   {age: 9, name: 'Beer'},\n * ).pipe(\n *   min<Person>( (a: Person, b: Person) => a.age < b.age ? -1 : 1),\n * )\n * .subscribe((x: Person) => console.log(x.name)); // -> 'Bar'\n * ```\n * @see {@link max}\n *\n * @param {Function} [comparer] - Optional comparer function that it will use instead of its default to compare the\n * value of two items.\n * @return {Observable<R>} An Observable that emits item with the smallest value.\n * @method min\n * @owner Observable\n */\nexport function min<T>(comparer?: (x: T, y: T) => number): MonoTypeOperatorFunction<T> {\n  const min: (x: T, y: T) => T = (typeof comparer === 'function')\n    ? (x, y) => comparer(x, y) < 0 ? x : y\n    : (x, y) => x < y ? x : y;\n  return reduce(min);\n}\n","import { Observable } from '../Observable';\nimport { from } from '../observable/from';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { isArray } from '../util/isArray';\nimport { ObservableInput, OperatorFunction } from '../types';\nimport { SimpleOuterSubscriber, SimpleInnerSubscriber, innerSubscribe } from '../innerSubscribe';\n\n/* tslint:disable:max-line-length */\nexport function onErrorResumeNext<T>(): OperatorFunction<T, T>;\nexport function onErrorResumeNext<T, T2>(v: ObservableInput<T2>): OperatorFunction<T, T | T2>;\nexport function onErrorResumeNext<T, T2, T3>(v: ObservableInput<T2>, v2: ObservableInput<T3>): OperatorFunction<T, T | T2 | T3>;\nexport function onErrorResumeNext<T, T2, T3, T4>(v: ObservableInput<T2>, v2: ObservableInput<T3>, v3: ObservableInput<T4>): OperatorFunction<T, T | T2 | T3 | T4>;\nexport function onErrorResumeNext<T, T2, T3, T4, T5>(v: ObservableInput<T2>, v2: ObservableInput<T3>, v3: ObservableInput<T4>, v4: ObservableInput<T5>): OperatorFunction<T, T | T2 | T3 | T4 | T5>;\nexport function onErrorResumeNext<T, T2, T3, T4, T5, T6>(v: ObservableInput<T2>, v2: ObservableInput<T3>, v3: ObservableInput<T4>, v4: ObservableInput<T5>, v5: ObservableInput<T6>): OperatorFunction<T, T | T2 | T3 | T4 | T5 | T6>;\nexport function onErrorResumeNext<T, T2, T3, T4, T5, T6, T7>(v: ObservableInput<T2>, v2: ObservableInput<T3>, v3: ObservableInput<T4>, v4: ObservableInput<T5>, v5: ObservableInput<T6>, v6: ObservableInput<T7>): OperatorFunction<T, T | T2 | T3 | T4 | T5 | T6 | T7>;\nexport function onErrorResumeNext<T, R>(...observables: Array<ObservableInput<any>>): OperatorFunction<T, T | R>;\nexport function onErrorResumeNext<T, R>(array: ObservableInput<any>[]): OperatorFunction<T, T | R>;\n/* tslint:enable:max-line-length */\n\n/**\n * When any of the provided Observable emits an complete or error notification, it immediately subscribes to the next one\n * that was passed.\n *\n * <span class=\"informal\">Execute series of Observables no matter what, even if it means swallowing errors.</span>\n *\n * ![](onErrorResumeNext.png)\n *\n * `onErrorResumeNext` is an operator that accepts a series of Observables, provided either directly as\n * arguments or as an array. If no single Observable is provided, returned Observable will simply behave the same\n * as the source.\n *\n * `onErrorResumeNext` returns an Observable that starts by subscribing and re-emitting values from the source Observable.\n * When its stream of values ends - no matter if Observable completed or emitted an error - `onErrorResumeNext`\n * will subscribe to the first Observable that was passed as an argument to the method. It will start re-emitting\n * its values as well and - again - when that stream ends, `onErrorResumeNext` will proceed to subscribing yet another\n * Observable in provided series, no matter if previous Observable completed or ended with an error. This will\n * be happening until there is no more Observables left in the series, at which point returned Observable will\n * complete - even if the last subscribed stream ended with an error.\n *\n * `onErrorResumeNext` can be therefore thought of as version of {@link concat} operator, which is more permissive\n * when it comes to the errors emitted by its input Observables. While `concat` subscribes to the next Observable\n * in series only if previous one successfully completed, `onErrorResumeNext` subscribes even if it ended with\n * an error.\n *\n * Note that you do not get any access to errors emitted by the Observables. In particular do not\n * expect these errors to appear in error callback passed to {@link Observable#subscribe}. If you want to take\n * specific actions based on what error was emitted by an Observable, you should try out {@link catchError} instead.\n *\n *\n * ## Example\n * Subscribe to the next Observable after map fails\n * ```ts\n * import { of } from 'rxjs';\n * import { onErrorResumeNext, map } from 'rxjs/operators';\n *\n * of(1, 2, 3, 0).pipe(\n *   map(x => {\n *       if (x === 0) { throw Error(); }\n *        return 10 / x;\n *   }),\n *   onErrorResumeNext(of(1, 2, 3)),\n * )\n * .subscribe(\n *   val => console.log(val),\n *   err => console.log(err),          // Will never be called.\n *   () => console.log('that\\'s it!')\n * );\n *\n * // Logs:\n * // 10\n * // 5\n * // 3.3333333333333335\n * // 1\n * // 2\n * // 3\n * // \"that's it!\"\n * ```\n *\n * @see {@link concat}\n * @see {@link catchError}\n *\n * @param {...ObservableInput} observables Observables passed either directly or as an array.\n * @return {Observable} An Observable that emits values from source Observable, but - if it errors - subscribes\n * to the next passed Observable and so on, until it completes or runs out of Observables.\n * @method onErrorResumeNext\n * @owner Observable\n */\n\nexport function onErrorResumeNext<T, R>(...nextSources: Array<ObservableInput<any> |\n                                                       Array<ObservableInput<any>>>): OperatorFunction<T, R> {\n  if (nextSources.length === 1 && isArray(nextSources[0])) {\n    nextSources = <Array<Observable<any>>>nextSources[0];\n  }\n\n  return (source: Observable<T>) => source.lift(new OnErrorResumeNextOperator<T, R>(nextSources));\n}\n\n/* tslint:disable:max-line-length */\nexport function onErrorResumeNextStatic<R>(v: ObservableInput<R>): Observable<R>;\nexport function onErrorResumeNextStatic<T2, T3, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>): Observable<R>;\nexport function onErrorResumeNextStatic<T2, T3, T4, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>): Observable<R>;\nexport function onErrorResumeNextStatic<T2, T3, T4, T5, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>): Observable<R>;\nexport function onErrorResumeNextStatic<T2, T3, T4, T5, T6, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>): Observable<R>;\n\nexport function onErrorResumeNextStatic<R>(...observables: Array<ObservableInput<any> | ((...values: Array<any>) => R)>): Observable<R>;\nexport function onErrorResumeNextStatic<R>(array: ObservableInput<any>[]): Observable<R>;\n/* tslint:enable:max-line-length */\n\nexport function onErrorResumeNextStatic<T, R>(...nextSources: Array<ObservableInput<any> |\n  Array<ObservableInput<any>> |\n  ((...values: Array<any>) => R)>): Observable<R> {\n  let source: ObservableInput<any>|undefined = undefined;\n\n  if (nextSources.length === 1 && isArray(nextSources[0])) {\n    nextSources = nextSources[0] as ObservableInput<any>[];\n  }\n  // TODO: resolve issue with passing no arguments.\n  source = nextSources.shift()!;\n\n  return from(source).lift(new OnErrorResumeNextOperator<T, R>(nextSources));\n}\n\nclass OnErrorResumeNextOperator<T, R> implements Operator<T, R> {\n  constructor(private nextSources: Array<ObservableInput<any>>) {\n  }\n\n  call(subscriber: Subscriber<R>, source: any): any {\n    return source.subscribe(new OnErrorResumeNextSubscriber(subscriber, this.nextSources));\n  }\n}\n\nclass OnErrorResumeNextSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n  constructor(protected destination: Subscriber<T>,\n              private nextSources: Array<ObservableInput<any>>) {\n    super(destination);\n  }\n\n  notifyError(): void {\n    this.subscribeToNextSource();\n  }\n\n  notifyComplete(): void {\n    this.subscribeToNextSource();\n  }\n\n  protected _error(err: any): void {\n    this.subscribeToNextSource();\n    this.unsubscribe();\n  }\n\n  protected _complete(): void {\n    this.subscribeToNextSource();\n    this.unsubscribe();\n  }\n\n  private subscribeToNextSource(): void {\n    const next = this.nextSources.shift();\n    if (!!next) {\n      const innerSubscriber = new SimpleInnerSubscriber(this);\n      const destination = this.destination as Subscription;\n      destination.add(innerSubscriber);\n      const innerSubscription = innerSubscribe(next, innerSubscriber);\n      // The returned subscription will usually be the subscriber that was\n      // passed. However, interop subscribers will be wrapped and for\n      // unsubscriptions to chain correctly, the wrapper needs to be added, too.\n      if (innerSubscription !== innerSubscriber) {\n        destination.add(innerSubscription);\n      }\n    } else {\n      this.destination.complete();\n    }\n  }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction } from '../types';\n\n/**\n * Groups pairs of consecutive emissions together and emits them as an array of\n * two values.\n *\n * <span class=\"informal\">Puts the current value and previous value together as\n * an array, and emits that.</span>\n *\n * ![](pairwise.png)\n *\n * The Nth emission from the source Observable will cause the output Observable\n * to emit an array [(N-1)th, Nth] of the previous and the current value, as a\n * pair. For this reason, `pairwise` emits on the second and subsequent\n * emissions from the source Observable, but not on the first emission, because\n * there is no previous value in that case.\n *\n * ## Example\n * On every click (starting from the second), emit the relative distance to the previous click\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { pairwise, map } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const pairs = clicks.pipe(pairwise());\n * const distance = pairs.pipe(\n *   map(pair => {\n *     const x0 = pair[0].clientX;\n *     const y0 = pair[0].clientY;\n *     const x1 = pair[1].clientX;\n *     const y1 = pair[1].clientY;\n *     return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));\n *   }),\n * );\n * distance.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link buffer}\n * @see {@link bufferCount}\n *\n * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of\n * consecutive values from the source Observable.\n * @method pairwise\n * @owner Observable\n */\nexport function pairwise<T>(): OperatorFunction<T, [T, T]> {\n  return (source: Observable<T>) => source.lift(new PairwiseOperator());\n}\n\nclass PairwiseOperator<T> implements Operator<T, [T, T]> {\n  call(subscriber: Subscriber<[T, T]>, source: any): any {\n    return source.subscribe(new PairwiseSubscriber(subscriber));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass PairwiseSubscriber<T> extends Subscriber<T> {\n  private prev: T;\n  private hasPrev: boolean = false;\n\n  constructor(destination: Subscriber<[T, T]>) {\n    super(destination);\n  }\n\n  _next(value: T): void {\n    let pair: [T, T] | undefined;\n\n    if (this.hasPrev) {\n      pair = [this.prev, value];\n    } else {\n      this.hasPrev = true;\n    }\n\n    this.prev = value;\n\n    if (pair) {\n      this.destination.next(pair);\n    }\n  }\n}\n","import { not } from '../util/not';\nimport { filter } from './filter';\nimport { Observable } from '../Observable';\nimport { UnaryFunction } from '../types';\n\n/**\n * Splits the source Observable into two, one with values that satisfy a\n * predicate, and another with values that don't satisfy the predicate.\n *\n * <span class=\"informal\">It's like {@link filter}, but returns two Observables:\n * one like the output of {@link filter}, and the other with values that did not\n * pass the condition.</span>\n *\n * ![](partition.png)\n *\n * `partition` outputs an array with two Observables that partition the values\n * from the source Observable through the given `predicate` function. The first\n * Observable in that array emits source values for which the predicate argument\n * returns true. The second Observable emits source values for which the\n * predicate returns false. The first behaves like {@link filter} and the second\n * behaves like {@link filter} with the predicate negated.\n *\n * ## Example\n * Partition click events into those on DIV elements and those elsewhere\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { partition } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const parts = clicks.pipe(partition(ev => ev.target.tagName === 'DIV'));\n * const clicksOnDivs = parts[0];\n * const clicksElsewhere = parts[1];\n * clicksOnDivs.subscribe(x => console.log('DIV clicked: ', x));\n * clicksElsewhere.subscribe(x => console.log('Other clicked: ', x));\n * ```\n *\n * @see {@link filter}\n *\n * @param {function(value: T, index: number): boolean} predicate A function that\n * evaluates each value emitted by the source Observable. If it returns `true`,\n * the value is emitted on the first Observable in the returned array, if\n * `false` the value is emitted on the second Observable in the array. The\n * `index` parameter is the number `i` for the i-th source emission that has\n * happened since the subscription, starting from the number `0`.\n * @param {any} [thisArg] An optional argument to determine the value of `this`\n * in the `predicate` function.\n * @return {[Observable<T>, Observable<T>]} An array with two Observables: one\n * with values that passed the predicate, and another with values that did not\n * pass the predicate.\n * @method partition\n * @owner Observable\n * @deprecated use `partition` static creation function instead\n */\nexport function partition<T>(predicate: (value: T, index: number) => boolean,\n                             thisArg?: any): UnaryFunction<Observable<T>, [Observable<T>, Observable<T>]> {\n  return (source: Observable<T>) => [\n    filter(predicate, thisArg)(source),\n    filter(not(predicate, thisArg) as any)(source)\n  ] as [Observable<T>, Observable<T>];\n}\n","import { Observable } from '../Observable';\nimport { map } from './map';\nimport { OperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function pluck<T, K1 extends keyof T>(k1: K1): OperatorFunction<T, T[K1]>;\nexport function pluck<T, K1 extends keyof T, K2 extends keyof T[K1]>(k1: K1, k2: K2): OperatorFunction<T, T[K1][K2]>;\nexport function pluck<T, K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2]>(k1: K1, k2: K2, k3: K3): OperatorFunction<T, T[K1][K2][K3]>;\nexport function pluck<T, K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3]>(k1: K1, k2: K2, k3: K3, k4: K4): OperatorFunction<T, T[K1][K2][K3][K4]>;\nexport function pluck<T, K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4]>(k1: K1, k2: K2, k3: K3, k4: K4, k5: K5): OperatorFunction<T, T[K1][K2][K3][K4][K5]>;\nexport function pluck<T, K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4], K6 extends keyof T[K1][K2][K3][K4][K5]>(k1: K1, k2: K2, k3: K3, k4: K4, k5: K5, k6: K6): OperatorFunction<T, T[K1][K2][K3][K4][K5][K6]>;\nexport function pluck<T, R>(...properties: string[]): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Maps each source value (an object) to its specified nested property.\n *\n * <span class=\"informal\">Like {@link map}, but meant only for picking one of\n * the nested properties of every emitted object.</span>\n *\n * ![](pluck.png)\n *\n * Given a list of strings describing a path to an object property, retrieves\n * the value of a specified nested property from all values in the source\n * Observable. If a property can't be resolved, it will return `undefined` for\n * that value.\n *\n * ## Example\n * Map every click to the tagName of the clicked target element\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { pluck } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const tagNames = clicks.pipe(pluck('target', 'tagName'));\n * tagNames.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link map}\n *\n * @param {...string} properties The nested properties to pluck from each source\n * value (an object).\n * @return {Observable} A new Observable of property values from the source values.\n * @method pluck\n * @owner Observable\n */\nexport function pluck<T, R>(...properties: string[]): OperatorFunction<T, R> {\n  const length = properties.length;\n  if (length === 0) {\n    throw new Error('list of properties cannot be empty.');\n  }\n  return (source: Observable<T>) => map(plucker(properties, length))(source as any);\n}\n\nfunction plucker(props: string[], length: number): (x: string) => any {\n  const mapper = (x: string) => {\n    let currentProp = x;\n    for (let i = 0; i < length; i++) {\n      const p = currentProp != null ? currentProp[props[i]] : undefined;\n      if (p !== void 0) {\n        currentProp = p;\n      } else {\n        return undefined;\n      }\n    }\n    return currentProp;\n  };\n\n  return mapper;\n}\n","import { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { multicast } from './multicast';\nimport { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { MonoTypeOperatorFunction, OperatorFunction, UnaryFunction, ObservableInput, ObservedValueOf } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function publish<T>(): UnaryFunction<Observable<T>, ConnectableObservable<T>>;\nexport function publish<T, O extends ObservableInput<any>>(selector: (shared: Observable<T>) => O): OperatorFunction<T, ObservedValueOf<O>>;\nexport function publish<T>(selector: MonoTypeOperatorFunction<T>): MonoTypeOperatorFunction<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called\n * before it begins emitting items to those Observers that have subscribed to it.\n *\n * <span class=\"informal\">Makes a cold Observable hot</span>\n *\n * ![](publish.png)\n *\n * ## Examples\n * Make source$ hot by applying publish operator, then merge each inner observable into a single one\n * and subscribe.\n * ```ts\n * import { of, zip, interval, merge } from \"rxjs\";\n * import { map, publish, tap } from \"rxjs/operators\";\n *\n * const source$ = zip(interval(2000), of(1, 2, 3, 4, 5, 6, 7, 8, 9)).pipe(\n *   map(values => values[1])\n * );\n *\n * source$\n *   .pipe(\n *     publish(multicasted$ =>\n *       merge(\n *         multicasted$.pipe(tap(x => console.log('Stream 1:', x))),\n *         multicasted$.pipe(tap(x => console.log('Stream 2:', x))),\n *         multicasted$.pipe(tap(x => console.log('Stream 3:', x))),\n *       )\n *     )\n *   )\n *   .subscribe();\n *\n * // Results every two seconds\n * // Stream 1: 1\n * // Stream 2: 1\n * // Stream 3: 1\n * // ...\n * // Stream 1: 9\n * // Stream 2: 9\n * // Stream 3: 9\n * ```\n *\n * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times\n * as needed, without causing multiple subscriptions to the source sequence.\n * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.\n * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.\n * @method publish\n * @owner Observable\n *\n *\n */\nexport function publish<T, R>(selector?: OperatorFunction<T, R>): MonoTypeOperatorFunction<T> | OperatorFunction<T, R> {\n  return selector ?\n    multicast(() => new Subject<T>(), selector) :\n    multicast(new Subject<T>());\n}\n","import { Observable } from '../Observable';\nimport { BehaviorSubject } from '../BehaviorSubject';\nimport { multicast } from './multicast';\nimport { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { UnaryFunction } from '../types';\n\n/**\n * @param value\n * @return {ConnectableObservable<T>}\n * @method publishBehavior\n * @owner Observable\n */\nexport function publishBehavior<T>(value: T):  UnaryFunction<Observable<T>, ConnectableObservable<T>> {\n  return (source: Observable<T>) => multicast(new BehaviorSubject<T>(value))(source) as ConnectableObservable<T>;\n}\n","import { Observable } from '../Observable';\nimport { AsyncSubject } from '../AsyncSubject';\nimport { multicast } from './multicast';\nimport { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { UnaryFunction } from '../types';\n\n/**\n * Returns a connectable observable sequence that shares a single subscription to the\n * underlying sequence containing only the last notification.\n *\n * ![](publishLast.png)\n *\n * Similar to {@link publish}, but it waits until the source observable completes and stores\n * the last emitted value.\n * Similarly to {@link publishReplay} and {@link publishBehavior}, this keeps storing the last\n * value even if it has no more subscribers. If subsequent subscriptions happen, they will\n * immediately get that last stored value and complete.\n *\n * ## Example\n *\n * ```ts\n * import { interval } from 'rxjs';\n * import { publishLast, tap, take } from 'rxjs/operators';\n *\n * const connectable =\n *   interval(1000)\n *     .pipe(\n *       tap(x => console.log(\"side effect\", x)),\n *       take(3),\n *       publishLast());\n *\n * connectable.subscribe(\n *   x => console.log(  \"Sub. A\", x),\n *   err => console.log(\"Sub. A Error\", err),\n *   () => console.log( \"Sub. A Complete\"));\n *\n * connectable.subscribe(\n *   x => console.log(  \"Sub. B\", x),\n *   err => console.log(\"Sub. B Error\", err),\n *   () => console.log( \"Sub. B Complete\"));\n *\n * connectable.connect();\n *\n * // Results:\n * //    \"side effect 0\"\n * //    \"side effect 1\"\n * //    \"side effect 2\"\n * //    \"Sub. A 2\"\n * //    \"Sub. B 2\"\n * //    \"Sub. A Complete\"\n * //    \"Sub. B Complete\"\n * ```\n *\n * @see {@link ConnectableObservable}\n * @see {@link publish}\n * @see {@link publishReplay}\n * @see {@link publishBehavior}\n *\n * @return {ConnectableObservable} An observable sequence that contains the elements of a\n * sequence produced by multicasting the source sequence.\n * @method publishLast\n * @owner Observable\n */\n\nexport function publishLast<T>(): UnaryFunction<Observable<T>, ConnectableObservable<T>> {\n  return (source: Observable<T>) => multicast(new AsyncSubject<T>())(source);\n}\n","import { Observable } from '../Observable';\nimport { ReplaySubject } from '../ReplaySubject';\nimport { multicast } from './multicast';\nimport { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { UnaryFunction, MonoTypeOperatorFunction, OperatorFunction, SchedulerLike, ObservableInput, ObservedValueOf } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function publishReplay<T>(bufferSize?: number, windowTime?: number, scheduler?: SchedulerLike): MonoTypeOperatorFunction<T>;\nexport function publishReplay<T, O extends ObservableInput<any>>(bufferSize?: number, windowTime?: number, selector?: (shared: Observable<T>) => O, scheduler?: SchedulerLike): OperatorFunction<T, ObservedValueOf<O>>;\n/* tslint:enable:max-line-length */\n\nexport function publishReplay<T, R>(bufferSize?: number,\n                                    windowTime?: number,\n                                    selectorOrScheduler?: SchedulerLike | OperatorFunction<T, R>,\n                                    scheduler?: SchedulerLike): UnaryFunction<Observable<T>, ConnectableObservable<R>> {\n\n  if (selectorOrScheduler && typeof selectorOrScheduler !== 'function') {\n    scheduler = selectorOrScheduler;\n  }\n\n  const selector = typeof selectorOrScheduler === 'function' ? selectorOrScheduler : undefined;\n  const subject = new ReplaySubject<T>(bufferSize, windowTime, scheduler);\n\n  return (source: Observable<T>) => multicast(() => subject, selector)(source) as ConnectableObservable<R>;\n}\n","import { Observable } from '../Observable';\nimport { isArray } from '../util/isArray';\nimport { MonoTypeOperatorFunction, OperatorFunction } from '../types';\nimport { race as raceStatic } from '../observable/race';\n\n/* tslint:disable:max-line-length */\n/** @deprecated Deprecated in favor of static race. */\nexport function race<T>(observables: Array<Observable<T>>): MonoTypeOperatorFunction<T>;\n/** @deprecated Deprecated in favor of static race. */\nexport function race<T, R>(observables: Array<Observable<T>>): OperatorFunction<T, R>;\n/** @deprecated Deprecated in favor of static race. */\nexport function race<T>(...observables: Array<Observable<T> | Array<Observable<T>>>): MonoTypeOperatorFunction<T>;\n/** @deprecated Deprecated in favor of static race. */\nexport function race<T, R>(...observables: Array<Observable<any> | Array<Observable<any>>>): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns an Observable that mirrors the first source Observable to emit a next,\n * error or complete notification from the combination of this Observable and supplied Observables.\n * @param {...Observables} ...observables Sources used to race for which Observable emits first.\n * @return {Observable} An Observable that mirrors the output of the first Observable to emit an item.\n * @method race\n * @owner Observable\n * @deprecated Deprecated in favor of static {@link race}.\n */\nexport function race<T>(...observables: (Observable<T> | Observable<T>[])[]): MonoTypeOperatorFunction<T> {\n  return function raceOperatorFunction(source: Observable<T>) {\n    // if the only argument is an array, it was most likely called with\n    // `pair([obs1, obs2, ...])`\n    if (observables.length === 1 && isArray(observables[0])) {\n      observables = observables[0] as Observable<T>[];\n    }\n\n    return source.lift.call(raceStatic(source, ...(observables as Observable<T>[])));\n  };\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { empty } from '../observable/empty';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Returns an Observable that will resubscribe to the source stream when the source stream completes, at most count times.\n *\n * <span class=\"informal\">Repeats all values emitted on the source. It's like {@link retry}, but for non error cases.</span>\n *\n * ![](repeat.png)\n *\n * Similar to {@link retry}, this operator repeats the stream of items emitted by the source for non error cases.\n * Repeat can be useful for creating observables that are meant to have some repeated pattern or rhythm.\n *\n * Note: `repeat(0)` returns an empty observable and `repeat()` will repeat forever\n *\n * ## Example\n * Repeat a message stream\n * ```ts\n * import { of } from 'rxjs';\n * import { repeat, delay } from 'rxjs/operators';\n *\n * const source = of('Repeat message');\n * const example = source.pipe(repeat(3));\n * example.subscribe(x => console.log(x));\n *\n * // Results\n * // Repeat message\n * // Repeat message\n * // Repeat message\n * ```\n *\n * Repeat 3 values, 2 times\n * ```ts\n * import { interval } from 'rxjs';\n * import { repeat, take } from 'rxjs/operators';\n *\n * const source = interval(1000);\n * const example = source.pipe(take(3), repeat(2));\n * example.subscribe(x => console.log(x));\n *\n * // Results every second\n * // 0\n * // 1\n * // 2\n * // 0\n * // 1\n * // 2\n * ```\n *\n * @see {@link repeatWhen}\n * @see {@link retry}\n *\n * @param {number} [count] The number of times the source Observable items are repeated, a count of 0 will yield\n * an empty Observable.\n * @return {Observable} An Observable that will resubscribe to the source stream when the source stream completes\n * , at most count times.\n * @method repeat\n * @owner Observable\n */\nexport function repeat<T>(count: number = -1): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => {\n    if (count === 0) {\n      return empty();\n    } else if (count < 0) {\n      return source.lift(new RepeatOperator(-1, source));\n    } else {\n      return source.lift(new RepeatOperator(count - 1, source));\n    }\n  };\n}\n\nclass RepeatOperator<T> implements Operator<T, T> {\n  constructor(private count: number,\n              private source: Observable<T>) {\n  }\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new RepeatSubscriber(subscriber, this.count, this.source));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass RepeatSubscriber<T> extends Subscriber<T> {\n  constructor(destination: Subscriber<any>,\n              private count: number,\n              private source: Observable<T>) {\n    super(destination);\n  }\n  complete() {\n    if (!this.isStopped) {\n      const { source, count } = this;\n      if (count === 0) {\n        return super.complete();\n      } else if (count > -1) {\n        this.count = count - 1;\n      }\n      source.subscribe(this._unsubscribeAndRecycle());\n    }\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { Subscription } from '../Subscription';\n\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\nimport { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';\n\n/**\n * Returns an Observable that mirrors the source Observable with the exception of a `complete`. If the source\n * Observable calls `complete`, this method will emit to the Observable returned from `notifier`. If that Observable\n * calls `complete` or `error`, then this method will call `complete` or `error` on the child subscription. Otherwise\n * this method will resubscribe to the source Observable.\n *\n * ![](repeatWhen.png)\n *\n * ## Example\n * Repeat a message stream on click\n * ```ts\n * import { of, fromEvent } from 'rxjs';\n * import { repeatWhen } from 'rxjs/operators';\n *\n * const source = of('Repeat message');\n * const documentClick$ = fromEvent(document, 'click');\n *\n * source.pipe(repeatWhen(() => documentClick$)\n * ).subscribe(data => console.log(data))\n * ```\n * @see {@link repeat}\n * @see {@link retry}\n * @see {@link retryWhen}\n *\n * @param {function(notifications: Observable): Observable} notifier - Receives an Observable of notifications with\n * which a user can `complete` or `error`, aborting the repetition.\n * @return {Observable} The source Observable modified with repeat logic.\n * @method repeatWhen\n * @owner Observable\n */\nexport function repeatWhen<T>(notifier: (notifications: Observable<any>) => Observable<any>): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => source.lift(new RepeatWhenOperator(notifier));\n}\n\nclass RepeatWhenOperator<T> implements Operator<T, T> {\n  constructor(protected notifier: (notifications: Observable<any>) => Observable<any>) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new RepeatWhenSubscriber(subscriber, this.notifier, source));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass RepeatWhenSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n\n  private notifications?: Subject<any>;\n  private retries?: Observable<any>;\n  private retriesSubscription?: Subscription;\n  private sourceIsBeingSubscribedTo: boolean = true;\n\n  constructor(destination: Subscriber<R>,\n              private notifier: (notifications: Observable<any>) => Observable<any>,\n              private source: Observable<T>) {\n    super(destination);\n  }\n\n  notifyNext(): void {\n    this.sourceIsBeingSubscribedTo = true;\n    this.source.subscribe(this);\n  }\n\n  notifyComplete(): void {\n    if (this.sourceIsBeingSubscribedTo === false) {\n      return super.complete();\n    }\n  }\n\n  complete() {\n    this.sourceIsBeingSubscribedTo = false;\n\n    if (!this.isStopped) {\n      if (!this.retries) {\n        this.subscribeToRetries();\n      }\n      if (!this.retriesSubscription || this.retriesSubscription.closed) {\n        return super.complete();\n      }\n\n      this._unsubscribeAndRecycle();\n      this.notifications!.next(undefined);\n    }\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _unsubscribe() {\n    const { notifications, retriesSubscription } = this;\n    if (notifications) {\n      notifications.unsubscribe();\n      this.notifications = undefined;\n    }\n    if (retriesSubscription) {\n      retriesSubscription.unsubscribe();\n      this.retriesSubscription = undefined;\n    }\n    this.retries = undefined;\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _unsubscribeAndRecycle(): Subscriber<T> {\n    const { _unsubscribe } = this;\n\n    this._unsubscribe = null!;\n    super._unsubscribeAndRecycle();\n    this._unsubscribe = _unsubscribe;\n\n    return this;\n  }\n\n  private subscribeToRetries() {\n    this.notifications = new Subject();\n    let retries;\n    try {\n      const { notifier } = this;\n      retries = notifier(this.notifications);\n    } catch (e) {\n      return super.complete();\n    }\n    this.retries = retries;\n    this.retriesSubscription = innerSubscribe(retries, new SimpleInnerSubscriber(this));\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\n\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable\n * calls `error`, this method will resubscribe to the source Observable for a maximum of `count` resubscriptions (given\n * as a number parameter) rather than propagating the `error` call.\n *\n * ![](retry.png)\n *\n * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those emitted\n * during failed subscriptions. For example, if an Observable fails at first but emits [1, 2] then succeeds the second\n * time and emits: [1, 2, 3, 4, 5] then the complete stream of emissions and notifications\n * would be: [1, 2, 1, 2, 3, 4, 5, `complete`].\n *\n * ## Example\n * ```ts\n * import { interval, of, throwError } from 'rxjs';\n * import { mergeMap, retry } from 'rxjs/operators';\n *\n * const source = interval(1000);\n * const example = source.pipe(\n *   mergeMap(val => {\n *     if(val > 5){\n *       return throwError('Error!');\n *     }\n *     return of(val);\n *   }),\n *   //retry 2 times on error\n *   retry(2)\n * );\n *\n * const subscribe = example.subscribe({\n *   next: val => console.log(val),\n *   error: val => console.log(`${val}: Retried 2 times then quit!`)\n * });\n *\n * // Output:\n * // 0..1..2..3..4..5..\n * // 0..1..2..3..4..5..\n * // 0..1..2..3..4..5..\n * // \"Error!: Retried 2 times then quit!\"\n * ```\n *\n * @param {number} count - Number of retry attempts before failing.\n * @return {Observable} The source Observable modified with the retry logic.\n * @method retry\n * @owner Observable\n */\nexport function retry<T>(count: number = -1): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => source.lift(new RetryOperator(count, source));\n}\n\nclass RetryOperator<T> implements Operator<T, T> {\n  constructor(private count: number,\n              private source: Observable<T>) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new RetrySubscriber(subscriber, this.count, this.source));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass RetrySubscriber<T> extends Subscriber<T> {\n  constructor(destination: Subscriber<any>,\n              private count: number,\n              private source: Observable<T>) {\n    super(destination);\n  }\n  error(err: any) {\n    if (!this.isStopped) {\n      const { source, count } = this;\n      if (count === 0) {\n        return super.error(err);\n      } else if (count > -1) {\n        this.count = count - 1;\n      }\n      source.subscribe(this._unsubscribeAndRecycle());\n    }\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { Subscription } from '../Subscription';\n\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\nimport { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';\n\n/**\n * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable\n * calls `error`, this method will emit the Throwable that caused the error to the Observable returned from `notifier`.\n * If that Observable calls `complete` or `error` then this method will call `complete` or `error` on the child\n * subscription. Otherwise this method will resubscribe to the source Observable.\n *\n * ![](retryWhen.png)\n *\n * @param {function(errors: Observable): Observable} notifier - Receives an Observable of notifications with which a\n * user can `complete` or `error`, aborting the retry.\n * @return {Observable} The source Observable modified with retry logic.\n * @method retryWhen\n * @owner Observable\n */\nexport function retryWhen<T>(notifier: (errors: Observable<any>) => Observable<any>): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => source.lift(new RetryWhenOperator(notifier, source));\n}\n\nclass RetryWhenOperator<T> implements Operator<T, T> {\n  constructor(protected notifier: (errors: Observable<any>) => Observable<any>,\n              protected source: Observable<T>) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new RetryWhenSubscriber(subscriber, this.notifier, this.source));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass RetryWhenSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n\n  private errors?: Subject<any>;\n  private retries?: Observable<any>;\n  private retriesSubscription?: Subscription;\n\n  constructor(destination: Subscriber<R>,\n              private notifier: (errors: Observable<any>) => Observable<any>,\n              private source: Observable<T>) {\n    super(destination);\n  }\n\n  error(err: any) {\n    if (!this.isStopped) {\n\n      let errors = this.errors;\n      let retries: any = this.retries;\n      let retriesSubscription = this.retriesSubscription;\n\n      if (!retries) {\n        errors = new Subject();\n        try {\n          const { notifier } = this;\n          retries = notifier(errors);\n        } catch (e) {\n          return super.error(e);\n        }\n        retriesSubscription = innerSubscribe(retries, new SimpleInnerSubscriber(this));\n      } else {\n        this.errors = undefined;\n        this.retriesSubscription = undefined;\n      }\n\n      this._unsubscribeAndRecycle();\n\n      this.errors = errors;\n      this.retries = retries;\n      this.retriesSubscription = retriesSubscription;\n\n      errors!.next(err);\n    }\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _unsubscribe() {\n    const { errors, retriesSubscription } = this;\n    if (errors) {\n      errors.unsubscribe();\n      this.errors = undefined;\n    }\n    if (retriesSubscription) {\n      retriesSubscription.unsubscribe();\n      this.retriesSubscription = undefined;\n    }\n    this.retries = undefined;\n  }\n\n  notifyNext(): void {\n    const { _unsubscribe } = this;\n\n    this._unsubscribe = null!;\n    this._unsubscribeAndRecycle();\n    this._unsubscribe = _unsubscribe;\n\n    this.source.subscribe(this);\n  }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\n\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\nimport { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';\n\n/**\n * Emits the most recently emitted value from the source Observable whenever\n * another Observable, the `notifier`, emits.\n *\n * <span class=\"informal\">It's like {@link sampleTime}, but samples whenever\n * the `notifier` Observable emits something.</span>\n *\n * ![](sample.png)\n *\n * Whenever the `notifier` Observable emits a value or completes, `sample`\n * looks at the source Observable and emits whichever value it has most recently\n * emitted since the previous sampling, unless the source has not emitted\n * anything since the previous sampling. The `notifier` is subscribed to as soon\n * as the output Observable is subscribed.\n *\n * ## Example\n * On every click, sample the most recent \"seconds\" timer\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { sample } from 'rxjs/operators';\n *\n * const seconds = interval(1000);\n * const clicks = fromEvent(document, 'click');\n * const result = seconds.pipe(sample(clicks));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link audit}\n * @see {@link debounce}\n * @see {@link sampleTime}\n * @see {@link throttle}\n *\n * @param {Observable<any>} notifier The Observable to use for sampling the\n * source Observable.\n * @return {Observable<T>} An Observable that emits the results of sampling the\n * values emitted by the source Observable whenever the notifier Observable\n * emits value or completes.\n * @method sample\n * @owner Observable\n */\nexport function sample<T>(notifier: Observable<any>): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => source.lift(new SampleOperator(notifier));\n}\n\nclass SampleOperator<T> implements Operator<T, T> {\n  constructor(private notifier: Observable<any>) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    const sampleSubscriber = new SampleSubscriber(subscriber);\n    const subscription = source.subscribe(sampleSubscriber);\n    subscription.add(innerSubscribe(this.notifier, new SimpleInnerSubscriber(sampleSubscriber)));\n    return subscription;\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SampleSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n  private value?: T;\n  private hasValue: boolean = false;\n\n  protected _next(value: T) {\n    this.value = value;\n    this.hasValue = true;\n  }\n\n  notifyNext(): void {\n    this.emitValue();\n  }\n\n  notifyComplete(): void {\n    this.emitValue();\n  }\n\n  emitValue() {\n    if (this.hasValue) {\n      this.hasValue = false;\n      this.destination.next!(this.value!);\n    }\n  }\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { async } from '../scheduler/async';\nimport { MonoTypeOperatorFunction, SchedulerAction, SchedulerLike, TeardownLogic } from '../types';\n\n/**\n * Emits the most recently emitted value from the source Observable within\n * periodic time intervals.\n *\n * <span class=\"informal\">Samples the source Observable at periodic time\n * intervals, emitting what it samples.</span>\n *\n * ![](sampleTime.png)\n *\n * `sampleTime` periodically looks at the source Observable and emits whichever\n * value it has most recently emitted since the previous sampling, unless the\n * source has not emitted anything since the previous sampling. The sampling\n * happens periodically in time every `period` milliseconds (or the time unit\n * defined by the optional `scheduler` argument). The sampling starts as soon as\n * the output Observable is subscribed.\n *\n * ## Example\n * Every second, emit the most recent click at most once\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { sampleTime } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(sampleTime(1000));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link auditTime}\n * @see {@link debounceTime}\n * @see {@link delay}\n * @see {@link sample}\n * @see {@link throttleTime}\n *\n * @param {number} period The sampling period expressed in milliseconds or the\n * time unit determined internally by the optional `scheduler`.\n * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for\n * managing the timers that handle the sampling.\n * @return {Observable<T>} An Observable that emits the results of sampling the\n * values emitted by the source Observable at the specified time interval.\n * @method sampleTime\n * @owner Observable\n */\nexport function sampleTime<T>(period: number, scheduler: SchedulerLike = async): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => source.lift(new SampleTimeOperator(period, scheduler));\n}\n\nclass SampleTimeOperator<T> implements Operator<T, T> {\n  constructor(private period: number,\n              private scheduler: SchedulerLike) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new SampleTimeSubscriber(subscriber, this.period, this.scheduler));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SampleTimeSubscriber<T> extends Subscriber<T> {\n  lastValue: T;\n  hasValue: boolean = false;\n\n  constructor(destination: Subscriber<T>,\n              private period: number,\n              private scheduler: SchedulerLike) {\n    super(destination);\n    this.add(scheduler.schedule(dispatchNotification, period, { subscriber: this, period }));\n  }\n\n  protected _next(value: T) {\n    this.lastValue = value;\n    this.hasValue = true;\n  }\n\n  notifyNext() {\n    if (this.hasValue) {\n      this.hasValue = false;\n      this.destination.next(this.lastValue);\n    }\n  }\n}\n\nfunction dispatchNotification<T>(this: SchedulerAction<any>, state: any) {\n  let { subscriber, period } = state;\n  subscriber.notifyNext();\n  this.schedule(state, period);\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\n\nimport { Observer, OperatorFunction } from '../types';\n\n/**\n * Compares all values of two observables in sequence using an optional comparator function\n * and returns an observable of a single boolean value representing whether or not the two sequences\n * are equal.\n *\n * <span class=\"informal\">Checks to see of all values emitted by both observables are equal, in order.</span>\n *\n * ![](sequenceEqual.png)\n *\n * `sequenceEqual` subscribes to two observables and buffers incoming values from each observable. Whenever either\n * observable emits a value, the value is buffered and the buffers are shifted and compared from the bottom\n * up; If any value pair doesn't match, the returned observable will emit `false` and complete. If one of the\n * observables completes, the operator will wait for the other observable to complete; If the other\n * observable emits before completing, the returned observable will emit `false` and complete. If one observable never\n * completes or emits after the other complets, the returned observable will never complete.\n *\n * ## Example\n * figure out if the Konami code matches\n * ```ts\n * import { from, fromEvent } from 'rxjs';\n * import { sequenceEqual, bufferCount, mergeMap, map } from 'rxjs/operators';\n *\n * const codes = from([\n *   'ArrowUp',\n *   'ArrowUp',\n *   'ArrowDown',\n *   'ArrowDown',\n *   'ArrowLeft',\n *   'ArrowRight',\n *   'ArrowLeft',\n *   'ArrowRight',\n *   'KeyB',\n *   'KeyA',\n *   'Enter', // no start key, clearly.\n * ]);\n *\n * const keys = fromEvent(document, 'keyup').pipe(map(e => e.code));\n * const matches = keys.pipe(\n *   bufferCount(11, 1),\n *   mergeMap(\n *     last11 => from(last11).pipe(sequenceEqual(codes)),\n *   ),\n * );\n * matches.subscribe(matched => console.log('Successful cheat at Contra? ', matched));\n * ```\n *\n * @see {@link combineLatest}\n * @see {@link zip}\n * @see {@link withLatestFrom}\n *\n * @param {Observable} compareTo The observable sequence to compare the source sequence to.\n * @param {function} [comparator] An optional function to compare each value pair\n * @return {Observable} An Observable of a single boolean value representing whether or not\n * the values emitted by both observables were equal in sequence.\n * @method sequenceEqual\n * @owner Observable\n */\nexport function sequenceEqual<T>(compareTo: Observable<T>,\n                                 comparator?: (a: T, b: T) => boolean): OperatorFunction<T, boolean> {\n  return (source: Observable<T>) => source.lift(new SequenceEqualOperator(compareTo, comparator));\n}\n\nexport class SequenceEqualOperator<T> implements Operator<T, boolean> {\n  constructor(private compareTo: Observable<T>,\n              private comparator: (a: T, b: T) => boolean) {\n  }\n\n  call(subscriber: Subscriber<boolean>, source: any): any {\n    return source.subscribe(new SequenceEqualSubscriber(subscriber, this.compareTo, this.comparator));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class SequenceEqualSubscriber<T, R> extends Subscriber<T> {\n  private _a: T[] = [];\n  private _b: T[] = [];\n  private _oneComplete = false;\n\n  constructor(destination: Observer<R>,\n              private compareTo: Observable<T>,\n              private comparator: (a: T, b: T) => boolean) {\n    super(destination);\n    (this.destination as Subscription).add(compareTo.subscribe(new SequenceEqualCompareToSubscriber(destination, this)));\n  }\n\n  protected _next(value: T): void {\n    if (this._oneComplete && this._b.length === 0) {\n      this.emit(false);\n    } else {\n      this._a.push(value);\n      this.checkValues();\n    }\n  }\n\n  public _complete(): void {\n    if (this._oneComplete) {\n      this.emit(this._a.length === 0 && this._b.length === 0);\n    } else {\n      this._oneComplete = true;\n    }\n    this.unsubscribe();\n  }\n\n  checkValues() {\n    const { _a, _b, comparator } = this;\n    while (_a.length > 0 && _b.length > 0) {\n      let a = _a.shift();\n      let b = _b.shift();\n      let areEqual = false;\n      try {\n        areEqual = comparator ? comparator(a, b) : a === b;\n      } catch (e) {\n        this.destination.error(e);\n      }\n      if (!areEqual) {\n        this.emit(false);\n      }\n    }\n  }\n\n  emit(value: boolean) {\n    const { destination } = this;\n    destination.next(value);\n    destination.complete();\n  }\n\n  nextB(value: T) {\n    if (this._oneComplete && this._a.length === 0) {\n      this.emit(false);\n    } else {\n      this._b.push(value);\n      this.checkValues();\n    }\n  }\n\n  completeB() {\n    if (this._oneComplete) {\n      this.emit(this._a.length === 0 && this._b.length === 0);\n    } else {\n      this._oneComplete = true;\n    }\n  }\n}\n\nclass SequenceEqualCompareToSubscriber<T, R> extends Subscriber<T> {\n  constructor(destination: Observer<R>, private parent: SequenceEqualSubscriber<T, R>) {\n    super(destination);\n  }\n\n  protected _next(value: T): void {\n    this.parent.nextB(value);\n  }\n\n  protected _error(err: any): void {\n    this.parent.error(err);\n    this.unsubscribe();\n  }\n\n  protected _complete(): void {\n    this.parent.completeB();\n    this.unsubscribe();\n  }\n}\n","import { Observable } from '../Observable';\nimport { multicast } from './multicast';\nimport { refCount } from './refCount';\nimport { Subject } from '../Subject';\n\nimport { MonoTypeOperatorFunction } from '../types';\n\nfunction shareSubjectFactory() {\n  return new Subject();\n}\n\n/**\n * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one\n * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will\n * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.\n * This is an alias for `multicast(() => new Subject()), refCount()`.\n *\n * ![](share.png)\n *\n * @return {Observable<T>} An Observable that upon connection causes the source Observable to emit items to its Observers.\n * @method share\n * @owner Observable\n */\nexport function share<T>(): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => refCount()(multicast(shareSubjectFactory)(source)) as Observable<T>;\n}\n","import { Observable } from '../Observable';\nimport { ReplaySubject } from '../ReplaySubject';\nimport { Subscription } from '../Subscription';\nimport { MonoTypeOperatorFunction, SchedulerLike } from '../types';\nimport { Subscriber } from '../Subscriber';\n\nexport interface ShareReplayConfig {\n  bufferSize?: number;\n  windowTime?: number;\n  refCount: boolean;\n  scheduler?: SchedulerLike;\n}\n\n/**\n * Share source and replay specified number of emissions on subscription.\n *\n * This operator is a specialization of `replay` that connects to a source observable\n * and multicasts through a `ReplaySubject` constructed with the specified arguments.\n * A successfully completed source will stay cached in the `shareReplayed observable` forever,\n * but an errored source can be retried.\n *\n * ## Why use shareReplay?\n * You generally want to use `shareReplay` when you have side-effects or taxing computations\n * that you do not wish to be executed amongst multiple subscribers.\n * It may also be valuable in situations where you know you will have late subscribers to\n * a stream that need access to previously emitted values.\n * This ability to replay values on subscription is what differentiates {@link share} and `shareReplay`.\n *\n * ![](shareReplay.png)\n *\n * ## Example\n * ```ts\n * import { interval } from 'rxjs';\n * import { shareReplay, take } from 'rxjs/operators';\n *\n * const obs$ = interval(1000);\n * const shared$ = obs$.pipe(\n *   take(4),\n *   shareReplay(3)\n * );\n * shared$.subscribe(x => console.log('source A: ', x));\n * shared$.subscribe(y => console.log('source B: ', y));\n *\n * ```\n *\n * @see {@link publish}\n * @see {@link share}\n * @see {@link publishReplay}\n *\n * @param {Number} [bufferSize=Number.POSITIVE_INFINITY] Maximum element count of the replay buffer.\n * @param {Number} [windowTime=Number.POSITIVE_INFINITY] Maximum time length of the replay buffer in milliseconds.\n * @param {Scheduler} [scheduler] Scheduler where connected observers within the selector function\n * will be invoked on.\n * @return {Observable} An observable sequence that contains the elements of a sequence produced\n * by multicasting the source sequence within a selector function.\n * @method shareReplay\n * @owner Observable\n */\nexport function shareReplay<T>(\n  config: ShareReplayConfig\n): MonoTypeOperatorFunction<T>;\nexport function shareReplay<T>(\n  bufferSize?: number,\n  windowTime?: number,\n  scheduler?: SchedulerLike\n): MonoTypeOperatorFunction<T>;\nexport function shareReplay<T>(\n  configOrBufferSize?: ShareReplayConfig | number,\n  windowTime?: number,\n  scheduler?: SchedulerLike\n): MonoTypeOperatorFunction<T> {\n  let config: ShareReplayConfig;\n  if (configOrBufferSize && typeof configOrBufferSize === 'object') {\n    config = configOrBufferSize as ShareReplayConfig;\n  } else {\n    config = {\n      bufferSize: configOrBufferSize as number | undefined,\n      windowTime,\n      refCount: false,\n      scheduler,\n    };\n  }\n  return (source: Observable<T>) => source.lift(shareReplayOperator(config));\n}\n\nfunction shareReplayOperator<T>({\n  bufferSize = Number.POSITIVE_INFINITY,\n  windowTime = Number.POSITIVE_INFINITY,\n  refCount: useRefCount,\n  scheduler,\n}: ShareReplayConfig) {\n  let subject: ReplaySubject<T> | undefined;\n  let refCount = 0;\n  let subscription: Subscription | undefined;\n  let hasError = false;\n  let isComplete = false;\n\n  return function shareReplayOperation(\n    this: Subscriber<T>,\n    source: Observable<T>\n  ) {\n    refCount++;\n    let innerSub: Subscription;\n    if (!subject || hasError) {\n      hasError = false;\n      subject = new ReplaySubject<T>(bufferSize, windowTime, scheduler);\n      innerSub = subject.subscribe(this);\n      subscription = source.subscribe({\n        next(value) {\n          subject.next(value);\n        },\n        error(err) {\n          hasError = true;\n          subject.error(err);\n        },\n        complete() {\n          isComplete = true;\n          subscription = undefined;\n          subject.complete();\n        },\n      });\n\n      // Here we need to check to see if the source synchronously completed. Although\n      // we're setting `subscription = undefined` in the completion handler, if the source\n      // is synchronous, that will happen *before* subscription is set by the return of\n      // the `subscribe` call.\n      if (isComplete) {\n        subscription = undefined;\n      }\n    } else {\n      innerSub = subject.subscribe(this);\n    }\n\n    this.add(() => {\n      refCount--;\n      innerSub.unsubscribe();\n      innerSub = undefined;\n      if (subscription && !isComplete && useRefCount && refCount === 0) {\n        subscription.unsubscribe();\n        subscription = undefined;\n        subject = undefined;\n      }\n    });\n  };\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { EmptyError } from '../util/EmptyError';\n\nimport { Observer, MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Returns an Observable that emits the single item emitted by the source Observable that matches a specified\n * predicate, if that Observable emits one such item. If the source Observable emits more than one such item or no\n * items, notify of an IllegalArgumentException or NoSuchElementException respectively. If the source Observable\n * emits items but none match the specified predicate then `undefined` is emitted.\n *\n * <span class=\"informal\">Like {@link first}, but emit with error notification if there is more than one value.</span>\n * ![](single.png)\n *\n * ## Example\n * emits 'error'\n * ```ts\n * import { range } from 'rxjs';\n * import { single } from 'rxjs/operators';\n *\n * const numbers = range(1,5).pipe(single());\n * numbers.subscribe(x => console.log('never get called'), e => console.log('error'));\n * // result\n * // 'error'\n * ```\n *\n * emits 'undefined'\n * ```ts\n * import { range } from 'rxjs';\n * import { single } from 'rxjs/operators';\n *\n * const numbers = range(1,5).pipe(single(x => x === 10));\n * numbers.subscribe(x => console.log(x));\n * // result\n * // 'undefined'\n * ```\n *\n * @see {@link first}\n * @see {@link find}\n * @see {@link findIndex}\n * @see {@link elementAt}\n *\n * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`\n * callback if the Observable completes before any `next` notification was sent.\n * @param {Function} predicate - A predicate function to evaluate items emitted by the source Observable.\n * @return {Observable<T>} An Observable that emits the single item emitted by the source Observable that matches\n * the predicate or `undefined` when no items match.\n *\n * @method single\n * @owner Observable\n */\nexport function single<T>(predicate?: (value: T, index: number, source: Observable<T>) => boolean): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => source.lift(new SingleOperator(predicate, source));\n}\n\nclass SingleOperator<T> implements Operator<T, T> {\n  constructor(private predicate?: (value: T, index: number, source: Observable<T>) => boolean,\n              private source?: Observable<T>) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new SingleSubscriber(subscriber, this.predicate, this.source));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SingleSubscriber<T> extends Subscriber<T> {\n  private seenValue: boolean = false;\n  private singleValue: T;\n  private index: number = 0;\n\n  constructor(destination: Observer<T>,\n              private predicate?: (value: T, index: number, source: Observable<T>) => boolean,\n              private source?: Observable<T>) {\n    super(destination);\n  }\n\n  private applySingleValue(value: T): void {\n    if (this.seenValue) {\n      this.destination.error('Sequence contains more than one element');\n    } else {\n      this.seenValue = true;\n      this.singleValue = value;\n    }\n  }\n\n  protected _next(value: T): void {\n    const index = this.index++;\n\n    if (this.predicate) {\n      this.tryNext(value, index);\n    } else {\n      this.applySingleValue(value);\n    }\n  }\n\n  private tryNext(value: T, index: number): void {\n    try {\n      if (this.predicate(value, index, this.source)) {\n        this.applySingleValue(value);\n      }\n    } catch (err) {\n      this.destination.error(err);\n    }\n  }\n\n  protected _complete(): void {\n    const destination = this.destination;\n\n    if (this.index > 0) {\n      destination.next(this.seenValue ? this.singleValue : undefined);\n      destination.complete();\n    } else {\n      destination.error(new EmptyError);\n    }\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Returns an Observable that skips the first `count` items emitted by the source Observable.\n *\n * ![](skip.png)\n *\n * @param {Number} count - The number of times, items emitted by source Observable should be skipped.\n * @return {Observable} An Observable that skips values emitted by the source Observable.\n *\n * @method skip\n * @owner Observable\n */\nexport function skip<T>(count: number): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => source.lift(new SkipOperator(count));\n}\n\nclass SkipOperator<T> implements Operator<T, T> {\n  constructor(private total: number) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new SkipSubscriber(subscriber, this.total));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SkipSubscriber<T> extends Subscriber<T> {\n  count: number = 0;\n\n  constructor(destination: Subscriber<T>, private total: number) {\n    super(destination);\n  }\n\n  protected _next(x: T) {\n    if (++this.count > this.total) {\n      this.destination.next(x);\n    }\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Skip the last `count` values emitted by the source Observable.\n *\n * ![](skipLast.png)\n *\n * `skipLast` returns an Observable that accumulates a queue with a length\n * enough to store the first `count` values. As more values are received,\n * values are taken from the front of the queue and produced on the result\n * sequence. This causes values to be delayed.\n *\n * ## Example\n * Skip the last 2 values of an Observable with many values\n * ```ts\n * import { range } from 'rxjs';\n * import { skipLast } from 'rxjs/operators';\n *\n * const many = range(1, 5);\n * const skipLastTwo = many.pipe(skipLast(2));\n * skipLastTwo.subscribe(x => console.log(x));\n *\n * // Results in:\n * // 1 2 3\n * ```\n *\n * @see {@link skip}\n * @see {@link skipUntil}\n * @see {@link skipWhile}\n * @see {@link take}\n *\n * @throws {ArgumentOutOfRangeError} When using `skipLast(i)`, it throws\n * ArgumentOutOrRangeError if `i < 0`.\n *\n * @param {number} count Number of elements to skip from the end of the source Observable.\n * @returns {Observable<T>} An Observable that skips the last count values\n * emitted by the source Observable.\n * @method skipLast\n * @owner Observable\n */\nexport function skipLast<T>(count: number): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => source.lift(new SkipLastOperator(count));\n}\n\nclass SkipLastOperator<T> implements Operator<T, T> {\n  constructor(private _skipCount: number) {\n    if (this._skipCount < 0) {\n      throw new ArgumentOutOfRangeError;\n    }\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    if (this._skipCount === 0) {\n      // If we don't want to skip any values then just subscribe\n      // to Subscriber without any further logic.\n      return source.subscribe(new Subscriber(subscriber));\n    } else {\n      return source.subscribe(new SkipLastSubscriber(subscriber, this._skipCount));\n    }\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SkipLastSubscriber<T> extends Subscriber<T> {\n  private _ring: T[];\n  private _count: number = 0;\n\n  constructor(destination: Subscriber<T>, private _skipCount: number) {\n    super(destination);\n    this._ring = new Array<T>(_skipCount);\n  }\n\n  protected _next(value: T): void {\n    const skipCount = this._skipCount;\n    const count = this._count++;\n\n    if (count < skipCount) {\n      this._ring[count] = value;\n    } else {\n      const currentIndex = count % skipCount;\n      const ring = this._ring;\n      const oldValue = ring[currentIndex];\n\n      ring[currentIndex] = value;\n      this.destination.next(oldValue);\n    }\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic, ObservableInput } from '../types';\nimport { Subscription } from '../Subscription';\nimport { SimpleOuterSubscriber, SimpleInnerSubscriber, innerSubscribe } from '../innerSubscribe';\n\n/**\n * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.\n *\n * The `skipUntil` operator causes the observable stream to skip the emission of values ​​until the passed in observable emits the first value.\n * This can be particularly useful in combination with user interactions, responses of http requests or waiting for specific times to pass by.\n *\n * ![](skipUntil.png)\n *\n * Internally the `skipUntil` operator subscribes to the passed in observable (in the following called *notifier*) in order to recognize the emission\n * of its first value. When this happens, the operator unsubscribes from the *notifier* and starts emitting the values of the *source*\n * observable. It will never let the *source* observable emit any values if the *notifier* completes or throws an error without emitting\n * a value before.\n *\n * ## Example\n *\n * In the following example, all emitted values ​​of the interval observable are skipped until the user clicks anywhere within the page.\n *\n * ```ts\n * import { interval, fromEvent } from 'rxjs';\n * import { skipUntil } from 'rxjs/operators';\n *\n * const intervalObservable = interval(1000);\n * const click = fromEvent(document, 'click');\n *\n * const emitAfterClick = intervalObservable.pipe(\n *   skipUntil(click)\n * );\n * // clicked at 4.6s. output: 5...6...7...8........ or\n * // clicked at 7.3s. output: 8...9...10..11.......\n * const subscribe = emitAfterClick.subscribe(value => console.log(value));\n * ```\n *\n * @param {Observable} notifier - The second Observable that has to emit an item before the source Observable's elements begin to\n * be mirrored by the resulting Observable.\n * @return {Observable<T>} An Observable that skips items from the source Observable until the second Observable emits\n * an item, then emits the remaining items.\n * @method skipUntil\n * @owner Observable\n */\nexport function skipUntil<T>(notifier: Observable<any>): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => source.lift(new SkipUntilOperator(notifier));\n}\n\nclass SkipUntilOperator<T> implements Operator<T, T> {\n  constructor(private notifier: Observable<any>) {\n  }\n\n  call(destination: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new SkipUntilSubscriber(destination, this.notifier));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SkipUntilSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n\n  private hasValue: boolean = false;\n  private innerSubscription?: Subscription;\n\n  constructor(destination: Subscriber<R>, notifier: ObservableInput<any>) {\n    super(destination);\n    const innerSubscriber = new SimpleInnerSubscriber(this);\n    this.add(innerSubscriber);\n    this.innerSubscription = innerSubscriber;\n    const innerSubscription = innerSubscribe(notifier, innerSubscriber);\n    // The returned subscription will usually be the subscriber that was\n    // passed. However, interop subscribers will be wrapped and for\n    // unsubscriptions to chain correctly, the wrapper needs to be added, too.\n    if (innerSubscription !== innerSubscriber) {\n      this.add(innerSubscription);\n      this.innerSubscription = innerSubscription;\n    }\n  }\n\n  protected _next(value: T) {\n    if (this.hasValue) {\n      super._next(value);\n    }\n  }\n\n  notifyNext(): void {\n    this.hasValue = true;\n    if (this.innerSubscription) {\n      this.innerSubscription.unsubscribe();\n    }\n  }\n\n  notifyComplete() {\n    /* do nothing */\n  }\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds\n * true, but emits all further source items as soon as the condition becomes false.\n *\n * ![](skipWhile.png)\n *\n * @param {Function} predicate - A function to test each item emitted from the source Observable.\n * @return {Observable<T>} An Observable that begins emitting items emitted by the source Observable when the\n * specified predicate becomes false.\n * @method skipWhile\n * @owner Observable\n */\nexport function skipWhile<T>(predicate: (value: T, index: number) => boolean): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => source.lift(new SkipWhileOperator(predicate));\n}\n\nclass SkipWhileOperator<T> implements Operator<T, T> {\n  constructor(private predicate: (value: T, index: number) => boolean) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SkipWhileSubscriber<T> extends Subscriber<T> {\n  private skipping: boolean = true;\n  private index: number = 0;\n\n  constructor(destination: Subscriber<T>,\n              private predicate: (value: T, index: number) => boolean) {\n    super(destination);\n  }\n\n  protected _next(value: T): void {\n    const destination = this.destination;\n    if (this.skipping) {\n      this.tryCallPredicate(value);\n    }\n\n    if (!this.skipping) {\n      destination.next(value);\n    }\n  }\n\n  private tryCallPredicate(value: T): void {\n    try {\n      const result = this.predicate(value, this.index++);\n      this.skipping = Boolean(result);\n    } catch (err) {\n      this.destination.error(err);\n    }\n  }\n}\n","import { Observable } from '../Observable';\nimport { concat } from '../observable/concat';\nimport { isScheduler } from '../util/isScheduler';\nimport { MonoTypeOperatorFunction, OperatorFunction, SchedulerLike } from '../types';\n\n/* tslint:disable:max-line-length */\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T>(scheduler: SchedulerLike): MonoTypeOperatorFunction<T>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D>(v1: D, scheduler: SchedulerLike): OperatorFunction<T, T | D>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D, E>(v1: D, v2: E, scheduler: SchedulerLike): OperatorFunction<T, T | D | E>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D, E, F>(v1: D, v2: E, v3: F, scheduler: SchedulerLike): OperatorFunction<T, T | D | E | F>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D, E, F, G>(v1: D, v2:  E, v3: F, v4: G, scheduler: SchedulerLike): OperatorFunction<T, T | D | E | F | G>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D, E, F, G, H>(v1: D, v2: E, v3: F, v4: G, v5: H, scheduler: SchedulerLike): OperatorFunction<T, T | D | E | F | G | H>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D, E, F, G, H, I>(v1: D, v2: E, v3: F, v4: G, v5: H, v6: I, scheduler: SchedulerLike): OperatorFunction<T, T | D | E | F | G | H | I>;\n\nexport function startWith<T, D>(v1: D): OperatorFunction<T, T | D>;\nexport function startWith<T, D, E>(v1: D, v2: E): OperatorFunction<T, T | D | E>;\nexport function startWith<T, D, E, F>(v1: D, v2: E, v3: F): OperatorFunction<T, T | D | E | F>;\nexport function startWith<T, D, E, F, G>(v1: D, v2:  E, v3: F, v4: G): OperatorFunction<T, T | D | E | F | G>;\nexport function startWith<T, D, E, F, G, H>(v1: D, v2: E, v3: F, v4: G, v5: H): OperatorFunction<T, T | D | E | F | G | H>;\nexport function startWith<T, D, E, F, G, H, I>(v1: D, v2: E, v3: F, v4: G, v5: H, v6: I): OperatorFunction<T, T | D | E | F | G | H | I>;\nexport function startWith<T, D = T>(...array: D[]): OperatorFunction<T, T | D>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D = T>(...array: Array<D | SchedulerLike>): OperatorFunction<T, T | D>;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns an Observable that emits the items you specify as arguments before it begins to emit\n * items emitted by the source Observable.\n *\n * <span class=\"informal\">First emits its arguments in order, and then any\n * emissions from the source.</span>\n *\n * ![](startWith.png)\n *\n * ## Examples\n *\n * Start the chain of emissions with `\"first\"`, `\"second\"`\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { startWith } from 'rxjs/operators';\n *\n * of(\"from source\")\n *   .pipe(startWith(\"first\", \"second\"))\n *   .subscribe(x => console.log(x));\n *\n * // results:\n * //   \"first\"\n * //   \"second\"\n * //   \"from source\"\n * ```\n *\n * @param {...T} values - Items you want the modified Observable to emit first.\n * @param {SchedulerLike} [scheduler] - A {@link SchedulerLike} to use for scheduling\n * the emissions of the `next` notifications.\n * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items\n * emitted by the source Observable.\n * @method startWith\n * @owner Observable\n */\nexport function startWith<T, D>(...array: Array<T | SchedulerLike>): OperatorFunction<T, T | D> {\n  const scheduler = array[array.length - 1] as SchedulerLike;\n  if (isScheduler(scheduler)) {\n    // deprecated path\n    array.pop();\n    return (source: Observable<T>) => concat(array as T[], source, scheduler);\n  } else {\n    return (source: Observable<T>) => concat(array as T[], source);\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { SubscribeOnObservable } from '../observable/SubscribeOnObservable';\nimport { MonoTypeOperatorFunction, SchedulerLike, TeardownLogic } from '../types';\n\n/**\n * Asynchronously subscribes Observers to this Observable on the specified {@link SchedulerLike}.\n *\n * With `subscribeOn` you can decide what type of scheduler a specific Observable will be using when it is subscribed to.\n *\n * Schedulers control the speed and order of emissions to observers from an Observable stream.\n *\n * ![](subscribeOn.png)\n *\n * ## Example\n * Given the following code:\n * ```javascript\n * import { of, merge } from 'rxjs';\n *\n * const a = of(1, 2, 3, 4);\n * const b = of(5, 6, 7, 8, 9);\n * merge(a, b).subscribe(console.log);\n * ```\n *\n * Both Observable `a` and `b` will emit their values directly and synchronously once they are subscribed to.\n * This will result in the output of `1 2 3 4 5 6 7 8 9`.\n *\n * But if we instead us the `subscribeOn` operator declaring that we want to use the {@link asyncScheduler} for values emited by Observable `a`:\n * ```javascript\n * import { of, merge, asyncScheduler } from 'rxjs';\n * import { subscribeOn } from 'rxjs/operators';\n *\n * const a = of(1, 2, 3, 4).pipe(subscribeOn(asyncScheduler));\n * const b = of(5, 6, 7, 8, 9);\n * merge(a, b).subscribe(console.log);\n * ```\n *\n * The output will instead be `5 6 7 8 9 1 2 3 4`.\n * The reason for this is that Observable `b` emits its values directly and synchronously like before\n * but the emissions from `a` are scheduled on the event loop because we are now using the {@link asyncScheduler} for that specific Observable.\n *\n * @param {SchedulerLike} scheduler - The {@link SchedulerLike} to perform subscription actions on.\n * @return {Observable<T>} The source Observable modified so that its subscriptions happen on the specified {@link SchedulerLike}.\n .\n * @method subscribeOn\n * @owner Observable\n */\nexport function subscribeOn<T>(scheduler: SchedulerLike, delay: number = 0): MonoTypeOperatorFunction<T> {\n  return function subscribeOnOperatorFunction(source: Observable<T>): Observable<T> {\n    return source.lift(new SubscribeOnOperator<T>(scheduler, delay));\n  };\n}\n\nclass SubscribeOnOperator<T> implements Operator<T, T> {\n  constructor(private scheduler: SchedulerLike,\n              private delay: number) {\n  }\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return new SubscribeOnObservable<T>(\n      source, this.delay, this.scheduler\n    ).subscribe(subscriber);\n  }\n}\n","import { SchedulerLike, SchedulerAction } from '../types';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { Observable } from '../Observable';\nimport { asap } from '../scheduler/asap';\nimport { isNumeric } from '../util/isNumeric';\n\nexport interface DispatchArg<T> {\n  source: Observable<T>;\n  subscriber: Subscriber<T>;\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @extends {Ignored}\n * @hide true\n */\nexport class SubscribeOnObservable<T> extends Observable<T> {\n  /** @nocollapse */\n  static create<T>(source: Observable<T>, delay: number = 0, scheduler: SchedulerLike = asap): Observable<T> {\n    return new SubscribeOnObservable(source, delay, scheduler);\n  }\n\n  /** @nocollapse */\n  static dispatch<T>(this: SchedulerAction<T>, arg: DispatchArg<T>): Subscription {\n    const { source, subscriber } = arg;\n    return this.add(source.subscribe(subscriber));\n  }\n\n  constructor(public source: Observable<T>,\n              private delayTime: number = 0,\n              private scheduler: SchedulerLike = asap) {\n    super();\n    if (!isNumeric(delayTime) || delayTime < 0) {\n      this.delayTime = 0;\n    }\n    if (!scheduler || typeof scheduler.schedule !== 'function') {\n      this.scheduler = asap;\n    }\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _subscribe(subscriber: Subscriber<T>) {\n    const delay = this.delayTime;\n    const source = this.source;\n    const scheduler = this.scheduler;\n\n    return scheduler.schedule<DispatchArg<any>>(SubscribeOnObservable.dispatch, delay, {\n      source, subscriber\n    });\n  }\n}\n","import {OperatorFunction, ObservableInput} from '../types';\nimport { switchMap } from './switchMap';\nimport { identity } from '../util/identity';\n\nexport function switchAll<T>(): OperatorFunction<ObservableInput<T>, T>;\nexport function switchAll<R>(): OperatorFunction<any, R>;\n\n/**\n * Converts a higher-order Observable into a first-order Observable\n * producing values only from the most recent observable sequence\n *\n * <span class=\"informal\">Flattens an Observable-of-Observables.</span>\n *\n * ![](switchAll.png)\n *\n * `switchAll` subscribes to a source that is an observable of observables, also known as a\n * \"higher-order observable\" (or `Observable<Observable<T>>`). It subscribes to the most recently\n * provided \"inner observable\" emitted by the source, unsubscribing from any previously subscribed\n * to inner observable, such that only the most recent inner observable may be subscribed to at\n * any point in time. The resulting observable returned by `switchAll` will only complete if the\n * source observable completes, *and* any currently subscribed to inner observable also has completed,\n * if there are any.\n *\n * ## Examples\n * Spawn a new interval observable for each click event, but for every new\n * click, cancel the previous interval and subscribe to the new one.\n *\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { switchAll, map, tap } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click').pipe(tap(() => console.log('click')));\n * const source = clicks.pipe(map((ev) => interval(1000)));\n *\n * source.pipe(\n *   switchAll()\n * ).subscribe(x => console.log(x));\n *\n * // Output\n * // click\n * // 1\n * // 2\n * // 3\n * // 4\n * // ...\n * // click\n * // 1\n * // 2\n * // 3\n * // ...\n * // click\n * // ...\n * ```\n *\n * @see {@link combineAll}\n * @see {@link concatAll}\n * @see {@link exhaust}\n * @see {@link switchMap}\n * @see {@link switchMapTo}\n * @see {@link mergeAll}\n */\n\nexport function switchAll<T>(): OperatorFunction<ObservableInput<T>, T> {\n  return switchMap(identity);\n}\n","import { ObservableInput, OperatorFunction } from '../types';\nimport { switchMap } from './switchMap';\n\n/* tslint:disable:max-line-length */\nexport function switchMapTo<R>(observable: ObservableInput<R>): OperatorFunction<any, R>;\n/** @deprecated resultSelector is no longer supported. Switch to using switchMap with an inner map */\nexport function switchMapTo<T, R>(observable: ObservableInput<R>, resultSelector: undefined): OperatorFunction<T, R>;\n/** @deprecated resultSelector is no longer supported. Switch to using switchMap with an inner map */\nexport function switchMapTo<T, I, R>(observable: ObservableInput<I>, resultSelector: (outerValue: T, innerValue: I, outerIndex: number, innerIndex: number) => R): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to the same Observable which is flattened multiple\n * times with {@link switchMap} in the output Observable.\n *\n * <span class=\"informal\">It's like {@link switchMap}, but maps each value\n * always to the same inner Observable.</span>\n *\n * ![](switchMapTo.png)\n *\n * Maps each source value to the given Observable `innerObservable` regardless\n * of the source value, and then flattens those resulting Observables into one\n * single Observable, which is the output Observable. The output Observables\n * emits values only from the most recently emitted instance of\n * `innerObservable`.\n *\n * ## Example\n * Rerun an interval Observable on every click event\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { switchMapTo } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(switchMapTo(interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMapTo}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link mergeMapTo}\n *\n * @param {ObservableInput} innerObservable An Observable to replace each value from\n * the source Observable.\n * @return {Observable} An Observable that emits items from the given\n * `innerObservable` (and optionally transformed through the deprecated `resultSelector`)\n * every time a value is emitted on the source Observable, and taking only the values\n * from the most recently projected inner Observable.\n * @method switchMapTo\n * @owner Observable\n */\nexport function switchMapTo<T, I, R>(\n  innerObservable: ObservableInput<I>,\n  resultSelector?: (outerValue: T, innerValue: I, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, I|R> {\n  return resultSelector ? switchMap(() => innerObservable, resultSelector) : switchMap(() => innerObservable);\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\n\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\nimport { innerSubscribe, SimpleInnerSubscriber, SimpleOuterSubscriber } from '../innerSubscribe';\n\n/**\n * Emits the values emitted by the source Observable until a `notifier`\n * Observable emits a value.\n *\n * <span class=\"informal\">Lets values pass until a second Observable,\n * `notifier`, emits a value. Then, it completes.</span>\n *\n * ![](takeUntil.png)\n *\n * `takeUntil` subscribes and begins mirroring the source Observable. It also\n * monitors a second Observable, `notifier` that you provide. If the `notifier`\n * emits a value, the output Observable stops mirroring the source Observable\n * and completes. If the `notifier` doesn't emit any value and completes\n * then `takeUntil` will pass all values.\n *\n * ## Example\n * Tick every second until the first click happens\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { takeUntil } from 'rxjs/operators';\n *\n * const source = interval(1000);\n * const clicks = fromEvent(document, 'click');\n * const result = source.pipe(takeUntil(clicks));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link take}\n * @see {@link takeLast}\n * @see {@link takeWhile}\n * @see {@link skip}\n *\n * @param {Observable} notifier The Observable whose first emitted value will\n * cause the output Observable of `takeUntil` to stop emitting values from the\n * source Observable.\n * @return {Observable<T>} An Observable that emits the values from the source\n * Observable until such time as `notifier` emits its first value.\n * @method takeUntil\n * @owner Observable\n */\nexport function takeUntil<T>(notifier: Observable<any>): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => source.lift(new TakeUntilOperator(notifier));\n}\n\nclass TakeUntilOperator<T> implements Operator<T, T> {\n  constructor(private notifier: Observable<any>) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    const takeUntilSubscriber = new TakeUntilSubscriber(subscriber);\n    const notifierSubscription = innerSubscribe(this.notifier, new SimpleInnerSubscriber(takeUntilSubscriber));\n    if (notifierSubscription && !takeUntilSubscriber.seenValue) {\n      takeUntilSubscriber.add(notifierSubscription);\n      return source.subscribe(takeUntilSubscriber);\n    }\n    return takeUntilSubscriber;\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass TakeUntilSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n  seenValue = false;\n\n  constructor(destination: Subscriber<any>, ) {\n    super(destination);\n  }\n\n  notifyNext(): void {\n    this.seenValue = true;\n    this.complete();\n  }\n\n  notifyComplete(): void {\n    // noop\n  }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction, MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\nexport function takeWhile<T, S extends T>(predicate: (value: T, index: number) => value is S): OperatorFunction<T, S>;\nexport function takeWhile<T, S extends T>(predicate: (value: T, index: number) => value is S, inclusive: false): OperatorFunction<T, S>;\nexport function takeWhile<T>(predicate: (value: T, index: number) => boolean, inclusive?: boolean): MonoTypeOperatorFunction<T>;\n\n/**\n * Emits values emitted by the source Observable so long as each value satisfies\n * the given `predicate`, and then completes as soon as this `predicate` is not\n * satisfied.\n *\n * <span class=\"informal\">Takes values from the source only while they pass the\n * condition given. When the first value does not satisfy, it completes.</span>\n *\n * ![](takeWhile.png)\n *\n * `takeWhile` subscribes and begins mirroring the source Observable. Each value\n * emitted on the source is given to the `predicate` function which returns a\n * boolean, representing a condition to be satisfied by the source values. The\n * output Observable emits the source values until such time as the `predicate`\n * returns false, at which point `takeWhile` stops mirroring the source\n * Observable and completes the output Observable.\n *\n * ## Example\n * Emit click events only while the clientX property is greater than 200\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { takeWhile } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(takeWhile(ev => ev.clientX > 200));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link take}\n * @see {@link takeLast}\n * @see {@link takeUntil}\n * @see {@link skip}\n *\n * @param {function(value: T, index: number): boolean} predicate A function that\n * evaluates a value emitted by the source Observable and returns a boolean.\n * Also takes the (zero-based) index as the second argument.\n * @param {boolean} inclusive When set to `true` the value that caused\n * `predicate` to return `false` will also be emitted.\n * @return {Observable<T>} An Observable that emits the values from the source\n * Observable so long as each value satisfies the condition defined by the\n * `predicate`, then completes.\n * @method takeWhile\n * @owner Observable\n */\nexport function takeWhile<T>(\n    predicate: (value: T, index: number) => boolean,\n    inclusive = false): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) =>\n             source.lift(new TakeWhileOperator(predicate, inclusive));\n}\n\nclass TakeWhileOperator<T> implements Operator<T, T> {\n  constructor(\n      private predicate: (value: T, index: number) => boolean,\n      private inclusive: boolean) {}\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(\n        new TakeWhileSubscriber(subscriber, this.predicate, this.inclusive));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass TakeWhileSubscriber<T> extends Subscriber<T> {\n  private index: number = 0;\n\n  constructor(\n      destination: Subscriber<T>,\n      private predicate: (value: T, index: number) => boolean,\n      private inclusive: boolean) {\n    super(destination);\n  }\n\n  protected _next(value: T): void {\n    const destination = this.destination;\n    let result: boolean;\n    try {\n      result = this.predicate(value, this.index++);\n    } catch (err) {\n      destination.error(err);\n      return;\n    }\n    this.nextOrComplete(value, result);\n  }\n\n  private nextOrComplete(value: T, predicateResult: boolean): void {\n    const destination = this.destination;\n    if (Boolean(predicateResult)) {\n      destination.next(value);\n    } else {\n      if (this.inclusive) {\n        destination.next(value);\n      }\n      destination.complete();\n    }\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, PartialObserver, TeardownLogic } from '../types';\nimport { noop } from '../util/noop';\nimport { isFunction } from '../util/isFunction';\n\n/* tslint:disable:max-line-length */\n/** @deprecated Use an observer instead of a complete callback */\nexport function tap<T>(next: null | undefined, error: null | undefined, complete: () => void): MonoTypeOperatorFunction<T>;\n/** @deprecated Use an observer instead of an error callback */\nexport function tap<T>(next: null | undefined, error: (error: any) => void, complete?: () => void): MonoTypeOperatorFunction<T>;\n/** @deprecated Use an observer instead of a complete callback */\nexport function tap<T>(next: (value: T) => void, error: null | undefined, complete: () => void): MonoTypeOperatorFunction<T>;\nexport function tap<T>(next?: (x: T) => void, error?: (e: any) => void, complete?: () => void): MonoTypeOperatorFunction<T>;\nexport function tap<T>(observer: PartialObserver<T>): MonoTypeOperatorFunction<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Perform a side effect for every emission on the source Observable, but return\n * an Observable that is identical to the source.\n *\n * <span class=\"informal\">Intercepts each emission on the source and runs a\n * function, but returns an output which is identical to the source as long as errors don't occur.</span>\n *\n * ![](do.png)\n *\n * Returns a mirrored Observable of the source Observable, but modified so that\n * the provided Observer is called to perform a side effect for every value,\n * error, and completion emitted by the source. Any errors that are thrown in\n * the aforementioned Observer or handlers are safely sent down the error path\n * of the output Observable.\n *\n * This operator is useful for debugging your Observables for the correct values\n * or performing other side effects.\n *\n * Note: this is different to a `subscribe` on the Observable. If the Observable\n * returned by `tap` is not subscribed, the side effects specified by the\n * Observer will never happen. `tap` therefore simply spies on existing\n * execution, it does not trigger an execution to happen like `subscribe` does.\n *\n * ## Example\n * Map every click to the clientX position of that click, while also logging the click event\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { tap, map } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const positions = clicks.pipe(\n *   tap(ev => console.log(ev)),\n *   map(ev => ev.clientX),\n * );\n * positions.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link map}\n * @see {@link Observable#subscribe}\n *\n * @param {Observer|function} [nextOrObserver] A normal Observer object or a\n * callback for `next`.\n * @param {function} [error] Callback for errors in the source.\n * @param {function} [complete] Callback for the completion of the source.\n * @return {Observable} An Observable identical to the source, but runs the\n * specified Observer or callback(s) for each item.\n * @name tap\n */\nexport function tap<T>(nextOrObserver?: PartialObserver<T> | ((x: T) => void),\n                       error?: (e: any) => void,\n                       complete?: () => void): MonoTypeOperatorFunction<T> {\n  return function tapOperatorFunction(source: Observable<T>): Observable<T> {\n    return source.lift(new DoOperator(nextOrObserver, error, complete));\n  };\n}\n\nclass DoOperator<T> implements Operator<T, T> {\n  constructor(private nextOrObserver?: PartialObserver<T> | ((x: T) => void),\n              private error?: (e: any) => void,\n              private complete?: () => void) {\n  }\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\n\nclass TapSubscriber<T> extends Subscriber<T> {\n  private _context: any;\n\n  private _tapNext: ((value: T) => void) = noop;\n\n  private _tapError: ((err: any) => void) = noop;\n\n  private _tapComplete: (() => void) = noop;\n\n  constructor(destination: Subscriber<T>,\n              observerOrNext?: PartialObserver<T> | ((value: T) => void),\n              error?: (e?: any) => void,\n              complete?: () => void) {\n      super(destination);\n      this._tapError = error || noop;\n      this._tapComplete = complete || noop;\n      if (isFunction(observerOrNext)) {\n        this._context = this;\n        this._tapNext = observerOrNext;\n      } else if (observerOrNext) {\n        this._context = observerOrNext;\n        this._tapNext = observerOrNext.next || noop;\n        this._tapError = observerOrNext.error || noop;\n        this._tapComplete = observerOrNext.complete || noop;\n      }\n    }\n\n  _next(value: T) {\n    try {\n      this._tapNext.call(this._context, value);\n    } catch (err) {\n      this.destination.error(err);\n      return;\n    }\n    this.destination.next(value);\n  }\n\n  _error(err: any) {\n    try {\n      this._tapError.call(this._context, err);\n    } catch (err) {\n      this.destination.error(err);\n      return;\n    }\n    this.destination.error(err);\n  }\n\n  _complete() {\n    try {\n      this._tapComplete.call(this._context, );\n    } catch (err) {\n      this.destination.error(err);\n      return;\n    }\n    return this.destination.complete();\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { async } from '../scheduler/async';\nimport { Observable } from '../Observable';\nimport { ThrottleConfig, defaultThrottleConfig } from './throttle';\nimport { MonoTypeOperatorFunction, SchedulerLike, TeardownLogic } from '../types';\n\n/**\n * Emits a value from the source Observable, then ignores subsequent source\n * values for `duration` milliseconds, then repeats this process.\n *\n * <span class=\"informal\">Lets a value pass, then ignores source values for the\n * next `duration` milliseconds.</span>\n *\n * ![](throttleTime.png)\n *\n * `throttleTime` emits the source Observable values on the output Observable\n * when its internal timer is disabled, and ignores source values when the timer\n * is enabled. Initially, the timer is disabled. As soon as the first source\n * value arrives, it is forwarded to the output Observable, and then the timer\n * is enabled. After `duration` milliseconds (or the time unit determined\n * internally by the optional `scheduler`) has passed, the timer is disabled,\n * and this process repeats for the next source value. Optionally takes a\n * {@link SchedulerLike} for managing timers.\n *\n * ## Examples\n *\n * #### Limit click rate\n *\n * Emit clicks at a rate of at most one click per second\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { throttleTime } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(throttleTime(1000));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * #### Double Click\n *\n * The following example only emits clicks which happen within a subsequent\n * delay of 400ms of the previous click. This for example can emulate a double\n * click. It makes use of the `trailing` parameter of the throttle configuration.\n *\n * ```ts\n * import { fromEvent, asyncScheduler } from 'rxjs';\n * import { throttleTime, withLatestFrom } from 'rxjs/operators';\n *\n * // defaultThottleConfig = { leading: true, trailing: false }\n * const throttleConfig = {\n *   leading: false,\n *   trailing: true\n * }\n *\n * const click = fromEvent(document, 'click');\n * const doubleClick = click.pipe(\n *   throttleTime(400, asyncScheduler, throttleConfig)\n * );\n *\n * doubleClick.subscribe((throttleValue: Event) => {\n *   console.log(`Double-clicked! Timestamp: ${throttleValue.timeStamp}`);\n * });\n * ```\n *\n * If you enable the `leading` parameter in this example, the output would be the primary click and\n * the double click, but restricts additional clicks within 400ms.\n *\n * @see {@link auditTime}\n * @see {@link debounceTime}\n * @see {@link delay}\n * @see {@link sampleTime}\n * @see {@link throttle}\n *\n * @param {number} duration Time to wait before emitting another value after\n * emitting the last value, measured in milliseconds or the time unit determined\n * internally by the optional `scheduler`.\n * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for\n * managing the timers that handle the throttling.\n * @param {Object} config a configuration object to define `leading` and\n * `trailing` behavior. Defaults to `{ leading: true, trailing: false }`.\n * @return {Observable<T>} An Observable that performs the throttle operation to\n * limit the rate of emissions from the source.\n * @method throttleTime\n * @owner Observable\n */\nexport function throttleTime<T>(duration: number,\n                                scheduler: SchedulerLike = async,\n                                config: ThrottleConfig = defaultThrottleConfig): MonoTypeOperatorFunction<T> {\n  return (source: Observable<T>) => source.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing));\n}\n\nclass ThrottleTimeOperator<T> implements Operator<T, T> {\n  constructor(private duration: number,\n              private scheduler: SchedulerLike,\n              private leading: boolean,\n              private trailing: boolean) {\n  }\n\n  call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n    return source.subscribe(\n      new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing)\n    );\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass ThrottleTimeSubscriber<T> extends Subscriber<T> {\n  private throttled: Subscription;\n  private _hasTrailingValue: boolean = false;\n  private _trailingValue: T = null;\n\n  constructor(destination: Subscriber<T>,\n              private duration: number,\n              private scheduler: SchedulerLike,\n              private leading: boolean,\n              private trailing: boolean) {\n    super(destination);\n  }\n\n  protected _next(value: T) {\n    if (this.throttled) {\n      if (this.trailing) {\n        this._trailingValue = value;\n        this._hasTrailingValue = true;\n      }\n    } else {\n      this.add(this.throttled = this.scheduler.schedule<DispatchArg<T>>(dispatchNext, this.duration, { subscriber: this }));\n      if (this.leading) {\n        this.destination.next(value);\n      } else if (this.trailing) {\n        this._trailingValue = value;\n        this._hasTrailingValue = true;\n      }\n    }\n  }\n\n  protected _complete() {\n    if (this._hasTrailingValue) {\n      this.destination.next(this._trailingValue);\n      this.destination.complete();\n    } else {\n      this.destination.complete();\n    }\n  }\n\n  clearThrottle() {\n    const throttled = this.throttled;\n    if (throttled) {\n      if (this.trailing && this._hasTrailingValue) {\n        this.destination.next(this._trailingValue);\n        this._trailingValue = null;\n        this._hasTrailingValue = false;\n      }\n      throttled.unsubscribe();\n      this.remove(throttled);\n      this.throttled = null;\n    }\n  }\n}\n\ninterface DispatchArg<T> {\n  subscriber: ThrottleTimeSubscriber<T>;\n}\n\nfunction dispatchNext<T>(arg: DispatchArg<T>) {\n  const { subscriber } = arg;\n  subscriber.clearThrottle();\n}\n","\nimport { Observable } from '../Observable';\nimport { async } from '../scheduler/async';\nimport { SchedulerLike, OperatorFunction } from '../types';\nimport { scan } from './scan';\nimport { defer } from '../observable/defer';\nimport { map } from './map';\n\n/**\n *\n * Emits an object containing the current value, and the time that has\n * passed between emitting the current value and the previous value, which is\n * calculated by using the provided `scheduler`'s `now()` method to retrieve\n * the current time at each emission, then calculating the difference. The `scheduler`\n * defaults to {@link asyncScheduler}, so by default, the `interval` will be in\n * milliseconds.\n *\n * <span class=\"informal\">Convert an Observable that emits items into one that\n * emits indications of the amount of time elapsed between those emissions.</span>\n *\n * ![](timeinterval.png)\n *\n * ## Examples\n * Emit inteval between current value with the last value\n *\n * ```ts\n * const seconds = interval(1000);\n *\n * seconds.pipe(timeInterval())\n * .subscribe(\n *     value => console.log(value),\n *     err => console.log(err),\n * );\n *\n * seconds.pipe(timeout(900))\n * .subscribe(\n *     value => console.log(value),\n *     err => console.log(err),\n * );\n *\n * // NOTE: The values will never be this precise,\n * // intervals created with `interval` or `setInterval`\n * // are non-deterministic.\n *\n * // {value: 0, interval: 1000}\n * // {value: 1, interval: 1000}\n * // {value: 2, interval: 1000}\n * ```\n *\n * @param {SchedulerLike} [scheduler] Scheduler used to get the current time.\n * @return {Observable<{ interval: number, value: T }>} Observable that emit infomation about value and interval\n * @method timeInterval\n */\nexport function timeInterval<T>(scheduler: SchedulerLike = async): OperatorFunction<T, TimeInterval<T>> {\n  return (source: Observable<T>) => defer(() => {\n    return source.pipe(\n      // TODO(benlesh): correct these typings.\n      scan(\n        ({ current }, value) => ({ value, current: scheduler.now(), last: current }),\n        { current: scheduler.now(), value: undefined,  last: undefined }\n      ) as any,\n      map<any, TimeInterval<T>>(({ current, last, value }) => new TimeInterval(value, current - last)),\n    );\n  });\n}\n\n// TODO(benlesh): make this an interface, export the interface, but not the implemented class,\n// there's no reason users should be manually creating this type.\n\n/**\n * @deprecated exposed API, use as interface only.\n */\nexport class TimeInterval<T> {\n  constructor(public value: T, public interval: number) {}\n}\n","import { async } from '../scheduler/async';\nimport { isDate } from '../util/isDate';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { TimeoutError } from '../util/TimeoutError';\nimport { MonoTypeOperatorFunction, SchedulerAction, SchedulerLike, TeardownLogic } from '../types';\nimport { timeoutWith } from './timeoutWith';\nimport { throwError } from '../observable/throwError';\n\n/**\n *\n * Errors if Observable does not emit a value in given time span.\n *\n * <span class=\"informal\">Timeouts on Observable that doesn't emit values fast enough.</span>\n *\n * ![](timeout.png)\n *\n * `timeout` operator accepts as an argument either a number or a Date.\n *\n * If number was provided, it returns an Observable that behaves like a source\n * Observable, unless there is a period of time where there is no value emitted.\n * So if you provide `100` as argument and first value comes after 50ms from\n * the moment of subscription, this value will be simply re-emitted by the resulting\n * Observable. If however after that 100ms passes without a second value being emitted,\n * stream will end with an error and source Observable will be unsubscribed.\n * These checks are performed throughout whole lifecycle of Observable - from the moment\n * it was subscribed to, until it completes or errors itself. Thus every value must be\n * emitted within specified period since previous value.\n *\n * If provided argument was Date, returned Observable behaves differently. It throws\n * if Observable did not complete before provided Date. This means that periods between\n * emission of particular values do not matter in this case. If Observable did not complete\n * before provided Date, source Observable will be unsubscribed. Other than that, resulting\n * stream behaves just as source Observable.\n *\n * `timeout` accepts also a Scheduler as a second parameter. It is used to schedule moment (or moments)\n * when returned Observable will check if source stream emitted value or completed.\n *\n * ## Examples\n * Check if ticks are emitted within certain timespan\n * ```ts\n * import { interval } from 'rxjs';\n * import { timeout } from 'rxjs/operators';\n *\n * const seconds = interval(1000);\n *\n * seconds.pipe(timeout(1100))      // Let's use bigger timespan to be safe,\n *                                  // since `interval` might fire a bit later then scheduled.\n * .subscribe(\n *     value => console.log(value), // Will emit numbers just as regular `interval` would.\n *     err => console.log(err),     // Will never be called.\n * );\n *\n * seconds.pipe(timeout(900))\n * .subscribe(\n *     value => console.log(value), // Will never be called.\n *     err => console.log(err),     // Will emit error before even first value is emitted,\n *                                  // since it did not arrive within 900ms period.\n * );\n * ```\n *\n * Use Date to check if Observable completed\n * ```ts\n * import { interval } from 'rxjs';\n * import { timeout } from 'rxjs/operators';\n *\n * const seconds = interval(1000);\n *\n * seconds.pipe(\n *   timeout(new Date(\"December 17, 2020 03:24:00\")),\n * )\n * .subscribe(\n *     value => console.log(value), // Will emit values as regular `interval` would\n *                                  // until December 17, 2020 at 03:24:00.\n *     err => console.log(err)      // On December 17, 2020 at 03:24:00 it will emit an error,\n *                                  // since Observable did not complete by then.\n * );\n * ```\n * @see {@link timeoutWith}\n *\n * @param {number|Date} due Number specifying period within which Observable must emit values\n *                          or Date specifying before when Observable should complete\n * @param {SchedulerLike} [scheduler] Scheduler controlling when timeout checks occur.\n * @return {Observable<T>} Observable that mirrors behaviour of source, unless timeout checks fail.\n * @method timeout\n * @owner Observable\n */\nexport function timeout<T>(due: number | Date,\n                           scheduler: SchedulerLike = async): MonoTypeOperatorFunction<T> {\n  return timeoutWith(due, throwError(new TimeoutError()), scheduler);\n}\n","\nimport { async } from '../scheduler/async';\nimport { OperatorFunction, SchedulerLike, Timestamp as TimestampInterface } from '../types';\nimport { map } from './map';\n\n/**\n * Attaches a timestamp to each item emitted by an observable indicating when it was emitted\n *\n * The `timestamp` operator maps the *source* observable stream to an object of type\n * `{value: T, timestamp: R}`. The properties are generically typed. The `value` property contains the value\n * and type of the *source* observable. The `timestamp` is generated by the schedulers `now` function. By\n * default it uses the *async* scheduler which simply returns `Date.now()` (milliseconds since 1970/01/01\n * 00:00:00:000) and therefore is of type `number`.\n *\n * ![](timestamp.png)\n *\n * ## Example\n *\n * In this example there is a timestamp attached to the documents click event.\n *\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { timestamp } from 'rxjs/operators';\n *\n * const clickWithTimestamp = fromEvent(document, 'click').pipe(\n *   timestamp()\n * );\n *\n * // Emits data of type {value: MouseEvent, timestamp: number}\n * clickWithTimestamp.subscribe(data => {\n *   console.log(data);\n * });\n * ```\n *\n * @param scheduler\n * @return {Observable<Timestamp<any>>|WebSocketSubject<T>|Observable<T>}\n * @method timestamp\n * @owner Observable\n */\nexport function timestamp<T>(scheduler: SchedulerLike = async): OperatorFunction<T, Timestamp<T>> {\n  return map((value: T) => new Timestamp(value, scheduler.now()));\n  // return (source: Observable<T>) => source.lift(new TimestampOperator(scheduler));\n}\n\nexport class Timestamp<T> implements TimestampInterface<T> {\n  constructor(public value: T, public timestamp: number) {\n  }\n}\n","import { reduce } from './reduce';\nimport { OperatorFunction } from '../types';\n\nfunction toArrayReducer<T>(arr: T[], item: T, index: number) {\n  if (index === 0) {\n    return [item];\n  }\n  arr.push(item);\n  return arr;\n}\n\n/**\n * Collects all source emissions and emits them as an array when the source completes.\n *\n * <span class=\"informal\">Get all values inside an array when the source completes</span>\n *\n * ![](toArray.png)\n *\n * `toArray` will wait until the source Observable completes before emitting\n * the array containing all emissions. When the source Observable errors no\n * array will be emitted.\n *\n *  ## Example\n * ```ts\n * import { interval } from 'rxjs';\n * import { toArray, take } from 'rxjs/operators';\n *\n * const source = interval(1000);\n * const example = source.pipe(\n *   take(10),\n *   toArray()\n * );\n *\n * const subscribe = example.subscribe(val => console.log(val));\n *\n * // output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n *\n * ```\n* @return An array from an observable sequence.\n* @method toArray\n* @owner Observable\n*/\nexport function toArray<T>(): OperatorFunction<T, T[]> {\n  return reduce(toArrayReducer, [] as T[]);\n}\n","import { Observable } from '../Observable';\nimport { OperatorFunction } from '../types';\nimport { Subject } from '../Subject';\nimport { Subscriber } from '../Subscriber';\nimport { Operator } from '../Operator';\nimport { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';\n\n/**\n * Branch out the source Observable values as a nested Observable whenever\n * `windowBoundaries` emits.\n *\n * <span class=\"informal\">It's like {@link buffer}, but emits a nested Observable\n * instead of an array.</span>\n *\n * ![](window.png)\n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable emits connected, non-overlapping\n * windows. It emits the current window and opens a new one whenever the\n * Observable `windowBoundaries` emits an item. Because each window is an\n * Observable, the output is a higher-order Observable.\n *\n * ## Example\n * In every window of 1 second each, emit at most 2 click events\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { window, mergeAll, map, take } from 'rxjs/operators';\n *\n *  const clicks = fromEvent(document, 'click');\n *  const sec = interval(1000);\n *  const result = clicks.pipe(\n *      window(sec),\n *      map(win => win.pipe(take(2))), // each window has at most 2 emissions\n *      mergeAll(),              // flatten the Observable-of-Observables\n *  );\n *  result.subscribe(x => console.log(x));\n * ```\n * @see {@link windowCount}\n * @see {@link windowTime}\n * @see {@link windowToggle}\n * @see {@link windowWhen}\n * @see {@link buffer}\n *\n * @param {Observable<any>} windowBoundaries An Observable that completes the\n * previous window and starts a new window.\n * @return {Observable<Observable<T>>} An Observable of windows, which are\n * Observables emitting values of the source Observable.\n * @method window\n * @owner Observable\n */\nexport function window<T>(windowBoundaries: Observable<any>): OperatorFunction<T, Observable<T>> {\n  return function windowOperatorFunction(source: Observable<T>) {\n    return source.lift(new WindowOperator(windowBoundaries));\n  };\n}\n\nclass WindowOperator<T> implements Operator<T, Observable<T>> {\n\n  constructor(private windowBoundaries: Observable<any>) {\n  }\n\n  call(subscriber: Subscriber<Observable<T>>, source: any): any {\n    const windowSubscriber = new WindowSubscriber(subscriber);\n    const sourceSubscription = source.subscribe(windowSubscriber);\n    if (!sourceSubscription.closed) {\n      windowSubscriber.add(innerSubscribe(this.windowBoundaries, new SimpleInnerSubscriber(windowSubscriber)));\n    }\n    return sourceSubscription;\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass WindowSubscriber<T> extends SimpleOuterSubscriber<T, any> {\n\n  private window: Subject<T> = new Subject<T>();\n\n  constructor(destination: Subscriber<Observable<T>>) {\n    super(destination);\n    destination.next(this.window);\n  }\n\n  notifyNext(): void {\n    this.openWindow();\n  }\n\n  notifyError(error: any): void {\n    this._error(error);\n  }\n\n  notifyComplete(): void {\n    this._complete();\n  }\n\n  protected _next(value: T): void {\n    this.window.next(value);\n  }\n\n  protected _error(err: any): void {\n    this.window.error(err);\n    this.destination.error!(err);\n  }\n\n  protected _complete(): void {\n    this.window.complete();\n    this.destination.complete!();\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _unsubscribe() {\n    this.window = null!;\n  }\n\n  private openWindow(): void  {\n    const prevWindow = this.window;\n    if (prevWindow) {\n      prevWindow.complete();\n    }\n    const destination = this.destination;\n    const newWindow = this.window = new Subject<T>();\n    destination.next!(newWindow);\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { OperatorFunction } from '../types';\n\n/**\n * Branch out the source Observable values as a nested Observable with each\n * nested Observable emitting at most `windowSize` values.\n *\n * <span class=\"informal\">It's like {@link bufferCount}, but emits a nested\n * Observable instead of an array.</span>\n *\n * ![](windowCount.png)\n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable emits windows every `startWindowEvery`\n * items, each containing no more than `windowSize` items. When the source\n * Observable completes or encounters an error, the output Observable emits\n * the current window and propagates the notification from the source\n * Observable. If `startWindowEvery` is not provided, then new windows are\n * started immediately at the start of the source and when each window completes\n * with size `windowSize`.\n *\n * ## Examples\n * Ignore every 3rd click event, starting from the first one\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { windowCount, map, mergeAll, skip } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n *   windowCount(3),\n *   map(win => win.pipe(skip(1))), // skip first of every 3 clicks\n *   mergeAll()                     // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Ignore every 3rd click event, starting from the third one\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { windowCount, mergeAll } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n *   windowCount(2, 3),\n *   mergeAll(),              // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link window}\n * @see {@link windowTime}\n * @see {@link windowToggle}\n * @see {@link windowWhen}\n * @see {@link bufferCount}\n *\n * @param {number} windowSize The maximum number of values emitted by each\n * window.\n * @param {number} [startWindowEvery] Interval at which to start a new window.\n * For example if `startWindowEvery` is `2`, then a new window will be started\n * on every other value from the source. A new window is started at the\n * beginning of the source by default.\n * @return {Observable<Observable<T>>} An Observable of windows, which in turn\n * are Observable of values.\n * @method windowCount\n * @owner Observable\n */\nexport function windowCount<T>(windowSize: number,\n                               startWindowEvery: number = 0): OperatorFunction<T, Observable<T>> {\n  return function windowCountOperatorFunction(source: Observable<T>) {\n    return source.lift(new WindowCountOperator<T>(windowSize, startWindowEvery));\n  };\n}\n\nclass WindowCountOperator<T> implements Operator<T, Observable<T>> {\n\n  constructor(private windowSize: number,\n              private startWindowEvery: number) {\n  }\n\n  call(subscriber: Subscriber<Observable<T>>, source: any): any {\n    return source.subscribe(new WindowCountSubscriber(subscriber, this.windowSize, this.startWindowEvery));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass WindowCountSubscriber<T> extends Subscriber<T> {\n  private windows: Subject<T>[] = [ new Subject<T>() ];\n  private count: number = 0;\n\n  constructor(protected destination: Subscriber<Observable<T>>,\n              private windowSize: number,\n              private startWindowEvery: number) {\n    super(destination);\n    destination.next(this.windows[0]);\n  }\n\n  protected _next(value: T) {\n    const startWindowEvery = (this.startWindowEvery > 0) ? this.startWindowEvery : this.windowSize;\n    const destination = this.destination;\n    const windowSize = this.windowSize;\n    const windows = this.windows;\n    const len = windows.length;\n\n    for (let i = 0; i < len && !this.closed; i++) {\n      windows[i].next(value);\n    }\n    const c = this.count - windowSize + 1;\n    if (c >= 0 && c % startWindowEvery === 0 && !this.closed) {\n      windows.shift().complete();\n    }\n    if (++this.count % startWindowEvery === 0 && !this.closed) {\n      const window = new Subject<T>();\n      windows.push(window);\n      destination.next(window);\n    }\n  }\n\n  protected _error(err: any) {\n    const windows = this.windows;\n    if (windows) {\n      while (windows.length > 0 && !this.closed) {\n        windows.shift().error(err);\n      }\n    }\n    this.destination.error(err);\n  }\n\n  protected _complete() {\n    const windows = this.windows;\n    if (windows) {\n      while (windows.length > 0 && !this.closed) {\n        windows.shift().complete();\n      }\n    }\n    this.destination.complete();\n  }\n\n  protected _unsubscribe() {\n    this.count = 0;\n    this.windows = null;\n  }\n}\n","import { Subject } from '../Subject';\nimport { Operator } from '../Operator';\nimport { async } from '../scheduler/async';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { isNumeric } from '../util/isNumeric';\nimport { isScheduler } from '../util/isScheduler';\nimport { OperatorFunction, SchedulerLike, SchedulerAction } from '../types';\n\n/**\n * Branch out the source Observable values as a nested Observable periodically\n * in time.\n *\n * <span class=\"informal\">It's like {@link bufferTime}, but emits a nested\n * Observable instead of an array.</span>\n *\n * ![](windowTime.png)\n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable starts a new window periodically, as\n * determined by the `windowCreationInterval` argument. It emits each window\n * after a fixed timespan, specified by the `windowTimeSpan` argument. When the\n * source Observable completes or encounters an error, the output Observable\n * emits the current window and propagates the notification from the source\n * Observable. If `windowCreationInterval` is not provided, the output\n * Observable starts a new window when the previous window of duration\n * `windowTimeSpan` completes. If `maxWindowCount` is provided, each window\n * will emit at most fixed number of values. Window will complete immediately\n * after emitting last value and next one still will open as specified by\n * `windowTimeSpan` and `windowCreationInterval` arguments.\n *\n * ## Examples\n * In every window of 1 second each, emit at most 2 click events\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { windowTime, map, mergeAll, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n *   windowTime(1000),\n *   map(win => win.pipe(take(2))), // each window has at most 2 emissions\n *   mergeAll(),                    // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Every 5 seconds start a window 1 second long, and emit at most 2 click events per window\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { windowTime, map, mergeAll, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n *   windowTime(1000, 5000),\n *   map(win => win.pipe(take(2))), // each window has at most 2 emissions\n *   mergeAll(),                    // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Same as example above but with maxWindowCount instead of take\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { windowTime, mergeAll } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n *   windowTime(1000, 5000, 2), // each window has still at most 2 emissions\n *   mergeAll(),                // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link window}\n * @see {@link windowCount}\n * @see {@link windowToggle}\n * @see {@link windowWhen}\n * @see {@link bufferTime}\n *\n * @param {number} windowTimeSpan The amount of time to fill each window.\n * @param {number} [windowCreationInterval] The interval at which to start new\n * windows.\n * @param {number} [maxWindowSize=Number.POSITIVE_INFINITY] Max number of\n * values each window can emit before completion.\n * @param {SchedulerLike} [scheduler=async] The scheduler on which to schedule the\n * intervals that determine window boundaries.\n * @return {Observable<Observable<T>>} An observable of windows, which in turn\n * are Observables.\n * @method windowTime\n * @owner Observable\n */\nexport function windowTime<T>(windowTimeSpan: number,\n                              scheduler?: SchedulerLike): OperatorFunction<T, Observable<T>>;\nexport function windowTime<T>(windowTimeSpan: number,\n                              windowCreationInterval: number,\n                              scheduler?: SchedulerLike): OperatorFunction<T, Observable<T>>;\nexport function windowTime<T>(windowTimeSpan: number,\n                              windowCreationInterval: number,\n                              maxWindowSize: number,\n                              scheduler?: SchedulerLike): OperatorFunction<T, Observable<T>>;\n\nexport function windowTime<T>(windowTimeSpan: number): OperatorFunction<T, Observable<T>> {\n  let scheduler: SchedulerLike = async;\n  let windowCreationInterval: number = null;\n  let maxWindowSize: number = Number.POSITIVE_INFINITY;\n\n  if (isScheduler(arguments[3])) {\n    scheduler = arguments[3];\n  }\n\n  if (isScheduler(arguments[2])) {\n    scheduler = arguments[2];\n  } else if (isNumeric(arguments[2])) {\n    maxWindowSize = Number(arguments[2]);\n  }\n\n  if (isScheduler(arguments[1])) {\n    scheduler = arguments[1];\n  } else if (isNumeric(arguments[1])) {\n    windowCreationInterval = Number(arguments[1]);\n  }\n\n  return function windowTimeOperatorFunction(source: Observable<T>) {\n    return source.lift(new WindowTimeOperator<T>(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler));\n  };\n}\n\nclass WindowTimeOperator<T> implements Operator<T, Observable<T>> {\n\n  constructor(private windowTimeSpan: number,\n              private windowCreationInterval: number | null,\n              private maxWindowSize: number,\n              private scheduler: SchedulerLike) {\n  }\n\n  call(subscriber: Subscriber<Observable<T>>, source: any): any {\n    return source.subscribe(new WindowTimeSubscriber(\n      subscriber, this.windowTimeSpan, this.windowCreationInterval, this.maxWindowSize, this.scheduler\n    ));\n  }\n}\n\ninterface CreationState<T> {\n  windowTimeSpan: number;\n  windowCreationInterval: number;\n  subscriber: WindowTimeSubscriber<T>;\n  scheduler: SchedulerLike;\n}\n\ninterface TimeSpanOnlyState<T> {\n    window: CountedSubject<T>;\n    windowTimeSpan: number;\n    subscriber: WindowTimeSubscriber<T>;\n  }\n\ninterface CloseWindowContext<T> {\n  action: SchedulerAction<CreationState<T>>;\n  subscription: Subscription;\n}\n\ninterface CloseState<T> {\n  subscriber: WindowTimeSubscriber<T>;\n  window: CountedSubject<T>;\n  context: CloseWindowContext<T>;\n}\n\nclass CountedSubject<T> extends Subject<T> {\n  private _numberOfNextedValues: number = 0;\n\n  next(value?: T): void {\n    this._numberOfNextedValues++;\n    super.next(value);\n  }\n\n  get numberOfNextedValues(): number {\n    return this._numberOfNextedValues;\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass WindowTimeSubscriber<T> extends Subscriber<T> {\n  private windows: CountedSubject<T>[] = [];\n\n  constructor(protected destination: Subscriber<Observable<T>>,\n              private windowTimeSpan: number,\n              private windowCreationInterval: number | null,\n              private maxWindowSize: number,\n              private scheduler: SchedulerLike) {\n    super(destination);\n\n    const window = this.openWindow();\n    if (windowCreationInterval !== null && windowCreationInterval >= 0) {\n      const closeState: CloseState<T> = { subscriber: this, window, context: <any>null };\n      const creationState: CreationState<T> = { windowTimeSpan, windowCreationInterval, subscriber: this, scheduler };\n      this.add(scheduler.schedule<CloseState<T>>(dispatchWindowClose, windowTimeSpan, closeState));\n      this.add(scheduler.schedule<CreationState<T>>(dispatchWindowCreation, windowCreationInterval, creationState));\n    } else {\n      const timeSpanOnlyState: TimeSpanOnlyState<T> = { subscriber: this, window, windowTimeSpan };\n      this.add(scheduler.schedule<TimeSpanOnlyState<T>>(dispatchWindowTimeSpanOnly, windowTimeSpan, timeSpanOnlyState));\n    }\n  }\n\n  protected _next(value: T): void {\n    const windows = this.windows;\n    const len = windows.length;\n    for (let i = 0; i < len; i++) {\n      const window = windows[i];\n      if (!window.closed) {\n        window.next(value);\n        if (window.numberOfNextedValues >= this.maxWindowSize) {\n          this.closeWindow(window);\n        }\n      }\n    }\n  }\n\n  protected _error(err: any): void {\n    const windows = this.windows;\n    while (windows.length > 0) {\n      windows.shift().error(err);\n    }\n    this.destination.error(err);\n  }\n\n  protected _complete(): void {\n    const windows = this.windows;\n    while (windows.length > 0) {\n      const window = windows.shift();\n      if (!window.closed) {\n        window.complete();\n      }\n    }\n    this.destination.complete();\n  }\n\n  public openWindow(): CountedSubject<T> {\n    const window = new CountedSubject<T>();\n    this.windows.push(window);\n    const destination = this.destination;\n    destination.next(window);\n    return window;\n  }\n\n  public closeWindow(window: CountedSubject<T>): void {\n    window.complete();\n    const windows = this.windows;\n    windows.splice(windows.indexOf(window), 1);\n  }\n}\n\nfunction dispatchWindowTimeSpanOnly<T>(this: SchedulerAction<TimeSpanOnlyState<T>>, state: TimeSpanOnlyState<T>): void {\n  const { subscriber, windowTimeSpan, window } = state;\n  if (window) {\n    subscriber.closeWindow(window);\n  }\n  state.window = subscriber.openWindow();\n  this.schedule(state, windowTimeSpan);\n}\n\nfunction dispatchWindowCreation<T>(this: SchedulerAction<CreationState<T>>, state: CreationState<T>): void {\n  const { windowTimeSpan, subscriber, scheduler, windowCreationInterval } = state;\n  const window = subscriber.openWindow();\n  const action = this;\n  let context: CloseWindowContext<T> = { action, subscription: <any>null };\n  const timeSpanState: CloseState<T> = { subscriber, window, context };\n  context.subscription = scheduler.schedule<CloseState<T>>(dispatchWindowClose, windowTimeSpan, timeSpanState);\n  action.add(context.subscription);\n  action.schedule(state, windowCreationInterval);\n}\n\nfunction dispatchWindowClose<T>(state: CloseState<T>): void {\n  const { subscriber, window, context } = state;\n  if (context && context.action && context.subscription) {\n    context.action.remove(context.subscription);\n  }\n  subscriber.closeWindow(window);\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { Subscription } from '../Subscription';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { OperatorFunction } from '../types';\n\n/**\n * Branch out the source Observable values as a nested Observable starting from\n * an emission from `openings` and ending when the output of `closingSelector`\n * emits.\n *\n * <span class=\"informal\">It's like {@link bufferToggle}, but emits a nested\n * Observable instead of an array.</span>\n *\n * ![](windowToggle.png)\n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable emits windows that contain those items\n * emitted by the source Observable between the time when the `openings`\n * Observable emits an item and when the Observable returned by\n * `closingSelector` emits an item.\n *\n * ## Example\n * Every other second, emit the click events from the next 500ms\n * ```ts\n * import { fromEvent, interval, EMPTY } from 'rxjs';\n * import { windowToggle, mergeAll } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const openings = interval(1000);\n * const result = clicks.pipe(\n *   windowToggle(openings, i => i % 2 ? interval(500) : EMPTY),\n *   mergeAll()\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link window}\n * @see {@link windowCount}\n * @see {@link windowTime}\n * @see {@link windowWhen}\n * @see {@link bufferToggle}\n *\n * @param {Observable<O>} openings An observable of notifications to start new\n * windows.\n * @param {function(value: O): Observable} closingSelector A function that takes\n * the value emitted by the `openings` observable and returns an Observable,\n * which, when it emits (either `next` or `complete`), signals that the\n * associated window should complete.\n * @return {Observable<Observable<T>>} An observable of windows, which in turn\n * are Observables.\n * @method windowToggle\n * @owner Observable\n */\nexport function windowToggle<T, O>(openings: Observable<O>,\n                                   closingSelector: (openValue: O) => Observable<any>): OperatorFunction<T, Observable<T>> {\n  return (source: Observable<T>) => source.lift(new WindowToggleOperator<T, O>(openings, closingSelector));\n}\n\nclass WindowToggleOperator<T, O> implements Operator<T, Observable<T>> {\n\n  constructor(private openings: Observable<O>,\n              private closingSelector: (openValue: O) => Observable<any>) {\n  }\n\n  call(subscriber: Subscriber<Observable<T>>, source: any): any {\n    return source.subscribe(new WindowToggleSubscriber(\n      subscriber, this.openings, this.closingSelector\n    ));\n  }\n}\n\ninterface WindowContext<T> {\n  window: Subject<T>;\n  subscription: Subscription;\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass WindowToggleSubscriber<T, O> extends OuterSubscriber<T, any> {\n  private contexts: WindowContext<T>[] = [];\n  private openSubscription: Subscription;\n\n  constructor(destination: Subscriber<Observable<T>>,\n              private openings: Observable<O>,\n              private closingSelector: (openValue: O) => Observable<any>) {\n    super(destination);\n    this.add(this.openSubscription = subscribeToResult(this, openings, openings as any));\n  }\n\n  protected _next(value: T) {\n    const { contexts } = this;\n    if (contexts) {\n      const len = contexts.length;\n      for (let i = 0; i < len; i++) {\n        contexts[i].window.next(value);\n      }\n    }\n  }\n\n  protected _error(err: any) {\n\n    const { contexts } = this;\n    this.contexts = null;\n\n    if (contexts) {\n      const len = contexts.length;\n      let index = -1;\n\n      while (++index < len) {\n        const context = contexts[index];\n        context.window.error(err);\n        context.subscription.unsubscribe();\n      }\n    }\n\n    super._error(err);\n  }\n\n  protected _complete() {\n    const { contexts } = this;\n    this.contexts = null;\n    if (contexts) {\n      const len = contexts.length;\n      let index = -1;\n      while (++index < len) {\n        const context = contexts[index];\n        context.window.complete();\n        context.subscription.unsubscribe();\n      }\n    }\n    super._complete();\n  }\n\n  /** @deprecated This is an internal implementation detail, do not use. */\n  _unsubscribe() {\n    const { contexts } = this;\n    this.contexts = null;\n    if (contexts) {\n      const len = contexts.length;\n      let index = -1;\n      while (++index < len) {\n        const context = contexts[index];\n        context.window.unsubscribe();\n        context.subscription.unsubscribe();\n      }\n    }\n  }\n\n  notifyNext(outerValue: any, innerValue: any,\n             outerIndex: number, innerIndex: number,\n             innerSub: InnerSubscriber<T, any>): void {\n\n    if (outerValue === this.openings) {\n      let closingNotifier;\n      try {\n        const { closingSelector } = this;\n        closingNotifier = closingSelector(innerValue);\n      } catch (e) {\n        return this.error(e);\n      }\n\n      const window = new Subject<T>();\n      const subscription = new Subscription();\n      const context = { window, subscription };\n      this.contexts.push(context);\n      const innerSubscription = subscribeToResult(this, closingNotifier, context as any);\n\n      if (innerSubscription.closed) {\n        this.closeWindow(this.contexts.length - 1);\n      } else {\n        (<any>innerSubscription).context = context;\n        subscription.add(innerSubscription);\n      }\n\n      this.destination.next(window);\n    } else {\n      this.closeWindow(this.contexts.indexOf(outerValue));\n    }\n  }\n\n  notifyError(err: any): void {\n    this.error(err);\n  }\n\n  notifyComplete(inner: Subscription): void {\n    if (inner !== this.openSubscription) {\n      this.closeWindow(this.contexts.indexOf((<any> inner).context));\n    }\n  }\n\n  private closeWindow(index: number): void {\n    if (index === -1) {\n      return;\n    }\n\n    const { contexts } = this;\n    const context = contexts[index];\n    const { window, subscription } = context;\n    contexts.splice(index, 1);\n    window.complete();\n    subscription.unsubscribe();\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { Subscription } from '../Subscription';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { OperatorFunction } from '../types';\n\n/**\n * Branch out the source Observable values as a nested Observable using a\n * factory function of closing Observables to determine when to start a new\n * window.\n *\n * <span class=\"informal\">It's like {@link bufferWhen}, but emits a nested\n * Observable instead of an array.</span>\n *\n * ![](windowWhen.png)\n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable emits connected, non-overlapping windows.\n * It emits the current window and opens a new one whenever the Observable\n * produced by the specified `closingSelector` function emits an item. The first\n * window is opened immediately when subscribing to the output Observable.\n *\n * ## Example\n * Emit only the first two clicks events in every window of [1-5] random seconds\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { windowWhen, map, mergeAll, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n *   windowWhen(() => interval(1000 + Math.random() * 4000)),\n *   map(win => win.pipe(take(2))),     // each window has at most 2 emissions\n *   mergeAll()                         // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link window}\n * @see {@link windowCount}\n * @see {@link windowTime}\n * @see {@link windowToggle}\n * @see {@link bufferWhen}\n *\n * @param {function(): Observable} closingSelector A function that takes no\n * arguments and returns an Observable that signals (on either `next` or\n * `complete`) when to close the previous window and start a new one.\n * @return {Observable<Observable<T>>} An observable of windows, which in turn\n * are Observables.\n * @method windowWhen\n * @owner Observable\n */\nexport function windowWhen<T>(closingSelector: () => Observable<any>): OperatorFunction<T, Observable<T>> {\n  return function windowWhenOperatorFunction(source: Observable<T>) {\n    return source.lift(new WindowOperator<T>(closingSelector));\n  };\n}\n\nclass WindowOperator<T> implements Operator<T, Observable<T>> {\n  constructor(private closingSelector: () => Observable<any>) {\n  }\n\n  call(subscriber: Subscriber<Observable<T>>, source: any): any {\n    return source.subscribe(new WindowSubscriber(subscriber, this.closingSelector));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass WindowSubscriber<T> extends OuterSubscriber<T, any> {\n  private window?: Subject<T>;\n  private closingNotification?: Subscription;\n\n  constructor(protected destination: Subscriber<Observable<T>>,\n              private closingSelector: () => Observable<any>) {\n    super(destination);\n    this.openWindow();\n  }\n\n  notifyNext(_outerValue: T, _innerValue: any,\n             _outerIndex: number, _innerIndex: number,\n             innerSub: InnerSubscriber<T, any>): void {\n    this.openWindow(innerSub);\n  }\n\n  notifyError(error: any): void {\n    this._error(error);\n  }\n\n  notifyComplete(innerSub: InnerSubscriber<T, any>): void {\n    this.openWindow(innerSub);\n  }\n\n  protected _next(value: T): void {\n    this.window!.next(value);\n  }\n\n  protected _error(err: any): void {\n    this.window!.error(err);\n    this.destination.error(err);\n    this.unsubscribeClosingNotification();\n  }\n\n  protected _complete(): void {\n    this.window!.complete();\n    this.destination.complete();\n    this.unsubscribeClosingNotification();\n  }\n\n  private unsubscribeClosingNotification(): void {\n    if (this.closingNotification) {\n      this.closingNotification.unsubscribe();\n    }\n  }\n\n  private openWindow(innerSub: InnerSubscriber<T, any> | null = null): void {\n    if (innerSub) {\n      this.remove(innerSub);\n      innerSub.unsubscribe();\n    }\n\n    const prevWindow = this.window;\n    if (prevWindow) {\n      prevWindow.complete();\n    }\n\n    const window = this.window = new Subject<T>();\n    this.destination.next(window);\n\n    let closingNotifier;\n    try {\n      const { closingSelector } = this;\n      closingNotifier = closingSelector();\n    } catch (e) {\n      this.destination.error(e);\n      this.window.error(e);\n      return;\n    }\n    this.add(this.closingNotification = subscribeToResult(this, closingNotifier));\n  }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function withLatestFrom<T, R>(project: (v1: T) => R): OperatorFunction<T, R>;\nexport function withLatestFrom<T, O2 extends ObservableInput<any>, R>(source2: O2, project: (v1: T, v2: ObservedValueOf<O2>) => R): OperatorFunction<T, R>;\nexport function withLatestFrom<T, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, R>(v2: O2, v3: O3, project: (v1: T, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>) => R): OperatorFunction<T, R>;\nexport function withLatestFrom<T, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, R>(v2: O2, v3: O3, v4: O4, project: (v1: T, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>) => R): OperatorFunction<T, R>;\nexport function withLatestFrom<T, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, R>(v2: O2, v3: O3, v4: O4, v5: O5, project: (v1: T, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>, v5: ObservedValueOf<O5>) => R): OperatorFunction<T, R>;\nexport function withLatestFrom<T, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>, R>(v2: O2, v3: O3, v4: O4, v5: O5, v6: O6, project: (v1: T, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>, v5: ObservedValueOf<O5>, v6: ObservedValueOf<O6>) => R): OperatorFunction<T, R>;\nexport function withLatestFrom<T, O2 extends ObservableInput<any>>(source2: O2): OperatorFunction<T, [T, ObservedValueOf<O2>]>;\nexport function withLatestFrom<T, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(v2: O2, v3: O3): OperatorFunction<T, [T, ObservedValueOf<O2>, ObservedValueOf<O3>]>;\nexport function withLatestFrom<T, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(v2: O2, v3: O3, v4: O4): OperatorFunction<T, [T, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>]>;\nexport function withLatestFrom<T, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(v2: O2, v3: O3, v4: O4, v5: O5): OperatorFunction<T, [T, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>]>;\nexport function withLatestFrom<T, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(v2: O2, v3: O3, v4: O4, v5: O5, v6: O6): OperatorFunction<T, [T, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>, ObservedValueOf<O6>]>;\nexport function withLatestFrom<T, R>(...observables: Array<ObservableInput<any> | ((...values: Array<any>) => R)>): OperatorFunction<T, R>;\nexport function withLatestFrom<T, R>(array: ObservableInput<any>[]): OperatorFunction<T, R>;\nexport function withLatestFrom<T, R>(array: ObservableInput<any>[], project: (...values: Array<any>) => R): OperatorFunction<T, R>;\n\n/* tslint:enable:max-line-length */\n\n/**\n * Combines the source Observable with other Observables to create an Observable\n * whose values are calculated from the latest values of each, only when the\n * source emits.\n *\n * <span class=\"informal\">Whenever the source Observable emits a value, it\n * computes a formula using that value plus the latest values from other input\n * Observables, then emits the output of that formula.</span>\n *\n * ![](withLatestFrom.png)\n *\n * `withLatestFrom` combines each value from the source Observable (the\n * instance) with the latest values from the other input Observables only when\n * the source emits a value, optionally using a `project` function to determine\n * the value to be emitted on the output Observable. All input Observables must\n * emit at least one value before the output Observable will emit a value.\n *\n * ## Example\n * On every click event, emit an array with the latest timer event plus the click event\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { withLatestFrom } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const timer = interval(1000);\n * const result = clicks.pipe(withLatestFrom(timer));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineLatest}\n *\n * @param {ObservableInput} other An input Observable to combine with the source\n * Observable. More than one input Observables may be given as argument.\n * @param {Function} [project] Projection function for combining values\n * together. Receives all values in order of the Observables passed, where the\n * first parameter is a value from the source Observable. (e.g.\n * `a.pipe(withLatestFrom(b, c), map(([a1, b1, c1]) => a1 + b1 + c1))`). If this is not\n * passed, arrays will be emitted on the output Observable.\n * @return {Observable} An Observable of projected values from the most recent\n * values from each input Observable, or an array of the most recent values from\n * each input Observable.\n * @method withLatestFrom\n * @owner Observable\n */\nexport function withLatestFrom<T, R>(...args: Array<ObservableInput<any> | ((...values: Array<any>) => R)>): OperatorFunction<T, R> {\n  return (source: Observable<T>) => {\n    let project: any;\n    if (typeof args[args.length - 1] === 'function') {\n      project = args.pop();\n    }\n    const observables = <Observable<any>[]>args;\n    return source.lift(new WithLatestFromOperator(observables, project));\n  };\n}\n\nclass WithLatestFromOperator<T, R> implements Operator<T, R> {\n  constructor(private observables: Observable<any>[],\n              private project?: (...values: any[]) => Observable<R>) {\n  }\n\n  call(subscriber: Subscriber<R>, source: any): any {\n    return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));\n  }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass WithLatestFromSubscriber<T, R> extends OuterSubscriber<T, R> {\n  private values: any[];\n  private toRespond: number[] = [];\n\n  constructor(destination: Subscriber<R>,\n              private observables: Observable<any>[],\n              private project?: (...values: any[]) => Observable<R>) {\n    super(destination);\n    const len = observables.length;\n    this.values = new Array(len);\n\n    for (let i = 0; i < len; i++) {\n      this.toRespond.push(i);\n    }\n\n    for (let i = 0; i < len; i++) {\n      let observable = observables[i];\n      this.add(subscribeToResult<T, R>(this, observable, undefined, i));\n    }\n  }\n\n  notifyNext(_outerValue: T, innerValue: R,\n             outerIndex: number): void {\n    this.values[outerIndex] = innerValue;\n    const toRespond = this.toRespond;\n    if (toRespond.length > 0) {\n      const found = toRespond.indexOf(outerIndex);\n      if (found !== -1) {\n        toRespond.splice(found, 1);\n      }\n    }\n  }\n\n  notifyComplete() {\n    // noop\n  }\n\n  protected _next(value: T) {\n    if (this.toRespond.length === 0) {\n      const args = [value, ...this.values];\n      if (this.project) {\n        this._tryProject(args);\n      } else {\n        this.destination.next!(args);\n      }\n    }\n  }\n\n  private _tryProject(args: any[]) {\n    let result: any;\n    try {\n      result = this.project!.apply(this, args);\n    } catch (err) {\n      this.destination.error!(err);\n      return;\n    }\n    this.destination.next!(result);\n  }\n}\n","import { zip as zipStatic } from '../observable/zip';\nimport { Observable } from '../Observable';\nimport { ObservableInput, OperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip<T, R>(project: (v1: T) => R): OperatorFunction<T, R>;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip<T, T2, R>(v2: ObservableInput<T2>, project: (v1: T, v2: T2) => R): OperatorFunction<T, R>;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip<T, T2, T3, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, project: (v1: T, v2: T2, v3: T3) => R): OperatorFunction<T, R>;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip<T, T2, T3, T4, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, project: (v1: T, v2: T2, v3: T3, v4: T4) => R): OperatorFunction<T, R>;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip<T, T2, T3, T4, T5, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, project: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => R): OperatorFunction<T, R>;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip<T, T2, T3, T4, T5, T6, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>, project: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5, v6: T6) => R): OperatorFunction<T, R> ;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip<T, T2>(v2: ObservableInput<T2>): OperatorFunction<T, [T, T2]>;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip<T, T2, T3>(v2: ObservableInput<T2>, v3: ObservableInput<T3>): OperatorFunction<T, [T, T2, T3]>;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip<T, T2, T3, T4>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>): OperatorFunction<T, [T, T2, T3, T4]>;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip<T, T2, T3, T4, T5>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>): OperatorFunction<T, [T, T2, T3, T4, T5]>;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip<T, T2, T3, T4, T5, T6>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>): OperatorFunction<T, [T, T2, T3, T4, T5, T6]> ;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip<T, R>(...observables: Array<ObservableInput<T> | ((...values: Array<T>) => R)>): OperatorFunction<T, R>;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip<T, R>(array: Array<ObservableInput<T>>): OperatorFunction<T, R>;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip<T, TOther, R>(array: Array<ObservableInput<TOther>>, project: (v1: T, ...values: Array<TOther>) => R): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * @deprecated Deprecated in favor of static {@link zip}.\n */\nexport function zip<T, R>(...observables: Array<ObservableInput<any> | ((...values: Array<any>) => R)>): OperatorFunction<T, R> {\n  return function zipOperatorFunction(source: Observable<T>) {\n    return source.lift.call(zipStatic<R>(source, ...observables));\n  };\n}","import { ZipOperator } from '../observable/zip';\nimport { Observable } from '../Observable';\nimport { OperatorFunction, ObservableInput } from '../types';\n\nexport function zipAll<T>(): OperatorFunction<ObservableInput<T>, T[]>;\nexport function zipAll<T>(): OperatorFunction<any, T[]>;\nexport function zipAll<T, R>(project: (...values: T[]) => R): OperatorFunction<ObservableInput<T>, R>;\nexport function zipAll<R>(project: (...values: Array<any>) => R): OperatorFunction<any, R>;\n\nexport function zipAll<T, R>(project?: (...values: Array<any>) => R): OperatorFunction<T, R> {\n  return (source: Observable<T>) => source.lift(new ZipOperator(project));\n}\n","import * as cookie from 'js-cookie';\n\nimport PayloadTransformer from './payload-transformer';\nimport RequestFactory from './request-factory';\nimport RequestSender from './request-sender';\nimport RequestSenderOptions from './request-sender-options';\n\nexport default function createRequestSender(options?: RequestSenderOptions): RequestSender {\n    return new RequestSender(\n        new RequestFactory(),\n        new PayloadTransformer(),\n        cookie,\n        options\n    );\n}\n","import Headers from './headers';\nimport RequestOptions from './request-options';\nimport Response from './response';\nimport toFormUrlEncoded from './to-form-url-encoded';\n\nconst JSON_CONTENT_TYPE_REGEXP = /application\\/(\\w+\\+)?json/;\nconst FORM_URLENCODED_CONTENT_TYPE_REGEXP = /application\\/x-www-form-urlencoded/;\n\nexport default class PayloadTransformer {\n    toRequestBody(options: RequestOptions): any {\n        const contentType = options.headers ? this._getHeader(options.headers, 'Content-Type') : '';\n\n        if (options.body) {\n            if (JSON_CONTENT_TYPE_REGEXP.test(contentType)) {\n                return JSON.stringify(options.body);\n            }\n\n            if (FORM_URLENCODED_CONTENT_TYPE_REGEXP.test(contentType)) {\n                return toFormUrlEncoded(options.body);\n            }\n        }\n\n        return options.body;\n    }\n\n    toResponse(xhr: XMLHttpRequest): Response {\n        const headers = this._parseResponseHeaders(xhr.getAllResponseHeaders());\n\n        // Using `responseText` to support legacy IE\n        const body = this._parseResponseBody(\n            'response' in xhr ? xhr.response : (xhr as any).responseText,\n            headers\n        );\n\n        return {\n            body,\n            headers,\n            status: xhr.status,\n            statusText: xhr.statusText,\n        };\n    }\n\n    private _parseResponseBody(body: string, headers: Headers): any {\n        const contentType = this._getHeader(headers, 'Content-Type');\n\n        if (body && JSON_CONTENT_TYPE_REGEXP.test(contentType)) {\n            return JSON.parse(body);\n        }\n\n        return body;\n    }\n\n    private _parseResponseHeaders(rawHeaders: string): Headers {\n        const lines = rawHeaders ? rawHeaders.replace(/\\r?\\n[\\t ]+/g, ' ').split(/\\r?\\n/) : [];\n\n        return lines.reduce((headers, line) => {\n            const parts = line.split(':');\n            const key = (parts.shift() || '').trim();\n\n            if (!key) {\n                return headers;\n            }\n\n            return {\n                ...headers,\n                [key.toLowerCase()]: parts.join(':').trim(),\n            };\n        }, {});\n    }\n\n    private _getHeader(headers: Headers, key: string): string {\n        if (!headers || !key) {\n            return '';\n        }\n\n        return headers[key] || headers[key.toLowerCase()] || '';\n    }\n}\n","export default function toFormUrlEncoded(data: any): string {\n    if (typeof data !== 'object' || data === null) {\n        return data;\n    }\n\n    return Object.keys(data)\n        .filter(key => data[key] !== undefined)\n        .map(key => {\n            const value = data[key];\n\n            if (typeof value === 'string') {\n                return `${key}=${encodeURIComponent(value)}`;\n            }\n\n            return `${key}=${encodeURIComponent(JSON.stringify(value) || '')}`;\n        })\n        .join('&');\n}\n","import * as queryString from 'query-string';\n\nimport Headers from './headers';\nimport RequestOptions from './request-options';\n\nexport default class RequestFactory {\n    createRequest(url: string, options?: RequestOptions): XMLHttpRequest {\n        const xhr = new XMLHttpRequest();\n\n        this._configureRequest(xhr, url, options);\n\n        return xhr;\n    }\n\n    private _configureRequest(xhr: XMLHttpRequest, url: string, options: RequestOptions = {}): void {\n        xhr.open(options.method || 'GET', this._formatUrl(url, options.params, options.encodeParams), true);\n\n        if (options.headers) {\n            this._configureRequestHeaders(xhr, options.headers);\n        }\n\n        if (typeof options.credentials === 'boolean') {\n            xhr.withCredentials = options.credentials;\n        }\n\n        if (typeof options.timeout === 'number') {\n            xhr.timeout = options.timeout;\n        }\n    }\n\n    private _configureRequestHeaders(xhr: XMLHttpRequest, headers: Headers): void {\n        Object.keys(headers).forEach(key => {\n            xhr.setRequestHeader(key, headers[key]);\n        });\n    }\n\n    private _formatUrl(url: string, params?: object, encodeParams: boolean = true): string {\n        if (!params || Object.keys(params).length === 0) {\n            return url;\n        }\n\n        return `${url}?${queryString.stringify(params, { encode: encodeParams })}`;\n    }\n}\n","import * as queryString from 'query-string';\n\nimport RequestOptions from './request-options';\nimport Response from './response';\n\nexport default interface Cache {\n    read<T>(url: string, options: RequestOptions): Response<T> | null;\n    write<T>(url: string, options: RequestOptions, response: Response<T>): void;\n}\n\ninterface CacheMap {\n    [key: string]: Response<any>;\n}\n\nexport class DefaultCache implements Cache {\n    private readonly _cache: CacheMap = {};\n\n    read<T>(url: string, options: RequestOptions): Response<T> | null {\n        const cacheKey = this.getKey(url, options.params);\n\n        return this._cache[cacheKey] || null;\n    }\n\n    write<T>(url: string, options: RequestOptions, response: Response<T>) {\n        const cacheKey = this.getKey(url, options.params);\n\n        this._cache[cacheKey] = response;\n    }\n\n    private getKey(url: string, params: object = {}) {\n        if (Object.keys(params).length === 0) {\n            return url;\n        }\n\n        return `${url}?${queryString.stringify(params)}`;\n    }\n}\n","export default function isPromise(promise: any): promise is PromiseLike<any> {\n    return !!promise &&\n        (typeof promise === 'object' || typeof promise === 'function') &&\n        typeof promise.then === 'function';\n}\n","import Timeout from './timeout';\n\nexport default function createTimeout(delay?: number): Timeout {\n    return new Timeout(delay);\n}\n","import createScriptLoader from './create-script-loader';\nimport ScriptLoader from './script-loader';\n\nlet instance: ScriptLoader;\n\nexport default function getScriptLoader(): ScriptLoader {\n    if (!instance) {\n        instance = createScriptLoader();\n    }\n\n    return instance;\n}\n","import createStylesheetLoader from './create-stylesheet-loader';\nimport StylesheetLoader from './stylesheet-loader';\n\nlet instance: StylesheetLoader;\n\nexport default function getStylesheetLoader(): StylesheetLoader {\n    if (!instance) {\n        instance = createStylesheetLoader();\n    }\n\n    return instance;\n}\n","import FormBuilder from './form-builder';\nimport FormPoster from './form-poster';\nimport FormPosterOptions from './form-poster-options';\n\nexport default function createFormPoster(options?: FormPosterOptions): FormPoster {\n    const formBuilder = new FormBuilder();\n    const formPoster = new FormPoster(formBuilder, options);\n\n    return formPoster;\n}\n","export default class FormBuilder {\n    build(url: string, data: { [key: string]: any }, target?: string): HTMLFormElement {\n        const form = document.createElement('form');\n\n        form.style.display = 'none';\n\n        form.setAttribute('action', url);\n        form.setAttribute('method', 'POST');\n        form.setAttribute('target', target || '_top');\n\n        Object.keys(data)\n            .forEach(key => {\n                const value = data[key];\n\n                form.appendChild(this._createInput(value, key));\n            });\n\n        return form;\n    }\n\n    private _createInput(value: any, key: string): HTMLInputElement {\n        const input = document.createElement('input');\n\n        input.setAttribute('name', key);\n        input.setAttribute('type', 'hidden');\n        input.setAttribute('value', value);\n\n        return input;\n    }\n}\n","export function isAbsoluteUrl(url: string): boolean {\n    return /^https?:\\/\\//.test(url);\n}\n\nexport function joinPaths(pathA: string, pathB: string): string {\n    return `${removeTrailingSlash(pathA)}/${removeLeadingSlash(pathB)}`;\n}\n\nfunction removeTrailingSlash(path: string): string {\n    return path.replace(/\\/$/, '');\n}\n\nfunction removeLeadingSlash(path: string): string {\n    return path.replace(/^\\//, '');\n}\n","import Client from './client/client';\n\n/**\n * @param {Object} [config]\n * @returns {Client}\n */\nexport function createClient(config) {\n    return Client.create(config);\n}\n","import objectAssign from 'object-assign';\nimport OffsitePaymentInitializer from '../payment/offsite-payment-initializer';\nimport PaymentSubmitter from '../payment/payment-submitter';\nimport ClientTokenGenerator from '../payment/client-token-generator';\nimport StoreRequestSender from '../store/store-request-sender';\nimport DEFAULT_CONFIG from './default-config';\n\nexport default class Client {\n    /**\n     * @param {Object} config\n     * @returns {Client}\n     */\n    static create(config) {\n        const clientConfig = objectAssign({}, DEFAULT_CONFIG, config);\n        const offsitePaymentInitializer = OffsitePaymentInitializer.create(clientConfig);\n        const paymentSubmitter = PaymentSubmitter.create(clientConfig);\n        const clientTokenGenerator = ClientTokenGenerator.create(clientConfig);\n        const storeRequestSender = StoreRequestSender.create(clientConfig);\n\n        return new Client(\n            clientConfig,\n            paymentSubmitter,\n            offsitePaymentInitializer,\n            clientTokenGenerator,\n            storeRequestSender,\n        );\n    }\n\n    /**\n     * @param {Object} config\n     * @param {PaymentSubmitter} paymentSubmitter\n     * @param {OffsitePaymentInitializer} offsitePaymentInitializer\n     * @param {ClientTokenGenerator} clientTokenGenerator\n     * @param {StoreRequestSender} storeRequestSender\n     */\n    constructor(\n        config,\n        paymentSubmitter,\n        offsitePaymentInitializer,\n        clientTokenGenerator,\n        storeRequestSender,\n    ) {\n        /**\n         * @private\n         * @type {Object}\n         */\n        this.config = config;\n\n        /**\n         * @private\n         * @type {PaymentSubmitter}\n         */\n        this.paymentSubmitter = paymentSubmitter;\n\n        /**\n         * @private\n         * @type {OffsitePaymentInitializer}\n         */\n        this.offsitePaymentInitializer = offsitePaymentInitializer;\n\n        /**\n         * @private\n         * @type {ClientTokenGenerator}\n         */\n        this.clientTokenGenerator = clientTokenGenerator;\n\n        /**\n         * @private\n         * @type {StoreRequestSender}\n         */\n        this.storeRequestSender = storeRequestSender;\n    }\n\n    /**\n     * @param {string} host\n     * @returns {void}\n     */\n    setHost(host) {\n        this.config.host = host;\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @param {Function} [callback]\n     * @param {string} target\n     * @returns {void}\n     */\n    initializeOffsitePayment(data, callback, target) {\n        this.offsitePaymentInitializer.initializeOffsitePayment(data, callback, target);\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @param {Function} [callback]\n     * @returns {void}\n     */\n    submitPayment(data, callback) {\n        this.paymentSubmitter.submitPayment(data, callback);\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @param {Function} [callback]\n     * @returns {void}\n     */\n    generateClientToken(data, callback) {\n        this.clientTokenGenerator.generateClientToken(data, callback);\n    }\n\n    /**\n     * @param {Object} data\n     * @param {string} data.storeId\n     * @param {string} data.customerId\n     * @param {string} data.currencyCode\n     * @param {Function} [callback]\n     * @return {void}\n     */\n    loadInstruments(data, callback) {\n        this.storeRequestSender.loadInstruments(data, callback);\n    }\n\n    /**\n     * @param {Object} data\n     * @param {string} data.storeId\n     * @param {string} data.customerId\n     * @param {string} data.currencyCode\n     * @param {AddressData} data.shippingAddress\n     * @param {Function} [callback]\n     * @return {void}\n     */\n    loadInstrumentsWithAddress(data, callback) {\n        this.storeRequestSender.loadInstrumentsWithAddress(data, callback);\n    }\n\n    /**\n     * @param {Object} data\n     * @param {string} data.storeId\n     * @param {string} data.customerId\n     * @param {string} data.instrumentId\n     * @param {string} data.currencyCode\n     * @param {Function} [callback]\n     * @return {void}\n     */\n    deleteShopperInstrument(data, callback) {\n        this.storeRequestSender.deleteShopperInstrument(data, callback);\n    }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { HOSTED } from './payment-types';\nimport PayloadMapper from './offsite-payment-mappers/payload-mapper';\nimport UrlHelper from './url-helper';\n\nexport default class OffsitePaymentInitializer {\n    /**\n     * @param {Object} config\n     * @returns {OffsitePaymentInitializer}\n     */\n    static create(config) {\n        const urlHelper = UrlHelper.create(config);\n        const formPoster = createFormPoster();\n        const payloadMapper = PayloadMapper.create();\n\n        return new OffsitePaymentInitializer(urlHelper, formPoster, payloadMapper);\n    }\n\n    /**\n     * @param {UrlHelper} urlHelper\n     * @param {FormPoster} formPoster\n     * @param {PayloadMapper} payloadMapper\n     * @returns {void}\n     */\n    constructor(urlHelper, formPoster, payloadMapper) {\n        /**\n         * @private\n         * @type {UrlHelper}\n         */\n        this.urlHelper = urlHelper;\n\n        /**\n         * @private\n         * @type {FormPoster}\n         */\n        this.formPoster = formPoster;\n\n        /**\n         * @private\n         * @type {PayloadMapper}\n         */\n        this.payloadMapper = payloadMapper;\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @param {Function} [callback]\n     * @param {string} target\n     * @returns {void}\n     * @throws {Error}\n     */\n    initializeOffsitePayment(data, callback, target) {\n        const { paymentMethod = {} } = data;\n\n        if (paymentMethod.type !== HOSTED) {\n            throw new Error(`${paymentMethod.type} is not supported.`);\n        }\n\n        const payload = this.payloadMapper.mapToPayload(data);\n        const url = this.urlHelper.getOffsitePaymentUrl();\n\n        this.formPoster.postForm(url, payload, callback, target);\n    }\n}\n","import objectAssign from 'object-assign';\nimport { omitNil, toString } from '../../common/utils';\nimport AddressMapper from './address-mapper';\nimport CustomerMapper from './customer-mapper';\nimport MetaMapper from './meta-mapper';\nimport PaymentMethodIdMapper from '../payment-method-mappers/payment-method-id-mapper';\nimport StoreMapper from './store-mapper';\n\nexport default class PayloadMapper {\n    /**\n     * @returns {PayloadMapper}\n     */\n    static create() {\n        const addressMapper = AddressMapper.create();\n        const customerMapper = CustomerMapper.create();\n        const metaMapper = MetaMapper.create();\n        const paymentMethodIdMapper = PaymentMethodIdMapper.create();\n        const storeMapper = StoreMapper.create();\n\n        return new PayloadMapper(addressMapper, customerMapper, metaMapper, paymentMethodIdMapper, storeMapper);\n    }\n\n    /**\n     * @param {AddressMapper} addressMapper\n     * @param {CustomerMapper} customerMapper\n     * @param {MetaMapper} metaMapper\n     * @param {PaymentMethodIdMapper} paymentMethodIdMapper\n     * @param {StoreMapper} storeMapper\n     * @returns {Object}\n     */\n    constructor(addressMapper, customerMapper, metaMapper, paymentMethodIdMapper, storeMapper) {\n        /**\n         * @private\n         * @type {AddressMapper}\n         */\n        this.addressMapper = addressMapper;\n\n        /**\n         * @private\n         * @type {CustomerMapper}\n         */\n        this.customerMapper = customerMapper;\n\n        /**\n         * @private\n         * @type {MetaMapper}\n         */\n        this.metaMapper = metaMapper;\n\n        /**\n         * @private\n         * @type {PaymentMethodIdMapper}\n         */\n        this.paymentMethodIdMapper = paymentMethodIdMapper;\n\n        /**\n         * @private\n         * @type {StoreMapper}\n         */\n        this.storeMapper = storeMapper;\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToPayload(data) {\n        const {\n            authToken, order = {}, payment = {}, paymentMethod = {},\n        } = data;\n\n        const payload = objectAssign(\n            {\n                amount: order.grandTotal ? order.grandTotal.integerAmount : null,\n                tax: order.taxTotal ? order.taxTotal.integerAmount : null,\n                bc_auth_token: authToken,\n                currency: order.currency,\n                gateway: this.paymentMethodIdMapper.mapToId(paymentMethod),\n                notify_url: order.callbackUrl,\n                order_id: order.orderId ? toString(order.orderId) : null,\n                page_title: document.title ? document.title : null,\n                payment_method_id: paymentMethod.id,\n                reference_id: order.orderId ? toString(order.orderId) : null,\n                return_url: paymentMethod.returnUrl || (order.payment ? order.payment.returnUrl : null),\n            },\n            this.addressMapper.mapToBillingAddress(data),\n            this.customerMapper.mapToCustomer(data),\n            this.metaMapper.mapToMeta(data),\n            this.addressMapper.mapToShippingAddress(data),\n            this.storeMapper.mapToStore(data),\n        );\n\n        const { formattedPayload = {} } = payment;\n\n        objectAssign(payload, formattedPayload);\n\n        return omitNil(payload);\n    }\n}\n","/**\n * @param {array|string} items\n * @param {array|string} item\n * @returns {boolean}\n */\nexport default function includes(items, item) {\n    if (!Array.isArray(items) && typeof items !== 'string') {\n        return false;\n    }\n\n    return items.indexOf(item) !== -1;\n}\n","import isEmptyStringOrNil from './is-emptystring-or-nil';\nimport omitProperty from './omit-property';\n\n/**\n * @param {Object} object\n * @returns {Object}\n */\nexport default function omitEmptyStringAndNil(object) {\n    return omitProperty(object, isEmptyStringOrNil);\n}\n","import isEmptyString from './is-empty-string';\nimport isNil from './is-nil';\n\n/**\n * @param {*} value\n * @returns {boolean}\n */\nexport default function isEmptyStringOrNil(value) {\n    return isEmptyString(value) || isNil(value);\n}\n","/**\n * @param {*} value\n * @returns {boolean}\n */\nexport default function isEmptyString(value) {\n    return value === '';\n}\n","import isNil from './is-nil';\nimport omitProperty from './omit-property';\n\n/**\n * @param {Object} object\n * @returns {Object}\n */\nexport default function omitNil(object) {\n    return omitProperty(object, isNil);\n}\n","/**\n * @param {*} value\n * @returns {number}\n */\nexport default function toNumber(value) {\n    return parseFloat(value) || 0;\n}\n","/**\n * @param {string} string\n * @returns {string}\n */\nexport default function toSnakeCase(string) {\n    if (typeof string !== 'string') {\n        return string;\n    }\n\n    return string.replace(/([a-z\\d])([A-Z]+)/g, '$1_$2')\n        .replace(/[-\\s]+/g, '_')\n        .toLowerCase();\n}\n","/**\n * @param {*} value\n * @returns {string}\n */\nexport default function toString(value) {\n    if (typeof value === 'string') {\n        return value;\n    }\n\n    if (typeof value === 'number' && !Number.isNaN(value)) {\n        return value.toString();\n    }\n\n    return '';\n}\n","import { omitNil, toSnakeCase } from '../../common/utils';\n\nexport default class AddressMapper {\n    /**\n     * @returns {AddressMapper}\n     */\n    static create() {\n        return new AddressMapper();\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToBillingAddress(data) {\n        return this.mapToAddress(data, 'billingAddress');\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToShippingAddress(data) {\n        return this.mapToAddress(data, 'shippingAddress');\n    }\n\n    /**\n     * @private\n     * @param {PaymentRequestData} data\n     * @param {string} addressKey\n     * @returns {Object}\n     */\n    mapToAddress(data, addressKey) {\n        const address = data[addressKey] || {};\n        const formattedAddressKey = toSnakeCase(addressKey);\n\n        return omitNil({\n            [`${formattedAddressKey}_city`]: address.city,\n            [`${formattedAddressKey}_company`]: address.company,\n            [`${formattedAddressKey}_country_code`]: address.countryCode,\n            [`${formattedAddressKey}_country`]: address.country,\n            [`${formattedAddressKey}_first_name`]: address.firstName,\n            [`${formattedAddressKey}_last_name`]: address.lastName,\n            [`${formattedAddressKey}_phone`]: address.phone,\n            [`${formattedAddressKey}_state_code`]: address.provinceCode,\n            [`${formattedAddressKey}_state`]: address.province,\n            [`${formattedAddressKey}_street_1`]: address.addressLine1,\n            [`${formattedAddressKey}_street_2`]: address.addressLine2,\n            [`${formattedAddressKey}_zip`]: address.postCode,\n        });\n    }\n}\n","import { omitNil } from '../../common/utils';\n\nexport default class CustomerMapper {\n    /**\n     * @returns {CustomerMapper}\n     */\n    static create() {\n        return new CustomerMapper();\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToCustomer(data) {\n        const { customer = {}, quoteMeta = {}, store = {} } = data;\n\n        return omitNil({\n            customer_browser_info: navigator.userAgent,\n            customer_email: customer.email,\n            customer_first_name: customer.firstName,\n            customer_geo_ip_country_code: quoteMeta.request ? quoteMeta.request.geoCountryCode : null,\n            customer_id: customer.customerId,\n            customer_last_name: customer.lastName,\n            customer_locale: store.storeLanguage,\n            customer_name: customer.name,\n            customer_phone: customer.phoneNumber,\n            customer_reference: customer.email,\n        });\n    }\n}\n","import { omitNil } from '../../common/utils';\n\nexport default class MetaMapper {\n    /**\n     * @returns {MetaMapper}\n     */\n    static create() {\n        return new MetaMapper();\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToMeta(data) {\n        const { source } = data;\n\n        return omitNil({\n            meta_referrer: document.referrer,\n            meta_source: source,\n            meta_user_agent: navigator.userAgent,\n        });\n    }\n}\n","export const CREDIT_CARD = 'credit-card';\nexport const MULTI_OPTION = 'multi-option';\n","export const BRAINTREE = 'braintree';\nexport const BRAINTREE_PAYPAL = 'braintreepaypal';\nexport const BRAINTREE_PAYPAL_CREDIT = 'braintreepaypalcredit';\nexport const BRAINTREE_VISACHECKOUT = 'braintreevisacheckout';\nexport const BRAINTREE_GOOGLEPAY = 'googlepaybraintree';\n\nexport const PAYPAL_COMMERCE = 'paypalcommerce';\nexport const PAYPAL_COMMERCE_ALTERNATIVE_METHODS = 'paypalcommercealternativemethods';\nexport const PAYPAL_COMMERCE_CREDIT = 'paypalcommercecredit';\nexport const PAYPAL_COMMERCE_CREDIT_CARDS = 'paypalcommercecreditcards';\n","import { omitNil, toString } from '../../common/utils';\n\nexport default class StoreMapper {\n    /**\n     * @returns {StoreMapper}\n     */\n    static create() {\n        return new StoreMapper();\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToStore(data) {\n        const { store = {} } = data;\n\n        return omitNil({\n            store_hash: store.storeHash,\n            store_id: store.storeId ? toString(store.storeId) : null,\n        });\n    }\n}\n","import { API } from './payment-types';\nimport PayloadMapper from './v1/payment-mappers/payload-mapper';\nimport RequestSender from '../common/http-request/request-sender';\nimport UrlHelper from './url-helper';\n\nexport default class PaymentSubmitter {\n    /**\n     * @param {Object} config\n     * @returns {PaymentSubmitter}\n     */\n    static create(config) {\n        const urlHelper = UrlHelper.create(config);\n        const requestSender = RequestSender.create();\n        const payloadMapper = PayloadMapper.create();\n\n        return new PaymentSubmitter(urlHelper, requestSender, payloadMapper);\n    }\n\n    /**\n     * @param {UrlHelper} urlHelper\n     * @param {RequestSender} requestSender\n     * @param {PayloadMapper} payloadMapper\n     * @returns {void}\n     */\n    constructor(urlHelper, requestSender, payloadMapper) {\n        /**\n         * @private\n         * @type {UrlHelper}\n         */\n        this.urlHelper = urlHelper;\n\n        /**\n         * @private\n         * @type {RequestSender}\n         */\n        this.requestSender = requestSender;\n\n        /**\n         * @private\n         * @type {PayloadMapper}\n         */\n        this.payloadMapper = payloadMapper;\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @param {Function} [callback]\n     * @returns {void}\n     * @throws {Error}\n     */\n    submitPayment(data, callback) {\n        const { paymentMethod = {} } = data;\n\n        if (paymentMethod.type !== API) {\n            throw new Error(`${paymentMethod.type} is not supported.`);\n        }\n\n        const payload = this.payloadMapper.mapToPayload(data);\n        const url = this.urlHelper.getPaymentUrl();\n        const options = {\n            headers: this.payloadMapper.mapToHeaders(data),\n        };\n\n        this.requestSender.postRequest(url, payload, options, callback);\n    }\n}\n","import { omitNil } from '../../../common/utils';\nimport CustomerMapper from './customer-mapper';\nimport OrderMapper from './order-mapper';\nimport PaymentMapper from './payment-mapper';\nimport StoreMapper from './store-mapper';\n\nexport default class PayloadMapper {\n    /**\n     * @returns {PayloadMapper}\n     */\n    static create() {\n        const customerMapper = CustomerMapper.create();\n        const orderMapper = OrderMapper.create();\n        const paymentMapper = PaymentMapper.create();\n        const storeMapper = StoreMapper.create();\n\n        return new PayloadMapper(customerMapper, orderMapper, paymentMapper, storeMapper);\n    }\n\n    /**\n     * @param {CustomerMapper} customerMapper\n     * @param {OrderMapper} orderMapper\n     * @param {PaymentMapper} paymentMapper\n     * @param {StoreMapper} storeMapper\n     */\n    constructor(customerMapper, orderMapper, paymentMapper, storeMapper) {\n        /**\n         * @private\n         * @type {CustomerMapper}\n         */\n        this.customerMapper = customerMapper;\n\n        /**\n         * @private\n         * @type {OrderMapper}\n         */\n        this.orderMapper = orderMapper;\n\n        /**\n         * @private\n         * @type {PaymentMapper}\n         */\n        this.paymentMapper = paymentMapper;\n\n        /**\n         * @private\n         * @type {StoreMapper}\n         */\n        this.storeMapper = storeMapper;\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToPayload(data) {\n        const { order = {}, additionalAction } = data;\n\n        return omitNil({\n            customer: this.customerMapper.mapToCustomer(data),\n            notify_url: order.callbackUrl,\n            order: this.orderMapper.mapToOrder(data),\n            payment: this.paymentMapper.mapToPayment(data),\n            store: this.storeMapper.mapToStore(data),\n            additional_action: additionalAction,\n        });\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToHeaders(data) {\n        const { authToken } = data;\n\n        return omitNil({\n            Authorization: authToken,\n        });\n    }\n}\n","import { omitNil, toString } from '../../../common/utils';\n\nexport default class CustomerMapper {\n    /**\n     * @returns {CustomerMapper}\n     */\n    static create() {\n        return new CustomerMapper();\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToCustomer(data) {\n        const { customer = {}, quoteMeta = {} } = data;\n\n        return omitNil({\n            customer_group: customer.customerGroupName ? { name: customer.customerGroupName } : null,\n            geo_ip_country_code: quoteMeta.request ? quoteMeta.request.geoCountryCode : null,\n            id: customer.customerId ? toString(customer.customerId) : null,\n            session_token: quoteMeta.request ? quoteMeta.request.sessionHash : null,\n        });\n    }\n}\n","import { omitEmptyStringAndNil, omitNil, toString } from '../../../common/utils';\n\nexport default class OrderMapper {\n    /**\n     * @returns {OrderMapper}\n     */\n    static create() {\n        return new OrderMapper();\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToOrder(data) {\n        const { order = {} } = data;\n\n        return omitNil({\n            billing_address: this.mapToBillingAddress(data),\n            coupons: this.mapToCoupons(data),\n            currency: order.currency,\n            id: order.orderId ? toString(order.orderId) : null,\n            items: this.mapToItems(data),\n            shipping: this.mapToShipping(data),\n            shipping_address: this.mapToShippingAddress(data),\n            token: order.token,\n            totals: this.mapToOrderTotals(data),\n        });\n    }\n\n    /**\n     * @private\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToBillingAddress(data) {\n        const { customer = {} } = data;\n        const address = this.mapToAddress(data, 'billingAddress');\n\n        if (customer.email) {\n            address.email = customer.email;\n        }\n\n        return address;\n    }\n\n    /**\n     * @private\n     * @param  {PaymentRequestData} data\n     * @return {Shipping[]}\n     */\n    mapToShipping(data) {\n        const { description, transitTime } = data.shippingOption || {};\n\n        if (description) {\n            return [omitEmptyStringAndNil({\n                method: description,\n                transit_time: transitTime,\n            })];\n        }\n\n        return [];\n    }\n\n    /**\n     * @private\n     * @param {PaymentRequestData} data\n     * @returns {Coupon[]}\n     */\n    mapToCoupons({ order = {} }) {\n        if (order.coupon && order.coupon.coupons) {\n            return order.coupon.coupons.map(({ code }) => ({ code }));\n        }\n\n        return [];\n    }\n\n    /**\n     * @private\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToShippingAddress(data) {\n        return this.mapToAddress(data, 'shippingAddress');\n    }\n\n    /**\n     * @private\n     * @param {PaymentRequestData} data\n     * @param {string} addressKey\n     * @returns {Object}\n     */\n    mapToAddress(data, addressKey) {\n        const address = data[addressKey] || {};\n\n        return omitEmptyStringAndNil({\n            city: address.city,\n            company: address.company,\n            country_code: address.countryCode,\n            country: address.country,\n            first_name: address.firstName,\n            last_name: address.lastName,\n            phone: address.phone,\n            state_code: address.provinceCode,\n            state: address.province,\n            street_1: address.addressLine1,\n            street_2: address.addressLine2,\n            zip: address.postCode,\n        });\n    }\n\n    /**\n     * @private\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToItems(data) {\n        const { cart = { items: [] } } = data;\n\n        return cart.items.map((itemData) => omitNil({\n            code: itemData.id,\n            variant_id: itemData.variantId,\n            name: itemData.name,\n            price: itemData.integerAmount,\n            unit_price: itemData.integerUnitPrice,\n            quantity: itemData.quantity,\n            sku: itemData.sku,\n        }));\n    }\n\n    /**\n     * @private\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToOrderTotals(data) {\n        const { order = {} } = data;\n\n        return omitNil({\n            grand_total: order.grandTotal ? order.grandTotal.integerAmount : null,\n            handling: order.handling ? order.handling.integerAmount : null,\n            shipping: order.shipping ? order.shipping.integerAmount : null,\n            subtotal: order.subtotal ? order.subtotal.integerAmount : null,\n            tax: order.taxTotal ? order.taxTotal.integerAmount : null,\n        });\n    }\n}\n","import objectAssign from 'object-assign';\nimport { omitNil, toNumber } from '../../../common/utils';\n\nimport PaymentMethodIdMapper from '../../payment-method-mappers/payment-method-id-mapper';\n\nexport default class PaymentMapper {\n    /**\n     * @param {PaymentMethodIdMapper} paymentMethodIdMapper\n     * @returns {PaymentMapper}\n     */\n    static create() {\n        const paymentMethodIdMapper = PaymentMethodIdMapper.create();\n\n        return new PaymentMapper(paymentMethodIdMapper);\n    }\n\n    /**\n     * @param {PaymentMethodIdMapper} paymentMethodIdMapper\n     * @returns {void}\n     */\n    constructor(paymentMethodIdMapper) {\n        /**\n         * @private\n         * @type {PaymentMethodIdMapper}\n         */\n        this.paymentMethodIdMapper = paymentMethodIdMapper;\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToPayment(data) {\n        const {\n            order = {},\n            orderMeta = {},\n            payment = {},\n            paymentMethod = {},\n        } = data;\n\n        const payload = {\n            device_info: payment.deviceSessionId ? payment.deviceSessionId : null,\n            device: orderMeta.deviceFingerprint ? { fingerprint_id: orderMeta.deviceFingerprint } : null,\n            gateway: this.paymentMethodIdMapper.mapToId(paymentMethod),\n            notify_url: order.callbackUrl,\n            return_url: paymentMethod.returnUrl || (order.payment ? order.payment.returnUrl : null),\n            vault_payment_instrument: !payment.instrumentId ? payment.shouldSaveInstrument : null,\n            set_as_default_stored_instrument: (payment.instrumentId || payment.shouldSaveInstrument) ? payment.shouldSetAsDefaultInstrument : null,\n        };\n\n        const { method } = paymentMethod;\n\n        if (method) {\n            objectAssign(payload, { method });\n        }\n\n        const nonce = payment.nonce || paymentMethod.nonce;\n\n        if (payment.formattedPayload) {\n            objectAssign(payload, payment.formattedPayload);\n        } else if (payment.instrumentId) {\n            objectAssign(payload, {\n                bigpay_token: this.mapToBigPayToken(data),\n            });\n        } else if (nonce) {\n            objectAssign(payload, {\n                credit_card_token: {\n                    token: nonce,\n                },\n            });\n        } else if (payment.cryptogramId) {\n            objectAssign(payload, {\n                credit_card_cryptogram: this.mapToCryptogram(data),\n            });\n        } else {\n            objectAssign(payload, {\n                credit_card: this.mapToCreditCard(data),\n            });\n        }\n\n        return omitNil(payload);\n    }\n\n    /**\n     * @private\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToCreditCard(data) {\n        const { payment = {} } = data;\n\n        return omitNil({\n            account_name: payment.ccName,\n            month: payment.ccExpiry ? toNumber(payment.ccExpiry.month) : null,\n            number: payment.ccNumber,\n            verification_value: payment.ccCvv,\n            year: payment.ccExpiry ? toNumber(payment.ccExpiry.year) : null,\n            customer_code: payment.ccCustomerCode,\n            three_d_secure: payment.threeDSecure,\n            hosted_form_nonce: payment.hostedFormNonce,\n        });\n    }\n\n    /**\n     * @private\n     * @param {PaymentRequestData} data\n     * @return {Object}\n     */\n    mapToBigPayToken({ payment }) {\n        return omitNil({\n            credit_card_number_confirmation: payment.ccNumber,\n            token: payment.instrumentId,\n            verification_value: payment.ccCvv,\n            verification_nonce: payment.nonce,\n            three_d_secure: payment.threeDSecure,\n            hosted_form_nonce: payment.hostedFormNonce,\n        });\n    }\n\n    /**\n     * @private\n     * @param {PaymentRequestData} data\n     * @return {Object}\n     */\n    mapToCryptogram({ payment }) {\n        return omitNil({\n            payment_cryptogram: payment.cryptogramId,\n            eci: payment.eci,\n            xid: payment.transactionId,\n            month: payment.ccExpiry ? toNumber(payment.ccExpiry.month) : null,\n            number: payment.ccNumber,\n            year: payment.ccExpiry ? toNumber(payment.ccExpiry.year) : null,\n            account_mask: payment.accountMask,\n        });\n    }\n}\n","import { omitNil, toString } from '../../../common/utils';\n\nexport default class StoreMapper {\n    /**\n     * @returns {StoreMapper}\n     */\n    static create() {\n        return new StoreMapper();\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToStore(data) {\n        const { store = {} } = data;\n\n        return omitNil({\n            hash: store.storeHash,\n            id: store.storeId ? toString(store.storeId) : null,\n            name: store.storeName,\n        });\n    }\n}\n","import { APPLICATION_JSON } from './content-types';\nimport { GET } from './method-types';\n\nconst DEFAULT_OPTIONS = {\n    headers: {\n        Accept: APPLICATION_JSON,\n        'Content-Type': APPLICATION_JSON,\n    },\n    method: GET,\n};\n\nexport default DEFAULT_OPTIONS;\n","import objectAssign from 'object-assign';\nimport { APPLICATION_JSON } from './content-types';\nimport { includes } from '../utils';\n\nexport default class PayloadTransformer {\n    /**\n     * @returns {PayloadTransformer}\n     */\n    static create() {\n        return new PayloadTransformer();\n    }\n\n    /**\n     * @param {Object} data\n     * @param {string} [contentType = APPLICATION_JSON]\n     * @returns {Object}\n     */\n    toRequest(data, contentType = APPLICATION_JSON) {\n        if (data && includes(contentType, APPLICATION_JSON)) {\n            return JSON.stringify(data);\n        }\n\n        return data;\n    }\n\n    /**\n     * @param {XMLHttpRequest} xhr\n     * @returns {Object}\n     * @property {Object} data\n     * @property {number} status\n     * @property {string} statusText\n     */\n    fromResponse(xhr) {\n        const headers = this.parseResponseHeaders(xhr.getAllResponseHeaders());\n        const contentType = xhr.getResponseHeader('Content-Type');\n        const { status, statusText } = xhr;\n\n        let data = 'response' in xhr ? xhr.response : xhr.responseText;\n\n        if (data && includes(contentType, APPLICATION_JSON)) {\n            data = JSON.parse(data);\n        }\n\n        return {\n            data, headers, status, statusText,\n        };\n    }\n\n    /**\n     * @private\n     * @param {string} rawHeaders\n     * @returns {Object}\n     */\n    parseResponseHeaders(rawHeaders) {\n        const lines = rawHeaders ? rawHeaders.replace(/\\r?\\n[\\t ]+/g, ' ').split(/\\r?\\n/) : [];\n\n        return lines.reduce((headers, line) => {\n            const parts = line.split(':');\n            const key = (parts.shift() || '').trim();\n\n            if (!key) {\n                return headers;\n            }\n\n            return objectAssign({}, headers, {\n                [key.toLowerCase()]: parts.join(':').trim(),\n            });\n        }, {});\n    }\n}\n","export default class RequestFactory {\n    /**\n     * @returns {RequestFactory}\n     */\n    static create() {\n        return new RequestFactory();\n    }\n\n    /**\n     * @param {string} url\n     * @param {Object} options\n     * @param {Function} [callback]\n     * @returns {XMLHttpRequest}\n     */\n    createRequest(url, options, callback) {\n        const xhr = new XMLHttpRequest();\n\n        xhr.onerror = () => {\n            if (callback) {\n                callback(new Error(xhr.statusText));\n            }\n        };\n\n        xhr.onload = () => {\n            if (callback) {\n                callback();\n            }\n        };\n\n        xhr.open(options.method, url, true);\n        this.setOptions(xhr, options);\n\n        return xhr;\n    }\n\n    /**\n     * @private\n     * @param {XMLHttpRequest} xhr\n     * @param {Object} headers\n     * @returns {void}\n     */\n    setHeaders(xhr, headers) {\n        const headerKeys = Object.keys(headers);\n\n        headerKeys.forEach((key) => {\n            const value = headers[key];\n\n            xhr.setRequestHeader(key, value);\n        });\n    }\n\n    /**\n     * @private\n     * @param {XMLHttpRequest} xhr\n     * @param {Object} options\n     * @returns {void}\n     */\n    setOptions(xhr, options) {\n        xhr.withCredentials = options.withCredentials;\n\n        if (options.headers) {\n            this.setHeaders(xhr, options.headers);\n        }\n    }\n}\n","import RequestSender from '../common/http-request/request-sender';\nimport ClientTokenMapper from './v2/payment-mappers/client-token-mapper';\nimport UrlHelper from './url-helper';\n\nexport default class ClientTokenGenerator {\n    /**\n     * @param {Object} config\n     * @returns {PaymentSubmitter}\n     */\n    static create(config) {\n        const urlHelper = UrlHelper.create(config);\n        const requestSender = RequestSender.create();\n        const clientTokenMapper = ClientTokenMapper.create();\n\n        return new ClientTokenGenerator(urlHelper, requestSender, clientTokenMapper);\n    }\n\n    /**\n     * @param {UrlHelper} urlHelper\n     * @param {RequestSender} requestSender\n     * @param {ClientTokenMapper} clientTokenMapper\n     * @returns {void}\n     */\n    constructor(urlHelper, requestSender, clientTokenMapper) {\n        /**\n         * @private\n         * @type {UrlHelper}\n         */\n        this.urlHelper = urlHelper;\n\n        /**\n         * @private\n         * @type {RequestSender}\n         */\n        this.requestSender = requestSender;\n\n        /**\n         * @private\n         * @type {ClientTokenMapper}\n         */\n        this.clientTokenMapper = clientTokenMapper;\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @param {Function} [callback]\n     * @returns {void}\n     */\n    generateClientToken(data, callback) {\n        const url = this.urlHelper.getGenerateClientTokenUrl();\n        const payload = this.clientTokenMapper.mapToClientToken(data);\n\n        this.requestSender.postRequest(url, payload, {}, callback);\n    }\n}\n","import { omitNil } from '../../../common/utils';\nimport CartMapper from './cart-mapper';\nimport GatewayMapper from './gateway-mapper';\nimport QuoteMapper from './quote-mapper';\nimport StoreMapper from './store-mapper';\n\nexport default class ClientTokenMapper {\n    /**\n     * @returns {ClientTokenMapper}\n     */\n    static create() {\n        const cartMapper = CartMapper.create();\n        const gatewayMapper = GatewayMapper.create();\n        const quoteMapper = QuoteMapper.create();\n        const storeMapper = StoreMapper.create();\n\n        return new ClientTokenMapper(cartMapper, gatewayMapper, quoteMapper, storeMapper);\n    }\n\n    /**\n     * @param {CartMapper} cartMapper\n     * @param {GatewayMapper} gatewayMapper\n     * @param {QuoteMapper} quoteMapper\n     * @param {StoreMapper} storeMapper\n     */\n    constructor(cartMapper, gatewayMapper, quoteMapper, storeMapper) {\n        /**\n         * @private\n         * @type {CartMapper}\n         */\n        this.cartMapper = cartMapper;\n\n        /**\n         * @private\n         * @type {GatewayMapper}\n         */\n        this.gatewayMapper = gatewayMapper;\n\n        /**\n         * @private\n         * @type {QuoteMapper}\n         */\n        this.quoteMapper = quoteMapper;\n\n        /**\n         * @private\n         * @type {StoreMapper}\n         */\n        this.storeMapper = storeMapper;\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToClientToken(data) {\n        return omitNil({\n            cart: this.cartMapper.mapToCart(data),\n            gateway: this.gatewayMapper.mapToGateway(data),\n            quote: this.quoteMapper.mapToQuote(data),\n            store: this.storeMapper.mapToStore(data),\n        });\n    }\n}\n","import { omitNil } from '../../../common/utils';\n\nexport default class CartMapper {\n    /**\n     * @returns {CartMapper}\n     */\n    static create() {\n        return new CartMapper();\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToCart(data) {\n        const { cart = {} } = data;\n\n        return omitNil({\n            currency_code: cart.currency,\n            items: this.mapToItems(data),\n            totals: this.mapToOrderTotals(data),\n        });\n    }\n\n    /**\n     * @private\n     * @param {PaymentRequestData} data\n     * @returns {Object[]}\n     */\n    mapToItems(data) {\n        const { cart = { items: [] } } = data;\n\n        return cart.items.map((itemData) => omitNil({\n            discount_amount: itemData.integerDiscount,\n            name: itemData.name,\n            price: itemData.integerAmount,\n            unit_price: itemData.integerUnitPrice,\n            quantity: itemData.quantity,\n            sku: itemData.sku,\n            tax_amount: itemData.integerTax,\n            amount: itemData.integerAmountAfterDiscount,\n            type: this.mapToType(itemData),\n        }));\n    }\n\n    /**\n     * @private\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToOrderTotals(data) {\n        const { cart = {} } = data;\n\n        return omitNil({\n            discount_total: cart.discount ? cart.discount.integerAmount : null,\n            grand_total: cart.grandTotal ? cart.grandTotal.integerAmount : null,\n            shipping_total: cart.shipping ? cart.shipping.integerAmount : null,\n            subtotal: cart.subtotal ? cart.subtotal.integerAmount : null,\n            surcharge_total: cart.handling ? cart.handling.integerAmount : null,\n            tax_total: cart.taxTotal ? cart.taxTotal.integerAmount : null,\n        });\n    }\n\n    /**\n     * @private\n     * @param {Object} itemData\n     * @returns {Object}\n     */\n    mapToType(itemData) {\n        const types = {\n            ItemPhysicalEntity: 'physical',\n            ItemDigitalEntity: 'digital',\n            ItemGiftCertificateEntity: 'gift_card',\n        };\n\n        return types[itemData.type];\n    }\n}\n","import { omitNil } from '../../../common/utils';\nimport PaymentMethodIdMapper from '../../payment-method-mappers/payment-method-id-mapper';\n\nexport default class GatewayMapper {\n    /**\n     * @returns {GatewayMapper}\n     */\n    static create() {\n        const paymentMethodIdMapper = PaymentMethodIdMapper.create();\n\n        return new GatewayMapper(paymentMethodIdMapper);\n    }\n\n    /**\n     * @param {PaymentMethodIdMapper} paymentMethodIdMapper\n     * @returns {void}\n     */\n    constructor(paymentMethodIdMapper) {\n        /**\n         * @private\n         * @type {PaymentMethodIdMapper}\n         */\n        this.paymentMethodIdMapper = paymentMethodIdMapper;\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToGateway(data) {\n        const { paymentMethod = {} } = data;\n\n        return omitNil({\n            name: this.paymentMethodIdMapper.mapToId(paymentMethod),\n        });\n    }\n}\n","import { omitNil } from '../../../common/utils';\n\nexport default class QuoteMapper {\n    /**\n     * @returns {QuoteMapper}\n     */\n    static create() {\n        return new QuoteMapper();\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToQuote(data) {\n        return omitNil({\n            billing_address: this.mapToAddress(data, 'billingAddress'),\n            shipping_address: this.mapToAddress(data, 'shippingAddress'),\n        });\n    }\n\n    /**\n     * @private\n     * @param {PaymentRequestData} data\n     * @param {string} addressKey\n     * @returns {Object}\n     */\n    mapToAddress(data, addressKey) {\n        const { customer = {} } = data;\n        const address = data[addressKey] || {};\n\n        return omitNil({\n            address_line_1: address.addressLine1,\n            address_line_2: address.addressLine2,\n            city: address.city,\n            company: address.company,\n            country_code: address.countryCode,\n            email: customer.email,\n            first_name: address.firstName,\n            last_name: address.lastName,\n            phone: address.phone,\n            postal_code: address.postCode,\n            state: address.province,\n        });\n    }\n}\n","import { omitNil, toNumber } from '../../../common/utils';\n\nexport default class StoreMapper {\n    /**\n     * @returns {StoreMapper}\n     */\n    static create() {\n        return new StoreMapper();\n    }\n\n    /**\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToStore(data) {\n        return omitNil({\n            locale: this.mapToLocale(data),\n            store_identity: this.mapToIdentity(data),\n            urls: this.mapToUrls(data),\n        });\n    }\n\n    /**\n     * @private\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToLocale(data) {\n        const { store = {} } = data;\n\n        return omitNil({\n            country_code: store.countryCode,\n            currency_code: store.currencyCode,\n            language_code: store.storeLanguage,\n        });\n    }\n\n    /**\n     * @private\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToIdentity(data) {\n        const { store = {} } = data;\n\n        return omitNil({\n            id: store.storeId ? toNumber(store.storeId) : null,\n            name: store.storeName,\n        });\n    }\n\n    /**\n     * @private\n     * @param {PaymentRequestData} data\n     * @returns {Object}\n     */\n    mapToUrls(data) {\n        const { store = {} } = data;\n\n        return omitNil({\n            cart: store.cartLink,\n            checkout: store.checkoutLink,\n            confirmation: store.orderConfirmationLink,\n            home: store.shopPath,\n        });\n    }\n}\n","import RequestSender from '../common/http-request/request-sender';\nimport { DELETE, POST } from '../common/http-request/method-types';\nimport UrlHelper from './url-helper';\nimport {\n    mapToHeaders,\n    mapToTrustedShippingAddressPayload,\n} from './v2/mappers';\n\nexport default class StoreRequestSender {\n    /**\n     * @param {Object} config\n     * @returns {StoreRequestSender}\n     */\n    static create(config) {\n        const urlHelper = UrlHelper.create(config);\n        const requestSender = RequestSender.create();\n\n        return new StoreRequestSender(urlHelper, requestSender);\n    }\n\n    /**\n     * @param {UrlHelper} urlHelper\n     * @param {RequestSender} requestSender\n     * @returns {void}\n     */\n    constructor(urlHelper, requestSender) {\n        /**\n         * @private\n         * @type {UrlHelper}\n         */\n        this.urlHelper = urlHelper;\n\n        /**\n         * @private\n         * @type {RequestSender}\n         */\n        this.requestSender = requestSender;\n    }\n\n    /**\n     * @param {Object} data\n     * @param {Function} [callback]\n     * @return {void}\n     */\n    loadInstruments(data, callback) {\n        const url = this.urlHelper.getInstrumentsUrl(\n            data.storeId,\n            data.customerId,\n            data.currencyCode,\n        );\n        const options = {\n            headers: mapToHeaders(data),\n        };\n\n        this.requestSender.sendRequest(url, null, options, callback);\n    }\n\n    /**\n     * @param {Object} data\n     * @param {Function} [callback]\n     * @return {void}\n     */\n    loadInstrumentsWithAddress(data, callback) {\n        const url = this.urlHelper.getTrustedShippingAddressUrl(\n            data.storeId,\n            data.customerId,\n            data.currencyCode,\n        );\n        const payload = mapToTrustedShippingAddressPayload(data);\n        const options = {\n            method: POST,\n            headers: mapToHeaders(data),\n        };\n\n        this.requestSender.postRequest(url, payload, options, callback);\n    }\n\n    /**\n     * @param {Object} data\n     * @param {Function} [callback]\n     * @return {void}\n     */\n    deleteShopperInstrument(data, callback) {\n        const url = this.urlHelper.getInstrumentByIdUrl(\n            data.storeId,\n            data.customerId,\n            data.instrumentId,\n            data.currencyCode,\n        );\n        const options = {\n            method: DELETE,\n            headers: mapToHeaders(data),\n        };\n\n        this.requestSender.sendRequest(url, null, options, callback);\n    }\n}\n","export default class UrlHelper {\n    /**\n     * @param {Object} config\n     * @param {string} config.host\n     * @returns {CustomerMapper}\n     */\n    static create(config) {\n        return new UrlHelper(config);\n    }\n\n    /**\n     * @param {Object} config\n     * @param {string} config.host\n     * @returns {void}\n     */\n    constructor(config) {\n        /**\n         * @private\n         * @type {Object}\n         */\n        this.config = config;\n    }\n\n    /**\n     * @private\n     * @returns {string}\n     * @throws {Error}\n     */\n    get host() {\n        if (!this.config || !this.config.host) {\n            throw new Error('Host URL unavailable or not supplied.');\n        }\n\n        return this.config.host;\n    }\n\n    /**\n     * @param {number} storeId\n     * @param {number} customerId\n     * @param {string} currencyCode\n     * @returns {string}\n     */\n    getInstrumentsUrl(storeId, customerId, currencyCode) {\n        return `${this.host}/api/v3/stores/${storeId}/shoppers/${customerId}/instruments?currency_code=${currencyCode}`;\n    }\n\n    /**\n     * @param {number} storeId\n     * @param {number} customerId\n     * @param {string} currencyCode\n     * @return {string}\n     */\n    getTrustedShippingAddressUrl(storeId, customerId, currencyCode) {\n        return `${this.host}/api/v3/stores/${storeId}/shoppers/${customerId}/instruments/trusted_shipping_address?currency_code=${currencyCode}`;\n    }\n\n    /**\n     * @param {number} storeId\n     * @param {number} customerId\n     * @param {number} instrumentId\n     * @param {string} currencyCode\n     * @returns {string}\n     */\n    getInstrumentByIdUrl(storeId, customerId, instrumentId, currencyCode) {\n        return `${this.host}/api/v2/stores/${storeId}/shoppers/${customerId}/instruments/${instrumentId}?currency_code=${currencyCode}`;\n    }\n}\n","import { omitNil } from '../../../common/utils';\n\n/**\n * @param {Object} [data={}]\n * @param {Object} data.billingAddress\n * @param {CreditCard} data.creditCard\n * @param {boolean} data.defaultInstrument\n * @param {string} data.providerName\n * @return {Object}\n */\nexport function mapToInstrumentPayload(data = {}) {\n    const {\n        providerName,\n        defaultInstrument,\n    } = data;\n\n    const provider = omitNil({ name: providerName });\n\n    return omitNil({\n        provider,\n        credit_card: mapToCreditCard(data),\n        billing_address: mapToAddress(data.billingAddress),\n        default_instrument: defaultInstrument,\n    });\n}\n\n/**\n * @param {Object} [data={}]\n * @param {Object} data.shippingAddress\n * @return {Object}\n */\nexport function mapToTrustedShippingAddressPayload(data = {}) {\n    return omitNil({\n        shipping_address: mapToAddress(data.shippingAddress),\n    });\n}\n\n/**\n * @param {Object} data\n * @param {string} data.authToken\n * @return {Object}\n */\nexport function mapToHeaders({ authToken: Authorization } = {}) {\n    return omitNil({\n        Authorization,\n    });\n}\n\n/**\n * @param {AddressData} address\n * @return {Object}\n */\nfunction mapToAddress(address = {}) {\n    const state = mapToState(address.provinceCode, address.province);\n\n    return omitNil({\n        address_line_1: address.addressLine1,\n        address_line_2: address.addressLine2,\n        city: address.city,\n        company: address.company,\n        country_code: address.countryCode,\n        email: address.email,\n        first_name: address.firstName,\n        last_name: address.lastName,\n        phone: address.phone,\n        postal_code: address.postCode,\n        state,\n    });\n}\n\n/**\n * @param {string} code\n * @param {string} name\n * @return {Object}\n */\nfunction mapToState(code, name) {\n    return omitNil({\n        code,\n        name,\n    });\n}\n\n/**\n * @param {Object} data\n * @param {CreditCard} data.creditCard\n * @return {Object}\n */\nfunction mapToCreditCard({ creditCard = {} }) {\n    const threeDSecure = omitNil(creditCard.threeDSecure);\n\n    return omitNil({\n        cardholder_name: creditCard.cardholderName,\n        number: creditCard.number,\n        month: creditCard.month,\n        year: creditCard.year,\n        verification_code: creditCard.verificationCode,\n        issue_month: creditCard.issueMonth,\n        issue_year: creditCard.issueYear,\n        issue_number: creditCard.issueNumber,\n        track_data: creditCard.trackData,\n        is_manual_entry: creditCard.isManualEntry,\n        icc_data: creditCard.iccData,\n        fallback_reason: creditCard.fallbackReason,\n        is_contactless: creditCard.isContactless,\n        encrypted_pin_cryptogram: creditCard.encryptedPinCryptogram,\n        encrypted_pin_ksn: creditCard.encryptedPinKsn,\n        three_d_secure: threeDSecure,\n    });\n}\n","const DEFAULT_CONFIG = {\n    host: '',\n};\n\nexport default DEFAULT_CONFIG;\n"],"sourceRoot":""}