@munchi_oy/payments 1.5.10 → 1.5.11

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
- "use strict";var w=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var k=Object.prototype.hasOwnProperty;var V=(u,e)=>{for(var r in e)w(u,r,{get:e[r],enumerable:!0})},W=(u,e,r,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of U(e))!k.call(u,n)&&n!==r&&w(u,n,{get:()=>e[n],enumerable:!(t=x(e,n))||t.enumerable});return u};var G=u=>W(w({},"__esModule",{value:!0}),u);var te={};V(te,{AppReaderStatus:()=>M,MunchiPaymentSDK:()=>N,PaymentInteractionState:()=>E,SdkPaymentStatus:()=>T});module.exports=G(te);var f=require("@munchi_oy/core");var O="1.5.10";var l=class u extends Error{code;rawError;constructor(e,r,t){super(r),this.name="PaymentSDKError",this.code=e,this.rawError=t,Object.setPrototypeOf(this,u.prototype)}};var g=require("@munchi_oy/core");var T=(o=>(o.PENDING="PENDING",o.SUCCESS="SUCCESS",o.APPROVED="APPROVED",o.FAILED="FAILED",o.CANCELLED="CANCELLED",o.ERROR="ERROR",o))(T||{}),E=(a=>(a.IDLE="IDLE",a.CONNECTING="CONNECTING",a.REQUIRES_INPUT="REQUIRES_INPUT",a.PROCESSING="PROCESSING",a.SUCCESS="SUCCESS",a.FAILED="FAILED",a.INTERNAL_ERROR="INTERNAL_ERROR",a.VERIFYING="VERIFYING",a))(E||{});var S=class{constructor(e,r,t){this.messaging=r;this.config=t;this.api=new g.PaymentApi(void 0,"",e)}api;abortController=null;currentRequestId=null;paymentProvider=g.PaymentProviderEnum.Nets;async processPayment(e,r){this.abortController=new AbortController,r("CONNECTING");let t={amount:e.amountCents,businessId:Number(this.config.storeId),referenceId:e.orderRef,currency:e.currency,displayId:e.displayId,options:{allowPinBypass:!0,transactionType:g.TransactionType.Purchase}};try{let{data:n}=await this.api.initiateNetsTerminalTransaction(t),i=n.connectCloudRequestId;if(!i)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=i,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:i});let o=await this.waitForPaymentCompletion(i,e.orderRef,this.abortController.signal);return this.currentRequestId=null,o}catch(n){throw this.currentRequestId=null,n instanceof l?n:new l("TERMINAL_BUSY","Failed to create Nets Intent",n)}}async waitForPaymentCompletion(e,r,t){let n=`nets.requests.${e}`,i=g.PaymentEventType.StatusChanged;return new Promise((o,s)=>{let a=!1,c=()=>{a=!0,typeof m=="function"&&m(),clearTimeout(y)},d=()=>{c(),s(new l("CANCELLED","Transaction cancelled"))};t.addEventListener("abort",d);let m=this.messaging.subscribe(n,i,I=>{a||(c(),t.removeEventListener("abort",d),o(this.handleSuccess(I)))}),y=setTimeout(async()=>{if(!(a||t.aborted))try{let I=await this.pollOrderStatus(e,r,this.config.storeId,t);o(this.handleSuccess(I))}catch(I){s(new l("TIMEOUT","Payment timed out and polling failed",I))}finally{t.removeEventListener("abort",d),c()}},1e4)})}async pollOrderStatus(e,r,t,n){let a=Date.now()+12e4;for(;Date.now()<a;){if(n.aborted)throw new Error("Aborted");try{let{data:c}=await this.api.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(c.status!==g.SimplePaymentStatus.Pending)return c}catch(c){if(c instanceof Error&&c.message==="Aborted")throw c}await new Promise(c=>{let d=()=>{clearTimeout(m),c(void 0)};n.addEventListener("abort",d,{once:!0});let m=setTimeout(()=>{n.removeEventListener("abort",d),c(void 0)},2e3)})}throw new Error("Payment verification timed out.")}async cancelTransaction(e){if(!this.currentRequestId)return!1;let r={requestId:this.currentRequestId,businessId:Number(this.config.storeId)};try{return await this.api.cancelNetsTerminalTransaction(r),this.abortController?.abort(),this.currentRequestId=null,!0}catch{return!1}}async refundTransaction(e,r){try{this.abortController=new AbortController;let t={amount:e.amountCents,businessId:Number(this.config.storeId),currency:e.currency,displayId:this.config.kioskId,referenceId:e.orderRef,options:{allowPinBypass:!0,transactionType:g.TransactionType.ReturnOfGoods}},{data:n}=await this.api.initiateNetsTerminalTransaction(t),i=n.connectCloudRequestId;if(!i)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=i,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:i});let o=await this.waitForPaymentCompletion(i,e.orderRef,this.abortController.signal);return this.currentRequestId=null,o}catch(t){throw this.currentRequestId=null,t instanceof l||t instanceof l?t:new l("NETWORK_ERROR","Failed to refund Nets transaction",t)}}async verifyFinalStatus(e,r){try{let{data:t}=await this.api.getPaymentStatus({businessId:Number(this.config.storeId),orderId:e.orderRef,provider:this.paymentProvider,referenceId:r});return this.handleSuccess(t)}catch(t){throw new l("NETWORK_ERROR","Failed to verify final Nets status",t)}}handleSuccess(e){let r=e.status===g.SimplePaymentStatus.Success,t={success:r,status:r?"SUCCESS":"FAILED",orderId:e.orderId,transaction:e.transaction};return e.transactionId&&(t.transactionId=e.transactionId),e.error?.code&&(t.errorCode=e.error.code),e.error?.message&&(t.errorMessage=e.error.message),t}abort(){this.abortController?.abort()}};var p=require("@munchi_oy/core");var _=u=>{if(!u)return 0;let e=Number.parseInt(u,10);return Number.isFinite(e)?e:0},D=u=>{if(!u)return new Date().toISOString();let e=new Date(u);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()};var Y="vivapayclient://pay/v1",B="abort",$="cancel",j="sale",L="transactionDetails",Q=4e3,X="534287",z="38",H="493591",J="497439",Z=[H,J],ee=["CREDIT","PREPAID","CORPORATE"],v=class{constructor(e,r,t,n){this.config=t;this.appToAppConfig=n;this.api=new p.VivaApi(void 0,"",e),this.paymentApi=new p.PaymentApi(void 0,"",e),this.paymentApiWithReference=this.paymentApi}api;paymentApi;abortController=null;currentClientTransactionId=null;currentIsvClientTransactionId=null;currentCurrency=null;currentOrderRef=null;currentSourceTerminalId=null;latestResult=null;paymentApiWithReference;wasCancelled=!1;getExecutionMode(){return"callback_driven"}async processPayment(e,r){if(!this.appToAppConfig.enabled)throw new l("STRATEGY_ERROR","Viva app-to-app is not enabled");r("CONNECTING");try{let{data:t}=await this.api.createVivaAppToAppPayment(this.buildCreatePaymentPayload(e));return await this.runAction(j,this.buildLaunchParams(t),e,r)}catch(t){throw new l("NETWORK_ERROR","Failed to create Viva app-to-app payment",t)}}async cancelTransaction(e){if(!this.currentClientTransactionId)return!1;let r=await this.lookupTransactionDetails();if(r)return this.latestResult=r,this.wasCancelled=r.status==="CANCELLED",this.abortController?.abort(),!0;try{await this.appToAppConfig.adapter.openUrl(this.buildActionUrl(B,{}))}catch(t){throw this.abortController?.abort(),new l("NETWORK_ERROR","Failed to launch Viva abort flow",t)}return this.wasCancelled=!0,this.abortController?.abort(),!0}async refundTransaction(e,r){r("CONNECTING");let t=await this.fetchPaymentReference(e),n=this.buildRefundLaunchParams(e,t);return this.runAction($,n,e,r)}async verifyFinalStatus(e,r){return this.latestResult?this.latestResult:this.wasCancelled?{success:!1,status:"CANCELLED",orderId:this.currentOrderRef??r,errorCode:p.PaymentFailureCode.PaymentCancelledByUser,errorMessage:"Transaction was cancelled",transactionId:r}:{success:!1,status:"PENDING",orderId:this.currentOrderRef??r,transactionId:r}}abort(){this.abortController?.abort()}async runAction(e,r,t,n){if(!this.appToAppConfig.enabled)throw new l("STRATEGY_ERROR","Viva app-to-app is not enabled");this.abortController=new AbortController,this.latestResult=null,this.wasCancelled=!1,this.currentCurrency=t.currency,this.currentOrderRef=t.orderRef,this.currentSourceTerminalId=r.sourceTerminalId??r.tid??null,this.currentClientTransactionId=r.clientTransactionId??null,this.currentIsvClientTransactionId=r.ISV_clientTransactionId??null;let i=this.currentClientTransactionId?{sessionId:this.currentClientTransactionId}:void 0;return new Promise((o,s)=>{let a=(m,y)=>{m?.(),this.abortController?.signal.removeEventListener("abort",y)},c=()=>{a(d,c),s(new Error("Aborted"))},d=this.appToAppConfig.adapter.subscribe(m=>{if(this.abortController?.signal.aborted)return;let y=this.parseCallbackUrl(m);y&&this.matchesKnownTransactionId(y.rawParams)&&(this.latestResult=y.result,this.wasCancelled=y.result.status==="CANCELLED",this.currentClientTransactionId=null,this.currentIsvClientTransactionId=null,this.currentCurrency=null,this.currentOrderRef=null,this.currentSourceTerminalId=null,a(d,c),o(y.result))});this.abortController?.signal.addEventListener("abort",c),n("REQUIRES_INPUT",i),this.appToAppConfig.adapter.openUrl(this.buildActionUrl(e,r)).then(()=>{this.abortController?.signal.aborted}).catch(m=>{a(d,c),this.currentClientTransactionId=null,this.currentIsvClientTransactionId=null,this.currentCurrency=null,this.currentOrderRef=null,this.currentSourceTerminalId=null,s(new l("NETWORK_ERROR","Failed to launch Viva app",m))})})}buildCreatePaymentPayload(e){let r=e.options??{},t={amount:e.amountCents,referenceId:e.orderRef,businessId:Number(this.config.storeId),currency:e.currency,displayId:e.displayId,showReceipt:!0,showTransactionResult:!0};return r.tipAmount!==void 0&&(t.tipAmount=r.tipAmount),t}buildLaunchParams(e){let r={};return Object.entries(e).forEach(([t,n])=>{n!==void 0&&(r[t]=String(n))}),r}buildRefundLaunchParams(e,r){let t=e.options??{},n=r?.originalTransactionId?.trim()||e.originalTransactionId.trim(),i={amount:String(e.amountCents),clientTransactionId:n,show_receipt:"true",show_transaction_result:"true"};if(t.sourceCode&&(i.sourceCode=t.sourceCode),r?.referenceCode&&(i.orderCode=r.referenceCode),r?.shortReferenceCode&&(i.shortOrderCode=r.shortReferenceCode),r?.receiptNumber&&(i.referenceNumber=r.receiptNumber),r?.terminalId&&(i.tid=r.terminalId),r?.referenceCode||r?.shortReferenceCode||r?.receiptNumber)return i;let o=n;return/^\d+$/.test(o)&&(o.length===16?i.orderCode=o:o.length===10?i.shortOrderCode=o:i.referenceNumber=o),i}async fetchPaymentReference(e){try{let{data:r}=await this.paymentApiWithReference.getPaymentReference({orderId:e.orderRef,provider:p.PaymentProvider.Viva,transactionId:e.originalTransactionId});return this.extractPaymentReferenceContext(r)}catch{return}}extractPaymentReferenceContext(e){if(!e)return;let r=e.references;if(!r||typeof r!="object"||Array.isArray(r))return{originalTransactionId:e.originalTransactionId};let t=r,n={originalTransactionId:this.readReferenceValue(t.originalTransactionId)??this.readReferenceValue(t.clientTransactionId)??e.originalTransactionId},i=this.readReferenceValue(t.receiptNumber)??this.readReferenceValue(t.referenceNumber),o=this.readReferenceValue(t.referenceCode)??this.readReferenceValue(t.orderCode),s=this.readReferenceValue(t.shortReferenceCode)??this.readReferenceValue(t.shortOrderCode),a=this.readReferenceValue(t.terminalId)??this.readReferenceValue(t.tid);return i&&(n.receiptNumber=i),o&&(n.referenceCode=o),s&&(n.shortReferenceCode=s),a&&(n.terminalId=a),n}readReferenceValue(e){if(typeof e!="string")return;let r=e.trim();return r.length>0?r:void 0}buildActionUrl(e,r){let t=new URLSearchParams({action:e,appId:this.appToAppConfig.appId,callback:this.appToAppConfig.callbackUrl});return Object.entries(r).forEach(([n,i])=>{t.set(n,i)}),`${Y}?${t.toString()}`}parseCallbackUrl(e){if(!this.matchesCallbackBase(e))return null;let r=new URL(e),t=Object.fromEntries(r.searchParams.entries()),n=this.isSuccessfulCallback(t),i=this.isCancelledCallback(t),o=this.resolveFailureCode(t,i),s={success:n,status:n?"SUCCESS":i?"CANCELLED":"FAILED",orderId:this.currentOrderRef??t.clientTransactionId??"unknown",errorCode:n?"":o,errorMessage:n?"":t.message??"Transaction failed without error details"};n&&(s.transaction=this.mapCallbackToTransaction(t));let a=t.transactionId??t.orderCode??t.clientTransactionId,c=t.errorCode??this.extractErrorReferenceFromMessage(t.message)??t.referenceNumber??t.tid??t.rrn;return a&&(s.transactionId=a),c&&(s.errorReference=c),{rawParams:t,result:s}}matchesCallbackBase(e){let r=new URL(e),t=new URL(this.appToAppConfig.callbackUrl);return r.protocol===t.protocol&&r.hostname===t.hostname&&r.pathname===t.pathname}matchesKnownTransactionId(e){let r=[this.currentClientTransactionId,this.currentIsvClientTransactionId].filter(n=>!!n);if(r.length===0)return!0;let t=[e.clientTransactionId,e.ISV_clientTransactionId].filter(n=>!!n);return t.length===0?!0:t.some(n=>r.includes(n))}resolveFailureCode(e,r){if(r)return p.PaymentFailureCode.PaymentCancelledByUser;let t=e.errorCode;if(t?.includes("."))return t;if(this.isTransactionDetailsAction(e)&&(e.transactionType??"").toLowerCase().includes("abort"))return p.PaymentFailureCode.SystemUnknown;let n=(e.message??"").toLowerCase(),i=(e.status??"").toLowerCase();return n.includes("declined")||i==="declined"||i==="fail"||i==="failed"?p.PaymentFailureCode.PaymentDeclined:p.PaymentFailureCode.SystemUnknown}isSuccessfulCallback(e){let r=(e.status??"").toLowerCase();return this.isTransactionDetailsAction(e)?r!=="success"?!1:!(e.transactionType??"").toLowerCase().includes("abort"):r==="success"}isTransactionDetailsAction(e){return(e.action??"").toLowerCase()===L.toLowerCase()}isCancelledCallback(e){let r=(e.status??"").toLowerCase(),t=(e.message??"").toLowerCase(),n=(e.errorCode??"").toLowerCase();return r==="cancelled"||r==="canceled"||t.includes("user_cancel")||t.includes("user cancel")||n.includes("user_cancel")||n.includes("user cancel")}extractErrorReferenceFromMessage(e){return e?e.match(/\((-?\d+)\)/)?.[1]:void 0}mapCallbackToTransaction(e){let r=e.transactionId??e.orderCode??e.clientTransactionId??"unknown",t=D(e.transactionDate),n=_(e.amount),i=_(e.tipAmount);return{amount:n,cardDetail:{aid:e.aid??null,applicationLabel:e.applicationLabel??null,cardNumber:e.accountNumber??"N/A",cardType:e.cardType??"N/A",issuer:e.bankId??null,orderCode:e.orderCode??null,timestamp:t,transactionId:r},createdAt:t,fees:this.buildFeesFromTip(i),id:r,label:null,provider:p.PaymentProvider.Viva,rawData:e,referenceId:e.clientTransactionId??null,roundingDifference:0,type:this.getVivaPaymentMethodType(e)}}getVivaPaymentMethodType(e){let r=(e.applicationLabel??"").toUpperCase().trim(),n=(e.accountNumber??"").substring(0,6),i=(e.bankId??"").trim();return n===X||i===z?p.PaymentMethod.Edenred:Z.includes(n)?p.PaymentMethod.WoltBenefit:ee.some(o=>r.includes(o))?p.PaymentMethod.Credit:p.PaymentMethod.Debit}buildFeesFromTip(e){return!e||!this.currentCurrency?null:{parts:[{taxAmount:0,total:{amount:e,currency:this.currentCurrency},type:p.FeeType.TipAmount,vatPercentage:0}]}}async lookupTransactionDetails(){if(!this.currentClientTransactionId||!this.currentSourceTerminalId)return null;let e={clientTransactionId:this.currentClientTransactionId,sourceTerminalId:this.currentSourceTerminalId};return new Promise(r=>{let t=!1,n=setTimeout(()=>{t||(t=!0,i(),r(null))},Q),i=this.appToAppConfig.adapter.subscribe(o=>{if(t)return;let s=this.parseCallbackUrl(o);s&&this.matchesKnownTransactionId(s.rawParams)&&(t=!0,clearTimeout(n),i(),r(s.result))});this.appToAppConfig.adapter.openUrl(this.buildActionUrl(L,e)).catch(()=>{t||(t=!0,clearTimeout(n),i(),r(null))})})}};var R=require("@munchi_oy/core");var P=class{constructor(e,r,t){this.messaging=r;this.config=t;this.api=new R.PaymentApi(void 0,"",e)}api;abortController=null;currentSessionId=null;paymentProvider=R.PaymentProviderEnum.Viva;async processPayment(e,r){this.abortController=new AbortController,r("CONNECTING");let t={amount:e.amountCents,referenceId:e.orderRef,businessId:parseInt(this.config.storeId),currency:e.currency,displayId:e.displayId,showReceipt:!0,showTransactionResult:!0};try{let{data:n}=await this.api.initiateTerminalTransaction(t);if(this.currentSessionId=n.sessionId,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:n.sessionId});let i=await this.waitForPaymentCompletion(n.sessionId,e.orderRef,this.abortController.signal);return this.currentSessionId=null,i}catch(n){throw this.currentSessionId=null,n instanceof l?n:new l("NETWORK_ERROR","Failed to create Viva Intent",n)}}async waitForPaymentCompletion(e,r,t){let i=`viva.${this.config.channel.toLowerCase()}.requests.${e}`,o="payment:status-changed";return new Promise((s,a)=>{let c=!1,d=()=>{c=!0,typeof y=="function"&&y(),clearTimeout(I)},m=()=>{d(),a(new Error("Aborted"))};t.addEventListener("abort",m);let y=this.messaging.subscribe(i,o,C=>{c||C.status!==R.SimplePaymentStatus.Pending&&(d(),t.removeEventListener("abort",m),s(this.handleSuccess(C)))}),I=setTimeout(async()=>{if(!(c||t.aborted))try{let C=await this.pollOrderStatus(e,r,this.config.storeId,t);s(this.handleSuccess(C))}catch(C){a(new l("TIMEOUT","Payment timed out and polling failed",C))}finally{t.removeEventListener("abort",m),d()}},1e4)})}async pollOrderStatus(e,r,t,n){let a=Date.now()+12e4;for(;Date.now()<a;){if(n.aborted)throw new Error("Aborted");try{let{data:c}=await this.api.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(c.status!==R.SimplePaymentStatus.Pending)return c}catch(c){if(c instanceof Error&&c.message==="Aborted")throw c}await new Promise(c=>{let d=()=>{clearTimeout(m),c(void 0)};n.addEventListener("abort",d,{once:!0});let m=setTimeout(()=>{n.removeEventListener("abort",d),c(void 0)},2e3)})}throw new Error("Payment verification timed out.")}handleSuccess(e){let r=e.status===R.SimplePaymentStatus.Success,t={success:r,status:r?"SUCCESS":"FAILED",orderId:e.orderId,errorCode:e.error?.code||(r?"":R.PaymentFailureCode.SystemUnknown),errorMessage:e.error?.message||(r?"":"Transaction failed without error details")};return e.transactionId&&(t.transactionId=e.transactionId),e.error?.referenceError&&(t.errorReference=e.error.referenceError),e.transaction&&(t.transaction=e.transaction),t}async cancelTransaction(e){if(!this.currentSessionId)return!1;try{let r=this.currentSessionId;return this.currentSessionId=null,await this.api.cancelVivaTransactionV2({cashRegisterId:this.config.storeId,sessionId:r}),this.abortController?.abort(),!0}catch(r){throw this.currentSessionId=null,new l("NETWORK_ERROR","Failed to cancel Viva transaction",r)}}async verifyFinalStatus(e,r){try{let{data:t}=await this.api.getPaymentStatus({businessId:Number(this.config.storeId),orderId:e.orderRef,provider:this.paymentProvider,referenceId:r}),n=t.status===R.SimplePaymentStatus.Success,i=t.status===R.SimplePaymentStatus.Pending,o={success:n,status:n?"SUCCESS":i?"PENDING":"FAILED",orderId:t.orderId,errorCode:t.error?.code||(n||i?"":R.PaymentFailureCode.SystemUnknown),errorMessage:t.error?.message||(n||i?"":"Transaction failed without error details")};return t.transactionId&&(o.transactionId=t.transactionId),t.error?.referenceError&&(o.errorReference=t.error.referenceError),t.transaction&&(o.transaction=t.transaction),o}catch(t){throw new l("NETWORK_ERROR","Failed to verify final transaction status",t)}}async refundTransaction(e,r){try{let t={amount:e.amountCents,businessId:Number(this.config.storeId),displayId:this.config.kioskId,currency:e.currency,orderReferenceId:e.orderRef,referenceId:e.originalTransactionId},{data:n}=await this.api.refundSingleVivaTransaction(t),i=n.success;return{success:i,status:i?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:n.sessionId}}catch(t){throw new l("NETWORK_ERROR","Failed to refund Viva transaction",t)}}abort(){this.abortController?.abort()}};var h=require("@munchi_oy/core"),F=require("axios");var A=class{constructor(e,r,t){this.messaging=r;this.config=t;this.paymentApi=new h.PaymentApi(void 0,"",e),this.worldlineApi=new h.WorldlineApi(void 0,"",e)}paymentApi;worldlineApi;abortController=null;currentOperationId=null;paymentProvider=h.PaymentProviderEnum.Worldline;async processPayment(e,r){this.abortController=new AbortController,r("CONNECTING");let t={amount:e.amountCents,businessId:Number(this.config.storeId),currency:e.currency,displayId:e.displayId,referenceId:e.orderRef,showReceipt:!0,showTransactionResult:!0,...e.options&&"tipAmount"in e.options&&typeof e.options.tipAmount=="number"?{tipAmount:e.options.tipAmount}:{}};try{let n=await this.worldlineApi.createPayment(t),i=this.extractOperationId(n.data);if(this.currentOperationId=i,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:i});let o=await this.waitForPaymentCompletion(i,e.orderRef,h.PaymentEventType.StatusChanged,this.abortController.signal);return this.currentOperationId=null,o}catch(n){throw this.currentOperationId=null,n instanceof l?n:this.mapWorldlineRequestError(n,"Failed to create Worldline payment")}}async cancelTransaction(e){if(!this.currentOperationId)return!1;let r={businessId:Number(this.config.storeId),targetOperationId:this.currentOperationId};try{return await this.worldlineApi.cancelPayment(r),!0}catch(t){throw this.mapWorldlineRequestError(t,"Failed to cancel Worldline transaction")}}async refundTransaction(e,r){this.abortController=new AbortController,r("CONNECTING");let t={amount:e.amountCents,businessId:Number(this.config.storeId),currency:e.currency,displayId:e.displayId,orderReferenceId:e.orderRef,referenceId:e.originalTransactionId};try{let n=await this.worldlineApi.createRefund(t),i=this.extractOperationId(n.data);if(this.currentOperationId=i,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:i});let o=await this.waitForPaymentCompletion(i,e.orderRef,h.PaymentEventType.RefundStatusChanged,this.abortController.signal);return this.currentOperationId=null,o}catch(n){throw this.currentOperationId=null,n instanceof l?n:this.mapWorldlineRequestError(n,"Failed to refund Worldline transaction")}}async verifyFinalStatus(e,r){try{let{data:t}=await this.paymentApi.getPaymentStatus({businessId:Number(this.config.storeId),orderId:e.orderRef,provider:this.paymentProvider,referenceId:r});return this.handlePaymentStatus(t)}catch(t){throw this.mapWorldlineRequestError(t,"Failed to verify final Worldline status")}}abort(){this.abortController?.abort()}async waitForPaymentCompletion(e,r,t,n){let i=`worldline.requests.${e}`;return new Promise((o,s)=>{let a=!1,c=()=>{a=!0,typeof m=="function"&&m(),clearTimeout(y)},d=()=>{c(),s(new l("CANCELLED","Transaction cancelled"))};n.addEventListener("abort",d);let m=this.messaging.subscribe(i,t,I=>{a||I.status===h.SimplePaymentStatus.Pending||(c(),n.removeEventListener("abort",d),o(this.handlePaymentStatus(I)))}),y=setTimeout(async()=>{if(!(a||n.aborted))try{let I=await this.pollOrderStatus(e,r,this.config.storeId,n);o(this.handlePaymentStatus(I))}catch(I){s(new l("TIMEOUT","Payment timed out and polling failed",I))}finally{n.removeEventListener("abort",d),c()}},1e4)})}async pollOrderStatus(e,r,t,n){let s=Date.now()+12e4;for(;Date.now()<s;){if(n.aborted)throw new Error("Aborted");try{let{data:a}=await this.paymentApi.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(a.status!==h.SimplePaymentStatus.Pending)return a}catch(a){if(a instanceof Error&&a.message==="Aborted")throw a}await new Promise(a=>{let c=()=>{clearTimeout(d),a(void 0)};n.addEventListener("abort",c,{once:!0});let d=setTimeout(()=>{n.removeEventListener("abort",c),a(void 0)},2e3)})}throw new Error("Payment verification timed out.")}handlePaymentStatus(e){let r=e.status===h.SimplePaymentStatus.Success,t=e.status===h.SimplePaymentStatus.Pending,n={success:r,status:r?"SUCCESS":t?"PENDING":"FAILED",orderId:e.orderId,errorCode:e.error?.code||(r||t?"":h.PaymentFailureCode.SystemUnknown),errorMessage:e.error?.message||(r||t?"":"Transaction failed without error details")};return e.transactionId&&(n.transactionId=e.transactionId),e.error?.referenceError&&(n.errorReference=e.error.referenceError),e.transaction&&(n.transaction=e.transaction),n}extractOperationId(e){let r=typeof e=="object"&&e!==null&&"operationId"in e&&typeof e.operationId=="string"?e.operationId:null;if(!r)throw new Error("operationId is missing from response.");return r}mapWorldlineRequestError(e,r){if((0,F.isAxiosError)(e)){if(e.response?.status===400||e.response?.status===409)return new l("TERMINAL_BUSY",r,e);if(e.response?.status===404)return new l("TERMINAL_OFFLINE",r,e)}return new l("NETWORK_ERROR",r,e)}};var N=class u{static VIVA_TIMEOUT_CANCEL_TIMEOUT_MS=5e3;strategy;axios;messaging;provider;timeoutMs;logger;_currentState="IDLE";_listeners=[];_cancellationIntent=!1;_currentSessionId;_autoResetTimer;autoResetOptions;appToAppConfig;static TERMINAL_STATES=["SUCCESS","FAILED","INTERNAL_ERROR"];static RESTING_STATES=["IDLE",...u.TERMINAL_STATES];constructor(e,r,t,n={},i){this.axios=e,this.messaging=r,this.provider=t.provider,this.logger=n.logger,this.timeoutMs=n.timeoutMs||3e4,this.autoResetOptions=n.autoResetOnPaymentComplete,this.appToAppConfig=n.appToApp,this.strategy=i??this.resolveStrategy(t)}get version(){return O}get currentState(){return this._currentState}generateErrorResult(e,r,t){return{success:!1,status:"ERROR",errorCode:this.normalizeErrorCode(r),errorMessage:t,orderId:e}}normalizeErrorCode(e){return e?e.includes(".")?e:{CANCELLED:f.PaymentFailureCode.PaymentCancelledByUser,DECLINED:f.PaymentFailureCode.PaymentDeclined,TERMINAL_BUSY:f.PaymentFailureCode.TerminalBusy,TERMINAL_OFFLINE:f.PaymentFailureCode.TerminalOffline,TIMEOUT:f.PaymentFailureCode.TerminalTimeout,NETWORK_ERROR:f.PaymentFailureCode.SystemProviderError,STRATEGY_ERROR:f.PaymentFailureCode.SystemProviderError,MISSING_CONFIG:f.PaymentFailureCode.SystemUnknown,INVALID_AMOUNT:f.PaymentFailureCode.SystemUnknown,UNKNOWN:f.PaymentFailureCode.SystemUnknown}[e]??f.PaymentFailureCode.SystemUnknown:f.PaymentFailureCode.SystemUnknown}subscribe=e=>(this._listeners.push(e),e(this._currentState),()=>{this._listeners=this._listeners.filter(r=>r!==e)});transitionTo(e){if(this._currentState===e)return;if(e==="IDLE"){this.cancelAutoReset(),this._currentState=e,this._listeners.forEach(t=>t(e));return}if(u.TERMINAL_STATES.includes(this._currentState)){let t=`Invalid State Transition: Attempted to move from terminal state ${this._currentState} to ${e}`;throw this.logger?.error(t),this._currentState!=="INTERNAL_ERROR"&&(this._currentState="INTERNAL_ERROR",this._listeners.forEach(n=>n(this._currentState))),new l("UNKNOWN",t)}this._currentState=e,u.TERMINAL_STATES.includes(e)&&this.scheduleAutoReset(e),this._listeners.forEach(t=>t(e))}_resetScheduledAt;get nextAutoResetAt(){return this._resetScheduledAt}cancelAutoReset(){this._autoResetTimer&&(clearTimeout(this._autoResetTimer),this._autoResetTimer=void 0),this._resetScheduledAt=void 0}scheduleAutoReset(e){if(!this.autoResetOptions)return;let t=e==="SUCCESS"?this.autoResetOptions.successDelayMs??5e3:this.autoResetOptions.failureDelayMs??5e3;this.logger?.info(`Scheduling auto-reset to IDLE in ${t}ms`),this._resetScheduledAt=Date.now()+t,this._autoResetTimer=setTimeout(()=>{this.logger?.info("Auto-reset triggered"),this.reset()},t)}resolveStrategy(e){switch(e.provider){case f.PaymentProvider.Nets:return new S(this.axios,this.messaging,e);case f.PaymentProvider.Worldline:return new A(this.axios,this.messaging,e);case f.PaymentProvider.Viva:return this.appToAppConfig?.enabled?new v(this.axios,this.messaging,e,this.appToAppConfig):new P(this.axios,this.messaging,e);default:return new P(this.axios,this.messaging,e)}}initiateTransaction=async(e,r)=>{let t=r??{},n=e.orderRef;if(!u.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");let o=Date.now();if(this._cancellationIntent=!1,this._currentSessionId=void 0,this.transitionTo("IDLE"),e.amountCents<=0)return this.generateErrorResult(e.orderRef,"INVALID_AMOUNT","Amount must be greater than 0");try{let s=(m,y)=>{y?.sessionId&&(this._currentSessionId=y.sessionId),m!=="FAILED"&&(this.transitionTo(m),this.fireStateCallback(m,t,n))},a=this.strategy.processPayment(e,s),d=(this.strategy.getExecutionMode?.()??"managed")==="callback_driven"?await a:await Promise.race([a,new Promise((m,y)=>{setTimeout(()=>{y(new l("TIMEOUT","Transaction timed out"))},this.timeoutMs)})]);if(d.success)this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(d));else{if(this._cancellationIntent)return await this.handleTransactionError(e,new Error("Aborted after resolution"),t);this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(d))}return this.logger?.info("Transaction completed successfully",{orderId:e.orderRef,durationMs:Date.now()-o}),d}catch(s){return this.logger?.warn("Transaction interrupted. Handling final status...",{error:s}),await this.handleTransactionError(e,s,t)}};async handleTransactionError(e,r,t={}){let n=r instanceof l&&r.code==="TIMEOUT";if(!this._cancellationIntent&&!n&&(this.transitionTo("VERIFYING"),this.safeFireCallback(()=>t.onVerifying?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId}))),this._cancellationIntent){try{if(this._currentSessionId){let s=await this.verifyWithRetry(e,this._currentSessionId);if(s.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(s)),s}}catch(s){this.logger?.warn("Final status verification failed during cancellation",{err:s})}return this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId})),{success:!1,status:"CANCELLED",errorCode:this.normalizeErrorCode("CANCELLED"),orderId:e.orderRef,...this._currentSessionId?{transactionId:this._currentSessionId}:{}}}let i,o=this._currentSessionId;if(n&&o&&this.provider===f.PaymentProvider.Viva&&!this.appToAppConfig?.enabled)try{let s=await this.recoverVivaTimeout(e,o);if(s.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(s)),s;i=s}catch(s){this.logger?.warn("Failed to get detailed error from verifyFinalStatus",{verifyErr:s}),i=this.buildErrorResultFromException(e.orderRef,s)}else if(o){this.strategy.abort();try{let s=await this.verifyWithRetry(e,o);if(s.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(s)),s;i=s}catch(s){this.logger?.warn("Failed to get detailed error from verifyFinalStatus",{verifyErr:s}),i=this.buildErrorResultFromException(e.orderRef,s)}}else this.strategy.abort(),i=this.buildErrorResultFromException(e.orderRef,r);return this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(i)),i}async recoverVivaTimeout(e,r){let t;try{await Promise.race([this.strategy.cancelTransaction(()=>{}),new Promise((n,i)=>{t=setTimeout(()=>{i(new Error("Viva timeout cancellation timed out"))},u.VIVA_TIMEOUT_CANCEL_TIMEOUT_MS)})])}catch(n){this.logger?.warn("Viva timeout cancellation attempt failed",{error:n})}finally{t&&clearTimeout(t),this.strategy.abort()}return await this.verifyWithRetry(e,r)}static VERIFY_TIMEOUT_MS=1e4;static VERIFY_MAX_RETRIES=3;static VERIFY_RETRY_DELAY_MS=1500;async verifyWithRetry(e,r){let t,n=!0;for(let s=1;s<=u.VERIFY_MAX_RETRIES;s++)try{let a=await Promise.race([this.strategy.verifyFinalStatus(e,r),new Promise((c,d)=>setTimeout(()=>d(new Error("Verify timed out")),u.VERIFY_TIMEOUT_MS))]);if(a.status==="PENDING"){t=new Error("Verify returned pending status"),this.logger?.warn(`verifyFinalStatus attempt ${s}/${u.VERIFY_MAX_RETRIES} returned pending status`),s<u.VERIFY_MAX_RETRIES&&await new Promise(c=>setTimeout(c,u.VERIFY_RETRY_DELAY_MS));continue}return a}catch(a){t=a,a instanceof Error&&a.message==="Verify timed out"||(n=!1),this.logger?.warn(`verifyFinalStatus attempt ${s}/${u.VERIFY_MAX_RETRIES} failed`,{err:a}),s<u.VERIFY_MAX_RETRIES&&await new Promise(d=>setTimeout(d,u.VERIFY_RETRY_DELAY_MS))}let i=t instanceof Error?t.message:"Verify retries exhausted",o=n?f.PaymentFailureCode.PaymentTimeout:f.PaymentFailureCode.PaymentUnknown;throw new l(o,i)}buildErrorResultFromException(e,r){return r instanceof l?this.generateErrorResult(e,r.code,r.message):this.generateErrorResult(e,"UNKNOWN",r instanceof Error?r.message:"Unknown fatal error")}fireStateCallback(e,r,t){let n={orderRef:t,refPaymentId:this._currentSessionId};switch(e){case"CONNECTING":this.safeFireCallback(()=>r.onConnecting?.(n));break;case"REQUIRES_INPUT":this.safeFireCallback(()=>r.onRequiresInput?.(n));break;case"PROCESSING":this.safeFireCallback(()=>r.onProcessing?.(n));break}}safeFireCallback(e){try{e()}catch(r){this.logger?.warn("Callback execution failed",{error:r})}}cancel=async()=>{if(this.logger?.info("Attempting cancellation"),u.TERMINAL_STATES.includes(this._currentState))return this.logger?.warn("Cannot cancel: Transaction already in terminal state",{state:this._currentState}),!1;if(!this._currentSessionId&&this._currentState==="IDLE")return this.logger?.warn("Cannot cancel: No active session to cancel",{state:this._currentState}),!1;this._cancellationIntent=!0,this.transitionTo("VERIFYING");try{return await this.strategy.cancelTransaction(r=>this.transitionTo(r))}catch(e){return this.logger?.error("Cancellation command failed",e),!1}};reset=()=>{u.TERMINAL_STATES.includes(this._currentState)&&(this._currentSessionId=void 0,this._cancellationIntent=!1,this.transitionTo("IDLE"))};refund=async(e,r)=>{let t=r??{};if(this.logger?.info("Initiating refund",{orderRef:e.orderRef}),this._currentSessionId=void 0,this._cancellationIntent=!1,!u.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");this.transitionTo("IDLE");try{let i=(s,a)=>{a?.sessionId&&(this._currentSessionId=a.sessionId),s!=="FAILED"&&(this.transitionTo(s),this.fireStateCallback(s,t,e.orderRef))},o=await this.strategy.refundTransaction(e,i);return o.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(o))):this._cancellationIntent||o.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId}))):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(o))),this.logger?.info("Refund completed",{success:o.success,orderRef:e.orderRef}),o}catch(i){if(this.logger?.error("Refund failed",i),this._cancellationIntent){try{if(this._currentSessionId){let s=await this.verifyWithRetry(e,this._currentSessionId);return s.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(s)),s):s.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId})),s):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(s)),s)}}catch(s){this.logger?.warn("Refund final status verification failed",{verifyError:s})}return this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId})),{success:!1,status:"CANCELLED",errorCode:this.normalizeErrorCode("CANCELLED"),orderId:e.orderRef,...this._currentSessionId?{transactionId:this._currentSessionId}:{}}}this.transitionTo("FAILED");let o=this.generateErrorResult(e.orderRef,"UNKNOWN",i instanceof Error?i.message:"Refund failed");return this.safeFireCallback(()=>t.onError?.(o)),o}}};var M=(n=>(n.CONNECTING="CONNECTING",n.CONNECTED="CONNECTED",n.OFFLINE="OFFLINE",n.DISCONNECTED="DISCONNECTED",n))(M||{});0&&(module.exports={AppReaderStatus,MunchiPaymentSDK,PaymentInteractionState,SdkPaymentStatus});
1
+ "use strict";var w=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var k=Object.prototype.hasOwnProperty;var V=(u,e)=>{for(var r in e)w(u,r,{get:e[r],enumerable:!0})},W=(u,e,r,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of U(e))!k.call(u,n)&&n!==r&&w(u,n,{get:()=>e[n],enumerable:!(t=x(e,n))||t.enumerable});return u};var G=u=>W(w({},"__esModule",{value:!0}),u);var te={};V(te,{AppReaderStatus:()=>M,MunchiPaymentSDK:()=>N,PaymentInteractionState:()=>E,SdkPaymentStatus:()=>T});module.exports=G(te);var f=require("@munchi_oy/core");var O="1.5.11";var l=class u extends Error{code;rawError;constructor(e,r,t){super(r),this.name="PaymentSDKError",this.code=e,this.rawError=t,Object.setPrototypeOf(this,u.prototype)}};var g=require("@munchi_oy/core");var T=(o=>(o.PENDING="PENDING",o.SUCCESS="SUCCESS",o.APPROVED="APPROVED",o.FAILED="FAILED",o.CANCELLED="CANCELLED",o.ERROR="ERROR",o))(T||{}),E=(a=>(a.IDLE="IDLE",a.CONNECTING="CONNECTING",a.REQUIRES_INPUT="REQUIRES_INPUT",a.PROCESSING="PROCESSING",a.SUCCESS="SUCCESS",a.FAILED="FAILED",a.INTERNAL_ERROR="INTERNAL_ERROR",a.VERIFYING="VERIFYING",a))(E||{});var S=class{constructor(e,r,t){this.messaging=r;this.config=t;this.api=new g.PaymentApi(void 0,"",e)}api;abortController=null;currentRequestId=null;paymentProvider=g.PaymentProviderEnum.Nets;async processPayment(e,r){this.abortController=new AbortController,r("CONNECTING");let t={amount:e.amountCents,businessId:Number(this.config.storeId),referenceId:e.orderRef,currency:e.currency,displayId:e.displayId,options:{allowPinBypass:!0,transactionType:g.TransactionType.Purchase}};try{let{data:n}=await this.api.initiateNetsTerminalTransaction(t),i=n.connectCloudRequestId;if(!i)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=i,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:i});let o=await this.waitForPaymentCompletion(i,e.orderRef,this.abortController.signal);return this.currentRequestId=null,o}catch(n){throw this.currentRequestId=null,n instanceof l?n:new l("TERMINAL_BUSY","Failed to create Nets Intent",n)}}async waitForPaymentCompletion(e,r,t){let n=`nets.requests.${e}`,i=g.PaymentEventType.StatusChanged;return new Promise((o,s)=>{let a=!1,c=()=>{a=!0,typeof m=="function"&&m(),clearTimeout(y)},d=()=>{c(),s(new l("CANCELLED","Transaction cancelled"))};t.addEventListener("abort",d);let m=this.messaging.subscribe(n,i,I=>{a||(c(),t.removeEventListener("abort",d),o(this.handleSuccess(I)))}),y=setTimeout(async()=>{if(!(a||t.aborted))try{let I=await this.pollOrderStatus(e,r,this.config.storeId,t);o(this.handleSuccess(I))}catch(I){s(new l("TIMEOUT","Payment timed out and polling failed",I))}finally{t.removeEventListener("abort",d),c()}},1e4)})}async pollOrderStatus(e,r,t,n){let a=Date.now()+12e4;for(;Date.now()<a;){if(n.aborted)throw new Error("Aborted");try{let{data:c}=await this.api.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(c.status!==g.SimplePaymentStatus.Pending)return c}catch(c){if(c instanceof Error&&c.message==="Aborted")throw c}await new Promise(c=>{let d=()=>{clearTimeout(m),c(void 0)};n.addEventListener("abort",d,{once:!0});let m=setTimeout(()=>{n.removeEventListener("abort",d),c(void 0)},2e3)})}throw new Error("Payment verification timed out.")}async cancelTransaction(e){if(!this.currentRequestId)return!1;let r={requestId:this.currentRequestId,businessId:Number(this.config.storeId)};try{return await this.api.cancelNetsTerminalTransaction(r),this.abortController?.abort(),this.currentRequestId=null,!0}catch{return!1}}async refundTransaction(e,r){try{this.abortController=new AbortController;let t={amount:e.amountCents,businessId:Number(this.config.storeId),currency:e.currency,displayId:this.config.kioskId,referenceId:e.orderRef,options:{allowPinBypass:!0,transactionType:g.TransactionType.ReturnOfGoods}},{data:n}=await this.api.initiateNetsTerminalTransaction(t),i=n.connectCloudRequestId;if(!i)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=i,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:i});let o=await this.waitForPaymentCompletion(i,e.orderRef,this.abortController.signal);return this.currentRequestId=null,o}catch(t){throw this.currentRequestId=null,t instanceof l||t instanceof l?t:new l("NETWORK_ERROR","Failed to refund Nets transaction",t)}}async verifyFinalStatus(e,r){try{let{data:t}=await this.api.getPaymentStatus({businessId:Number(this.config.storeId),orderId:e.orderRef,provider:this.paymentProvider,referenceId:r});return this.handleSuccess(t)}catch(t){throw new l("NETWORK_ERROR","Failed to verify final Nets status",t)}}handleSuccess(e){let r=e.status===g.SimplePaymentStatus.Success,t={success:r,status:r?"SUCCESS":"FAILED",orderId:e.orderId,transaction:e.transaction};return e.transactionId&&(t.transactionId=e.transactionId),e.error?.code&&(t.errorCode=e.error.code),e.error?.message&&(t.errorMessage=e.error.message),t}abort(){this.abortController?.abort()}};var p=require("@munchi_oy/core");var _=u=>{if(!u)return 0;let e=Number.parseInt(u,10);return Number.isFinite(e)?e:0},D=u=>{if(!u)return new Date().toISOString();let e=new Date(u);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()};var Y="vivapayclient://pay/v1",B="abort",$="cancel",j="sale",L="transactionDetails",Q=4e3,X="534287",z="38",H="493591",J="497439",Z=[H,J],ee=["CREDIT","PREPAID","CORPORATE"],v=class{constructor(e,r,t,n){this.config=t;this.appToAppConfig=n;this.api=new p.VivaApi(void 0,"",e),this.paymentApi=new p.PaymentApi(void 0,"",e),this.paymentApiWithReference=this.paymentApi}api;paymentApi;abortController=null;currentClientTransactionId=null;currentIsvClientTransactionId=null;currentCurrency=null;currentOrderRef=null;currentSourceTerminalId=null;latestResult=null;paymentApiWithReference;wasCancelled=!1;getExecutionMode(){return"callback_driven"}async processPayment(e,r){if(!this.appToAppConfig.enabled)throw new l("STRATEGY_ERROR","Viva app-to-app is not enabled");r("CONNECTING");try{let{data:t}=await this.api.createVivaAppToAppPayment(this.buildCreatePaymentPayload(e));return await this.runAction(j,this.buildLaunchParams(t),e,r)}catch(t){throw new l("NETWORK_ERROR","Failed to create Viva app-to-app payment",t)}}async cancelTransaction(e){if(!this.currentClientTransactionId)return!1;let r=await this.lookupTransactionDetails();if(r)return this.latestResult=r,this.wasCancelled=r.status==="CANCELLED",this.abortController?.abort(),!0;try{await this.appToAppConfig.adapter.openUrl(this.buildActionUrl(B,{}))}catch(t){throw this.abortController?.abort(),new l("NETWORK_ERROR","Failed to launch Viva abort flow",t)}return this.wasCancelled=!0,this.abortController?.abort(),!0}async refundTransaction(e,r){r("CONNECTING");let t=await this.fetchPaymentReference(e),n=this.buildRefundLaunchParams(e,t);return this.runAction($,n,e,r)}async verifyFinalStatus(e,r){return this.latestResult?this.latestResult:this.wasCancelled?{success:!1,status:"CANCELLED",orderId:this.currentOrderRef??r,errorCode:p.PaymentFailureCode.PaymentCancelledByUser,errorMessage:"Transaction was cancelled",transactionId:r}:{success:!1,status:"PENDING",orderId:this.currentOrderRef??r,transactionId:r}}abort(){this.abortController?.abort()}async runAction(e,r,t,n){if(!this.appToAppConfig.enabled)throw new l("STRATEGY_ERROR","Viva app-to-app is not enabled");this.abortController=new AbortController,this.latestResult=null,this.wasCancelled=!1,this.currentCurrency=t.currency,this.currentOrderRef=t.orderRef,this.currentSourceTerminalId=r.sourceTerminalId??r.tid??null,this.currentClientTransactionId=r.clientTransactionId??null,this.currentIsvClientTransactionId=r.ISV_clientTransactionId??null;let i=this.currentClientTransactionId?{sessionId:this.currentClientTransactionId}:void 0;return new Promise((o,s)=>{let a=(m,y)=>{m?.(),this.abortController?.signal.removeEventListener("abort",y)},c=()=>{a(d,c),s(new Error("Aborted"))},d=this.appToAppConfig.adapter.subscribe(m=>{if(this.abortController?.signal.aborted)return;let y=this.parseCallbackUrl(m);y&&this.matchesKnownTransactionId(y.rawParams)&&(this.latestResult=y.result,this.wasCancelled=y.result.status==="CANCELLED",this.currentClientTransactionId=null,this.currentIsvClientTransactionId=null,this.currentCurrency=null,this.currentOrderRef=null,this.currentSourceTerminalId=null,a(d,c),o(y.result))});this.abortController?.signal.addEventListener("abort",c),n("REQUIRES_INPUT",i),this.appToAppConfig.adapter.openUrl(this.buildActionUrl(e,r)).then(()=>{this.abortController?.signal.aborted}).catch(m=>{a(d,c),this.currentClientTransactionId=null,this.currentIsvClientTransactionId=null,this.currentCurrency=null,this.currentOrderRef=null,this.currentSourceTerminalId=null,s(new l("NETWORK_ERROR","Failed to launch Viva app",m))})})}buildCreatePaymentPayload(e){let r=e.options??{},t={amount:e.amountCents,referenceId:e.orderRef,businessId:Number(this.config.storeId),currency:e.currency,displayId:e.displayId,showReceipt:!0,showTransactionResult:!0};return r.tipAmount!==void 0&&(t.tipAmount=r.tipAmount),t}buildLaunchParams(e){let r={};return Object.entries(e).forEach(([t,n])=>{n!==void 0&&(r[t]=String(n))}),r}buildRefundLaunchParams(e,r){let t=e.options??{},n=r?.originalTransactionId?.trim()||e.originalTransactionId.trim(),i={amount:String(e.amountCents),clientTransactionId:n,show_receipt:"true",show_transaction_result:"true"};if(t.sourceCode&&(i.sourceCode=t.sourceCode),r?.referenceCode&&(i.orderCode=r.referenceCode),r?.shortReferenceCode&&(i.shortOrderCode=r.shortReferenceCode),r?.receiptNumber&&(i.referenceNumber=r.receiptNumber),r?.terminalId&&(i.tid=r.terminalId),r?.referenceCode||r?.shortReferenceCode||r?.receiptNumber)return i;let o=n;return/^\d+$/.test(o)&&(o.length===16?i.orderCode=o:o.length===10?i.shortOrderCode=o:i.referenceNumber=o),i}async fetchPaymentReference(e){try{let{data:r}=await this.paymentApiWithReference.getPaymentReference({orderId:e.orderRef,provider:p.PaymentProvider.Viva,transactionId:e.originalTransactionId});return this.extractPaymentReferenceContext(r)}catch{return}}extractPaymentReferenceContext(e){if(!e)return;let r=e.references;if(!r||typeof r!="object"||Array.isArray(r))return{originalTransactionId:e.originalTransactionId};let t=r,n={originalTransactionId:this.readReferenceValue(t.originalTransactionId)??this.readReferenceValue(t.clientTransactionId)??e.originalTransactionId},i=this.readReferenceValue(t.receiptNumber)??this.readReferenceValue(t.referenceNumber),o=this.readReferenceValue(t.referenceCode)??this.readReferenceValue(t.orderCode),s=this.readReferenceValue(t.shortReferenceCode)??this.readReferenceValue(t.shortOrderCode),a=this.readReferenceValue(t.terminalId)??this.readReferenceValue(t.tid);return i&&(n.receiptNumber=i),o&&(n.referenceCode=o),s&&(n.shortReferenceCode=s),a&&(n.terminalId=a),n}readReferenceValue(e){if(typeof e!="string")return;let r=e.trim();return r.length>0?r:void 0}buildActionUrl(e,r){let t=new URLSearchParams({action:e,appId:this.appToAppConfig.appId,callback:this.appToAppConfig.callbackUrl});return Object.entries(r).forEach(([n,i])=>{t.set(n,i)}),`${Y}?${t.toString()}`}parseCallbackUrl(e){if(!this.matchesCallbackBase(e))return null;let r=new URL(e),t=Object.fromEntries(r.searchParams.entries()),n=this.isSuccessfulCallback(t),i=this.isCancelledCallback(t),o=this.resolveFailureCode(t,i),s={success:n,status:n?"SUCCESS":i?"CANCELLED":"FAILED",orderId:this.currentOrderRef??t.clientTransactionId??"unknown",errorCode:n?"":o,errorMessage:n?"":t.message??"Transaction failed without error details"};n&&(s.transaction=this.mapCallbackToTransaction(t));let a=t.transactionId??t.orderCode??t.clientTransactionId,c=t.errorCode??this.extractErrorReferenceFromMessage(t.message)??t.referenceNumber??t.tid??t.rrn;return a&&(s.transactionId=a),c&&(s.errorReference=c),{rawParams:t,result:s}}matchesCallbackBase(e){let r=new URL(e),t=new URL(this.appToAppConfig.callbackUrl);return r.protocol===t.protocol&&r.hostname===t.hostname&&r.pathname===t.pathname}matchesKnownTransactionId(e){let r=[this.currentClientTransactionId,this.currentIsvClientTransactionId].filter(n=>!!n);if(r.length===0)return!0;let t=[e.clientTransactionId,e.ISV_clientTransactionId].filter(n=>!!n);return t.length===0?!0:t.some(n=>r.includes(n))}resolveFailureCode(e,r){if(r)return p.PaymentFailureCode.PaymentCancelledByUser;let t=e.errorCode;if(t?.includes("."))return t;if(this.isTransactionDetailsAction(e)&&(e.transactionType??"").toLowerCase().includes("abort"))return p.PaymentFailureCode.SystemUnknown;let n=(e.message??"").toLowerCase(),i=(e.status??"").toLowerCase();return n.includes("declined")||i==="declined"||i==="fail"||i==="failed"?p.PaymentFailureCode.PaymentDeclined:p.PaymentFailureCode.SystemUnknown}isSuccessfulCallback(e){let r=(e.status??"").toLowerCase();return this.isTransactionDetailsAction(e)?r!=="success"?!1:!(e.transactionType??"").toLowerCase().includes("abort"):r==="success"}isTransactionDetailsAction(e){return(e.action??"").toLowerCase()===L.toLowerCase()}isCancelledCallback(e){let r=(e.status??"").toLowerCase(),t=(e.message??"").toLowerCase(),n=(e.errorCode??"").toLowerCase();return r==="cancelled"||r==="canceled"||t.includes("user_cancel")||t.includes("user cancel")||n.includes("user_cancel")||n.includes("user cancel")}extractErrorReferenceFromMessage(e){return e?e.match(/\((-?\d+)\)/)?.[1]:void 0}mapCallbackToTransaction(e){let r=e.transactionId??e.orderCode??e.clientTransactionId??"unknown",t=D(e.transactionDate),n=_(e.amount),i=_(e.tipAmount);return{amount:n,cardDetail:{aid:e.aid??null,applicationLabel:e.applicationLabel??null,cardNumber:e.accountNumber??"N/A",cardType:e.cardType??"N/A",issuer:e.bankId??null,orderCode:e.orderCode??null,timestamp:t,transactionId:r},createdAt:t,fees:this.buildFeesFromTip(i),id:r,label:null,provider:p.PaymentProvider.Viva,rawData:e,referenceId:e.clientTransactionId??null,roundingDifference:0,type:this.getVivaPaymentMethodType(e)}}getVivaPaymentMethodType(e){let r=(e.applicationLabel??"").toUpperCase().trim(),n=(e.accountNumber??"").substring(0,6),i=(e.bankId??"").trim();return n===X||i===z?p.PaymentMethod.Edenred:Z.includes(n)?p.PaymentMethod.WoltBenefit:ee.some(o=>r.includes(o))?p.PaymentMethod.Credit:p.PaymentMethod.Debit}buildFeesFromTip(e){return!e||!this.currentCurrency?null:{parts:[{taxAmount:0,total:{amount:e,currency:this.currentCurrency},type:p.FeeType.TipAmount,vatPercentage:0}]}}async lookupTransactionDetails(){if(!this.currentClientTransactionId||!this.currentSourceTerminalId)return null;let e={clientTransactionId:this.currentClientTransactionId,sourceTerminalId:this.currentSourceTerminalId};return new Promise(r=>{let t=!1,n=setTimeout(()=>{t||(t=!0,i(),r(null))},Q),i=this.appToAppConfig.adapter.subscribe(o=>{if(t)return;let s=this.parseCallbackUrl(o);s&&this.matchesKnownTransactionId(s.rawParams)&&(t=!0,clearTimeout(n),i(),r(s.result))});this.appToAppConfig.adapter.openUrl(this.buildActionUrl(L,e)).catch(()=>{t||(t=!0,clearTimeout(n),i(),r(null))})})}};var R=require("@munchi_oy/core");var P=class{constructor(e,r,t){this.messaging=r;this.config=t;this.api=new R.PaymentApi(void 0,"",e)}api;abortController=null;currentSessionId=null;paymentProvider=R.PaymentProviderEnum.Viva;async processPayment(e,r){this.abortController=new AbortController,r("CONNECTING");let t={amount:e.amountCents,referenceId:e.orderRef,businessId:parseInt(this.config.storeId),currency:e.currency,displayId:e.displayId,showReceipt:!0,showTransactionResult:!0};try{let{data:n}=await this.api.initiateTerminalTransaction(t);if(this.currentSessionId=n.sessionId,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:n.sessionId});let i=await this.waitForPaymentCompletion(n.sessionId,e.orderRef,this.abortController.signal);return this.currentSessionId=null,i}catch(n){throw this.currentSessionId=null,n instanceof l?n:new l("NETWORK_ERROR","Failed to create Viva Intent",n)}}async waitForPaymentCompletion(e,r,t){let i=`viva.${this.config.channel.toLowerCase()}.requests.${e}`,o="payment:status-changed";return new Promise((s,a)=>{let c=!1,d=()=>{c=!0,typeof y=="function"&&y(),clearTimeout(I)},m=()=>{d(),a(new Error("Aborted"))};t.addEventListener("abort",m);let y=this.messaging.subscribe(i,o,C=>{c||C.status!==R.SimplePaymentStatus.Pending&&(d(),t.removeEventListener("abort",m),s(this.handleSuccess(C)))}),I=setTimeout(async()=>{if(!(c||t.aborted))try{let C=await this.pollOrderStatus(e,r,this.config.storeId,t);s(this.handleSuccess(C))}catch(C){a(new l("TIMEOUT","Payment timed out and polling failed",C))}finally{t.removeEventListener("abort",m),d()}},1e4)})}async pollOrderStatus(e,r,t,n){let a=Date.now()+12e4;for(;Date.now()<a;){if(n.aborted)throw new Error("Aborted");try{let{data:c}=await this.api.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(c.status!==R.SimplePaymentStatus.Pending)return c}catch(c){if(c instanceof Error&&c.message==="Aborted")throw c}await new Promise(c=>{let d=()=>{clearTimeout(m),c(void 0)};n.addEventListener("abort",d,{once:!0});let m=setTimeout(()=>{n.removeEventListener("abort",d),c(void 0)},2e3)})}throw new Error("Payment verification timed out.")}handleSuccess(e){let r=e.status===R.SimplePaymentStatus.Success,t={success:r,status:r?"SUCCESS":"FAILED",orderId:e.orderId,errorCode:e.error?.code||(r?"":R.PaymentFailureCode.SystemUnknown),errorMessage:e.error?.message||(r?"":"Transaction failed without error details")};return e.transactionId&&(t.transactionId=e.transactionId),e.error?.referenceError&&(t.errorReference=e.error.referenceError),e.transaction&&(t.transaction=e.transaction),t}async cancelTransaction(e){if(!this.currentSessionId)return!1;try{let r=this.currentSessionId;return this.currentSessionId=null,await this.api.cancelVivaTransactionV2({cashRegisterId:this.config.storeId,sessionId:r}),this.abortController?.abort(),!0}catch(r){throw this.currentSessionId=null,new l("NETWORK_ERROR","Failed to cancel Viva transaction",r)}}async verifyFinalStatus(e,r){try{let{data:t}=await this.api.getPaymentStatus({businessId:Number(this.config.storeId),orderId:e.orderRef,provider:this.paymentProvider,referenceId:r}),n=t.status===R.SimplePaymentStatus.Success,i=t.status===R.SimplePaymentStatus.Pending,o={success:n,status:n?"SUCCESS":i?"PENDING":"FAILED",orderId:t.orderId,errorCode:t.error?.code||(n||i?"":R.PaymentFailureCode.SystemUnknown),errorMessage:t.error?.message||(n||i?"":"Transaction failed without error details")};return t.transactionId&&(o.transactionId=t.transactionId),t.error?.referenceError&&(o.errorReference=t.error.referenceError),t.transaction&&(o.transaction=t.transaction),o}catch(t){throw new l("NETWORK_ERROR","Failed to verify final transaction status",t)}}async refundTransaction(e,r){try{let t={amount:e.amountCents,businessId:Number(this.config.storeId),displayId:this.config.kioskId,currency:e.currency,orderReferenceId:e.orderRef,referenceId:e.originalTransactionId},{data:n}=await this.api.refundSingleVivaTransaction(t),i=n.success;return{success:i,status:i?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:n.sessionId}}catch(t){throw new l("NETWORK_ERROR","Failed to refund Viva transaction",t)}}abort(){this.abortController?.abort()}};var h=require("@munchi_oy/core"),F=require("axios");var A=class{constructor(e,r,t){this.messaging=r;this.config=t;this.paymentApi=new h.PaymentApi(void 0,"",e),this.worldlineApi=new h.WorldlineApi(void 0,"",e)}paymentApi;worldlineApi;abortController=null;currentOperationId=null;paymentProvider=h.PaymentProviderEnum.Worldline;async processPayment(e,r){this.abortController=new AbortController,r("CONNECTING");let t={amount:e.amountCents,businessId:Number(this.config.storeId),currency:e.currency,displayId:e.displayId,referenceId:e.orderRef,showReceipt:!0,showTransactionResult:!0,...e.options&&"tipAmount"in e.options&&typeof e.options.tipAmount=="number"?{tipAmount:e.options.tipAmount}:{}};try{let n=await this.worldlineApi.createPayment(t),i=this.extractOperationId(n.data);if(this.currentOperationId=i,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:i});let o=await this.waitForPaymentCompletion(i,e.orderRef,h.PaymentEventType.StatusChanged,this.abortController.signal);return this.currentOperationId=null,o}catch(n){throw this.currentOperationId=null,n instanceof l?n:this.mapWorldlineRequestError(n,"Failed to create Worldline payment")}}async cancelTransaction(e){if(!this.currentOperationId)return!1;let r={businessId:Number(this.config.storeId),targetOperationId:this.currentOperationId};try{return await this.worldlineApi.cancelPayment(r),!0}catch(t){throw this.mapWorldlineRequestError(t,"Failed to cancel Worldline transaction")}}async refundTransaction(e,r){this.abortController=new AbortController,r("CONNECTING");let t={amount:e.amountCents,businessId:Number(this.config.storeId),currency:e.currency,displayId:e.displayId,orderReferenceId:e.orderRef,referenceId:e.originalTransactionId};try{let n=await this.worldlineApi.createRefund(t),i=this.extractOperationId(n.data);if(this.currentOperationId=i,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:i});let o=await this.waitForPaymentCompletion(i,e.orderRef,h.PaymentEventType.RefundStatusChanged,this.abortController.signal);return this.currentOperationId=null,o}catch(n){throw this.currentOperationId=null,n instanceof l?n:this.mapWorldlineRequestError(n,"Failed to refund Worldline transaction")}}async verifyFinalStatus(e,r){try{let{data:t}=await this.paymentApi.getPaymentStatus({businessId:Number(this.config.storeId),orderId:e.orderRef,provider:this.paymentProvider,referenceId:r});return this.handlePaymentStatus(t)}catch(t){throw this.mapWorldlineRequestError(t,"Failed to verify final Worldline status")}}abort(){this.abortController?.abort()}async waitForPaymentCompletion(e,r,t,n){let i=`worldline.requests.${e}`;return new Promise((o,s)=>{let a=!1,c=()=>{a=!0,typeof m=="function"&&m(),clearTimeout(y)},d=()=>{c(),s(new l("CANCELLED","Transaction cancelled"))};n.addEventListener("abort",d);let m=this.messaging.subscribe(i,t,I=>{a||I.status===h.SimplePaymentStatus.Pending||(c(),n.removeEventListener("abort",d),o(this.handlePaymentStatus(I)))}),y=setTimeout(async()=>{if(!(a||n.aborted))try{let I=await this.pollOrderStatus(e,r,this.config.storeId,n);o(this.handlePaymentStatus(I))}catch(I){s(new l("TIMEOUT","Payment timed out and polling failed",I))}finally{n.removeEventListener("abort",d),c()}},1e4)})}async pollOrderStatus(e,r,t,n){let s=Date.now()+12e4;for(;Date.now()<s;){if(n.aborted)throw new Error("Aborted");try{let{data:a}=await this.paymentApi.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(a.status!==h.SimplePaymentStatus.Pending)return a}catch(a){if(a instanceof Error&&a.message==="Aborted")throw a}await new Promise(a=>{let c=()=>{clearTimeout(d),a(void 0)};n.addEventListener("abort",c,{once:!0});let d=setTimeout(()=>{n.removeEventListener("abort",c),a(void 0)},2e3)})}throw new Error("Payment verification timed out.")}handlePaymentStatus(e){let r=e.status===h.SimplePaymentStatus.Success,t=e.status===h.SimplePaymentStatus.Pending,n={success:r,status:r?"SUCCESS":t?"PENDING":"FAILED",orderId:e.orderId,errorCode:e.error?.code||(r||t?"":h.PaymentFailureCode.SystemUnknown),errorMessage:e.error?.message||(r||t?"":"Transaction failed without error details")};return e.transactionId&&(n.transactionId=e.transactionId),e.error?.referenceError&&(n.errorReference=e.error.referenceError),e.transaction&&(n.transaction=e.transaction),n}extractOperationId(e){let r=typeof e=="object"&&e!==null&&"operationId"in e&&typeof e.operationId=="string"?e.operationId:null;if(!r)throw new Error("operationId is missing from response.");return r}mapWorldlineRequestError(e,r){if((0,F.isAxiosError)(e)){if(e.response?.status===400||e.response?.status===409)return new l("TERMINAL_BUSY",r,e);if(e.response?.status===404)return new l("TERMINAL_OFFLINE",r,e)}return new l("NETWORK_ERROR",r,e)}};var N=class u{static VIVA_TIMEOUT_CANCEL_TIMEOUT_MS=5e3;strategy;axios;messaging;provider;timeoutMs;logger;_currentState="IDLE";_listeners=[];_cancellationIntent=!1;_currentSessionId;_autoResetTimer;autoResetOptions;appToAppConfig;static TERMINAL_STATES=["SUCCESS","FAILED","INTERNAL_ERROR"];static RESTING_STATES=["IDLE",...u.TERMINAL_STATES];constructor(e,r,t,n={},i){this.axios=e,this.messaging=r,this.provider=t.provider,this.logger=n.logger,this.timeoutMs=n.timeoutMs||3e4,this.autoResetOptions=n.autoResetOnPaymentComplete,this.appToAppConfig=n.appToApp,this.strategy=i??this.resolveStrategy(t)}get version(){return O}get currentState(){return this._currentState}generateErrorResult(e,r,t){return{success:!1,status:"ERROR",errorCode:this.normalizeErrorCode(r),errorMessage:t,orderId:e}}normalizeErrorCode(e){return e?e.includes(".")?e:{CANCELLED:f.PaymentFailureCode.PaymentCancelledByUser,DECLINED:f.PaymentFailureCode.PaymentDeclined,TERMINAL_BUSY:f.PaymentFailureCode.TerminalBusy,TERMINAL_OFFLINE:f.PaymentFailureCode.TerminalOffline,TIMEOUT:f.PaymentFailureCode.TerminalTimeout,NETWORK_ERROR:f.PaymentFailureCode.SystemProviderError,STRATEGY_ERROR:f.PaymentFailureCode.SystemProviderError,MISSING_CONFIG:f.PaymentFailureCode.SystemUnknown,INVALID_AMOUNT:f.PaymentFailureCode.SystemUnknown,UNKNOWN:f.PaymentFailureCode.SystemUnknown}[e]??f.PaymentFailureCode.SystemUnknown:f.PaymentFailureCode.SystemUnknown}subscribe=e=>(this._listeners.push(e),e(this._currentState),()=>{this._listeners=this._listeners.filter(r=>r!==e)});transitionTo(e){if(this._currentState===e)return;if(e==="IDLE"){this.cancelAutoReset(),this._currentState=e,this._listeners.forEach(t=>t(e));return}if(u.TERMINAL_STATES.includes(this._currentState)){let t=`Invalid State Transition: Attempted to move from terminal state ${this._currentState} to ${e}`;throw this.logger?.error(t),this._currentState!=="INTERNAL_ERROR"&&(this._currentState="INTERNAL_ERROR",this._listeners.forEach(n=>n(this._currentState))),new l("UNKNOWN",t)}this._currentState=e,u.TERMINAL_STATES.includes(e)&&this.scheduleAutoReset(e),this._listeners.forEach(t=>t(e))}_resetScheduledAt;get nextAutoResetAt(){return this._resetScheduledAt}cancelAutoReset(){this._autoResetTimer&&(clearTimeout(this._autoResetTimer),this._autoResetTimer=void 0),this._resetScheduledAt=void 0}scheduleAutoReset(e){if(!this.autoResetOptions)return;let t=e==="SUCCESS"?this.autoResetOptions.successDelayMs??5e3:this.autoResetOptions.failureDelayMs??5e3;this.logger?.info(`Scheduling auto-reset to IDLE in ${t}ms`),this._resetScheduledAt=Date.now()+t,this._autoResetTimer=setTimeout(()=>{this.logger?.info("Auto-reset triggered"),this.reset()},t)}resolveStrategy(e){switch(e.provider){case f.PaymentProvider.Nets:return new S(this.axios,this.messaging,e);case f.PaymentProvider.Worldline:return new A(this.axios,this.messaging,e);case f.PaymentProvider.Viva:return this.appToAppConfig?.enabled?new v(this.axios,this.messaging,e,this.appToAppConfig):new P(this.axios,this.messaging,e);default:return new P(this.axios,this.messaging,e)}}initiateTransaction=async(e,r)=>{let t=r??{},n=e.orderRef;if(!u.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");let o=Date.now();if(this._cancellationIntent=!1,this._currentSessionId=void 0,this.transitionTo("IDLE"),e.amountCents<=0)return this.generateErrorResult(e.orderRef,"INVALID_AMOUNT","Amount must be greater than 0");try{let s=(m,y)=>{y?.sessionId&&(this._currentSessionId=y.sessionId),m!=="FAILED"&&(this.transitionTo(m),this.fireStateCallback(m,t,n))},a=this.strategy.processPayment(e,s),d=(this.strategy.getExecutionMode?.()??"managed")==="callback_driven"?await a:await Promise.race([a,new Promise((m,y)=>{setTimeout(()=>{y(new l("TIMEOUT","Transaction timed out"))},this.timeoutMs)})]);if(d.success)this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(d));else{if(this._cancellationIntent)return await this.handleTransactionError(e,new Error("Aborted after resolution"),t);this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(d))}return this.logger?.info("Transaction completed successfully",{orderId:e.orderRef,durationMs:Date.now()-o}),d}catch(s){return this.logger?.warn("Transaction interrupted. Handling final status...",{error:s}),await this.handleTransactionError(e,s,t)}};async handleTransactionError(e,r,t={}){let n=r instanceof l&&r.code==="TIMEOUT";if(!this._cancellationIntent&&!n&&(this.transitionTo("VERIFYING"),this.safeFireCallback(()=>t.onVerifying?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId}))),this._cancellationIntent){try{if(this._currentSessionId){let s=await this.verifyWithRetry(e,this._currentSessionId);if(s.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(s)),s}}catch(s){this.logger?.warn("Final status verification failed during cancellation",{err:s})}return this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId})),{success:!1,status:"CANCELLED",errorCode:this.normalizeErrorCode("CANCELLED"),orderId:e.orderRef,...this._currentSessionId?{transactionId:this._currentSessionId}:{}}}let i,o=this._currentSessionId;if(n&&o&&this.provider===f.PaymentProvider.Viva&&!this.appToAppConfig?.enabled)try{let s=await this.recoverVivaTimeout(e,o);if(s.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(s)),s;i=s}catch(s){this.logger?.warn("Failed to get detailed error from verifyFinalStatus",{verifyErr:s}),i=this.buildErrorResultFromException(e.orderRef,s)}else if(o){this.strategy.abort();try{let s=await this.verifyWithRetry(e,o);if(s.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(s)),s;i=s}catch(s){this.logger?.warn("Failed to get detailed error from verifyFinalStatus",{verifyErr:s}),i=this.buildErrorResultFromException(e.orderRef,s)}}else this.strategy.abort(),i=this.buildErrorResultFromException(e.orderRef,r);return this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(i)),i}async recoverVivaTimeout(e,r){let t;try{await Promise.race([this.strategy.cancelTransaction(()=>{}),new Promise((n,i)=>{t=setTimeout(()=>{i(new Error("Viva timeout cancellation timed out"))},u.VIVA_TIMEOUT_CANCEL_TIMEOUT_MS)})])}catch(n){this.logger?.warn("Viva timeout cancellation attempt failed",{error:n})}finally{t&&clearTimeout(t),this.strategy.abort()}return await this.verifyWithRetry(e,r)}static VERIFY_TIMEOUT_MS=1e4;static VERIFY_MAX_RETRIES=3;static VERIFY_RETRY_DELAY_MS=1500;async verifyWithRetry(e,r){let t,n=!0;for(let s=1;s<=u.VERIFY_MAX_RETRIES;s++)try{let a=await Promise.race([this.strategy.verifyFinalStatus(e,r),new Promise((c,d)=>setTimeout(()=>d(new Error("Verify timed out")),u.VERIFY_TIMEOUT_MS))]);if(a.status==="PENDING"){t=new Error("Verify returned pending status"),this.logger?.warn(`verifyFinalStatus attempt ${s}/${u.VERIFY_MAX_RETRIES} returned pending status`),s<u.VERIFY_MAX_RETRIES&&await new Promise(c=>setTimeout(c,u.VERIFY_RETRY_DELAY_MS));continue}return a}catch(a){t=a,a instanceof Error&&a.message==="Verify timed out"||(n=!1),this.logger?.warn(`verifyFinalStatus attempt ${s}/${u.VERIFY_MAX_RETRIES} failed`,{err:a}),s<u.VERIFY_MAX_RETRIES&&await new Promise(d=>setTimeout(d,u.VERIFY_RETRY_DELAY_MS))}let i=t instanceof Error?t.message:"Verify retries exhausted",o=n?f.PaymentFailureCode.PaymentTimeout:f.PaymentFailureCode.PaymentUnknown;throw new l(o,i)}buildErrorResultFromException(e,r){return r instanceof l?this.generateErrorResult(e,r.code,r.message):this.generateErrorResult(e,"UNKNOWN",r instanceof Error?r.message:"Unknown fatal error")}fireStateCallback(e,r,t){let n={orderRef:t,refPaymentId:this._currentSessionId};switch(e){case"CONNECTING":this.safeFireCallback(()=>r.onConnecting?.(n));break;case"REQUIRES_INPUT":this.safeFireCallback(()=>r.onRequiresInput?.(n));break;case"PROCESSING":this.safeFireCallback(()=>r.onProcessing?.(n));break}}safeFireCallback(e){try{e()}catch(r){this.logger?.warn("Callback execution failed",{error:r})}}cancel=async()=>{if(this.logger?.info("Attempting cancellation"),u.TERMINAL_STATES.includes(this._currentState))return this.logger?.warn("Cannot cancel: Transaction already in terminal state",{state:this._currentState}),!1;if(!this._currentSessionId&&this._currentState==="IDLE")return this.logger?.warn("Cannot cancel: No active session to cancel",{state:this._currentState}),!1;this._cancellationIntent=!0,this.transitionTo("VERIFYING");try{return await this.strategy.cancelTransaction(r=>this.transitionTo(r))}catch(e){return this.logger?.error("Cancellation command failed",e),!1}};reset=()=>{u.TERMINAL_STATES.includes(this._currentState)&&(this._currentSessionId=void 0,this._cancellationIntent=!1,this.transitionTo("IDLE"))};refund=async(e,r)=>{let t=r??{};if(this.logger?.info("Initiating refund",{orderRef:e.orderRef}),this._currentSessionId=void 0,this._cancellationIntent=!1,!u.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");this.transitionTo("IDLE");try{let i=(s,a)=>{a?.sessionId&&(this._currentSessionId=a.sessionId),s!=="FAILED"&&(this.transitionTo(s),this.fireStateCallback(s,t,e.orderRef))},o=await this.strategy.refundTransaction(e,i);return o.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(o))):this._cancellationIntent||o.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId}))):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(o))),this.logger?.info("Refund completed",{success:o.success,orderRef:e.orderRef}),o}catch(i){if(this.logger?.error("Refund failed",i),this._cancellationIntent){try{if(this._currentSessionId){let s=await this.verifyWithRetry(e,this._currentSessionId);return s.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(s)),s):s.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId})),s):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(s)),s)}}catch(s){this.logger?.warn("Refund final status verification failed",{verifyError:s})}return this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId})),{success:!1,status:"CANCELLED",errorCode:this.normalizeErrorCode("CANCELLED"),orderId:e.orderRef,...this._currentSessionId?{transactionId:this._currentSessionId}:{}}}this.transitionTo("FAILED");let o=this.generateErrorResult(e.orderRef,"UNKNOWN",i instanceof Error?i.message:"Refund failed");return this.safeFireCallback(()=>t.onError?.(o)),o}}};var M=(n=>(n.CONNECTING="CONNECTING",n.CONNECTED="CONNECTED",n.OFFLINE="OFFLINE",n.DISCONNECTED="DISCONNECTED",n))(M||{});0&&(module.exports={AppReaderStatus,MunchiPaymentSDK,PaymentInteractionState,SdkPaymentStatus});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{PaymentFailureCode as y,PaymentProvider as N}from"@munchi_oy/core";var O="1.5.10";var l=class d extends Error{code;rawError;constructor(e,r,t){super(r),this.name="PaymentSDKError",this.code=e,this.rawError=t,Object.setPrototypeOf(this,d.prototype)}};import{PaymentApi as W,PaymentEventType as G,PaymentProviderEnum as q,SimplePaymentStatus as D,TransactionType as L}from"@munchi_oy/core";var I=(o=>(o.PENDING="PENDING",o.SUCCESS="SUCCESS",o.APPROVED="APPROVED",o.FAILED="FAILED",o.CANCELLED="CANCELLED",o.ERROR="ERROR",o))(I||{}),R=(a=>(a.IDLE="IDLE",a.CONNECTING="CONNECTING",a.REQUIRES_INPUT="REQUIRES_INPUT",a.PROCESSING="PROCESSING",a.SUCCESS="SUCCESS",a.FAILED="FAILED",a.INTERNAL_ERROR="INTERNAL_ERROR",a.VERIFYING="VERIFYING",a))(R||{});var C=class{constructor(e,r,t){this.messaging=r;this.config=t;this.api=new W(void 0,"",e)}api;abortController=null;currentRequestId=null;paymentProvider=q.Nets;async processPayment(e,r){this.abortController=new AbortController,r("CONNECTING");let t={amount:e.amountCents,businessId:Number(this.config.storeId),referenceId:e.orderRef,currency:e.currency,displayId:e.displayId,options:{allowPinBypass:!0,transactionType:L.Purchase}};try{let{data:n}=await this.api.initiateNetsTerminalTransaction(t),i=n.connectCloudRequestId;if(!i)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=i,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:i});let o=await this.waitForPaymentCompletion(i,e.orderRef,this.abortController.signal);return this.currentRequestId=null,o}catch(n){throw this.currentRequestId=null,n instanceof l?n:new l("TERMINAL_BUSY","Failed to create Nets Intent",n)}}async waitForPaymentCompletion(e,r,t){let n=`nets.requests.${e}`,i=G.StatusChanged;return new Promise((o,s)=>{let a=!1,c=()=>{a=!0,typeof m=="function"&&m(),clearTimeout(p)},u=()=>{c(),s(new l("CANCELLED","Transaction cancelled"))};t.addEventListener("abort",u);let m=this.messaging.subscribe(n,i,f=>{a||(c(),t.removeEventListener("abort",u),o(this.handleSuccess(f)))}),p=setTimeout(async()=>{if(!(a||t.aborted))try{let f=await this.pollOrderStatus(e,r,this.config.storeId,t);o(this.handleSuccess(f))}catch(f){s(new l("TIMEOUT","Payment timed out and polling failed",f))}finally{t.removeEventListener("abort",u),c()}},1e4)})}async pollOrderStatus(e,r,t,n){let a=Date.now()+12e4;for(;Date.now()<a;){if(n.aborted)throw new Error("Aborted");try{let{data:c}=await this.api.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(c.status!==D.Pending)return c}catch(c){if(c instanceof Error&&c.message==="Aborted")throw c}await new Promise(c=>{let u=()=>{clearTimeout(m),c(void 0)};n.addEventListener("abort",u,{once:!0});let m=setTimeout(()=>{n.removeEventListener("abort",u),c(void 0)},2e3)})}throw new Error("Payment verification timed out.")}async cancelTransaction(e){if(!this.currentRequestId)return!1;let r={requestId:this.currentRequestId,businessId:Number(this.config.storeId)};try{return await this.api.cancelNetsTerminalTransaction(r),this.abortController?.abort(),this.currentRequestId=null,!0}catch{return!1}}async refundTransaction(e,r){try{this.abortController=new AbortController;let t={amount:e.amountCents,businessId:Number(this.config.storeId),currency:e.currency,displayId:this.config.kioskId,referenceId:e.orderRef,options:{allowPinBypass:!0,transactionType:L.ReturnOfGoods}},{data:n}=await this.api.initiateNetsTerminalTransaction(t),i=n.connectCloudRequestId;if(!i)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=i,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:i});let o=await this.waitForPaymentCompletion(i,e.orderRef,this.abortController.signal);return this.currentRequestId=null,o}catch(t){throw this.currentRequestId=null,t instanceof l||t instanceof l?t:new l("NETWORK_ERROR","Failed to refund Nets transaction",t)}}async verifyFinalStatus(e,r){try{let{data:t}=await this.api.getPaymentStatus({businessId:Number(this.config.storeId),orderId:e.orderRef,provider:this.paymentProvider,referenceId:r});return this.handleSuccess(t)}catch(t){throw new l("NETWORK_ERROR","Failed to verify final Nets status",t)}}handleSuccess(e){let r=e.status===D.Success,t={success:r,status:r?"SUCCESS":"FAILED",orderId:e.orderId,transaction:e.transaction};return e.transactionId&&(t.transactionId=e.transactionId),e.error?.code&&(t.errorCode=e.error.code),e.error?.message&&(t.errorMessage=e.error.message),t}abort(){this.abortController?.abort()}};import{FeeType as Y,PaymentApi as B,PaymentFailureCode as g,PaymentMethod as S,PaymentProvider as M,VivaApi as $}from"@munchi_oy/core";var w=d=>{if(!d)return 0;let e=Number.parseInt(d,10);return Number.isFinite(e)?e:0},F=d=>{if(!d)return new Date().toISOString();let e=new Date(d);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()};var j="vivapayclient://pay/v1",Q="abort",X="cancel",z="sale",x="transactionDetails",H=4e3,J="534287",Z="38",ee="493591",te="497439",re=[ee,te],ne=["CREDIT","PREPAID","CORPORATE"],b=class{constructor(e,r,t,n){this.config=t;this.appToAppConfig=n;this.api=new $(void 0,"",e),this.paymentApi=new B(void 0,"",e),this.paymentApiWithReference=this.paymentApi}api;paymentApi;abortController=null;currentClientTransactionId=null;currentIsvClientTransactionId=null;currentCurrency=null;currentOrderRef=null;currentSourceTerminalId=null;latestResult=null;paymentApiWithReference;wasCancelled=!1;getExecutionMode(){return"callback_driven"}async processPayment(e,r){if(!this.appToAppConfig.enabled)throw new l("STRATEGY_ERROR","Viva app-to-app is not enabled");r("CONNECTING");try{let{data:t}=await this.api.createVivaAppToAppPayment(this.buildCreatePaymentPayload(e));return await this.runAction(z,this.buildLaunchParams(t),e,r)}catch(t){throw new l("NETWORK_ERROR","Failed to create Viva app-to-app payment",t)}}async cancelTransaction(e){if(!this.currentClientTransactionId)return!1;let r=await this.lookupTransactionDetails();if(r)return this.latestResult=r,this.wasCancelled=r.status==="CANCELLED",this.abortController?.abort(),!0;try{await this.appToAppConfig.adapter.openUrl(this.buildActionUrl(Q,{}))}catch(t){throw this.abortController?.abort(),new l("NETWORK_ERROR","Failed to launch Viva abort flow",t)}return this.wasCancelled=!0,this.abortController?.abort(),!0}async refundTransaction(e,r){r("CONNECTING");let t=await this.fetchPaymentReference(e),n=this.buildRefundLaunchParams(e,t);return this.runAction(X,n,e,r)}async verifyFinalStatus(e,r){return this.latestResult?this.latestResult:this.wasCancelled?{success:!1,status:"CANCELLED",orderId:this.currentOrderRef??r,errorCode:g.PaymentCancelledByUser,errorMessage:"Transaction was cancelled",transactionId:r}:{success:!1,status:"PENDING",orderId:this.currentOrderRef??r,transactionId:r}}abort(){this.abortController?.abort()}async runAction(e,r,t,n){if(!this.appToAppConfig.enabled)throw new l("STRATEGY_ERROR","Viva app-to-app is not enabled");this.abortController=new AbortController,this.latestResult=null,this.wasCancelled=!1,this.currentCurrency=t.currency,this.currentOrderRef=t.orderRef,this.currentSourceTerminalId=r.sourceTerminalId??r.tid??null,this.currentClientTransactionId=r.clientTransactionId??null,this.currentIsvClientTransactionId=r.ISV_clientTransactionId??null;let i=this.currentClientTransactionId?{sessionId:this.currentClientTransactionId}:void 0;return new Promise((o,s)=>{let a=(m,p)=>{m?.(),this.abortController?.signal.removeEventListener("abort",p)},c=()=>{a(u,c),s(new Error("Aborted"))},u=this.appToAppConfig.adapter.subscribe(m=>{if(this.abortController?.signal.aborted)return;let p=this.parseCallbackUrl(m);p&&this.matchesKnownTransactionId(p.rawParams)&&(this.latestResult=p.result,this.wasCancelled=p.result.status==="CANCELLED",this.currentClientTransactionId=null,this.currentIsvClientTransactionId=null,this.currentCurrency=null,this.currentOrderRef=null,this.currentSourceTerminalId=null,a(u,c),o(p.result))});this.abortController?.signal.addEventListener("abort",c),n("REQUIRES_INPUT",i),this.appToAppConfig.adapter.openUrl(this.buildActionUrl(e,r)).then(()=>{this.abortController?.signal.aborted}).catch(m=>{a(u,c),this.currentClientTransactionId=null,this.currentIsvClientTransactionId=null,this.currentCurrency=null,this.currentOrderRef=null,this.currentSourceTerminalId=null,s(new l("NETWORK_ERROR","Failed to launch Viva app",m))})})}buildCreatePaymentPayload(e){let r=e.options??{},t={amount:e.amountCents,referenceId:e.orderRef,businessId:Number(this.config.storeId),currency:e.currency,displayId:e.displayId,showReceipt:!0,showTransactionResult:!0};return r.tipAmount!==void 0&&(t.tipAmount=r.tipAmount),t}buildLaunchParams(e){let r={};return Object.entries(e).forEach(([t,n])=>{n!==void 0&&(r[t]=String(n))}),r}buildRefundLaunchParams(e,r){let t=e.options??{},n=r?.originalTransactionId?.trim()||e.originalTransactionId.trim(),i={amount:String(e.amountCents),clientTransactionId:n,show_receipt:"true",show_transaction_result:"true"};if(t.sourceCode&&(i.sourceCode=t.sourceCode),r?.referenceCode&&(i.orderCode=r.referenceCode),r?.shortReferenceCode&&(i.shortOrderCode=r.shortReferenceCode),r?.receiptNumber&&(i.referenceNumber=r.receiptNumber),r?.terminalId&&(i.tid=r.terminalId),r?.referenceCode||r?.shortReferenceCode||r?.receiptNumber)return i;let o=n;return/^\d+$/.test(o)&&(o.length===16?i.orderCode=o:o.length===10?i.shortOrderCode=o:i.referenceNumber=o),i}async fetchPaymentReference(e){try{let{data:r}=await this.paymentApiWithReference.getPaymentReference({orderId:e.orderRef,provider:M.Viva,transactionId:e.originalTransactionId});return this.extractPaymentReferenceContext(r)}catch{return}}extractPaymentReferenceContext(e){if(!e)return;let r=e.references;if(!r||typeof r!="object"||Array.isArray(r))return{originalTransactionId:e.originalTransactionId};let t=r,n={originalTransactionId:this.readReferenceValue(t.originalTransactionId)??this.readReferenceValue(t.clientTransactionId)??e.originalTransactionId},i=this.readReferenceValue(t.receiptNumber)??this.readReferenceValue(t.referenceNumber),o=this.readReferenceValue(t.referenceCode)??this.readReferenceValue(t.orderCode),s=this.readReferenceValue(t.shortReferenceCode)??this.readReferenceValue(t.shortOrderCode),a=this.readReferenceValue(t.terminalId)??this.readReferenceValue(t.tid);return i&&(n.receiptNumber=i),o&&(n.referenceCode=o),s&&(n.shortReferenceCode=s),a&&(n.terminalId=a),n}readReferenceValue(e){if(typeof e!="string")return;let r=e.trim();return r.length>0?r:void 0}buildActionUrl(e,r){let t=new URLSearchParams({action:e,appId:this.appToAppConfig.appId,callback:this.appToAppConfig.callbackUrl});return Object.entries(r).forEach(([n,i])=>{t.set(n,i)}),`${j}?${t.toString()}`}parseCallbackUrl(e){if(!this.matchesCallbackBase(e))return null;let r=new URL(e),t=Object.fromEntries(r.searchParams.entries()),n=this.isSuccessfulCallback(t),i=this.isCancelledCallback(t),o=this.resolveFailureCode(t,i),s={success:n,status:n?"SUCCESS":i?"CANCELLED":"FAILED",orderId:this.currentOrderRef??t.clientTransactionId??"unknown",errorCode:n?"":o,errorMessage:n?"":t.message??"Transaction failed without error details"};n&&(s.transaction=this.mapCallbackToTransaction(t));let a=t.transactionId??t.orderCode??t.clientTransactionId,c=t.errorCode??this.extractErrorReferenceFromMessage(t.message)??t.referenceNumber??t.tid??t.rrn;return a&&(s.transactionId=a),c&&(s.errorReference=c),{rawParams:t,result:s}}matchesCallbackBase(e){let r=new URL(e),t=new URL(this.appToAppConfig.callbackUrl);return r.protocol===t.protocol&&r.hostname===t.hostname&&r.pathname===t.pathname}matchesKnownTransactionId(e){let r=[this.currentClientTransactionId,this.currentIsvClientTransactionId].filter(n=>!!n);if(r.length===0)return!0;let t=[e.clientTransactionId,e.ISV_clientTransactionId].filter(n=>!!n);return t.length===0?!0:t.some(n=>r.includes(n))}resolveFailureCode(e,r){if(r)return g.PaymentCancelledByUser;let t=e.errorCode;if(t?.includes("."))return t;if(this.isTransactionDetailsAction(e)&&(e.transactionType??"").toLowerCase().includes("abort"))return g.SystemUnknown;let n=(e.message??"").toLowerCase(),i=(e.status??"").toLowerCase();return n.includes("declined")||i==="declined"||i==="fail"||i==="failed"?g.PaymentDeclined:g.SystemUnknown}isSuccessfulCallback(e){let r=(e.status??"").toLowerCase();return this.isTransactionDetailsAction(e)?r!=="success"?!1:!(e.transactionType??"").toLowerCase().includes("abort"):r==="success"}isTransactionDetailsAction(e){return(e.action??"").toLowerCase()===x.toLowerCase()}isCancelledCallback(e){let r=(e.status??"").toLowerCase(),t=(e.message??"").toLowerCase(),n=(e.errorCode??"").toLowerCase();return r==="cancelled"||r==="canceled"||t.includes("user_cancel")||t.includes("user cancel")||n.includes("user_cancel")||n.includes("user cancel")}extractErrorReferenceFromMessage(e){return e?e.match(/\((-?\d+)\)/)?.[1]:void 0}mapCallbackToTransaction(e){let r=e.transactionId??e.orderCode??e.clientTransactionId??"unknown",t=F(e.transactionDate),n=w(e.amount),i=w(e.tipAmount);return{amount:n,cardDetail:{aid:e.aid??null,applicationLabel:e.applicationLabel??null,cardNumber:e.accountNumber??"N/A",cardType:e.cardType??"N/A",issuer:e.bankId??null,orderCode:e.orderCode??null,timestamp:t,transactionId:r},createdAt:t,fees:this.buildFeesFromTip(i),id:r,label:null,provider:M.Viva,rawData:e,referenceId:e.clientTransactionId??null,roundingDifference:0,type:this.getVivaPaymentMethodType(e)}}getVivaPaymentMethodType(e){let r=(e.applicationLabel??"").toUpperCase().trim(),n=(e.accountNumber??"").substring(0,6),i=(e.bankId??"").trim();return n===J||i===Z?S.Edenred:re.includes(n)?S.WoltBenefit:ne.some(o=>r.includes(o))?S.Credit:S.Debit}buildFeesFromTip(e){return!e||!this.currentCurrency?null:{parts:[{taxAmount:0,total:{amount:e,currency:this.currentCurrency},type:Y.TipAmount,vatPercentage:0}]}}async lookupTransactionDetails(){if(!this.currentClientTransactionId||!this.currentSourceTerminalId)return null;let e={clientTransactionId:this.currentClientTransactionId,sourceTerminalId:this.currentSourceTerminalId};return new Promise(r=>{let t=!1,n=setTimeout(()=>{t||(t=!0,i(),r(null))},H),i=this.appToAppConfig.adapter.subscribe(o=>{if(t)return;let s=this.parseCallbackUrl(o);s&&this.matchesKnownTransactionId(s.rawParams)&&(t=!0,clearTimeout(n),i(),r(s.result))});this.appToAppConfig.adapter.openUrl(this.buildActionUrl(x,e)).catch(()=>{t||(t=!0,clearTimeout(n),i(),r(null))})})}};import{PaymentApi as ie,PaymentFailureCode as U,PaymentProviderEnum as se,SimplePaymentStatus as T}from"@munchi_oy/core";var E=class{constructor(e,r,t){this.messaging=r;this.config=t;this.api=new ie(void 0,"",e)}api;abortController=null;currentSessionId=null;paymentProvider=se.Viva;async processPayment(e,r){this.abortController=new AbortController,r("CONNECTING");let t={amount:e.amountCents,referenceId:e.orderRef,businessId:parseInt(this.config.storeId),currency:e.currency,displayId:e.displayId,showReceipt:!0,showTransactionResult:!0};try{let{data:n}=await this.api.initiateTerminalTransaction(t);if(this.currentSessionId=n.sessionId,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:n.sessionId});let i=await this.waitForPaymentCompletion(n.sessionId,e.orderRef,this.abortController.signal);return this.currentSessionId=null,i}catch(n){throw this.currentSessionId=null,n instanceof l?n:new l("NETWORK_ERROR","Failed to create Viva Intent",n)}}async waitForPaymentCompletion(e,r,t){let i=`viva.${this.config.channel.toLowerCase()}.requests.${e}`,o="payment:status-changed";return new Promise((s,a)=>{let c=!1,u=()=>{c=!0,typeof p=="function"&&p(),clearTimeout(f)},m=()=>{u(),a(new Error("Aborted"))};t.addEventListener("abort",m);let p=this.messaging.subscribe(i,o,h=>{c||h.status!==T.Pending&&(u(),t.removeEventListener("abort",m),s(this.handleSuccess(h)))}),f=setTimeout(async()=>{if(!(c||t.aborted))try{let h=await this.pollOrderStatus(e,r,this.config.storeId,t);s(this.handleSuccess(h))}catch(h){a(new l("TIMEOUT","Payment timed out and polling failed",h))}finally{t.removeEventListener("abort",m),u()}},1e4)})}async pollOrderStatus(e,r,t,n){let a=Date.now()+12e4;for(;Date.now()<a;){if(n.aborted)throw new Error("Aborted");try{let{data:c}=await this.api.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(c.status!==T.Pending)return c}catch(c){if(c instanceof Error&&c.message==="Aborted")throw c}await new Promise(c=>{let u=()=>{clearTimeout(m),c(void 0)};n.addEventListener("abort",u,{once:!0});let m=setTimeout(()=>{n.removeEventListener("abort",u),c(void 0)},2e3)})}throw new Error("Payment verification timed out.")}handleSuccess(e){let r=e.status===T.Success,t={success:r,status:r?"SUCCESS":"FAILED",orderId:e.orderId,errorCode:e.error?.code||(r?"":U.SystemUnknown),errorMessage:e.error?.message||(r?"":"Transaction failed without error details")};return e.transactionId&&(t.transactionId=e.transactionId),e.error?.referenceError&&(t.errorReference=e.error.referenceError),e.transaction&&(t.transaction=e.transaction),t}async cancelTransaction(e){if(!this.currentSessionId)return!1;try{let r=this.currentSessionId;return this.currentSessionId=null,await this.api.cancelVivaTransactionV2({cashRegisterId:this.config.storeId,sessionId:r}),this.abortController?.abort(),!0}catch(r){throw this.currentSessionId=null,new l("NETWORK_ERROR","Failed to cancel Viva transaction",r)}}async verifyFinalStatus(e,r){try{let{data:t}=await this.api.getPaymentStatus({businessId:Number(this.config.storeId),orderId:e.orderRef,provider:this.paymentProvider,referenceId:r}),n=t.status===T.Success,i=t.status===T.Pending,o={success:n,status:n?"SUCCESS":i?"PENDING":"FAILED",orderId:t.orderId,errorCode:t.error?.code||(n||i?"":U.SystemUnknown),errorMessage:t.error?.message||(n||i?"":"Transaction failed without error details")};return t.transactionId&&(o.transactionId=t.transactionId),t.error?.referenceError&&(o.errorReference=t.error.referenceError),t.transaction&&(o.transaction=t.transaction),o}catch(t){throw new l("NETWORK_ERROR","Failed to verify final transaction status",t)}}async refundTransaction(e,r){try{let t={amount:e.amountCents,businessId:Number(this.config.storeId),displayId:this.config.kioskId,currency:e.currency,orderReferenceId:e.orderRef,referenceId:e.originalTransactionId},{data:n}=await this.api.refundSingleVivaTransaction(t),i=n.success;return{success:i,status:i?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:n.sessionId}}catch(t){throw new l("NETWORK_ERROR","Failed to refund Viva transaction",t)}}abort(){this.abortController?.abort()}};import{PaymentApi as oe,PaymentEventType as k,PaymentFailureCode as ae,PaymentProviderEnum as ce,SimplePaymentStatus as v,WorldlineApi as le}from"@munchi_oy/core";import{isAxiosError as ue}from"axios";var A=class{constructor(e,r,t){this.messaging=r;this.config=t;this.paymentApi=new oe(void 0,"",e),this.worldlineApi=new le(void 0,"",e)}paymentApi;worldlineApi;abortController=null;currentOperationId=null;paymentProvider=ce.Worldline;async processPayment(e,r){this.abortController=new AbortController,r("CONNECTING");let t={amount:e.amountCents,businessId:Number(this.config.storeId),currency:e.currency,displayId:e.displayId,referenceId:e.orderRef,showReceipt:!0,showTransactionResult:!0,...e.options&&"tipAmount"in e.options&&typeof e.options.tipAmount=="number"?{tipAmount:e.options.tipAmount}:{}};try{let n=await this.worldlineApi.createPayment(t),i=this.extractOperationId(n.data);if(this.currentOperationId=i,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:i});let o=await this.waitForPaymentCompletion(i,e.orderRef,k.StatusChanged,this.abortController.signal);return this.currentOperationId=null,o}catch(n){throw this.currentOperationId=null,n instanceof l?n:this.mapWorldlineRequestError(n,"Failed to create Worldline payment")}}async cancelTransaction(e){if(!this.currentOperationId)return!1;let r={businessId:Number(this.config.storeId),targetOperationId:this.currentOperationId};try{return await this.worldlineApi.cancelPayment(r),!0}catch(t){throw this.mapWorldlineRequestError(t,"Failed to cancel Worldline transaction")}}async refundTransaction(e,r){this.abortController=new AbortController,r("CONNECTING");let t={amount:e.amountCents,businessId:Number(this.config.storeId),currency:e.currency,displayId:e.displayId,orderReferenceId:e.orderRef,referenceId:e.originalTransactionId};try{let n=await this.worldlineApi.createRefund(t),i=this.extractOperationId(n.data);if(this.currentOperationId=i,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:i});let o=await this.waitForPaymentCompletion(i,e.orderRef,k.RefundStatusChanged,this.abortController.signal);return this.currentOperationId=null,o}catch(n){throw this.currentOperationId=null,n instanceof l?n:this.mapWorldlineRequestError(n,"Failed to refund Worldline transaction")}}async verifyFinalStatus(e,r){try{let{data:t}=await this.paymentApi.getPaymentStatus({businessId:Number(this.config.storeId),orderId:e.orderRef,provider:this.paymentProvider,referenceId:r});return this.handlePaymentStatus(t)}catch(t){throw this.mapWorldlineRequestError(t,"Failed to verify final Worldline status")}}abort(){this.abortController?.abort()}async waitForPaymentCompletion(e,r,t,n){let i=`worldline.requests.${e}`;return new Promise((o,s)=>{let a=!1,c=()=>{a=!0,typeof m=="function"&&m(),clearTimeout(p)},u=()=>{c(),s(new l("CANCELLED","Transaction cancelled"))};n.addEventListener("abort",u);let m=this.messaging.subscribe(i,t,f=>{a||f.status===v.Pending||(c(),n.removeEventListener("abort",u),o(this.handlePaymentStatus(f)))}),p=setTimeout(async()=>{if(!(a||n.aborted))try{let f=await this.pollOrderStatus(e,r,this.config.storeId,n);o(this.handlePaymentStatus(f))}catch(f){s(new l("TIMEOUT","Payment timed out and polling failed",f))}finally{n.removeEventListener("abort",u),c()}},1e4)})}async pollOrderStatus(e,r,t,n){let s=Date.now()+12e4;for(;Date.now()<s;){if(n.aborted)throw new Error("Aborted");try{let{data:a}=await this.paymentApi.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(a.status!==v.Pending)return a}catch(a){if(a instanceof Error&&a.message==="Aborted")throw a}await new Promise(a=>{let c=()=>{clearTimeout(u),a(void 0)};n.addEventListener("abort",c,{once:!0});let u=setTimeout(()=>{n.removeEventListener("abort",c),a(void 0)},2e3)})}throw new Error("Payment verification timed out.")}handlePaymentStatus(e){let r=e.status===v.Success,t=e.status===v.Pending,n={success:r,status:r?"SUCCESS":t?"PENDING":"FAILED",orderId:e.orderId,errorCode:e.error?.code||(r||t?"":ae.SystemUnknown),errorMessage:e.error?.message||(r||t?"":"Transaction failed without error details")};return e.transactionId&&(n.transactionId=e.transactionId),e.error?.referenceError&&(n.errorReference=e.error.referenceError),e.transaction&&(n.transaction=e.transaction),n}extractOperationId(e){let r=typeof e=="object"&&e!==null&&"operationId"in e&&typeof e.operationId=="string"?e.operationId:null;if(!r)throw new Error("operationId is missing from response.");return r}mapWorldlineRequestError(e,r){if(ue(e)){if(e.response?.status===400||e.response?.status===409)return new l("TERMINAL_BUSY",r,e);if(e.response?.status===404)return new l("TERMINAL_OFFLINE",r,e)}return new l("NETWORK_ERROR",r,e)}};var _=class d{static VIVA_TIMEOUT_CANCEL_TIMEOUT_MS=5e3;strategy;axios;messaging;provider;timeoutMs;logger;_currentState="IDLE";_listeners=[];_cancellationIntent=!1;_currentSessionId;_autoResetTimer;autoResetOptions;appToAppConfig;static TERMINAL_STATES=["SUCCESS","FAILED","INTERNAL_ERROR"];static RESTING_STATES=["IDLE",...d.TERMINAL_STATES];constructor(e,r,t,n={},i){this.axios=e,this.messaging=r,this.provider=t.provider,this.logger=n.logger,this.timeoutMs=n.timeoutMs||3e4,this.autoResetOptions=n.autoResetOnPaymentComplete,this.appToAppConfig=n.appToApp,this.strategy=i??this.resolveStrategy(t)}get version(){return O}get currentState(){return this._currentState}generateErrorResult(e,r,t){return{success:!1,status:"ERROR",errorCode:this.normalizeErrorCode(r),errorMessage:t,orderId:e}}normalizeErrorCode(e){return e?e.includes(".")?e:{CANCELLED:y.PaymentCancelledByUser,DECLINED:y.PaymentDeclined,TERMINAL_BUSY:y.TerminalBusy,TERMINAL_OFFLINE:y.TerminalOffline,TIMEOUT:y.TerminalTimeout,NETWORK_ERROR:y.SystemProviderError,STRATEGY_ERROR:y.SystemProviderError,MISSING_CONFIG:y.SystemUnknown,INVALID_AMOUNT:y.SystemUnknown,UNKNOWN:y.SystemUnknown}[e]??y.SystemUnknown:y.SystemUnknown}subscribe=e=>(this._listeners.push(e),e(this._currentState),()=>{this._listeners=this._listeners.filter(r=>r!==e)});transitionTo(e){if(this._currentState===e)return;if(e==="IDLE"){this.cancelAutoReset(),this._currentState=e,this._listeners.forEach(t=>t(e));return}if(d.TERMINAL_STATES.includes(this._currentState)){let t=`Invalid State Transition: Attempted to move from terminal state ${this._currentState} to ${e}`;throw this.logger?.error(t),this._currentState!=="INTERNAL_ERROR"&&(this._currentState="INTERNAL_ERROR",this._listeners.forEach(n=>n(this._currentState))),new l("UNKNOWN",t)}this._currentState=e,d.TERMINAL_STATES.includes(e)&&this.scheduleAutoReset(e),this._listeners.forEach(t=>t(e))}_resetScheduledAt;get nextAutoResetAt(){return this._resetScheduledAt}cancelAutoReset(){this._autoResetTimer&&(clearTimeout(this._autoResetTimer),this._autoResetTimer=void 0),this._resetScheduledAt=void 0}scheduleAutoReset(e){if(!this.autoResetOptions)return;let t=e==="SUCCESS"?this.autoResetOptions.successDelayMs??5e3:this.autoResetOptions.failureDelayMs??5e3;this.logger?.info(`Scheduling auto-reset to IDLE in ${t}ms`),this._resetScheduledAt=Date.now()+t,this._autoResetTimer=setTimeout(()=>{this.logger?.info("Auto-reset triggered"),this.reset()},t)}resolveStrategy(e){switch(e.provider){case N.Nets:return new C(this.axios,this.messaging,e);case N.Worldline:return new A(this.axios,this.messaging,e);case N.Viva:return this.appToAppConfig?.enabled?new b(this.axios,this.messaging,e,this.appToAppConfig):new E(this.axios,this.messaging,e);default:return new E(this.axios,this.messaging,e)}}initiateTransaction=async(e,r)=>{let t=r??{},n=e.orderRef;if(!d.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");let o=Date.now();if(this._cancellationIntent=!1,this._currentSessionId=void 0,this.transitionTo("IDLE"),e.amountCents<=0)return this.generateErrorResult(e.orderRef,"INVALID_AMOUNT","Amount must be greater than 0");try{let s=(m,p)=>{p?.sessionId&&(this._currentSessionId=p.sessionId),m!=="FAILED"&&(this.transitionTo(m),this.fireStateCallback(m,t,n))},a=this.strategy.processPayment(e,s),u=(this.strategy.getExecutionMode?.()??"managed")==="callback_driven"?await a:await Promise.race([a,new Promise((m,p)=>{setTimeout(()=>{p(new l("TIMEOUT","Transaction timed out"))},this.timeoutMs)})]);if(u.success)this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(u));else{if(this._cancellationIntent)return await this.handleTransactionError(e,new Error("Aborted after resolution"),t);this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(u))}return this.logger?.info("Transaction completed successfully",{orderId:e.orderRef,durationMs:Date.now()-o}),u}catch(s){return this.logger?.warn("Transaction interrupted. Handling final status...",{error:s}),await this.handleTransactionError(e,s,t)}};async handleTransactionError(e,r,t={}){let n=r instanceof l&&r.code==="TIMEOUT";if(!this._cancellationIntent&&!n&&(this.transitionTo("VERIFYING"),this.safeFireCallback(()=>t.onVerifying?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId}))),this._cancellationIntent){try{if(this._currentSessionId){let s=await this.verifyWithRetry(e,this._currentSessionId);if(s.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(s)),s}}catch(s){this.logger?.warn("Final status verification failed during cancellation",{err:s})}return this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId})),{success:!1,status:"CANCELLED",errorCode:this.normalizeErrorCode("CANCELLED"),orderId:e.orderRef,...this._currentSessionId?{transactionId:this._currentSessionId}:{}}}let i,o=this._currentSessionId;if(n&&o&&this.provider===N.Viva&&!this.appToAppConfig?.enabled)try{let s=await this.recoverVivaTimeout(e,o);if(s.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(s)),s;i=s}catch(s){this.logger?.warn("Failed to get detailed error from verifyFinalStatus",{verifyErr:s}),i=this.buildErrorResultFromException(e.orderRef,s)}else if(o){this.strategy.abort();try{let s=await this.verifyWithRetry(e,o);if(s.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(s)),s;i=s}catch(s){this.logger?.warn("Failed to get detailed error from verifyFinalStatus",{verifyErr:s}),i=this.buildErrorResultFromException(e.orderRef,s)}}else this.strategy.abort(),i=this.buildErrorResultFromException(e.orderRef,r);return this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(i)),i}async recoverVivaTimeout(e,r){let t;try{await Promise.race([this.strategy.cancelTransaction(()=>{}),new Promise((n,i)=>{t=setTimeout(()=>{i(new Error("Viva timeout cancellation timed out"))},d.VIVA_TIMEOUT_CANCEL_TIMEOUT_MS)})])}catch(n){this.logger?.warn("Viva timeout cancellation attempt failed",{error:n})}finally{t&&clearTimeout(t),this.strategy.abort()}return await this.verifyWithRetry(e,r)}static VERIFY_TIMEOUT_MS=1e4;static VERIFY_MAX_RETRIES=3;static VERIFY_RETRY_DELAY_MS=1500;async verifyWithRetry(e,r){let t,n=!0;for(let s=1;s<=d.VERIFY_MAX_RETRIES;s++)try{let a=await Promise.race([this.strategy.verifyFinalStatus(e,r),new Promise((c,u)=>setTimeout(()=>u(new Error("Verify timed out")),d.VERIFY_TIMEOUT_MS))]);if(a.status==="PENDING"){t=new Error("Verify returned pending status"),this.logger?.warn(`verifyFinalStatus attempt ${s}/${d.VERIFY_MAX_RETRIES} returned pending status`),s<d.VERIFY_MAX_RETRIES&&await new Promise(c=>setTimeout(c,d.VERIFY_RETRY_DELAY_MS));continue}return a}catch(a){t=a,a instanceof Error&&a.message==="Verify timed out"||(n=!1),this.logger?.warn(`verifyFinalStatus attempt ${s}/${d.VERIFY_MAX_RETRIES} failed`,{err:a}),s<d.VERIFY_MAX_RETRIES&&await new Promise(u=>setTimeout(u,d.VERIFY_RETRY_DELAY_MS))}let i=t instanceof Error?t.message:"Verify retries exhausted",o=n?y.PaymentTimeout:y.PaymentUnknown;throw new l(o,i)}buildErrorResultFromException(e,r){return r instanceof l?this.generateErrorResult(e,r.code,r.message):this.generateErrorResult(e,"UNKNOWN",r instanceof Error?r.message:"Unknown fatal error")}fireStateCallback(e,r,t){let n={orderRef:t,refPaymentId:this._currentSessionId};switch(e){case"CONNECTING":this.safeFireCallback(()=>r.onConnecting?.(n));break;case"REQUIRES_INPUT":this.safeFireCallback(()=>r.onRequiresInput?.(n));break;case"PROCESSING":this.safeFireCallback(()=>r.onProcessing?.(n));break}}safeFireCallback(e){try{e()}catch(r){this.logger?.warn("Callback execution failed",{error:r})}}cancel=async()=>{if(this.logger?.info("Attempting cancellation"),d.TERMINAL_STATES.includes(this._currentState))return this.logger?.warn("Cannot cancel: Transaction already in terminal state",{state:this._currentState}),!1;if(!this._currentSessionId&&this._currentState==="IDLE")return this.logger?.warn("Cannot cancel: No active session to cancel",{state:this._currentState}),!1;this._cancellationIntent=!0,this.transitionTo("VERIFYING");try{return await this.strategy.cancelTransaction(r=>this.transitionTo(r))}catch(e){return this.logger?.error("Cancellation command failed",e),!1}};reset=()=>{d.TERMINAL_STATES.includes(this._currentState)&&(this._currentSessionId=void 0,this._cancellationIntent=!1,this.transitionTo("IDLE"))};refund=async(e,r)=>{let t=r??{};if(this.logger?.info("Initiating refund",{orderRef:e.orderRef}),this._currentSessionId=void 0,this._cancellationIntent=!1,!d.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");this.transitionTo("IDLE");try{let i=(s,a)=>{a?.sessionId&&(this._currentSessionId=a.sessionId),s!=="FAILED"&&(this.transitionTo(s),this.fireStateCallback(s,t,e.orderRef))},o=await this.strategy.refundTransaction(e,i);return o.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(o))):this._cancellationIntent||o.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId}))):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(o))),this.logger?.info("Refund completed",{success:o.success,orderRef:e.orderRef}),o}catch(i){if(this.logger?.error("Refund failed",i),this._cancellationIntent){try{if(this._currentSessionId){let s=await this.verifyWithRetry(e,this._currentSessionId);return s.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(s)),s):s.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId})),s):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(s)),s)}}catch(s){this.logger?.warn("Refund final status verification failed",{verifyError:s})}return this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId})),{success:!1,status:"CANCELLED",errorCode:this.normalizeErrorCode("CANCELLED"),orderId:e.orderRef,...this._currentSessionId?{transactionId:this._currentSessionId}:{}}}this.transitionTo("FAILED");let o=this.generateErrorResult(e.orderRef,"UNKNOWN",i instanceof Error?i.message:"Refund failed");return this.safeFireCallback(()=>t.onError?.(o)),o}}};var de=(n=>(n.CONNECTING="CONNECTING",n.CONNECTED="CONNECTED",n.OFFLINE="OFFLINE",n.DISCONNECTED="DISCONNECTED",n))(de||{});export{de as AppReaderStatus,_ as MunchiPaymentSDK,R as PaymentInteractionState,I as SdkPaymentStatus};
1
+ import{PaymentFailureCode as y,PaymentProvider as N}from"@munchi_oy/core";var O="1.5.11";var l=class d extends Error{code;rawError;constructor(e,r,t){super(r),this.name="PaymentSDKError",this.code=e,this.rawError=t,Object.setPrototypeOf(this,d.prototype)}};import{PaymentApi as W,PaymentEventType as G,PaymentProviderEnum as q,SimplePaymentStatus as D,TransactionType as L}from"@munchi_oy/core";var I=(o=>(o.PENDING="PENDING",o.SUCCESS="SUCCESS",o.APPROVED="APPROVED",o.FAILED="FAILED",o.CANCELLED="CANCELLED",o.ERROR="ERROR",o))(I||{}),R=(a=>(a.IDLE="IDLE",a.CONNECTING="CONNECTING",a.REQUIRES_INPUT="REQUIRES_INPUT",a.PROCESSING="PROCESSING",a.SUCCESS="SUCCESS",a.FAILED="FAILED",a.INTERNAL_ERROR="INTERNAL_ERROR",a.VERIFYING="VERIFYING",a))(R||{});var C=class{constructor(e,r,t){this.messaging=r;this.config=t;this.api=new W(void 0,"",e)}api;abortController=null;currentRequestId=null;paymentProvider=q.Nets;async processPayment(e,r){this.abortController=new AbortController,r("CONNECTING");let t={amount:e.amountCents,businessId:Number(this.config.storeId),referenceId:e.orderRef,currency:e.currency,displayId:e.displayId,options:{allowPinBypass:!0,transactionType:L.Purchase}};try{let{data:n}=await this.api.initiateNetsTerminalTransaction(t),i=n.connectCloudRequestId;if(!i)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=i,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:i});let o=await this.waitForPaymentCompletion(i,e.orderRef,this.abortController.signal);return this.currentRequestId=null,o}catch(n){throw this.currentRequestId=null,n instanceof l?n:new l("TERMINAL_BUSY","Failed to create Nets Intent",n)}}async waitForPaymentCompletion(e,r,t){let n=`nets.requests.${e}`,i=G.StatusChanged;return new Promise((o,s)=>{let a=!1,c=()=>{a=!0,typeof m=="function"&&m(),clearTimeout(p)},u=()=>{c(),s(new l("CANCELLED","Transaction cancelled"))};t.addEventListener("abort",u);let m=this.messaging.subscribe(n,i,f=>{a||(c(),t.removeEventListener("abort",u),o(this.handleSuccess(f)))}),p=setTimeout(async()=>{if(!(a||t.aborted))try{let f=await this.pollOrderStatus(e,r,this.config.storeId,t);o(this.handleSuccess(f))}catch(f){s(new l("TIMEOUT","Payment timed out and polling failed",f))}finally{t.removeEventListener("abort",u),c()}},1e4)})}async pollOrderStatus(e,r,t,n){let a=Date.now()+12e4;for(;Date.now()<a;){if(n.aborted)throw new Error("Aborted");try{let{data:c}=await this.api.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(c.status!==D.Pending)return c}catch(c){if(c instanceof Error&&c.message==="Aborted")throw c}await new Promise(c=>{let u=()=>{clearTimeout(m),c(void 0)};n.addEventListener("abort",u,{once:!0});let m=setTimeout(()=>{n.removeEventListener("abort",u),c(void 0)},2e3)})}throw new Error("Payment verification timed out.")}async cancelTransaction(e){if(!this.currentRequestId)return!1;let r={requestId:this.currentRequestId,businessId:Number(this.config.storeId)};try{return await this.api.cancelNetsTerminalTransaction(r),this.abortController?.abort(),this.currentRequestId=null,!0}catch{return!1}}async refundTransaction(e,r){try{this.abortController=new AbortController;let t={amount:e.amountCents,businessId:Number(this.config.storeId),currency:e.currency,displayId:this.config.kioskId,referenceId:e.orderRef,options:{allowPinBypass:!0,transactionType:L.ReturnOfGoods}},{data:n}=await this.api.initiateNetsTerminalTransaction(t),i=n.connectCloudRequestId;if(!i)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=i,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:i});let o=await this.waitForPaymentCompletion(i,e.orderRef,this.abortController.signal);return this.currentRequestId=null,o}catch(t){throw this.currentRequestId=null,t instanceof l||t instanceof l?t:new l("NETWORK_ERROR","Failed to refund Nets transaction",t)}}async verifyFinalStatus(e,r){try{let{data:t}=await this.api.getPaymentStatus({businessId:Number(this.config.storeId),orderId:e.orderRef,provider:this.paymentProvider,referenceId:r});return this.handleSuccess(t)}catch(t){throw new l("NETWORK_ERROR","Failed to verify final Nets status",t)}}handleSuccess(e){let r=e.status===D.Success,t={success:r,status:r?"SUCCESS":"FAILED",orderId:e.orderId,transaction:e.transaction};return e.transactionId&&(t.transactionId=e.transactionId),e.error?.code&&(t.errorCode=e.error.code),e.error?.message&&(t.errorMessage=e.error.message),t}abort(){this.abortController?.abort()}};import{FeeType as Y,PaymentApi as B,PaymentFailureCode as g,PaymentMethod as S,PaymentProvider as M,VivaApi as $}from"@munchi_oy/core";var w=d=>{if(!d)return 0;let e=Number.parseInt(d,10);return Number.isFinite(e)?e:0},F=d=>{if(!d)return new Date().toISOString();let e=new Date(d);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()};var j="vivapayclient://pay/v1",Q="abort",X="cancel",z="sale",x="transactionDetails",H=4e3,J="534287",Z="38",ee="493591",te="497439",re=[ee,te],ne=["CREDIT","PREPAID","CORPORATE"],b=class{constructor(e,r,t,n){this.config=t;this.appToAppConfig=n;this.api=new $(void 0,"",e),this.paymentApi=new B(void 0,"",e),this.paymentApiWithReference=this.paymentApi}api;paymentApi;abortController=null;currentClientTransactionId=null;currentIsvClientTransactionId=null;currentCurrency=null;currentOrderRef=null;currentSourceTerminalId=null;latestResult=null;paymentApiWithReference;wasCancelled=!1;getExecutionMode(){return"callback_driven"}async processPayment(e,r){if(!this.appToAppConfig.enabled)throw new l("STRATEGY_ERROR","Viva app-to-app is not enabled");r("CONNECTING");try{let{data:t}=await this.api.createVivaAppToAppPayment(this.buildCreatePaymentPayload(e));return await this.runAction(z,this.buildLaunchParams(t),e,r)}catch(t){throw new l("NETWORK_ERROR","Failed to create Viva app-to-app payment",t)}}async cancelTransaction(e){if(!this.currentClientTransactionId)return!1;let r=await this.lookupTransactionDetails();if(r)return this.latestResult=r,this.wasCancelled=r.status==="CANCELLED",this.abortController?.abort(),!0;try{await this.appToAppConfig.adapter.openUrl(this.buildActionUrl(Q,{}))}catch(t){throw this.abortController?.abort(),new l("NETWORK_ERROR","Failed to launch Viva abort flow",t)}return this.wasCancelled=!0,this.abortController?.abort(),!0}async refundTransaction(e,r){r("CONNECTING");let t=await this.fetchPaymentReference(e),n=this.buildRefundLaunchParams(e,t);return this.runAction(X,n,e,r)}async verifyFinalStatus(e,r){return this.latestResult?this.latestResult:this.wasCancelled?{success:!1,status:"CANCELLED",orderId:this.currentOrderRef??r,errorCode:g.PaymentCancelledByUser,errorMessage:"Transaction was cancelled",transactionId:r}:{success:!1,status:"PENDING",orderId:this.currentOrderRef??r,transactionId:r}}abort(){this.abortController?.abort()}async runAction(e,r,t,n){if(!this.appToAppConfig.enabled)throw new l("STRATEGY_ERROR","Viva app-to-app is not enabled");this.abortController=new AbortController,this.latestResult=null,this.wasCancelled=!1,this.currentCurrency=t.currency,this.currentOrderRef=t.orderRef,this.currentSourceTerminalId=r.sourceTerminalId??r.tid??null,this.currentClientTransactionId=r.clientTransactionId??null,this.currentIsvClientTransactionId=r.ISV_clientTransactionId??null;let i=this.currentClientTransactionId?{sessionId:this.currentClientTransactionId}:void 0;return new Promise((o,s)=>{let a=(m,p)=>{m?.(),this.abortController?.signal.removeEventListener("abort",p)},c=()=>{a(u,c),s(new Error("Aborted"))},u=this.appToAppConfig.adapter.subscribe(m=>{if(this.abortController?.signal.aborted)return;let p=this.parseCallbackUrl(m);p&&this.matchesKnownTransactionId(p.rawParams)&&(this.latestResult=p.result,this.wasCancelled=p.result.status==="CANCELLED",this.currentClientTransactionId=null,this.currentIsvClientTransactionId=null,this.currentCurrency=null,this.currentOrderRef=null,this.currentSourceTerminalId=null,a(u,c),o(p.result))});this.abortController?.signal.addEventListener("abort",c),n("REQUIRES_INPUT",i),this.appToAppConfig.adapter.openUrl(this.buildActionUrl(e,r)).then(()=>{this.abortController?.signal.aborted}).catch(m=>{a(u,c),this.currentClientTransactionId=null,this.currentIsvClientTransactionId=null,this.currentCurrency=null,this.currentOrderRef=null,this.currentSourceTerminalId=null,s(new l("NETWORK_ERROR","Failed to launch Viva app",m))})})}buildCreatePaymentPayload(e){let r=e.options??{},t={amount:e.amountCents,referenceId:e.orderRef,businessId:Number(this.config.storeId),currency:e.currency,displayId:e.displayId,showReceipt:!0,showTransactionResult:!0};return r.tipAmount!==void 0&&(t.tipAmount=r.tipAmount),t}buildLaunchParams(e){let r={};return Object.entries(e).forEach(([t,n])=>{n!==void 0&&(r[t]=String(n))}),r}buildRefundLaunchParams(e,r){let t=e.options??{},n=r?.originalTransactionId?.trim()||e.originalTransactionId.trim(),i={amount:String(e.amountCents),clientTransactionId:n,show_receipt:"true",show_transaction_result:"true"};if(t.sourceCode&&(i.sourceCode=t.sourceCode),r?.referenceCode&&(i.orderCode=r.referenceCode),r?.shortReferenceCode&&(i.shortOrderCode=r.shortReferenceCode),r?.receiptNumber&&(i.referenceNumber=r.receiptNumber),r?.terminalId&&(i.tid=r.terminalId),r?.referenceCode||r?.shortReferenceCode||r?.receiptNumber)return i;let o=n;return/^\d+$/.test(o)&&(o.length===16?i.orderCode=o:o.length===10?i.shortOrderCode=o:i.referenceNumber=o),i}async fetchPaymentReference(e){try{let{data:r}=await this.paymentApiWithReference.getPaymentReference({orderId:e.orderRef,provider:M.Viva,transactionId:e.originalTransactionId});return this.extractPaymentReferenceContext(r)}catch{return}}extractPaymentReferenceContext(e){if(!e)return;let r=e.references;if(!r||typeof r!="object"||Array.isArray(r))return{originalTransactionId:e.originalTransactionId};let t=r,n={originalTransactionId:this.readReferenceValue(t.originalTransactionId)??this.readReferenceValue(t.clientTransactionId)??e.originalTransactionId},i=this.readReferenceValue(t.receiptNumber)??this.readReferenceValue(t.referenceNumber),o=this.readReferenceValue(t.referenceCode)??this.readReferenceValue(t.orderCode),s=this.readReferenceValue(t.shortReferenceCode)??this.readReferenceValue(t.shortOrderCode),a=this.readReferenceValue(t.terminalId)??this.readReferenceValue(t.tid);return i&&(n.receiptNumber=i),o&&(n.referenceCode=o),s&&(n.shortReferenceCode=s),a&&(n.terminalId=a),n}readReferenceValue(e){if(typeof e!="string")return;let r=e.trim();return r.length>0?r:void 0}buildActionUrl(e,r){let t=new URLSearchParams({action:e,appId:this.appToAppConfig.appId,callback:this.appToAppConfig.callbackUrl});return Object.entries(r).forEach(([n,i])=>{t.set(n,i)}),`${j}?${t.toString()}`}parseCallbackUrl(e){if(!this.matchesCallbackBase(e))return null;let r=new URL(e),t=Object.fromEntries(r.searchParams.entries()),n=this.isSuccessfulCallback(t),i=this.isCancelledCallback(t),o=this.resolveFailureCode(t,i),s={success:n,status:n?"SUCCESS":i?"CANCELLED":"FAILED",orderId:this.currentOrderRef??t.clientTransactionId??"unknown",errorCode:n?"":o,errorMessage:n?"":t.message??"Transaction failed without error details"};n&&(s.transaction=this.mapCallbackToTransaction(t));let a=t.transactionId??t.orderCode??t.clientTransactionId,c=t.errorCode??this.extractErrorReferenceFromMessage(t.message)??t.referenceNumber??t.tid??t.rrn;return a&&(s.transactionId=a),c&&(s.errorReference=c),{rawParams:t,result:s}}matchesCallbackBase(e){let r=new URL(e),t=new URL(this.appToAppConfig.callbackUrl);return r.protocol===t.protocol&&r.hostname===t.hostname&&r.pathname===t.pathname}matchesKnownTransactionId(e){let r=[this.currentClientTransactionId,this.currentIsvClientTransactionId].filter(n=>!!n);if(r.length===0)return!0;let t=[e.clientTransactionId,e.ISV_clientTransactionId].filter(n=>!!n);return t.length===0?!0:t.some(n=>r.includes(n))}resolveFailureCode(e,r){if(r)return g.PaymentCancelledByUser;let t=e.errorCode;if(t?.includes("."))return t;if(this.isTransactionDetailsAction(e)&&(e.transactionType??"").toLowerCase().includes("abort"))return g.SystemUnknown;let n=(e.message??"").toLowerCase(),i=(e.status??"").toLowerCase();return n.includes("declined")||i==="declined"||i==="fail"||i==="failed"?g.PaymentDeclined:g.SystemUnknown}isSuccessfulCallback(e){let r=(e.status??"").toLowerCase();return this.isTransactionDetailsAction(e)?r!=="success"?!1:!(e.transactionType??"").toLowerCase().includes("abort"):r==="success"}isTransactionDetailsAction(e){return(e.action??"").toLowerCase()===x.toLowerCase()}isCancelledCallback(e){let r=(e.status??"").toLowerCase(),t=(e.message??"").toLowerCase(),n=(e.errorCode??"").toLowerCase();return r==="cancelled"||r==="canceled"||t.includes("user_cancel")||t.includes("user cancel")||n.includes("user_cancel")||n.includes("user cancel")}extractErrorReferenceFromMessage(e){return e?e.match(/\((-?\d+)\)/)?.[1]:void 0}mapCallbackToTransaction(e){let r=e.transactionId??e.orderCode??e.clientTransactionId??"unknown",t=F(e.transactionDate),n=w(e.amount),i=w(e.tipAmount);return{amount:n,cardDetail:{aid:e.aid??null,applicationLabel:e.applicationLabel??null,cardNumber:e.accountNumber??"N/A",cardType:e.cardType??"N/A",issuer:e.bankId??null,orderCode:e.orderCode??null,timestamp:t,transactionId:r},createdAt:t,fees:this.buildFeesFromTip(i),id:r,label:null,provider:M.Viva,rawData:e,referenceId:e.clientTransactionId??null,roundingDifference:0,type:this.getVivaPaymentMethodType(e)}}getVivaPaymentMethodType(e){let r=(e.applicationLabel??"").toUpperCase().trim(),n=(e.accountNumber??"").substring(0,6),i=(e.bankId??"").trim();return n===J||i===Z?S.Edenred:re.includes(n)?S.WoltBenefit:ne.some(o=>r.includes(o))?S.Credit:S.Debit}buildFeesFromTip(e){return!e||!this.currentCurrency?null:{parts:[{taxAmount:0,total:{amount:e,currency:this.currentCurrency},type:Y.TipAmount,vatPercentage:0}]}}async lookupTransactionDetails(){if(!this.currentClientTransactionId||!this.currentSourceTerminalId)return null;let e={clientTransactionId:this.currentClientTransactionId,sourceTerminalId:this.currentSourceTerminalId};return new Promise(r=>{let t=!1,n=setTimeout(()=>{t||(t=!0,i(),r(null))},H),i=this.appToAppConfig.adapter.subscribe(o=>{if(t)return;let s=this.parseCallbackUrl(o);s&&this.matchesKnownTransactionId(s.rawParams)&&(t=!0,clearTimeout(n),i(),r(s.result))});this.appToAppConfig.adapter.openUrl(this.buildActionUrl(x,e)).catch(()=>{t||(t=!0,clearTimeout(n),i(),r(null))})})}};import{PaymentApi as ie,PaymentFailureCode as U,PaymentProviderEnum as se,SimplePaymentStatus as T}from"@munchi_oy/core";var E=class{constructor(e,r,t){this.messaging=r;this.config=t;this.api=new ie(void 0,"",e)}api;abortController=null;currentSessionId=null;paymentProvider=se.Viva;async processPayment(e,r){this.abortController=new AbortController,r("CONNECTING");let t={amount:e.amountCents,referenceId:e.orderRef,businessId:parseInt(this.config.storeId),currency:e.currency,displayId:e.displayId,showReceipt:!0,showTransactionResult:!0};try{let{data:n}=await this.api.initiateTerminalTransaction(t);if(this.currentSessionId=n.sessionId,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:n.sessionId});let i=await this.waitForPaymentCompletion(n.sessionId,e.orderRef,this.abortController.signal);return this.currentSessionId=null,i}catch(n){throw this.currentSessionId=null,n instanceof l?n:new l("NETWORK_ERROR","Failed to create Viva Intent",n)}}async waitForPaymentCompletion(e,r,t){let i=`viva.${this.config.channel.toLowerCase()}.requests.${e}`,o="payment:status-changed";return new Promise((s,a)=>{let c=!1,u=()=>{c=!0,typeof p=="function"&&p(),clearTimeout(f)},m=()=>{u(),a(new Error("Aborted"))};t.addEventListener("abort",m);let p=this.messaging.subscribe(i,o,h=>{c||h.status!==T.Pending&&(u(),t.removeEventListener("abort",m),s(this.handleSuccess(h)))}),f=setTimeout(async()=>{if(!(c||t.aborted))try{let h=await this.pollOrderStatus(e,r,this.config.storeId,t);s(this.handleSuccess(h))}catch(h){a(new l("TIMEOUT","Payment timed out and polling failed",h))}finally{t.removeEventListener("abort",m),u()}},1e4)})}async pollOrderStatus(e,r,t,n){let a=Date.now()+12e4;for(;Date.now()<a;){if(n.aborted)throw new Error("Aborted");try{let{data:c}=await this.api.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(c.status!==T.Pending)return c}catch(c){if(c instanceof Error&&c.message==="Aborted")throw c}await new Promise(c=>{let u=()=>{clearTimeout(m),c(void 0)};n.addEventListener("abort",u,{once:!0});let m=setTimeout(()=>{n.removeEventListener("abort",u),c(void 0)},2e3)})}throw new Error("Payment verification timed out.")}handleSuccess(e){let r=e.status===T.Success,t={success:r,status:r?"SUCCESS":"FAILED",orderId:e.orderId,errorCode:e.error?.code||(r?"":U.SystemUnknown),errorMessage:e.error?.message||(r?"":"Transaction failed without error details")};return e.transactionId&&(t.transactionId=e.transactionId),e.error?.referenceError&&(t.errorReference=e.error.referenceError),e.transaction&&(t.transaction=e.transaction),t}async cancelTransaction(e){if(!this.currentSessionId)return!1;try{let r=this.currentSessionId;return this.currentSessionId=null,await this.api.cancelVivaTransactionV2({cashRegisterId:this.config.storeId,sessionId:r}),this.abortController?.abort(),!0}catch(r){throw this.currentSessionId=null,new l("NETWORK_ERROR","Failed to cancel Viva transaction",r)}}async verifyFinalStatus(e,r){try{let{data:t}=await this.api.getPaymentStatus({businessId:Number(this.config.storeId),orderId:e.orderRef,provider:this.paymentProvider,referenceId:r}),n=t.status===T.Success,i=t.status===T.Pending,o={success:n,status:n?"SUCCESS":i?"PENDING":"FAILED",orderId:t.orderId,errorCode:t.error?.code||(n||i?"":U.SystemUnknown),errorMessage:t.error?.message||(n||i?"":"Transaction failed without error details")};return t.transactionId&&(o.transactionId=t.transactionId),t.error?.referenceError&&(o.errorReference=t.error.referenceError),t.transaction&&(o.transaction=t.transaction),o}catch(t){throw new l("NETWORK_ERROR","Failed to verify final transaction status",t)}}async refundTransaction(e,r){try{let t={amount:e.amountCents,businessId:Number(this.config.storeId),displayId:this.config.kioskId,currency:e.currency,orderReferenceId:e.orderRef,referenceId:e.originalTransactionId},{data:n}=await this.api.refundSingleVivaTransaction(t),i=n.success;return{success:i,status:i?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:n.sessionId}}catch(t){throw new l("NETWORK_ERROR","Failed to refund Viva transaction",t)}}abort(){this.abortController?.abort()}};import{PaymentApi as oe,PaymentEventType as k,PaymentFailureCode as ae,PaymentProviderEnum as ce,SimplePaymentStatus as v,WorldlineApi as le}from"@munchi_oy/core";import{isAxiosError as ue}from"axios";var A=class{constructor(e,r,t){this.messaging=r;this.config=t;this.paymentApi=new oe(void 0,"",e),this.worldlineApi=new le(void 0,"",e)}paymentApi;worldlineApi;abortController=null;currentOperationId=null;paymentProvider=ce.Worldline;async processPayment(e,r){this.abortController=new AbortController,r("CONNECTING");let t={amount:e.amountCents,businessId:Number(this.config.storeId),currency:e.currency,displayId:e.displayId,referenceId:e.orderRef,showReceipt:!0,showTransactionResult:!0,...e.options&&"tipAmount"in e.options&&typeof e.options.tipAmount=="number"?{tipAmount:e.options.tipAmount}:{}};try{let n=await this.worldlineApi.createPayment(t),i=this.extractOperationId(n.data);if(this.currentOperationId=i,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:i});let o=await this.waitForPaymentCompletion(i,e.orderRef,k.StatusChanged,this.abortController.signal);return this.currentOperationId=null,o}catch(n){throw this.currentOperationId=null,n instanceof l?n:this.mapWorldlineRequestError(n,"Failed to create Worldline payment")}}async cancelTransaction(e){if(!this.currentOperationId)return!1;let r={businessId:Number(this.config.storeId),targetOperationId:this.currentOperationId};try{return await this.worldlineApi.cancelPayment(r),!0}catch(t){throw this.mapWorldlineRequestError(t,"Failed to cancel Worldline transaction")}}async refundTransaction(e,r){this.abortController=new AbortController,r("CONNECTING");let t={amount:e.amountCents,businessId:Number(this.config.storeId),currency:e.currency,displayId:e.displayId,orderReferenceId:e.orderRef,referenceId:e.originalTransactionId};try{let n=await this.worldlineApi.createRefund(t),i=this.extractOperationId(n.data);if(this.currentOperationId=i,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:i});let o=await this.waitForPaymentCompletion(i,e.orderRef,k.RefundStatusChanged,this.abortController.signal);return this.currentOperationId=null,o}catch(n){throw this.currentOperationId=null,n instanceof l?n:this.mapWorldlineRequestError(n,"Failed to refund Worldline transaction")}}async verifyFinalStatus(e,r){try{let{data:t}=await this.paymentApi.getPaymentStatus({businessId:Number(this.config.storeId),orderId:e.orderRef,provider:this.paymentProvider,referenceId:r});return this.handlePaymentStatus(t)}catch(t){throw this.mapWorldlineRequestError(t,"Failed to verify final Worldline status")}}abort(){this.abortController?.abort()}async waitForPaymentCompletion(e,r,t,n){let i=`worldline.requests.${e}`;return new Promise((o,s)=>{let a=!1,c=()=>{a=!0,typeof m=="function"&&m(),clearTimeout(p)},u=()=>{c(),s(new l("CANCELLED","Transaction cancelled"))};n.addEventListener("abort",u);let m=this.messaging.subscribe(i,t,f=>{a||f.status===v.Pending||(c(),n.removeEventListener("abort",u),o(this.handlePaymentStatus(f)))}),p=setTimeout(async()=>{if(!(a||n.aborted))try{let f=await this.pollOrderStatus(e,r,this.config.storeId,n);o(this.handlePaymentStatus(f))}catch(f){s(new l("TIMEOUT","Payment timed out and polling failed",f))}finally{n.removeEventListener("abort",u),c()}},1e4)})}async pollOrderStatus(e,r,t,n){let s=Date.now()+12e4;for(;Date.now()<s;){if(n.aborted)throw new Error("Aborted");try{let{data:a}=await this.paymentApi.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(a.status!==v.Pending)return a}catch(a){if(a instanceof Error&&a.message==="Aborted")throw a}await new Promise(a=>{let c=()=>{clearTimeout(u),a(void 0)};n.addEventListener("abort",c,{once:!0});let u=setTimeout(()=>{n.removeEventListener("abort",c),a(void 0)},2e3)})}throw new Error("Payment verification timed out.")}handlePaymentStatus(e){let r=e.status===v.Success,t=e.status===v.Pending,n={success:r,status:r?"SUCCESS":t?"PENDING":"FAILED",orderId:e.orderId,errorCode:e.error?.code||(r||t?"":ae.SystemUnknown),errorMessage:e.error?.message||(r||t?"":"Transaction failed without error details")};return e.transactionId&&(n.transactionId=e.transactionId),e.error?.referenceError&&(n.errorReference=e.error.referenceError),e.transaction&&(n.transaction=e.transaction),n}extractOperationId(e){let r=typeof e=="object"&&e!==null&&"operationId"in e&&typeof e.operationId=="string"?e.operationId:null;if(!r)throw new Error("operationId is missing from response.");return r}mapWorldlineRequestError(e,r){if(ue(e)){if(e.response?.status===400||e.response?.status===409)return new l("TERMINAL_BUSY",r,e);if(e.response?.status===404)return new l("TERMINAL_OFFLINE",r,e)}return new l("NETWORK_ERROR",r,e)}};var _=class d{static VIVA_TIMEOUT_CANCEL_TIMEOUT_MS=5e3;strategy;axios;messaging;provider;timeoutMs;logger;_currentState="IDLE";_listeners=[];_cancellationIntent=!1;_currentSessionId;_autoResetTimer;autoResetOptions;appToAppConfig;static TERMINAL_STATES=["SUCCESS","FAILED","INTERNAL_ERROR"];static RESTING_STATES=["IDLE",...d.TERMINAL_STATES];constructor(e,r,t,n={},i){this.axios=e,this.messaging=r,this.provider=t.provider,this.logger=n.logger,this.timeoutMs=n.timeoutMs||3e4,this.autoResetOptions=n.autoResetOnPaymentComplete,this.appToAppConfig=n.appToApp,this.strategy=i??this.resolveStrategy(t)}get version(){return O}get currentState(){return this._currentState}generateErrorResult(e,r,t){return{success:!1,status:"ERROR",errorCode:this.normalizeErrorCode(r),errorMessage:t,orderId:e}}normalizeErrorCode(e){return e?e.includes(".")?e:{CANCELLED:y.PaymentCancelledByUser,DECLINED:y.PaymentDeclined,TERMINAL_BUSY:y.TerminalBusy,TERMINAL_OFFLINE:y.TerminalOffline,TIMEOUT:y.TerminalTimeout,NETWORK_ERROR:y.SystemProviderError,STRATEGY_ERROR:y.SystemProviderError,MISSING_CONFIG:y.SystemUnknown,INVALID_AMOUNT:y.SystemUnknown,UNKNOWN:y.SystemUnknown}[e]??y.SystemUnknown:y.SystemUnknown}subscribe=e=>(this._listeners.push(e),e(this._currentState),()=>{this._listeners=this._listeners.filter(r=>r!==e)});transitionTo(e){if(this._currentState===e)return;if(e==="IDLE"){this.cancelAutoReset(),this._currentState=e,this._listeners.forEach(t=>t(e));return}if(d.TERMINAL_STATES.includes(this._currentState)){let t=`Invalid State Transition: Attempted to move from terminal state ${this._currentState} to ${e}`;throw this.logger?.error(t),this._currentState!=="INTERNAL_ERROR"&&(this._currentState="INTERNAL_ERROR",this._listeners.forEach(n=>n(this._currentState))),new l("UNKNOWN",t)}this._currentState=e,d.TERMINAL_STATES.includes(e)&&this.scheduleAutoReset(e),this._listeners.forEach(t=>t(e))}_resetScheduledAt;get nextAutoResetAt(){return this._resetScheduledAt}cancelAutoReset(){this._autoResetTimer&&(clearTimeout(this._autoResetTimer),this._autoResetTimer=void 0),this._resetScheduledAt=void 0}scheduleAutoReset(e){if(!this.autoResetOptions)return;let t=e==="SUCCESS"?this.autoResetOptions.successDelayMs??5e3:this.autoResetOptions.failureDelayMs??5e3;this.logger?.info(`Scheduling auto-reset to IDLE in ${t}ms`),this._resetScheduledAt=Date.now()+t,this._autoResetTimer=setTimeout(()=>{this.logger?.info("Auto-reset triggered"),this.reset()},t)}resolveStrategy(e){switch(e.provider){case N.Nets:return new C(this.axios,this.messaging,e);case N.Worldline:return new A(this.axios,this.messaging,e);case N.Viva:return this.appToAppConfig?.enabled?new b(this.axios,this.messaging,e,this.appToAppConfig):new E(this.axios,this.messaging,e);default:return new E(this.axios,this.messaging,e)}}initiateTransaction=async(e,r)=>{let t=r??{},n=e.orderRef;if(!d.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");let o=Date.now();if(this._cancellationIntent=!1,this._currentSessionId=void 0,this.transitionTo("IDLE"),e.amountCents<=0)return this.generateErrorResult(e.orderRef,"INVALID_AMOUNT","Amount must be greater than 0");try{let s=(m,p)=>{p?.sessionId&&(this._currentSessionId=p.sessionId),m!=="FAILED"&&(this.transitionTo(m),this.fireStateCallback(m,t,n))},a=this.strategy.processPayment(e,s),u=(this.strategy.getExecutionMode?.()??"managed")==="callback_driven"?await a:await Promise.race([a,new Promise((m,p)=>{setTimeout(()=>{p(new l("TIMEOUT","Transaction timed out"))},this.timeoutMs)})]);if(u.success)this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(u));else{if(this._cancellationIntent)return await this.handleTransactionError(e,new Error("Aborted after resolution"),t);this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(u))}return this.logger?.info("Transaction completed successfully",{orderId:e.orderRef,durationMs:Date.now()-o}),u}catch(s){return this.logger?.warn("Transaction interrupted. Handling final status...",{error:s}),await this.handleTransactionError(e,s,t)}};async handleTransactionError(e,r,t={}){let n=r instanceof l&&r.code==="TIMEOUT";if(!this._cancellationIntent&&!n&&(this.transitionTo("VERIFYING"),this.safeFireCallback(()=>t.onVerifying?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId}))),this._cancellationIntent){try{if(this._currentSessionId){let s=await this.verifyWithRetry(e,this._currentSessionId);if(s.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(s)),s}}catch(s){this.logger?.warn("Final status verification failed during cancellation",{err:s})}return this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId})),{success:!1,status:"CANCELLED",errorCode:this.normalizeErrorCode("CANCELLED"),orderId:e.orderRef,...this._currentSessionId?{transactionId:this._currentSessionId}:{}}}let i,o=this._currentSessionId;if(n&&o&&this.provider===N.Viva&&!this.appToAppConfig?.enabled)try{let s=await this.recoverVivaTimeout(e,o);if(s.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(s)),s;i=s}catch(s){this.logger?.warn("Failed to get detailed error from verifyFinalStatus",{verifyErr:s}),i=this.buildErrorResultFromException(e.orderRef,s)}else if(o){this.strategy.abort();try{let s=await this.verifyWithRetry(e,o);if(s.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(s)),s;i=s}catch(s){this.logger?.warn("Failed to get detailed error from verifyFinalStatus",{verifyErr:s}),i=this.buildErrorResultFromException(e.orderRef,s)}}else this.strategy.abort(),i=this.buildErrorResultFromException(e.orderRef,r);return this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(i)),i}async recoverVivaTimeout(e,r){let t;try{await Promise.race([this.strategy.cancelTransaction(()=>{}),new Promise((n,i)=>{t=setTimeout(()=>{i(new Error("Viva timeout cancellation timed out"))},d.VIVA_TIMEOUT_CANCEL_TIMEOUT_MS)})])}catch(n){this.logger?.warn("Viva timeout cancellation attempt failed",{error:n})}finally{t&&clearTimeout(t),this.strategy.abort()}return await this.verifyWithRetry(e,r)}static VERIFY_TIMEOUT_MS=1e4;static VERIFY_MAX_RETRIES=3;static VERIFY_RETRY_DELAY_MS=1500;async verifyWithRetry(e,r){let t,n=!0;for(let s=1;s<=d.VERIFY_MAX_RETRIES;s++)try{let a=await Promise.race([this.strategy.verifyFinalStatus(e,r),new Promise((c,u)=>setTimeout(()=>u(new Error("Verify timed out")),d.VERIFY_TIMEOUT_MS))]);if(a.status==="PENDING"){t=new Error("Verify returned pending status"),this.logger?.warn(`verifyFinalStatus attempt ${s}/${d.VERIFY_MAX_RETRIES} returned pending status`),s<d.VERIFY_MAX_RETRIES&&await new Promise(c=>setTimeout(c,d.VERIFY_RETRY_DELAY_MS));continue}return a}catch(a){t=a,a instanceof Error&&a.message==="Verify timed out"||(n=!1),this.logger?.warn(`verifyFinalStatus attempt ${s}/${d.VERIFY_MAX_RETRIES} failed`,{err:a}),s<d.VERIFY_MAX_RETRIES&&await new Promise(u=>setTimeout(u,d.VERIFY_RETRY_DELAY_MS))}let i=t instanceof Error?t.message:"Verify retries exhausted",o=n?y.PaymentTimeout:y.PaymentUnknown;throw new l(o,i)}buildErrorResultFromException(e,r){return r instanceof l?this.generateErrorResult(e,r.code,r.message):this.generateErrorResult(e,"UNKNOWN",r instanceof Error?r.message:"Unknown fatal error")}fireStateCallback(e,r,t){let n={orderRef:t,refPaymentId:this._currentSessionId};switch(e){case"CONNECTING":this.safeFireCallback(()=>r.onConnecting?.(n));break;case"REQUIRES_INPUT":this.safeFireCallback(()=>r.onRequiresInput?.(n));break;case"PROCESSING":this.safeFireCallback(()=>r.onProcessing?.(n));break}}safeFireCallback(e){try{e()}catch(r){this.logger?.warn("Callback execution failed",{error:r})}}cancel=async()=>{if(this.logger?.info("Attempting cancellation"),d.TERMINAL_STATES.includes(this._currentState))return this.logger?.warn("Cannot cancel: Transaction already in terminal state",{state:this._currentState}),!1;if(!this._currentSessionId&&this._currentState==="IDLE")return this.logger?.warn("Cannot cancel: No active session to cancel",{state:this._currentState}),!1;this._cancellationIntent=!0,this.transitionTo("VERIFYING");try{return await this.strategy.cancelTransaction(r=>this.transitionTo(r))}catch(e){return this.logger?.error("Cancellation command failed",e),!1}};reset=()=>{d.TERMINAL_STATES.includes(this._currentState)&&(this._currentSessionId=void 0,this._cancellationIntent=!1,this.transitionTo("IDLE"))};refund=async(e,r)=>{let t=r??{};if(this.logger?.info("Initiating refund",{orderRef:e.orderRef}),this._currentSessionId=void 0,this._cancellationIntent=!1,!d.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");this.transitionTo("IDLE");try{let i=(s,a)=>{a?.sessionId&&(this._currentSessionId=a.sessionId),s!=="FAILED"&&(this.transitionTo(s),this.fireStateCallback(s,t,e.orderRef))},o=await this.strategy.refundTransaction(e,i);return o.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(o))):this._cancellationIntent||o.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId}))):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(o))),this.logger?.info("Refund completed",{success:o.success,orderRef:e.orderRef}),o}catch(i){if(this.logger?.error("Refund failed",i),this._cancellationIntent){try{if(this._currentSessionId){let s=await this.verifyWithRetry(e,this._currentSessionId);return s.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(s)),s):s.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId})),s):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(s)),s)}}catch(s){this.logger?.warn("Refund final status verification failed",{verifyError:s})}return this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId})),{success:!1,status:"CANCELLED",errorCode:this.normalizeErrorCode("CANCELLED"),orderId:e.orderRef,...this._currentSessionId?{transactionId:this._currentSessionId}:{}}}this.transitionTo("FAILED");let o=this.generateErrorResult(e.orderRef,"UNKNOWN",i instanceof Error?i.message:"Refund failed");return this.safeFireCallback(()=>t.onError?.(o)),o}}};var de=(n=>(n.CONNECTING="CONNECTING",n.CONNECTED="CONNECTED",n.OFFLINE="OFFLINE",n.DISCONNECTED="DISCONNECTED",n))(de||{});export{de as AppReaderStatus,_ as MunchiPaymentSDK,R as PaymentInteractionState,I as SdkPaymentStatus};
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "1.5.10";
1
+ export declare const VERSION = "1.5.11";
2
2
  //# sourceMappingURL=version.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@munchi_oy/payments",
3
- "version": "1.5.10",
3
+ "version": "1.5.11",
4
4
  "description": "Munchi Payments SDK - Payment processing utilities",
5
5
  "license": "UNLICENSED",
6
6
  "publishConfig": {
package/src/version.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  // This file is auto-generated. Do not edit manually.
2
2
  // Run 'pnpm version:sync' to update this file.
3
- export const VERSION = "1.5.10";
3
+ export const VERSION = "1.5.11";