@munchi_oy/payments 1.10.4 → 1.10.5

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 x=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var B=(a,e)=>{for(var r in e)x(a,r,{get:e[r],enumerable:!0})},$=(a,e,r,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of q(e))!Y.call(a,n)&&n!==r&&x(a,n,{get:()=>e[n],enumerable:!(t=K(e,n))||t.enumerable});return a};var Q=a=>$(x({},"__esModule",{value:!0}),a);var ae={};B(ae,{AppReaderStatus:()=>G,MunchiPaymentSDK:()=>F,PaymentInteractionState:()=>C,SdkPaymentStatus:()=>T});module.exports=Q(ae);var I=require("@munchi_oy/core");var M="1.10.4";var l=class a extends Error{code;rawError;constructor(e,r,t){super(r),this.name="PaymentSDKError",this.code=e,this.rawError=t,Object.setPrototypeOf(this,a.prototype)}};var R=require("@munchi_oy/core");var T=(i=>(i.PENDING="PENDING",i.SUCCESS="SUCCESS",i.APPROVED="APPROVED",i.FAILED="FAILED",i.CANCELLED="CANCELLED",i.ERROR="ERROR",i))(T||{}),C=(c=>(c.IDLE="IDLE",c.CONNECTING="CONNECTING",c.REQUIRES_INPUT="REQUIRES_INPUT",c.PROCESSING="PROCESSING",c.SUCCESS="SUCCESS",c.FAILED="FAILED",c.INTERNAL_ERROR="INTERNAL_ERROR",c.VERIFYING="VERIFYING",c))(C||{});var w=class{constructor(e,r,t){this.messaging=r;this.config=t;this.api=new R.PaymentApi(void 0,"",e)}api;abortController=null;currentRequestId=null;paymentProvider=R.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:R.TransactionType.Purchase}};try{let{data:n}=await this.api.initiateNetsTerminalTransaction(t),s=n.connectCloudRequestId;if(!s)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=s,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,this.abortController.signal);return this.currentRequestId=null,i}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}`,s=R.PaymentEventType.StatusChanged;return new Promise((i,o)=>{let c=!1,u=()=>{c=!0,typeof m=="function"&&m(),clearTimeout(y)},d=()=>{u(),o(new l("CANCELLED","Transaction cancelled"))};t.addEventListener("abort",d);let m=this.messaging.subscribe(n,s,p=>{c||p.status===R.SimplePaymentStatus.Pending||(u(),t.removeEventListener("abort",d),i(this.handleSuccess(p)))}),y=setTimeout(async()=>{if(!(c||t.aborted))try{let p=await this.pollOrderStatus(e,r,this.config.storeId,t);i(this.handleSuccess(p))}catch(p){o(new l("TIMEOUT","Payment timed out and polling failed",p))}finally{t.removeEventListener("abort",d),u()}},1e4)})}async pollOrderStatus(e,r,t,n){let c=Date.now()+12e4;for(;Date.now()<c;){if(n.aborted)throw new Error("Aborted");try{let{data:u}=await this.api.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(u.status!==R.SimplePaymentStatus.Pending)return u}catch(u){if(u instanceof Error&&u.message==="Aborted")throw u}await new Promise(u=>{let d=()=>{clearTimeout(m),u(void 0)};n.addEventListener("abort",d,{once:!0});let m=setTimeout(()=>{n.removeEventListener("abort",d),u(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:R.TransactionType.ReturnOfGoods}},{data:n}=await this.api.initiateNetsTerminalTransaction(t),s=n.connectCloudRequestId;if(!s)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=s,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,this.abortController.signal);return this.currentRequestId=null,i}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===R.SimplePaymentStatus.Success,t=e.status===R.SimplePaymentStatus.Pending,n={success:r,status:r?"SUCCESS":t?"PENDING":"FAILED",orderId:e.orderId,transaction:e.transaction};return e.transactionId&&(n.transactionId=e.transactionId),e.error?.code&&(n.errorCode=e.error.code),e.error?.message&&(n.errorMessage=e.error.message),n}abort(){this.abortController?.abort()}};var f=require("@munchi_oy/core");var N=a=>{if(!a)return 0;let e=Number.parseInt(a,10);return Number.isFinite(e)?e:0},U=a=>{if(!a)return new Date().toISOString();let e=new Date(a);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()};var X="vivapayclient://pay/v1",H="abort",J="sale",k="transactionDetails",Z=4e3,ee="534287",te="38",re="493591",ne="497439",se=[re,ne],ie=["CREDIT","PREPAID","CORPORATE"],D=class{constructor(e,r,t,n){this.config=t;this.appToAppConfig=n;this.sessionApi=new f.PaymentSessionApi(void 0,"",e)}sessionApi;abortController=null;currentClientTransactionId=null;currentIsvClientTransactionId=null;currentCurrency=null;currentOrderRef=null;currentSourceTerminalId=null;latestResult=null;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.sessionApi.initiateVivaA2aSession(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(H,{}))}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){try{let t={sessionId:e.originalTransactionId,amount:e.amountCents},{data:n}=await this.sessionApi.refundVivaSession(t),s=n.status===f.PaymentSessionStatus.Refunded||n.status===f.PaymentSessionStatus.Refunding,i={success:s,status:s?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:n.providerTransactionId??n.sessionId};return s||(n.errorCode&&(i.errorCode=n.errorCode),n.errorMessage&&(i.errorMessage=n.errorMessage)),i}catch(t){throw new l("NETWORK_ERROR","Failed to refund Viva transaction",t)}}async verifyFinalStatus(e,r){return this.latestResult?this.latestResult:this.wasCancelled?{success:!1,status:"CANCELLED",orderId:this.currentOrderRef??r,errorCode:f.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 s=this.currentClientTransactionId?{sessionId:this.currentClientTransactionId}:void 0;return new Promise((i,o)=>{let c=(m,y)=>{m?.(),this.abortController?.signal.removeEventListener("abort",y)},u=()=>{c(d,u),o(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,c(d,u),i(y.result))});this.abortController?.signal.addEventListener("abort",u),n("REQUIRES_INPUT",s),this.appToAppConfig.adapter.openUrl(this.buildActionUrl(e,r)).then(()=>{this.abortController?.signal.aborted}).catch(m=>{c(d,u),this.currentClientTransactionId=null,this.currentIsvClientTransactionId=null,this.currentCurrency=null,this.currentOrderRef=null,this.currentSourceTerminalId=null,o(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:!1,showTransactionResult:!1};return r.tipAmount!==void 0&&(t.tipAmount=r.tipAmount),e.splitContext!==void 0&&(t.splitContext=e.splitContext),t}buildLaunchParams(e){let r={};return Object.entries(e).forEach(([t,n])=>{n!==void 0&&(t==="clientToken"||t==="sessionId"||(r[t]=String(n)))}),r}buildActionUrl(e,r){let t=new URLSearchParams({action:e,appId:this.appToAppConfig.appId,callback:this.resolveCallbackQueryParam()});return Object.entries(r).forEach(([n,s])=>{t.set(n,s)}),`${X}?${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),s=this.isCancelledCallback(t),i=this.resolveFailureCode(t,s),o={success:n,status:n?"SUCCESS":s?"CANCELLED":"FAILED",orderId:this.currentOrderRef??t.clientTransactionId??"unknown",errorCode:n?"":i,errorMessage:n?"":t.message??"Transaction failed without error details"};n&&(o.transaction=this.mapCallbackToTransaction(t));let c=t.transactionId??t.orderCode??t.clientTransactionId,u=t.errorCode??this.extractErrorReferenceFromMessage(t.message)??t.referenceNumber??t.tid??t.rrn;return c&&(o.transactionId=c),u&&(o.errorReference=u),{rawParams:t,result:o}}matchesCallbackBase(e){let r=new URL(e),t=this.appToAppConfig.callbackUrl;if(!t.includes("://")){let s=t.replace(/:$/,"");return r.protocol===`${s}:`}let n=new URL(t);return r.protocol===n.protocol&&r.hostname===n.hostname&&r.pathname===n.pathname}resolveCallbackQueryParam(){if(this.appToAppConfig.callbackParamFormat!=="scheme-only")return this.appToAppConfig.callbackUrl;let e=this.appToAppConfig.callbackUrl;return e.includes("://")?new URL(e).protocol.replace(/:$/,""):e.replace(/:$/,"")}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 f.PaymentFailureCode.PaymentCancelledByUser;let t=e.errorCode;if(t?.includes("."))return t;if(this.isTransactionDetailsAction(e)&&(e.transactionType??"").toLowerCase().includes("abort"))return f.PaymentFailureCode.SystemUnknown;let n=(e.message??"").toLowerCase(),s=(e.status??"").toLowerCase();return n.includes("declined")||s==="declined"||s==="fail"||s==="failed"||s==="failure"?f.PaymentFailureCode.PaymentDeclined:f.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()===k.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")||t.includes("cancelled by user")||t.includes("canceled by user")||t.includes("transaction cancelled by user")||t.includes("transaction canceled by user")||n.includes("user_cancel")||n.includes("user cancel")||n==="1000"&&(t.includes("cancelled by user")||t.includes("canceled by user"))}extractErrorReferenceFromMessage(e){return e?e.match(/\((-?\d+)\)/)?.[1]:void 0}mapCallbackToTransaction(e){let r=e.transactionId??e.orderCode??e.clientTransactionId??"unknown",t=U(e.transactionDate),n=N(e.tipAmount),s=N(e.surchargeAmount);return{amount:N(e.amount)-n-s,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.buildFees(n,s),id:r,label:null,provider:f.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),s=(e.bankId??"").trim();return n===ee||s===te?f.PaymentMethod.Edenred:se.includes(n)?f.PaymentMethod.WoltBenefit:ie.some(i=>r.includes(i))?f.PaymentMethod.Credit:f.PaymentMethod.Debit}buildFees(e,r){if(!this.currentCurrency)return null;let t=[];return e>0&&t.push({taxAmount:0,total:{amount:e,currency:this.currentCurrency},type:f.FeeType.TipAmount,vatPercentage:0}),r>0&&t.push({taxAmount:0,total:{amount:r,currency:this.currentCurrency},type:f.FeeType.Surcharge,vatPercentage:0}),t.length===0?null:{parts:t}}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,s(),r(null))},Z),s=this.appToAppConfig.adapter.subscribe(i=>{if(t)return;let o=this.parseCallbackUrl(i);o&&this.matchesKnownTransactionId(o.rawParams)&&(t=!0,clearTimeout(n),s(),r(o.result))});this.appToAppConfig.adapter.openUrl(this.buildActionUrl(k,e)).catch(()=>{t||(t=!0,clearTimeout(n),s(),r(null))})})}};var E=require("@munchi_oy/core");var g=require("@munchi_oy/core");function oe(a){throw new l("UNKNOWN",`Unhandled payment session status: ${String(a)}`)}function _(a){return{success:!1,status:"PENDING",orderId:a,errorCode:"",errorMessage:""}}function V(a,e){switch(a.status){case g.PaymentSessionStatus.Initiated:case g.PaymentSessionStatus.Processing:case g.PaymentSessionStatus.Voiding:case g.PaymentSessionStatus.Refunding:return _(e);case g.PaymentSessionStatus.Success:case g.PaymentSessionStatus.Closed:{let r={success:!0,status:"SUCCESS",orderId:e,errorCode:"",errorMessage:""};return a.providerTransactionId&&(r.transactionId=a.providerTransactionId),r}case g.PaymentSessionStatus.VoidFailed:case g.PaymentSessionStatus.Failed:{let r={success:!1,status:"FAILED",orderId:e,errorCode:a.errorCode||g.PaymentFailureCode.SystemUnknown,errorMessage:a.errorMessage||"Transaction failed without error details"};return a.providerTransactionId&&(r.transactionId=a.providerTransactionId),r}case g.PaymentSessionStatus.Cancelled:case g.PaymentSessionStatus.Voided:case g.PaymentSessionStatus.Refunded:{let r={success:!1,status:"CANCELLED",orderId:e};return a.errorCode&&(r.errorCode=a.errorCode),a.errorMessage&&(r.errorMessage=a.errorMessage),a.providerTransactionId&&(r.transactionId=a.providerTransactionId),r}default:return oe(a.status)}}var O=class a{constructor(e,r,t){this.messaging=r;this.config=t;this.sessionApi=new E.PaymentSessionApi(void 0,"",e)}static POLLING_DURATION_MS=18e4;static POLLING_INTERVAL_MS=1e3;static VERIFY_DURATION_MS=3e4;static INITIAL_POLL_DELAY_MS=1e4;sessionApi;abortController=null;idempotencyKey=null;idempotencyOrderRef=null;currentClientToken=null;async processPayment(e,r){this.abortController=new AbortController,(this.idempotencyKey===null||this.idempotencyOrderRef!==e.orderRef)&&(this.idempotencyKey=this.generateIdempotencyKey(),this.idempotencyOrderRef=e.orderRef),this.currentClientToken=null,r("CONNECTING");let t={amount:e.amountCents,businessId:Number(this.config.storeId),orderId:e.orderRef};e.splitContext!==void 0&&(t.splitContext=e.splitContext);try{let{data:n}=await this.sessionApi.initiateVivaSession(t,this.idempotencyKey);this.currentClientToken=n.clientToken;let s=this.abortController.signal;if(s.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:n.sessionId});let i=await this.waitForCompletion(n.clientToken,n.sessionId,e,s);return i?this.finalize(i):(await this.armCancel(n.clientToken),_(e.orderRef))}catch(n){throw n instanceof l?n:new l("NETWORK_ERROR","Failed to create Viva payment session",n)}}async verifyFinalStatus(e,r){if(!this.currentClientToken)throw new l("NETWORK_ERROR","No active payment session to verify");let t=await this.pollUntilTerminal(this.currentClientToken,e,void 0,a.VERIFY_DURATION_MS);return this.finalize(t??_(e.orderRef))}async cancelTransaction(e){if(!this.currentClientToken)return!1;try{await this.sessionApi.cancelVivaSession(this.currentClientToken)}catch(r){throw new l("NETWORK_ERROR","Failed to cancel Viva payment session",r)}return this.abortController?.abort(),!0}async refundTransaction(e,r){try{let t={sessionId:e.originalTransactionId,amount:e.amountCents},{data:n}=await this.sessionApi.refundVivaSession(t),s=n.status===E.PaymentSessionStatus.Refunded||n.status===E.PaymentSessionStatus.Refunding,i={success:s,status:s?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:n.providerTransactionId??n.sessionId};return s||(n.errorCode&&(i.errorCode=n.errorCode),n.errorMessage&&(i.errorMessage=n.errorMessage)),i}catch(t){throw new l("NETWORK_ERROR","Failed to refund Viva transaction",t)}}async revertTransaction(e){try{let r={sessionId:e.originalTransactionId},{data:t}=await this.sessionApi.revertVivaSession(r),n=t.status===E.PaymentSessionStatus.Refunded||t.status===E.PaymentSessionStatus.Refunding,s={success:n,status:n?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:t.providerTransactionId??t.sessionId};return n||(t.errorCode&&(s.errorCode=t.errorCode),t.errorMessage&&(s.errorMessage=t.errorMessage)),s}catch(r){throw new l("NETWORK_ERROR","Failed to revert Viva transaction",r)}}abort(){this.abortController?.abort()}async pollUntilTerminal(e,r,t,n){let s=Date.now()+n;for(;Date.now()<s;){if(t?.aborted)throw new Error("Aborted");let i;try{i=(await this.sessionApi.getPaymentSession(e)).data}catch(o){if(o instanceof Error&&o.message==="Aborted")throw o}if(t?.aborted)throw new Error("Aborted");if(i){let o=V(i,r.orderRef);if(o.status!=="PENDING")return o}await this.delay(a.POLLING_INTERVAL_MS,t)}}waitForCompletion(e,r,t,n){let s=`viva.${this.config.channel.toLowerCase()}.requests.${r}`;return new Promise((i,o)=>{let c=!1,u=()=>{c=!0,typeof m=="function"&&m(),clearTimeout(y),n.removeEventListener("abort",d)},d=()=>{u(),o(new Error("Aborted"))};n.addEventListener("abort",d);let m=this.messaging.subscribe(s,"payment:status-changed",p=>{c||p.status!==E.SimplePaymentStatus.Pending&&(u(),i(this.mapStatusDto(p,t)))}),y=setTimeout(()=>{c||this.pollUntilTerminal(e,t,n,a.POLLING_DURATION_MS).then(p=>{c||(u(),i(p))},p=>{c||(u(),o(p))})},a.INITIAL_POLL_DELAY_MS)})}mapStatusDto(e,r){let t=e.status===E.SimplePaymentStatus.Success,n={success:t,status:t?"SUCCESS":"FAILED",orderId:r.orderRef,errorCode:e.error?.code||(t?"":E.PaymentFailureCode.SystemUnknown),errorMessage:e.error?.message||(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}finalize(e){return e.status!=="PENDING"&&(this.idempotencyKey=null,this.idempotencyOrderRef=null),e}armCancel(e){return this.sessionApi.cancelVivaSession(e).then(()=>{},()=>{})}generateIdempotencyKey(){let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let t=Math.random()*16|0;return(r==="x"?t:t&3|8).toString(16)})}delay(e,r){return new Promise(t=>{let n=()=>{clearTimeout(s),t()};r&&r.addEventListener("abort",n,{once:!0});let s=setTimeout(()=>{r&&r.removeEventListener("abort",n),t()},e)})}};var S=require("@munchi_oy/core");var A=class a{constructor(e,r,t){this.messaging=r;this.config=t;this.api=new S.PaymentApi(void 0,"",e)}static INITIAL_POLL_DELAY_MS=1e4;static POLLING_DURATION_MS=18e4;static POLLING_INTERVAL_MS=2e3;static TIMEOUT_CANCEL_TIMEOUT_MS=5e3;static VERIFY_TIMEOUT_MS=1e4;static VERIFY_MAX_RETRIES=3;static VERIFY_RETRY_DELAY_MS=1500;api;abortController=null;currentSessionId=null;paymentProvider=S.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 s=await this.waitForPaymentCompletion(n.sessionId,e,this.abortController.signal);return this.currentSessionId=null,s}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 s=`viva.${this.config.channel.toLowerCase()}.requests.${e}`,i="payment:status-changed";return new Promise((o,c)=>{let u=!1,d=()=>{u=!0,typeof y=="function"&&y(),clearTimeout(p)},m=()=>{d(),c(new Error("Aborted"))};t.addEventListener("abort",m);let y=this.messaging.subscribe(s,i,P=>{u||P.status!==S.SimplePaymentStatus.Pending&&(d(),t.removeEventListener("abort",m),o(this.handleSuccess(P)))}),p=setTimeout(async()=>{if(!(u||t.aborted))try{let P=await this.pollOrderStatus(e,r.orderRef,this.config.storeId,t);if(u)return;o(this.handleSuccess(P))}catch(P){if(u)return;if(P instanceof Error&&P.message==="Aborted"){c(P);return}try{let b=await this.recoverAfterPollingTimeout(r,e);o(b)}catch(b){c(b instanceof l?b:new l("TIMEOUT","Payment timed out and polling failed",b))}}finally{t.removeEventListener("abort",m),d()}},a.INITIAL_POLL_DELAY_MS)})}async pollOrderStatus(e,r,t,n){let i=Date.now()+a.POLLING_DURATION_MS;for(;Date.now()<i;){if(n.aborted)throw new Error("Aborted");try{let{data:o}=await this.api.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(o.status!==S.SimplePaymentStatus.Pending)return o}catch(o){if(o instanceof Error&&o.message==="Aborted")throw o}await new Promise(o=>{let c=()=>{clearTimeout(u),o(void 0)};n.addEventListener("abort",c,{once:!0});let u=setTimeout(()=>{n.removeEventListener("abort",c),o(void 0)},a.POLLING_INTERVAL_MS)})}throw new Error("Payment verification timed out.")}async recoverAfterPollingTimeout(e,r){return await this.cancelSessionWithTimeout(r),await this.verifyFinalStatusWithRetry(e,r)}async cancelSessionWithTimeout(e){let r;try{await Promise.race([this.cancelSession(e),new Promise((t,n)=>{r=setTimeout(()=>{n(new Error("Viva timeout cancellation timed out"))},a.TIMEOUT_CANCEL_TIMEOUT_MS)})])}catch{}finally{r&&clearTimeout(r)}}async cancelSession(e){return await this.api.cancelVivaTransactionV2({cashRegisterId:this.config.storeId,sessionId:e}),this.currentSessionId===e&&(this.currentSessionId=null),!0}async verifyFinalStatusWithRetry(e,r){let t;for(let n=1;n<=a.VERIFY_MAX_RETRIES;n++)try{let s=await Promise.race([this.verifyFinalStatus(e,r),new Promise((i,o)=>setTimeout(()=>o(new Error("Verify timed out")),a.VERIFY_TIMEOUT_MS))]);if(s.status==="PENDING"){t=new Error("Verify returned pending status"),n<a.VERIFY_MAX_RETRIES&&await new Promise(i=>setTimeout(i,a.VERIFY_RETRY_DELAY_MS));continue}return s}catch(s){t=s,n<a.VERIFY_MAX_RETRIES&&await new Promise(i=>setTimeout(i,a.VERIFY_RETRY_DELAY_MS))}throw new l(S.PaymentFailureCode.PaymentTimeout,"Payment Failed",t)}handleSuccess(e){let r=e.status===S.SimplePaymentStatus.Success,t={success:r,status:r?"SUCCESS":"FAILED",orderId:e.orderId,errorCode:e.error?.code||(r?"":S.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===S.SimplePaymentStatus.Success,s=t.status===S.SimplePaymentStatus.Pending,i={success:n,status:n?"SUCCESS":s?"PENDING":"FAILED",orderId:t.orderId,errorCode:t.error?.code||(n||s?"":S.PaymentFailureCode.SystemUnknown),errorMessage:t.error?.message||(n||s?"":"Transaction failed without error details")};return t.transactionId&&(i.transactionId=t.transactionId),t.error?.referenceError&&(i.errorReference=t.error.referenceError),t.transaction&&(i.transaction=t.transaction),i}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),s=n.success;return{success:s,status:s?"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"),W=require("axios");var L=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),s=this.extractOperationId(n.data);if(this.currentOperationId=s,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,h.PaymentEventType.StatusChanged,this.abortController.signal);return this.currentOperationId=null,i}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),s=this.extractOperationId(n.data);if(this.currentOperationId=s,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,h.PaymentEventType.RefundStatusChanged,this.abortController.signal);return this.currentOperationId=null,i}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 s=`worldline.requests.${e}`;return new Promise((i,o)=>{let c=!1,u=()=>{c=!0,typeof m=="function"&&m(),clearTimeout(y)},d=()=>{u(),o(new l("CANCELLED","Transaction cancelled"))};n.addEventListener("abort",d);let m=this.messaging.subscribe(s,t,p=>{c||p.status===h.SimplePaymentStatus.Pending||(u(),n.removeEventListener("abort",d),i(this.handlePaymentStatus(p)))}),y=setTimeout(async()=>{if(!(c||n.aborted))try{let p=await this.pollOrderStatus(e,r,this.config.storeId,n);i(this.handlePaymentStatus(p))}catch(p){o(new l("TIMEOUT","Payment timed out and polling failed",p))}finally{n.removeEventListener("abort",d),u()}},1e4)})}async pollOrderStatus(e,r,t,n){let o=Date.now()+12e4;for(;Date.now()<o;){if(n.aborted)throw new Error("Aborted");try{let{data:c}=await this.paymentApi.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(c.status!==h.SimplePaymentStatus.Pending)return c}catch(c){if(c instanceof Error&&c.message==="Aborted")throw c}await new Promise(c=>{let u=()=>{clearTimeout(d),c(void 0)};n.addEventListener("abort",u,{once:!0});let d=setTimeout(()=>{n.removeEventListener("abort",u),c(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,W.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 F=class a{strategy;axios;messaging;timeoutMs;logger;_currentState="IDLE";_listeners=[];_cancellationIntent=!1;_currentSessionId;_autoResetTimer;autoResetOptions;appToAppConfig;paymentSessionConfig;static TERMINAL_STATES=["SUCCESS","FAILED","INTERNAL_ERROR"];static RESTING_STATES=["IDLE",...a.TERMINAL_STATES];constructor(e,r,t,n={},s){this.axios=e,this.messaging=r,this.logger=n.logger,this.timeoutMs=n.timeoutMs||3e4,this.autoResetOptions=n.autoResetOnPaymentComplete,this.appToAppConfig=n.appToApp,this.paymentSessionConfig=n.paymentSession,this.strategy=s??this.resolveStrategy(t)}get version(){return M}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:I.PaymentFailureCode.PaymentCancelledByUser,DECLINED:I.PaymentFailureCode.PaymentDeclined,TERMINAL_BUSY:I.PaymentFailureCode.TerminalBusy,TERMINAL_OFFLINE:I.PaymentFailureCode.TerminalOffline,TIMEOUT:I.PaymentFailureCode.TerminalTimeout,NETWORK_ERROR:I.PaymentFailureCode.SystemProviderError,STRATEGY_ERROR:I.PaymentFailureCode.SystemProviderError,MISSING_CONFIG:I.PaymentFailureCode.SystemUnknown,INVALID_AMOUNT:I.PaymentFailureCode.SystemUnknown,UNKNOWN:I.PaymentFailureCode.SystemUnknown}[e]??I.PaymentFailureCode.SystemUnknown:I.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(a.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,a.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 I.PaymentProvider.Nets:return new w(this.axios,this.messaging,e);case I.PaymentProvider.Worldline:return new L(this.axios,this.messaging,e);case I.PaymentProvider.Viva:return this.appToAppConfig?.enabled?new D(this.axios,this.messaging,e,this.appToAppConfig):this.paymentSessionConfig?.enabled?new O(this.axios,this.messaging,e):new A(this.axios,this.messaging,e);default:return new A(this.axios,this.messaging,e)}}initiateTransaction=async(e,r)=>{let t=r??{},n=e.orderRef;if(!a.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");let i=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 o=(m,y)=>{y?.sessionId&&(this._currentSessionId=y.sessionId),m!=="FAILED"&&(this.transitionTo(m),this.fireStateCallback(m,t,n))},c=this.strategy.processPayment(e,o),d=(this.strategy.getExecutionMode?.()??"managed")==="callback_driven"?await c:await Promise.race([c,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()-i}),d}catch(o){return this.logger?.warn("Transaction interrupted. Handling final status...",{error:o}),await this.handleTransactionError(e,o,t)}};async handleTransactionError(e,r,t={}){let n=r instanceof l&&(r.code==="TIMEOUT"||r.code===I.PaymentFailureCode.PaymentTimeout);if(!this._cancellationIntent&&!n&&(this.transitionTo("VERIFYING"),this.safeFireCallback(()=>t.onVerifying?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId}))),this._cancellationIntent){try{if(this._currentSessionId){let i=await this.strategy.verifyFinalStatus(e,this._currentSessionId);if(i.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(i)),i}}catch(i){this.logger?.warn("Final status verification failed during cancellation",{err:i})}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 s;if(this.strategy.abort(),this._currentSessionId)try{let i=await this.strategy.verifyFinalStatus(e,this._currentSessionId);if(i.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(i)),i;s=n&&i.status==="PENDING"?this.buildErrorResultFromException(e.orderRef,r):i}catch(i){this.logger?.warn("Failed to get detailed error from verifyFinalStatus",{verifyErr:i}),s=this.buildErrorResultFromException(e.orderRef,i)}else s=this.buildErrorResultFromException(e.orderRef,r);return this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(s)),s}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"),a.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=()=>{a.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,!a.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");this.transitionTo("IDLE");try{let s=(o,c)=>{c?.sessionId&&(this._currentSessionId=c.sessionId),o!=="FAILED"&&(this.transitionTo(o),this.fireStateCallback(o,t,e.orderRef))},i=await this.strategy.refundTransaction(e,s);return i.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(i))):this._cancellationIntent||i.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId}))):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(i))),this.logger?.info("Refund completed",{success:i.success,orderRef:e.orderRef}),i}catch(s){if(this.logger?.error("Refund failed",s),this._cancellationIntent){try{if(this._currentSessionId){let o=await this.strategy.verifyFinalStatus(e,this._currentSessionId);return o.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(o)),o):o.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId})),o):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(o)),o)}}catch(o){this.logger?.warn("Refund final status verification failed",{verifyError:o})}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 i=this.generateErrorResult(e.orderRef,"UNKNOWN",s instanceof Error?s.message:"Refund failed");return this.safeFireCallback(()=>t.onError?.(i)),i}};revert=async(e,r)=>{let t=r??{};if(this.logger?.info("Reverting payment",{orderRef:e.orderRef}),this._currentSessionId=e.originalTransactionId,this._cancellationIntent=!1,!a.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");let n=this.strategy.revertTransaction?.bind(this.strategy);if(!n)return this.generateErrorResult(e.orderRef,"STRATEGY_ERROR","Revert is not supported by the active payment strategy");this.transitionTo("CONNECTING");try{let s=await n(e);return this.settleSingleShot(s,e.orderRef,t),s}catch(s){return this.logger?.error("Revert failed",s),this.failSingleShot(e.orderRef,s,"Revert failed",t)}};settleSingleShot(e,r,t){e.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(e))):e.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:r,refPaymentId:this._currentSessionId}))):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(e)))}failSingleShot(e,r,t,n){let s=this.generateErrorResult(e,"NETWORK_ERROR",r instanceof Error?r.message:t);return this.transitionTo("FAILED"),this.safeFireCallback(()=>n.onError?.(s)),s}};var G=(n=>(n.CONNECTING="CONNECTING",n.CONNECTED="CONNECTED",n.OFFLINE="OFFLINE",n.DISCONNECTED="DISCONNECTED",n))(G||{});0&&(module.exports={AppReaderStatus,MunchiPaymentSDK,PaymentInteractionState,SdkPaymentStatus});
1
+ "use strict";var x=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var B=(a,e)=>{for(var r in e)x(a,r,{get:e[r],enumerable:!0})},$=(a,e,r,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of q(e))!Y.call(a,n)&&n!==r&&x(a,n,{get:()=>e[n],enumerable:!(t=K(e,n))||t.enumerable});return a};var Q=a=>$(x({},"__esModule",{value:!0}),a);var ae={};B(ae,{AppReaderStatus:()=>G,MunchiPaymentSDK:()=>F,PaymentInteractionState:()=>C,SdkPaymentStatus:()=>T});module.exports=Q(ae);var I=require("@munchi_oy/core");var M="1.10.5";var l=class a extends Error{code;rawError;constructor(e,r,t){super(r),this.name="PaymentSDKError",this.code=e,this.rawError=t,Object.setPrototypeOf(this,a.prototype)}};var g=require("@munchi_oy/core");var T=(i=>(i.PENDING="PENDING",i.SUCCESS="SUCCESS",i.APPROVED="APPROVED",i.FAILED="FAILED",i.CANCELLED="CANCELLED",i.ERROR="ERROR",i))(T||{}),C=(c=>(c.IDLE="IDLE",c.CONNECTING="CONNECTING",c.REQUIRES_INPUT="REQUIRES_INPUT",c.PROCESSING="PROCESSING",c.SUCCESS="SUCCESS",c.FAILED="FAILED",c.INTERNAL_ERROR="INTERNAL_ERROR",c.VERIFYING="VERIFYING",c))(C||{});var w=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),s=n.connectCloudRequestId;if(!s)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=s,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,this.abortController.signal);return this.currentRequestId=null,i}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}`,s=g.PaymentEventType.StatusChanged;return new Promise((i,o)=>{let c=!1,u=()=>{c=!0,typeof m=="function"&&m(),clearTimeout(y)},d=()=>{u(),o(new l("CANCELLED","Transaction cancelled"))};t.addEventListener("abort",d);let m=this.messaging.subscribe(n,s,p=>{c||p.status===g.SimplePaymentStatus.Pending||(u(),t.removeEventListener("abort",d),i(this.handleSuccess(p)))}),y=setTimeout(async()=>{if(!(c||t.aborted))try{let p=await this.pollOrderStatus(e,r,this.config.storeId,t);i(this.handleSuccess(p))}catch(p){o(new l("TIMEOUT","Payment timed out and polling failed",p))}finally{t.removeEventListener("abort",d),u()}},1e4)})}async pollOrderStatus(e,r,t,n){let c=Date.now()+12e4;for(;Date.now()<c;){if(n.aborted)throw new Error("Aborted");try{let{data:u}=await this.api.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(u.status!==g.SimplePaymentStatus.Pending)return u}catch(u){if(u instanceof Error&&u.message==="Aborted")throw u}await new Promise(u=>{let d=()=>{clearTimeout(m),u(void 0)};n.addEventListener("abort",d,{once:!0});let m=setTimeout(()=>{n.removeEventListener("abort",d),u(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),s=n.connectCloudRequestId;if(!s)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=s,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,this.abortController.signal);return this.currentRequestId=null,i}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=e.status===g.SimplePaymentStatus.Pending,n={success:r,status:r?"SUCCESS":t?"PENDING":"FAILED",orderId:e.orderId,transaction:e.transaction};return e.transactionId&&(n.transactionId=e.transactionId),e.error?.code&&(n.errorCode=e.error.code),e.error?.message&&(n.errorMessage=e.error.message),n}abort(){this.abortController?.abort()}};var f=require("@munchi_oy/core");var N=a=>{if(!a)return 0;let e=Number.parseInt(a,10);return Number.isFinite(e)?e:0},U=a=>{if(!a)return new Date().toISOString();let e=new Date(a);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()};var X="vivapayclient://pay/v1",H="abort",J="sale",k="transactionDetails",Z=4e3,ee="534287",te="38",re="493591",ne="497439",se=[re,ne],ie=["CREDIT","PREPAID","CORPORATE"],D=class{constructor(e,r,t,n){this.config=t;this.appToAppConfig=n;this.sessionApi=new f.PaymentSessionApi(void 0,"",e)}sessionApi;abortController=null;currentClientTransactionId=null;currentIsvClientTransactionId=null;currentCurrency=null;currentOrderRef=null;currentSourceTerminalId=null;latestResult=null;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.sessionApi.initiateVivaA2aSession(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(H,{}))}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){try{let t={sessionId:e.originalTransactionId,amount:e.amountCents},{data:n}=await this.sessionApi.refundVivaSession(t),s=n.status===f.PaymentSessionStatus.Refunded||n.status===f.PaymentSessionStatus.Refunding,i={success:s,status:s?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:n.providerTransactionId??n.sessionId};return s||(n.errorCode&&(i.errorCode=n.errorCode),n.errorMessage&&(i.errorMessage=n.errorMessage)),i}catch(t){throw new l("NETWORK_ERROR","Failed to refund Viva transaction",t)}}async verifyFinalStatus(e,r){return this.latestResult?this.latestResult:this.wasCancelled?{success:!1,status:"CANCELLED",orderId:this.currentOrderRef??r,errorCode:f.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 s=this.currentClientTransactionId?{sessionId:this.currentClientTransactionId}:void 0;return new Promise((i,o)=>{let c=(m,y)=>{m?.(),this.abortController?.signal.removeEventListener("abort",y)},u=()=>{c(d,u),o(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,c(d,u),i(y.result))});this.abortController?.signal.addEventListener("abort",u),n("REQUIRES_INPUT",s),this.appToAppConfig.adapter.openUrl(this.buildActionUrl(e,r)).then(()=>{this.abortController?.signal.aborted}).catch(m=>{c(d,u),this.currentClientTransactionId=null,this.currentIsvClientTransactionId=null,this.currentCurrency=null,this.currentOrderRef=null,this.currentSourceTerminalId=null,o(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:!1,showTransactionResult:!1};return r.tipAmount!==void 0&&(t.tipAmount=r.tipAmount),e.splitContext!==void 0&&(t.splitContext=e.splitContext),t}buildLaunchParams(e){let r={};return Object.entries(e).forEach(([t,n])=>{n!==void 0&&(t==="clientToken"||t==="sessionId"||(r[t]=String(n)))}),r}buildActionUrl(e,r){let t=new URLSearchParams({action:e,appId:this.appToAppConfig.appId,callback:this.resolveCallbackQueryParam()});return Object.entries(r).forEach(([n,s])=>{t.set(n,s)}),`${X}?${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),s=this.isCancelledCallback(t),i=this.resolveFailureCode(t,s),o={success:n,status:n?"SUCCESS":s?"CANCELLED":"FAILED",orderId:this.currentOrderRef??t.clientTransactionId??"unknown",errorCode:n?"":i,errorMessage:n?"":t.message??"Transaction failed without error details"};n&&(o.transaction=this.mapCallbackToTransaction(t));let c=t.transactionId??t.orderCode??t.clientTransactionId,u=t.errorCode??this.extractErrorReferenceFromMessage(t.message)??t.referenceNumber??t.tid??t.rrn;return c&&(o.transactionId=c),u&&(o.errorReference=u),{rawParams:t,result:o}}matchesCallbackBase(e){let r=new URL(e),t=this.appToAppConfig.callbackUrl;if(!t.includes("://")){let s=t.replace(/:$/,"");return r.protocol===`${s}:`}let n=new URL(t);return r.protocol===n.protocol&&r.hostname===n.hostname&&r.pathname===n.pathname}resolveCallbackQueryParam(){if(this.appToAppConfig.callbackParamFormat!=="scheme-only")return this.appToAppConfig.callbackUrl;let e=this.appToAppConfig.callbackUrl;return e.includes("://")?new URL(e).protocol.replace(/:$/,""):e.replace(/:$/,"")}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 f.PaymentFailureCode.PaymentCancelledByUser;let t=e.errorCode;if(t?.includes("."))return t;if(this.isTransactionDetailsAction(e)&&(e.transactionType??"").toLowerCase().includes("abort"))return f.PaymentFailureCode.SystemUnknown;let n=(e.message??"").toLowerCase(),s=(e.status??"").toLowerCase();return n.includes("declined")||s==="declined"||s==="fail"||s==="failed"||s==="failure"?f.PaymentFailureCode.PaymentDeclined:f.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()===k.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")||t.includes("cancelled by user")||t.includes("canceled by user")||t.includes("transaction cancelled by user")||t.includes("transaction canceled by user")||n.includes("user_cancel")||n.includes("user cancel")||n==="1000"&&(t.includes("cancelled by user")||t.includes("canceled by user"))}extractErrorReferenceFromMessage(e){return e?e.match(/\((-?\d+)\)/)?.[1]:void 0}mapCallbackToTransaction(e){let r=e.transactionId??e.orderCode??e.clientTransactionId??"unknown",t=U(e.transactionDate),n=N(e.tipAmount),s=N(e.surchargeAmount);return{amount:N(e.amount)-n-s,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.buildFees(n,s),id:r,label:null,provider:f.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),s=(e.bankId??"").trim();return n===ee||s===te?f.PaymentMethod.Edenred:se.includes(n)?f.PaymentMethod.WoltBenefit:ie.some(i=>r.includes(i))?f.PaymentMethod.Credit:f.PaymentMethod.Debit}buildFees(e,r){if(!this.currentCurrency)return null;let t=[];return e>0&&t.push({taxAmount:0,total:{amount:e,currency:this.currentCurrency},type:f.FeeType.TipAmount,vatPercentage:0}),r>0&&t.push({taxAmount:0,total:{amount:r,currency:this.currentCurrency},type:f.FeeType.Surcharge,vatPercentage:0}),t.length===0?null:{parts:t}}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,s(),r(null))},Z),s=this.appToAppConfig.adapter.subscribe(i=>{if(t)return;let o=this.parseCallbackUrl(i);o&&this.matchesKnownTransactionId(o.rawParams)&&(t=!0,clearTimeout(n),s(),r(o.result))});this.appToAppConfig.adapter.openUrl(this.buildActionUrl(k,e)).catch(()=>{t||(t=!0,clearTimeout(n),s(),r(null))})})}};var E=require("@munchi_oy/core");var R=require("@munchi_oy/core");function oe(a){throw new l("UNKNOWN",`Unhandled payment session status: ${String(a)}`)}function _(a){return{success:!1,status:"PENDING",orderId:a,errorCode:"",errorMessage:""}}function V(a,e){switch(a.status){case R.PaymentSessionStatus.Initiated:case R.PaymentSessionStatus.Processing:case R.PaymentSessionStatus.Voiding:case R.PaymentSessionStatus.Refunding:case R.PaymentSessionStatus.Dispatched:return _(e);case R.PaymentSessionStatus.Success:case R.PaymentSessionStatus.Closed:{let r={success:!0,status:"SUCCESS",orderId:e,errorCode:"",errorMessage:""};return a.providerTransactionId&&(r.transactionId=a.providerTransactionId),r}case R.PaymentSessionStatus.VoidFailed:case R.PaymentSessionStatus.Failed:{let r={success:!1,status:"FAILED",orderId:e,errorCode:a.errorCode||R.PaymentFailureCode.SystemUnknown,errorMessage:a.errorMessage||"Transaction failed without error details"};return a.providerTransactionId&&(r.transactionId=a.providerTransactionId),r}case R.PaymentSessionStatus.Cancelled:case R.PaymentSessionStatus.Voided:case R.PaymentSessionStatus.Refunded:{let r={success:!1,status:"CANCELLED",orderId:e};return a.errorCode&&(r.errorCode=a.errorCode),a.errorMessage&&(r.errorMessage=a.errorMessage),a.providerTransactionId&&(r.transactionId=a.providerTransactionId),r}default:return oe(a.status)}}var O=class a{constructor(e,r,t){this.messaging=r;this.config=t;this.sessionApi=new E.PaymentSessionApi(void 0,"",e)}static POLLING_DURATION_MS=18e4;static POLLING_INTERVAL_MS=1e3;static VERIFY_DURATION_MS=3e4;static INITIAL_POLL_DELAY_MS=1e4;sessionApi;abortController=null;idempotencyKey=null;idempotencyOrderRef=null;currentClientToken=null;async processPayment(e,r){this.abortController=new AbortController,(this.idempotencyKey===null||this.idempotencyOrderRef!==e.orderRef)&&(this.idempotencyKey=this.generateIdempotencyKey(),this.idempotencyOrderRef=e.orderRef),this.currentClientToken=null,r("CONNECTING");let t={amount:e.amountCents,businessId:Number(this.config.storeId),orderId:e.orderRef};e.splitContext!==void 0&&(t.splitContext=e.splitContext);try{let{data:n}=await this.sessionApi.initiateVivaSession(t,this.idempotencyKey);this.currentClientToken=n.clientToken;let s=this.abortController.signal;if(s.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:n.sessionId});let i=await this.waitForCompletion(n.clientToken,n.sessionId,e,s);return i?this.finalize(i):(await this.armCancel(n.clientToken),_(e.orderRef))}catch(n){throw n instanceof l?n:new l("NETWORK_ERROR","Failed to create Viva payment session",n)}}async verifyFinalStatus(e,r){if(!this.currentClientToken)throw new l("NETWORK_ERROR","No active payment session to verify");let t=await this.pollUntilTerminal(this.currentClientToken,e,void 0,a.VERIFY_DURATION_MS);return this.finalize(t??_(e.orderRef))}async cancelTransaction(e){if(!this.currentClientToken)return!1;try{await this.sessionApi.cancelVivaSession(this.currentClientToken)}catch(r){throw new l("NETWORK_ERROR","Failed to cancel Viva payment session",r)}return this.abortController?.abort(),!0}async refundTransaction(e,r){try{let t={sessionId:e.originalTransactionId,amount:e.amountCents},{data:n}=await this.sessionApi.refundVivaSession(t),s=n.status===E.PaymentSessionStatus.Refunded||n.status===E.PaymentSessionStatus.Refunding,i={success:s,status:s?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:n.providerTransactionId??n.sessionId};return s||(n.errorCode&&(i.errorCode=n.errorCode),n.errorMessage&&(i.errorMessage=n.errorMessage)),i}catch(t){throw new l("NETWORK_ERROR","Failed to refund Viva transaction",t)}}async revertTransaction(e){try{let r={sessionId:e.originalTransactionId},{data:t}=await this.sessionApi.revertVivaSession(r),n=t.status===E.PaymentSessionStatus.Refunded||t.status===E.PaymentSessionStatus.Refunding,s={success:n,status:n?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:t.providerTransactionId??t.sessionId};return n||(t.errorCode&&(s.errorCode=t.errorCode),t.errorMessage&&(s.errorMessage=t.errorMessage)),s}catch(r){throw new l("NETWORK_ERROR","Failed to revert Viva transaction",r)}}abort(){this.abortController?.abort()}async pollUntilTerminal(e,r,t,n){let s=Date.now()+n;for(;Date.now()<s;){if(t?.aborted)throw new Error("Aborted");let i;try{i=(await this.sessionApi.getPaymentSession(e)).data}catch(o){if(o instanceof Error&&o.message==="Aborted")throw o}if(t?.aborted)throw new Error("Aborted");if(i){let o=V(i,r.orderRef);if(o.status!=="PENDING")return o}await this.delay(a.POLLING_INTERVAL_MS,t)}}waitForCompletion(e,r,t,n){let s=`viva.${this.config.channel.toLowerCase()}.requests.${r}`;return new Promise((i,o)=>{let c=!1,u=()=>{c=!0,typeof m=="function"&&m(),clearTimeout(y),n.removeEventListener("abort",d)},d=()=>{u(),o(new Error("Aborted"))};n.addEventListener("abort",d);let m=this.messaging.subscribe(s,"payment:status-changed",p=>{c||p.status!==E.SimplePaymentStatus.Pending&&(u(),i(this.mapStatusDto(p,t)))}),y=setTimeout(()=>{c||this.pollUntilTerminal(e,t,n,a.POLLING_DURATION_MS).then(p=>{c||(u(),i(p))},p=>{c||(u(),o(p))})},a.INITIAL_POLL_DELAY_MS)})}mapStatusDto(e,r){let t=e.status===E.SimplePaymentStatus.Success,n={success:t,status:t?"SUCCESS":"FAILED",orderId:r.orderRef,errorCode:e.error?.code||(t?"":E.PaymentFailureCode.SystemUnknown),errorMessage:e.error?.message||(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}finalize(e){return e.status!=="PENDING"&&(this.idempotencyKey=null,this.idempotencyOrderRef=null),e}armCancel(e){return this.sessionApi.cancelVivaSession(e).then(()=>{},()=>{})}generateIdempotencyKey(){let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let t=Math.random()*16|0;return(r==="x"?t:t&3|8).toString(16)})}delay(e,r){return new Promise(t=>{let n=()=>{clearTimeout(s),t()};r&&r.addEventListener("abort",n,{once:!0});let s=setTimeout(()=>{r&&r.removeEventListener("abort",n),t()},e)})}};var S=require("@munchi_oy/core");var A=class a{constructor(e,r,t){this.messaging=r;this.config=t;this.api=new S.PaymentApi(void 0,"",e)}static INITIAL_POLL_DELAY_MS=1e4;static POLLING_DURATION_MS=18e4;static POLLING_INTERVAL_MS=2e3;static TIMEOUT_CANCEL_TIMEOUT_MS=5e3;static VERIFY_TIMEOUT_MS=1e4;static VERIFY_MAX_RETRIES=3;static VERIFY_RETRY_DELAY_MS=1500;api;abortController=null;currentSessionId=null;paymentProvider=S.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 s=await this.waitForPaymentCompletion(n.sessionId,e,this.abortController.signal);return this.currentSessionId=null,s}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 s=`viva.${this.config.channel.toLowerCase()}.requests.${e}`,i="payment:status-changed";return new Promise((o,c)=>{let u=!1,d=()=>{u=!0,typeof y=="function"&&y(),clearTimeout(p)},m=()=>{d(),c(new Error("Aborted"))};t.addEventListener("abort",m);let y=this.messaging.subscribe(s,i,P=>{u||P.status!==S.SimplePaymentStatus.Pending&&(d(),t.removeEventListener("abort",m),o(this.handleSuccess(P)))}),p=setTimeout(async()=>{if(!(u||t.aborted))try{let P=await this.pollOrderStatus(e,r.orderRef,this.config.storeId,t);if(u)return;o(this.handleSuccess(P))}catch(P){if(u)return;if(P instanceof Error&&P.message==="Aborted"){c(P);return}try{let b=await this.recoverAfterPollingTimeout(r,e);o(b)}catch(b){c(b instanceof l?b:new l("TIMEOUT","Payment timed out and polling failed",b))}}finally{t.removeEventListener("abort",m),d()}},a.INITIAL_POLL_DELAY_MS)})}async pollOrderStatus(e,r,t,n){let i=Date.now()+a.POLLING_DURATION_MS;for(;Date.now()<i;){if(n.aborted)throw new Error("Aborted");try{let{data:o}=await this.api.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(o.status!==S.SimplePaymentStatus.Pending)return o}catch(o){if(o instanceof Error&&o.message==="Aborted")throw o}await new Promise(o=>{let c=()=>{clearTimeout(u),o(void 0)};n.addEventListener("abort",c,{once:!0});let u=setTimeout(()=>{n.removeEventListener("abort",c),o(void 0)},a.POLLING_INTERVAL_MS)})}throw new Error("Payment verification timed out.")}async recoverAfterPollingTimeout(e,r){return await this.cancelSessionWithTimeout(r),await this.verifyFinalStatusWithRetry(e,r)}async cancelSessionWithTimeout(e){let r;try{await Promise.race([this.cancelSession(e),new Promise((t,n)=>{r=setTimeout(()=>{n(new Error("Viva timeout cancellation timed out"))},a.TIMEOUT_CANCEL_TIMEOUT_MS)})])}catch{}finally{r&&clearTimeout(r)}}async cancelSession(e){return await this.api.cancelVivaTransactionV2({cashRegisterId:this.config.storeId,sessionId:e}),this.currentSessionId===e&&(this.currentSessionId=null),!0}async verifyFinalStatusWithRetry(e,r){let t;for(let n=1;n<=a.VERIFY_MAX_RETRIES;n++)try{let s=await Promise.race([this.verifyFinalStatus(e,r),new Promise((i,o)=>setTimeout(()=>o(new Error("Verify timed out")),a.VERIFY_TIMEOUT_MS))]);if(s.status==="PENDING"){t=new Error("Verify returned pending status"),n<a.VERIFY_MAX_RETRIES&&await new Promise(i=>setTimeout(i,a.VERIFY_RETRY_DELAY_MS));continue}return s}catch(s){t=s,n<a.VERIFY_MAX_RETRIES&&await new Promise(i=>setTimeout(i,a.VERIFY_RETRY_DELAY_MS))}throw new l(S.PaymentFailureCode.PaymentTimeout,"Payment Failed",t)}handleSuccess(e){let r=e.status===S.SimplePaymentStatus.Success,t={success:r,status:r?"SUCCESS":"FAILED",orderId:e.orderId,errorCode:e.error?.code||(r?"":S.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===S.SimplePaymentStatus.Success,s=t.status===S.SimplePaymentStatus.Pending,i={success:n,status:n?"SUCCESS":s?"PENDING":"FAILED",orderId:t.orderId,errorCode:t.error?.code||(n||s?"":S.PaymentFailureCode.SystemUnknown),errorMessage:t.error?.message||(n||s?"":"Transaction failed without error details")};return t.transactionId&&(i.transactionId=t.transactionId),t.error?.referenceError&&(i.errorReference=t.error.referenceError),t.transaction&&(i.transaction=t.transaction),i}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),s=n.success;return{success:s,status:s?"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"),W=require("axios");var L=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),s=this.extractOperationId(n.data);if(this.currentOperationId=s,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,h.PaymentEventType.StatusChanged,this.abortController.signal);return this.currentOperationId=null,i}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),s=this.extractOperationId(n.data);if(this.currentOperationId=s,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,h.PaymentEventType.RefundStatusChanged,this.abortController.signal);return this.currentOperationId=null,i}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 s=`worldline.requests.${e}`;return new Promise((i,o)=>{let c=!1,u=()=>{c=!0,typeof m=="function"&&m(),clearTimeout(y)},d=()=>{u(),o(new l("CANCELLED","Transaction cancelled"))};n.addEventListener("abort",d);let m=this.messaging.subscribe(s,t,p=>{c||p.status===h.SimplePaymentStatus.Pending||(u(),n.removeEventListener("abort",d),i(this.handlePaymentStatus(p)))}),y=setTimeout(async()=>{if(!(c||n.aborted))try{let p=await this.pollOrderStatus(e,r,this.config.storeId,n);i(this.handlePaymentStatus(p))}catch(p){o(new l("TIMEOUT","Payment timed out and polling failed",p))}finally{n.removeEventListener("abort",d),u()}},1e4)})}async pollOrderStatus(e,r,t,n){let o=Date.now()+12e4;for(;Date.now()<o;){if(n.aborted)throw new Error("Aborted");try{let{data:c}=await this.paymentApi.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(c.status!==h.SimplePaymentStatus.Pending)return c}catch(c){if(c instanceof Error&&c.message==="Aborted")throw c}await new Promise(c=>{let u=()=>{clearTimeout(d),c(void 0)};n.addEventListener("abort",u,{once:!0});let d=setTimeout(()=>{n.removeEventListener("abort",u),c(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,W.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 F=class a{strategy;axios;messaging;timeoutMs;logger;_currentState="IDLE";_listeners=[];_cancellationIntent=!1;_currentSessionId;_autoResetTimer;autoResetOptions;appToAppConfig;paymentSessionConfig;static TERMINAL_STATES=["SUCCESS","FAILED","INTERNAL_ERROR"];static RESTING_STATES=["IDLE",...a.TERMINAL_STATES];constructor(e,r,t,n={},s){this.axios=e,this.messaging=r,this.logger=n.logger,this.timeoutMs=n.timeoutMs||3e4,this.autoResetOptions=n.autoResetOnPaymentComplete,this.appToAppConfig=n.appToApp,this.paymentSessionConfig=n.paymentSession,this.strategy=s??this.resolveStrategy(t)}get version(){return M}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:I.PaymentFailureCode.PaymentCancelledByUser,DECLINED:I.PaymentFailureCode.PaymentDeclined,TERMINAL_BUSY:I.PaymentFailureCode.TerminalBusy,TERMINAL_OFFLINE:I.PaymentFailureCode.TerminalOffline,TIMEOUT:I.PaymentFailureCode.TerminalTimeout,NETWORK_ERROR:I.PaymentFailureCode.SystemProviderError,STRATEGY_ERROR:I.PaymentFailureCode.SystemProviderError,MISSING_CONFIG:I.PaymentFailureCode.SystemUnknown,INVALID_AMOUNT:I.PaymentFailureCode.SystemUnknown,UNKNOWN:I.PaymentFailureCode.SystemUnknown}[e]??I.PaymentFailureCode.SystemUnknown:I.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(a.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,a.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 I.PaymentProvider.Nets:return new w(this.axios,this.messaging,e);case I.PaymentProvider.Worldline:return new L(this.axios,this.messaging,e);case I.PaymentProvider.Viva:return this.appToAppConfig?.enabled?new D(this.axios,this.messaging,e,this.appToAppConfig):this.paymentSessionConfig?.enabled?new O(this.axios,this.messaging,e):new A(this.axios,this.messaging,e);default:return new A(this.axios,this.messaging,e)}}initiateTransaction=async(e,r)=>{let t=r??{},n=e.orderRef;if(!a.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");let i=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 o=(m,y)=>{y?.sessionId&&(this._currentSessionId=y.sessionId),m!=="FAILED"&&(this.transitionTo(m),this.fireStateCallback(m,t,n))},c=this.strategy.processPayment(e,o),d=(this.strategy.getExecutionMode?.()??"managed")==="callback_driven"?await c:await Promise.race([c,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()-i}),d}catch(o){return this.logger?.warn("Transaction interrupted. Handling final status...",{error:o}),await this.handleTransactionError(e,o,t)}};async handleTransactionError(e,r,t={}){let n=r instanceof l&&(r.code==="TIMEOUT"||r.code===I.PaymentFailureCode.PaymentTimeout);if(!this._cancellationIntent&&!n&&(this.transitionTo("VERIFYING"),this.safeFireCallback(()=>t.onVerifying?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId}))),this._cancellationIntent){try{if(this._currentSessionId){let i=await this.strategy.verifyFinalStatus(e,this._currentSessionId);if(i.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(i)),i}}catch(i){this.logger?.warn("Final status verification failed during cancellation",{err:i})}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 s;if(this.strategy.abort(),this._currentSessionId)try{let i=await this.strategy.verifyFinalStatus(e,this._currentSessionId);if(i.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(i)),i;s=n&&i.status==="PENDING"?this.buildErrorResultFromException(e.orderRef,r):i}catch(i){this.logger?.warn("Failed to get detailed error from verifyFinalStatus",{verifyErr:i}),s=this.buildErrorResultFromException(e.orderRef,i)}else s=this.buildErrorResultFromException(e.orderRef,r);return this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(s)),s}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"),a.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=()=>{a.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,!a.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");this.transitionTo("IDLE");try{let s=(o,c)=>{c?.sessionId&&(this._currentSessionId=c.sessionId),o!=="FAILED"&&(this.transitionTo(o),this.fireStateCallback(o,t,e.orderRef))},i=await this.strategy.refundTransaction(e,s);return i.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(i))):this._cancellationIntent||i.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId}))):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(i))),this.logger?.info("Refund completed",{success:i.success,orderRef:e.orderRef}),i}catch(s){if(this.logger?.error("Refund failed",s),this._cancellationIntent){try{if(this._currentSessionId){let o=await this.strategy.verifyFinalStatus(e,this._currentSessionId);return o.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(o)),o):o.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId})),o):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(o)),o)}}catch(o){this.logger?.warn("Refund final status verification failed",{verifyError:o})}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 i=this.generateErrorResult(e.orderRef,"UNKNOWN",s instanceof Error?s.message:"Refund failed");return this.safeFireCallback(()=>t.onError?.(i)),i}};revert=async(e,r)=>{let t=r??{};if(this.logger?.info("Reverting payment",{orderRef:e.orderRef}),this._currentSessionId=e.originalTransactionId,this._cancellationIntent=!1,!a.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");let n=this.strategy.revertTransaction?.bind(this.strategy);if(!n)return this.generateErrorResult(e.orderRef,"STRATEGY_ERROR","Revert is not supported by the active payment strategy");this.transitionTo("CONNECTING");try{let s=await n(e);return this.settleSingleShot(s,e.orderRef,t),s}catch(s){return this.logger?.error("Revert failed",s),this.failSingleShot(e.orderRef,s,"Revert failed",t)}};settleSingleShot(e,r,t){e.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(e))):e.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:r,refPaymentId:this._currentSessionId}))):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(e)))}failSingleShot(e,r,t,n){let s=this.generateErrorResult(e,"NETWORK_ERROR",r instanceof Error?r.message:t);return this.transitionTo("FAILED"),this.safeFireCallback(()=>n.onError?.(s)),s}};var G=(n=>(n.CONNECTING="CONNECTING",n.CONNECTED="CONNECTED",n.OFFLINE="OFFLINE",n.DISCONNECTED="DISCONNECTED",n))(G||{});0&&(module.exports={AppReaderStatus,MunchiPaymentSDK,PaymentInteractionState,SdkPaymentStatus});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{PaymentFailureCode as f,PaymentProvider as M}from"@munchi_oy/core";var k="1.10.4";var l=class a extends Error{code;rawError;constructor(e,r,t){super(r),this.name="PaymentSDKError",this.code=e,this.rawError=t,Object.setPrototypeOf(this,a.prototype)}};import{PaymentApi as j,PaymentEventType as z,PaymentProviderEnum as X,SimplePaymentStatus as v,TransactionType as V}from"@munchi_oy/core";var R=(i=>(i.PENDING="PENDING",i.SUCCESS="SUCCESS",i.APPROVED="APPROVED",i.FAILED="FAILED",i.CANCELLED="CANCELLED",i.ERROR="ERROR",i))(R||{}),g=(c=>(c.IDLE="IDLE",c.CONNECTING="CONNECTING",c.REQUIRES_INPUT="REQUIRES_INPUT",c.PROCESSING="PROCESSING",c.SUCCESS="SUCCESS",c.FAILED="FAILED",c.INTERNAL_ERROR="INTERNAL_ERROR",c.VERIFYING="VERIFYING",c))(g||{});var b=class{constructor(e,r,t){this.messaging=r;this.config=t;this.api=new j(void 0,"",e)}api;abortController=null;currentRequestId=null;paymentProvider=X.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:V.Purchase}};try{let{data:n}=await this.api.initiateNetsTerminalTransaction(t),s=n.connectCloudRequestId;if(!s)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=s,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,this.abortController.signal);return this.currentRequestId=null,i}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}`,s=z.StatusChanged;return new Promise((i,o)=>{let c=!1,u=()=>{c=!0,typeof m=="function"&&m(),clearTimeout(y)},d=()=>{u(),o(new l("CANCELLED","Transaction cancelled"))};t.addEventListener("abort",d);let m=this.messaging.subscribe(n,s,p=>{c||p.status===v.Pending||(u(),t.removeEventListener("abort",d),i(this.handleSuccess(p)))}),y=setTimeout(async()=>{if(!(c||t.aborted))try{let p=await this.pollOrderStatus(e,r,this.config.storeId,t);i(this.handleSuccess(p))}catch(p){o(new l("TIMEOUT","Payment timed out and polling failed",p))}finally{t.removeEventListener("abort",d),u()}},1e4)})}async pollOrderStatus(e,r,t,n){let c=Date.now()+12e4;for(;Date.now()<c;){if(n.aborted)throw new Error("Aborted");try{let{data:u}=await this.api.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(u.status!==v.Pending)return u}catch(u){if(u instanceof Error&&u.message==="Aborted")throw u}await new Promise(u=>{let d=()=>{clearTimeout(m),u(void 0)};n.addEventListener("abort",d,{once:!0});let m=setTimeout(()=>{n.removeEventListener("abort",d),u(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:V.ReturnOfGoods}},{data:n}=await this.api.initiateNetsTerminalTransaction(t),s=n.connectCloudRequestId;if(!s)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=s,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,this.abortController.signal);return this.currentRequestId=null,i}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===v.Success,t=e.status===v.Pending,n={success:r,status:r?"SUCCESS":t?"PENDING":"FAILED",orderId:e.orderId,transaction:e.transaction};return e.transactionId&&(n.transactionId=e.transactionId),e.error?.code&&(n.errorCode=e.error.code),e.error?.message&&(n.errorMessage=e.error.message),n}abort(){this.abortController?.abort()}};import{FeeType as G,PaymentFailureCode as T,PaymentMethod as w,PaymentProvider as J,PaymentSessionApi as Z,PaymentSessionStatus as K}from"@munchi_oy/core";var A=a=>{if(!a)return 0;let e=Number.parseInt(a,10);return Number.isFinite(e)?e:0},W=a=>{if(!a)return new Date().toISOString();let e=new Date(a);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()};var ee="vivapayclient://pay/v1",te="abort",re="sale",q="transactionDetails",ne=4e3,se="534287",ie="38",oe="493591",ae="497439",ce=[oe,ae],le=["CREDIT","PREPAID","CORPORATE"],N=class{constructor(e,r,t,n){this.config=t;this.appToAppConfig=n;this.sessionApi=new Z(void 0,"",e)}sessionApi;abortController=null;currentClientTransactionId=null;currentIsvClientTransactionId=null;currentCurrency=null;currentOrderRef=null;currentSourceTerminalId=null;latestResult=null;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.sessionApi.initiateVivaA2aSession(this.buildCreatePaymentPayload(e));return await this.runAction(re,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(te,{}))}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){try{let t={sessionId:e.originalTransactionId,amount:e.amountCents},{data:n}=await this.sessionApi.refundVivaSession(t),s=n.status===K.Refunded||n.status===K.Refunding,i={success:s,status:s?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:n.providerTransactionId??n.sessionId};return s||(n.errorCode&&(i.errorCode=n.errorCode),n.errorMessage&&(i.errorMessage=n.errorMessage)),i}catch(t){throw new l("NETWORK_ERROR","Failed to refund Viva transaction",t)}}async verifyFinalStatus(e,r){return this.latestResult?this.latestResult:this.wasCancelled?{success:!1,status:"CANCELLED",orderId:this.currentOrderRef??r,errorCode:T.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 s=this.currentClientTransactionId?{sessionId:this.currentClientTransactionId}:void 0;return new Promise((i,o)=>{let c=(m,y)=>{m?.(),this.abortController?.signal.removeEventListener("abort",y)},u=()=>{c(d,u),o(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,c(d,u),i(y.result))});this.abortController?.signal.addEventListener("abort",u),n("REQUIRES_INPUT",s),this.appToAppConfig.adapter.openUrl(this.buildActionUrl(e,r)).then(()=>{this.abortController?.signal.aborted}).catch(m=>{c(d,u),this.currentClientTransactionId=null,this.currentIsvClientTransactionId=null,this.currentCurrency=null,this.currentOrderRef=null,this.currentSourceTerminalId=null,o(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:!1,showTransactionResult:!1};return r.tipAmount!==void 0&&(t.tipAmount=r.tipAmount),e.splitContext!==void 0&&(t.splitContext=e.splitContext),t}buildLaunchParams(e){let r={};return Object.entries(e).forEach(([t,n])=>{n!==void 0&&(t==="clientToken"||t==="sessionId"||(r[t]=String(n)))}),r}buildActionUrl(e,r){let t=new URLSearchParams({action:e,appId:this.appToAppConfig.appId,callback:this.resolveCallbackQueryParam()});return Object.entries(r).forEach(([n,s])=>{t.set(n,s)}),`${ee}?${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),s=this.isCancelledCallback(t),i=this.resolveFailureCode(t,s),o={success:n,status:n?"SUCCESS":s?"CANCELLED":"FAILED",orderId:this.currentOrderRef??t.clientTransactionId??"unknown",errorCode:n?"":i,errorMessage:n?"":t.message??"Transaction failed without error details"};n&&(o.transaction=this.mapCallbackToTransaction(t));let c=t.transactionId??t.orderCode??t.clientTransactionId,u=t.errorCode??this.extractErrorReferenceFromMessage(t.message)??t.referenceNumber??t.tid??t.rrn;return c&&(o.transactionId=c),u&&(o.errorReference=u),{rawParams:t,result:o}}matchesCallbackBase(e){let r=new URL(e),t=this.appToAppConfig.callbackUrl;if(!t.includes("://")){let s=t.replace(/:$/,"");return r.protocol===`${s}:`}let n=new URL(t);return r.protocol===n.protocol&&r.hostname===n.hostname&&r.pathname===n.pathname}resolveCallbackQueryParam(){if(this.appToAppConfig.callbackParamFormat!=="scheme-only")return this.appToAppConfig.callbackUrl;let e=this.appToAppConfig.callbackUrl;return e.includes("://")?new URL(e).protocol.replace(/:$/,""):e.replace(/:$/,"")}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 T.PaymentCancelledByUser;let t=e.errorCode;if(t?.includes("."))return t;if(this.isTransactionDetailsAction(e)&&(e.transactionType??"").toLowerCase().includes("abort"))return T.SystemUnknown;let n=(e.message??"").toLowerCase(),s=(e.status??"").toLowerCase();return n.includes("declined")||s==="declined"||s==="fail"||s==="failed"||s==="failure"?T.PaymentDeclined:T.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()===q.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")||t.includes("cancelled by user")||t.includes("canceled by user")||t.includes("transaction cancelled by user")||t.includes("transaction canceled by user")||n.includes("user_cancel")||n.includes("user cancel")||n==="1000"&&(t.includes("cancelled by user")||t.includes("canceled by user"))}extractErrorReferenceFromMessage(e){return e?e.match(/\((-?\d+)\)/)?.[1]:void 0}mapCallbackToTransaction(e){let r=e.transactionId??e.orderCode??e.clientTransactionId??"unknown",t=W(e.transactionDate),n=A(e.tipAmount),s=A(e.surchargeAmount);return{amount:A(e.amount)-n-s,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.buildFees(n,s),id:r,label:null,provider:J.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),s=(e.bankId??"").trim();return n===se||s===ie?w.Edenred:ce.includes(n)?w.WoltBenefit:le.some(i=>r.includes(i))?w.Credit:w.Debit}buildFees(e,r){if(!this.currentCurrency)return null;let t=[];return e>0&&t.push({taxAmount:0,total:{amount:e,currency:this.currentCurrency},type:G.TipAmount,vatPercentage:0}),r>0&&t.push({taxAmount:0,total:{amount:r,currency:this.currentCurrency},type:G.Surcharge,vatPercentage:0}),t.length===0?null:{parts:t}}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,s(),r(null))},ne),s=this.appToAppConfig.adapter.subscribe(i=>{if(t)return;let o=this.parseCallbackUrl(i);o&&this.matchesKnownTransactionId(o.rawParams)&&(t=!0,clearTimeout(n),s(),r(o.result))});this.appToAppConfig.adapter.openUrl(this.buildActionUrl(q,e)).catch(()=>{t||(t=!0,clearTimeout(n),s(),r(null))})})}};import{PaymentFailureCode as me,PaymentSessionApi as pe,PaymentSessionStatus as _,SimplePaymentStatus as B}from"@munchi_oy/core";import{PaymentFailureCode as ue,PaymentSessionStatus as I}from"@munchi_oy/core";function de(a){throw new l("UNKNOWN",`Unhandled payment session status: ${String(a)}`)}function D(a){return{success:!1,status:"PENDING",orderId:a,errorCode:"",errorMessage:""}}function Y(a,e){switch(a.status){case I.Initiated:case I.Processing:case I.Voiding:case I.Refunding:return D(e);case I.Success:case I.Closed:{let r={success:!0,status:"SUCCESS",orderId:e,errorCode:"",errorMessage:""};return a.providerTransactionId&&(r.transactionId=a.providerTransactionId),r}case I.VoidFailed:case I.Failed:{let r={success:!1,status:"FAILED",orderId:e,errorCode:a.errorCode||ue.SystemUnknown,errorMessage:a.errorMessage||"Transaction failed without error details"};return a.providerTransactionId&&(r.transactionId=a.providerTransactionId),r}case I.Cancelled:case I.Voided:case I.Refunded:{let r={success:!1,status:"CANCELLED",orderId:e};return a.errorCode&&(r.errorCode=a.errorCode),a.errorMessage&&(r.errorMessage=a.errorMessage),a.providerTransactionId&&(r.transactionId=a.providerTransactionId),r}default:return de(a.status)}}var O=class a{constructor(e,r,t){this.messaging=r;this.config=t;this.sessionApi=new pe(void 0,"",e)}static POLLING_DURATION_MS=18e4;static POLLING_INTERVAL_MS=1e3;static VERIFY_DURATION_MS=3e4;static INITIAL_POLL_DELAY_MS=1e4;sessionApi;abortController=null;idempotencyKey=null;idempotencyOrderRef=null;currentClientToken=null;async processPayment(e,r){this.abortController=new AbortController,(this.idempotencyKey===null||this.idempotencyOrderRef!==e.orderRef)&&(this.idempotencyKey=this.generateIdempotencyKey(),this.idempotencyOrderRef=e.orderRef),this.currentClientToken=null,r("CONNECTING");let t={amount:e.amountCents,businessId:Number(this.config.storeId),orderId:e.orderRef};e.splitContext!==void 0&&(t.splitContext=e.splitContext);try{let{data:n}=await this.sessionApi.initiateVivaSession(t,this.idempotencyKey);this.currentClientToken=n.clientToken;let s=this.abortController.signal;if(s.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:n.sessionId});let i=await this.waitForCompletion(n.clientToken,n.sessionId,e,s);return i?this.finalize(i):(await this.armCancel(n.clientToken),D(e.orderRef))}catch(n){throw n instanceof l?n:new l("NETWORK_ERROR","Failed to create Viva payment session",n)}}async verifyFinalStatus(e,r){if(!this.currentClientToken)throw new l("NETWORK_ERROR","No active payment session to verify");let t=await this.pollUntilTerminal(this.currentClientToken,e,void 0,a.VERIFY_DURATION_MS);return this.finalize(t??D(e.orderRef))}async cancelTransaction(e){if(!this.currentClientToken)return!1;try{await this.sessionApi.cancelVivaSession(this.currentClientToken)}catch(r){throw new l("NETWORK_ERROR","Failed to cancel Viva payment session",r)}return this.abortController?.abort(),!0}async refundTransaction(e,r){try{let t={sessionId:e.originalTransactionId,amount:e.amountCents},{data:n}=await this.sessionApi.refundVivaSession(t),s=n.status===_.Refunded||n.status===_.Refunding,i={success:s,status:s?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:n.providerTransactionId??n.sessionId};return s||(n.errorCode&&(i.errorCode=n.errorCode),n.errorMessage&&(i.errorMessage=n.errorMessage)),i}catch(t){throw new l("NETWORK_ERROR","Failed to refund Viva transaction",t)}}async revertTransaction(e){try{let r={sessionId:e.originalTransactionId},{data:t}=await this.sessionApi.revertVivaSession(r),n=t.status===_.Refunded||t.status===_.Refunding,s={success:n,status:n?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:t.providerTransactionId??t.sessionId};return n||(t.errorCode&&(s.errorCode=t.errorCode),t.errorMessage&&(s.errorMessage=t.errorMessage)),s}catch(r){throw new l("NETWORK_ERROR","Failed to revert Viva transaction",r)}}abort(){this.abortController?.abort()}async pollUntilTerminal(e,r,t,n){let s=Date.now()+n;for(;Date.now()<s;){if(t?.aborted)throw new Error("Aborted");let i;try{i=(await this.sessionApi.getPaymentSession(e)).data}catch(o){if(o instanceof Error&&o.message==="Aborted")throw o}if(t?.aborted)throw new Error("Aborted");if(i){let o=Y(i,r.orderRef);if(o.status!=="PENDING")return o}await this.delay(a.POLLING_INTERVAL_MS,t)}}waitForCompletion(e,r,t,n){let s=`viva.${this.config.channel.toLowerCase()}.requests.${r}`;return new Promise((i,o)=>{let c=!1,u=()=>{c=!0,typeof m=="function"&&m(),clearTimeout(y),n.removeEventListener("abort",d)},d=()=>{u(),o(new Error("Aborted"))};n.addEventListener("abort",d);let m=this.messaging.subscribe(s,"payment:status-changed",p=>{c||p.status!==B.Pending&&(u(),i(this.mapStatusDto(p,t)))}),y=setTimeout(()=>{c||this.pollUntilTerminal(e,t,n,a.POLLING_DURATION_MS).then(p=>{c||(u(),i(p))},p=>{c||(u(),o(p))})},a.INITIAL_POLL_DELAY_MS)})}mapStatusDto(e,r){let t=e.status===B.Success,n={success:t,status:t?"SUCCESS":"FAILED",orderId:r.orderRef,errorCode:e.error?.code||(t?"":me.SystemUnknown),errorMessage:e.error?.message||(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}finalize(e){return e.status!=="PENDING"&&(this.idempotencyKey=null,this.idempotencyOrderRef=null),e}armCancel(e){return this.sessionApi.cancelVivaSession(e).then(()=>{},()=>{})}generateIdempotencyKey(){let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let t=Math.random()*16|0;return(r==="x"?t:t&3|8).toString(16)})}delay(e,r){return new Promise(t=>{let n=()=>{clearTimeout(s),t()};r&&r.addEventListener("abort",n,{once:!0});let s=setTimeout(()=>{r&&r.removeEventListener("abort",n),t()},e)})}};import{PaymentApi as ye,PaymentFailureCode as x,PaymentProviderEnum as fe,SimplePaymentStatus as P}from"@munchi_oy/core";var C=class a{constructor(e,r,t){this.messaging=r;this.config=t;this.api=new ye(void 0,"",e)}static INITIAL_POLL_DELAY_MS=1e4;static POLLING_DURATION_MS=18e4;static POLLING_INTERVAL_MS=2e3;static TIMEOUT_CANCEL_TIMEOUT_MS=5e3;static VERIFY_TIMEOUT_MS=1e4;static VERIFY_MAX_RETRIES=3;static VERIFY_RETRY_DELAY_MS=1500;api;abortController=null;currentSessionId=null;paymentProvider=fe.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 s=await this.waitForPaymentCompletion(n.sessionId,e,this.abortController.signal);return this.currentSessionId=null,s}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 s=`viva.${this.config.channel.toLowerCase()}.requests.${e}`,i="payment:status-changed";return new Promise((o,c)=>{let u=!1,d=()=>{u=!0,typeof y=="function"&&y(),clearTimeout(p)},m=()=>{d(),c(new Error("Aborted"))};t.addEventListener("abort",m);let y=this.messaging.subscribe(s,i,h=>{u||h.status!==P.Pending&&(d(),t.removeEventListener("abort",m),o(this.handleSuccess(h)))}),p=setTimeout(async()=>{if(!(u||t.aborted))try{let h=await this.pollOrderStatus(e,r.orderRef,this.config.storeId,t);if(u)return;o(this.handleSuccess(h))}catch(h){if(u)return;if(h instanceof Error&&h.message==="Aborted"){c(h);return}try{let E=await this.recoverAfterPollingTimeout(r,e);o(E)}catch(E){c(E instanceof l?E:new l("TIMEOUT","Payment timed out and polling failed",E))}}finally{t.removeEventListener("abort",m),d()}},a.INITIAL_POLL_DELAY_MS)})}async pollOrderStatus(e,r,t,n){let i=Date.now()+a.POLLING_DURATION_MS;for(;Date.now()<i;){if(n.aborted)throw new Error("Aborted");try{let{data:o}=await this.api.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(o.status!==P.Pending)return o}catch(o){if(o instanceof Error&&o.message==="Aborted")throw o}await new Promise(o=>{let c=()=>{clearTimeout(u),o(void 0)};n.addEventListener("abort",c,{once:!0});let u=setTimeout(()=>{n.removeEventListener("abort",c),o(void 0)},a.POLLING_INTERVAL_MS)})}throw new Error("Payment verification timed out.")}async recoverAfterPollingTimeout(e,r){return await this.cancelSessionWithTimeout(r),await this.verifyFinalStatusWithRetry(e,r)}async cancelSessionWithTimeout(e){let r;try{await Promise.race([this.cancelSession(e),new Promise((t,n)=>{r=setTimeout(()=>{n(new Error("Viva timeout cancellation timed out"))},a.TIMEOUT_CANCEL_TIMEOUT_MS)})])}catch{}finally{r&&clearTimeout(r)}}async cancelSession(e){return await this.api.cancelVivaTransactionV2({cashRegisterId:this.config.storeId,sessionId:e}),this.currentSessionId===e&&(this.currentSessionId=null),!0}async verifyFinalStatusWithRetry(e,r){let t;for(let n=1;n<=a.VERIFY_MAX_RETRIES;n++)try{let s=await Promise.race([this.verifyFinalStatus(e,r),new Promise((i,o)=>setTimeout(()=>o(new Error("Verify timed out")),a.VERIFY_TIMEOUT_MS))]);if(s.status==="PENDING"){t=new Error("Verify returned pending status"),n<a.VERIFY_MAX_RETRIES&&await new Promise(i=>setTimeout(i,a.VERIFY_RETRY_DELAY_MS));continue}return s}catch(s){t=s,n<a.VERIFY_MAX_RETRIES&&await new Promise(i=>setTimeout(i,a.VERIFY_RETRY_DELAY_MS))}throw new l(x.PaymentTimeout,"Payment Failed",t)}handleSuccess(e){let r=e.status===P.Success,t={success:r,status:r?"SUCCESS":"FAILED",orderId:e.orderId,errorCode:e.error?.code||(r?"":x.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===P.Success,s=t.status===P.Pending,i={success:n,status:n?"SUCCESS":s?"PENDING":"FAILED",orderId:t.orderId,errorCode:t.error?.code||(n||s?"":x.SystemUnknown),errorMessage:t.error?.message||(n||s?"":"Transaction failed without error details")};return t.transactionId&&(i.transactionId=t.transactionId),t.error?.referenceError&&(i.errorReference=t.error.referenceError),t.transaction&&(i.transaction=t.transaction),i}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),s=n.success;return{success:s,status:s?"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 Ie,PaymentEventType as $,PaymentFailureCode as he,PaymentProviderEnum as Re,SimplePaymentStatus as L,WorldlineApi as ge}from"@munchi_oy/core";import{isAxiosError as Se}from"axios";var F=class{constructor(e,r,t){this.messaging=r;this.config=t;this.paymentApi=new Ie(void 0,"",e),this.worldlineApi=new ge(void 0,"",e)}paymentApi;worldlineApi;abortController=null;currentOperationId=null;paymentProvider=Re.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),s=this.extractOperationId(n.data);if(this.currentOperationId=s,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,$.StatusChanged,this.abortController.signal);return this.currentOperationId=null,i}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),s=this.extractOperationId(n.data);if(this.currentOperationId=s,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,$.RefundStatusChanged,this.abortController.signal);return this.currentOperationId=null,i}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 s=`worldline.requests.${e}`;return new Promise((i,o)=>{let c=!1,u=()=>{c=!0,typeof m=="function"&&m(),clearTimeout(y)},d=()=>{u(),o(new l("CANCELLED","Transaction cancelled"))};n.addEventListener("abort",d);let m=this.messaging.subscribe(s,t,p=>{c||p.status===L.Pending||(u(),n.removeEventListener("abort",d),i(this.handlePaymentStatus(p)))}),y=setTimeout(async()=>{if(!(c||n.aborted))try{let p=await this.pollOrderStatus(e,r,this.config.storeId,n);i(this.handlePaymentStatus(p))}catch(p){o(new l("TIMEOUT","Payment timed out and polling failed",p))}finally{n.removeEventListener("abort",d),u()}},1e4)})}async pollOrderStatus(e,r,t,n){let o=Date.now()+12e4;for(;Date.now()<o;){if(n.aborted)throw new Error("Aborted");try{let{data:c}=await this.paymentApi.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(c.status!==L.Pending)return c}catch(c){if(c instanceof Error&&c.message==="Aborted")throw c}await new Promise(c=>{let u=()=>{clearTimeout(d),c(void 0)};n.addEventListener("abort",u,{once:!0});let d=setTimeout(()=>{n.removeEventListener("abort",u),c(void 0)},2e3)})}throw new Error("Payment verification timed out.")}handlePaymentStatus(e){let r=e.status===L.Success,t=e.status===L.Pending,n={success:r,status:r?"SUCCESS":t?"PENDING":"FAILED",orderId:e.orderId,errorCode:e.error?.code||(r||t?"":he.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(Se(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 U=class a{strategy;axios;messaging;timeoutMs;logger;_currentState="IDLE";_listeners=[];_cancellationIntent=!1;_currentSessionId;_autoResetTimer;autoResetOptions;appToAppConfig;paymentSessionConfig;static TERMINAL_STATES=["SUCCESS","FAILED","INTERNAL_ERROR"];static RESTING_STATES=["IDLE",...a.TERMINAL_STATES];constructor(e,r,t,n={},s){this.axios=e,this.messaging=r,this.logger=n.logger,this.timeoutMs=n.timeoutMs||3e4,this.autoResetOptions=n.autoResetOnPaymentComplete,this.appToAppConfig=n.appToApp,this.paymentSessionConfig=n.paymentSession,this.strategy=s??this.resolveStrategy(t)}get version(){return k}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.PaymentCancelledByUser,DECLINED:f.PaymentDeclined,TERMINAL_BUSY:f.TerminalBusy,TERMINAL_OFFLINE:f.TerminalOffline,TIMEOUT:f.TerminalTimeout,NETWORK_ERROR:f.SystemProviderError,STRATEGY_ERROR:f.SystemProviderError,MISSING_CONFIG:f.SystemUnknown,INVALID_AMOUNT:f.SystemUnknown,UNKNOWN:f.SystemUnknown}[e]??f.SystemUnknown:f.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(a.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,a.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 M.Nets:return new b(this.axios,this.messaging,e);case M.Worldline:return new F(this.axios,this.messaging,e);case M.Viva:return this.appToAppConfig?.enabled?new N(this.axios,this.messaging,e,this.appToAppConfig):this.paymentSessionConfig?.enabled?new O(this.axios,this.messaging,e):new C(this.axios,this.messaging,e);default:return new C(this.axios,this.messaging,e)}}initiateTransaction=async(e,r)=>{let t=r??{},n=e.orderRef;if(!a.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");let i=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 o=(m,y)=>{y?.sessionId&&(this._currentSessionId=y.sessionId),m!=="FAILED"&&(this.transitionTo(m),this.fireStateCallback(m,t,n))},c=this.strategy.processPayment(e,o),d=(this.strategy.getExecutionMode?.()??"managed")==="callback_driven"?await c:await Promise.race([c,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()-i}),d}catch(o){return this.logger?.warn("Transaction interrupted. Handling final status...",{error:o}),await this.handleTransactionError(e,o,t)}};async handleTransactionError(e,r,t={}){let n=r instanceof l&&(r.code==="TIMEOUT"||r.code===f.PaymentTimeout);if(!this._cancellationIntent&&!n&&(this.transitionTo("VERIFYING"),this.safeFireCallback(()=>t.onVerifying?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId}))),this._cancellationIntent){try{if(this._currentSessionId){let i=await this.strategy.verifyFinalStatus(e,this._currentSessionId);if(i.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(i)),i}}catch(i){this.logger?.warn("Final status verification failed during cancellation",{err:i})}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 s;if(this.strategy.abort(),this._currentSessionId)try{let i=await this.strategy.verifyFinalStatus(e,this._currentSessionId);if(i.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(i)),i;s=n&&i.status==="PENDING"?this.buildErrorResultFromException(e.orderRef,r):i}catch(i){this.logger?.warn("Failed to get detailed error from verifyFinalStatus",{verifyErr:i}),s=this.buildErrorResultFromException(e.orderRef,i)}else s=this.buildErrorResultFromException(e.orderRef,r);return this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(s)),s}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"),a.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=()=>{a.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,!a.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");this.transitionTo("IDLE");try{let s=(o,c)=>{c?.sessionId&&(this._currentSessionId=c.sessionId),o!=="FAILED"&&(this.transitionTo(o),this.fireStateCallback(o,t,e.orderRef))},i=await this.strategy.refundTransaction(e,s);return i.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(i))):this._cancellationIntent||i.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId}))):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(i))),this.logger?.info("Refund completed",{success:i.success,orderRef:e.orderRef}),i}catch(s){if(this.logger?.error("Refund failed",s),this._cancellationIntent){try{if(this._currentSessionId){let o=await this.strategy.verifyFinalStatus(e,this._currentSessionId);return o.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(o)),o):o.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId})),o):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(o)),o)}}catch(o){this.logger?.warn("Refund final status verification failed",{verifyError:o})}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 i=this.generateErrorResult(e.orderRef,"UNKNOWN",s instanceof Error?s.message:"Refund failed");return this.safeFireCallback(()=>t.onError?.(i)),i}};revert=async(e,r)=>{let t=r??{};if(this.logger?.info("Reverting payment",{orderRef:e.orderRef}),this._currentSessionId=e.originalTransactionId,this._cancellationIntent=!1,!a.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");let n=this.strategy.revertTransaction?.bind(this.strategy);if(!n)return this.generateErrorResult(e.orderRef,"STRATEGY_ERROR","Revert is not supported by the active payment strategy");this.transitionTo("CONNECTING");try{let s=await n(e);return this.settleSingleShot(s,e.orderRef,t),s}catch(s){return this.logger?.error("Revert failed",s),this.failSingleShot(e.orderRef,s,"Revert failed",t)}};settleSingleShot(e,r,t){e.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(e))):e.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:r,refPaymentId:this._currentSessionId}))):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(e)))}failSingleShot(e,r,t,n){let s=this.generateErrorResult(e,"NETWORK_ERROR",r instanceof Error?r.message:t);return this.transitionTo("FAILED"),this.safeFireCallback(()=>n.onError?.(s)),s}};var Ee=(n=>(n.CONNECTING="CONNECTING",n.CONNECTED="CONNECTED",n.OFFLINE="OFFLINE",n.DISCONNECTED="DISCONNECTED",n))(Ee||{});export{Ee as AppReaderStatus,U as MunchiPaymentSDK,g as PaymentInteractionState,R as SdkPaymentStatus};
1
+ import{PaymentFailureCode as f,PaymentProvider as M}from"@munchi_oy/core";var k="1.10.5";var l=class a extends Error{code;rawError;constructor(e,r,t){super(r),this.name="PaymentSDKError",this.code=e,this.rawError=t,Object.setPrototypeOf(this,a.prototype)}};import{PaymentApi as j,PaymentEventType as z,PaymentProviderEnum as X,SimplePaymentStatus as v,TransactionType as V}from"@munchi_oy/core";var R=(i=>(i.PENDING="PENDING",i.SUCCESS="SUCCESS",i.APPROVED="APPROVED",i.FAILED="FAILED",i.CANCELLED="CANCELLED",i.ERROR="ERROR",i))(R||{}),g=(c=>(c.IDLE="IDLE",c.CONNECTING="CONNECTING",c.REQUIRES_INPUT="REQUIRES_INPUT",c.PROCESSING="PROCESSING",c.SUCCESS="SUCCESS",c.FAILED="FAILED",c.INTERNAL_ERROR="INTERNAL_ERROR",c.VERIFYING="VERIFYING",c))(g||{});var b=class{constructor(e,r,t){this.messaging=r;this.config=t;this.api=new j(void 0,"",e)}api;abortController=null;currentRequestId=null;paymentProvider=X.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:V.Purchase}};try{let{data:n}=await this.api.initiateNetsTerminalTransaction(t),s=n.connectCloudRequestId;if(!s)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=s,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,this.abortController.signal);return this.currentRequestId=null,i}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}`,s=z.StatusChanged;return new Promise((i,o)=>{let c=!1,u=()=>{c=!0,typeof m=="function"&&m(),clearTimeout(y)},d=()=>{u(),o(new l("CANCELLED","Transaction cancelled"))};t.addEventListener("abort",d);let m=this.messaging.subscribe(n,s,p=>{c||p.status===v.Pending||(u(),t.removeEventListener("abort",d),i(this.handleSuccess(p)))}),y=setTimeout(async()=>{if(!(c||t.aborted))try{let p=await this.pollOrderStatus(e,r,this.config.storeId,t);i(this.handleSuccess(p))}catch(p){o(new l("TIMEOUT","Payment timed out and polling failed",p))}finally{t.removeEventListener("abort",d),u()}},1e4)})}async pollOrderStatus(e,r,t,n){let c=Date.now()+12e4;for(;Date.now()<c;){if(n.aborted)throw new Error("Aborted");try{let{data:u}=await this.api.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(u.status!==v.Pending)return u}catch(u){if(u instanceof Error&&u.message==="Aborted")throw u}await new Promise(u=>{let d=()=>{clearTimeout(m),u(void 0)};n.addEventListener("abort",d,{once:!0});let m=setTimeout(()=>{n.removeEventListener("abort",d),u(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:V.ReturnOfGoods}},{data:n}=await this.api.initiateNetsTerminalTransaction(t),s=n.connectCloudRequestId;if(!s)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=s,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,this.abortController.signal);return this.currentRequestId=null,i}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===v.Success,t=e.status===v.Pending,n={success:r,status:r?"SUCCESS":t?"PENDING":"FAILED",orderId:e.orderId,transaction:e.transaction};return e.transactionId&&(n.transactionId=e.transactionId),e.error?.code&&(n.errorCode=e.error.code),e.error?.message&&(n.errorMessage=e.error.message),n}abort(){this.abortController?.abort()}};import{FeeType as G,PaymentFailureCode as T,PaymentMethod as w,PaymentProvider as J,PaymentSessionApi as Z,PaymentSessionStatus as K}from"@munchi_oy/core";var A=a=>{if(!a)return 0;let e=Number.parseInt(a,10);return Number.isFinite(e)?e:0},W=a=>{if(!a)return new Date().toISOString();let e=new Date(a);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()};var ee="vivapayclient://pay/v1",te="abort",re="sale",q="transactionDetails",ne=4e3,se="534287",ie="38",oe="493591",ae="497439",ce=[oe,ae],le=["CREDIT","PREPAID","CORPORATE"],N=class{constructor(e,r,t,n){this.config=t;this.appToAppConfig=n;this.sessionApi=new Z(void 0,"",e)}sessionApi;abortController=null;currentClientTransactionId=null;currentIsvClientTransactionId=null;currentCurrency=null;currentOrderRef=null;currentSourceTerminalId=null;latestResult=null;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.sessionApi.initiateVivaA2aSession(this.buildCreatePaymentPayload(e));return await this.runAction(re,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(te,{}))}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){try{let t={sessionId:e.originalTransactionId,amount:e.amountCents},{data:n}=await this.sessionApi.refundVivaSession(t),s=n.status===K.Refunded||n.status===K.Refunding,i={success:s,status:s?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:n.providerTransactionId??n.sessionId};return s||(n.errorCode&&(i.errorCode=n.errorCode),n.errorMessage&&(i.errorMessage=n.errorMessage)),i}catch(t){throw new l("NETWORK_ERROR","Failed to refund Viva transaction",t)}}async verifyFinalStatus(e,r){return this.latestResult?this.latestResult:this.wasCancelled?{success:!1,status:"CANCELLED",orderId:this.currentOrderRef??r,errorCode:T.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 s=this.currentClientTransactionId?{sessionId:this.currentClientTransactionId}:void 0;return new Promise((i,o)=>{let c=(m,y)=>{m?.(),this.abortController?.signal.removeEventListener("abort",y)},u=()=>{c(d,u),o(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,c(d,u),i(y.result))});this.abortController?.signal.addEventListener("abort",u),n("REQUIRES_INPUT",s),this.appToAppConfig.adapter.openUrl(this.buildActionUrl(e,r)).then(()=>{this.abortController?.signal.aborted}).catch(m=>{c(d,u),this.currentClientTransactionId=null,this.currentIsvClientTransactionId=null,this.currentCurrency=null,this.currentOrderRef=null,this.currentSourceTerminalId=null,o(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:!1,showTransactionResult:!1};return r.tipAmount!==void 0&&(t.tipAmount=r.tipAmount),e.splitContext!==void 0&&(t.splitContext=e.splitContext),t}buildLaunchParams(e){let r={};return Object.entries(e).forEach(([t,n])=>{n!==void 0&&(t==="clientToken"||t==="sessionId"||(r[t]=String(n)))}),r}buildActionUrl(e,r){let t=new URLSearchParams({action:e,appId:this.appToAppConfig.appId,callback:this.resolveCallbackQueryParam()});return Object.entries(r).forEach(([n,s])=>{t.set(n,s)}),`${ee}?${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),s=this.isCancelledCallback(t),i=this.resolveFailureCode(t,s),o={success:n,status:n?"SUCCESS":s?"CANCELLED":"FAILED",orderId:this.currentOrderRef??t.clientTransactionId??"unknown",errorCode:n?"":i,errorMessage:n?"":t.message??"Transaction failed without error details"};n&&(o.transaction=this.mapCallbackToTransaction(t));let c=t.transactionId??t.orderCode??t.clientTransactionId,u=t.errorCode??this.extractErrorReferenceFromMessage(t.message)??t.referenceNumber??t.tid??t.rrn;return c&&(o.transactionId=c),u&&(o.errorReference=u),{rawParams:t,result:o}}matchesCallbackBase(e){let r=new URL(e),t=this.appToAppConfig.callbackUrl;if(!t.includes("://")){let s=t.replace(/:$/,"");return r.protocol===`${s}:`}let n=new URL(t);return r.protocol===n.protocol&&r.hostname===n.hostname&&r.pathname===n.pathname}resolveCallbackQueryParam(){if(this.appToAppConfig.callbackParamFormat!=="scheme-only")return this.appToAppConfig.callbackUrl;let e=this.appToAppConfig.callbackUrl;return e.includes("://")?new URL(e).protocol.replace(/:$/,""):e.replace(/:$/,"")}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 T.PaymentCancelledByUser;let t=e.errorCode;if(t?.includes("."))return t;if(this.isTransactionDetailsAction(e)&&(e.transactionType??"").toLowerCase().includes("abort"))return T.SystemUnknown;let n=(e.message??"").toLowerCase(),s=(e.status??"").toLowerCase();return n.includes("declined")||s==="declined"||s==="fail"||s==="failed"||s==="failure"?T.PaymentDeclined:T.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()===q.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")||t.includes("cancelled by user")||t.includes("canceled by user")||t.includes("transaction cancelled by user")||t.includes("transaction canceled by user")||n.includes("user_cancel")||n.includes("user cancel")||n==="1000"&&(t.includes("cancelled by user")||t.includes("canceled by user"))}extractErrorReferenceFromMessage(e){return e?e.match(/\((-?\d+)\)/)?.[1]:void 0}mapCallbackToTransaction(e){let r=e.transactionId??e.orderCode??e.clientTransactionId??"unknown",t=W(e.transactionDate),n=A(e.tipAmount),s=A(e.surchargeAmount);return{amount:A(e.amount)-n-s,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.buildFees(n,s),id:r,label:null,provider:J.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),s=(e.bankId??"").trim();return n===se||s===ie?w.Edenred:ce.includes(n)?w.WoltBenefit:le.some(i=>r.includes(i))?w.Credit:w.Debit}buildFees(e,r){if(!this.currentCurrency)return null;let t=[];return e>0&&t.push({taxAmount:0,total:{amount:e,currency:this.currentCurrency},type:G.TipAmount,vatPercentage:0}),r>0&&t.push({taxAmount:0,total:{amount:r,currency:this.currentCurrency},type:G.Surcharge,vatPercentage:0}),t.length===0?null:{parts:t}}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,s(),r(null))},ne),s=this.appToAppConfig.adapter.subscribe(i=>{if(t)return;let o=this.parseCallbackUrl(i);o&&this.matchesKnownTransactionId(o.rawParams)&&(t=!0,clearTimeout(n),s(),r(o.result))});this.appToAppConfig.adapter.openUrl(this.buildActionUrl(q,e)).catch(()=>{t||(t=!0,clearTimeout(n),s(),r(null))})})}};import{PaymentFailureCode as me,PaymentSessionApi as pe,PaymentSessionStatus as _,SimplePaymentStatus as B}from"@munchi_oy/core";import{PaymentFailureCode as ue,PaymentSessionStatus as I}from"@munchi_oy/core";function de(a){throw new l("UNKNOWN",`Unhandled payment session status: ${String(a)}`)}function D(a){return{success:!1,status:"PENDING",orderId:a,errorCode:"",errorMessage:""}}function Y(a,e){switch(a.status){case I.Initiated:case I.Processing:case I.Voiding:case I.Refunding:case I.Dispatched:return D(e);case I.Success:case I.Closed:{let r={success:!0,status:"SUCCESS",orderId:e,errorCode:"",errorMessage:""};return a.providerTransactionId&&(r.transactionId=a.providerTransactionId),r}case I.VoidFailed:case I.Failed:{let r={success:!1,status:"FAILED",orderId:e,errorCode:a.errorCode||ue.SystemUnknown,errorMessage:a.errorMessage||"Transaction failed without error details"};return a.providerTransactionId&&(r.transactionId=a.providerTransactionId),r}case I.Cancelled:case I.Voided:case I.Refunded:{let r={success:!1,status:"CANCELLED",orderId:e};return a.errorCode&&(r.errorCode=a.errorCode),a.errorMessage&&(r.errorMessage=a.errorMessage),a.providerTransactionId&&(r.transactionId=a.providerTransactionId),r}default:return de(a.status)}}var O=class a{constructor(e,r,t){this.messaging=r;this.config=t;this.sessionApi=new pe(void 0,"",e)}static POLLING_DURATION_MS=18e4;static POLLING_INTERVAL_MS=1e3;static VERIFY_DURATION_MS=3e4;static INITIAL_POLL_DELAY_MS=1e4;sessionApi;abortController=null;idempotencyKey=null;idempotencyOrderRef=null;currentClientToken=null;async processPayment(e,r){this.abortController=new AbortController,(this.idempotencyKey===null||this.idempotencyOrderRef!==e.orderRef)&&(this.idempotencyKey=this.generateIdempotencyKey(),this.idempotencyOrderRef=e.orderRef),this.currentClientToken=null,r("CONNECTING");let t={amount:e.amountCents,businessId:Number(this.config.storeId),orderId:e.orderRef};e.splitContext!==void 0&&(t.splitContext=e.splitContext);try{let{data:n}=await this.sessionApi.initiateVivaSession(t,this.idempotencyKey);this.currentClientToken=n.clientToken;let s=this.abortController.signal;if(s.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:n.sessionId});let i=await this.waitForCompletion(n.clientToken,n.sessionId,e,s);return i?this.finalize(i):(await this.armCancel(n.clientToken),D(e.orderRef))}catch(n){throw n instanceof l?n:new l("NETWORK_ERROR","Failed to create Viva payment session",n)}}async verifyFinalStatus(e,r){if(!this.currentClientToken)throw new l("NETWORK_ERROR","No active payment session to verify");let t=await this.pollUntilTerminal(this.currentClientToken,e,void 0,a.VERIFY_DURATION_MS);return this.finalize(t??D(e.orderRef))}async cancelTransaction(e){if(!this.currentClientToken)return!1;try{await this.sessionApi.cancelVivaSession(this.currentClientToken)}catch(r){throw new l("NETWORK_ERROR","Failed to cancel Viva payment session",r)}return this.abortController?.abort(),!0}async refundTransaction(e,r){try{let t={sessionId:e.originalTransactionId,amount:e.amountCents},{data:n}=await this.sessionApi.refundVivaSession(t),s=n.status===_.Refunded||n.status===_.Refunding,i={success:s,status:s?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:n.providerTransactionId??n.sessionId};return s||(n.errorCode&&(i.errorCode=n.errorCode),n.errorMessage&&(i.errorMessage=n.errorMessage)),i}catch(t){throw new l("NETWORK_ERROR","Failed to refund Viva transaction",t)}}async revertTransaction(e){try{let r={sessionId:e.originalTransactionId},{data:t}=await this.sessionApi.revertVivaSession(r),n=t.status===_.Refunded||t.status===_.Refunding,s={success:n,status:n?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:t.providerTransactionId??t.sessionId};return n||(t.errorCode&&(s.errorCode=t.errorCode),t.errorMessage&&(s.errorMessage=t.errorMessage)),s}catch(r){throw new l("NETWORK_ERROR","Failed to revert Viva transaction",r)}}abort(){this.abortController?.abort()}async pollUntilTerminal(e,r,t,n){let s=Date.now()+n;for(;Date.now()<s;){if(t?.aborted)throw new Error("Aborted");let i;try{i=(await this.sessionApi.getPaymentSession(e)).data}catch(o){if(o instanceof Error&&o.message==="Aborted")throw o}if(t?.aborted)throw new Error("Aborted");if(i){let o=Y(i,r.orderRef);if(o.status!=="PENDING")return o}await this.delay(a.POLLING_INTERVAL_MS,t)}}waitForCompletion(e,r,t,n){let s=`viva.${this.config.channel.toLowerCase()}.requests.${r}`;return new Promise((i,o)=>{let c=!1,u=()=>{c=!0,typeof m=="function"&&m(),clearTimeout(y),n.removeEventListener("abort",d)},d=()=>{u(),o(new Error("Aborted"))};n.addEventListener("abort",d);let m=this.messaging.subscribe(s,"payment:status-changed",p=>{c||p.status!==B.Pending&&(u(),i(this.mapStatusDto(p,t)))}),y=setTimeout(()=>{c||this.pollUntilTerminal(e,t,n,a.POLLING_DURATION_MS).then(p=>{c||(u(),i(p))},p=>{c||(u(),o(p))})},a.INITIAL_POLL_DELAY_MS)})}mapStatusDto(e,r){let t=e.status===B.Success,n={success:t,status:t?"SUCCESS":"FAILED",orderId:r.orderRef,errorCode:e.error?.code||(t?"":me.SystemUnknown),errorMessage:e.error?.message||(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}finalize(e){return e.status!=="PENDING"&&(this.idempotencyKey=null,this.idempotencyOrderRef=null),e}armCancel(e){return this.sessionApi.cancelVivaSession(e).then(()=>{},()=>{})}generateIdempotencyKey(){let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let t=Math.random()*16|0;return(r==="x"?t:t&3|8).toString(16)})}delay(e,r){return new Promise(t=>{let n=()=>{clearTimeout(s),t()};r&&r.addEventListener("abort",n,{once:!0});let s=setTimeout(()=>{r&&r.removeEventListener("abort",n),t()},e)})}};import{PaymentApi as ye,PaymentFailureCode as x,PaymentProviderEnum as fe,SimplePaymentStatus as P}from"@munchi_oy/core";var C=class a{constructor(e,r,t){this.messaging=r;this.config=t;this.api=new ye(void 0,"",e)}static INITIAL_POLL_DELAY_MS=1e4;static POLLING_DURATION_MS=18e4;static POLLING_INTERVAL_MS=2e3;static TIMEOUT_CANCEL_TIMEOUT_MS=5e3;static VERIFY_TIMEOUT_MS=1e4;static VERIFY_MAX_RETRIES=3;static VERIFY_RETRY_DELAY_MS=1500;api;abortController=null;currentSessionId=null;paymentProvider=fe.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 s=await this.waitForPaymentCompletion(n.sessionId,e,this.abortController.signal);return this.currentSessionId=null,s}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 s=`viva.${this.config.channel.toLowerCase()}.requests.${e}`,i="payment:status-changed";return new Promise((o,c)=>{let u=!1,d=()=>{u=!0,typeof y=="function"&&y(),clearTimeout(p)},m=()=>{d(),c(new Error("Aborted"))};t.addEventListener("abort",m);let y=this.messaging.subscribe(s,i,h=>{u||h.status!==P.Pending&&(d(),t.removeEventListener("abort",m),o(this.handleSuccess(h)))}),p=setTimeout(async()=>{if(!(u||t.aborted))try{let h=await this.pollOrderStatus(e,r.orderRef,this.config.storeId,t);if(u)return;o(this.handleSuccess(h))}catch(h){if(u)return;if(h instanceof Error&&h.message==="Aborted"){c(h);return}try{let E=await this.recoverAfterPollingTimeout(r,e);o(E)}catch(E){c(E instanceof l?E:new l("TIMEOUT","Payment timed out and polling failed",E))}}finally{t.removeEventListener("abort",m),d()}},a.INITIAL_POLL_DELAY_MS)})}async pollOrderStatus(e,r,t,n){let i=Date.now()+a.POLLING_DURATION_MS;for(;Date.now()<i;){if(n.aborted)throw new Error("Aborted");try{let{data:o}=await this.api.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(o.status!==P.Pending)return o}catch(o){if(o instanceof Error&&o.message==="Aborted")throw o}await new Promise(o=>{let c=()=>{clearTimeout(u),o(void 0)};n.addEventListener("abort",c,{once:!0});let u=setTimeout(()=>{n.removeEventListener("abort",c),o(void 0)},a.POLLING_INTERVAL_MS)})}throw new Error("Payment verification timed out.")}async recoverAfterPollingTimeout(e,r){return await this.cancelSessionWithTimeout(r),await this.verifyFinalStatusWithRetry(e,r)}async cancelSessionWithTimeout(e){let r;try{await Promise.race([this.cancelSession(e),new Promise((t,n)=>{r=setTimeout(()=>{n(new Error("Viva timeout cancellation timed out"))},a.TIMEOUT_CANCEL_TIMEOUT_MS)})])}catch{}finally{r&&clearTimeout(r)}}async cancelSession(e){return await this.api.cancelVivaTransactionV2({cashRegisterId:this.config.storeId,sessionId:e}),this.currentSessionId===e&&(this.currentSessionId=null),!0}async verifyFinalStatusWithRetry(e,r){let t;for(let n=1;n<=a.VERIFY_MAX_RETRIES;n++)try{let s=await Promise.race([this.verifyFinalStatus(e,r),new Promise((i,o)=>setTimeout(()=>o(new Error("Verify timed out")),a.VERIFY_TIMEOUT_MS))]);if(s.status==="PENDING"){t=new Error("Verify returned pending status"),n<a.VERIFY_MAX_RETRIES&&await new Promise(i=>setTimeout(i,a.VERIFY_RETRY_DELAY_MS));continue}return s}catch(s){t=s,n<a.VERIFY_MAX_RETRIES&&await new Promise(i=>setTimeout(i,a.VERIFY_RETRY_DELAY_MS))}throw new l(x.PaymentTimeout,"Payment Failed",t)}handleSuccess(e){let r=e.status===P.Success,t={success:r,status:r?"SUCCESS":"FAILED",orderId:e.orderId,errorCode:e.error?.code||(r?"":x.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===P.Success,s=t.status===P.Pending,i={success:n,status:n?"SUCCESS":s?"PENDING":"FAILED",orderId:t.orderId,errorCode:t.error?.code||(n||s?"":x.SystemUnknown),errorMessage:t.error?.message||(n||s?"":"Transaction failed without error details")};return t.transactionId&&(i.transactionId=t.transactionId),t.error?.referenceError&&(i.errorReference=t.error.referenceError),t.transaction&&(i.transaction=t.transaction),i}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),s=n.success;return{success:s,status:s?"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 Ie,PaymentEventType as $,PaymentFailureCode as he,PaymentProviderEnum as Re,SimplePaymentStatus as L,WorldlineApi as ge}from"@munchi_oy/core";import{isAxiosError as Se}from"axios";var F=class{constructor(e,r,t){this.messaging=r;this.config=t;this.paymentApi=new Ie(void 0,"",e),this.worldlineApi=new ge(void 0,"",e)}paymentApi;worldlineApi;abortController=null;currentOperationId=null;paymentProvider=Re.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),s=this.extractOperationId(n.data);if(this.currentOperationId=s,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,$.StatusChanged,this.abortController.signal);return this.currentOperationId=null,i}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),s=this.extractOperationId(n.data);if(this.currentOperationId=s,this.abortController.signal.aborted)throw new Error("Aborted");r("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,$.RefundStatusChanged,this.abortController.signal);return this.currentOperationId=null,i}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 s=`worldline.requests.${e}`;return new Promise((i,o)=>{let c=!1,u=()=>{c=!0,typeof m=="function"&&m(),clearTimeout(y)},d=()=>{u(),o(new l("CANCELLED","Transaction cancelled"))};n.addEventListener("abort",d);let m=this.messaging.subscribe(s,t,p=>{c||p.status===L.Pending||(u(),n.removeEventListener("abort",d),i(this.handlePaymentStatus(p)))}),y=setTimeout(async()=>{if(!(c||n.aborted))try{let p=await this.pollOrderStatus(e,r,this.config.storeId,n);i(this.handlePaymentStatus(p))}catch(p){o(new l("TIMEOUT","Payment timed out and polling failed",p))}finally{n.removeEventListener("abort",d),u()}},1e4)})}async pollOrderStatus(e,r,t,n){let o=Date.now()+12e4;for(;Date.now()<o;){if(n.aborted)throw new Error("Aborted");try{let{data:c}=await this.paymentApi.getPaymentStatus({businessId:Number(t),orderId:r,provider:this.paymentProvider,referenceId:e});if(n.aborted)throw new Error("Aborted");if(c.status!==L.Pending)return c}catch(c){if(c instanceof Error&&c.message==="Aborted")throw c}await new Promise(c=>{let u=()=>{clearTimeout(d),c(void 0)};n.addEventListener("abort",u,{once:!0});let d=setTimeout(()=>{n.removeEventListener("abort",u),c(void 0)},2e3)})}throw new Error("Payment verification timed out.")}handlePaymentStatus(e){let r=e.status===L.Success,t=e.status===L.Pending,n={success:r,status:r?"SUCCESS":t?"PENDING":"FAILED",orderId:e.orderId,errorCode:e.error?.code||(r||t?"":he.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(Se(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 U=class a{strategy;axios;messaging;timeoutMs;logger;_currentState="IDLE";_listeners=[];_cancellationIntent=!1;_currentSessionId;_autoResetTimer;autoResetOptions;appToAppConfig;paymentSessionConfig;static TERMINAL_STATES=["SUCCESS","FAILED","INTERNAL_ERROR"];static RESTING_STATES=["IDLE",...a.TERMINAL_STATES];constructor(e,r,t,n={},s){this.axios=e,this.messaging=r,this.logger=n.logger,this.timeoutMs=n.timeoutMs||3e4,this.autoResetOptions=n.autoResetOnPaymentComplete,this.appToAppConfig=n.appToApp,this.paymentSessionConfig=n.paymentSession,this.strategy=s??this.resolveStrategy(t)}get version(){return k}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.PaymentCancelledByUser,DECLINED:f.PaymentDeclined,TERMINAL_BUSY:f.TerminalBusy,TERMINAL_OFFLINE:f.TerminalOffline,TIMEOUT:f.TerminalTimeout,NETWORK_ERROR:f.SystemProviderError,STRATEGY_ERROR:f.SystemProviderError,MISSING_CONFIG:f.SystemUnknown,INVALID_AMOUNT:f.SystemUnknown,UNKNOWN:f.SystemUnknown}[e]??f.SystemUnknown:f.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(a.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,a.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 M.Nets:return new b(this.axios,this.messaging,e);case M.Worldline:return new F(this.axios,this.messaging,e);case M.Viva:return this.appToAppConfig?.enabled?new N(this.axios,this.messaging,e,this.appToAppConfig):this.paymentSessionConfig?.enabled?new O(this.axios,this.messaging,e):new C(this.axios,this.messaging,e);default:return new C(this.axios,this.messaging,e)}}initiateTransaction=async(e,r)=>{let t=r??{},n=e.orderRef;if(!a.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");let i=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 o=(m,y)=>{y?.sessionId&&(this._currentSessionId=y.sessionId),m!=="FAILED"&&(this.transitionTo(m),this.fireStateCallback(m,t,n))},c=this.strategy.processPayment(e,o),d=(this.strategy.getExecutionMode?.()??"managed")==="callback_driven"?await c:await Promise.race([c,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()-i}),d}catch(o){return this.logger?.warn("Transaction interrupted. Handling final status...",{error:o}),await this.handleTransactionError(e,o,t)}};async handleTransactionError(e,r,t={}){let n=r instanceof l&&(r.code==="TIMEOUT"||r.code===f.PaymentTimeout);if(!this._cancellationIntent&&!n&&(this.transitionTo("VERIFYING"),this.safeFireCallback(()=>t.onVerifying?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId}))),this._cancellationIntent){try{if(this._currentSessionId){let i=await this.strategy.verifyFinalStatus(e,this._currentSessionId);if(i.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(i)),i}}catch(i){this.logger?.warn("Final status verification failed during cancellation",{err:i})}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 s;if(this.strategy.abort(),this._currentSessionId)try{let i=await this.strategy.verifyFinalStatus(e,this._currentSessionId);if(i.success)return this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(i)),i;s=n&&i.status==="PENDING"?this.buildErrorResultFromException(e.orderRef,r):i}catch(i){this.logger?.warn("Failed to get detailed error from verifyFinalStatus",{verifyErr:i}),s=this.buildErrorResultFromException(e.orderRef,i)}else s=this.buildErrorResultFromException(e.orderRef,r);return this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(s)),s}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"),a.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=()=>{a.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,!a.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");this.transitionTo("IDLE");try{let s=(o,c)=>{c?.sessionId&&(this._currentSessionId=c.sessionId),o!=="FAILED"&&(this.transitionTo(o),this.fireStateCallback(o,t,e.orderRef))},i=await this.strategy.refundTransaction(e,s);return i.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(i))):this._cancellationIntent||i.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId}))):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(i))),this.logger?.info("Refund completed",{success:i.success,orderRef:e.orderRef}),i}catch(s){if(this.logger?.error("Refund failed",s),this._cancellationIntent){try{if(this._currentSessionId){let o=await this.strategy.verifyFinalStatus(e,this._currentSessionId);return o.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(o)),o):o.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:e.orderRef,refPaymentId:this._currentSessionId})),o):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(o)),o)}}catch(o){this.logger?.warn("Refund final status verification failed",{verifyError:o})}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 i=this.generateErrorResult(e.orderRef,"UNKNOWN",s instanceof Error?s.message:"Refund failed");return this.safeFireCallback(()=>t.onError?.(i)),i}};revert=async(e,r)=>{let t=r??{};if(this.logger?.info("Reverting payment",{orderRef:e.orderRef}),this._currentSessionId=e.originalTransactionId,this._cancellationIntent=!1,!a.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");let n=this.strategy.revertTransaction?.bind(this.strategy);if(!n)return this.generateErrorResult(e.orderRef,"STRATEGY_ERROR","Revert is not supported by the active payment strategy");this.transitionTo("CONNECTING");try{let s=await n(e);return this.settleSingleShot(s,e.orderRef,t),s}catch(s){return this.logger?.error("Revert failed",s),this.failSingleShot(e.orderRef,s,"Revert failed",t)}};settleSingleShot(e,r,t){e.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(e))):e.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:r,refPaymentId:this._currentSessionId}))):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(e)))}failSingleShot(e,r,t,n){let s=this.generateErrorResult(e,"NETWORK_ERROR",r instanceof Error?r.message:t);return this.transitionTo("FAILED"),this.safeFireCallback(()=>n.onError?.(s)),s}};var Ee=(n=>(n.CONNECTING="CONNECTING",n.CONNECTED="CONNECTED",n.OFFLINE="OFFLINE",n.DISCONNECTED="DISCONNECTED",n))(Ee||{});export{Ee as AppReaderStatus,U as MunchiPaymentSDK,g as PaymentInteractionState,R as SdkPaymentStatus};
@@ -1 +1 @@
1
- {"version":3,"file":"sessionResult.d.ts","sourceRoot":"","sources":["../../../src/strategies/sessionResult.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,qBAAqB,EAC3B,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,KAAK,aAAa,EAAoB,MAAM,kBAAkB,CAAC;AASxE,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,aAAa,CAQ5D;AAED,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,qBAAqB,EAC3B,OAAO,EAAE,MAAM,GACd,aAAa,CA8Df"}
1
+ {"version":3,"file":"sessionResult.d.ts","sourceRoot":"","sources":["../../../src/strategies/sessionResult.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,qBAAqB,EAC3B,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,KAAK,aAAa,EAAoB,MAAM,kBAAkB,CAAC;AASxE,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,aAAa,CAQ5D;AAED,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,qBAAqB,EAC3B,OAAO,EAAE,MAAM,GACd,aAAa,CA+Df"}
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "1.10.4";
1
+ export declare const VERSION = "1.10.5";
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.10.4",
3
+ "version": "1.10.5",
4
4
  "description": "Munchi Payments SDK - Payment processing utilities",
5
5
  "license": "UNLICENSED",
6
6
  "publishConfig": {
@@ -32,7 +32,7 @@
32
32
  "@types/jest": "^30.0.0",
33
33
  "tsup": "^8.0.0",
34
34
  "typescript": "^5.0.0",
35
- "@munchi_oy/core": "1.9.46"
35
+ "@munchi_oy/core": "1.9.56"
36
36
  },
37
37
  "scripts": {
38
38
  "test": "jest",
@@ -33,6 +33,7 @@ export function mapSessionResult(
33
33
  case PaymentSessionStatus.Processing:
34
34
  case PaymentSessionStatus.Voiding:
35
35
  case PaymentSessionStatus.Refunding:
36
+ case PaymentSessionStatus.Dispatched:
36
37
  return pendingResult(orderId);
37
38
 
38
39
  case PaymentSessionStatus.Success:
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.10.4";
3
+ export const VERSION = "1.10.5";