@tonder.io/ionic-lite-sdk 0.0.59-beta.DEV1845.f4d343f → 0.0.59

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.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{get as e}from"lodash";import t from"skyflow-js";function n(e,t,n,o){return new(n||(n=Promise))((function(r,i){function s(e){try{d(o.next(e))}catch(e){i(e)}}function a(e){try{d(o.throw(e))}catch(e){i(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}d((o=o.apply(e,t||[])).next())}))}function o(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)}function r(e,t,n,o,r){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?r.call(e,n):r?r.value=n:t.set(e,n),n}function i(e,t,o){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${e}/api/v1/payments/business/${t}`,{headers:{Authorization:`Token ${t}`},signal:o});return yield n.json()}))}"function"==typeof SuppressedError&&SuppressedError;class s{constructor({code:e,body:t,name:n,message:o,stack:r}){this.code=e,this.body=t,this.name=n,this.message=o,this.stack=r}}const a=()=>({javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent}),d=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},l=e=>new s({code:(null==e?void 0:e.status)?e.status:e.code,body:null==e?void 0:e.body,name:e?"string"==typeof e?"catch":e.name:"Error",message:e?"string"==typeof e?e:e.message:"Error",stack:"string"==typeof e?void 0:e.stack}),c=(e,t=void 0)=>n(void 0,void 0,void 0,(function*(){let n,o,r="Error";e&&"json"in e&&(n=yield null==e?void 0:e.json()),e&&"status"in e&&(o=e.status.toString()),!n&&e&&"text"in e&&(r=yield e.text()),(null==n?void 0:n.detail)&&(r=n.detail);return new s({code:o,body:n,name:o,message:r,stack:t})}));function u(e,t){var n,o;let r=200;try{r=Number((null==t?void 0:t.code)||200)}catch(e){}const i={status:"error",code:r,message:"",detail:(null===(n=null==t?void 0:t.body)||void 0===n?void 0:n.detail)||(null===(o=null==t?void 0:t.body)||void 0===o?void 0:o.error)||t.body||"Ocurrio un error inesperado."};return Object.assign(Object.assign({},i),e)}class h{constructor({payload:e=null,apiKey:t,baseUrl:n,redirectOnComplete:o,tdsIframeId:r,tonderPayButtonId:i,callBack:s}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=n,this.apiKey=t,this.payload=e,this.tdsIframeId=r,this.tonderPayButtonId=i,this.redirectOnComplete=o,this.callBack=s}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,n,o,r,i;const s=null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===n?void 0:n.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const e=null===(i=null===(r=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}getUrlWithExpiration(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,n;if(null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===n?void 0:n.iframe)return new Promise(((e,t)=>{var n,o,r;const i=null===(r=null===(o=null===(n=this.payload)||void 0===n?void 0:n.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===r?void 0:r.iframe;if(i){this.saveVerifyTransactionUrl();const n=document.createElement("div");n.innerHTML=i,document.body.appendChild(n);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',n.appendChild(o);const r=document.getElementById("tdsMmethodTgtFrame");r?r.onload=()=>e(!0):(console.log("No redirection found"),t(!1))}else console.log("No redirection found"),t(!1)}))}getRedirectUrl(){var e,t,n;return null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===n?void 0:n.url}redirectToChallenge(){const e=this.getRedirectUrl();if(e)if(this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=e;else{const t=document.querySelector(`#${this.tdsIframeId}`);if(t){t.setAttribute("src",e),t.setAttribute("style","display: block");const o=this,r=e=>n(this,void 0,void 0,(function*(){const e=()=>{try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}t&&t.setAttribute("style","display: none"),o.callBack&&o.callBack(o.payload),t.removeEventListener("load",r)},i=t=>n(this,void 0,void 0,(function*(){const r=yield new Promise(((e,n)=>e(t)));if(r){if((e=>"Pending"!==(null==e?void 0:e.transaction_status))(r))return e();{const e=setTimeout((()=>n(this,void 0,void 0,(function*(){clearTimeout(e),yield i(o.requestTransactionStatus())}))),7e3)}}}));yield i(o.requestTransactionStatus())}));t.addEventListener("load",r)}else console.log("No iframe found")}else this.callBack&&this.callBack(this.payload)}requestTransactionStatus(){return n(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration(),t=e.startsWith("https://")?e:`${this.baseUrl}${e}`,n=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});if(200!==n.status)return console.error("La verificación de la transacción falló."),null;return yield n.json()}))}getURLParameters(){const e={},t=new URLSearchParams(window.location.search);for(const[n,o]of t)e[n]=o;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return n(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const n=document.createElement("input");n.type="hidden",n.name=e.creq,n.value=e.creq,t.appendChild(n);const o=document.createElement("input");o.type="hidden",o.name=e.term_url,o.value=e.TermUrl,t.appendChild(o),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return n(this,void 0,void 0,(function*(){const t=yield e.json();return"Pending"===t.status&&t.redirect_post_url?yield this.handle3dsChallenge(t):["Success","Authorized"].includes(t.status)?this.handleSuccessTransaction(t):(this.handleDeclinedTransaction(e),t)}))}verifyTransactionStatus(){return n(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration();if(e){const t=e.startsWith("https://")?e:`${this.baseUrl}${e}`;try{const e=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==e.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),e):yield this.handleTransactionResponse(e)}catch(e){console.error("Error al verificar la transacción:",e),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}const p=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function m(e,t,o){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/checkout-router/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(Object.assign(Object.assign({},r),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(i.status>=200&&i.status<=299)return yield i.json();{const e=yield i.json(),t=new Error("Failed to start checkout router");throw t.details=e,t}}catch(e){throw e}}))}function y(e,t,o=!0,r=null){return n(this,void 0,void 0,(function*(){let n=yield window.OpenPay;return n.setId(e),n.setApiKey(t),n.setSandboxMode(o),yield n.deviceData.setup({signal:r})}))}const v=Object.freeze({saveCardError:"Ha ocurrido un error guardando la tarjeta. Inténtalo nuevamente.",removeCardError:"Ha ocurrido un error eliminado la tarjeta. Inténtalo nuevamente.",getCardsError:"Ha ocurrido un error obteniendo las tarjetas del customer. Inténtalo nuevamente.",cardExist:"La tarjeta fue registrada previamente.",removedCard:"Card deleted successfully",errorCheckout:"No se ha podido procesar el pago",cardSaved:"Tarjeta registrada con éxito.",getPaymentMethodsError:"Ha ocurrido un error obteniendo las métodos de pago del customer. Inténtalo nuevamente.",getBusinessError:"Ha ocurrido un error obteniendo los datos del comercio. Inténtalo nuevamente.",secureTokenError:"Ha ocurrido un error obteniendo el token de seguridad."});var f,g,_,A,b,E,T,O,C,S,I,R,j;class N{constructor({mode:e="stage",customization:t,apiKey:n,apiKeyTonder:o,returnUrl:r,tdsIframeId:i,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d}){f.add(this),this.baseUrl="",this.cartTotal="0",this.secureToken="",this.customization={redirectOnComplete:!0},this.metadata={},this.order_reference=null,this.card={},this.currency="",g.set(this,void 0),_.set(this,void 0),this.apiKeyTonder=o||n||"",this.returnUrl=r,this.callBack=s,this.mode=e,this.customer={},this.baseUrl=a||p[this.mode]||p.stage,this.abortController=new AbortController,this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new h({apiKey:n,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:i,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=i}configureCheckout(e){"secureToken"in e&&o(this,f,"m",E).call(this,e.secureToken),o(this,f,"m",A).call(this,e)}verify3dsTransaction(){return n(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield o(this,f,"m",I).call(this,e);return this.process3ds.setPayload(t),this._handle3dsRedirect(t)}))}payment(e){return new Promise(((t,r)=>n(this,void 0,void 0,(function*(){try{o(this,f,"m",A).call(this,e);const n=yield this._checkout(e);this.process3ds.setPayload(n);if(yield this._handle3dsRedirect(n)){try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}this.callBack&&this.callBack(n),t(n)}}catch(e){r(e)}}))))}getSecureToken(e){return n(this,void 0,void 0,(function*(){try{return yield function(e,t,o=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${e}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:o});if(n.ok)return yield n.json();throw yield c(n)}catch(e){throw l(e)}}))}(this.baseUrl,e)}catch(e){throw u({message:v.secureTokenError},e)}}))}_initializeCheckout(){return n(this,void 0,void 0,(function*(){const e=yield this._fetchMerchantData();e&&e.mercado_pago&&e.mercado_pago.active&&function(){try{const e=document.createElement("script");e.src="https://www.mercadopago.com/v2/security.js",e.setAttribute("view",""),e.onload=()=>{},e.onerror=e=>{console.error("Error loading Mercado Pago script:",e)},document.head.appendChild(e)}catch(e){console.error("Error attempting to inject Mercado Pago script:",e)}}()}))}_checkout(e){return n(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(e){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(e=null){return n(this,void 0,void 0,(function*(){return o(this,_,"f")||r(this,_,yield function(e,t,o,r=null){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/customer/`,i={email:o.email,first_name:null==o?void 0:o.firstName,last_name:null==o?void 0:o.lastName,phone:null==o?void 0:o.phone},s=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},signal:r,body:JSON.stringify(i)});if(201===s.status)return yield s.json();throw new Error(`Error: ${s.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,this.customer,e),"f"),o(this,_,"f")}))}_handleCheckout({card:t,payment_method:r,customer:i,isSandbox:s,returnUrl:d}){return n(this,void 0,void 0,(function*(){const{openpay_keys:l,reference:c,business:u}=this.merchantData,h=Number(this.cartTotal);try{let p;!p&&l.merchant_id&&l.public_key&&!r&&(p=yield y(l.merchant_id,l.public_key,s,this.abortController.signal));const{id:v,auth_token:f}=i,_={business:this.apiKeyTonder,client:f,billing_address_id:null,shipping_address_id:null,amount:h,status:"A",reference:c,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata},A=yield function(e,t,o){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/orders/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(r)});if(201===i.status)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,_),b=(new Date).toISOString(),E={business_pk:u.pk,client_id:v,amount:h,date:b,order_id:A.id,customer_order_reference:this.order_reference?this.order_reference:c,items:this.cartItems,currency:this.currency,metadata:this.metadata},T=yield function(e,t,o){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/business/${o.business_pk}/payments/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(r)});if(i.status>=200&&i.status<=299)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,E),O=Object.assign(Object.assign(Object.assign({name:e(this.customer,"firstName",e(this.customer,"name","")),last_name:e(this.customer,"lastName",e(this.customer,"lastname","")),email_client:e(this.customer,"email",""),phone_number:e(this.customer,"phone",""),return_url:d||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:h,title_ship:"shipping",description:"transaction",device_session_id:p||null,token_id:"",order_id:A.id,business_id:u.pk,payment_id:T.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:a(),currency:this.currency},r?{payment_method:r}:{card:t}),{apm_config:o(this,g,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),C=yield m(this.baseUrl,this.apiKeyTonder,O);return C||!1}catch(e){throw console.log(e),e}}))}_fetchMerchantData(){return n(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(e){return this.merchantData}}))}_getCustomerCards(e,t){return n(this,void 0,void 0,(function*(){return yield function(e,t,o,r,i=null){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${r}/cards/`,s=yield fetch(n,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t},signal:i});if(s.ok)return yield s.json();if(401===s.status)return{user_id:0,cards:[]};throw yield c(s)}catch(e){throw l(e)}}))}(this.baseUrl,e,this.secureToken,t)}))}_saveCustomerCard(e,t,o){return n(this,void 0,void 0,(function*(){return yield function(e,t,o,r,i){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${r}/cards/`,s=yield fetch(n,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t},body:JSON.stringify(i)});if(s.ok)return yield s.json();throw yield c(s)}catch(e){throw l(e)}}))}(this.baseUrl,e,this.secureToken,t,o)}))}_removeCustomerCard(e,t,o){return n(this,void 0,void 0,(function*(){return yield function(e,t,o,r="",i){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${i}/cards/${r}`,s=yield fetch(n,{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t}});if(204===s.status)return v.removedCard;if(s.ok&&"json"in s)return yield s.json();throw yield c(s)}catch(e){throw l(e)}}))}(this.baseUrl,e,this.secureToken,o,t)}))}_fetchCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){return yield function(e,t,o={status:"active",pagesize:"10000"},r=null){return n(this,void 0,void 0,(function*(){try{const n=new URLSearchParams(o).toString(),i=yield fetch(`${e}/api/v1/payment_methods?${n}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:r});if(i.ok)return yield i.json();throw yield c(i)}catch(e){throw l(e)}}))}(this.baseUrl,this.apiKeyTonder)}))}_handle3dsRedirect(e){var t,o;return n(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(o=null===(t=null==e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((e=>{console.log("Error loading iframe:",e)}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}}function k(e,t,o=null){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${e}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${t}`},signal:o});if(n.ok){return(yield n.json()).token}throw new Error("Failed to retrieve bearer token")}))}g=new WeakMap,_=new WeakMap,f=new WeakSet,A=function(e){var t,n;!e||e&&0===Object.keys(e).length||(o(this,f,"m",b).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),o(this,f,"m",T).call(this,(null===(n=e.cart)||void 0===n?void 0:n.items)||[]),o(this,f,"m",O).call(this,e),o(this,f,"m",C).call(this,e),o(this,f,"m",S).call(this,e),o(this,f,"m",R).call(this,e))},b=function(e){e&&(this.customer=e)},E=function(e){this.secureToken=e},T=function(e){this.cartItems=e},O=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},C=function(e){this.currency=null==e?void 0:e.currency},S=function(e){this.card=null==e?void 0:e.card},I=function(e){var t,o,r;return n(this,void 0,void 0,(function*(){if("Hard"===(null===(t=null==e?void 0:e.decline)||void 0===t?void 0:t.error_type)||(null===(o=null==e?void 0:e.checkout)||void 0===o?void 0:o.is_route_finished)||(null==e?void 0:e.is_route_finished)||["Pending"].includes(null==e?void 0:e.transaction_status))return e;if(["Success","Authorized"].includes(null==e?void 0:e.transaction_status))return e;if(e){const t={checkout_id:(null===(r=e.checkout)||void 0===r?void 0:r.id)||(null==e?void 0:e.checkout_id)};try{return yield m(this.baseUrl,this.apiKeyTonder,t)}catch(e){}return e}}))},R=function(e){r(this,g,null==e?void 0:e.apm_config,"f")},function(e){e.CARD_NUMBER="card_number",e.CVV="cvv",e.EXPIRATION_MONTH="expiration_month",e.EXPIRATION_YEAR="expiration_year",e.CARDHOLDER_NAME="cardholder_name"}(j||(j={}));const M={type:t.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},w=RegExp("^(?!s*$).+"),U={type:t.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:w,error:"El campo es requerido"}},P="Titular de la tarjeta",D="Número de tarjeta",L="CVC/CVV",x="Mes",B="Año",$="Fecha de expiración",K="Nombre como aparece en la tarjeta",F="1234 1234 1234 1234",V="3-4 dígitos",z="MM",X="AA",Y={base:{border:"1px solid #e0e0e0",padding:"10px 7px",borderRadius:"5px",color:"#1d1d1d",marginTop:"2px",backgroundColor:"white",fontFamily:'"Inter", sans-serif',fontSize:"16px","&::placeholder":{color:"#ccc"}},complete:{color:"#4caf50"},invalid:{border:"1px solid #f44336"},empty:{},focus:{},global:{"@import":'url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;700&display=swap")'}},J={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif'}},W={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function H({baseUrl:e,apiKey:o,vault_id:r,vault_url:i,data:s}){return n(this,void 0,void 0,(function*(){const a=t.init({vaultID:r,vaultURL:i,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield k(e,o)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}}).container(t.ContainerType.COLLECT),d=yield function(e,o){return n(this,void 0,void 0,(function*(){const r=yield function(e,o){return n(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(e).map((e=>n(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:e,type:t.ElementType.INPUT_FIELD}),key:e}})))))}))}(e,o);return r?r.map((t=>new Promise((n=>{var o;const r=document.createElement("div");r.hidden=!0,r.id=`id-${t.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(r),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const o=e[t.key];return t.element.setValue(o),n(t.element.isMounted())}}),120)}),120)})))):[]}))}(s,a);if((yield Promise.all(d)).some((e=>!e)))throw l(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const e=yield a.collect();if(e)return e.records[0].fields;throw l(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(e){throw l(e)}}))}function G(e){const{element:n,fieldMessage:o="",errorStyles:r={},requiredMessage:i="Campo requerido",invalidMessage:s="Campo no válido",events:a}=e;"on"in n&&(n.on(t.EventName.CHANGE,(e=>{Z({eventName:"onChange",data:e,events:a}),q({element:n,errorStyles:r,color:"transparent"})})),n.on(t.EventName.BLUR,(e=>{if(Z({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?i:""!=o?`El campo ${o} no es válido`:s;n.setError(t)}q({element:n,errorStyles:r})})),n.on(t.EventName.FOCUS,(e=>{Z({eventName:"onFocus",data:e,events:a}),q({element:n,errorStyles:r,color:"transparent"}),n.resetError()})))}function q(e){const{element:t,errorStyles:n={},color:o=""}=e;Object.keys(n).length>0&&t.update({errorTextStyles:Object.assign(Object.assign({},n),{base:Object.assign(Object.assign({},n.base&&Object.assign({},n.base)),""!=o&&{color:o})})})}const Z=t=>{const{eventName:n,data:o,events:r}=t;if(r&&n in r){const t=r[n];"function"==typeof t&&t({elementType:e(o,"elementType",""),isEmpty:e(o,"isEmpty",""),isFocused:e(o,"isFocused",""),isValid:e(o,"isValid","")})}},Q=Object.freeze({SORIANA:"SORIANA",OXXO:"OXXO",OXXOPAY:"OXXOPAY",SPEI:"SPEI",CODI:"CODI",MERCADOPAGO:"MERCADOPAGO",PAYPAL:"PAYPAL",COMERCIALMEXICANA:"COMERCIALMEXICANA",BANCOMER:"BANCOMER",WALMART:"WALMART",BODEGA:"BODEGA",SAMSCLUB:"SAMSCLUB",SUPERAMA:"SUPERAMA",CALIMAX:"CALIMAX",EXTRA:"EXTRA",CIRCULOK:"CIRCULOK",SEVEN11:"7ELEVEN",TELECOMM:"TELECOMM",BANORTE:"BANORTE",BENAVIDES:"BENAVIDES",DELAHORRO:"DELAHORRO",ELASTURIANO:"ELASTURIANO",WALDOS:"WALDOS",ALSUPER:"ALSUPER",KIOSKO:"KIOSKO",STAMARIA:"STAMARIA",LAMASBARATA:"LAMASBARATA",FARMROMA:"FARMROMA",FARMUNION:"FARMUNION",FARMATODO:"FARMATODO",SFDEASIS:"SFDEASIS",FARM911:"FARM911",FARMECONOMICAS:"FARMECONOMICAS",FARMMEDICITY:"FARMMEDICITY",RIANXEIRA:"RIANXEIRA",WESTERNUNION:"WESTERNUNION",ZONAPAGO:"ZONAPAGO",CAJALOSANDES:"CAJALOSANDES",CAJAPAITA:"CAJAPAITA",CAJASANTA:"CAJASANTA",CAJASULLANA:"CAJASULLANA",CAJATRUJILLO:"CAJATRUJILLO",EDPYME:"EDPYME",KASNET:"KASNET",NORANDINO:"NORANDINO",QAPAQ:"QAPAQ",RAIZ:"RAIZ",PAYSER:"PAYSER",WUNION:"WUNION",BANCOCONTINENTAL:"BANCOCONTINENTAL",GMONEY:"GMONEY",GOPAY:"GOPAY",WU:"WU",PUNTOSHEY:"PUNTOSHEY",AMPM:"AMPM",JUMBOMARKET:"JUMBOMARKET",SMELPUEBLO:"SMELPUEBLO",BAM:"BAM",REFACIL:"REFACIL",ACYVALORES:"ACYVALORES"}),ee={[Q.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[Q.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[Q.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[Q.MERCADOPAGO]:{label:"Mercado Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/mercadopago.png"},[Q.OXXOPAY]:{label:"Oxxo Pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxopay.png"},[Q.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[Q.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[Q.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[Q.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[Q.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[Q.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[Q.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[Q.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[Q.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[Q.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[Q.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[Q.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[Q.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[Q.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[Q.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[Q.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[Q.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[Q.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[Q.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[Q.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[Q.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[Q.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[Q.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[Q.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[Q.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[Q.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[Q.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},te=e=>{const t=e.toUpperCase().trim().replace(/\s+/g,"");return ee[t]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class ne extends N{constructor({apiKey:e,mode:t,returnUrl:n,callBack:o,apiKeyTonder:r,baseUrlTonder:i,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:n,callBack:o,apiKeyTonder:r,baseUrlTonder:i,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe"}),this.activeAPMs=[],this.collectContainer=null,this.skyflowInstance=null,this.events=d||{}}injectCheckout(){return n(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),t=yield this._getCustomerCards(e,this.merchantData.business.pk);return Object.assign(Object.assign({},t),{cards:t.cards.map((e=>{return Object.assign(Object.assign({},e),{icon:(t=e.fields.card_scheme,"Visa"===t?"https://d35a75syrgujp0.cloudfront.net/cards/visa.png":"Mastercard"===t?"https://d35a75syrgujp0.cloudfront.net/cards/mastercard.png":"American Express"===t?"https://d35a75syrgujp0.cloudfront.net/cards/american_express.png":"https://d35a75syrgujp0.cloudfront.net/cards/default_card.png")});var t}))})}catch(e){throw u({message:v.getCardsError},e)}}))}saveCustomerCard(e){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{vault_id:n,vault_url:o,business:r}=this.merchantData,i=yield H({vault_id:n,vault_url:o,data:Object.assign(Object.assign({},e),{card_number:e.card_number.replace(/\s+/g,""),expiration_month:e.expiration_month.replace(/\s+/g,""),expiration_year:e.expiration_year.replace(/\s+/g,""),cvv:e.cvv.replace(/\s+/g,""),cardholder_name:e.cardholder_name.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder});return yield this._saveCustomerCard(t,null==r?void 0:r.pk,i)}catch(e){throw u({message:v.saveCardError},e)}}))}removeCustomerCard(e){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{business:n}=this.merchantData;return yield this._removeCustomerCard(t,null==n?void 0:n.pk,e)}catch(e){throw u({message:v.removeCardError},e)}}))}getCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){try{const e=yield this._fetchCustomerPaymentMethods();return(e&&"results"in e&&e.results.length>0?e.results:[]).filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},te(e.payment_method)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw u({message:v.getPaymentMethodsError},e)}}))}mountCardFields(e){return n(this,void 0,void 0,(function*(){yield this.createSkyflowInstance(),this.collectContainer=yield function(e){var o,r,i,s,a,d,l,c,u,h,p,m,y,v,f,g,_;return n(this,void 0,void 0,(function*(){const{skyflowInstance:n,data:A,customization:b,events:E}=e,T=n.container(t.ContainerType.COLLECT),O=[],C={[j.CVV]:t.ElementType.CVV,[j.CARD_NUMBER]:t.ElementType.CARD_NUMBER,[j.EXPIRATION_MONTH]:t.ElementType.EXPIRATION_MONTH,[j.EXPIRATION_YEAR]:t.ElementType.EXPIRATION_YEAR,[j.CARDHOLDER_NAME]:t.ElementType.CARDHOLDER_NAME},S={[j.CVV]:[U],[j.CARD_NUMBER]:[U],[j.EXPIRATION_MONTH]:[U],[j.EXPIRATION_YEAR]:[U],[j.CARDHOLDER_NAME]:[M,U]},I={errorStyles:(null===(r=null===(o=null==b?void 0:b.styles)||void 0===o?void 0:o.cardForm)||void 0===r?void 0:r.errorStyles)||W,inputStyles:(null===(s=null===(i=null==b?void 0:b.styles)||void 0===i?void 0:i.cardForm)||void 0===s?void 0:s.inputStyles)||Y,labelStyles:(null===(d=null===(a=null==b?void 0:b.styles)||void 0===a?void 0:a.cardForm)||void 0===d?void 0:d.labelStyles)||J},R={name:(null===(l=null==b?void 0:b.labels)||void 0===l?void 0:l.name)||P,card_number:(null===(c=null==b?void 0:b.labels)||void 0===c?void 0:c.card_number)||D,cvv:(null===(u=null==b?void 0:b.labels)||void 0===u?void 0:u.cvv)||L,expiration_date:(null===(h=null==b?void 0:b.labels)||void 0===h?void 0:h.expiry_date)||$,expiration_month:(null===(p=null==b?void 0:b.labels)||void 0===p?void 0:p.expiration_month)||x,expiration_year:(null===(m=null==b?void 0:b.labels)||void 0===m?void 0:m.expiration_year)||B},N={name:(null===(y=null==b?void 0:b.placeholders)||void 0===y?void 0:y.name)||K,card_number:(null===(v=null==b?void 0:b.placeholders)||void 0===v?void 0:v.card_number)||F,cvv:(null===(f=null==b?void 0:b.placeholders)||void 0===f?void 0:f.cvv)||V,expiration_month:(null===(g=null==b?void 0:b.placeholders)||void 0===g?void 0:g.expiration_month)||z,expiration_year:(null===(_=null==b?void 0:b.placeholders)||void 0===_?void 0:_.expiration_year)||X},k={[j.CVV]:null==E?void 0:E.cvvEvents,[j.CARD_NUMBER]:null==E?void 0:E.cardNumberEvents,[j.EXPIRATION_MONTH]:null==E?void 0:E.monthEvents,[j.EXPIRATION_YEAR]:null==E?void 0:E.yearEvents,[j.CARDHOLDER_NAME]:null==E?void 0:E.cardHolderEvents};if("fields"in A&&Array.isArray(A.fields))if(A.fields.length>0&&"string"==typeof A.fields[0])for(const e of A.fields){const t=T.create(Object.assign(Object.assign(Object.assign({table:"cards",column:e,type:C[e],validations:S[e]},I),{label:R[e],placeholder:N[e]}),A.card_id?{skyflowID:A.card_id}:{}));G({element:t,errorStyles:I.errorStyles,fieldMessage:[j.CVV,j.EXPIRATION_MONTH,j.EXPIRATION_YEAR].includes(e)?"":R[e],events:k[e]});const n=`#collect_${String(e)}`+(A.card_id?`_${A.card_id}`:"");t.mount(n),O.push({element:t,containerId:n})}else for(const e of A.fields){const t=e.field,n=T.create(Object.assign(Object.assign(Object.assign({table:"cards",column:t,type:C[t],validations:S[t]},I),{label:R[t],placeholder:N[t]}),A.card_id?{skyflowID:A.card_id}:{})),o=e.container_id||`#collect_${String(t)}`+(A.card_id?`_${A.card_id}`:"");n.mount(o),O.push({element:n,containerId:o})}return{elements:O.map((e=>e.element)),container:T}}))}({skyflowInstance:this.skyflowInstance,data:e,customization:this.customization,events:this.events})}))}getBusiness(){return n(this,void 0,void 0,(function*(){try{return yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw u({message:v.getBusinessError},e)}}))}createSkyflowInstance(){return n(this,void 0,void 0,(function*(){if(this.skyflowInstance)return this.skyflowInstance;yield this._fetchMerchantData();const{vault_id:e,vault_url:o}=this.merchantData;this.skyflowInstance=yield function({baseUrl:e,apiKey:o,vault_id:r,vault_url:i}){return n(this,void 0,void 0,(function*(){return t.init({vaultID:r,vaultURL:i,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield k(e,o)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}})}))}({vault_id:e,vault_url:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}getOpenpayDeviceSessionID(e,t,o){return n(this,void 0,void 0,(function*(){try{return yield y(e,t,o)}catch(e){throw l(e)}}))}getSkyflowTokens({vault_id:e,vault_url:t,data:o}){return n(this,void 0,void 0,(function*(){return yield H({vault_id:e,vault_url:t,data:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:t,isSandbox:o,returnUrl:r}){var i;return n(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const n=yield this._getCustomer(this.abortController.signal),{vault_id:s,vault_url:a}=this.merchantData;let d;if(!t)if("string"==typeof e){const t=null===(i=this.collectContainer)||void 0===i?void 0:i.container;t&&(yield t.collect()),d={skyflow_id:e}}else d=yield H({vault_id:s,vault_url:a,data:Object.assign(Object.assign({},e),{card_number:e.card_number.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder});return yield this._handleCheckout({card:d,payment_method:t,customer:n,isSandbox:o,returnUrl:r})}))}customerRegister(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/customer/`,n={email:e},o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield c(o)}catch(e){throw l(e)}}))}createOrder(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/orders/`,n=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield c(o)}catch(e){throw l(e)}}))}createPayment(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/business/${e.business_pk}/payments/`,n=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield c(o)}catch(e){throw l(e)}}))}startCheckoutRouter(e){return n(this,void 0,void 0,(function*(){const t=yield m(this.baseUrl,this.apiKeyTonder,e);if(yield this.init3DSRedirect(t))return t}))}init3DSRedirect(e){return n(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this._handle3dsRedirect(e)}))}startCheckoutRouterFull(e){return n(this,void 0,void 0,(function*(){try{const{order:t,total:n,customer:o,skyflowTokens:r,return_url:i,isSandbox:d,metadata:l,currency:c,payment_method:u}=e,h=yield this._fetchMerchantData(),p=yield this.customerRegister(o.email);if(!(p&&"auth_token"in p&&h&&"reference"in h))throw new s({code:"500",body:h,name:"Keys error",message:"Merchant or customer reposne errors"});{const e={business:this.apiKeyTonder,client:p.auth_token,billing_address_id:null,shipping_address_id:null,amount:n,reference:h.reference,is_oneclick:!0,items:t.items},v=yield this.createOrder(e),f=(new Date).toISOString();if(!("id"in v&&"id"in p&&"business"in h))throw new s({code:"500",body:v,name:"Keys error",message:"Order response errors"});{const e={business_pk:h.business.pk,amount:n,date:f,order_id:v.id,client_id:p.id},t=yield this.createPayment(e);let s;const{openpay_keys:g,business:_}=h;g.merchant_id&&g.public_key&&(s=yield y(g.merchant_id,g.public_key,d));const A=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:i,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:n,title_ship:"shipping",description:"transaction",device_session_id:s||null,token_id:"",order_id:"id"in v&&v.id,business_id:_.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:l,browser_info:a(),currency:c},u?{payment_method:u}:{card:r}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),b=yield m(this.baseUrl,this.apiKeyTonder,A);if(yield this.init3DSRedirect(b))return b}}}catch(e){throw l(e)}}))}registerCustomerCard(e,t,o){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${d(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-token":t,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},o))});if(n.ok)return yield n.json();throw yield c(n)}catch(e){throw l(e)}}))}deleteCustomerCard(e,t=""){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${d(this.merchantData)}/cards/${t}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(n.ok)return!0;throw yield c(n)}catch(e){throw l(e)}}))}getActiveAPMs(){return n(this,void 0,void 0,(function*(){try{const e=yield function(e,t,o="?status=active&page_size=10000&country=México",r=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${e}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:r});if(n.ok)return yield n.json();throw yield c(n)}catch(e){throw l(e)}}))}(this.baseUrl,this.apiKeyTonder),t=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=t.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},te(e.payment_method)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}function oe(e){return/^\d{12,19}$/.test(e)&&de(e)}function re(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function ie(e){return/^\d{3,4}$/.test(e)}function se(e){return/^(0[1-9]|1[0-2])$/.test(e)}function ae(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const de=e=>{const t=`${e}`.split("").reverse().map((e=>Number.parseInt(e))),n=t.shift();let o=t.reduce(((e,t,n)=>n%2!=0?e+t:e+((t*=2)>9?t-9:t)),0);return o+=n,o%10==0};export{N as BaseInlineCheckout,ne as LiteCheckout,ie as validateCVV,oe as validateCardNumber,re as validateCardholderName,se as validateExpirationMonth,ae as validateExpirationYear};
1
+ import{get as e}from"lodash";import t from"skyflow-js";function n(e,t,n,o){return new(n||(n=Promise))((function(r,i){function s(e){try{d(o.next(e))}catch(e){i(e)}}function a(e){try{d(o.throw(e))}catch(e){i(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}d((o=o.apply(e,t||[])).next())}))}function o(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)}function r(e,t,n,o,r){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?r.call(e,n):r?r.value=n:t.set(e,n),n}function i(e,t,o){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${e}/api/v1/payments/business/${t}`,{headers:{Authorization:`Token ${t}`},signal:o});return yield n.json()}))}"function"==typeof SuppressedError&&SuppressedError;class s{constructor({code:e,body:t,name:n,message:o,stack:r}){this.code=e,this.body=t,this.name=n,this.message=o,this.stack=r}}const a=()=>({javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent}),d=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},l=e=>new s({code:(null==e?void 0:e.status)?e.status:e.code,body:null==e?void 0:e.body,name:e?"string"==typeof e?"catch":e.name:"Error",message:e?"string"==typeof e?e:e.message:"Error",stack:"string"==typeof e?void 0:e.stack}),c=(e,t=void 0)=>n(void 0,void 0,void 0,(function*(){let n,o,r="Error";e&&"json"in e&&(n=yield null==e?void 0:e.json()),e&&"status"in e&&(o=e.status.toString()),!n&&e&&"text"in e&&(r=yield e.text()),(null==n?void 0:n.detail)&&(r=n.detail);return new s({code:o,body:n,name:o,message:r,stack:t})}));function u(e,t){var n,o;let r=200;try{r=Number((null==t?void 0:t.code)||200)}catch(e){}const i={status:"error",code:r,message:"",detail:(null===(n=null==t?void 0:t.body)||void 0===n?void 0:n.detail)||(null===(o=null==t?void 0:t.body)||void 0===o?void 0:o.error)||t.body||"Ocurrio un error inesperado."};return Object.assign(Object.assign({},i),e)}class h{constructor({payload:e=null,apiKey:t,baseUrl:n,redirectOnComplete:o,tdsIframeId:r,tonderPayButtonId:i,callBack:s}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=n,this.apiKey=t,this.payload=e,this.tdsIframeId=r,this.tonderPayButtonId=i,this.redirectOnComplete=o,this.callBack=s}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,n,o,r,i;const s=null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===n?void 0:n.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const e=null===(i=null===(r=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}getUrlWithExpiration(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,n;if(null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===n?void 0:n.iframe)return new Promise(((e,t)=>{var n,o,r;const i=null===(r=null===(o=null===(n=this.payload)||void 0===n?void 0:n.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===r?void 0:r.iframe;if(i){this.saveVerifyTransactionUrl();const n=document.createElement("div");n.innerHTML=i,document.body.appendChild(n);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',n.appendChild(o);const r=document.getElementById("tdsMmethodTgtFrame");r?r.onload=()=>e(!0):(console.log("No redirection found"),t(!1))}else console.log("No redirection found"),t(!1)}))}getRedirectUrl(){var e,t,n;return null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===n?void 0:n.url}redirectToChallenge(){const e=this.getRedirectUrl();if(e)if(this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=e;else{const t=document.querySelector(`#${this.tdsIframeId}`);if(t){t.setAttribute("src",e),t.setAttribute("style","display: block");const o=this,r=e=>n(this,void 0,void 0,(function*(){const e=()=>{try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}t&&t.setAttribute("style","display: none"),o.callBack&&o.callBack(o.payload),t.removeEventListener("load",r)},i=t=>n(this,void 0,void 0,(function*(){const r=yield new Promise(((e,n)=>e(t)));if(r){if((e=>"Pending"!==(null==e?void 0:e.transaction_status))(r))return e();{const e=setTimeout((()=>n(this,void 0,void 0,(function*(){clearTimeout(e),yield i(o.requestTransactionStatus())}))),7e3)}}}));yield i(o.requestTransactionStatus())}));t.addEventListener("load",r)}else console.log("No iframe found")}else this.callBack&&this.callBack(this.payload)}requestTransactionStatus(){return n(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration(),t=e.startsWith("https://")?e:`${this.baseUrl}${e}`,n=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});if(200!==n.status)return console.error("La verificación de la transacción falló."),null;return yield n.json()}))}getURLParameters(){const e={},t=new URLSearchParams(window.location.search);for(const[n,o]of t)e[n]=o;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return n(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const n=document.createElement("input");n.type="hidden",n.name=e.creq,n.value=e.creq,t.appendChild(n);const o=document.createElement("input");o.type="hidden",o.name=e.term_url,o.value=e.TermUrl,t.appendChild(o),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return n(this,void 0,void 0,(function*(){const t=yield e.json();return"Pending"===t.status&&t.redirect_post_url?yield this.handle3dsChallenge(t):["Success","Authorized"].includes(t.status)?this.handleSuccessTransaction(t):(this.handleDeclinedTransaction(e),t)}))}verifyTransactionStatus(){return n(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration();if(e){const t=e.startsWith("https://")?e:`${this.baseUrl}${e}`;try{const e=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==e.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),e):yield this.handleTransactionResponse(e)}catch(e){console.error("Error al verificar la transacción:",e),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}const p=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function m(e,t,o){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/checkout-router/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(Object.assign(Object.assign({},r),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(i.status>=200&&i.status<=299)return yield i.json();{const e=yield i.json(),t=new Error("Failed to start checkout router");throw t.details=e,t}}catch(e){throw e}}))}function y(e,t,o=!0,r=null){return n(this,void 0,void 0,(function*(){let n=yield window.OpenPay;return n.setId(e),n.setApiKey(t),n.setSandboxMode(o),yield n.deviceData.setup({signal:r})}))}const v=Object.freeze({saveCardError:"Ha ocurrido un error guardando la tarjeta. Inténtalo nuevamente.",removeCardError:"Ha ocurrido un error eliminado la tarjeta. Inténtalo nuevamente.",getCardsError:"Ha ocurrido un error obteniendo las tarjetas del customer. Inténtalo nuevamente.",cardExist:"La tarjeta fue registrada previamente.",removedCard:"Card deleted successfully",errorCheckout:"No se ha podido procesar el pago",cardSaved:"Tarjeta registrada con éxito.",getPaymentMethodsError:"Ha ocurrido un error obteniendo las métodos de pago del customer. Inténtalo nuevamente.",getBusinessError:"Ha ocurrido un error obteniendo los datos del comercio. Inténtalo nuevamente.",secureTokenError:"Ha ocurrido un error obteniendo el token de seguridad."});var f,g,_,A,b,E,T,O,C,S,I,R,j;class N{constructor({mode:e="stage",customization:t,apiKey:n,apiKeyTonder:o,returnUrl:r,tdsIframeId:i,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d}){f.add(this),this.baseUrl="",this.cartTotal="0",this.secureToken="",this.customization={redirectOnComplete:!0},this.metadata={},this.order_reference=null,this.card={},this.currency="",g.set(this,void 0),_.set(this,void 0),this.apiKeyTonder=o||n||"",this.returnUrl=r,this.callBack=s,this.mode=e,this.customer={},this.baseUrl=a||p[this.mode]||p.stage,this.abortController=new AbortController,this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new h({apiKey:n,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:i,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=i}configureCheckout(e){"secureToken"in e&&o(this,f,"m",E).call(this,e.secureToken),o(this,f,"m",A).call(this,e)}verify3dsTransaction(){return n(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield o(this,f,"m",I).call(this,e);return this.process3ds.setPayload(t),this._handle3dsRedirect(t)}))}payment(e){return new Promise(((t,r)=>n(this,void 0,void 0,(function*(){try{o(this,f,"m",A).call(this,e);const n=yield this._checkout(e);this.process3ds.setPayload(n);if(yield this._handle3dsRedirect(n)){try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}this.callBack&&this.callBack(n),t(n)}}catch(e){r(e)}}))))}getSecureToken(e){return n(this,void 0,void 0,(function*(){try{return yield function(e,t,o=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${e}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:o});if(n.ok)return yield n.json();throw yield c(n)}catch(e){throw l(e)}}))}(this.baseUrl,e)}catch(e){throw u({message:v.secureTokenError},e)}}))}_initializeCheckout(){return n(this,void 0,void 0,(function*(){const e=yield this._fetchMerchantData();e&&e.mercado_pago&&e.mercado_pago.active&&function(){try{const e=document.createElement("script");e.src="https://www.mercadopago.com/v2/security.js",e.setAttribute("view",""),e.onload=()=>{},e.onerror=e=>{console.error("Error loading Mercado Pago script:",e)},document.head.appendChild(e)}catch(e){console.error("Error attempting to inject Mercado Pago script:",e)}}()}))}_checkout(e){return n(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(e){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(e=null){return n(this,void 0,void 0,(function*(){return o(this,_,"f")||r(this,_,yield function(e,t,o,r=null){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/customer/`,i={email:o.email,first_name:null==o?void 0:o.firstName,last_name:null==o?void 0:o.lastName,phone:null==o?void 0:o.phone},s=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},signal:r,body:JSON.stringify(i)});if(201===s.status)return yield s.json();throw new Error(`Error: ${s.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,this.customer,e),"f"),o(this,_,"f")}))}_handleCheckout({card:t,payment_method:r,customer:i,isSandbox:s,returnUrl:d}){return n(this,void 0,void 0,(function*(){const{openpay_keys:l,reference:c,business:u}=this.merchantData,h=Number(this.cartTotal);try{let p;!p&&l.merchant_id&&l.public_key&&!r&&(p=yield y(l.merchant_id,l.public_key,s,this.abortController.signal));const{id:v,auth_token:f}=i,_={business:this.apiKeyTonder,client:f,billing_address_id:null,shipping_address_id:null,amount:h,status:"A",reference:c,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata},A=yield function(e,t,o){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/orders/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(r)});if(201===i.status)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,_),b=(new Date).toISOString(),E={business_pk:u.pk,client_id:v,amount:h,date:b,order_id:A.id,customer_order_reference:this.order_reference?this.order_reference:c,items:this.cartItems,currency:this.currency,metadata:this.metadata},T=yield function(e,t,o){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/business/${o.business_pk}/payments/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(r)});if(i.status>=200&&i.status<=299)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,E),O=Object.assign(Object.assign(Object.assign({name:e(this.customer,"firstName",e(this.customer,"name","")),last_name:e(this.customer,"lastName",e(this.customer,"lastname","")),email_client:e(this.customer,"email",""),phone_number:e(this.customer,"phone",""),return_url:d||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:h,title_ship:"shipping",description:"transaction",device_session_id:p||null,token_id:"",order_id:A.id,business_id:u.pk,payment_id:T.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:a(),currency:this.currency},r?{payment_method:r}:{card:t}),{apm_config:o(this,g,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),C=yield m(this.baseUrl,this.apiKeyTonder,O);return C||!1}catch(e){throw console.log(e),e}}))}_fetchMerchantData(){return n(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(e){return this.merchantData}}))}_getCustomerCards(e,t){return n(this,void 0,void 0,(function*(){return yield function(e,t,o,r,i=null){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${r}/cards/`,s=yield fetch(n,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t},signal:i});if(s.ok)return yield s.json();if(401===s.status)return{user_id:0,cards:[]};throw yield c(s)}catch(e){throw l(e)}}))}(this.baseUrl,e,this.secureToken,t)}))}_saveCustomerCard(e,t,o){return n(this,void 0,void 0,(function*(){return yield function(e,t,o,r,i){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${r}/cards/`,s=yield fetch(n,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t},body:JSON.stringify(i)});if(s.ok)return yield s.json();throw yield c(s)}catch(e){throw l(e)}}))}(this.baseUrl,e,this.secureToken,t,o)}))}_removeCustomerCard(e,t,o){return n(this,void 0,void 0,(function*(){return yield function(e,t,o,r="",i){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${i}/cards/${r}`,s=yield fetch(n,{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t}});if(204===s.status)return v.removedCard;if(s.ok&&"json"in s)return yield s.json();throw yield c(s)}catch(e){throw l(e)}}))}(this.baseUrl,e,this.secureToken,o,t)}))}_fetchCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){return yield function(e,t,o={status:"active",pagesize:"10000"},r=null){return n(this,void 0,void 0,(function*(){try{const n=new URLSearchParams(o).toString(),i=yield fetch(`${e}/api/v1/payment_methods?${n}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:r});if(i.ok)return yield i.json();throw yield c(i)}catch(e){throw l(e)}}))}(this.baseUrl,this.apiKeyTonder)}))}_handle3dsRedirect(e){var t,o;return n(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(o=null===(t=null==e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((e=>{console.log("Error loading iframe:",e)}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}}function k(e,t,o=null){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${e}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${t}`},signal:o});if(n.ok){return(yield n.json()).token}throw new Error("Failed to retrieve bearer token")}))}g=new WeakMap,_=new WeakMap,f=new WeakSet,A=function(e){var t,n;!e||e&&0===Object.keys(e).length||(o(this,f,"m",b).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),o(this,f,"m",T).call(this,(null===(n=e.cart)||void 0===n?void 0:n.items)||[]),o(this,f,"m",O).call(this,e),o(this,f,"m",C).call(this,e),o(this,f,"m",S).call(this,e),o(this,f,"m",R).call(this,e))},b=function(e){e&&(this.customer=e)},E=function(e){this.secureToken=e},T=function(e){this.cartItems=e},O=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},C=function(e){this.currency=null==e?void 0:e.currency},S=function(e){this.card=null==e?void 0:e.card},I=function(e){var t,o,r;return n(this,void 0,void 0,(function*(){if("Hard"===(null===(t=null==e?void 0:e.decline)||void 0===t?void 0:t.error_type)||(null===(o=null==e?void 0:e.checkout)||void 0===o?void 0:o.is_route_finished)||(null==e?void 0:e.is_route_finished)||["Pending"].includes(null==e?void 0:e.transaction_status))return e;if(["Success","Authorized"].includes(null==e?void 0:e.transaction_status))return e;if(e){const t={checkout_id:(null===(r=e.checkout)||void 0===r?void 0:r.id)||(null==e?void 0:e.checkout_id)};try{return yield m(this.baseUrl,this.apiKeyTonder,t)}catch(e){}return e}}))},R=function(e){r(this,g,null==e?void 0:e.apm_config,"f")},function(e){e.CARD_NUMBER="card_number",e.CVV="cvv",e.EXPIRATION_MONTH="expiration_month",e.EXPIRATION_YEAR="expiration_year",e.CARDHOLDER_NAME="cardholder_name"}(j||(j={}));const w={type:t.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},M=RegExp("^(?!s*$).+"),U={type:t.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:M,error:"El campo es requerido"}},P="Titular de la tarjeta",D="Número de tarjeta",L="CVC/CVV",x="Mes",$="Año",B="Fecha de expiración",K="Nombre como aparece en la tarjeta",F="1234 1234 1234 1234",V="3-4 dígitos",z="MM",X="AA",Y={base:{border:"1px solid #e0e0e0",padding:"10px 7px",borderRadius:"5px",color:"#1d1d1d",marginTop:"2px",backgroundColor:"white",fontFamily:'"Inter", sans-serif',fontSize:"16px","&::placeholder":{color:"#ccc"}},complete:{color:"#4caf50"},invalid:{border:"1px solid #f44336"},empty:{},focus:{},global:{"@import":'url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;700&display=swap")'}},J={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif'}},W={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function H({baseUrl:e,apiKey:o,vault_id:r,vault_url:i,data:s}){return n(this,void 0,void 0,(function*(){const a=t.init({vaultID:r,vaultURL:i,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield k(e,o)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}}).container(t.ContainerType.COLLECT),d=yield function(e,o){return n(this,void 0,void 0,(function*(){const r=yield function(e,o){return n(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(e).map((e=>n(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:e,type:t.ElementType.INPUT_FIELD}),key:e}})))))}))}(e,o);return r?r.map((t=>new Promise((n=>{var o;const r=document.createElement("div");r.hidden=!0,r.id=`id-${t.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(r),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const o=e[t.key];return t.element.setValue(o),n(t.element.isMounted())}}),120)}),120)})))):[]}))}(s,a);if((yield Promise.all(d)).some((e=>!e)))throw l(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const e=yield a.collect();if(e)return e.records[0].fields;throw l(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(e){throw l(e)}}))}function G(e){const{element:n,fieldMessage:o="",errorStyles:r={},requiredMessage:i="Campo requerido",invalidMessage:s="Campo no válido",events:a}=e;"on"in n&&(n.on(t.EventName.CHANGE,(e=>{Z({eventName:"onChange",data:e,events:a}),q({element:n,errorStyles:r,color:"transparent"})})),n.on(t.EventName.BLUR,(e=>{if(Z({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?i:""!=o?`El campo ${o} no es válido`:s;n.setError(t)}q({element:n,errorStyles:r})})),n.on(t.EventName.FOCUS,(e=>{Z({eventName:"onFocus",data:e,events:a}),q({element:n,errorStyles:r,color:"transparent"}),n.resetError()})))}function q(e){const{element:t,errorStyles:n={},color:o=""}=e;Object.keys(n).length>0&&t.update({errorTextStyles:Object.assign(Object.assign({},n),{base:Object.assign(Object.assign({},n.base&&Object.assign({},n.base)),""!=o&&{color:o})})})}const Z=t=>{const{eventName:n,data:o,events:r}=t;if(r&&n in r){const t=r[n];"function"==typeof t&&t({elementType:e(o,"elementType",""),isEmpty:e(o,"isEmpty",""),isFocused:e(o,"isFocused",""),isValid:e(o,"isValid","")})}};function Q(e){return n(this,void 0,void 0,(function*(){const{element:t,containerId:n,retries:o=2,delay:r=30}=e;for(let e=0;e<=o;e++){if(document.querySelector(n))return void t.mount(n);e<o&&(yield new Promise((e=>setTimeout(e,r))))}console.warn(`[mountCardFields] Container ${n} was not found after ${o+1} attempts`)}))}const ee=Object.freeze({SORIANA:"SORIANA",OXXO:"OXXO",OXXOPAY:"OXXOPAY",SPEI:"SPEI",CODI:"CODI",MERCADOPAGO:"MERCADOPAGO",PAYPAL:"PAYPAL",COMERCIALMEXICANA:"COMERCIALMEXICANA",BANCOMER:"BANCOMER",WALMART:"WALMART",BODEGA:"BODEGA",SAMSCLUB:"SAMSCLUB",SUPERAMA:"SUPERAMA",CALIMAX:"CALIMAX",EXTRA:"EXTRA",CIRCULOK:"CIRCULOK",SEVEN11:"7ELEVEN",TELECOMM:"TELECOMM",BANORTE:"BANORTE",BENAVIDES:"BENAVIDES",DELAHORRO:"DELAHORRO",ELASTURIANO:"ELASTURIANO",WALDOS:"WALDOS",ALSUPER:"ALSUPER",KIOSKO:"KIOSKO",STAMARIA:"STAMARIA",LAMASBARATA:"LAMASBARATA",FARMROMA:"FARMROMA",FARMUNION:"FARMUNION",FARMATODO:"FARMATODO",SFDEASIS:"SFDEASIS",FARM911:"FARM911",FARMECONOMICAS:"FARMECONOMICAS",FARMMEDICITY:"FARMMEDICITY",RIANXEIRA:"RIANXEIRA",WESTERNUNION:"WESTERNUNION",ZONAPAGO:"ZONAPAGO",CAJALOSANDES:"CAJALOSANDES",CAJAPAITA:"CAJAPAITA",CAJASANTA:"CAJASANTA",CAJASULLANA:"CAJASULLANA",CAJATRUJILLO:"CAJATRUJILLO",EDPYME:"EDPYME",KASNET:"KASNET",NORANDINO:"NORANDINO",QAPAQ:"QAPAQ",RAIZ:"RAIZ",PAYSER:"PAYSER",WUNION:"WUNION",BANCOCONTINENTAL:"BANCOCONTINENTAL",GMONEY:"GMONEY",GOPAY:"GOPAY",WU:"WU",PUNTOSHEY:"PUNTOSHEY",AMPM:"AMPM",JUMBOMARKET:"JUMBOMARKET",SMELPUEBLO:"SMELPUEBLO",BAM:"BAM",REFACIL:"REFACIL",ACYVALORES:"ACYVALORES"}),te={[ee.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[ee.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[ee.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[ee.MERCADOPAGO]:{label:"Mercado Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/mercadopago.png"},[ee.OXXOPAY]:{label:"Oxxo Pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxopay.png"},[ee.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[ee.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[ee.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[ee.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[ee.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[ee.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[ee.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[ee.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[ee.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[ee.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[ee.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[ee.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[ee.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[ee.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[ee.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[ee.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[ee.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[ee.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[ee.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[ee.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[ee.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[ee.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[ee.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[ee.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[ee.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[ee.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[ee.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ee.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},ne=e=>{const t=e.toUpperCase().trim().replace(/\s+/g,"");return te[t]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class oe extends N{constructor({apiKey:e,mode:t,returnUrl:n,callBack:o,apiKeyTonder:r,baseUrlTonder:i,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:n,callBack:o,apiKeyTonder:r,baseUrlTonder:i,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe"}),this.activeAPMs=[],this.collectContainer=null,this.skyflowInstance=null,this.events=d||{}}injectCheckout(){return n(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),t=yield this._getCustomerCards(e,this.merchantData.business.pk);return Object.assign(Object.assign({},t),{cards:t.cards.map((e=>{return Object.assign(Object.assign({},e),{icon:(t=e.fields.card_scheme,"Visa"===t?"https://d35a75syrgujp0.cloudfront.net/cards/visa.png":"Mastercard"===t?"https://d35a75syrgujp0.cloudfront.net/cards/mastercard.png":"American Express"===t?"https://d35a75syrgujp0.cloudfront.net/cards/american_express.png":"https://d35a75syrgujp0.cloudfront.net/cards/default_card.png")});var t}))})}catch(e){throw u({message:v.getCardsError},e)}}))}saveCustomerCard(e){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{vault_id:n,vault_url:o,business:r}=this.merchantData,i=yield H({vault_id:n,vault_url:o,data:Object.assign(Object.assign({},e),{card_number:e.card_number.replace(/\s+/g,""),expiration_month:e.expiration_month.replace(/\s+/g,""),expiration_year:e.expiration_year.replace(/\s+/g,""),cvv:e.cvv.replace(/\s+/g,""),cardholder_name:e.cardholder_name.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder});return yield this._saveCustomerCard(t,null==r?void 0:r.pk,i)}catch(e){throw u({message:v.saveCardError},e)}}))}removeCustomerCard(e){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{business:n}=this.merchantData;return yield this._removeCustomerCard(t,null==n?void 0:n.pk,e)}catch(e){throw u({message:v.removeCardError},e)}}))}getCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){try{const e=yield this._fetchCustomerPaymentMethods();return(e&&"results"in e&&e.results.length>0?e.results:[]).filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},ne(e.payment_method)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw u({message:v.getPaymentMethodsError},e)}}))}mountCardFields(e){return n(this,void 0,void 0,(function*(){yield this.createSkyflowInstance(),this.collectContainer=yield function(e){var o,r,i,s,a,d,l,c,u,h,p,m,y,v,f,g,_;return n(this,void 0,void 0,(function*(){const{skyflowInstance:n,data:A,customization:b,events:E}=e,T=n.container(t.ContainerType.COLLECT),O=[],C={[j.CVV]:t.ElementType.CVV,[j.CARD_NUMBER]:t.ElementType.CARD_NUMBER,[j.EXPIRATION_MONTH]:t.ElementType.EXPIRATION_MONTH,[j.EXPIRATION_YEAR]:t.ElementType.EXPIRATION_YEAR,[j.CARDHOLDER_NAME]:t.ElementType.CARDHOLDER_NAME},S={[j.CVV]:[U],[j.CARD_NUMBER]:[U],[j.EXPIRATION_MONTH]:[U],[j.EXPIRATION_YEAR]:[U],[j.CARDHOLDER_NAME]:[w,U]},I={errorStyles:(null===(r=null===(o=null==b?void 0:b.styles)||void 0===o?void 0:o.cardForm)||void 0===r?void 0:r.errorStyles)||W,inputStyles:(null===(s=null===(i=null==b?void 0:b.styles)||void 0===i?void 0:i.cardForm)||void 0===s?void 0:s.inputStyles)||Y,labelStyles:(null===(d=null===(a=null==b?void 0:b.styles)||void 0===a?void 0:a.cardForm)||void 0===d?void 0:d.labelStyles)||J},R={name:(null===(l=null==b?void 0:b.labels)||void 0===l?void 0:l.name)||P,card_number:(null===(c=null==b?void 0:b.labels)||void 0===c?void 0:c.card_number)||D,cvv:(null===(u=null==b?void 0:b.labels)||void 0===u?void 0:u.cvv)||L,expiration_date:(null===(h=null==b?void 0:b.labels)||void 0===h?void 0:h.expiry_date)||B,expiration_month:(null===(p=null==b?void 0:b.labels)||void 0===p?void 0:p.expiration_month)||x,expiration_year:(null===(m=null==b?void 0:b.labels)||void 0===m?void 0:m.expiration_year)||$},N={name:(null===(y=null==b?void 0:b.placeholders)||void 0===y?void 0:y.name)||K,card_number:(null===(v=null==b?void 0:b.placeholders)||void 0===v?void 0:v.card_number)||F,cvv:(null===(f=null==b?void 0:b.placeholders)||void 0===f?void 0:f.cvv)||V,expiration_month:(null===(g=null==b?void 0:b.placeholders)||void 0===g?void 0:g.expiration_month)||z,expiration_year:(null===(_=null==b?void 0:b.placeholders)||void 0===_?void 0:_.expiration_year)||X},k={[j.CVV]:null==E?void 0:E.cvvEvents,[j.CARD_NUMBER]:null==E?void 0:E.cardNumberEvents,[j.EXPIRATION_MONTH]:null==E?void 0:E.monthEvents,[j.EXPIRATION_YEAR]:null==E?void 0:E.yearEvents,[j.CARDHOLDER_NAME]:null==E?void 0:E.cardHolderEvents};if("fields"in A&&Array.isArray(A.fields))if(A.fields.length>0&&"string"==typeof A.fields[0])for(const e of A.fields){const t=T.create(Object.assign(Object.assign(Object.assign({table:"cards",column:e,type:C[e],validations:S[e]},I),{label:R[e],placeholder:N[e]}),A.card_id?{skyflowID:A.card_id}:{}));G({element:t,errorStyles:I.errorStyles,fieldMessage:[j.CVV,j.EXPIRATION_MONTH,j.EXPIRATION_YEAR].includes(e)?"":R[e],events:k[e]});const n=`#collect_${String(e)}`+(A.card_id?`_${A.card_id}`:"");yield Q({element:t,containerId:n}),O.push({element:t,containerId:n})}else for(const e of A.fields){const t=e.field,n=T.create(Object.assign(Object.assign(Object.assign({table:"cards",column:t,type:C[t],validations:S[t]},I),{label:R[t],placeholder:N[t]}),A.card_id?{skyflowID:A.card_id}:{})),o=e.container_id||`#collect_${String(t)}`+(A.card_id?`_${A.card_id}`:"");yield Q({element:n,containerId:o}),O.push({element:n,containerId:o})}return{elements:O.map((e=>e.element)),container:T}}))}({skyflowInstance:this.skyflowInstance,data:e,customization:this.customization,events:this.events})}))}getBusiness(){return n(this,void 0,void 0,(function*(){try{return yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw u({message:v.getBusinessError},e)}}))}createSkyflowInstance(){return n(this,void 0,void 0,(function*(){if(this.skyflowInstance)return this.skyflowInstance;yield this._fetchMerchantData();const{vault_id:e,vault_url:o}=this.merchantData;this.skyflowInstance=yield function({baseUrl:e,apiKey:o,vault_id:r,vault_url:i}){return n(this,void 0,void 0,(function*(){return t.init({vaultID:r,vaultURL:i,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield k(e,o)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}})}))}({vault_id:e,vault_url:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}getOpenpayDeviceSessionID(e,t,o){return n(this,void 0,void 0,(function*(){try{return yield y(e,t,o)}catch(e){throw l(e)}}))}getSkyflowTokens({vault_id:e,vault_url:t,data:o}){return n(this,void 0,void 0,(function*(){return yield H({vault_id:e,vault_url:t,data:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:t,isSandbox:o,returnUrl:r}){var i;return n(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const n=yield this._getCustomer(this.abortController.signal),{vault_id:s,vault_url:a}=this.merchantData;let d;if(!t)if("string"==typeof e){const t=null===(i=this.collectContainer)||void 0===i?void 0:i.container;try{yield t.collect()}catch(e){t&&console.error("Error collecting card data",e)}d={skyflow_id:e}}else d=yield H({vault_id:s,vault_url:a,data:Object.assign(Object.assign({},e),{card_number:e.card_number.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder});return yield this._handleCheckout({card:d,payment_method:t,customer:n,isSandbox:o,returnUrl:r})}))}customerRegister(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/customer/`,n={email:e},o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield c(o)}catch(e){throw l(e)}}))}createOrder(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/orders/`,n=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield c(o)}catch(e){throw l(e)}}))}createPayment(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/business/${e.business_pk}/payments/`,n=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield c(o)}catch(e){throw l(e)}}))}startCheckoutRouter(e){return n(this,void 0,void 0,(function*(){const t=yield m(this.baseUrl,this.apiKeyTonder,e);if(yield this.init3DSRedirect(t))return t}))}init3DSRedirect(e){return n(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this._handle3dsRedirect(e)}))}startCheckoutRouterFull(e){return n(this,void 0,void 0,(function*(){try{const{order:t,total:n,customer:o,skyflowTokens:r,return_url:i,isSandbox:d,metadata:l,currency:c,payment_method:u}=e,h=yield this._fetchMerchantData(),p=yield this.customerRegister(o.email);if(!(p&&"auth_token"in p&&h&&"reference"in h))throw new s({code:"500",body:h,name:"Keys error",message:"Merchant or customer reposne errors"});{const e={business:this.apiKeyTonder,client:p.auth_token,billing_address_id:null,shipping_address_id:null,amount:n,reference:h.reference,is_oneclick:!0,items:t.items},v=yield this.createOrder(e),f=(new Date).toISOString();if(!("id"in v&&"id"in p&&"business"in h))throw new s({code:"500",body:v,name:"Keys error",message:"Order response errors"});{const e={business_pk:h.business.pk,amount:n,date:f,order_id:v.id,client_id:p.id},t=yield this.createPayment(e);let s;const{openpay_keys:g,business:_}=h;g.merchant_id&&g.public_key&&(s=yield y(g.merchant_id,g.public_key,d));const A=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:i,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:n,title_ship:"shipping",description:"transaction",device_session_id:s||null,token_id:"",order_id:"id"in v&&v.id,business_id:_.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:l,browser_info:a(),currency:c},u?{payment_method:u}:{card:r}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),b=yield m(this.baseUrl,this.apiKeyTonder,A);if(yield this.init3DSRedirect(b))return b}}}catch(e){throw l(e)}}))}registerCustomerCard(e,t,o){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${d(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-token":t,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},o))});if(n.ok)return yield n.json();throw yield c(n)}catch(e){throw l(e)}}))}deleteCustomerCard(e,t=""){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${d(this.merchantData)}/cards/${t}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(n.ok)return!0;throw yield c(n)}catch(e){throw l(e)}}))}getActiveAPMs(){return n(this,void 0,void 0,(function*(){try{const e=yield function(e,t,o="?status=active&page_size=10000&country=México",r=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${e}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:r});if(n.ok)return yield n.json();throw yield c(n)}catch(e){throw l(e)}}))}(this.baseUrl,this.apiKeyTonder),t=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=t.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},ne(e.payment_method)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}function re(e){return/^\d{12,19}$/.test(e)&&le(e)}function ie(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function se(e){return/^\d{3,4}$/.test(e)}function ae(e){return/^(0[1-9]|1[0-2])$/.test(e)}function de(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const le=e=>{const t=`${e}`.split("").reverse().map((e=>Number.parseInt(e))),n=t.shift();let o=t.reduce(((e,t,n)=>n%2!=0?e+t:e+((t*=2)>9?t-9:t)),0);return o+=n,o%10==0};export{N as BaseInlineCheckout,oe as LiteCheckout,se as validateCVV,re as validateCardNumber,ie as validateCardholderName,ae as validateExpirationMonth,de as validateExpirationYear};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tonder.io/ionic-lite-sdk",
3
- "version": "0.0.59-beta.DEV1845.f4d343f",
3
+ "version": "0.0.59",
4
4
  "description": "Tonder ionic lite SDK",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -13,7 +13,7 @@
13
13
  "license": "ISC",
14
14
  "dependencies": {
15
15
  "lodash.get": "^4.4.2",
16
- "skyflow-js": "2.4.4",
16
+ "skyflow-js": "2.5.0",
17
17
  "ts-node": "^10.9.2"
18
18
  },
19
19
  "publishConfig": {
@@ -289,8 +289,12 @@ export class LiteCheckout extends BaseInlineCheckout implements ILiteCheckout{
289
289
  if (!payment_method) {
290
290
  if (typeof card === "string") {
291
291
  const container = this.collectContainer?.container as CollectorContainer;
292
- if(container){
292
+ try{
293
293
  await container.collect()
294
+ }catch (e){
295
+ if(container){
296
+ console.error("Error collecting card data", e);
297
+ }
294
298
  }
295
299
  skyflowTokens = {
296
300
  skyflow_id: card,
@@ -211,7 +211,7 @@ export async function mountSkyflowFields(event: {
211
211
  [CardFieldEnum.EXPIRATION_MONTH]: events?.monthEvents,
212
212
  [CardFieldEnum.EXPIRATION_YEAR]: events?.yearEvents,
213
213
  [CardFieldEnum.CARDHOLDER_NAME]: events?.cardHolderEvents,
214
- }
214
+ };
215
215
 
216
216
  if ("fields" in data && Array.isArray(data.fields)) {
217
217
  if (data.fields.length > 0 && typeof data.fields[0] === "string") {
@@ -229,13 +229,19 @@ export async function mountSkyflowFields(event: {
229
229
  handleSkyflowElementEvents({
230
230
  element,
231
231
  errorStyles: customStyles.errorStyles,
232
- fieldMessage: [CardFieldEnum.CVV, CardFieldEnum.EXPIRATION_MONTH, CardFieldEnum.EXPIRATION_YEAR].includes(field) ? "":labels[field],
232
+ fieldMessage: [
233
+ CardFieldEnum.CVV,
234
+ CardFieldEnum.EXPIRATION_MONTH,
235
+ CardFieldEnum.EXPIRATION_YEAR,
236
+ ].includes(field)
237
+ ? ""
238
+ : labels[field],
233
239
  events: eventsByField[field],
234
240
  });
235
241
  const containerId =
236
242
  `#collect_${String(field)}` +
237
243
  (data.card_id ? `_${data.card_id}` : "");
238
- element.mount(containerId);
244
+ await tryMountElement({element, containerId});
239
245
  elements.push({ element, containerId });
240
246
  }
241
247
  } else {
@@ -257,7 +263,7 @@ export async function mountSkyflowFields(event: {
257
263
  const containerId =
258
264
  fieldObj.container_id ||
259
265
  `#collect_${String(key)}` + (data.card_id ? `_${data.card_id}` : "");
260
- element.mount(containerId);
266
+ await tryMountElement({element, containerId});
261
267
  elements.push({ element, containerId });
262
268
  }
263
269
  }
@@ -283,11 +289,11 @@ function handleSkyflowElementEvents(event: {
283
289
  errorStyles = {},
284
290
  requiredMessage = "Campo requerido",
285
291
  invalidMessage = "Campo no válido",
286
- events
292
+ events,
287
293
  } = event;
288
294
  if ("on" in element) {
289
295
  element.on(Skyflow.EventName.CHANGE, (state: any) => {
290
- executeEvent({eventName: "onChange", data: state, events});
296
+ executeEvent({ eventName: "onChange", data: state, events });
291
297
  updateErrorLabel({
292
298
  element,
293
299
  errorStyles,
@@ -296,7 +302,7 @@ function handleSkyflowElementEvents(event: {
296
302
  });
297
303
 
298
304
  element.on(Skyflow.EventName.BLUR, (state: any) => {
299
- executeEvent({eventName: "onBlur", data: state, events});
305
+ executeEvent({ eventName: "onBlur", data: state, events });
300
306
  if (!state.isValid) {
301
307
  const msj_error = state.isEmpty
302
308
  ? requiredMessage
@@ -312,7 +318,7 @@ function handleSkyflowElementEvents(event: {
312
318
  });
313
319
 
314
320
  element.on(Skyflow.EventName.FOCUS, (state: any) => {
315
- executeEvent({eventName: "onFocus", data: state, events});
321
+ executeEvent({ eventName: "onFocus", data: state, events });
316
322
  updateErrorLabel({
317
323
  element,
318
324
  errorStyles,
@@ -361,3 +367,25 @@ const executeEvent = (event: {
361
367
  }
362
368
  }
363
369
  };
370
+
371
+ async function tryMountElement(event: {
372
+ element: any;
373
+ containerId: string;
374
+ retries?: number;
375
+ delay?: number;
376
+ }): Promise<void> {
377
+ const { element, containerId, retries = 2, delay = 30 } = event;
378
+ for (let i = 0; i <= retries; i++) {
379
+ const el = document.querySelector(containerId);
380
+ if (el) {
381
+ element.mount(containerId);
382
+ return;
383
+ }
384
+ if (i < retries) {
385
+ await new Promise((resolve) => setTimeout(resolve, delay));
386
+ }
387
+ }
388
+ console.warn(
389
+ `[mountCardFields] Container ${containerId} was not found after ${retries + 1} attempts`,
390
+ );
391
+ }