@bigcommerce/checkout-sdk 1.932.1 → 1.933.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/cjs/checkout-button.js +1 -1
  2. package/dist/cjs/checkout-sdk-essential.js +1 -1
  3. package/dist/cjs/checkout-sdk.js +1 -1
  4. package/dist/cjs/hosted-form-v2-iframe-content.js +1 -1
  5. package/dist/cjs/hosted-form-v2-iframe-content.js.map +1 -1
  6. package/dist/cjs/hosted-form-v2-iframe-host.js +1 -1
  7. package/dist/cjs/hosted-form-v2-iframe-host.js.map +1 -1
  8. package/dist/cjs/integrations/amazon-pay.js +1 -1
  9. package/dist/cjs/integrations/bigcommerce-payments.js +1 -1
  10. package/dist/cjs/integrations/braintree.js +1 -1
  11. package/dist/cjs/integrations/google-pay.js +1 -1
  12. package/dist/cjs/integrations/klarna.js +1 -1
  13. package/dist/cjs/integrations/paypal-commerce.js +1 -1
  14. package/dist/cjs/integrations/paypal-express.js +1 -1
  15. package/dist/cjs/integrations/zip.js +1 -1
  16. package/dist/esm/checkout-button.js +1 -1
  17. package/dist/esm/checkout-sdk-essential.js +1 -1
  18. package/dist/esm/checkout-sdk.js +1 -1
  19. package/dist/esm/hosted-form-v2-iframe-content.js +1 -1
  20. package/dist/esm/hosted-form-v2-iframe-content.js.map +1 -1
  21. package/dist/esm/hosted-form-v2-iframe-host.js +1 -1
  22. package/dist/esm/integrations/amazon-pay.js +1 -1
  23. package/dist/esm/integrations/bigcommerce-payments.js +1 -1
  24. package/dist/esm/integrations/braintree.js +1 -1
  25. package/dist/esm/integrations/google-pay.js +1 -1
  26. package/dist/esm/integrations/klarna.js +1 -1
  27. package/dist/esm/integrations/paypal-commerce.js +1 -1
  28. package/dist/esm/integrations/paypal-express.js +1 -1
  29. package/dist/esm/integrations/zip.js +1 -1
  30. package/dist/hosted-form-v2-iframe-content.d.ts +1 -0
  31. package/dist/hosted-form-v2-iframe-host.d.ts +6 -5
  32. package/package.json +6 -1
@@ -1,2 +1,2 @@
1
- import{createRequestSender as e}from"@bigcommerce/request-sender";import{fromEvent as t}from"rxjs";import{filter as n,map as r,take as i}from"rxjs/operators";import{creditCardType as s,cvv as a,expirationDate as o,number as d}from"card-validator";import{flatMap as c,get as u,isString as l,kebabCase as p,map as h,max as _,snakeCase as m,values as y}from"lodash";import{object as f,string as g}from"yup";class v extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}class b extends v{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}function E(e){if(!/^(https?:)?\/\//.test(e))throw new b("The provided URL must be absolute.");const t=document.createElement("a");t.href=e;const n=t.port&&-1!==e.indexOf(`${t.hostname}:${t.port}`)?t.port:"";return{hash:t.hash,hostname:t.hostname,href:t.href,origin:`${t.protocol}//${t.hostname}${n?`:${n}`:""}`,pathname:t.pathname,port:n,protocol:t.protocol,search:t.search}}function w(e){return E(0===e.hostname.indexOf("www")?e.href:e.href.replace(e.hostname,`www.${e.hostname}`))}function O(e,t,n){if("function"!=typeof n.value)return n;let r=n.value;return{get(){const e=r.bind(this);return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e},set(e){r=e}}}function C(e,t){return e.type===t}class S{constructor(e){this._sourceOrigins=[E(e).origin,w(E(e)).origin],this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))}addListener(e,t){let n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)}removeListener(e,t){const n=this._listeners[e];if(!n)return;const r=n.indexOf(t);r>=0&&n.splice(r,1)}trigger(e,t){const n=this._listeners[e.type];n&&n.forEach(n=>t?n(e,t):n(e))}_handleMessage(e){if(-1===this._sourceOrigins.indexOf(e.origin)||!C(e.data,e.data.type))return;const t=e.data,{context:n}=t,r=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}(t,["context"]);this.trigger(r,n)}}!function(e,t,n,r){var i,s=arguments.length,a=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,r);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(s<3?i(a):s>3?i(t,n,a):i(t,n))||a);s>3&&a&&Object.defineProperty(t,n,a)}([function(e,t,n){return t&&n?O(0,t,n):function(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(n=>{const r=Object.getOwnPropertyDescriptor(e.prototype,n);r&&"constructor"!==n&&Object.defineProperty(t.prototype,n,O(e.prototype,n,r))}),t}(e)}],S.prototype,"_handleMessage",null);class T{setNonce(e){this._nonce=e}getNonce(){return this._nonce}}let P;function I(){return P=P||new T,P}class x{constructor(e,t,n){this._targetWindow=t,this._context=n,this._targetOrigin="*"===e?"*":E(e).origin}post(e,s){const a=this._targetWindow;if(window===a)return;if(!a)throw new Error("Unable to post message because target window is not set.");const o=s&&t(window,"message").pipe(n(e=>e.origin===this._targetOrigin&&C(e.data,e.data.type)&&-1!==[s.successType,s.errorType].indexOf(e.data.type)),r(e=>{if(s.errorType===e.data.type)throw e.data;return e.data}),i(1)).toPromise();return a.postMessage(Object.assign(Object.assign({},e),{context:this._context}),this._targetOrigin),o}setTarget(e){this._targetWindow=e}setContext(e){this._context=e}}var D;!function(e){e.CardCode="cardCode",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.Note="note",e.Hidden="hidden"}(D||(D={}));const N=D;var V;!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(V||(V={}));const A=V;var L,R,j;!function(e){e.Card="card",e.ManualPayment="manual_payment"}(L||(L={})),function(e){e.BankDeposit="bigcommerce_offline.bank_deposit",e.Cheque="bigcommerce_offline.cheque",e.Cod="bigcommerce_offline.cod",e.InStore="bigcommerce_offline.in_store",e.MoneyOrder="bigcommerce_offline.money_order"}(R||(R={})),function(e){e.BankDeposit="bank_deposit",e.Cheque="cheque",e.Cod="cod",e.InStore="in_store",e.MoneyOrder="money_order"}(j||(j={}));const F={[R.BankDeposit]:j.BankDeposit,[R.Cheque]:j.Cheque,[R.Cod]:j.Cod,[R.InStore]:j.InStore,[R.MoneyOrder]:j.MoneyOrder},M=e=>Object.values(R).includes(e);class U{constructor(e,t){this._requestSender=e,this._paymentOrigin=t}submitPayment(e,t,n){return r=this,i=void 0,a=function*(){var r,i,s;const{paymentMethodId:a,paymentSessionToken:o}=e;let d;if("bigcommerce.manual_payment"===a)d={type:L.ManualPayment,note:null!==(r=t.note)&&void 0!==r?r:""};else if(M(a))d={type:F[a]};else{const[e,n]=t.cardExpiry?t.cardExpiry.split("/"):[];d={type:L.Card,name:null!==(i=t.cardName)&&void 0!==i?i:"",number:t.cardNumber?t.cardNumber.replace(/ /g,""):"",expires:{month:Number(e.trim()),year:Number(`20${n.trim()}`)},verification_value:null!==(s=t.cardCode)&&void 0!==s?s:void 0}}const c={headers:{Accept:A.Json,"Content-Type":A.Json,"X-Payment-Session-Token":o},body:{instrument:d,payment_method_id:a,form_nonce:null!=n?n:void 0}};return this._requestSender.post(`${this._paymentOrigin}/payments`,c)},new((s=void 0)||(s=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function o(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var r;t.done?e(t.value):(r=t.value,r instanceof s?r:new s(function(e){e(r)})).then(n,o)}d((a=a.apply(r,i||[])).next())});var r,i,s,a}}var H,q;class k{constructor(e){this._requestSender=e}submitPaymentInstrument(e,t){return n=this,r=void 0,s=function*(){const{providerId:n,currencyCode:r,paymentsUrl:i,shopperId:s,storeHash:a,vaultToken:o}=e,{billingAddress:d,instrument:c,defaultInstrument:u}=t,l=`${i}/stores/${a}/customers/${s}/stored_instruments`,p={headers:{Authorization:o,Accept:"application/vnd.bc.v1+json","Content-Type":"application/vnd.bc.v1+json"},body:JSON.stringify({instrument:{type:c.type,cardholder_name:c.cardholderName,number:c.number,expiry_month:c.expiryMonth,expiry_year:c.expiryYear,verification_value:c.verificationValue},billing_address:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({email:d.email,address1:d.address1},d.address2&&{address2:d.address2}),{city:d.city,postal_code:d.postalCode,country_code:d.countryCode}),d.company&&{company:d.company}),{first_name:d.firstName,last_name:d.lastName}),d.phone&&{phone:d.phone}),d.stateOrProvinceCode&&{state_or_province_code:d.stateOrProvinceCode}),provider_id:n,default_instrument:u,currency_code:r})};yield this._requestSender.post(l,p)},new((i=void 0)||(i=Promise))(function(e,t){function a(e){try{d(s.next(e))}catch(e){t(e)}}function o(e){try{d(s.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,o)}d((s=s.apply(n,r||[])).next())});var n,r,i,s}}class ${format(e){const[t="",n=""]=e.split(new RegExp("\\s*/\\s*")),r=t.slice(0,2),i=4===n.length?n.slice(-2):n?n.slice(0,2):t.slice(2);return e.length<2?t:e.length>3&&!i?r:`${r} / ${i}`}toObject(e){const[t="",n=""]=e.split(new RegExp("\\s*/\\s*"));return/^\d+$/.test(t)&&/^\d+$/.test(n)?{month:1===t.length?`0${t}`:t.slice(0,2),year:2===n.length?`20${n}`:n.slice(0,4)}:{month:"",year:""}}}class B{format(e){const{card:t}=d(e);if(!t)return e;const n=_(s(e).map(e=>_(e.lengths))),r=this.unformat(e).slice(0,n);return t.gaps.filter(e=>r.length>e).reduce((e,t,n)=>[e.slice(0,t+n),e.slice(t+n)].join(" "),r)}unformat(e){const{card:t}=d(e);return t?e.replace(new RegExp(" ","g"),""):e}}function z(e){switch(e){case N.CardCode:return"cc-csc";case N.CardExpiry:return"cc-exp";case N.CardName:return"cc-name";case N.CardNumber:return"cc-number";default:return""}}class W{constructor(e,t,n){this._form=e,this._fieldTypes=t,this._inputAggregator=n,this._handleChange=e=>{const t=e.target;if(!t)throw new Error("Unable to get a reference to the target of the change event.");const n=this._inputAggregator.getInputs().find(e=>this._getAutocompleteElementId(e.getType())===t.id);n&&n.setValue(t.value)},this._inputs=this._fieldTypes.map(e=>this._createInput(e))}attach(){this._inputs.forEach(e=>this._form.appendChild(e))}detach(){this._inputs.forEach(e=>{e.parentElement&&e.parentElement.removeChild(e)})}_createInput(e){const t=document.createElement("input");return t.autocomplete=z(e),t.id=this._getAutocompleteElementId(e),t.tabIndex=-1,t.style.position="absolute",t.style.opacity="0",t.style.zIndex="-1",t.addEventListener("change",this._handleChange),t}_getAutocompleteElementId(e){return`autocomplete-${p(e)}`}}!function(e){e.AttachRequested="HOSTED_FIELD:ATTACH_REQUESTED",e.SubmitRequested="HOSTED_FIELD:SUBMITTED_REQUESTED",e.SubmitManualOrderRequested="HOSTED_FIELD:SUBMIT_MANUAL_ORDER_REQUESTED",e.ValidateRequested="HOSTED_FIELD:VALIDATE_REQUESTED",e.StoredCardRequested="HOSTED_FIELD:STORED_CARD_REQUESTED"}(H||(H={})),function(e){e.AttachSucceeded="HOSTED_INPUT:ATTACH_SUCCEEDED",e.AttachFailed="HOSTED_INPUT:ATTACH_FAILED",e.BinChanged="HOSTED_INPUT:BIN_CHANGED",e.Blurred="HOSTED_INPUT:BLURRED",e.Changed="HOSTED_INPUT:CHANGED",e.CardTypeChanged="HOSTED_INPUT:CARD_TYPE_CHANGED",e.Entered="HOSTED_INPUT:ENTERED",e.Focused="HOSTED_INPUT:FOCUSED",e.SubmitSucceeded="HOSTED_INPUT:SUBMIT_SUCCEEDED",e.SubmitFailed="HOSTED_INPUT:SUBMIT_FAILED",e.SubmitManualOrderSucceeded="HOSTED_INPUT:SUBMIT_MANUAL_ORDER_SUCCEEDED",e.SubmitManualOrderFailed="HOSTED_INPUT:SUBMIT_MANUAL_ORDER_FAILED",e.Validated="HOSTED_INPUT:VALIDATED",e.StoredCardSucceeded="HOSTED_INPUT:STORED_CARD_SUCCEEDED",e.StoredCardFailed="HOSTED_INPUT:STORED_CARD_FAILED"}(q||(q={}));class J{constructor(e,t,n,r,i,s,a,o,d,c,u,l,p){this._type=e,this._form=t,this._placeholder=n,this._accessibilityLabel=r,this._autocomplete=i,this._styles=s,this._fontUrls=a,this._eventListener=o,this._eventPoster=d,this._inputAggregator=c,this._inputValidator=u,this._manualOrderPaymentHandler=l,this._storedCardHandler=p,this._isTouched=!1,this._handleInput=e=>{const t=e.target;this._processChange(t.value)},this._handleBlur=()=>{this._applyStyles(this._styles.default),this._validateForm(),this._eventPoster.post({type:q.Blurred,payload:{fieldType:this._type}})},this._handleFocus=()=>{this._applyStyles(this._styles.focus),this._eventPoster.post({type:q.Focused,payload:{fieldType:this._type}})},this._handleValidate=()=>{this._validateForm()},this._handleSubmit=e=>{e.preventDefault(),this._eventPoster.post({type:q.Entered,payload:{fieldType:this._type}})},this._forceFocusToInput=()=>{document.activeElement===document.body&&(navigator.userAgent.toLowerCase().indexOf("safari")>-1?""===this._input.value&&(this._input.setAttribute("value"," "),this._input.setSelectionRange(0,1),this._input.setAttribute("value","")):this._input.focus())},this._input=document.createElement("input"),this._input.addEventListener("input",this._handleInput),this._input.addEventListener("blur",this._handleBlur),this._input.addEventListener("focus",this._handleFocus),this._eventListener.addListener(H.ValidateRequested,this._handleValidate),this._eventListener.addListener(H.SubmitManualOrderRequested,this._manualOrderPaymentHandler.handle),this._eventListener.addListener(H.StoredCardRequested,this._storedCardHandler.handle),this._configureInput()}getType(){return this._type}getValue(){return this._input.value}setValue(e){this._processChange(e)}isTouched(){return this._isTouched}attach(){this._form.appendChild(this._input),this._form.addEventListener("submit",this._handleSubmit),this._loadFonts(),this._eventPoster.setTarget(window.parent),this._eventListener.listen(),window.addEventListener("focus",this._forceFocusToInput),window.hostedInput=this,this._eventPoster.post({type:q.AttachSucceeded})}detach(){this._input.parentElement&&this._input.parentElement.removeChild(this._input),this._form.removeEventListener("submit",this._handleSubmit),this._unloadFonts(),window.removeEventListener("focus",this._forceFocusToInput),this._eventListener.stopListen()}_formatValue(e){this._input.value=e}_notifyChange(e){this._eventPoster.post({type:q.Changed,payload:{fieldType:this._type}})}_configureInput(){switch(this._input.style.backgroundColor="transparent",this._input.style.border="0",this._input.style.display="block",this._input.style.height="100%",this._input.style.margin="0",this._input.style.outline="none",this._input.style.padding="0",this._input.style.width="100%",this._input.id=p(this._type),this._input.placeholder=this._placeholder,this._input.autocomplete=this._autocomplete,this._input.setAttribute("aria-label",this._accessibilityLabel),this._applyStyles(this._styles.default),this._input.id){case"card-code":case"card-expiry":case"card-number":this._input.type="text",this._input.inputMode="numeric",this._input.pattern="[0-9]*";break;case"card-name":case"note":case"hidden":this._input.type="text",this._input.inputMode="text"}}_applyStyles(e={}){const t={color:e.color,fontFamily:e.fontFamily,fontSize:e.fontSize,fontWeight:e.fontWeight};Object.keys(t).forEach(e=>{t[e]&&(this._input.style[e]=t[e]||"")})}_loadFonts(){this._fontLinks||(this._fontLinks=this._fontUrls.filter(e=>"fonts.googleapis.com"===E(e).hostname).filter(e=>!document.querySelector(`link[href='${e}'][rel='stylesheet']`)).map(e=>{const t=document.createElement("link");return t.rel="stylesheet",t.href=e,document.head.appendChild(t),t}))}_unloadFonts(){this._fontLinks&&(this._fontLinks.forEach(e=>{e.parentElement&&e.parentElement.removeChild(e)}),this._fontLinks=void 0)}_validateForm(){return e=this,t=void 0,r=function*(){const e=this._inputAggregator.getInputValues(),t=yield this._inputValidator.validate(e);t.isValid?this._applyStyles(this._styles.default):this._applyStyles(this._styles.error),this._eventPoster.post({type:q.Validated,payload:t})},new((n=void 0)||(n=Promise))(function(i,s){function a(e){try{d(r.next(e))}catch(e){s(e)}}function o(e){try{d(r.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,o)}d((r=r.apply(e,t||[])).next())});var e,t,n,r}_processChange(e){e!==this._previousValue&&(this._isTouched=!0,this._formatValue(e),this._validateForm(),this._notifyChange(e),this._previousValue=e)}}class Q extends J{constructor(e,t,n,r,i,s,a,o,d,c,u,l,p){super(N.CardExpiry,e,t,n,r,i,s,a,o,d,c,u,l),this._formatter=p}_formatValue(e){this._input.value=this._formatter.format(e)}}class Y extends J{constructor(e,t,n,r,i,s,a,o,d,c,u,l,p,h,_){super(e,t,n,r,i,s,a,o,d,c,u,l,p),this._autocompleteFieldset=h,this._formatter=_}attach(){super.attach(),this._autocompleteFieldset.attach()}_notifyChange(e){const t=d(e).card,n=this._previousValue&&d(this._previousValue).card;u(n,"type")!==u(t,"type")&&this._eventPoster.post({type:q.CardTypeChanged,payload:{cardType:t?t.type:void 0}});const r=this._formatter.unformat(e),i=this._previousValue?this._formatter.unformat(this._previousValue):"",s=r.length>=6&&d(r).isPotentiallyValid?r.substr(0,6):"";s!==(i.length>=6?i.substr(0,6):"")&&this._eventPoster.post({type:q.BinChanged,payload:{bin:s}})}_formatValue(e){const t=this._input.selectionEnd,n=this._formatter.format(e);t===e.length&&e.length<n.length?this._input.setSelectionRange(n.length,n.length):this._input.setSelectionRange(t||0,t||0),this._input.value=n}}class G{constructor(e){this._parentWindow=e}getInputs(e){return Array.prototype.slice.call(this._parentWindow.frames).reduce((t,n)=>{try{const r=n.hostedInput;return!r||e&&!e(r)?t:[...t,r]}catch(e){if(e instanceof DOMException)return t;if(e instanceof Error&&"Permission denied"===e.message)return t;throw e}},[])}getInputValues(e){return this.getInputs(e).reduce((e,t)=>Object.assign(Object.assign({},e),{[t.getType()]:t.getValue()}),{})}}class X extends v{constructor(e){super(["Unable to proceed due to invalid user input values",...c(y(e),e=>h(e,({message:e})=>e))].join(". ")),this.errors=e,this.name="InvalidHostedFormValueError",this.type="invalid_hosted_form_value"}}class K{constructor(e,t,n,r,i){this._inputAggregator=e,this._inputValidator=t,this._inputStorage=n,this._eventPoster=r,this._manualOrderPaymentRequestSender=i,this.handle=e=>{return t=this,n=void 0,i=function*(){var t,n;const{payload:{data:r}}=e,i=this._inputAggregator.getInputValues(),s=yield this._inputValidator.validate(i);if(this._eventPoster.post({type:q.Validated,payload:s}),!s.isValid){const e=new X(s.errors);return this._eventPoster.post({type:q.SubmitManualOrderFailed,payload:{error:{code:m(e.name),message:e.message}}})}try{const e=yield this._manualOrderPaymentRequestSender.submitPayment(r,i,this._inputStorage.getNonce()),s="failure"===u(e.body,"type")&&l(u(e.body,"code")),a="error"===u(e.body,"type"),o=M(r.paymentMethodId)&&"continue"===u(e.body,"type")&&"complete_offline"===u(e.body,"code"),d="continue"===u(e.body,"type")&&"await_confirmation"===u(e.body,"code"),c="success"===u(e.body,"type")||o||d;s?this._eventPoster.post({type:q.SubmitManualOrderFailed,payload:{error:{code:String(null!==(t=u(e.body,"code"))&&void 0!==t?t:"")}}}):a?this._eventPoster.post({type:q.SubmitManualOrderFailed,payload:{error:{code:String(null!==(n=u(e.body,"type"))&&void 0!==n?n:"")}}}):c&&this._eventPoster.post({type:q.SubmitManualOrderSucceeded,payload:{response:e}})}catch(e){this._isPaymentErrorResponse(e)?this._eventPoster.post({type:q.SubmitManualOrderFailed,payload:{error:e.body.errors[0],response:e}}):this._isErrorResponse(e)&&this._eventPoster.post({type:q.SubmitManualOrderFailed,payload:{error:{code:m(e.name),message:e.message}}})}},new((r=void 0)||(r=Promise))(function(e,s){function a(e){try{d(i.next(e))}catch(e){s(e)}}function o(e){try{d(i.throw(e))}catch(e){s(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,o)}d((i=i.apply(t,n||[])).next())});var t,n,r,i}}_isPaymentErrorResponse(e){const{body:{errors:t=[]}={}}=e||{};return"string"==typeof(t[0]&&t[0].code)&&"string"==typeof(t[0]&&t[0].message)}_isErrorResponse(e){return"object"==typeof e&&null!==e&&("name"in e&&"string"==typeof e.name||!("name"in e))&&("message"in e&&"string"==typeof e.message||!("message"in e))}}class Z{constructor(e,t,n,r){this._inputAggregator=e,this._inputValidator=t,this._eventPoster=n,this._storedCardRequestSender=r,this.handle=e=>{return t=this,n=void 0,i=function*(){var t;const{payload:{data:n,fields:r}}=e,i=this._inputAggregator.getInputValues(),s=yield this._inputValidator.validate(i);if(this._eventPoster.post({type:q.Validated,payload:s}),!s.isValid)return this._eventPoster.post({type:q.StoredCardFailed});const{defaultInstrument:a}=r,o=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}(r,["defaultInstrument"]),[d,c]=i.cardExpiry?i.cardExpiry.split("/"):[];try{yield this._storedCardRequestSender.submitPaymentInstrument(n,{billingAddress:o,instrument:{type:"card",cardholderName:i.cardName||"",number:i.cardNumber?i.cardNumber.replace(/ /g,""):"",expiryMonth:Number(d.trim()),expiryYear:Number(`20${c.trim()}`),verificationValue:null!==(t=i.cardCode)&&void 0!==t?t:""},defaultInstrument:a}),this._eventPoster.post({type:q.StoredCardSucceeded})}catch(e){this._eventPoster.post({type:q.StoredCardFailed})}},new((r=void 0)||(r=Promise))(function(e,s){function a(e){try{d(i.next(e))}catch(e){s(e)}}function o(e){try{d(i.throw(e))}catch(e){s(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,o)}d((i=i.apply(t,n||[])).next())});var t,n,r,i}}}class ee{constructor(){this._completeSchema={cardCode:this._getCardCodeSchema(),cardExpiry:this._getCardExpirySchema(),cardName:this._getCardNameSchema(),cardNumber:this._getCardNumberSchema(),note:this._getNoteSchema()},this._configureCardValidator()}validate(e){return t=this,n=void 0,i=function*(){const t={},n={errors:{},isValid:!0};let r;for(r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=this._completeSchema[r],n.errors[r]=[]);try{return yield f(t).validate(e,{abortEarly:!1}),n}catch(e){if(this._isValidationErrorType(e))throw e;return{errors:Object.keys(n.errors).reduce((t,n)=>Object.assign(Object.assign({},t),{[n]:e.inner.filter(e=>e.path===n).map(e=>({fieldType:e.path,message:e.errors.join(" "),type:e.type}))}),{}),isValid:!1}}},new((r=void 0)||(r=Promise))(function(e,s){function a(e){try{d(i.next(e))}catch(e){s(e)}}function o(e){try{d(i.throw(e))}catch(e){s(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,o)}d((i=i.apply(t,n||[])).next())});var t,n,r,i}_configureCardValidator(){const e=s.getTypeInfo("discover"),t=s.getTypeInfo("visa");s.updateCard("visa",{lengths:[13,...t.lengths||[]]}),s.updateCard("discover",{patterns:[...e.patterns||[],[810,817]]}),s.addCard({niceType:"Mada",type:"mada",patterns:[400861,401757,407197,407395,409201,410685,412565,417633,419593,422817,422818,422819,428331,428671,428672,428673,431361,432328,434107,439954,440533,440647,440795,445564,446393,446404,446672,455036,455708,457865,458456,462220,468540,468541,468542,468543,483010,483011,483012,484783,486094,486095,486096,489317,489318,489319,493428,504300,506968,508160,513213,520058,521076,524130,524514,529415,529741,530060,530906,531095,531196,532013,535825,535989,536023,537767,539931,543085,543357,549760,554180,557606,558848,585265,588845,588846,588847,588848,588849,588850,588851,588982,588983,589005,589206,604906,605141,636120,968201,968202,968203,968204,968205,968206,968207,968208,968209,968210,968211],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}})}_getCardCodeSchema(){return g().required("CVV is required").test({message:"CVV must be valid",name:"invalid_card_code",test(e){const{card:t}=d(this.parent.cardNumber||"");return a(e,t&&t.code?t.code.size:void 0).isValid}})}_getCardExpirySchema(){return g().required("Expiration date is required").test({message:"Expiration date must be a valid future date in MM / YY format",name:"invalid_card_expiry",test:e=>o(e).isValid})}_getCardNameSchema(){return g().max(200).required("Full name is required").test({message:"Credit card name must be valid",name:"invalid_card_name",test:e=>{const t=e.replace(/\s/g,"").match(/[0-9]+/g);if(!(null==t?void 0:t.length))return!0;for(const e of t)if(d(e).isValid)return!1;return!0}})}_getNoteSchema(){return g().required("Manual payment description is required").max(128,"Payment description cannot exceed 128 letters")}_getCardNumberSchema(){return g().required("Credit card number is required").test({message:"Credit card number must be valid",name:"invalid_card_number",test:e=>d(e).isValid})}_isValidationErrorType(e){return"name"in e&&"ValidationError"!==e.name}}class te{constructor(e,t){this._parentOrigin=e,this._paymentOrigin=t}create(e,t,n={},r=[],i="",s=function(e){switch(e){case N.CardCode:return"CVC";case N.CardExpiry:return"Expiration";case N.CardName:return"Name on card";case N.CardNumber:return"Credit card number";case N.Note:return"Payment note";case N.Hidden:return"Hidden field"}}(t)){const a=z(t);return t===N.CardNumber?this._createNumberInput(t,e,n,r,i,s,a):t===N.CardExpiry?this._createExpiryInput(e,n,r,i,s,a):this._createInput(t,e,n,r,i,s,a)}normalizeParentOrigin(e){this._parentOrigin!==e&&(this._parentOrigin!==w(E(e)).origin&&e!==w(E(this._parentOrigin)).origin||(this._parentOrigin=e))}getParentOrigin(){return this._parentOrigin}_createExpiryInput(e,t,n,r,i="",s=""){return new Q(e,r,i,s,t,n,new S(this._parentOrigin),new x(this._parentOrigin,window.parent),new G(window.parent),new ee,this._createManualOrderPaymentHandler(),this._createStoredCardHandler(),new $)}_createNumberInput(e,t,n,r,i,s="",a=""){return new Y(e,t,i,s,a,n,r,new S(this._parentOrigin),new x(this._parentOrigin,window.parent),new G(window.parent),new ee,this._createManualOrderPaymentHandler(),this._createStoredCardHandler(),new W(t,[N.CardCode,N.CardExpiry,N.CardName],new G(window.parent)),new B)}_createInput(e,t,n,r,i,s="",a=""){return new J(e,t,i,s,a,n,r,new S(this._parentOrigin),new x(this._parentOrigin,window.parent),new G(window.parent),new ee,this._createManualOrderPaymentHandler(),this._createStoredCardHandler())}_createManualOrderPaymentHandler(){return new K(new G(window.parent),new ee,I(),new x(this._parentOrigin,window.parent),new U(e(),this._paymentOrigin))}_createStoredCardHandler(){return new Z(new G(window.parent),new ee,new x(this._parentOrigin,window.parent),new k(e()))}}class ne extends v{constructor(e){super(e||"Unable to proceed due to invalid configuration provided for the hosted payment form."),this.name="InvalidHostedFormConfigError",this.type="invalid_hosted_form_config"}}class re{constructor(e,t,n){this._factory=e,this._storage=t,this._eventListener=n}initialize(e,n){n&&this._storage.setNonce(n);const s=this._createFormContainer(e);return this._resetPageStyles(e),this._eventListener.listen(),t(this._eventListener,H.AttachRequested).pipe(r(({payload:e})=>{const{accessibilityLabel:t,fontUrls:n,placeholder:r,styles:i,origin:a,type:o}=e;a&&this._factory.normalizeParentOrigin(a);const d=this._factory.create(s,o,i,n,r,t);return d.attach(),d}),i(1)).toPromise()}_resetPageStyles(e){[document.querySelector("html"),document.querySelector("body"),document.getElementById(e)].forEach(e=>{e&&(e.style.height="100%",e.style.width="100%",e.style.overflow="hidden",e.style.padding="0",e.style.margin="0")})}_createFormContainer(e){const t=document.getElementById(e);if(!t)throw new ne("Unable to proceed because the provided container ID is not valid.");const n=document.createElement("form"),r=document.createElement("button");return n.noValidate=!0,n.style.height="100%",n.style.width="100%",r.style.display="none",t.appendChild(n),n.appendChild(r),n}}function ie(e){const{containerId:t,nonce:n,parentOrigin:r,paymentOrigin:i}=e;return new re(new te(r,i),I(),new S(r)).initialize(t,n)}const se=new x("*",window.parent);function ae(e){se.post({type:q.AttachFailed,payload:{error:e}})}export{ie as initializeHostedInput,ae as notifyInitializeError};
1
+ import{createRequestSender as e}from"@bigcommerce/request-sender";import{fromEvent as t}from"rxjs";import{filter as n,map as r,take as i}from"rxjs/operators";import{creditCardType as s,cvv as a,expirationDate as o,number as d}from"card-validator";import{flatMap as c,get as u,isString as l,kebabCase as p,map as h,max as _,snakeCase as m,values as y}from"lodash";import{object as f,string as g}from"yup";class v extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}class b extends v{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}function E(e){if(!/^(https?:)?\/\//.test(e))throw new b("The provided URL must be absolute.");const t=document.createElement("a");t.href=e;const n=t.port&&-1!==e.indexOf(`${t.hostname}:${t.port}`)?t.port:"";return{hash:t.hash,hostname:t.hostname,href:t.href,origin:`${t.protocol}//${t.hostname}${n?`:${n}`:""}`,pathname:t.pathname,port:n,protocol:t.protocol,search:t.search}}function w(e){return E(0===e.hostname.indexOf("www")?e.href:e.href.replace(e.hostname,`www.${e.hostname}`))}function O(e,t,n){if("function"!=typeof n.value)return n;let r=n.value;return{get(){const e=r.bind(this);return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e},set(e){r=e}}}function C(e,t){return e.type===t}class S{constructor(e){this._sourceOrigins=[E(e).origin,w(E(e)).origin],this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))}addListener(e,t){let n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)}removeListener(e,t){const n=this._listeners[e];if(!n)return;const r=n.indexOf(t);r>=0&&n.splice(r,1)}trigger(e,t){const n=this._listeners[e.type];n&&n.forEach(n=>t?n(e,t):n(e))}_handleMessage(e){if(-1===this._sourceOrigins.indexOf(e.origin)||!C(e.data,e.data.type))return;const t=e.data,{context:n}=t,r=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}(t,["context"]);this.trigger(r,n)}}!function(e,t,n,r){var i,s=arguments.length,a=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,r);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(s<3?i(a):s>3?i(t,n,a):i(t,n))||a);s>3&&a&&Object.defineProperty(t,n,a)}([function(e,t,n){return t&&n?O(0,t,n):function(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(n=>{const r=Object.getOwnPropertyDescriptor(e.prototype,n);r&&"constructor"!==n&&Object.defineProperty(t.prototype,n,O(e.prototype,n,r))}),t}(e)}],S.prototype,"_handleMessage",null);class T{setNonce(e){this._nonce=e}getNonce(){return this._nonce}}let P;function I(){return P=P||new T,P}class x{constructor(e,t,n){this._targetWindow=t,this._context=n,this._targetOrigin="*"===e?"*":E(e).origin}post(e,s){const a=this._targetWindow;if(window===a)return;if(!a)throw new Error("Unable to post message because target window is not set.");const o=s&&t(window,"message").pipe(n(e=>e.origin===this._targetOrigin&&C(e.data,e.data.type)&&-1!==[s.successType,s.errorType].indexOf(e.data.type)),r(e=>{if(s.errorType===e.data.type)throw e.data;return e.data}),i(1)).toPromise();return a.postMessage(Object.assign(Object.assign({},e),{context:this._context}),this._targetOrigin),o}setTarget(e){this._targetWindow=e}setContext(e){this._context=e}}var D;!function(e){e.CardCode="cardCode",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.Note="note",e.Hidden="hidden"}(D||(D={}));const N=D;var V;!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(V||(V={}));const A=V;var L,R,j;!function(e){e.Card="card",e.ManualPayment="manual_payment",e.TokenizedCard="tokenized_card"}(L||(L={})),function(e){e.BankDeposit="bigcommerce_offline.bank_deposit",e.Cheque="bigcommerce_offline.cheque",e.Cod="bigcommerce_offline.cod",e.InStore="bigcommerce_offline.in_store",e.MoneyOrder="bigcommerce_offline.money_order"}(R||(R={})),function(e){e.BankDeposit="bank_deposit",e.Cheque="cheque",e.Cod="cod",e.InStore="in_store",e.MoneyOrder="money_order"}(j||(j={}));const F={[R.BankDeposit]:j.BankDeposit,[R.Cheque]:j.Cheque,[R.Cod]:j.Cod,[R.InStore]:j.InStore,[R.MoneyOrder]:j.MoneyOrder},M=e=>Object.values(R).includes(e);class U{constructor(e,t){this._requestSender=e,this._paymentOrigin=t}submitPayment(e,t,n){return r=this,i=void 0,a=function*(){var r,i,s;const{paymentMethodId:a,paymentSessionToken:o}=e;let d;if(e.token)d={type:L.TokenizedCard,token:e.token};else if("bigcommerce.manual_payment"===a)d={type:L.ManualPayment,note:null!==(r=t.note)&&void 0!==r?r:""};else if(M(a))d={type:F[a]};else{const[e,n]=t.cardExpiry?t.cardExpiry.split("/"):[];d={type:L.Card,name:null!==(i=t.cardName)&&void 0!==i?i:"",number:t.cardNumber?t.cardNumber.replace(/ /g,""):"",expires:{month:Number(e.trim()),year:Number(`20${n.trim()}`)},verification_value:null!==(s=t.cardCode)&&void 0!==s?s:void 0}}const c={headers:{Accept:A.Json,"Content-Type":A.Json,"X-Payment-Session-Token":o},body:{instrument:d,payment_method_id:a,form_nonce:null!=n?n:void 0}};return this._requestSender.post(`${this._paymentOrigin}/payments`,c)},new((s=void 0)||(s=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function o(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var r;t.done?e(t.value):(r=t.value,r instanceof s?r:new s(function(e){e(r)})).then(n,o)}d((a=a.apply(r,i||[])).next())});var r,i,s,a}}var H,q;class k{constructor(e){this._requestSender=e}submitPaymentInstrument(e,t){return n=this,r=void 0,s=function*(){const{providerId:n,currencyCode:r,paymentsUrl:i,shopperId:s,storeHash:a,vaultToken:o}=e,{billingAddress:d,instrument:c,defaultInstrument:u}=t,l=`${i}/stores/${a}/customers/${s}/stored_instruments`,p={headers:{Authorization:o,Accept:"application/vnd.bc.v1+json","Content-Type":"application/vnd.bc.v1+json"},body:JSON.stringify({instrument:{type:c.type,cardholder_name:c.cardholderName,number:c.number,expiry_month:c.expiryMonth,expiry_year:c.expiryYear,verification_value:c.verificationValue},billing_address:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({email:d.email,address1:d.address1},d.address2&&{address2:d.address2}),{city:d.city,postal_code:d.postalCode,country_code:d.countryCode}),d.company&&{company:d.company}),{first_name:d.firstName,last_name:d.lastName}),d.phone&&{phone:d.phone}),d.stateOrProvinceCode&&{state_or_province_code:d.stateOrProvinceCode}),provider_id:n,default_instrument:u,currency_code:r})};yield this._requestSender.post(l,p)},new((i=void 0)||(i=Promise))(function(e,t){function a(e){try{d(s.next(e))}catch(e){t(e)}}function o(e){try{d(s.throw(e))}catch(e){t(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,o)}d((s=s.apply(n,r||[])).next())});var n,r,i,s}}class ${format(e){const[t="",n=""]=e.split(new RegExp("\\s*/\\s*")),r=t.slice(0,2),i=4===n.length?n.slice(-2):n?n.slice(0,2):t.slice(2);return e.length<2?t:e.length>3&&!i?r:`${r} / ${i}`}toObject(e){const[t="",n=""]=e.split(new RegExp("\\s*/\\s*"));return/^\d+$/.test(t)&&/^\d+$/.test(n)?{month:1===t.length?`0${t}`:t.slice(0,2),year:2===n.length?`20${n}`:n.slice(0,4)}:{month:"",year:""}}}class B{format(e){const{card:t}=d(e);if(!t)return e;const n=_(s(e).map(e=>_(e.lengths))),r=this.unformat(e).slice(0,n);return t.gaps.filter(e=>r.length>e).reduce((e,t,n)=>[e.slice(0,t+n),e.slice(t+n)].join(" "),r)}unformat(e){const{card:t}=d(e);return t?e.replace(new RegExp(" ","g"),""):e}}function z(e){switch(e){case N.CardCode:return"cc-csc";case N.CardExpiry:return"cc-exp";case N.CardName:return"cc-name";case N.CardNumber:return"cc-number";default:return""}}class W{constructor(e,t,n){this._form=e,this._fieldTypes=t,this._inputAggregator=n,this._handleChange=e=>{const t=e.target;if(!t)throw new Error("Unable to get a reference to the target of the change event.");const n=this._inputAggregator.getInputs().find(e=>this._getAutocompleteElementId(e.getType())===t.id);n&&n.setValue(t.value)},this._inputs=this._fieldTypes.map(e=>this._createInput(e))}attach(){this._inputs.forEach(e=>this._form.appendChild(e))}detach(){this._inputs.forEach(e=>{e.parentElement&&e.parentElement.removeChild(e)})}_createInput(e){const t=document.createElement("input");return t.autocomplete=z(e),t.id=this._getAutocompleteElementId(e),t.tabIndex=-1,t.style.position="absolute",t.style.opacity="0",t.style.zIndex="-1",t.addEventListener("change",this._handleChange),t}_getAutocompleteElementId(e){return`autocomplete-${p(e)}`}}!function(e){e.AttachRequested="HOSTED_FIELD:ATTACH_REQUESTED",e.SubmitRequested="HOSTED_FIELD:SUBMITTED_REQUESTED",e.SubmitManualOrderRequested="HOSTED_FIELD:SUBMIT_MANUAL_ORDER_REQUESTED",e.ValidateRequested="HOSTED_FIELD:VALIDATE_REQUESTED",e.StoredCardRequested="HOSTED_FIELD:STORED_CARD_REQUESTED"}(H||(H={})),function(e){e.AttachSucceeded="HOSTED_INPUT:ATTACH_SUCCEEDED",e.AttachFailed="HOSTED_INPUT:ATTACH_FAILED",e.BinChanged="HOSTED_INPUT:BIN_CHANGED",e.Blurred="HOSTED_INPUT:BLURRED",e.Changed="HOSTED_INPUT:CHANGED",e.CardTypeChanged="HOSTED_INPUT:CARD_TYPE_CHANGED",e.Entered="HOSTED_INPUT:ENTERED",e.Focused="HOSTED_INPUT:FOCUSED",e.SubmitSucceeded="HOSTED_INPUT:SUBMIT_SUCCEEDED",e.SubmitFailed="HOSTED_INPUT:SUBMIT_FAILED",e.SubmitManualOrderSucceeded="HOSTED_INPUT:SUBMIT_MANUAL_ORDER_SUCCEEDED",e.SubmitManualOrderFailed="HOSTED_INPUT:SUBMIT_MANUAL_ORDER_FAILED",e.Validated="HOSTED_INPUT:VALIDATED",e.StoredCardSucceeded="HOSTED_INPUT:STORED_CARD_SUCCEEDED",e.StoredCardFailed="HOSTED_INPUT:STORED_CARD_FAILED"}(q||(q={}));class J{constructor(e,t,n,r,i,s,a,o,d,c,u,l,p){this._type=e,this._form=t,this._placeholder=n,this._accessibilityLabel=r,this._autocomplete=i,this._styles=s,this._fontUrls=a,this._eventListener=o,this._eventPoster=d,this._inputAggregator=c,this._inputValidator=u,this._manualOrderPaymentHandler=l,this._storedCardHandler=p,this._isTouched=!1,this._handleInput=e=>{const t=e.target;this._processChange(t.value)},this._handleBlur=()=>{this._applyStyles(this._styles.default),this._validateForm(),this._eventPoster.post({type:q.Blurred,payload:{fieldType:this._type}})},this._handleFocus=()=>{this._applyStyles(this._styles.focus),this._eventPoster.post({type:q.Focused,payload:{fieldType:this._type}})},this._handleValidate=()=>{this._validateForm()},this._handleSubmit=e=>{e.preventDefault(),this._eventPoster.post({type:q.Entered,payload:{fieldType:this._type}})},this._forceFocusToInput=()=>{document.activeElement===document.body&&(navigator.userAgent.toLowerCase().indexOf("safari")>-1?""===this._input.value&&(this._input.setAttribute("value"," "),this._input.setSelectionRange(0,1),this._input.setAttribute("value","")):this._input.focus())},this._input=document.createElement("input"),this._input.addEventListener("input",this._handleInput),this._input.addEventListener("blur",this._handleBlur),this._input.addEventListener("focus",this._handleFocus),this._eventListener.addListener(H.ValidateRequested,this._handleValidate),this._eventListener.addListener(H.SubmitManualOrderRequested,this._manualOrderPaymentHandler.handle),this._eventListener.addListener(H.StoredCardRequested,this._storedCardHandler.handle),this._configureInput()}getType(){return this._type}getValue(){return this._input.value}setValue(e){this._processChange(e)}isTouched(){return this._isTouched}attach(){this._form.appendChild(this._input),this._form.addEventListener("submit",this._handleSubmit),this._loadFonts(),this._eventPoster.setTarget(window.parent),this._eventListener.listen(),window.addEventListener("focus",this._forceFocusToInput),window.hostedInput=this,this._eventPoster.post({type:q.AttachSucceeded})}detach(){this._input.parentElement&&this._input.parentElement.removeChild(this._input),this._form.removeEventListener("submit",this._handleSubmit),this._unloadFonts(),window.removeEventListener("focus",this._forceFocusToInput),this._eventListener.stopListen()}_formatValue(e){this._input.value=e}_notifyChange(e){this._eventPoster.post({type:q.Changed,payload:{fieldType:this._type}})}_configureInput(){switch(this._input.style.backgroundColor="transparent",this._input.style.border="0",this._input.style.display="block",this._input.style.height="100%",this._input.style.margin="0",this._input.style.outline="none",this._input.style.padding="0",this._input.style.width="100%",this._input.id=p(this._type),this._input.placeholder=this._placeholder,this._input.autocomplete=this._autocomplete,this._input.setAttribute("aria-label",this._accessibilityLabel),this._applyStyles(this._styles.default),this._input.id){case"card-code":case"card-expiry":case"card-number":this._input.type="text",this._input.inputMode="numeric",this._input.pattern="[0-9]*";break;case"card-name":case"note":case"hidden":this._input.type="text",this._input.inputMode="text"}}_applyStyles(e={}){const t={color:e.color,fontFamily:e.fontFamily,fontSize:e.fontSize,fontWeight:e.fontWeight};Object.keys(t).forEach(e=>{t[e]&&(this._input.style[e]=t[e]||"")})}_loadFonts(){this._fontLinks||(this._fontLinks=this._fontUrls.filter(e=>"fonts.googleapis.com"===E(e).hostname).filter(e=>!document.querySelector(`link[href='${e}'][rel='stylesheet']`)).map(e=>{const t=document.createElement("link");return t.rel="stylesheet",t.href=e,document.head.appendChild(t),t}))}_unloadFonts(){this._fontLinks&&(this._fontLinks.forEach(e=>{e.parentElement&&e.parentElement.removeChild(e)}),this._fontLinks=void 0)}_validateForm(){return e=this,t=void 0,r=function*(){const e=this._inputAggregator.getInputValues(),t=yield this._inputValidator.validate(e);t.isValid?this._applyStyles(this._styles.default):this._applyStyles(this._styles.error),this._eventPoster.post({type:q.Validated,payload:t})},new((n=void 0)||(n=Promise))(function(i,s){function a(e){try{d(r.next(e))}catch(e){s(e)}}function o(e){try{d(r.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,o)}d((r=r.apply(e,t||[])).next())});var e,t,n,r}_processChange(e){e!==this._previousValue&&(this._isTouched=!0,this._formatValue(e),this._validateForm(),this._notifyChange(e),this._previousValue=e)}}class Q extends J{constructor(e,t,n,r,i,s,a,o,d,c,u,l,p){super(N.CardExpiry,e,t,n,r,i,s,a,o,d,c,u,l),this._formatter=p}_formatValue(e){this._input.value=this._formatter.format(e)}}class Y extends J{constructor(e,t,n,r,i,s,a,o,d,c,u,l,p,h,_){super(e,t,n,r,i,s,a,o,d,c,u,l,p),this._autocompleteFieldset=h,this._formatter=_}attach(){super.attach(),this._autocompleteFieldset.attach()}_notifyChange(e){const t=d(e).card,n=this._previousValue&&d(this._previousValue).card;u(n,"type")!==u(t,"type")&&this._eventPoster.post({type:q.CardTypeChanged,payload:{cardType:t?t.type:void 0}});const r=this._formatter.unformat(e),i=this._previousValue?this._formatter.unformat(this._previousValue):"",s=r.length>=6&&d(r).isPotentiallyValid?r.substr(0,6):"";s!==(i.length>=6?i.substr(0,6):"")&&this._eventPoster.post({type:q.BinChanged,payload:{bin:s}})}_formatValue(e){const t=this._input.selectionEnd,n=this._formatter.format(e);t===e.length&&e.length<n.length?this._input.setSelectionRange(n.length,n.length):this._input.setSelectionRange(t||0,t||0),this._input.value=n}}class G{constructor(e){this._parentWindow=e}getInputs(e){return Array.prototype.slice.call(this._parentWindow.frames).reduce((t,n)=>{try{const r=n.hostedInput;return!r||e&&!e(r)?t:[...t,r]}catch(e){if(e instanceof DOMException)return t;if(e instanceof Error&&"Permission denied"===e.message)return t;throw e}},[])}getInputValues(e){return this.getInputs(e).reduce((e,t)=>Object.assign(Object.assign({},e),{[t.getType()]:t.getValue()}),{})}}class X extends v{constructor(e){super(["Unable to proceed due to invalid user input values",...c(y(e),e=>h(e,({message:e})=>e))].join(". ")),this.errors=e,this.name="InvalidHostedFormValueError",this.type="invalid_hosted_form_value"}}class K{constructor(e,t,n,r,i){this._inputAggregator=e,this._inputValidator=t,this._inputStorage=n,this._eventPoster=r,this._manualOrderPaymentRequestSender=i,this.handle=e=>{return t=this,n=void 0,i=function*(){var t,n;const{payload:{data:r}}=e,i=this._inputAggregator.getInputValues(),s=yield this._inputValidator.validate(i);if(this._eventPoster.post({type:q.Validated,payload:s}),!s.isValid){const e=new X(s.errors);return this._eventPoster.post({type:q.SubmitManualOrderFailed,payload:{error:{code:m(e.name),message:e.message}}})}try{const e=yield this._manualOrderPaymentRequestSender.submitPayment(r,i,this._inputStorage.getNonce()),s="failure"===u(e.body,"type")&&l(u(e.body,"code")),a="error"===u(e.body,"type"),o=M(r.paymentMethodId)&&"continue"===u(e.body,"type")&&"complete_offline"===u(e.body,"code"),d="continue"===u(e.body,"type")&&"await_confirmation"===u(e.body,"code"),c="success"===u(e.body,"type")||o||d;s?this._eventPoster.post({type:q.SubmitManualOrderFailed,payload:{error:{code:String(null!==(t=u(e.body,"code"))&&void 0!==t?t:"")}}}):a?this._eventPoster.post({type:q.SubmitManualOrderFailed,payload:{error:{code:String(null!==(n=u(e.body,"type"))&&void 0!==n?n:"")}}}):c&&this._eventPoster.post({type:q.SubmitManualOrderSucceeded,payload:{response:e}})}catch(e){this._isPaymentErrorResponse(e)?this._eventPoster.post({type:q.SubmitManualOrderFailed,payload:{error:e.body.errors[0],response:e}}):this._isErrorResponse(e)&&this._eventPoster.post({type:q.SubmitManualOrderFailed,payload:{error:{code:m(e.name),message:e.message}}})}},new((r=void 0)||(r=Promise))(function(e,s){function a(e){try{d(i.next(e))}catch(e){s(e)}}function o(e){try{d(i.throw(e))}catch(e){s(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,o)}d((i=i.apply(t,n||[])).next())});var t,n,r,i}}_isPaymentErrorResponse(e){const{body:{errors:t=[]}={}}=e||{};return"string"==typeof(t[0]&&t[0].code)&&"string"==typeof(t[0]&&t[0].message)}_isErrorResponse(e){return"object"==typeof e&&null!==e&&("name"in e&&"string"==typeof e.name||!("name"in e))&&("message"in e&&"string"==typeof e.message||!("message"in e))}}class Z{constructor(e,t,n,r){this._inputAggregator=e,this._inputValidator=t,this._eventPoster=n,this._storedCardRequestSender=r,this.handle=e=>{return t=this,n=void 0,i=function*(){var t;const{payload:{data:n,fields:r}}=e,i=this._inputAggregator.getInputValues(),s=yield this._inputValidator.validate(i);if(this._eventPoster.post({type:q.Validated,payload:s}),!s.isValid)return this._eventPoster.post({type:q.StoredCardFailed});const{defaultInstrument:a}=r,o=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}(r,["defaultInstrument"]),[d,c]=i.cardExpiry?i.cardExpiry.split("/"):[];try{yield this._storedCardRequestSender.submitPaymentInstrument(n,{billingAddress:o,instrument:{type:"card",cardholderName:i.cardName||"",number:i.cardNumber?i.cardNumber.replace(/ /g,""):"",expiryMonth:Number(d.trim()),expiryYear:Number(`20${c.trim()}`),verificationValue:null!==(t=i.cardCode)&&void 0!==t?t:""},defaultInstrument:a}),this._eventPoster.post({type:q.StoredCardSucceeded})}catch(e){this._eventPoster.post({type:q.StoredCardFailed})}},new((r=void 0)||(r=Promise))(function(e,s){function a(e){try{d(i.next(e))}catch(e){s(e)}}function o(e){try{d(i.throw(e))}catch(e){s(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,o)}d((i=i.apply(t,n||[])).next())});var t,n,r,i}}}class ee{constructor(){this._completeSchema={cardCode:this._getCardCodeSchema(),cardExpiry:this._getCardExpirySchema(),cardName:this._getCardNameSchema(),cardNumber:this._getCardNumberSchema(),note:this._getNoteSchema()},this._configureCardValidator()}validate(e){return t=this,n=void 0,i=function*(){const t={},n={errors:{},isValid:!0};let r;for(r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=this._completeSchema[r],n.errors[r]=[]);try{return yield f(t).validate(e,{abortEarly:!1}),n}catch(e){if(this._isValidationErrorType(e))throw e;return{errors:Object.keys(n.errors).reduce((t,n)=>Object.assign(Object.assign({},t),{[n]:e.inner.filter(e=>e.path===n).map(e=>({fieldType:e.path,message:e.errors.join(" "),type:e.type}))}),{}),isValid:!1}}},new((r=void 0)||(r=Promise))(function(e,s){function a(e){try{d(i.next(e))}catch(e){s(e)}}function o(e){try{d(i.throw(e))}catch(e){s(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,o)}d((i=i.apply(t,n||[])).next())});var t,n,r,i}_configureCardValidator(){const e=s.getTypeInfo("discover"),t=s.getTypeInfo("visa");s.updateCard("visa",{lengths:[13,...t.lengths||[]]}),s.updateCard("discover",{patterns:[...e.patterns||[],[810,817]]}),s.addCard({niceType:"Mada",type:"mada",patterns:[400861,401757,407197,407395,409201,410685,412565,417633,419593,422817,422818,422819,428331,428671,428672,428673,431361,432328,434107,439954,440533,440647,440795,445564,446393,446404,446672,455036,455708,457865,458456,462220,468540,468541,468542,468543,483010,483011,483012,484783,486094,486095,486096,489317,489318,489319,493428,504300,506968,508160,513213,520058,521076,524130,524514,529415,529741,530060,530906,531095,531196,532013,535825,535989,536023,537767,539931,543085,543357,549760,554180,557606,558848,585265,588845,588846,588847,588848,588849,588850,588851,588982,588983,589005,589206,604906,605141,636120,968201,968202,968203,968204,968205,968206,968207,968208,968209,968210,968211],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}})}_getCardCodeSchema(){return g().required("CVV is required").test({message:"CVV must be valid",name:"invalid_card_code",test(e){const{card:t}=d(this.parent.cardNumber||"");return a(e,t&&t.code?t.code.size:void 0).isValid}})}_getCardExpirySchema(){return g().required("Expiration date is required").test({message:"Expiration date must be a valid future date in MM / YY format",name:"invalid_card_expiry",test:e=>o(e).isValid})}_getCardNameSchema(){return g().max(200).required("Full name is required").test({message:"Credit card name must be valid",name:"invalid_card_name",test:e=>{const t=e.replace(/\s/g,"").match(/[0-9]+/g);if(!(null==t?void 0:t.length))return!0;for(const e of t)if(d(e).isValid)return!1;return!0}})}_getNoteSchema(){return g().required("Manual payment description is required").max(128,"Payment description cannot exceed 128 letters")}_getCardNumberSchema(){return g().required("Credit card number is required").test({message:"Credit card number must be valid",name:"invalid_card_number",test:e=>d(e).isValid})}_isValidationErrorType(e){return"name"in e&&"ValidationError"!==e.name}}class te{constructor(e,t){this._parentOrigin=e,this._paymentOrigin=t}create(e,t,n={},r=[],i="",s=function(e){switch(e){case N.CardCode:return"CVC";case N.CardExpiry:return"Expiration";case N.CardName:return"Name on card";case N.CardNumber:return"Credit card number";case N.Note:return"Payment note";case N.Hidden:return"Hidden field"}}(t)){const a=z(t);return t===N.CardNumber?this._createNumberInput(t,e,n,r,i,s,a):t===N.CardExpiry?this._createExpiryInput(e,n,r,i,s,a):this._createInput(t,e,n,r,i,s,a)}normalizeParentOrigin(e){this._parentOrigin!==e&&(this._parentOrigin!==w(E(e)).origin&&e!==w(E(this._parentOrigin)).origin||(this._parentOrigin=e))}getParentOrigin(){return this._parentOrigin}_createExpiryInput(e,t,n,r,i="",s=""){return new Q(e,r,i,s,t,n,new S(this._parentOrigin),new x(this._parentOrigin,window.parent),new G(window.parent),new ee,this._createManualOrderPaymentHandler(),this._createStoredCardHandler(),new $)}_createNumberInput(e,t,n,r,i,s="",a=""){return new Y(e,t,i,s,a,n,r,new S(this._parentOrigin),new x(this._parentOrigin,window.parent),new G(window.parent),new ee,this._createManualOrderPaymentHandler(),this._createStoredCardHandler(),new W(t,[N.CardCode,N.CardExpiry,N.CardName],new G(window.parent)),new B)}_createInput(e,t,n,r,i,s="",a=""){return new J(e,t,i,s,a,n,r,new S(this._parentOrigin),new x(this._parentOrigin,window.parent),new G(window.parent),new ee,this._createManualOrderPaymentHandler(),this._createStoredCardHandler())}_createManualOrderPaymentHandler(){return new K(new G(window.parent),new ee,I(),new x(this._parentOrigin,window.parent),new U(e(),this._paymentOrigin))}_createStoredCardHandler(){return new Z(new G(window.parent),new ee,new x(this._parentOrigin,window.parent),new k(e()))}}class ne extends v{constructor(e){super(e||"Unable to proceed due to invalid configuration provided for the hosted payment form."),this.name="InvalidHostedFormConfigError",this.type="invalid_hosted_form_config"}}class re{constructor(e,t,n){this._factory=e,this._storage=t,this._eventListener=n}initialize(e,n){n&&this._storage.setNonce(n);const s=this._createFormContainer(e);return this._resetPageStyles(e),this._eventListener.listen(),t(this._eventListener,H.AttachRequested).pipe(r(({payload:e})=>{const{accessibilityLabel:t,fontUrls:n,placeholder:r,styles:i,origin:a,type:o}=e;a&&this._factory.normalizeParentOrigin(a);const d=this._factory.create(s,o,i,n,r,t);return d.attach(),d}),i(1)).toPromise()}_resetPageStyles(e){[document.querySelector("html"),document.querySelector("body"),document.getElementById(e)].forEach(e=>{e&&(e.style.height="100%",e.style.width="100%",e.style.overflow="hidden",e.style.padding="0",e.style.margin="0")})}_createFormContainer(e){const t=document.getElementById(e);if(!t)throw new ne("Unable to proceed because the provided container ID is not valid.");const n=document.createElement("form"),r=document.createElement("button");return n.noValidate=!0,n.style.height="100%",n.style.width="100%",r.style.display="none",t.appendChild(n),n.appendChild(r),n}}function ie(e){const{containerId:t,nonce:n,parentOrigin:r,paymentOrigin:i}=e;return new re(new te(r,i),I(),new S(r)).initialize(t,n)}const se=new x("*",window.parent);function ae(e){se.post({type:q.AttachFailed,payload:{error:e}})}export{ie as initializeHostedInput,ae as notifyInitializeError};
2
2
  //# sourceMappingURL=hosted-form-v2-iframe-content.js.map